file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
distributed_dqn_v2.py
# Chih-Hsiang Wamg # 2019/6/2 import gym import torch import time import os import ray import numpy as np import csv from tqdm import tqdm from random import uniform, randint import io import base64 from IPython.display import HTML from dqn_model import DQNModel from dqn_model import _DQNModel from memory import ReplayBuffer from memory_remote import ReplayBuffer_remote import matplotlib.pyplot as plt from custom_cartpole import CartPoleEnv FloatTensor = torch.FloatTensor # =================== Helper Function =================== def plot_result(total_rewards ,learning_num, legend): print("\nLearning Performance:\n") episodes = [] for i in range(len(total_rewards)): episodes.append(i * learning_num + 1) plt.figure(num = 1) fig, ax = plt.subplots() plt.plot(episodes, total_rewards) plt.title('performance') plt.legend(legend) plt.xlabel("Episodes") plt.ylabel("total rewards") plt.show() # =================== Hyperparams =================== hyperparams_CartPole = { 'epsilon_decay_steps' : 100000, 'final_epsilon' : 0.1, 'batch_size' : 32, 'update_steps' : 10, 'memory_size' : 2000, 'beta' : 0.99, 'model_replace_freq' : 2000, 'learning_rate' : 0.0003, 'use_target_model': True } # =================== Initialize Environment =================== # Set the Env name and action space for CartPole ENV_NAME = 'CartPole_distributed' # Move left, Move right ACTION_DICT = { "LEFT": 0, "RIGHT":1 } # Register the environment env_CartPole = CartPoleEnv() # =================== Ray Init =================== ray.shutdown() # ray.init(include_webui=False, ignore_reinit_error=True, redis_max_memory=500000000, object_store_memory=5000000000) ray.init() # =================== DQN =================== class DQN_agent(object):
# =================== Ray Servers =================== @ray.remote class DQNModel_server(DQN_agent): def __init__(self, env, hyper_params, memory): super().__init__(env, hyper_params) self.memory_server = memory def update_batch(self): batch = ray.get(self.memory_server.sample.remote(self.batch_size)) if not batch: return (states, actions, reward, next_states, is_terminal) = batch states = states next_states = next_states terminal = FloatTensor([0 if t else 1 for t in is_terminal]) reward = FloatTensor(reward) batch_index = torch.arange(self.batch_size, dtype=torch.long) # Current Q Values _, q_values = self.eval_model.predict_batch(states) q_values = q_values[batch_index, actions] # Calculate target if self.use_target_model: actions, q_next = self.target_model.predict_batch(next_states) else: actions, q_next = self.eval_model.predict_batch(next_states) q_target = reward + self.beta * torch.max(q_next, dim=1)[0] * terminal # update model self.eval_model.fit(q_values, q_target) def getReturn(self): return self.eval_model, self.steps def learn(self): self.steps += 1 if self.steps % self.update_steps == 0: self.update_batch() if self.steps % self.model_replace_freq == 0 and self.use_target_model: self.target_model.replace(self.eval_model) # =================== Workers =================== @ray.remote def collecting_worker(model, env, hyper_params, max_episode_steps, memory, tasks_num): for _ in range(tasks_num): state = env.reset() done = False steps = 0 eval_model, total_steps = ray.get(model.getReturn.remote()) while steps < max_episode_steps and not done: steps += 1 a = ray.get(model.explore_or_exploit_policy.remote(state)) s_, reward, done, info = env.step(a) memory.add.remote(state, a, reward, s_, done) state = s_ model.learn.remote() @ray.remote def evaluation_worker(model, env, max_episode_steps, tasks_num): total_reward = 0 for _ in range(tasks_num): state = env.reset() done = False steps = 0 while steps < max_episode_steps and not done: steps += 1 action = ray.get(model.greedy_policy.remote(state)) state, reward, done, _ = env.step(action) total_reward += reward return total_reward / tasks_num # =================== Agent =================== class distributed_DQN_agent(): def __init__(self, env, hyper_params, training_episodes, test_interval, cw_num = 4, ew_num = 4, trials = 30): self.memory_server = ReplayBuffer_remote.remote(hyper_params['memory_size']) self.model_server = DQNModel_server.remote(env, hyper_params, self.memory_server) self.env = env self.max_episode_steps = env._max_episode_steps self.cw_num = cw_num self.ew_num = ew_num self.hyper_params = hyper_params self.training_episodes = training_episodes self.test_interval = test_interval self.trials = trials def learn_and_evaluate(self): results = [] num = 0 for _ in range(self.training_episodes // self.test_interval): num += 1 collector_ids, evaluators_ids = [], [] # learn for _ in range(self.cw_num): collector_ids.append(collecting_worker.remote(self.model_server, self.env, self.hyper_params, self.max_episode_steps, self.memory_server, test_interval//self.cw_num)) # evaluate for _ in range(self.ew_num): evaluators_ids.append(evaluation_worker.remote(self.model_server, self.env, self.max_episode_steps, self.trials//self.ew_num)) total_reward = sum(ray.get(evaluators_ids)) avg_reward = total_reward / self.ew_num print(num, " avg_reward: ", avg_reward) results.append(avg_reward) return results # =================== Main =================== env_CartPole.reset() cw_num = 8 # collecter workers ew_num = 4 # evaluater workers training_episodes, test_interval, trials = 7000, 50, 30 agent = distributed_DQN_agent(env_CartPole, hyperparams_CartPole, training_episodes, test_interval, cw_num, ew_num, trials) start_time = time.time() result = agent.learn_and_evaluate() print("running time: ", time.time()-start_time) print(result) with open('hw4_result.csv', 'w') as file: writer = csv.writer(file, delimiter=',') writer.writerow(result) file.close() plot_result(result, test_interval, ["batch_update with target_model"])
def __init__(self, env, hyper_params, action_space = len(ACTION_DICT)): self.env = env self.max_episode_steps = env._max_episode_steps """ beta: The discounted factor of Q-value function (epsilon): The explore or exploit policy epsilon. initial_epsilon: When the 'steps' is 0, the epsilon is initial_epsilon, 1 final_epsilon: After the number of 'steps' reach 'epsilon_decay_steps', The epsilon set to the 'final_epsilon' determinately. epsilon_decay_steps: The epsilon will decrease linearly along with the steps from 0 to 'epsilon_decay_steps'. """ self.beta = hyper_params['beta'] self.initial_epsilon = 1 self.final_epsilon = hyper_params['final_epsilon'] self.epsilon_decay_steps = hyper_params['epsilon_decay_steps'] """ episode: Record training episode steps: Add 1 when predicting an action learning: The trigger of agent learning. It is on while training agent. It is off while testing agent. action_space: The action space of the current environment, e.g 2. """ self.episode = 0 self.steps = 0 self.best_reward = 0 self.learning = True self.action_space = action_space """ input_len: The input length of the neural network. It equals to the length of the state vector. output_len: The output length of the neural network. It is equal to the action space. eval_model: The model for predicting action for the agent. target_model: The model for calculating Q-value of next_state to update 'eval_model'. use_target_model: Trigger for turn 'target_model' on/off """ state = env.reset() input_len = len(state) output_len = action_space self.eval_model = DQNModel(input_len, output_len, learning_rate = hyper_params['learning_rate']) self.use_target_model = hyper_params['use_target_model'] if self.use_target_model: self.target_model = DQNModel(input_len, output_len) # memory: Store and sample experience replay. # self.memory = ReplayBuffer(hyper_params['memory_size']) """ batch_size: Mini batch size for training model. update_steps: The frequence of traning model model_replace_freq: The frequence of replacing 'target_model' by 'eval_model' """ self.batch_size = hyper_params['batch_size'] self.update_steps = hyper_params['update_steps'] self.model_replace_freq = hyper_params['model_replace_freq'] def linear_decrease(self, initial_value, final_value, curr_steps, final_decay_steps): decay_rate = curr_steps / final_decay_steps if decay_rate > 1: decay_rate = 1 return initial_value - (initial_value - final_value) * decay_rate def explore_or_exploit_policy(self, state): p = uniform(0, 1) # Get decreased epsilon epsilon = self.linear_decrease(self.initial_epsilon, self.final_epsilon, self.steps, self.epsilon_decay_steps) if p < epsilon: #return action return randint(0, self.action_space - 1) else: #return action return self.greedy_policy(state) def greedy_policy(self, state): return self.eval_model.predict(state)
identifier_body
distributed_dqn_v2.py
# Chih-Hsiang Wamg # 2019/6/2 import gym import torch import time import os import ray import numpy as np import csv from tqdm import tqdm from random import uniform, randint import io import base64 from IPython.display import HTML from dqn_model import DQNModel from dqn_model import _DQNModel from memory import ReplayBuffer from memory_remote import ReplayBuffer_remote import matplotlib.pyplot as plt from custom_cartpole import CartPoleEnv FloatTensor = torch.FloatTensor # =================== Helper Function =================== def plot_result(total_rewards ,learning_num, legend): print("\nLearning Performance:\n") episodes = [] for i in range(len(total_rewards)): episodes.append(i * learning_num + 1) plt.figure(num = 1) fig, ax = plt.subplots() plt.plot(episodes, total_rewards) plt.title('performance') plt.legend(legend) plt.xlabel("Episodes") plt.ylabel("total rewards") plt.show() # =================== Hyperparams =================== hyperparams_CartPole = { 'epsilon_decay_steps' : 100000, 'final_epsilon' : 0.1, 'batch_size' : 32, 'update_steps' : 10, 'memory_size' : 2000, 'beta' : 0.99, 'model_replace_freq' : 2000, 'learning_rate' : 0.0003, 'use_target_model': True } # =================== Initialize Environment =================== # Set the Env name and action space for CartPole ENV_NAME = 'CartPole_distributed' # Move left, Move right ACTION_DICT = { "LEFT": 0, "RIGHT":1 } # Register the environment env_CartPole = CartPoleEnv() # =================== Ray Init =================== ray.shutdown() # ray.init(include_webui=False, ignore_reinit_error=True, redis_max_memory=500000000, object_store_memory=5000000000) ray.init() # =================== DQN =================== class DQN_agent(object): def __init__(self, env, hyper_params, action_space = len(ACTION_DICT)): self.env = env self.max_episode_steps = env._max_episode_steps """ beta: The discounted factor of Q-value function (epsilon): The explore or exploit policy epsilon. initial_epsilon: When the 'steps' is 0, the epsilon is initial_epsilon, 1 final_epsilon: After the number of 'steps' reach 'epsilon_decay_steps', The epsilon set to the 'final_epsilon' determinately. epsilon_decay_steps: The epsilon will decrease linearly along with the steps from 0 to 'epsilon_decay_steps'. """ self.beta = hyper_params['beta'] self.initial_epsilon = 1 self.final_epsilon = hyper_params['final_epsilon'] self.epsilon_decay_steps = hyper_params['epsilon_decay_steps'] """ episode: Record training episode steps: Add 1 when predicting an action learning: The trigger of agent learning. It is on while training agent. It is off while testing agent. action_space: The action space of the current environment, e.g 2. """ self.episode = 0 self.steps = 0 self.best_reward = 0 self.learning = True self.action_space = action_space """ input_len: The input length of the neural network. It equals to the length of the state vector. output_len: The output length of the neural network. It is equal to the action space. eval_model: The model for predicting action for the agent. target_model: The model for calculating Q-value of next_state to update 'eval_model'. use_target_model: Trigger for turn 'target_model' on/off """ state = env.reset() input_len = len(state) output_len = action_space self.eval_model = DQNModel(input_len, output_len, learning_rate = hyper_params['learning_rate']) self.use_target_model = hyper_params['use_target_model'] if self.use_target_model: self.target_model = DQNModel(input_len, output_len) # memory: Store and sample experience replay. # self.memory = ReplayBuffer(hyper_params['memory_size']) """ batch_size: Mini batch size for training model. update_steps: The frequence of traning model model_replace_freq: The frequence of replacing 'target_model' by 'eval_model' """ self.batch_size = hyper_params['batch_size'] self.update_steps = hyper_params['update_steps'] self.model_replace_freq = hyper_params['model_replace_freq'] def linear_decrease(self, initial_value, final_value, curr_steps, final_decay_steps): decay_rate = curr_steps / final_decay_steps if decay_rate > 1: decay_rate = 1 return initial_value - (initial_value - final_value) * decay_rate def explore_or_exploit_policy(self, state): p = uniform(0, 1) # Get decreased epsilon epsilon = self.linear_decrease(self.initial_epsilon, self.final_epsilon, self.steps, self.epsilon_decay_steps) if p < epsilon: #return action return randint(0, self.action_space - 1) else: #return action return self.greedy_policy(state) def greedy_policy(self, state): return self.eval_model.predict(state) # =================== Ray Servers =================== @ray.remote class DQNModel_server(DQN_agent): def __init__(self, env, hyper_params, memory): super().__init__(env, hyper_params) self.memory_server = memory def update_batch(self): batch = ray.get(self.memory_server.sample.remote(self.batch_size)) if not batch: return (states, actions, reward, next_states, is_terminal) = batch states = states next_states = next_states terminal = FloatTensor([0 if t else 1 for t in is_terminal]) reward = FloatTensor(reward) batch_index = torch.arange(self.batch_size, dtype=torch.long) # Current Q Values _, q_values = self.eval_model.predict_batch(states) q_values = q_values[batch_index, actions] # Calculate target if self.use_target_model: actions, q_next = self.target_model.predict_batch(next_states) else: actions, q_next = self.eval_model.predict_batch(next_states) q_target = reward + self.beta * torch.max(q_next, dim=1)[0] * terminal # update model self.eval_model.fit(q_values, q_target) def
(self): return self.eval_model, self.steps def learn(self): self.steps += 1 if self.steps % self.update_steps == 0: self.update_batch() if self.steps % self.model_replace_freq == 0 and self.use_target_model: self.target_model.replace(self.eval_model) # =================== Workers =================== @ray.remote def collecting_worker(model, env, hyper_params, max_episode_steps, memory, tasks_num): for _ in range(tasks_num): state = env.reset() done = False steps = 0 eval_model, total_steps = ray.get(model.getReturn.remote()) while steps < max_episode_steps and not done: steps += 1 a = ray.get(model.explore_or_exploit_policy.remote(state)) s_, reward, done, info = env.step(a) memory.add.remote(state, a, reward, s_, done) state = s_ model.learn.remote() @ray.remote def evaluation_worker(model, env, max_episode_steps, tasks_num): total_reward = 0 for _ in range(tasks_num): state = env.reset() done = False steps = 0 while steps < max_episode_steps and not done: steps += 1 action = ray.get(model.greedy_policy.remote(state)) state, reward, done, _ = env.step(action) total_reward += reward return total_reward / tasks_num # =================== Agent =================== class distributed_DQN_agent(): def __init__(self, env, hyper_params, training_episodes, test_interval, cw_num = 4, ew_num = 4, trials = 30): self.memory_server = ReplayBuffer_remote.remote(hyper_params['memory_size']) self.model_server = DQNModel_server.remote(env, hyper_params, self.memory_server) self.env = env self.max_episode_steps = env._max_episode_steps self.cw_num = cw_num self.ew_num = ew_num self.hyper_params = hyper_params self.training_episodes = training_episodes self.test_interval = test_interval self.trials = trials def learn_and_evaluate(self): results = [] num = 0 for _ in range(self.training_episodes // self.test_interval): num += 1 collector_ids, evaluators_ids = [], [] # learn for _ in range(self.cw_num): collector_ids.append(collecting_worker.remote(self.model_server, self.env, self.hyper_params, self.max_episode_steps, self.memory_server, test_interval//self.cw_num)) # evaluate for _ in range(self.ew_num): evaluators_ids.append(evaluation_worker.remote(self.model_server, self.env, self.max_episode_steps, self.trials//self.ew_num)) total_reward = sum(ray.get(evaluators_ids)) avg_reward = total_reward / self.ew_num print(num, " avg_reward: ", avg_reward) results.append(avg_reward) return results # =================== Main =================== env_CartPole.reset() cw_num = 8 # collecter workers ew_num = 4 # evaluater workers training_episodes, test_interval, trials = 7000, 50, 30 agent = distributed_DQN_agent(env_CartPole, hyperparams_CartPole, training_episodes, test_interval, cw_num, ew_num, trials) start_time = time.time() result = agent.learn_and_evaluate() print("running time: ", time.time()-start_time) print(result) with open('hw4_result.csv', 'w') as file: writer = csv.writer(file, delimiter=',') writer.writerow(result) file.close() plot_result(result, test_interval, ["batch_update with target_model"])
getReturn
identifier_name
distributed_dqn_v2.py
# Chih-Hsiang Wamg # 2019/6/2 import gym import torch import time import os import ray import numpy as np import csv from tqdm import tqdm from random import uniform, randint import io import base64 from IPython.display import HTML from dqn_model import DQNModel from dqn_model import _DQNModel from memory import ReplayBuffer from memory_remote import ReplayBuffer_remote import matplotlib.pyplot as plt from custom_cartpole import CartPoleEnv FloatTensor = torch.FloatTensor # =================== Helper Function =================== def plot_result(total_rewards ,learning_num, legend): print("\nLearning Performance:\n") episodes = [] for i in range(len(total_rewards)): episodes.append(i * learning_num + 1) plt.figure(num = 1) fig, ax = plt.subplots() plt.plot(episodes, total_rewards) plt.title('performance') plt.legend(legend) plt.xlabel("Episodes") plt.ylabel("total rewards") plt.show() # =================== Hyperparams =================== hyperparams_CartPole = { 'epsilon_decay_steps' : 100000, 'final_epsilon' : 0.1, 'batch_size' : 32, 'update_steps' : 10, 'memory_size' : 2000, 'beta' : 0.99, 'model_replace_freq' : 2000, 'learning_rate' : 0.0003, 'use_target_model': True } # =================== Initialize Environment =================== # Set the Env name and action space for CartPole ENV_NAME = 'CartPole_distributed' # Move left, Move right ACTION_DICT = { "LEFT": 0, "RIGHT":1 } # Register the environment env_CartPole = CartPoleEnv() # =================== Ray Init =================== ray.shutdown() # ray.init(include_webui=False, ignore_reinit_error=True, redis_max_memory=500000000, object_store_memory=5000000000) ray.init() # =================== DQN =================== class DQN_agent(object): def __init__(self, env, hyper_params, action_space = len(ACTION_DICT)): self.env = env self.max_episode_steps = env._max_episode_steps """ beta: The discounted factor of Q-value function (epsilon): The explore or exploit policy epsilon. initial_epsilon: When the 'steps' is 0, the epsilon is initial_epsilon, 1 final_epsilon: After the number of 'steps' reach 'epsilon_decay_steps', The epsilon set to the 'final_epsilon' determinately. epsilon_decay_steps: The epsilon will decrease linearly along with the steps from 0 to 'epsilon_decay_steps'. """ self.beta = hyper_params['beta'] self.initial_epsilon = 1 self.final_epsilon = hyper_params['final_epsilon'] self.epsilon_decay_steps = hyper_params['epsilon_decay_steps'] """ episode: Record training episode steps: Add 1 when predicting an action learning: The trigger of agent learning. It is on while training agent. It is off while testing agent. action_space: The action space of the current environment, e.g 2. """ self.episode = 0 self.steps = 0 self.best_reward = 0 self.learning = True self.action_space = action_space """ input_len: The input length of the neural network. It equals to the length of the state vector. output_len: The output length of the neural network. It is equal to the action space. eval_model: The model for predicting action for the agent. target_model: The model for calculating Q-value of next_state to update 'eval_model'. use_target_model: Trigger for turn 'target_model' on/off """ state = env.reset() input_len = len(state) output_len = action_space self.eval_model = DQNModel(input_len, output_len, learning_rate = hyper_params['learning_rate']) self.use_target_model = hyper_params['use_target_model'] if self.use_target_model: self.target_model = DQNModel(input_len, output_len) # memory: Store and sample experience replay. # self.memory = ReplayBuffer(hyper_params['memory_size']) """ batch_size: Mini batch size for training model. update_steps: The frequence of traning model model_replace_freq: The frequence of replacing 'target_model' by 'eval_model' """ self.batch_size = hyper_params['batch_size'] self.update_steps = hyper_params['update_steps'] self.model_replace_freq = hyper_params['model_replace_freq'] def linear_decrease(self, initial_value, final_value, curr_steps, final_decay_steps): decay_rate = curr_steps / final_decay_steps if decay_rate > 1: decay_rate = 1 return initial_value - (initial_value - final_value) * decay_rate def explore_or_exploit_policy(self, state): p = uniform(0, 1) # Get decreased epsilon epsilon = self.linear_decrease(self.initial_epsilon, self.final_epsilon, self.steps, self.epsilon_decay_steps) if p < epsilon: #return action return randint(0, self.action_space - 1)
def greedy_policy(self, state): return self.eval_model.predict(state) # =================== Ray Servers =================== @ray.remote class DQNModel_server(DQN_agent): def __init__(self, env, hyper_params, memory): super().__init__(env, hyper_params) self.memory_server = memory def update_batch(self): batch = ray.get(self.memory_server.sample.remote(self.batch_size)) if not batch: return (states, actions, reward, next_states, is_terminal) = batch states = states next_states = next_states terminal = FloatTensor([0 if t else 1 for t in is_terminal]) reward = FloatTensor(reward) batch_index = torch.arange(self.batch_size, dtype=torch.long) # Current Q Values _, q_values = self.eval_model.predict_batch(states) q_values = q_values[batch_index, actions] # Calculate target if self.use_target_model: actions, q_next = self.target_model.predict_batch(next_states) else: actions, q_next = self.eval_model.predict_batch(next_states) q_target = reward + self.beta * torch.max(q_next, dim=1)[0] * terminal # update model self.eval_model.fit(q_values, q_target) def getReturn(self): return self.eval_model, self.steps def learn(self): self.steps += 1 if self.steps % self.update_steps == 0: self.update_batch() if self.steps % self.model_replace_freq == 0 and self.use_target_model: self.target_model.replace(self.eval_model) # =================== Workers =================== @ray.remote def collecting_worker(model, env, hyper_params, max_episode_steps, memory, tasks_num): for _ in range(tasks_num): state = env.reset() done = False steps = 0 eval_model, total_steps = ray.get(model.getReturn.remote()) while steps < max_episode_steps and not done: steps += 1 a = ray.get(model.explore_or_exploit_policy.remote(state)) s_, reward, done, info = env.step(a) memory.add.remote(state, a, reward, s_, done) state = s_ model.learn.remote() @ray.remote def evaluation_worker(model, env, max_episode_steps, tasks_num): total_reward = 0 for _ in range(tasks_num): state = env.reset() done = False steps = 0 while steps < max_episode_steps and not done: steps += 1 action = ray.get(model.greedy_policy.remote(state)) state, reward, done, _ = env.step(action) total_reward += reward return total_reward / tasks_num # =================== Agent =================== class distributed_DQN_agent(): def __init__(self, env, hyper_params, training_episodes, test_interval, cw_num = 4, ew_num = 4, trials = 30): self.memory_server = ReplayBuffer_remote.remote(hyper_params['memory_size']) self.model_server = DQNModel_server.remote(env, hyper_params, self.memory_server) self.env = env self.max_episode_steps = env._max_episode_steps self.cw_num = cw_num self.ew_num = ew_num self.hyper_params = hyper_params self.training_episodes = training_episodes self.test_interval = test_interval self.trials = trials def learn_and_evaluate(self): results = [] num = 0 for _ in range(self.training_episodes // self.test_interval): num += 1 collector_ids, evaluators_ids = [], [] # learn for _ in range(self.cw_num): collector_ids.append(collecting_worker.remote(self.model_server, self.env, self.hyper_params, self.max_episode_steps, self.memory_server, test_interval//self.cw_num)) # evaluate for _ in range(self.ew_num): evaluators_ids.append(evaluation_worker.remote(self.model_server, self.env, self.max_episode_steps, self.trials//self.ew_num)) total_reward = sum(ray.get(evaluators_ids)) avg_reward = total_reward / self.ew_num print(num, " avg_reward: ", avg_reward) results.append(avg_reward) return results # =================== Main =================== env_CartPole.reset() cw_num = 8 # collecter workers ew_num = 4 # evaluater workers training_episodes, test_interval, trials = 7000, 50, 30 agent = distributed_DQN_agent(env_CartPole, hyperparams_CartPole, training_episodes, test_interval, cw_num, ew_num, trials) start_time = time.time() result = agent.learn_and_evaluate() print("running time: ", time.time()-start_time) print(result) with open('hw4_result.csv', 'w') as file: writer = csv.writer(file, delimiter=',') writer.writerow(result) file.close() plot_result(result, test_interval, ["batch_update with target_model"])
else: #return action return self.greedy_policy(state)
random_line_split
distributed_dqn_v2.py
# Chih-Hsiang Wamg # 2019/6/2 import gym import torch import time import os import ray import numpy as np import csv from tqdm import tqdm from random import uniform, randint import io import base64 from IPython.display import HTML from dqn_model import DQNModel from dqn_model import _DQNModel from memory import ReplayBuffer from memory_remote import ReplayBuffer_remote import matplotlib.pyplot as plt from custom_cartpole import CartPoleEnv FloatTensor = torch.FloatTensor # =================== Helper Function =================== def plot_result(total_rewards ,learning_num, legend): print("\nLearning Performance:\n") episodes = [] for i in range(len(total_rewards)): episodes.append(i * learning_num + 1) plt.figure(num = 1) fig, ax = plt.subplots() plt.plot(episodes, total_rewards) plt.title('performance') plt.legend(legend) plt.xlabel("Episodes") plt.ylabel("total rewards") plt.show() # =================== Hyperparams =================== hyperparams_CartPole = { 'epsilon_decay_steps' : 100000, 'final_epsilon' : 0.1, 'batch_size' : 32, 'update_steps' : 10, 'memory_size' : 2000, 'beta' : 0.99, 'model_replace_freq' : 2000, 'learning_rate' : 0.0003, 'use_target_model': True } # =================== Initialize Environment =================== # Set the Env name and action space for CartPole ENV_NAME = 'CartPole_distributed' # Move left, Move right ACTION_DICT = { "LEFT": 0, "RIGHT":1 } # Register the environment env_CartPole = CartPoleEnv() # =================== Ray Init =================== ray.shutdown() # ray.init(include_webui=False, ignore_reinit_error=True, redis_max_memory=500000000, object_store_memory=5000000000) ray.init() # =================== DQN =================== class DQN_agent(object): def __init__(self, env, hyper_params, action_space = len(ACTION_DICT)): self.env = env self.max_episode_steps = env._max_episode_steps """ beta: The discounted factor of Q-value function (epsilon): The explore or exploit policy epsilon. initial_epsilon: When the 'steps' is 0, the epsilon is initial_epsilon, 1 final_epsilon: After the number of 'steps' reach 'epsilon_decay_steps', The epsilon set to the 'final_epsilon' determinately. epsilon_decay_steps: The epsilon will decrease linearly along with the steps from 0 to 'epsilon_decay_steps'. """ self.beta = hyper_params['beta'] self.initial_epsilon = 1 self.final_epsilon = hyper_params['final_epsilon'] self.epsilon_decay_steps = hyper_params['epsilon_decay_steps'] """ episode: Record training episode steps: Add 1 when predicting an action learning: The trigger of agent learning. It is on while training agent. It is off while testing agent. action_space: The action space of the current environment, e.g 2. """ self.episode = 0 self.steps = 0 self.best_reward = 0 self.learning = True self.action_space = action_space """ input_len: The input length of the neural network. It equals to the length of the state vector. output_len: The output length of the neural network. It is equal to the action space. eval_model: The model for predicting action for the agent. target_model: The model for calculating Q-value of next_state to update 'eval_model'. use_target_model: Trigger for turn 'target_model' on/off """ state = env.reset() input_len = len(state) output_len = action_space self.eval_model = DQNModel(input_len, output_len, learning_rate = hyper_params['learning_rate']) self.use_target_model = hyper_params['use_target_model'] if self.use_target_model: self.target_model = DQNModel(input_len, output_len) # memory: Store and sample experience replay. # self.memory = ReplayBuffer(hyper_params['memory_size']) """ batch_size: Mini batch size for training model. update_steps: The frequence of traning model model_replace_freq: The frequence of replacing 'target_model' by 'eval_model' """ self.batch_size = hyper_params['batch_size'] self.update_steps = hyper_params['update_steps'] self.model_replace_freq = hyper_params['model_replace_freq'] def linear_decrease(self, initial_value, final_value, curr_steps, final_decay_steps): decay_rate = curr_steps / final_decay_steps if decay_rate > 1: decay_rate = 1 return initial_value - (initial_value - final_value) * decay_rate def explore_or_exploit_policy(self, state): p = uniform(0, 1) # Get decreased epsilon epsilon = self.linear_decrease(self.initial_epsilon, self.final_epsilon, self.steps, self.epsilon_decay_steps) if p < epsilon: #return action return randint(0, self.action_space - 1) else: #return action return self.greedy_policy(state) def greedy_policy(self, state): return self.eval_model.predict(state) # =================== Ray Servers =================== @ray.remote class DQNModel_server(DQN_agent): def __init__(self, env, hyper_params, memory): super().__init__(env, hyper_params) self.memory_server = memory def update_batch(self): batch = ray.get(self.memory_server.sample.remote(self.batch_size)) if not batch: return (states, actions, reward, next_states, is_terminal) = batch states = states next_states = next_states terminal = FloatTensor([0 if t else 1 for t in is_terminal]) reward = FloatTensor(reward) batch_index = torch.arange(self.batch_size, dtype=torch.long) # Current Q Values _, q_values = self.eval_model.predict_batch(states) q_values = q_values[batch_index, actions] # Calculate target if self.use_target_model: actions, q_next = self.target_model.predict_batch(next_states) else: actions, q_next = self.eval_model.predict_batch(next_states) q_target = reward + self.beta * torch.max(q_next, dim=1)[0] * terminal # update model self.eval_model.fit(q_values, q_target) def getReturn(self): return self.eval_model, self.steps def learn(self): self.steps += 1 if self.steps % self.update_steps == 0: self.update_batch() if self.steps % self.model_replace_freq == 0 and self.use_target_model: self.target_model.replace(self.eval_model) # =================== Workers =================== @ray.remote def collecting_worker(model, env, hyper_params, max_episode_steps, memory, tasks_num): for _ in range(tasks_num):
@ray.remote def evaluation_worker(model, env, max_episode_steps, tasks_num): total_reward = 0 for _ in range(tasks_num): state = env.reset() done = False steps = 0 while steps < max_episode_steps and not done: steps += 1 action = ray.get(model.greedy_policy.remote(state)) state, reward, done, _ = env.step(action) total_reward += reward return total_reward / tasks_num # =================== Agent =================== class distributed_DQN_agent(): def __init__(self, env, hyper_params, training_episodes, test_interval, cw_num = 4, ew_num = 4, trials = 30): self.memory_server = ReplayBuffer_remote.remote(hyper_params['memory_size']) self.model_server = DQNModel_server.remote(env, hyper_params, self.memory_server) self.env = env self.max_episode_steps = env._max_episode_steps self.cw_num = cw_num self.ew_num = ew_num self.hyper_params = hyper_params self.training_episodes = training_episodes self.test_interval = test_interval self.trials = trials def learn_and_evaluate(self): results = [] num = 0 for _ in range(self.training_episodes // self.test_interval): num += 1 collector_ids, evaluators_ids = [], [] # learn for _ in range(self.cw_num): collector_ids.append(collecting_worker.remote(self.model_server, self.env, self.hyper_params, self.max_episode_steps, self.memory_server, test_interval//self.cw_num)) # evaluate for _ in range(self.ew_num): evaluators_ids.append(evaluation_worker.remote(self.model_server, self.env, self.max_episode_steps, self.trials//self.ew_num)) total_reward = sum(ray.get(evaluators_ids)) avg_reward = total_reward / self.ew_num print(num, " avg_reward: ", avg_reward) results.append(avg_reward) return results # =================== Main =================== env_CartPole.reset() cw_num = 8 # collecter workers ew_num = 4 # evaluater workers training_episodes, test_interval, trials = 7000, 50, 30 agent = distributed_DQN_agent(env_CartPole, hyperparams_CartPole, training_episodes, test_interval, cw_num, ew_num, trials) start_time = time.time() result = agent.learn_and_evaluate() print("running time: ", time.time()-start_time) print(result) with open('hw4_result.csv', 'w') as file: writer = csv.writer(file, delimiter=',') writer.writerow(result) file.close() plot_result(result, test_interval, ["batch_update with target_model"])
state = env.reset() done = False steps = 0 eval_model, total_steps = ray.get(model.getReturn.remote()) while steps < max_episode_steps and not done: steps += 1 a = ray.get(model.explore_or_exploit_policy.remote(state)) s_, reward, done, info = env.step(a) memory.add.remote(state, a, reward, s_, done) state = s_ model.learn.remote()
conditional_block
wasm_vm.rs
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::sync::{mpsc::Sender, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use zellij_utils::{serde, zellij_tile}; use serde::{de::DeserializeOwned, Serialize}; use wasmer::{ imports, ChainableNamedResolver, Function, ImportObject, Instance, Module, Store, Value, WasmerEnv, }; use wasmer_wasi::{Pipe, WasiEnv, WasiState}; use zellij_tile::data::{Event, EventType, PluginIds}; use crate::{ panes::PaneId, pty::PtyInstruction, screen::ScreenInstruction, thread_bus::{Bus, ThreadSenders}, }; use zellij_utils::errors::{ContextType, PluginContext}; #[derive(Clone, Debug)] pub(crate) enum PluginInstruction { Load(Sender<u32>, PathBuf), Update(Option<u32>, Event), // Focused plugin / broadcast, event data Render(Sender<String>, u32, usize, usize), // String buffer, plugin id, rows, cols Unload(u32), Exit, } impl From<&PluginInstruction> for PluginContext { fn from(plugin_instruction: &PluginInstruction) -> Self { match *plugin_instruction { PluginInstruction::Load(..) => PluginContext::Load, PluginInstruction::Update(..) => PluginContext::Update, PluginInstruction::Render(..) => PluginContext::Render, PluginInstruction::Unload(_) => PluginContext::Unload, PluginInstruction::Exit => PluginContext::Exit, } } } #[derive(WasmerEnv, Clone)] pub(crate) struct PluginEnv { pub plugin_id: u32, pub senders: ThreadSenders, pub wasi_env: WasiEnv, pub subscriptions: Arc<Mutex<HashSet<EventType>>>, } // Thread main -------------------------------------------------------------------------------------------------------- pub(crate) fn wasm_thread_main(bus: Bus<PluginInstruction>, store: Store, data_dir: PathBuf) { let mut plugin_id = 0; let mut plugin_map = HashMap::new(); loop { let (event, mut err_ctx) = bus.recv().expect("failed to receive event on channel"); err_ctx.add_call(ContextType::Plugin((&event).into())); match event { PluginInstruction::Load(pid_tx, path) => { let plugin_dir = data_dir.join("plugins/"); let wasm_bytes = fs::read(&path) .or_else(|_| fs::read(&path.with_extension("wasm"))) .or_else(|_| fs::read(&plugin_dir.join(&path).with_extension("wasm"))) .unwrap_or_else(|_| panic!("cannot find plugin {}", &path.display())); // FIXME: Cache this compiled module on disk. I could use `(de)serialize_to_file()` for that let module = Module::new(&store, &wasm_bytes).unwrap(); let output = Pipe::new(); let input = Pipe::new(); let mut wasi_env = WasiState::new("Zellij") .env("CLICOLOR_FORCE", "1") .preopen(|p| { p.directory(".") // FIXME: Change this to a more meaningful dir .alias(".") .read(true) .write(true) .create(true) }) .unwrap() .stdin(Box::new(input)) .stdout(Box::new(output)) .finalize() .unwrap(); let wasi = wasi_env.import_object(&module).unwrap(); let plugin_env = PluginEnv { plugin_id, senders: bus.senders.clone(), wasi_env, subscriptions: Arc::new(Mutex::new(HashSet::new())), }; let zellij = zellij_exports(&store, &plugin_env); let instance = Instance::new(&module, &zellij.chain_back(wasi)).unwrap(); let start = instance.exports.get_function("_start").unwrap(); // This eventually calls the `.load()` method start.call(&[]).unwrap(); plugin_map.insert(plugin_id, (instance, plugin_env)); pid_tx.send(plugin_id).unwrap(); plugin_id += 1; } PluginInstruction::Update(pid, event) =>
PluginInstruction::Render(buf_tx, pid, rows, cols) => { let (instance, plugin_env) = plugin_map.get(&pid).unwrap(); let render = instance.exports.get_function("render").unwrap(); render .call(&[Value::I32(rows as i32), Value::I32(cols as i32)]) .unwrap(); buf_tx.send(wasi_read_string(&plugin_env.wasi_env)).unwrap(); } PluginInstruction::Unload(pid) => drop(plugin_map.remove(&pid)), PluginInstruction::Exit => break, } } } // Plugin API --------------------------------------------------------------------------------------------------------- pub(crate) fn zellij_exports(store: &Store, plugin_env: &PluginEnv) -> ImportObject { macro_rules! zellij_export { ($($host_function:ident),+ $(,)?) => { imports! { "zellij" => { $(stringify!($host_function) => Function::new_native_with_env(store, plugin_env.clone(), $host_function),)+ } } } } zellij_export! { host_subscribe, host_unsubscribe, host_set_invisible_borders, host_set_max_height, host_set_selectable, host_get_plugin_ids, host_open_file, host_set_timeout, } } fn host_subscribe(plugin_env: &PluginEnv) { let mut subscriptions = plugin_env.subscriptions.lock().unwrap(); let new: HashSet<EventType> = wasi_read_object(&plugin_env.wasi_env); subscriptions.extend(new); } fn host_unsubscribe(plugin_env: &PluginEnv) { let mut subscriptions = plugin_env.subscriptions.lock().unwrap(); let old: HashSet<EventType> = wasi_read_object(&plugin_env.wasi_env); subscriptions.retain(|k| !old.contains(k)); } fn host_set_selectable(plugin_env: &PluginEnv, selectable: i32) { let selectable = selectable != 0; plugin_env .senders .send_to_screen(ScreenInstruction::SetSelectable( PaneId::Plugin(plugin_env.plugin_id), selectable, )) .unwrap() } fn host_set_max_height(plugin_env: &PluginEnv, max_height: i32) { let max_height = max_height as usize; plugin_env .senders .send_to_screen(ScreenInstruction::SetMaxHeight( PaneId::Plugin(plugin_env.plugin_id), max_height, )) .unwrap() } fn host_set_invisible_borders(plugin_env: &PluginEnv, invisible_borders: i32) { let invisible_borders = invisible_borders != 0; plugin_env .senders .send_to_screen(ScreenInstruction::SetInvisibleBorders( PaneId::Plugin(plugin_env.plugin_id), invisible_borders, )) .unwrap() } fn host_get_plugin_ids(plugin_env: &PluginEnv) { let ids = PluginIds { plugin_id: plugin_env.plugin_id, zellij_pid: process::id(), }; wasi_write_object(&plugin_env.wasi_env, &ids); } fn host_open_file(plugin_env: &PluginEnv) { let path: PathBuf = wasi_read_object(&plugin_env.wasi_env); plugin_env .senders .send_to_pty(PtyInstruction::SpawnTerminal(Some(path))) .unwrap(); } fn host_set_timeout(plugin_env: &PluginEnv, secs: f64) { // There is a fancy, high-performance way to do this with zero additional threads: // If the plugin thread keeps a BinaryHeap of timer structs, it can manage multiple and easily `.peek()` at the // next time to trigger in O(1) time. Once the wake-up time is known, the `wasm` thread can use `recv_timeout()` // to wait for an event with the timeout set to be the time of the next wake up. If events come in in the meantime, // they are handled, but if the timeout triggers, we replace the event from `recv()` with an // `Update(pid, TimerEvent)` and pop the timer from the Heap (or reschedule it). No additional threads for as many // timers as we'd like. // // But that's a lot of code, and this is a few lines: let send_plugin_instructions = plugin_env.senders.to_plugin.clone(); let update_target = Some(plugin_env.plugin_id); thread::spawn(move || { let start_time = Instant::now(); thread::sleep(Duration::from_secs_f64(secs)); // FIXME: The way that elapsed time is being calculated here is not exact; it doesn't take into account the // time it takes an event to actually reach the plugin after it's sent to the `wasm` thread. let elapsed_time = Instant::now().duration_since(start_time).as_secs_f64(); send_plugin_instructions .unwrap() .send(PluginInstruction::Update( update_target, Event::Timer(elapsed_time), )) .unwrap(); }); } // Helper Functions --------------------------------------------------------------------------------------------------- // FIXME: Unwrap city pub fn wasi_read_string(wasi_env: &WasiEnv) -> String { let mut state = wasi_env.state(); let wasi_file = state.fs.stdout_mut().unwrap().as_mut().unwrap(); let mut buf = String::new(); wasi_file.read_to_string(&mut buf).unwrap(); buf } pub fn wasi_write_string(wasi_env: &WasiEnv, buf: &str) { let mut state = wasi_env.state(); let wasi_file = state.fs.stdin_mut().unwrap().as_mut().unwrap(); writeln!(wasi_file, "{}\r", buf).unwrap(); } pub fn wasi_write_object(wasi_env: &WasiEnv, object: &impl Serialize) { wasi_write_string(wasi_env, &serde_json::to_string(&object).unwrap()); } pub fn wasi_read_object<T: DeserializeOwned>(wasi_env: &WasiEnv) -> T { let json = wasi_read_string(wasi_env); serde_json::from_str(&json).unwrap() }
{ for (&i, (instance, plugin_env)) in &plugin_map { let subs = plugin_env.subscriptions.lock().unwrap(); // FIXME: This is very janky... Maybe I should write my own macro for Event -> EventType? let event_type = EventType::from_str(&event.to_string()).unwrap(); if (pid.is_none() || pid == Some(i)) && subs.contains(&event_type) { let update = instance.exports.get_function("update").unwrap(); wasi_write_object(&plugin_env.wasi_env, &event); update.call(&[]).unwrap(); } } drop(bus.senders.send_to_screen(ScreenInstruction::Render)); }
conditional_block
wasm_vm.rs
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::sync::{mpsc::Sender, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use zellij_utils::{serde, zellij_tile}; use serde::{de::DeserializeOwned, Serialize}; use wasmer::{ imports, ChainableNamedResolver, Function, ImportObject, Instance, Module, Store, Value, WasmerEnv, }; use wasmer_wasi::{Pipe, WasiEnv, WasiState}; use zellij_tile::data::{Event, EventType, PluginIds}; use crate::{ panes::PaneId, pty::PtyInstruction, screen::ScreenInstruction, thread_bus::{Bus, ThreadSenders}, }; use zellij_utils::errors::{ContextType, PluginContext}; #[derive(Clone, Debug)] pub(crate) enum
{ Load(Sender<u32>, PathBuf), Update(Option<u32>, Event), // Focused plugin / broadcast, event data Render(Sender<String>, u32, usize, usize), // String buffer, plugin id, rows, cols Unload(u32), Exit, } impl From<&PluginInstruction> for PluginContext { fn from(plugin_instruction: &PluginInstruction) -> Self { match *plugin_instruction { PluginInstruction::Load(..) => PluginContext::Load, PluginInstruction::Update(..) => PluginContext::Update, PluginInstruction::Render(..) => PluginContext::Render, PluginInstruction::Unload(_) => PluginContext::Unload, PluginInstruction::Exit => PluginContext::Exit, } } } #[derive(WasmerEnv, Clone)] pub(crate) struct PluginEnv { pub plugin_id: u32, pub senders: ThreadSenders, pub wasi_env: WasiEnv, pub subscriptions: Arc<Mutex<HashSet<EventType>>>, } // Thread main -------------------------------------------------------------------------------------------------------- pub(crate) fn wasm_thread_main(bus: Bus<PluginInstruction>, store: Store, data_dir: PathBuf) { let mut plugin_id = 0; let mut plugin_map = HashMap::new(); loop { let (event, mut err_ctx) = bus.recv().expect("failed to receive event on channel"); err_ctx.add_call(ContextType::Plugin((&event).into())); match event { PluginInstruction::Load(pid_tx, path) => { let plugin_dir = data_dir.join("plugins/"); let wasm_bytes = fs::read(&path) .or_else(|_| fs::read(&path.with_extension("wasm"))) .or_else(|_| fs::read(&plugin_dir.join(&path).with_extension("wasm"))) .unwrap_or_else(|_| panic!("cannot find plugin {}", &path.display())); // FIXME: Cache this compiled module on disk. I could use `(de)serialize_to_file()` for that let module = Module::new(&store, &wasm_bytes).unwrap(); let output = Pipe::new(); let input = Pipe::new(); let mut wasi_env = WasiState::new("Zellij") .env("CLICOLOR_FORCE", "1") .preopen(|p| { p.directory(".") // FIXME: Change this to a more meaningful dir .alias(".") .read(true) .write(true) .create(true) }) .unwrap() .stdin(Box::new(input)) .stdout(Box::new(output)) .finalize() .unwrap(); let wasi = wasi_env.import_object(&module).unwrap(); let plugin_env = PluginEnv { plugin_id, senders: bus.senders.clone(), wasi_env, subscriptions: Arc::new(Mutex::new(HashSet::new())), }; let zellij = zellij_exports(&store, &plugin_env); let instance = Instance::new(&module, &zellij.chain_back(wasi)).unwrap(); let start = instance.exports.get_function("_start").unwrap(); // This eventually calls the `.load()` method start.call(&[]).unwrap(); plugin_map.insert(plugin_id, (instance, plugin_env)); pid_tx.send(plugin_id).unwrap(); plugin_id += 1; } PluginInstruction::Update(pid, event) => { for (&i, (instance, plugin_env)) in &plugin_map { let subs = plugin_env.subscriptions.lock().unwrap(); // FIXME: This is very janky... Maybe I should write my own macro for Event -> EventType? let event_type = EventType::from_str(&event.to_string()).unwrap(); if (pid.is_none() || pid == Some(i)) && subs.contains(&event_type) { let update = instance.exports.get_function("update").unwrap(); wasi_write_object(&plugin_env.wasi_env, &event); update.call(&[]).unwrap(); } } drop(bus.senders.send_to_screen(ScreenInstruction::Render)); } PluginInstruction::Render(buf_tx, pid, rows, cols) => { let (instance, plugin_env) = plugin_map.get(&pid).unwrap(); let render = instance.exports.get_function("render").unwrap(); render .call(&[Value::I32(rows as i32), Value::I32(cols as i32)]) .unwrap(); buf_tx.send(wasi_read_string(&plugin_env.wasi_env)).unwrap(); } PluginInstruction::Unload(pid) => drop(plugin_map.remove(&pid)), PluginInstruction::Exit => break, } } } // Plugin API --------------------------------------------------------------------------------------------------------- pub(crate) fn zellij_exports(store: &Store, plugin_env: &PluginEnv) -> ImportObject { macro_rules! zellij_export { ($($host_function:ident),+ $(,)?) => { imports! { "zellij" => { $(stringify!($host_function) => Function::new_native_with_env(store, plugin_env.clone(), $host_function),)+ } } } } zellij_export! { host_subscribe, host_unsubscribe, host_set_invisible_borders, host_set_max_height, host_set_selectable, host_get_plugin_ids, host_open_file, host_set_timeout, } } fn host_subscribe(plugin_env: &PluginEnv) { let mut subscriptions = plugin_env.subscriptions.lock().unwrap(); let new: HashSet<EventType> = wasi_read_object(&plugin_env.wasi_env); subscriptions.extend(new); } fn host_unsubscribe(plugin_env: &PluginEnv) { let mut subscriptions = plugin_env.subscriptions.lock().unwrap(); let old: HashSet<EventType> = wasi_read_object(&plugin_env.wasi_env); subscriptions.retain(|k| !old.contains(k)); } fn host_set_selectable(plugin_env: &PluginEnv, selectable: i32) { let selectable = selectable != 0; plugin_env .senders .send_to_screen(ScreenInstruction::SetSelectable( PaneId::Plugin(plugin_env.plugin_id), selectable, )) .unwrap() } fn host_set_max_height(plugin_env: &PluginEnv, max_height: i32) { let max_height = max_height as usize; plugin_env .senders .send_to_screen(ScreenInstruction::SetMaxHeight( PaneId::Plugin(plugin_env.plugin_id), max_height, )) .unwrap() } fn host_set_invisible_borders(plugin_env: &PluginEnv, invisible_borders: i32) { let invisible_borders = invisible_borders != 0; plugin_env .senders .send_to_screen(ScreenInstruction::SetInvisibleBorders( PaneId::Plugin(plugin_env.plugin_id), invisible_borders, )) .unwrap() } fn host_get_plugin_ids(plugin_env: &PluginEnv) { let ids = PluginIds { plugin_id: plugin_env.plugin_id, zellij_pid: process::id(), }; wasi_write_object(&plugin_env.wasi_env, &ids); } fn host_open_file(plugin_env: &PluginEnv) { let path: PathBuf = wasi_read_object(&plugin_env.wasi_env); plugin_env .senders .send_to_pty(PtyInstruction::SpawnTerminal(Some(path))) .unwrap(); } fn host_set_timeout(plugin_env: &PluginEnv, secs: f64) { // There is a fancy, high-performance way to do this with zero additional threads: // If the plugin thread keeps a BinaryHeap of timer structs, it can manage multiple and easily `.peek()` at the // next time to trigger in O(1) time. Once the wake-up time is known, the `wasm` thread can use `recv_timeout()` // to wait for an event with the timeout set to be the time of the next wake up. If events come in in the meantime, // they are handled, but if the timeout triggers, we replace the event from `recv()` with an // `Update(pid, TimerEvent)` and pop the timer from the Heap (or reschedule it). No additional threads for as many // timers as we'd like. // // But that's a lot of code, and this is a few lines: let send_plugin_instructions = plugin_env.senders.to_plugin.clone(); let update_target = Some(plugin_env.plugin_id); thread::spawn(move || { let start_time = Instant::now(); thread::sleep(Duration::from_secs_f64(secs)); // FIXME: The way that elapsed time is being calculated here is not exact; it doesn't take into account the // time it takes an event to actually reach the plugin after it's sent to the `wasm` thread. let elapsed_time = Instant::now().duration_since(start_time).as_secs_f64(); send_plugin_instructions .unwrap() .send(PluginInstruction::Update( update_target, Event::Timer(elapsed_time), )) .unwrap(); }); } // Helper Functions --------------------------------------------------------------------------------------------------- // FIXME: Unwrap city pub fn wasi_read_string(wasi_env: &WasiEnv) -> String { let mut state = wasi_env.state(); let wasi_file = state.fs.stdout_mut().unwrap().as_mut().unwrap(); let mut buf = String::new(); wasi_file.read_to_string(&mut buf).unwrap(); buf } pub fn wasi_write_string(wasi_env: &WasiEnv, buf: &str) { let mut state = wasi_env.state(); let wasi_file = state.fs.stdin_mut().unwrap().as_mut().unwrap(); writeln!(wasi_file, "{}\r", buf).unwrap(); } pub fn wasi_write_object(wasi_env: &WasiEnv, object: &impl Serialize) { wasi_write_string(wasi_env, &serde_json::to_string(&object).unwrap()); } pub fn wasi_read_object<T: DeserializeOwned>(wasi_env: &WasiEnv) -> T { let json = wasi_read_string(wasi_env); serde_json::from_str(&json).unwrap() }
PluginInstruction
identifier_name
wasm_vm.rs
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::sync::{mpsc::Sender, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use zellij_utils::{serde, zellij_tile}; use serde::{de::DeserializeOwned, Serialize}; use wasmer::{ imports, ChainableNamedResolver, Function, ImportObject, Instance, Module, Store, Value, WasmerEnv, }; use wasmer_wasi::{Pipe, WasiEnv, WasiState}; use zellij_tile::data::{Event, EventType, PluginIds}; use crate::{ panes::PaneId, pty::PtyInstruction, screen::ScreenInstruction, thread_bus::{Bus, ThreadSenders}, }; use zellij_utils::errors::{ContextType, PluginContext}; #[derive(Clone, Debug)] pub(crate) enum PluginInstruction { Load(Sender<u32>, PathBuf), Update(Option<u32>, Event), // Focused plugin / broadcast, event data Render(Sender<String>, u32, usize, usize), // String buffer, plugin id, rows, cols Unload(u32), Exit, } impl From<&PluginInstruction> for PluginContext { fn from(plugin_instruction: &PluginInstruction) -> Self { match *plugin_instruction { PluginInstruction::Load(..) => PluginContext::Load, PluginInstruction::Update(..) => PluginContext::Update, PluginInstruction::Render(..) => PluginContext::Render, PluginInstruction::Unload(_) => PluginContext::Unload, PluginInstruction::Exit => PluginContext::Exit, } } } #[derive(WasmerEnv, Clone)] pub(crate) struct PluginEnv { pub plugin_id: u32, pub senders: ThreadSenders, pub wasi_env: WasiEnv, pub subscriptions: Arc<Mutex<HashSet<EventType>>>, } // Thread main -------------------------------------------------------------------------------------------------------- pub(crate) fn wasm_thread_main(bus: Bus<PluginInstruction>, store: Store, data_dir: PathBuf) { let mut plugin_id = 0; let mut plugin_map = HashMap::new(); loop { let (event, mut err_ctx) = bus.recv().expect("failed to receive event on channel"); err_ctx.add_call(ContextType::Plugin((&event).into())); match event { PluginInstruction::Load(pid_tx, path) => { let plugin_dir = data_dir.join("plugins/"); let wasm_bytes = fs::read(&path) .or_else(|_| fs::read(&path.with_extension("wasm"))) .or_else(|_| fs::read(&plugin_dir.join(&path).with_extension("wasm"))) .unwrap_or_else(|_| panic!("cannot find plugin {}", &path.display())); // FIXME: Cache this compiled module on disk. I could use `(de)serialize_to_file()` for that let module = Module::new(&store, &wasm_bytes).unwrap(); let output = Pipe::new(); let input = Pipe::new(); let mut wasi_env = WasiState::new("Zellij") .env("CLICOLOR_FORCE", "1") .preopen(|p| { p.directory(".") // FIXME: Change this to a more meaningful dir .alias(".") .read(true) .write(true) .create(true) }) .unwrap() .stdin(Box::new(input)) .stdout(Box::new(output)) .finalize() .unwrap(); let wasi = wasi_env.import_object(&module).unwrap(); let plugin_env = PluginEnv { plugin_id, senders: bus.senders.clone(), wasi_env, subscriptions: Arc::new(Mutex::new(HashSet::new())), }; let zellij = zellij_exports(&store, &plugin_env); let instance = Instance::new(&module, &zellij.chain_back(wasi)).unwrap(); let start = instance.exports.get_function("_start").unwrap(); // This eventually calls the `.load()` method start.call(&[]).unwrap(); plugin_map.insert(plugin_id, (instance, plugin_env)); pid_tx.send(plugin_id).unwrap(); plugin_id += 1; } PluginInstruction::Update(pid, event) => { for (&i, (instance, plugin_env)) in &plugin_map { let subs = plugin_env.subscriptions.lock().unwrap(); // FIXME: This is very janky... Maybe I should write my own macro for Event -> EventType? let event_type = EventType::from_str(&event.to_string()).unwrap(); if (pid.is_none() || pid == Some(i)) && subs.contains(&event_type) { let update = instance.exports.get_function("update").unwrap(); wasi_write_object(&plugin_env.wasi_env, &event); update.call(&[]).unwrap(); } } drop(bus.senders.send_to_screen(ScreenInstruction::Render)); } PluginInstruction::Render(buf_tx, pid, rows, cols) => { let (instance, plugin_env) = plugin_map.get(&pid).unwrap(); let render = instance.exports.get_function("render").unwrap(); render .call(&[Value::I32(rows as i32), Value::I32(cols as i32)]) .unwrap(); buf_tx.send(wasi_read_string(&plugin_env.wasi_env)).unwrap(); } PluginInstruction::Unload(pid) => drop(plugin_map.remove(&pid)), PluginInstruction::Exit => break, } } } // Plugin API --------------------------------------------------------------------------------------------------------- pub(crate) fn zellij_exports(store: &Store, plugin_env: &PluginEnv) -> ImportObject { macro_rules! zellij_export { ($($host_function:ident),+ $(,)?) => { imports! { "zellij" => { $(stringify!($host_function) => Function::new_native_with_env(store, plugin_env.clone(), $host_function),)+ } } } } zellij_export! { host_subscribe, host_unsubscribe, host_set_invisible_borders, host_set_max_height, host_set_selectable, host_get_plugin_ids, host_open_file, host_set_timeout, } } fn host_subscribe(plugin_env: &PluginEnv) { let mut subscriptions = plugin_env.subscriptions.lock().unwrap(); let new: HashSet<EventType> = wasi_read_object(&plugin_env.wasi_env); subscriptions.extend(new); } fn host_unsubscribe(plugin_env: &PluginEnv) { let mut subscriptions = plugin_env.subscriptions.lock().unwrap(); let old: HashSet<EventType> = wasi_read_object(&plugin_env.wasi_env); subscriptions.retain(|k| !old.contains(k)); } fn host_set_selectable(plugin_env: &PluginEnv, selectable: i32) { let selectable = selectable != 0; plugin_env .senders .send_to_screen(ScreenInstruction::SetSelectable( PaneId::Plugin(plugin_env.plugin_id), selectable, )) .unwrap() } fn host_set_max_height(plugin_env: &PluginEnv, max_height: i32) { let max_height = max_height as usize; plugin_env .senders .send_to_screen(ScreenInstruction::SetMaxHeight( PaneId::Plugin(plugin_env.plugin_id), max_height, )) .unwrap() } fn host_set_invisible_borders(plugin_env: &PluginEnv, invisible_borders: i32) { let invisible_borders = invisible_borders != 0; plugin_env .senders .send_to_screen(ScreenInstruction::SetInvisibleBorders( PaneId::Plugin(plugin_env.plugin_id), invisible_borders, )) .unwrap() } fn host_get_plugin_ids(plugin_env: &PluginEnv)
fn host_open_file(plugin_env: &PluginEnv) { let path: PathBuf = wasi_read_object(&plugin_env.wasi_env); plugin_env .senders .send_to_pty(PtyInstruction::SpawnTerminal(Some(path))) .unwrap(); } fn host_set_timeout(plugin_env: &PluginEnv, secs: f64) { // There is a fancy, high-performance way to do this with zero additional threads: // If the plugin thread keeps a BinaryHeap of timer structs, it can manage multiple and easily `.peek()` at the // next time to trigger in O(1) time. Once the wake-up time is known, the `wasm` thread can use `recv_timeout()` // to wait for an event with the timeout set to be the time of the next wake up. If events come in in the meantime, // they are handled, but if the timeout triggers, we replace the event from `recv()` with an // `Update(pid, TimerEvent)` and pop the timer from the Heap (or reschedule it). No additional threads for as many // timers as we'd like. // // But that's a lot of code, and this is a few lines: let send_plugin_instructions = plugin_env.senders.to_plugin.clone(); let update_target = Some(plugin_env.plugin_id); thread::spawn(move || { let start_time = Instant::now(); thread::sleep(Duration::from_secs_f64(secs)); // FIXME: The way that elapsed time is being calculated here is not exact; it doesn't take into account the // time it takes an event to actually reach the plugin after it's sent to the `wasm` thread. let elapsed_time = Instant::now().duration_since(start_time).as_secs_f64(); send_plugin_instructions .unwrap() .send(PluginInstruction::Update( update_target, Event::Timer(elapsed_time), )) .unwrap(); }); } // Helper Functions --------------------------------------------------------------------------------------------------- // FIXME: Unwrap city pub fn wasi_read_string(wasi_env: &WasiEnv) -> String { let mut state = wasi_env.state(); let wasi_file = state.fs.stdout_mut().unwrap().as_mut().unwrap(); let mut buf = String::new(); wasi_file.read_to_string(&mut buf).unwrap(); buf } pub fn wasi_write_string(wasi_env: &WasiEnv, buf: &str) { let mut state = wasi_env.state(); let wasi_file = state.fs.stdin_mut().unwrap().as_mut().unwrap(); writeln!(wasi_file, "{}\r", buf).unwrap(); } pub fn wasi_write_object(wasi_env: &WasiEnv, object: &impl Serialize) { wasi_write_string(wasi_env, &serde_json::to_string(&object).unwrap()); } pub fn wasi_read_object<T: DeserializeOwned>(wasi_env: &WasiEnv) -> T { let json = wasi_read_string(wasi_env); serde_json::from_str(&json).unwrap() }
{ let ids = PluginIds { plugin_id: plugin_env.plugin_id, zellij_pid: process::id(), }; wasi_write_object(&plugin_env.wasi_env, &ids); }
identifier_body
wasm_vm.rs
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::sync::{mpsc::Sender, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use zellij_utils::{serde, zellij_tile}; use serde::{de::DeserializeOwned, Serialize}; use wasmer::{ imports, ChainableNamedResolver, Function, ImportObject, Instance, Module, Store, Value, WasmerEnv, }; use wasmer_wasi::{Pipe, WasiEnv, WasiState}; use zellij_tile::data::{Event, EventType, PluginIds}; use crate::{ panes::PaneId, pty::PtyInstruction, screen::ScreenInstruction, thread_bus::{Bus, ThreadSenders}, }; use zellij_utils::errors::{ContextType, PluginContext}; #[derive(Clone, Debug)] pub(crate) enum PluginInstruction { Load(Sender<u32>, PathBuf), Update(Option<u32>, Event), // Focused plugin / broadcast, event data Render(Sender<String>, u32, usize, usize), // String buffer, plugin id, rows, cols Unload(u32), Exit, } impl From<&PluginInstruction> for PluginContext { fn from(plugin_instruction: &PluginInstruction) -> Self { match *plugin_instruction { PluginInstruction::Load(..) => PluginContext::Load, PluginInstruction::Update(..) => PluginContext::Update, PluginInstruction::Render(..) => PluginContext::Render, PluginInstruction::Unload(_) => PluginContext::Unload, PluginInstruction::Exit => PluginContext::Exit, } } } #[derive(WasmerEnv, Clone)] pub(crate) struct PluginEnv { pub plugin_id: u32, pub senders: ThreadSenders, pub wasi_env: WasiEnv, pub subscriptions: Arc<Mutex<HashSet<EventType>>>, } // Thread main -------------------------------------------------------------------------------------------------------- pub(crate) fn wasm_thread_main(bus: Bus<PluginInstruction>, store: Store, data_dir: PathBuf) { let mut plugin_id = 0; let mut plugin_map = HashMap::new(); loop { let (event, mut err_ctx) = bus.recv().expect("failed to receive event on channel"); err_ctx.add_call(ContextType::Plugin((&event).into())); match event { PluginInstruction::Load(pid_tx, path) => { let plugin_dir = data_dir.join("plugins/"); let wasm_bytes = fs::read(&path) .or_else(|_| fs::read(&path.with_extension("wasm"))) .or_else(|_| fs::read(&plugin_dir.join(&path).with_extension("wasm"))) .unwrap_or_else(|_| panic!("cannot find plugin {}", &path.display())); // FIXME: Cache this compiled module on disk. I could use `(de)serialize_to_file()` for that let module = Module::new(&store, &wasm_bytes).unwrap(); let output = Pipe::new(); let input = Pipe::new(); let mut wasi_env = WasiState::new("Zellij") .env("CLICOLOR_FORCE", "1") .preopen(|p| { p.directory(".") // FIXME: Change this to a more meaningful dir .alias(".") .read(true) .write(true) .create(true) }) .unwrap() .stdin(Box::new(input)) .stdout(Box::new(output)) .finalize() .unwrap(); let wasi = wasi_env.import_object(&module).unwrap(); let plugin_env = PluginEnv { plugin_id, senders: bus.senders.clone(), wasi_env, subscriptions: Arc::new(Mutex::new(HashSet::new())), }; let zellij = zellij_exports(&store, &plugin_env); let instance = Instance::new(&module, &zellij.chain_back(wasi)).unwrap(); let start = instance.exports.get_function("_start").unwrap(); // This eventually calls the `.load()` method start.call(&[]).unwrap(); plugin_map.insert(plugin_id, (instance, plugin_env)); pid_tx.send(plugin_id).unwrap(); plugin_id += 1; } PluginInstruction::Update(pid, event) => { for (&i, (instance, plugin_env)) in &plugin_map { let subs = plugin_env.subscriptions.lock().unwrap(); // FIXME: This is very janky... Maybe I should write my own macro for Event -> EventType? let event_type = EventType::from_str(&event.to_string()).unwrap(); if (pid.is_none() || pid == Some(i)) && subs.contains(&event_type) { let update = instance.exports.get_function("update").unwrap(); wasi_write_object(&plugin_env.wasi_env, &event); update.call(&[]).unwrap(); } } drop(bus.senders.send_to_screen(ScreenInstruction::Render)); } PluginInstruction::Render(buf_tx, pid, rows, cols) => { let (instance, plugin_env) = plugin_map.get(&pid).unwrap(); let render = instance.exports.get_function("render").unwrap(); render .call(&[Value::I32(rows as i32), Value::I32(cols as i32)]) .unwrap();
} PluginInstruction::Unload(pid) => drop(plugin_map.remove(&pid)), PluginInstruction::Exit => break, } } } // Plugin API --------------------------------------------------------------------------------------------------------- pub(crate) fn zellij_exports(store: &Store, plugin_env: &PluginEnv) -> ImportObject { macro_rules! zellij_export { ($($host_function:ident),+ $(,)?) => { imports! { "zellij" => { $(stringify!($host_function) => Function::new_native_with_env(store, plugin_env.clone(), $host_function),)+ } } } } zellij_export! { host_subscribe, host_unsubscribe, host_set_invisible_borders, host_set_max_height, host_set_selectable, host_get_plugin_ids, host_open_file, host_set_timeout, } } fn host_subscribe(plugin_env: &PluginEnv) { let mut subscriptions = plugin_env.subscriptions.lock().unwrap(); let new: HashSet<EventType> = wasi_read_object(&plugin_env.wasi_env); subscriptions.extend(new); } fn host_unsubscribe(plugin_env: &PluginEnv) { let mut subscriptions = plugin_env.subscriptions.lock().unwrap(); let old: HashSet<EventType> = wasi_read_object(&plugin_env.wasi_env); subscriptions.retain(|k| !old.contains(k)); } fn host_set_selectable(plugin_env: &PluginEnv, selectable: i32) { let selectable = selectable != 0; plugin_env .senders .send_to_screen(ScreenInstruction::SetSelectable( PaneId::Plugin(plugin_env.plugin_id), selectable, )) .unwrap() } fn host_set_max_height(plugin_env: &PluginEnv, max_height: i32) { let max_height = max_height as usize; plugin_env .senders .send_to_screen(ScreenInstruction::SetMaxHeight( PaneId::Plugin(plugin_env.plugin_id), max_height, )) .unwrap() } fn host_set_invisible_borders(plugin_env: &PluginEnv, invisible_borders: i32) { let invisible_borders = invisible_borders != 0; plugin_env .senders .send_to_screen(ScreenInstruction::SetInvisibleBorders( PaneId::Plugin(plugin_env.plugin_id), invisible_borders, )) .unwrap() } fn host_get_plugin_ids(plugin_env: &PluginEnv) { let ids = PluginIds { plugin_id: plugin_env.plugin_id, zellij_pid: process::id(), }; wasi_write_object(&plugin_env.wasi_env, &ids); } fn host_open_file(plugin_env: &PluginEnv) { let path: PathBuf = wasi_read_object(&plugin_env.wasi_env); plugin_env .senders .send_to_pty(PtyInstruction::SpawnTerminal(Some(path))) .unwrap(); } fn host_set_timeout(plugin_env: &PluginEnv, secs: f64) { // There is a fancy, high-performance way to do this with zero additional threads: // If the plugin thread keeps a BinaryHeap of timer structs, it can manage multiple and easily `.peek()` at the // next time to trigger in O(1) time. Once the wake-up time is known, the `wasm` thread can use `recv_timeout()` // to wait for an event with the timeout set to be the time of the next wake up. If events come in in the meantime, // they are handled, but if the timeout triggers, we replace the event from `recv()` with an // `Update(pid, TimerEvent)` and pop the timer from the Heap (or reschedule it). No additional threads for as many // timers as we'd like. // // But that's a lot of code, and this is a few lines: let send_plugin_instructions = plugin_env.senders.to_plugin.clone(); let update_target = Some(plugin_env.plugin_id); thread::spawn(move || { let start_time = Instant::now(); thread::sleep(Duration::from_secs_f64(secs)); // FIXME: The way that elapsed time is being calculated here is not exact; it doesn't take into account the // time it takes an event to actually reach the plugin after it's sent to the `wasm` thread. let elapsed_time = Instant::now().duration_since(start_time).as_secs_f64(); send_plugin_instructions .unwrap() .send(PluginInstruction::Update( update_target, Event::Timer(elapsed_time), )) .unwrap(); }); } // Helper Functions --------------------------------------------------------------------------------------------------- // FIXME: Unwrap city pub fn wasi_read_string(wasi_env: &WasiEnv) -> String { let mut state = wasi_env.state(); let wasi_file = state.fs.stdout_mut().unwrap().as_mut().unwrap(); let mut buf = String::new(); wasi_file.read_to_string(&mut buf).unwrap(); buf } pub fn wasi_write_string(wasi_env: &WasiEnv, buf: &str) { let mut state = wasi_env.state(); let wasi_file = state.fs.stdin_mut().unwrap().as_mut().unwrap(); writeln!(wasi_file, "{}\r", buf).unwrap(); } pub fn wasi_write_object(wasi_env: &WasiEnv, object: &impl Serialize) { wasi_write_string(wasi_env, &serde_json::to_string(&object).unwrap()); } pub fn wasi_read_object<T: DeserializeOwned>(wasi_env: &WasiEnv) -> T { let json = wasi_read_string(wasi_env); serde_json::from_str(&json).unwrap() }
buf_tx.send(wasi_read_string(&plugin_env.wasi_env)).unwrap();
random_line_split
state.rs
use std::any::type_name; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit::{ serialization::{Bincode2, Serde}, storage::{AppendStore, AppendStoreMut}, }; use crate::msg::{Battle, BattleDump, ContractInfo, Hero, HeroDump, PlayerStats, TokenInfo}; use crate::stats::Stats; pub const CONFIG_KEY: &[u8] = b"config"; pub const PREFIX_VIEW_KEY: &[u8] = b"viewkey"; pub const PREFIX_HISTORY: &[u8] = b"history"; pub const PREFIX_BATTLE_ID: &[u8] = b"battleids"; pub const PREFIX_TOURN_STATS: &[u8] = b"trnstat"; pub const PREFIX_ALL_STATS: &[u8] = b"allstat"; pub const PREFIX_PLAYERS: &[u8] = b"players"; pub const PREFIX_SEEN: &[u8] = b"seen"; pub const ADMIN_KEY: &[u8] = b"admin"; pub const BOTS_KEY: &[u8] = b"bots"; pub const LEADERBOARDS_KEY: &[u8] = b"ldrbds"; pub const IMPORT_FROM_KEY: &[u8] = b"import"; pub const EXPORT_CONFIG_KEY: &[u8] = b"export"; /// arena config #[derive(Serialize, Deserialize)] pub struct Config { /// heroes waiting to fight pub heroes: Vec<StoreWaitingHero>, /// prng seed pub prng_seed: Vec<u8>, /// combined entropy strings supplied with the heroes pub entropy: String, /// current battle count in this arena pub battle_cnt: u64, /// battle count from previous arenas pub previous_battles: u64, /// viewing key used with the card contracts pub viewing_key: String, /// contract info of all the card versions pub card_versions: Vec<StoreContractInfo>, /// true if battles are halted pub fight_halt: bool, /// total number of players pub player_cnt: u32, /// list of new players that need to be added pub new_players: Vec<CanonicalAddr>, } /// export config #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ExportConfig { /// new arena contract info pub new_arena: StoreContractInfo, /// next block to export pub next: u32, } /// stored leaderboard entry #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Rank { /// player's score pub score: i32, /// player's address pub address: CanonicalAddr, } /// tournament data #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Tourney { /// tournament start time pub start: u64, /// tournament leaderboard pub leaderboard: Vec<Rank>, } /// leaderboards #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Leaderboards { /// tournament leaderboard pub tourney: Tourney, /// all time leaderboard pub all_time: Vec<Rank>, } /// tournament stats #[derive(Serialize, Deserialize, Clone, Debug)] pub struct TourneyStats { /// time of last update pub last_seen: u64, /// player's stats for this tournament pub stats: StorePlayerStats, } /// stored player stats #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StorePlayerStats { /// player's score pub score: i32, /// number of battles pub battles: u32, /// number of wins pub wins: u32, /// number of ties pub ties: u32, /// number of times took 3rd place in a 2-way tie pub third_in_two_way_ties: u32, /// number of losses pub losses: u32, } impl Default for StorePlayerStats { fn default() -> Self { Self { score: 0, battles: 0, wins: 0, ties: 0, third_in_two_way_ties: 0, losses: 0, } } } impl StorePlayerStats { /// Returns StdResult<PlayerStats> from converting a StorePlayerStats to a displayable /// PlayerStats /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `address` - a reference to the address corresponding to these stats pub fn into_humanized<A: Api>( self, api: &A, address: &CanonicalAddr, ) -> StdResult<PlayerStats> { let stats = PlayerStats { score: self.score, address: api.human_address(address)?, battles: self.battles, wins: self.wins, ties: self.ties, third_in_two_way_ties: self.third_in_two_way_ties, losses: self.losses, }; Ok(stats) } } /// waiting hero's info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreWaitingHero { /// hero's owner pub owner: CanonicalAddr, /// name of the hero pub name: String, /// hero's token info pub token_info: StoreTokenInfo, /// hero's stats pub stats: Stats, } /// hero info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreHero { /// hero's owner pub owner: CanonicalAddr, /// name of the hero pub name: String, /// hero's token info pub token_info: StoreTokenInfo, /// hero's skills before the battle pub pre_battle_skills: Vec<u8>, /// hero's skills after the battle pub post_battle_skills: Vec<u8>, } impl StoreHero { /// Returns StdResult<Hero> from converting a StoreHero to a displayable Hero /// /// # Arguments /// /// * `versions` - a slice of ContractInfo of token contract versions pub fn
(self, versions: &[ContractInfo]) -> StdResult<Hero> { let hero = Hero { name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle_skills: self.pre_battle_skills, post_battle_skills: self.post_battle_skills, }; Ok(hero) } /// Returns StdResult<HeroDump> from converting a StoreHero to a displayable HeroDump /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_dump<A: Api>(self, api: &A, versions: &[ContractInfo]) -> StdResult<HeroDump> { let hero = HeroDump { owner: api.human_address(&self.owner)?, name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle_skills: self.pre_battle_skills, post_battle_skills: self.post_battle_skills, }; Ok(hero) } } /// a hero's token info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreTokenInfo { /// hero's token id pub token_id: String, /// index of the card contract version pub version: u8, } /// battle info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreBattle { /// battle id number pub battle_number: u64, /// number of seconds since epoch time 01/01/1970 in which the battle took place pub timestamp: u64, /// heroes that fought pub heroes: Vec<StoreHero>, /// skill used to determine the winner pub skill_used: u8, /// index of winning hero pub winner: Option<u8>, /// winning skill value pub winning_skill_value: u8, } impl StoreBattle { /// Returns StdResult<Battle> from converting a StoreBattle to a displayable Battle /// /// # Arguments /// /// * `address` - a reference to the address querying their battle history /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_humanized( mut self, address: &CanonicalAddr, versions: &[ContractInfo], ) -> StdResult<Battle> { if let Some(pos) = self.heroes.iter().position(|h| h.owner == *address) { let winner = self.winner.map(|u| self.heroes[u as usize].name.clone()); let battle = Battle { battle_number: self.battle_number, timestamp: self.timestamp, my_hero: self.heroes.swap_remove(pos).into_humanized(versions)?, skill_used: self.skill_used, winner, winning_skill_value: self.winning_skill_value, i_won: self.winner.map_or_else(|| false, |w| w as usize == pos), }; Ok(battle) } else { Err(StdError::generic_err("Battle History corupted")) } } /// Returns StdResult<BattleDump> from converting a StoreBattle to a displayable BattleDump /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_dump<A: Api>( mut self, api: &A, versions: &[ContractInfo], ) -> StdResult<BattleDump> { let battle = BattleDump { battle_number: self.battle_number, timestamp: self.timestamp, heroes: self .heroes .drain(..) .map(|h| h.into_dump(api, versions)) .collect::<StdResult<Vec<HeroDump>>>()?, skill_used: self.skill_used, winner: self.winner, winning_skill_value: self.winning_skill_value, }; Ok(battle) } } /// code hash and address of a contract #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreContractInfo { /// contract's code hash string pub code_hash: String, /// contract's address pub address: CanonicalAddr, } impl StoreContractInfo { /// Returns StdResult<ContractInfo> from converting a StoreContractInfo to a displayable /// ContractInfo /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses pub fn to_humanized<A: Api>(&self, api: &A) -> StdResult<ContractInfo> { let info = ContractInfo { address: api.human_address(&self.address)?, code_hash: self.code_hash.clone(), }; Ok(info) } } /// Returns StdResult<()> after saving the battle id /// /// # Arguments /// /// * `storage` - a mutable reference to the storage this item should go to /// * `battle_num` - the battle id to store /// * `address` - a reference to the address for which to store this battle id pub fn append_battle_for_addr<S: Storage>( storage: &mut S, battle_num: u64, address: &CanonicalAddr, ) -> StdResult<()> { let mut store = PrefixedStorage::multilevel(&[PREFIX_BATTLE_ID, address.as_slice()], storage); let mut store = AppendStoreMut::attach_or_create(&mut store)?; store.push(&battle_num) } /// Returns StdResult<Vec<Battle>> of the battles to display /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `storage` - a reference to the contract's storage /// * `address` - a reference to the address whose battles to display /// * `page` - page to start displaying /// * `page_size` - number of txs per page pub fn get_history<A: Api, S: ReadonlyStorage>( api: &A, storage: &S, address: &CanonicalAddr, page: u32, page_size: u32, ) -> StdResult<Vec<Battle>> { let id_store = ReadonlyPrefixedStorage::multilevel(&[PREFIX_BATTLE_ID, address.as_slice()], storage); // Try to access the storage of battle ids for the account. // If it doesn't exist yet, return an empty list of battles. let id_store = if let Some(result) = AppendStore::<u64, _>::attach(&id_store) { result? } else { return Ok(vec![]); }; let config: Config = load(storage, CONFIG_KEY)?; let versions = config .card_versions .iter() .map(|v| v.to_humanized(api)) .collect::<StdResult<Vec<ContractInfo>>>()?; // access battle storage let his_store = ReadonlyPrefixedStorage::new(PREFIX_HISTORY, storage); // Take `page_size` battles starting from the latest battle, potentially skipping `page * page_size` // battles from the start. let battles: StdResult<Vec<Battle>> = id_store .iter() .rev() .skip((page * page_size) as usize) .take(page_size as usize) .map(|id| { id.map(|id| { load(&his_store, &id.to_le_bytes()) .and_then(|b: StoreBattle| b.into_humanized(address, &versions)) }) .and_then(|x| x) }) .collect(); battles } pub fn save<T: Serialize, S: Storage>(storage: &mut S, key: &[u8], value: &T) -> StdResult<()> { storage.set(key, &Bincode2::serialize(value)?); Ok(()) } pub fn remove<S: Storage>(storage: &mut S, key: &[u8]) { storage.remove(key); } pub fn load<T: DeserializeOwned, S: ReadonlyStorage>(storage: &S, key: &[u8]) -> StdResult<T> { Bincode2::deserialize( &storage .get(key) .ok_or_else(|| StdError::not_found(type_name::<T>()))?, ) } pub fn may_load<T: DeserializeOwned, S: ReadonlyStorage>( storage: &S, key: &[u8], ) -> StdResult<Option<T>> { match storage.get(key) { Some(value) => Bincode2::deserialize(&value).map(Some), None => Ok(None), } }
into_humanized
identifier_name
state.rs
use std::any::type_name; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit::{ serialization::{Bincode2, Serde}, storage::{AppendStore, AppendStoreMut}, }; use crate::msg::{Battle, BattleDump, ContractInfo, Hero, HeroDump, PlayerStats, TokenInfo}; use crate::stats::Stats; pub const CONFIG_KEY: &[u8] = b"config"; pub const PREFIX_VIEW_KEY: &[u8] = b"viewkey"; pub const PREFIX_HISTORY: &[u8] = b"history"; pub const PREFIX_BATTLE_ID: &[u8] = b"battleids"; pub const PREFIX_TOURN_STATS: &[u8] = b"trnstat"; pub const PREFIX_ALL_STATS: &[u8] = b"allstat"; pub const PREFIX_PLAYERS: &[u8] = b"players"; pub const PREFIX_SEEN: &[u8] = b"seen"; pub const ADMIN_KEY: &[u8] = b"admin"; pub const BOTS_KEY: &[u8] = b"bots"; pub const LEADERBOARDS_KEY: &[u8] = b"ldrbds"; pub const IMPORT_FROM_KEY: &[u8] = b"import"; pub const EXPORT_CONFIG_KEY: &[u8] = b"export"; /// arena config #[derive(Serialize, Deserialize)] pub struct Config { /// heroes waiting to fight pub heroes: Vec<StoreWaitingHero>, /// prng seed pub prng_seed: Vec<u8>, /// combined entropy strings supplied with the heroes pub entropy: String, /// current battle count in this arena pub battle_cnt: u64, /// battle count from previous arenas pub previous_battles: u64, /// viewing key used with the card contracts pub viewing_key: String, /// contract info of all the card versions pub card_versions: Vec<StoreContractInfo>, /// true if battles are halted pub fight_halt: bool, /// total number of players pub player_cnt: u32, /// list of new players that need to be added pub new_players: Vec<CanonicalAddr>, } /// export config #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ExportConfig { /// new arena contract info pub new_arena: StoreContractInfo, /// next block to export pub next: u32, } /// stored leaderboard entry #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Rank { /// player's score pub score: i32, /// player's address pub address: CanonicalAddr, } /// tournament data #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Tourney { /// tournament start time pub start: u64, /// tournament leaderboard pub leaderboard: Vec<Rank>, } /// leaderboards #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Leaderboards { /// tournament leaderboard pub tourney: Tourney, /// all time leaderboard pub all_time: Vec<Rank>, } /// tournament stats #[derive(Serialize, Deserialize, Clone, Debug)] pub struct TourneyStats { /// time of last update pub last_seen: u64, /// player's stats for this tournament pub stats: StorePlayerStats, } /// stored player stats #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StorePlayerStats { /// player's score pub score: i32, /// number of battles pub battles: u32, /// number of wins pub wins: u32, /// number of ties pub ties: u32, /// number of times took 3rd place in a 2-way tie pub third_in_two_way_ties: u32, /// number of losses pub losses: u32, } impl Default for StorePlayerStats { fn default() -> Self { Self { score: 0, battles: 0, wins: 0, ties: 0, third_in_two_way_ties: 0, losses: 0, } } } impl StorePlayerStats { /// Returns StdResult<PlayerStats> from converting a StorePlayerStats to a displayable /// PlayerStats /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `address` - a reference to the address corresponding to these stats pub fn into_humanized<A: Api>( self, api: &A, address: &CanonicalAddr, ) -> StdResult<PlayerStats> { let stats = PlayerStats { score: self.score, address: api.human_address(address)?, battles: self.battles, wins: self.wins, ties: self.ties, third_in_two_way_ties: self.third_in_two_way_ties, losses: self.losses, }; Ok(stats) } } /// waiting hero's info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreWaitingHero { /// hero's owner pub owner: CanonicalAddr, /// name of the hero pub name: String, /// hero's token info pub token_info: StoreTokenInfo, /// hero's stats pub stats: Stats, } /// hero info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreHero { /// hero's owner pub owner: CanonicalAddr, /// name of the hero pub name: String, /// hero's token info pub token_info: StoreTokenInfo, /// hero's skills before the battle pub pre_battle_skills: Vec<u8>, /// hero's skills after the battle pub post_battle_skills: Vec<u8>, } impl StoreHero { /// Returns StdResult<Hero> from converting a StoreHero to a displayable Hero /// /// # Arguments /// /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_humanized(self, versions: &[ContractInfo]) -> StdResult<Hero> { let hero = Hero { name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle_skills: self.pre_battle_skills, post_battle_skills: self.post_battle_skills, }; Ok(hero) } /// Returns StdResult<HeroDump> from converting a StoreHero to a displayable HeroDump /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_dump<A: Api>(self, api: &A, versions: &[ContractInfo]) -> StdResult<HeroDump> { let hero = HeroDump { owner: api.human_address(&self.owner)?, name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle_skills: self.pre_battle_skills, post_battle_skills: self.post_battle_skills, }; Ok(hero) } } /// a hero's token info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreTokenInfo { /// hero's token id pub token_id: String, /// index of the card contract version pub version: u8, } /// battle info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreBattle { /// battle id number pub battle_number: u64, /// number of seconds since epoch time 01/01/1970 in which the battle took place pub timestamp: u64, /// heroes that fought pub heroes: Vec<StoreHero>, /// skill used to determine the winner pub skill_used: u8, /// index of winning hero pub winner: Option<u8>, /// winning skill value pub winning_skill_value: u8, } impl StoreBattle { /// Returns StdResult<Battle> from converting a StoreBattle to a displayable Battle /// /// # Arguments /// /// * `address` - a reference to the address querying their battle history /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_humanized( mut self, address: &CanonicalAddr, versions: &[ContractInfo], ) -> StdResult<Battle> { if let Some(pos) = self.heroes.iter().position(|h| h.owner == *address) { let winner = self.winner.map(|u| self.heroes[u as usize].name.clone()); let battle = Battle { battle_number: self.battle_number, timestamp: self.timestamp, my_hero: self.heroes.swap_remove(pos).into_humanized(versions)?, skill_used: self.skill_used, winner, winning_skill_value: self.winning_skill_value, i_won: self.winner.map_or_else(|| false, |w| w as usize == pos), }; Ok(battle) } else { Err(StdError::generic_err("Battle History corupted")) } } /// Returns StdResult<BattleDump> from converting a StoreBattle to a displayable BattleDump /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_dump<A: Api>( mut self, api: &A, versions: &[ContractInfo], ) -> StdResult<BattleDump> { let battle = BattleDump { battle_number: self.battle_number, timestamp: self.timestamp, heroes: self .heroes .drain(..) .map(|h| h.into_dump(api, versions)) .collect::<StdResult<Vec<HeroDump>>>()?, skill_used: self.skill_used, winner: self.winner, winning_skill_value: self.winning_skill_value, }; Ok(battle) } } /// code hash and address of a contract #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreContractInfo { /// contract's code hash string pub code_hash: String, /// contract's address pub address: CanonicalAddr, } impl StoreContractInfo { /// Returns StdResult<ContractInfo> from converting a StoreContractInfo to a displayable /// ContractInfo /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses pub fn to_humanized<A: Api>(&self, api: &A) -> StdResult<ContractInfo> { let info = ContractInfo { address: api.human_address(&self.address)?, code_hash: self.code_hash.clone(), }; Ok(info) } } /// Returns StdResult<()> after saving the battle id /// /// # Arguments /// /// * `storage` - a mutable reference to the storage this item should go to /// * `battle_num` - the battle id to store /// * `address` - a reference to the address for which to store this battle id pub fn append_battle_for_addr<S: Storage>( storage: &mut S, battle_num: u64, address: &CanonicalAddr, ) -> StdResult<()> { let mut store = PrefixedStorage::multilevel(&[PREFIX_BATTLE_ID, address.as_slice()], storage); let mut store = AppendStoreMut::attach_or_create(&mut store)?; store.push(&battle_num) }
/// * `api` - a reference to the Api used to convert human and canonical addresses /// * `storage` - a reference to the contract's storage /// * `address` - a reference to the address whose battles to display /// * `page` - page to start displaying /// * `page_size` - number of txs per page pub fn get_history<A: Api, S: ReadonlyStorage>( api: &A, storage: &S, address: &CanonicalAddr, page: u32, page_size: u32, ) -> StdResult<Vec<Battle>> { let id_store = ReadonlyPrefixedStorage::multilevel(&[PREFIX_BATTLE_ID, address.as_slice()], storage); // Try to access the storage of battle ids for the account. // If it doesn't exist yet, return an empty list of battles. let id_store = if let Some(result) = AppendStore::<u64, _>::attach(&id_store) { result? } else { return Ok(vec![]); }; let config: Config = load(storage, CONFIG_KEY)?; let versions = config .card_versions .iter() .map(|v| v.to_humanized(api)) .collect::<StdResult<Vec<ContractInfo>>>()?; // access battle storage let his_store = ReadonlyPrefixedStorage::new(PREFIX_HISTORY, storage); // Take `page_size` battles starting from the latest battle, potentially skipping `page * page_size` // battles from the start. let battles: StdResult<Vec<Battle>> = id_store .iter() .rev() .skip((page * page_size) as usize) .take(page_size as usize) .map(|id| { id.map(|id| { load(&his_store, &id.to_le_bytes()) .and_then(|b: StoreBattle| b.into_humanized(address, &versions)) }) .and_then(|x| x) }) .collect(); battles } pub fn save<T: Serialize, S: Storage>(storage: &mut S, key: &[u8], value: &T) -> StdResult<()> { storage.set(key, &Bincode2::serialize(value)?); Ok(()) } pub fn remove<S: Storage>(storage: &mut S, key: &[u8]) { storage.remove(key); } pub fn load<T: DeserializeOwned, S: ReadonlyStorage>(storage: &S, key: &[u8]) -> StdResult<T> { Bincode2::deserialize( &storage .get(key) .ok_or_else(|| StdError::not_found(type_name::<T>()))?, ) } pub fn may_load<T: DeserializeOwned, S: ReadonlyStorage>( storage: &S, key: &[u8], ) -> StdResult<Option<T>> { match storage.get(key) { Some(value) => Bincode2::deserialize(&value).map(Some), None => Ok(None), } }
/// Returns StdResult<Vec<Battle>> of the battles to display /// /// # Arguments ///
random_line_split
state.rs
use std::any::type_name; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit::{ serialization::{Bincode2, Serde}, storage::{AppendStore, AppendStoreMut}, }; use crate::msg::{Battle, BattleDump, ContractInfo, Hero, HeroDump, PlayerStats, TokenInfo}; use crate::stats::Stats; pub const CONFIG_KEY: &[u8] = b"config"; pub const PREFIX_VIEW_KEY: &[u8] = b"viewkey"; pub const PREFIX_HISTORY: &[u8] = b"history"; pub const PREFIX_BATTLE_ID: &[u8] = b"battleids"; pub const PREFIX_TOURN_STATS: &[u8] = b"trnstat"; pub const PREFIX_ALL_STATS: &[u8] = b"allstat"; pub const PREFIX_PLAYERS: &[u8] = b"players"; pub const PREFIX_SEEN: &[u8] = b"seen"; pub const ADMIN_KEY: &[u8] = b"admin"; pub const BOTS_KEY: &[u8] = b"bots"; pub const LEADERBOARDS_KEY: &[u8] = b"ldrbds"; pub const IMPORT_FROM_KEY: &[u8] = b"import"; pub const EXPORT_CONFIG_KEY: &[u8] = b"export"; /// arena config #[derive(Serialize, Deserialize)] pub struct Config { /// heroes waiting to fight pub heroes: Vec<StoreWaitingHero>, /// prng seed pub prng_seed: Vec<u8>, /// combined entropy strings supplied with the heroes pub entropy: String, /// current battle count in this arena pub battle_cnt: u64, /// battle count from previous arenas pub previous_battles: u64, /// viewing key used with the card contracts pub viewing_key: String, /// contract info of all the card versions pub card_versions: Vec<StoreContractInfo>, /// true if battles are halted pub fight_halt: bool, /// total number of players pub player_cnt: u32, /// list of new players that need to be added pub new_players: Vec<CanonicalAddr>, } /// export config #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ExportConfig { /// new arena contract info pub new_arena: StoreContractInfo, /// next block to export pub next: u32, } /// stored leaderboard entry #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Rank { /// player's score pub score: i32, /// player's address pub address: CanonicalAddr, } /// tournament data #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Tourney { /// tournament start time pub start: u64, /// tournament leaderboard pub leaderboard: Vec<Rank>, } /// leaderboards #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Leaderboards { /// tournament leaderboard pub tourney: Tourney, /// all time leaderboard pub all_time: Vec<Rank>, } /// tournament stats #[derive(Serialize, Deserialize, Clone, Debug)] pub struct TourneyStats { /// time of last update pub last_seen: u64, /// player's stats for this tournament pub stats: StorePlayerStats, } /// stored player stats #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StorePlayerStats { /// player's score pub score: i32, /// number of battles pub battles: u32, /// number of wins pub wins: u32, /// number of ties pub ties: u32, /// number of times took 3rd place in a 2-way tie pub third_in_two_way_ties: u32, /// number of losses pub losses: u32, } impl Default for StorePlayerStats { fn default() -> Self { Self { score: 0, battles: 0, wins: 0, ties: 0, third_in_two_way_ties: 0, losses: 0, } } } impl StorePlayerStats { /// Returns StdResult<PlayerStats> from converting a StorePlayerStats to a displayable /// PlayerStats /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `address` - a reference to the address corresponding to these stats pub fn into_humanized<A: Api>( self, api: &A, address: &CanonicalAddr, ) -> StdResult<PlayerStats> { let stats = PlayerStats { score: self.score, address: api.human_address(address)?, battles: self.battles, wins: self.wins, ties: self.ties, third_in_two_way_ties: self.third_in_two_way_ties, losses: self.losses, }; Ok(stats) } } /// waiting hero's info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreWaitingHero { /// hero's owner pub owner: CanonicalAddr, /// name of the hero pub name: String, /// hero's token info pub token_info: StoreTokenInfo, /// hero's stats pub stats: Stats, } /// hero info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreHero { /// hero's owner pub owner: CanonicalAddr, /// name of the hero pub name: String, /// hero's token info pub token_info: StoreTokenInfo, /// hero's skills before the battle pub pre_battle_skills: Vec<u8>, /// hero's skills after the battle pub post_battle_skills: Vec<u8>, } impl StoreHero { /// Returns StdResult<Hero> from converting a StoreHero to a displayable Hero /// /// # Arguments /// /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_humanized(self, versions: &[ContractInfo]) -> StdResult<Hero> { let hero = Hero { name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle_skills: self.pre_battle_skills, post_battle_skills: self.post_battle_skills, }; Ok(hero) } /// Returns StdResult<HeroDump> from converting a StoreHero to a displayable HeroDump /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_dump<A: Api>(self, api: &A, versions: &[ContractInfo]) -> StdResult<HeroDump> { let hero = HeroDump { owner: api.human_address(&self.owner)?, name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle_skills: self.pre_battle_skills, post_battle_skills: self.post_battle_skills, }; Ok(hero) } } /// a hero's token info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreTokenInfo { /// hero's token id pub token_id: String, /// index of the card contract version pub version: u8, } /// battle info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreBattle { /// battle id number pub battle_number: u64, /// number of seconds since epoch time 01/01/1970 in which the battle took place pub timestamp: u64, /// heroes that fought pub heroes: Vec<StoreHero>, /// skill used to determine the winner pub skill_used: u8, /// index of winning hero pub winner: Option<u8>, /// winning skill value pub winning_skill_value: u8, } impl StoreBattle { /// Returns StdResult<Battle> from converting a StoreBattle to a displayable Battle /// /// # Arguments /// /// * `address` - a reference to the address querying their battle history /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_humanized( mut self, address: &CanonicalAddr, versions: &[ContractInfo], ) -> StdResult<Battle> { if let Some(pos) = self.heroes.iter().position(|h| h.owner == *address) { let winner = self.winner.map(|u| self.heroes[u as usize].name.clone()); let battle = Battle { battle_number: self.battle_number, timestamp: self.timestamp, my_hero: self.heroes.swap_remove(pos).into_humanized(versions)?, skill_used: self.skill_used, winner, winning_skill_value: self.winning_skill_value, i_won: self.winner.map_or_else(|| false, |w| w as usize == pos), }; Ok(battle) } else { Err(StdError::generic_err("Battle History corupted")) } } /// Returns StdResult<BattleDump> from converting a StoreBattle to a displayable BattleDump /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_dump<A: Api>( mut self, api: &A, versions: &[ContractInfo], ) -> StdResult<BattleDump>
} /// code hash and address of a contract #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreContractInfo { /// contract's code hash string pub code_hash: String, /// contract's address pub address: CanonicalAddr, } impl StoreContractInfo { /// Returns StdResult<ContractInfo> from converting a StoreContractInfo to a displayable /// ContractInfo /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses pub fn to_humanized<A: Api>(&self, api: &A) -> StdResult<ContractInfo> { let info = ContractInfo { address: api.human_address(&self.address)?, code_hash: self.code_hash.clone(), }; Ok(info) } } /// Returns StdResult<()> after saving the battle id /// /// # Arguments /// /// * `storage` - a mutable reference to the storage this item should go to /// * `battle_num` - the battle id to store /// * `address` - a reference to the address for which to store this battle id pub fn append_battle_for_addr<S: Storage>( storage: &mut S, battle_num: u64, address: &CanonicalAddr, ) -> StdResult<()> { let mut store = PrefixedStorage::multilevel(&[PREFIX_BATTLE_ID, address.as_slice()], storage); let mut store = AppendStoreMut::attach_or_create(&mut store)?; store.push(&battle_num) } /// Returns StdResult<Vec<Battle>> of the battles to display /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `storage` - a reference to the contract's storage /// * `address` - a reference to the address whose battles to display /// * `page` - page to start displaying /// * `page_size` - number of txs per page pub fn get_history<A: Api, S: ReadonlyStorage>( api: &A, storage: &S, address: &CanonicalAddr, page: u32, page_size: u32, ) -> StdResult<Vec<Battle>> { let id_store = ReadonlyPrefixedStorage::multilevel(&[PREFIX_BATTLE_ID, address.as_slice()], storage); // Try to access the storage of battle ids for the account. // If it doesn't exist yet, return an empty list of battles. let id_store = if let Some(result) = AppendStore::<u64, _>::attach(&id_store) { result? } else { return Ok(vec![]); }; let config: Config = load(storage, CONFIG_KEY)?; let versions = config .card_versions .iter() .map(|v| v.to_humanized(api)) .collect::<StdResult<Vec<ContractInfo>>>()?; // access battle storage let his_store = ReadonlyPrefixedStorage::new(PREFIX_HISTORY, storage); // Take `page_size` battles starting from the latest battle, potentially skipping `page * page_size` // battles from the start. let battles: StdResult<Vec<Battle>> = id_store .iter() .rev() .skip((page * page_size) as usize) .take(page_size as usize) .map(|id| { id.map(|id| { load(&his_store, &id.to_le_bytes()) .and_then(|b: StoreBattle| b.into_humanized(address, &versions)) }) .and_then(|x| x) }) .collect(); battles } pub fn save<T: Serialize, S: Storage>(storage: &mut S, key: &[u8], value: &T) -> StdResult<()> { storage.set(key, &Bincode2::serialize(value)?); Ok(()) } pub fn remove<S: Storage>(storage: &mut S, key: &[u8]) { storage.remove(key); } pub fn load<T: DeserializeOwned, S: ReadonlyStorage>(storage: &S, key: &[u8]) -> StdResult<T> { Bincode2::deserialize( &storage .get(key) .ok_or_else(|| StdError::not_found(type_name::<T>()))?, ) } pub fn may_load<T: DeserializeOwned, S: ReadonlyStorage>( storage: &S, key: &[u8], ) -> StdResult<Option<T>> { match storage.get(key) { Some(value) => Bincode2::deserialize(&value).map(Some), None => Ok(None), } }
{ let battle = BattleDump { battle_number: self.battle_number, timestamp: self.timestamp, heroes: self .heroes .drain(..) .map(|h| h.into_dump(api, versions)) .collect::<StdResult<Vec<HeroDump>>>()?, skill_used: self.skill_used, winner: self.winner, winning_skill_value: self.winning_skill_value, }; Ok(battle) }
identifier_body
state.rs
use std::any::type_name; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit::{ serialization::{Bincode2, Serde}, storage::{AppendStore, AppendStoreMut}, }; use crate::msg::{Battle, BattleDump, ContractInfo, Hero, HeroDump, PlayerStats, TokenInfo}; use crate::stats::Stats; pub const CONFIG_KEY: &[u8] = b"config"; pub const PREFIX_VIEW_KEY: &[u8] = b"viewkey"; pub const PREFIX_HISTORY: &[u8] = b"history"; pub const PREFIX_BATTLE_ID: &[u8] = b"battleids"; pub const PREFIX_TOURN_STATS: &[u8] = b"trnstat"; pub const PREFIX_ALL_STATS: &[u8] = b"allstat"; pub const PREFIX_PLAYERS: &[u8] = b"players"; pub const PREFIX_SEEN: &[u8] = b"seen"; pub const ADMIN_KEY: &[u8] = b"admin"; pub const BOTS_KEY: &[u8] = b"bots"; pub const LEADERBOARDS_KEY: &[u8] = b"ldrbds"; pub const IMPORT_FROM_KEY: &[u8] = b"import"; pub const EXPORT_CONFIG_KEY: &[u8] = b"export"; /// arena config #[derive(Serialize, Deserialize)] pub struct Config { /// heroes waiting to fight pub heroes: Vec<StoreWaitingHero>, /// prng seed pub prng_seed: Vec<u8>, /// combined entropy strings supplied with the heroes pub entropy: String, /// current battle count in this arena pub battle_cnt: u64, /// battle count from previous arenas pub previous_battles: u64, /// viewing key used with the card contracts pub viewing_key: String, /// contract info of all the card versions pub card_versions: Vec<StoreContractInfo>, /// true if battles are halted pub fight_halt: bool, /// total number of players pub player_cnt: u32, /// list of new players that need to be added pub new_players: Vec<CanonicalAddr>, } /// export config #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ExportConfig { /// new arena contract info pub new_arena: StoreContractInfo, /// next block to export pub next: u32, } /// stored leaderboard entry #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Rank { /// player's score pub score: i32, /// player's address pub address: CanonicalAddr, } /// tournament data #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Tourney { /// tournament start time pub start: u64, /// tournament leaderboard pub leaderboard: Vec<Rank>, } /// leaderboards #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Leaderboards { /// tournament leaderboard pub tourney: Tourney, /// all time leaderboard pub all_time: Vec<Rank>, } /// tournament stats #[derive(Serialize, Deserialize, Clone, Debug)] pub struct TourneyStats { /// time of last update pub last_seen: u64, /// player's stats for this tournament pub stats: StorePlayerStats, } /// stored player stats #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StorePlayerStats { /// player's score pub score: i32, /// number of battles pub battles: u32, /// number of wins pub wins: u32, /// number of ties pub ties: u32, /// number of times took 3rd place in a 2-way tie pub third_in_two_way_ties: u32, /// number of losses pub losses: u32, } impl Default for StorePlayerStats { fn default() -> Self { Self { score: 0, battles: 0, wins: 0, ties: 0, third_in_two_way_ties: 0, losses: 0, } } } impl StorePlayerStats { /// Returns StdResult<PlayerStats> from converting a StorePlayerStats to a displayable /// PlayerStats /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `address` - a reference to the address corresponding to these stats pub fn into_humanized<A: Api>( self, api: &A, address: &CanonicalAddr, ) -> StdResult<PlayerStats> { let stats = PlayerStats { score: self.score, address: api.human_address(address)?, battles: self.battles, wins: self.wins, ties: self.ties, third_in_two_way_ties: self.third_in_two_way_ties, losses: self.losses, }; Ok(stats) } } /// waiting hero's info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreWaitingHero { /// hero's owner pub owner: CanonicalAddr, /// name of the hero pub name: String, /// hero's token info pub token_info: StoreTokenInfo, /// hero's stats pub stats: Stats, } /// hero info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreHero { /// hero's owner pub owner: CanonicalAddr, /// name of the hero pub name: String, /// hero's token info pub token_info: StoreTokenInfo, /// hero's skills before the battle pub pre_battle_skills: Vec<u8>, /// hero's skills after the battle pub post_battle_skills: Vec<u8>, } impl StoreHero { /// Returns StdResult<Hero> from converting a StoreHero to a displayable Hero /// /// # Arguments /// /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_humanized(self, versions: &[ContractInfo]) -> StdResult<Hero> { let hero = Hero { name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle_skills: self.pre_battle_skills, post_battle_skills: self.post_battle_skills, }; Ok(hero) } /// Returns StdResult<HeroDump> from converting a StoreHero to a displayable HeroDump /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_dump<A: Api>(self, api: &A, versions: &[ContractInfo]) -> StdResult<HeroDump> { let hero = HeroDump { owner: api.human_address(&self.owner)?, name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle_skills: self.pre_battle_skills, post_battle_skills: self.post_battle_skills, }; Ok(hero) } } /// a hero's token info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreTokenInfo { /// hero's token id pub token_id: String, /// index of the card contract version pub version: u8, } /// battle info #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreBattle { /// battle id number pub battle_number: u64, /// number of seconds since epoch time 01/01/1970 in which the battle took place pub timestamp: u64, /// heroes that fought pub heroes: Vec<StoreHero>, /// skill used to determine the winner pub skill_used: u8, /// index of winning hero pub winner: Option<u8>, /// winning skill value pub winning_skill_value: u8, } impl StoreBattle { /// Returns StdResult<Battle> from converting a StoreBattle to a displayable Battle /// /// # Arguments /// /// * `address` - a reference to the address querying their battle history /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_humanized( mut self, address: &CanonicalAddr, versions: &[ContractInfo], ) -> StdResult<Battle> { if let Some(pos) = self.heroes.iter().position(|h| h.owner == *address) { let winner = self.winner.map(|u| self.heroes[u as usize].name.clone()); let battle = Battle { battle_number: self.battle_number, timestamp: self.timestamp, my_hero: self.heroes.swap_remove(pos).into_humanized(versions)?, skill_used: self.skill_used, winner, winning_skill_value: self.winning_skill_value, i_won: self.winner.map_or_else(|| false, |w| w as usize == pos), }; Ok(battle) } else { Err(StdError::generic_err("Battle History corupted")) } } /// Returns StdResult<BattleDump> from converting a StoreBattle to a displayable BattleDump /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `versions` - a slice of ContractInfo of token contract versions pub fn into_dump<A: Api>( mut self, api: &A, versions: &[ContractInfo], ) -> StdResult<BattleDump> { let battle = BattleDump { battle_number: self.battle_number, timestamp: self.timestamp, heroes: self .heroes .drain(..) .map(|h| h.into_dump(api, versions)) .collect::<StdResult<Vec<HeroDump>>>()?, skill_used: self.skill_used, winner: self.winner, winning_skill_value: self.winning_skill_value, }; Ok(battle) } } /// code hash and address of a contract #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreContractInfo { /// contract's code hash string pub code_hash: String, /// contract's address pub address: CanonicalAddr, } impl StoreContractInfo { /// Returns StdResult<ContractInfo> from converting a StoreContractInfo to a displayable /// ContractInfo /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses pub fn to_humanized<A: Api>(&self, api: &A) -> StdResult<ContractInfo> { let info = ContractInfo { address: api.human_address(&self.address)?, code_hash: self.code_hash.clone(), }; Ok(info) } } /// Returns StdResult<()> after saving the battle id /// /// # Arguments /// /// * `storage` - a mutable reference to the storage this item should go to /// * `battle_num` - the battle id to store /// * `address` - a reference to the address for which to store this battle id pub fn append_battle_for_addr<S: Storage>( storage: &mut S, battle_num: u64, address: &CanonicalAddr, ) -> StdResult<()> { let mut store = PrefixedStorage::multilevel(&[PREFIX_BATTLE_ID, address.as_slice()], storage); let mut store = AppendStoreMut::attach_or_create(&mut store)?; store.push(&battle_num) } /// Returns StdResult<Vec<Battle>> of the battles to display /// /// # Arguments /// /// * `api` - a reference to the Api used to convert human and canonical addresses /// * `storage` - a reference to the contract's storage /// * `address` - a reference to the address whose battles to display /// * `page` - page to start displaying /// * `page_size` - number of txs per page pub fn get_history<A: Api, S: ReadonlyStorage>( api: &A, storage: &S, address: &CanonicalAddr, page: u32, page_size: u32, ) -> StdResult<Vec<Battle>> { let id_store = ReadonlyPrefixedStorage::multilevel(&[PREFIX_BATTLE_ID, address.as_slice()], storage); // Try to access the storage of battle ids for the account. // If it doesn't exist yet, return an empty list of battles. let id_store = if let Some(result) = AppendStore::<u64, _>::attach(&id_store)
else { return Ok(vec![]); }; let config: Config = load(storage, CONFIG_KEY)?; let versions = config .card_versions .iter() .map(|v| v.to_humanized(api)) .collect::<StdResult<Vec<ContractInfo>>>()?; // access battle storage let his_store = ReadonlyPrefixedStorage::new(PREFIX_HISTORY, storage); // Take `page_size` battles starting from the latest battle, potentially skipping `page * page_size` // battles from the start. let battles: StdResult<Vec<Battle>> = id_store .iter() .rev() .skip((page * page_size) as usize) .take(page_size as usize) .map(|id| { id.map(|id| { load(&his_store, &id.to_le_bytes()) .and_then(|b: StoreBattle| b.into_humanized(address, &versions)) }) .and_then(|x| x) }) .collect(); battles } pub fn save<T: Serialize, S: Storage>(storage: &mut S, key: &[u8], value: &T) -> StdResult<()> { storage.set(key, &Bincode2::serialize(value)?); Ok(()) } pub fn remove<S: Storage>(storage: &mut S, key: &[u8]) { storage.remove(key); } pub fn load<T: DeserializeOwned, S: ReadonlyStorage>(storage: &S, key: &[u8]) -> StdResult<T> { Bincode2::deserialize( &storage .get(key) .ok_or_else(|| StdError::not_found(type_name::<T>()))?, ) } pub fn may_load<T: DeserializeOwned, S: ReadonlyStorage>( storage: &S, key: &[u8], ) -> StdResult<Option<T>> { match storage.get(key) { Some(value) => Bincode2::deserialize(&value).map(Some), None => Ok(None), } }
{ result? }
conditional_block
testingfrog.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(clippy::all)] //**************************************** // tracing test //**************************************** // use axum::{routing::get, Router}; // use std::error::Error; // // use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Registry}; // use tracing_tree::HierarchicalLayer; // use website::handlers; // // #[tokio::main] // async fn main() -> Result<(), Box<dyn Error>> { // Registry::default() // .with(EnvFilter::from_default_env()) // .with( // HierarchicalLayer::new(2) // .with_targets(true) // .with_bracketed_fields(true), // ) // .init(); // // let app = Router::new().route("/", get(handlers::root::get)); // // axum::Server::bind(&"0.0.0.0:8000".parse().unwrap()) // .serve(app.into_make_service()) // .await?; // // Ok(()) // } // **************************************** // parsing and rendering test // **************************************** use nom::{ branch::alt, bytes::complete::{tag, take_till, take_until}, character::complete::{newline, space0, space1}, combinator::map, multi::separated_list0, sequence::{delimited, pair, tuple}, IResult, }; use std::{error::Error, fs}; use pulldown_cmark::{html, CodeBlockKind, Event, Parser, Tag}; use syntect::{ highlighting::ThemeSet, html::{highlighted_html_for_file, highlighted_html_for_string}, parsing::SyntaxSet, }; type BoxError = Box<dyn Error>; type BoxResult<T> = Result<T, BoxError>; #[derive(Debug)] enum PostStatus { Draft, Published, } // a simple struct to hold a post, without parsing the markdown // basically, simply parse the header before feeding it to content pipeline struct Post<'input> { title: &'input str, tags: Vec<&'input str>, status: PostStatus, raw_content: &'input str, } fn post_title(input: &str) -> IResult<&str, &str> { delimited(tag("title"), take_until("\n"), newline)(input) } fn post_tags(input: &str) -> IResult<&str, Vec<&str>> { delimited( pair(tag("tags:"), space0), separated_list0( tuple((space0, tag(","), space0)), take_till(|c| c == ',' || c == '\n'), ), newline, )(input) } fn post_status(input: &str) -> IResult<&str, PostStatus> { delimited( tag("status:"), delimited( space1, alt(( map(tag("published"), |_| PostStatus::Published), map(tag("draft"), |_| PostStatus::Draft), )), space0, ), newline, )(input) } fn post_header(input: &str) -> IResult<&str, (&str, Vec<&str>, PostStatus)> { delimited( pair(tag("---"), newline), tuple((post_title, post_tags, post_status)), pair(tag("---"), newline), )(input) } impl<'a> Post<'a> { fn from_str(input: &'a str) -> Result<Post<'a>, Box<dyn Error>> { let (remaining, (title, tags, status)) = post_header(input).map_err(|e| e.to_owned())?; Ok(Self { title, tags, status, raw_content: remaining, }) } } struct SyntectEvent<I> { inner: I, tok: Option<String>, syntax_set: SyntaxSet, } impl<'a, I> SyntectEvent<I> { fn new(inner: I) -> Self { Self { inner, tok: None, syntax_set: SyntaxSet::load_defaults_newlines(), } } } impl<'a, I> Iterator for SyntectEvent<I> where I: Iterator<Item = Event<'a>>, { type Item = Event<'a>; fn next(&mut self) -> Option<Self::Item> { match self.inner.next() { None => None, Some(ev) => match ev { Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(ref tok))) => { self.tok = Some(tok.to_string()); Some(ev) // self.next() // TODO check that, it's fishy, used to strip the <code> block } Event::Text(ref content) => { if let Some(tok) = &self.tok { let ts = ThemeSet::load_defaults(); let theme = &ts.themes["Solarized (light)"]; let s = self .syntax_set .find_syntax_by_token(&tok) .unwrap_or_else(|| self.syntax_set.find_syntax_plain_text()); eprintln!("syntax found: {}", s.name); match highlighted_html_for_string(content, &self.syntax_set, &s, &theme) { Ok(res) => Some(Event::Html(res.into())), Err(err) => { eprintln!("error during html conversion: {:?}", err); Some(ev) } } } else { Some(ev) } } Event::End(Tag::CodeBlock(CodeBlockKind::Fenced(_))) => { self.tok = None; Some(ev) } _ => Some(ev), }, } } } fn main() -> BoxResult<()> { let fmt = time::format_description::parse("[year]-[month]-[day]")?; let t = time::Date::parse("2022-08-01-coucou", &fmt)?; println!("{}", t.format(&fmt)?); return Ok(()); let raws = fs::read_dir("./blog/posts/")? .into_iter() .map(|d| d.and_then(|d| fs::read_to_string(d.path()))) .collect::<Result<Vec<_>, _>>()?; let posts: Vec<Post> = raws // .map(|d| d.and_then(|d| fs::read_to_string(d.path()).map_err(|e| // Box::new(e) as Box<dyn Error> // ))) .iter() .map(|s| Post::from_str(s)) .collect::<BoxResult<Vec<_>>>()?; // let posts2: Vec<Post> = fs::read_dir("./blog/posts/")? // .into_iter() // .map(|d| { // d.and_then(|d| fs::read_to_string(d.path())) // .map_err(|e| Box::new(e) as Box<dyn Error>) // .as_ref().map(|x| Post::from_str(x).unwrap()) // .map_err(|e| todo!()) // }) // .collect::<BoxResult<Vec<_>>>()?; let blah = vec![fs::read_to_string( "./blog/posts/2020-03-31-quick-static-hosting.md", )?]; let _p = blah .iter() .map(|s| Post::from_str(s).unwrap()) .collect::<Vec<_>>(); let raw = include_str!("test.md"); let post = Post::from_str(raw)?; let parser = Parser::new(post.raw_content); // let ts = ThemeSet::load_defaults(); // let ss = SyntaxSet::load_defaults_newlines(); // let theme = &ts.themes["Solarized (light)"]; // for event in &parser { // println!("{:?}", event); // // if let Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(tok))) = event { // // println!("!!!!!!!!!!!!!! got a token {tok:?}"); // // let syn = ss.find_syntax_by_token(&tok).as_ref().map(|x| &*x.name); // // println!("syntax? {:?}", syn); // // } // } let events = SyntectEvent::new(parser); let mut html_output = String::new(); html::push_html(&mut html_output, events); println!("{}", html_output); // println!("title: {}", post.title); // println!("tags: {:?}", post.tags); // println!("status: {:?}", post.status); // for sr in ss.syntaxes() { // println!("{} - {:?}", sr.name, sr.file_extensions); // } // let ts = ThemeSet::load_defaults(); // let theme = &ts.themes["Solarized (light)"]; // let html = highlighted_html_for_file("src/bin/geekingfrog.rs", &ss, theme).unwrap(); // println!("{}", html); Ok(()) } // //**************************************** // // Axum test // //**************************************** // use axum::{ // extract::{ // ws::{Message, WebSocket}, // State, WebSocketUpgrade, // }, // http::StatusCode, // response::{Html, IntoResponse, Response}, // routing::{get, get_service}, // BoxError, Router, // }; // use notify::{watcher, RecursiveMode, Watcher, raw_watcher}; // use parking_lot::RwLock; // use std::{ // net::SocketAddr, // sync::{mpsc, Arc}, // time::Duration, // }; // use tera::Tera; // use tokio::sync::watch::{self, Receiver, Sender}; // use tower::ServiceBuilder; // use tower_http::{services::ServeDir, trace::TraceLayer}; // // #[derive(Clone)] // struct AppState { // template: Arc<RwLock<Tera>>, // refresh_chan: Receiver<()>, // } // // #[tokio::main] // async fn main() -> Result<(), BoxError> { // tracing_subscriber::fmt::init(); // // let tera = Arc::new(RwLock::new( // Tera::new("templates/**/*.html").expect("can get tera"), // )); // let (refresh_tx, refresh_rx) = watch::channel(()); // // // force a new value from the initial one so that calling rx.watch // // is sure to return something. // refresh_tx.send(())?; // // let app_state = AppState { // template: tera.clone(), // refresh_chan: refresh_rx, // }; // // let service = ServiceBuilder::new().layer(TraceLayer::new_for_http()); // // .layer(ServeDir::new("templates")); // // let app = Router::with_state(app_state) // .layer(service) // .route("/", get(root)) // .route("/ws/autorefresh", get(autorefresh_handler)) // .nest( // "/static", // get_service(ServeDir::new("static")).handle_error(|err: std::io::Error| async move { // tracing::info!("Error serving static staff: {err:?}"); // (StatusCode::INTERNAL_SERVER_ERROR, format!("{err:?}")) // }), // ); // // let addr = SocketAddr::from(([127, 0, 0, 1], 8888)); // // tokio::try_join!( // async { // tokio::task::spawn_blocking(move || watch_templates_change(tera, refresh_tx)).await? // }, // async { // tracing::debug!("Listening on {addr}"); // axum::Server::bind(&addr) // .serve(app.into_make_service()) // .await?; // Ok(()) // } // )?; // // Ok(()) // } // // async fn root(State(state): State<AppState>) -> Result<Html<String>, AppError> { // Ok(state // .template // .read() // .render("index.html", &tera::Context::new())? // .into()) // } // // async fn autorefresh_handler( // ws: WebSocketUpgrade, // State(state): State<AppState>, // ) -> impl IntoResponse { // tracing::debug!("got a websocket upgrade request"); // ws.on_upgrade(|socket| handle_socket(socket, state.refresh_chan)) // } // // async fn handle_socket(mut socket: WebSocket, mut refresh_tx: Receiver<()>) { // // There's this weird problem, if a watched file has changed at some point // // there will be a new value on the refresh_rx channel, and calling // // `changed` on it will return immediately, even if the change has happened // // before this call. So always ignore the first change on the channel. // // The sender will always send a new value after channel creation to avoid // // a different behavior between pages loaded before and after a change // // to a watched file. // let mut has_seen_one_change = false; // loop { // tokio::select! { // x = refresh_tx.changed() => { // tracing::debug!("refresh event!"); // if !has_seen_one_change { // has_seen_one_change = true; // continue // } // // match x { // Ok(_) => if socket.send(Message::Text("refresh".to_string())).await.is_err() { // tracing::debug!("cannot send stuff, socket probably disconnected"); // break; // }, // Err(err) => { // tracing::error!("Cannot read refresh chan??? {err:?}"); // break // }, // } // } // msg = socket.recv() => { // match msg { // Some(_) => { // tracing::debug!("received a websocket message, don't care"); // }, // None => { // tracing::debug!("websocket disconnected"); // break // }, // } // } // else => break // } // } // } // // #[derive(thiserror::Error, Debug)] // enum AppError { // #[error("Template error")] // TemplateError(#[from] tera::Error), // } // // impl IntoResponse for AppError { // fn into_response(self) -> Response { // let res = match self { // AppError::TemplateError(err) => ( // StatusCode::INTERNAL_SERVER_ERROR, // format!("Templating error: {err}"), // ), // }; // res.into_response() // } // } // // fn watch_templates_change(tera: Arc<RwLock<Tera>>, refresh_tx: Sender<()>) -> Result<(), BoxError> { // let (tx, rx) = std::sync::mpsc::channel(); // let rx = Debounced { // rx, // d: Duration::from_millis(300), // }; // // // the default watcher is debounced, but will always send the first event // // emmediately, and then debounce any further events. But that means a regular // // update actually triggers many events, which are debounced to 2 events. // // So use the raw_watcher and manually debounce // let mut watcher = raw_watcher(tx)?; // watcher.watch("templates", RecursiveMode::Recursive)?; // loop { // match rx.recv() { // Ok(ev) => { // tracing::info!("debounced event {ev:?}"); // tera.write().full_reload()?; // refresh_tx.send(())?; // } // Err(_timeout_error) => (), // } // } // } // // /// wrap a Receiver<T> such that if many T are received between the given Duration // /// then only the latest one will be kept and returned when calling recv // struct Debounced<T> { // rx: mpsc::Receiver<T>, // d: Duration, // }
// loop { // match prev { // Some(v) => match self.rx.recv_timeout(self.d) { // Ok(newval) => { // prev = Some(newval); // continue; // } // Err(_) => break Ok(v), // }, // None => match self.rx.recv() { // Ok(val) => { // prev = Some(val); // continue; // } // Err(err) => break Err(err), // }, // } // } // } // }
// // impl<T> Debounced<T> { // fn recv(&self) -> Result<T, mpsc::RecvError> { // let mut prev = None; //
random_line_split
testingfrog.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(clippy::all)] //**************************************** // tracing test //**************************************** // use axum::{routing::get, Router}; // use std::error::Error; // // use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Registry}; // use tracing_tree::HierarchicalLayer; // use website::handlers; // // #[tokio::main] // async fn main() -> Result<(), Box<dyn Error>> { // Registry::default() // .with(EnvFilter::from_default_env()) // .with( // HierarchicalLayer::new(2) // .with_targets(true) // .with_bracketed_fields(true), // ) // .init(); // // let app = Router::new().route("/", get(handlers::root::get)); // // axum::Server::bind(&"0.0.0.0:8000".parse().unwrap()) // .serve(app.into_make_service()) // .await?; // // Ok(()) // } // **************************************** // parsing and rendering test // **************************************** use nom::{ branch::alt, bytes::complete::{tag, take_till, take_until}, character::complete::{newline, space0, space1}, combinator::map, multi::separated_list0, sequence::{delimited, pair, tuple}, IResult, }; use std::{error::Error, fs}; use pulldown_cmark::{html, CodeBlockKind, Event, Parser, Tag}; use syntect::{ highlighting::ThemeSet, html::{highlighted_html_for_file, highlighted_html_for_string}, parsing::SyntaxSet, }; type BoxError = Box<dyn Error>; type BoxResult<T> = Result<T, BoxError>; #[derive(Debug)] enum PostStatus { Draft, Published, } // a simple struct to hold a post, without parsing the markdown // basically, simply parse the header before feeding it to content pipeline struct Post<'input> { title: &'input str, tags: Vec<&'input str>, status: PostStatus, raw_content: &'input str, } fn post_title(input: &str) -> IResult<&str, &str> { delimited(tag("title"), take_until("\n"), newline)(input) } fn post_tags(input: &str) -> IResult<&str, Vec<&str>> { delimited( pair(tag("tags:"), space0), separated_list0( tuple((space0, tag(","), space0)), take_till(|c| c == ',' || c == '\n'), ), newline, )(input) } fn post_status(input: &str) -> IResult<&str, PostStatus>
fn post_header(input: &str) -> IResult<&str, (&str, Vec<&str>, PostStatus)> { delimited( pair(tag("---"), newline), tuple((post_title, post_tags, post_status)), pair(tag("---"), newline), )(input) } impl<'a> Post<'a> { fn from_str(input: &'a str) -> Result<Post<'a>, Box<dyn Error>> { let (remaining, (title, tags, status)) = post_header(input).map_err(|e| e.to_owned())?; Ok(Self { title, tags, status, raw_content: remaining, }) } } struct SyntectEvent<I> { inner: I, tok: Option<String>, syntax_set: SyntaxSet, } impl<'a, I> SyntectEvent<I> { fn new(inner: I) -> Self { Self { inner, tok: None, syntax_set: SyntaxSet::load_defaults_newlines(), } } } impl<'a, I> Iterator for SyntectEvent<I> where I: Iterator<Item = Event<'a>>, { type Item = Event<'a>; fn next(&mut self) -> Option<Self::Item> { match self.inner.next() { None => None, Some(ev) => match ev { Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(ref tok))) => { self.tok = Some(tok.to_string()); Some(ev) // self.next() // TODO check that, it's fishy, used to strip the <code> block } Event::Text(ref content) => { if let Some(tok) = &self.tok { let ts = ThemeSet::load_defaults(); let theme = &ts.themes["Solarized (light)"]; let s = self .syntax_set .find_syntax_by_token(&tok) .unwrap_or_else(|| self.syntax_set.find_syntax_plain_text()); eprintln!("syntax found: {}", s.name); match highlighted_html_for_string(content, &self.syntax_set, &s, &theme) { Ok(res) => Some(Event::Html(res.into())), Err(err) => { eprintln!("error during html conversion: {:?}", err); Some(ev) } } } else { Some(ev) } } Event::End(Tag::CodeBlock(CodeBlockKind::Fenced(_))) => { self.tok = None; Some(ev) } _ => Some(ev), }, } } } fn main() -> BoxResult<()> { let fmt = time::format_description::parse("[year]-[month]-[day]")?; let t = time::Date::parse("2022-08-01-coucou", &fmt)?; println!("{}", t.format(&fmt)?); return Ok(()); let raws = fs::read_dir("./blog/posts/")? .into_iter() .map(|d| d.and_then(|d| fs::read_to_string(d.path()))) .collect::<Result<Vec<_>, _>>()?; let posts: Vec<Post> = raws // .map(|d| d.and_then(|d| fs::read_to_string(d.path()).map_err(|e| // Box::new(e) as Box<dyn Error> // ))) .iter() .map(|s| Post::from_str(s)) .collect::<BoxResult<Vec<_>>>()?; // let posts2: Vec<Post> = fs::read_dir("./blog/posts/")? // .into_iter() // .map(|d| { // d.and_then(|d| fs::read_to_string(d.path())) // .map_err(|e| Box::new(e) as Box<dyn Error>) // .as_ref().map(|x| Post::from_str(x).unwrap()) // .map_err(|e| todo!()) // }) // .collect::<BoxResult<Vec<_>>>()?; let blah = vec![fs::read_to_string( "./blog/posts/2020-03-31-quick-static-hosting.md", )?]; let _p = blah .iter() .map(|s| Post::from_str(s).unwrap()) .collect::<Vec<_>>(); let raw = include_str!("test.md"); let post = Post::from_str(raw)?; let parser = Parser::new(post.raw_content); // let ts = ThemeSet::load_defaults(); // let ss = SyntaxSet::load_defaults_newlines(); // let theme = &ts.themes["Solarized (light)"]; // for event in &parser { // println!("{:?}", event); // // if let Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(tok))) = event { // // println!("!!!!!!!!!!!!!! got a token {tok:?}"); // // let syn = ss.find_syntax_by_token(&tok).as_ref().map(|x| &*x.name); // // println!("syntax? {:?}", syn); // // } // } let events = SyntectEvent::new(parser); let mut html_output = String::new(); html::push_html(&mut html_output, events); println!("{}", html_output); // println!("title: {}", post.title); // println!("tags: {:?}", post.tags); // println!("status: {:?}", post.status); // for sr in ss.syntaxes() { // println!("{} - {:?}", sr.name, sr.file_extensions); // } // let ts = ThemeSet::load_defaults(); // let theme = &ts.themes["Solarized (light)"]; // let html = highlighted_html_for_file("src/bin/geekingfrog.rs", &ss, theme).unwrap(); // println!("{}", html); Ok(()) } // //**************************************** // // Axum test // //**************************************** // use axum::{ // extract::{ // ws::{Message, WebSocket}, // State, WebSocketUpgrade, // }, // http::StatusCode, // response::{Html, IntoResponse, Response}, // routing::{get, get_service}, // BoxError, Router, // }; // use notify::{watcher, RecursiveMode, Watcher, raw_watcher}; // use parking_lot::RwLock; // use std::{ // net::SocketAddr, // sync::{mpsc, Arc}, // time::Duration, // }; // use tera::Tera; // use tokio::sync::watch::{self, Receiver, Sender}; // use tower::ServiceBuilder; // use tower_http::{services::ServeDir, trace::TraceLayer}; // // #[derive(Clone)] // struct AppState { // template: Arc<RwLock<Tera>>, // refresh_chan: Receiver<()>, // } // // #[tokio::main] // async fn main() -> Result<(), BoxError> { // tracing_subscriber::fmt::init(); // // let tera = Arc::new(RwLock::new( // Tera::new("templates/**/*.html").expect("can get tera"), // )); // let (refresh_tx, refresh_rx) = watch::channel(()); // // // force a new value from the initial one so that calling rx.watch // // is sure to return something. // refresh_tx.send(())?; // // let app_state = AppState { // template: tera.clone(), // refresh_chan: refresh_rx, // }; // // let service = ServiceBuilder::new().layer(TraceLayer::new_for_http()); // // .layer(ServeDir::new("templates")); // // let app = Router::with_state(app_state) // .layer(service) // .route("/", get(root)) // .route("/ws/autorefresh", get(autorefresh_handler)) // .nest( // "/static", // get_service(ServeDir::new("static")).handle_error(|err: std::io::Error| async move { // tracing::info!("Error serving static staff: {err:?}"); // (StatusCode::INTERNAL_SERVER_ERROR, format!("{err:?}")) // }), // ); // // let addr = SocketAddr::from(([127, 0, 0, 1], 8888)); // // tokio::try_join!( // async { // tokio::task::spawn_blocking(move || watch_templates_change(tera, refresh_tx)).await? // }, // async { // tracing::debug!("Listening on {addr}"); // axum::Server::bind(&addr) // .serve(app.into_make_service()) // .await?; // Ok(()) // } // )?; // // Ok(()) // } // // async fn root(State(state): State<AppState>) -> Result<Html<String>, AppError> { // Ok(state // .template // .read() // .render("index.html", &tera::Context::new())? // .into()) // } // // async fn autorefresh_handler( // ws: WebSocketUpgrade, // State(state): State<AppState>, // ) -> impl IntoResponse { // tracing::debug!("got a websocket upgrade request"); // ws.on_upgrade(|socket| handle_socket(socket, state.refresh_chan)) // } // // async fn handle_socket(mut socket: WebSocket, mut refresh_tx: Receiver<()>) { // // There's this weird problem, if a watched file has changed at some point // // there will be a new value on the refresh_rx channel, and calling // // `changed` on it will return immediately, even if the change has happened // // before this call. So always ignore the first change on the channel. // // The sender will always send a new value after channel creation to avoid // // a different behavior between pages loaded before and after a change // // to a watched file. // let mut has_seen_one_change = false; // loop { // tokio::select! { // x = refresh_tx.changed() => { // tracing::debug!("refresh event!"); // if !has_seen_one_change { // has_seen_one_change = true; // continue // } // // match x { // Ok(_) => if socket.send(Message::Text("refresh".to_string())).await.is_err() { // tracing::debug!("cannot send stuff, socket probably disconnected"); // break; // }, // Err(err) => { // tracing::error!("Cannot read refresh chan??? {err:?}"); // break // }, // } // } // msg = socket.recv() => { // match msg { // Some(_) => { // tracing::debug!("received a websocket message, don't care"); // }, // None => { // tracing::debug!("websocket disconnected"); // break // }, // } // } // else => break // } // } // } // // #[derive(thiserror::Error, Debug)] // enum AppError { // #[error("Template error")] // TemplateError(#[from] tera::Error), // } // // impl IntoResponse for AppError { // fn into_response(self) -> Response { // let res = match self { // AppError::TemplateError(err) => ( // StatusCode::INTERNAL_SERVER_ERROR, // format!("Templating error: {err}"), // ), // }; // res.into_response() // } // } // // fn watch_templates_change(tera: Arc<RwLock<Tera>>, refresh_tx: Sender<()>) -> Result<(), BoxError> { // let (tx, rx) = std::sync::mpsc::channel(); // let rx = Debounced { // rx, // d: Duration::from_millis(300), // }; // // // the default watcher is debounced, but will always send the first event // // emmediately, and then debounce any further events. But that means a regular // // update actually triggers many events, which are debounced to 2 events. // // So use the raw_watcher and manually debounce // let mut watcher = raw_watcher(tx)?; // watcher.watch("templates", RecursiveMode::Recursive)?; // loop { // match rx.recv() { // Ok(ev) => { // tracing::info!("debounced event {ev:?}"); // tera.write().full_reload()?; // refresh_tx.send(())?; // } // Err(_timeout_error) => (), // } // } // } // // /// wrap a Receiver<T> such that if many T are received between the given Duration // /// then only the latest one will be kept and returned when calling recv // struct Debounced<T> { // rx: mpsc::Receiver<T>, // d: Duration, // } // // impl<T> Debounced<T> { // fn recv(&self) -> Result<T, mpsc::RecvError> { // let mut prev = None; // // loop { // match prev { // Some(v) => match self.rx.recv_timeout(self.d) { // Ok(newval) => { // prev = Some(newval); // continue; // } // Err(_) => break Ok(v), // }, // None => match self.rx.recv() { // Ok(val) => { // prev = Some(val); // continue; // } // Err(err) => break Err(err), // }, // } // } // } // }
{ delimited( tag("status:"), delimited( space1, alt(( map(tag("published"), |_| PostStatus::Published), map(tag("draft"), |_| PostStatus::Draft), )), space0, ), newline, )(input) }
identifier_body
testingfrog.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(clippy::all)] //**************************************** // tracing test //**************************************** // use axum::{routing::get, Router}; // use std::error::Error; // // use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Registry}; // use tracing_tree::HierarchicalLayer; // use website::handlers; // // #[tokio::main] // async fn main() -> Result<(), Box<dyn Error>> { // Registry::default() // .with(EnvFilter::from_default_env()) // .with( // HierarchicalLayer::new(2) // .with_targets(true) // .with_bracketed_fields(true), // ) // .init(); // // let app = Router::new().route("/", get(handlers::root::get)); // // axum::Server::bind(&"0.0.0.0:8000".parse().unwrap()) // .serve(app.into_make_service()) // .await?; // // Ok(()) // } // **************************************** // parsing and rendering test // **************************************** use nom::{ branch::alt, bytes::complete::{tag, take_till, take_until}, character::complete::{newline, space0, space1}, combinator::map, multi::separated_list0, sequence::{delimited, pair, tuple}, IResult, }; use std::{error::Error, fs}; use pulldown_cmark::{html, CodeBlockKind, Event, Parser, Tag}; use syntect::{ highlighting::ThemeSet, html::{highlighted_html_for_file, highlighted_html_for_string}, parsing::SyntaxSet, }; type BoxError = Box<dyn Error>; type BoxResult<T> = Result<T, BoxError>; #[derive(Debug)] enum PostStatus { Draft, Published, } // a simple struct to hold a post, without parsing the markdown // basically, simply parse the header before feeding it to content pipeline struct Post<'input> { title: &'input str, tags: Vec<&'input str>, status: PostStatus, raw_content: &'input str, } fn post_title(input: &str) -> IResult<&str, &str> { delimited(tag("title"), take_until("\n"), newline)(input) } fn post_tags(input: &str) -> IResult<&str, Vec<&str>> { delimited( pair(tag("tags:"), space0), separated_list0( tuple((space0, tag(","), space0)), take_till(|c| c == ',' || c == '\n'), ), newline, )(input) } fn
(input: &str) -> IResult<&str, PostStatus> { delimited( tag("status:"), delimited( space1, alt(( map(tag("published"), |_| PostStatus::Published), map(tag("draft"), |_| PostStatus::Draft), )), space0, ), newline, )(input) } fn post_header(input: &str) -> IResult<&str, (&str, Vec<&str>, PostStatus)> { delimited( pair(tag("---"), newline), tuple((post_title, post_tags, post_status)), pair(tag("---"), newline), )(input) } impl<'a> Post<'a> { fn from_str(input: &'a str) -> Result<Post<'a>, Box<dyn Error>> { let (remaining, (title, tags, status)) = post_header(input).map_err(|e| e.to_owned())?; Ok(Self { title, tags, status, raw_content: remaining, }) } } struct SyntectEvent<I> { inner: I, tok: Option<String>, syntax_set: SyntaxSet, } impl<'a, I> SyntectEvent<I> { fn new(inner: I) -> Self { Self { inner, tok: None, syntax_set: SyntaxSet::load_defaults_newlines(), } } } impl<'a, I> Iterator for SyntectEvent<I> where I: Iterator<Item = Event<'a>>, { type Item = Event<'a>; fn next(&mut self) -> Option<Self::Item> { match self.inner.next() { None => None, Some(ev) => match ev { Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(ref tok))) => { self.tok = Some(tok.to_string()); Some(ev) // self.next() // TODO check that, it's fishy, used to strip the <code> block } Event::Text(ref content) => { if let Some(tok) = &self.tok { let ts = ThemeSet::load_defaults(); let theme = &ts.themes["Solarized (light)"]; let s = self .syntax_set .find_syntax_by_token(&tok) .unwrap_or_else(|| self.syntax_set.find_syntax_plain_text()); eprintln!("syntax found: {}", s.name); match highlighted_html_for_string(content, &self.syntax_set, &s, &theme) { Ok(res) => Some(Event::Html(res.into())), Err(err) => { eprintln!("error during html conversion: {:?}", err); Some(ev) } } } else { Some(ev) } } Event::End(Tag::CodeBlock(CodeBlockKind::Fenced(_))) => { self.tok = None; Some(ev) } _ => Some(ev), }, } } } fn main() -> BoxResult<()> { let fmt = time::format_description::parse("[year]-[month]-[day]")?; let t = time::Date::parse("2022-08-01-coucou", &fmt)?; println!("{}", t.format(&fmt)?); return Ok(()); let raws = fs::read_dir("./blog/posts/")? .into_iter() .map(|d| d.and_then(|d| fs::read_to_string(d.path()))) .collect::<Result<Vec<_>, _>>()?; let posts: Vec<Post> = raws // .map(|d| d.and_then(|d| fs::read_to_string(d.path()).map_err(|e| // Box::new(e) as Box<dyn Error> // ))) .iter() .map(|s| Post::from_str(s)) .collect::<BoxResult<Vec<_>>>()?; // let posts2: Vec<Post> = fs::read_dir("./blog/posts/")? // .into_iter() // .map(|d| { // d.and_then(|d| fs::read_to_string(d.path())) // .map_err(|e| Box::new(e) as Box<dyn Error>) // .as_ref().map(|x| Post::from_str(x).unwrap()) // .map_err(|e| todo!()) // }) // .collect::<BoxResult<Vec<_>>>()?; let blah = vec![fs::read_to_string( "./blog/posts/2020-03-31-quick-static-hosting.md", )?]; let _p = blah .iter() .map(|s| Post::from_str(s).unwrap()) .collect::<Vec<_>>(); let raw = include_str!("test.md"); let post = Post::from_str(raw)?; let parser = Parser::new(post.raw_content); // let ts = ThemeSet::load_defaults(); // let ss = SyntaxSet::load_defaults_newlines(); // let theme = &ts.themes["Solarized (light)"]; // for event in &parser { // println!("{:?}", event); // // if let Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(tok))) = event { // // println!("!!!!!!!!!!!!!! got a token {tok:?}"); // // let syn = ss.find_syntax_by_token(&tok).as_ref().map(|x| &*x.name); // // println!("syntax? {:?}", syn); // // } // } let events = SyntectEvent::new(parser); let mut html_output = String::new(); html::push_html(&mut html_output, events); println!("{}", html_output); // println!("title: {}", post.title); // println!("tags: {:?}", post.tags); // println!("status: {:?}", post.status); // for sr in ss.syntaxes() { // println!("{} - {:?}", sr.name, sr.file_extensions); // } // let ts = ThemeSet::load_defaults(); // let theme = &ts.themes["Solarized (light)"]; // let html = highlighted_html_for_file("src/bin/geekingfrog.rs", &ss, theme).unwrap(); // println!("{}", html); Ok(()) } // //**************************************** // // Axum test // //**************************************** // use axum::{ // extract::{ // ws::{Message, WebSocket}, // State, WebSocketUpgrade, // }, // http::StatusCode, // response::{Html, IntoResponse, Response}, // routing::{get, get_service}, // BoxError, Router, // }; // use notify::{watcher, RecursiveMode, Watcher, raw_watcher}; // use parking_lot::RwLock; // use std::{ // net::SocketAddr, // sync::{mpsc, Arc}, // time::Duration, // }; // use tera::Tera; // use tokio::sync::watch::{self, Receiver, Sender}; // use tower::ServiceBuilder; // use tower_http::{services::ServeDir, trace::TraceLayer}; // // #[derive(Clone)] // struct AppState { // template: Arc<RwLock<Tera>>, // refresh_chan: Receiver<()>, // } // // #[tokio::main] // async fn main() -> Result<(), BoxError> { // tracing_subscriber::fmt::init(); // // let tera = Arc::new(RwLock::new( // Tera::new("templates/**/*.html").expect("can get tera"), // )); // let (refresh_tx, refresh_rx) = watch::channel(()); // // // force a new value from the initial one so that calling rx.watch // // is sure to return something. // refresh_tx.send(())?; // // let app_state = AppState { // template: tera.clone(), // refresh_chan: refresh_rx, // }; // // let service = ServiceBuilder::new().layer(TraceLayer::new_for_http()); // // .layer(ServeDir::new("templates")); // // let app = Router::with_state(app_state) // .layer(service) // .route("/", get(root)) // .route("/ws/autorefresh", get(autorefresh_handler)) // .nest( // "/static", // get_service(ServeDir::new("static")).handle_error(|err: std::io::Error| async move { // tracing::info!("Error serving static staff: {err:?}"); // (StatusCode::INTERNAL_SERVER_ERROR, format!("{err:?}")) // }), // ); // // let addr = SocketAddr::from(([127, 0, 0, 1], 8888)); // // tokio::try_join!( // async { // tokio::task::spawn_blocking(move || watch_templates_change(tera, refresh_tx)).await? // }, // async { // tracing::debug!("Listening on {addr}"); // axum::Server::bind(&addr) // .serve(app.into_make_service()) // .await?; // Ok(()) // } // )?; // // Ok(()) // } // // async fn root(State(state): State<AppState>) -> Result<Html<String>, AppError> { // Ok(state // .template // .read() // .render("index.html", &tera::Context::new())? // .into()) // } // // async fn autorefresh_handler( // ws: WebSocketUpgrade, // State(state): State<AppState>, // ) -> impl IntoResponse { // tracing::debug!("got a websocket upgrade request"); // ws.on_upgrade(|socket| handle_socket(socket, state.refresh_chan)) // } // // async fn handle_socket(mut socket: WebSocket, mut refresh_tx: Receiver<()>) { // // There's this weird problem, if a watched file has changed at some point // // there will be a new value on the refresh_rx channel, and calling // // `changed` on it will return immediately, even if the change has happened // // before this call. So always ignore the first change on the channel. // // The sender will always send a new value after channel creation to avoid // // a different behavior between pages loaded before and after a change // // to a watched file. // let mut has_seen_one_change = false; // loop { // tokio::select! { // x = refresh_tx.changed() => { // tracing::debug!("refresh event!"); // if !has_seen_one_change { // has_seen_one_change = true; // continue // } // // match x { // Ok(_) => if socket.send(Message::Text("refresh".to_string())).await.is_err() { // tracing::debug!("cannot send stuff, socket probably disconnected"); // break; // }, // Err(err) => { // tracing::error!("Cannot read refresh chan??? {err:?}"); // break // }, // } // } // msg = socket.recv() => { // match msg { // Some(_) => { // tracing::debug!("received a websocket message, don't care"); // }, // None => { // tracing::debug!("websocket disconnected"); // break // }, // } // } // else => break // } // } // } // // #[derive(thiserror::Error, Debug)] // enum AppError { // #[error("Template error")] // TemplateError(#[from] tera::Error), // } // // impl IntoResponse for AppError { // fn into_response(self) -> Response { // let res = match self { // AppError::TemplateError(err) => ( // StatusCode::INTERNAL_SERVER_ERROR, // format!("Templating error: {err}"), // ), // }; // res.into_response() // } // } // // fn watch_templates_change(tera: Arc<RwLock<Tera>>, refresh_tx: Sender<()>) -> Result<(), BoxError> { // let (tx, rx) = std::sync::mpsc::channel(); // let rx = Debounced { // rx, // d: Duration::from_millis(300), // }; // // // the default watcher is debounced, but will always send the first event // // emmediately, and then debounce any further events. But that means a regular // // update actually triggers many events, which are debounced to 2 events. // // So use the raw_watcher and manually debounce // let mut watcher = raw_watcher(tx)?; // watcher.watch("templates", RecursiveMode::Recursive)?; // loop { // match rx.recv() { // Ok(ev) => { // tracing::info!("debounced event {ev:?}"); // tera.write().full_reload()?; // refresh_tx.send(())?; // } // Err(_timeout_error) => (), // } // } // } // // /// wrap a Receiver<T> such that if many T are received between the given Duration // /// then only the latest one will be kept and returned when calling recv // struct Debounced<T> { // rx: mpsc::Receiver<T>, // d: Duration, // } // // impl<T> Debounced<T> { // fn recv(&self) -> Result<T, mpsc::RecvError> { // let mut prev = None; // // loop { // match prev { // Some(v) => match self.rx.recv_timeout(self.d) { // Ok(newval) => { // prev = Some(newval); // continue; // } // Err(_) => break Ok(v), // }, // None => match self.rx.recv() { // Ok(val) => { // prev = Some(val); // continue; // } // Err(err) => break Err(err), // }, // } // } // } // }
post_status
identifier_name
sync.rs
//! This module supports synchronizing a UPM database with a copy on a remote repository. The //! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and //! "delete" primitives of the UPM sync protocol. use reqwest::multipart; use std::io::Read; use std::path::{Path, PathBuf}; use std::str; use std::time::Duration; use backup; use database::Database; use error::UpmError; /// The UPM sync protocol's delete command. This is appended to the repository URL. const DELETE_CMD: &'static str = "deletefile.php"; /// The UPM sync protocol's upload command. This is appended to the repository URL. const UPLOAD_CMD: &'static str = "upload.php"; /// This field name is used for the database file when uploading. const UPM_UPLOAD_FIELD_NAME: &'static str = "userfile"; /// Abort the operation if the server doesn't respond for this time interval. const TIMEOUT_SECS: u64 = 10; /// The UPM sync protocol returns an HTTP body of "OK" if the request was successful, otherwise it /// returns one of these error codes: FILE_DOESNT_EXIST, FILE_WASNT_DELETED, FILE_ALREADY_EXISTS, /// FILE_WASNT_MOVED, FILE_WASNT_UPLOADED const UPM_SUCCESS: &'static str = "OK"; /// UPM sync protocol responses should never be longer than this size. const UPM_MAX_RESPONSE_CODE_LENGTH: usize = 64; /// The MIME type used when uploading a database. const DATABASE_MIME_TYPE: &'static str = "application/octet-stream"; impl From<reqwest::Error> for UpmError { /// Convert a reqwest error into a `UpmError`. fn from(err: reqwest::Error) -> UpmError { UpmError::Sync(format!("{}", err)) } } /// A successful sync will result in one of these three conditions. pub enum SyncResult { /// The remote repository's copy of the database was replaced with the local copy. RemoteSynced, /// The local database was replaced with the remote repository's copy. LocalSynced, /// Neither the local database nor the remote database was changed, since they were both the /// same revision. NeitherSynced, } /// Provide basic access to the remote repository. struct Repository { url: String, http_username: String, http_password: String, client: reqwest::Client, } impl Repository { /// Create a new `Repository` struct with the provided URL and credentials. fn new(url: &str, http_username: &str, http_password: &str) -> Result<Repository, UpmError> { // Create a new reqwest client. let client = reqwest::Client::builder() .timeout(Duration::from_secs(TIMEOUT_SECS)) .build()?; Ok(Repository { url: String::from(url), http_username: String::from(http_username), http_password: String::from(http_password), client, }) } // // Provide the three operations of the UPM sync protocol: // Download, delete, and upload. // /// Download the remote database with the provided name. The database is returned in raw form /// as a byte buffer. fn download(&mut self, database_name: &str) -> Result<Vec<u8>, UpmError> { let url = self.make_url(database_name); // Send request let mut response = self .client .get(&url) .basic_auth(self.http_username.clone(), Some(self.http_password.clone())) .send()?; // Process response if !response.status().is_success() { return match response.status() { reqwest::StatusCode::NOT_FOUND => Err(UpmError::SyncDatabaseNotFound), _ => Err(UpmError::Sync(format!("{}", response.status()))), }; } let mut data: Vec<u8> = Vec::new(); response.read_to_end(&mut data)?; Ok(data) } /// Delete the specified database from the remote repository. fn delete(&mut self, database_name: &str) -> Result<(), UpmError> { let url = self.make_url(DELETE_CMD); // Send request let mut response = self .client .post(&url) .basic_auth(self.http_username.clone(), Some(self.http_password.clone())) .form(&[("fileToDelete", database_name)]) .send()?;
self.check_response(&mut response)?; Ok(()) } /// Upload the provided database to the remote repository. The database is provided in raw /// form as a byte buffer. fn upload(&mut self, database_name: &str, database_bytes: Vec<u8>) -> Result<(), UpmError> { let url: String = self.make_url(UPLOAD_CMD); // Thanks to Sean (seanmonstar) for helping to translate this code to multipart code // of reqwest let part = multipart::Part::bytes(database_bytes.clone()) .file_name(database_name.to_string()) .mime_str(DATABASE_MIME_TYPE)?; let form = multipart::Form::new().part(UPM_UPLOAD_FIELD_NAME, part); // Send request let mut response = self.client.post(&url).multipart(form).send()?; // Process response self.check_response(&mut response)?; Ok(()) } /// Construct a URL by appending the provided string to the repository URL, adding a separating /// slash character if needed. fn make_url(&self, path_component: &str) -> String { if self.url.ends_with('/') { format!("{}{}", self.url, path_component) } else { format!("{}/{}", self.url, path_component) } } /// Confirm that the HTTP response was successful and valid. fn check_response(&self, response: &mut reqwest::Response) -> Result<(), UpmError> { if !response.status().is_success() { return Err(UpmError::Sync(format!("{}", response.status()))); } let mut response_code = String::new(); response.read_to_string(&mut response_code)?; if response_code.len() > UPM_MAX_RESPONSE_CODE_LENGTH { return Err(UpmError::Sync(format!( "Unexpected response from server ({} bytes)", response_code.len() ))); } if response_code != UPM_SUCCESS { return Err(UpmError::Sync(format!("Server error: {}", response_code))); } Ok(()) } } /// Download a database from the remote repository without performing any sync operation with a /// local database. This is useful when downloading an existing remote database for the first /// time. pub fn download<P: AsRef<Path>>( repo_url: &str, repo_username: &str, repo_password: &str, database_filename: P, ) -> Result<Vec<u8>, UpmError> { let mut repo = Repository::new(repo_url, repo_username, repo_password)?; let name = Database::path_to_name(&database_filename)?; repo.download(&name) } /// Synchronize the local and remote databases using the UPM sync protocol. If an optional remote /// password is provided, it will be used when decrypting the remote database; otherwise, the /// password of the local database will be used. Return true if the caller needs to reload the /// local database. /// /// The sync logic is as follows: /// /// 1. Download the current remote database from the provided URL. /// - Attempt to decrypt this database with the master password. /// - If decryption fails, return /// [`UpmError::BadPassword`](../error/enum.UpmError.html#variant.BadPassword). (The caller /// may wish to prompt the user for the remote password, then try again.) /// 2. Take action based on the revisions of the local and remote database: /// - If the local revision is greater than the remote revision, upload the local database to /// the remote repository (overwriting the pre-existing remote database). /// - If the local revision is less than the remote revision, replace the local database with /// the remote database (overwriting the pre-existing local database). /// - If the local revision is the same as the remote revision, then do nothing. /// 3. The caller may wish to mimic the behavior of the UPM Java application by considering the /// local database to be dirty if it has not been synced in 5 minutes. /// /// NOTE: It is theoretically possible for two UPM clients to revision the database separately /// before syncing, and result in a situation where one will "win" and the other will have its /// changes silently lost. The caller should exercise the appropriate level of paranoia to /// mitigate this risk. For example, prompting for sync before the user begins making a /// modification, and marking the database as dirty after 5 minutes. pub fn sync(database: &Database, remote_password: Option<&str>) -> Result<SyncResult, UpmError> { // Collect all the facts. if database.sync_url.is_empty() { return Err(UpmError::NoSyncURL); } if database.sync_credentials.is_empty() { return Err(UpmError::NoSyncCredentials); } let sync_account = match database.account(&database.sync_credentials) { Some(a) => a, None => return Err(UpmError::NoSyncCredentials), }; let database_filename = match database.path() { Some(f) => f, None => return Err(UpmError::NoDatabaseFilename), }; let database_name = match database.name() { Some(n) => n, None => return Err(UpmError::NoDatabaseFilename), }; let local_password = match database.password() { Some(p) => p, None => return Err(UpmError::NoDatabasePassword), }; let remote_password = match remote_password { Some(p) => p, None => local_password, }; // 1. Download the remote database. // If the remote database has a different password than the local // database, we will return UpmError::BadPassword and the caller can // prompt the user for the remote password, and call this function // again with Some(remote_password). let mut repo = Repository::new( &database.sync_url, &sync_account.user, &sync_account.password, )?; let remote_exists; let mut remote_database = match repo.download(database_name) { Ok(bytes) => { remote_exists = true; Database::load_from_bytes(&bytes, remote_password)? } Err(UpmError::SyncDatabaseNotFound) => { // No remote database with that name exists, so this must be a fresh sync. // We'll use a stub database with revision 0. remote_exists = false; Database::new() } Err(e) => return Err(e), }; // 2. Copy databases as needed. if database.sync_revision > remote_database.sync_revision { // Copy the local database to the remote. // First, upload a backup copy in case something goes wrong between delete() and upload(). if super::PARANOID_BACKUPS { let backup_database_path = backup::generate_backup_filename(&PathBuf::from(database_name))?; let backup_database_name = backup_database_path.to_str(); if let Some(backup_database_name) = backup_database_name { repo.upload( backup_database_name, database.save_to_bytes(remote_password)?, )?; } } // Delete the existing remote database, if it exists. if remote_exists { repo.delete(&database_name)?; } // Upload the local database to the remote. Make sure to re-encrypt with the local // password, in case it has been changed recently. repo.upload(database_name, database.save_to_bytes(local_password)?)?; Ok(SyncResult::RemoteSynced) } else if database.sync_revision < remote_database.sync_revision { // Replace the local database with the remote database remote_database.set_path(&database_filename)?; remote_database.save()?; // The caller should reload the local database when it receives this result. Ok(SyncResult::LocalSynced) } else { // Revisions are the same -- do nothing. Ok(SyncResult::NeitherSynced) } }
// Process response
random_line_split
sync.rs
//! This module supports synchronizing a UPM database with a copy on a remote repository. The //! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and //! "delete" primitives of the UPM sync protocol. use reqwest::multipart; use std::io::Read; use std::path::{Path, PathBuf}; use std::str; use std::time::Duration; use backup; use database::Database; use error::UpmError; /// The UPM sync protocol's delete command. This is appended to the repository URL. const DELETE_CMD: &'static str = "deletefile.php"; /// The UPM sync protocol's upload command. This is appended to the repository URL. const UPLOAD_CMD: &'static str = "upload.php"; /// This field name is used for the database file when uploading. const UPM_UPLOAD_FIELD_NAME: &'static str = "userfile"; /// Abort the operation if the server doesn't respond for this time interval. const TIMEOUT_SECS: u64 = 10; /// The UPM sync protocol returns an HTTP body of "OK" if the request was successful, otherwise it /// returns one of these error codes: FILE_DOESNT_EXIST, FILE_WASNT_DELETED, FILE_ALREADY_EXISTS, /// FILE_WASNT_MOVED, FILE_WASNT_UPLOADED const UPM_SUCCESS: &'static str = "OK"; /// UPM sync protocol responses should never be longer than this size. const UPM_MAX_RESPONSE_CODE_LENGTH: usize = 64; /// The MIME type used when uploading a database. const DATABASE_MIME_TYPE: &'static str = "application/octet-stream"; impl From<reqwest::Error> for UpmError { /// Convert a reqwest error into a `UpmError`. fn from(err: reqwest::Error) -> UpmError { UpmError::Sync(format!("{}", err)) } } /// A successful sync will result in one of these three conditions. pub enum SyncResult { /// The remote repository's copy of the database was replaced with the local copy. RemoteSynced, /// The local database was replaced with the remote repository's copy. LocalSynced, /// Neither the local database nor the remote database was changed, since they were both the /// same revision. NeitherSynced, } /// Provide basic access to the remote repository. struct Repository { url: String, http_username: String, http_password: String, client: reqwest::Client, } impl Repository { /// Create a new `Repository` struct with the provided URL and credentials. fn new(url: &str, http_username: &str, http_password: &str) -> Result<Repository, UpmError> { // Create a new reqwest client. let client = reqwest::Client::builder() .timeout(Duration::from_secs(TIMEOUT_SECS)) .build()?; Ok(Repository { url: String::from(url), http_username: String::from(http_username), http_password: String::from(http_password), client, }) } // // Provide the three operations of the UPM sync protocol: // Download, delete, and upload. // /// Download the remote database with the provided name. The database is returned in raw form /// as a byte buffer. fn download(&mut self, database_name: &str) -> Result<Vec<u8>, UpmError> { let url = self.make_url(database_name); // Send request let mut response = self .client .get(&url) .basic_auth(self.http_username.clone(), Some(self.http_password.clone())) .send()?; // Process response if !response.status().is_success() { return match response.status() { reqwest::StatusCode::NOT_FOUND => Err(UpmError::SyncDatabaseNotFound), _ => Err(UpmError::Sync(format!("{}", response.status()))), }; } let mut data: Vec<u8> = Vec::new(); response.read_to_end(&mut data)?; Ok(data) } /// Delete the specified database from the remote repository. fn delete(&mut self, database_name: &str) -> Result<(), UpmError> { let url = self.make_url(DELETE_CMD); // Send request let mut response = self .client .post(&url) .basic_auth(self.http_username.clone(), Some(self.http_password.clone())) .form(&[("fileToDelete", database_name)]) .send()?; // Process response self.check_response(&mut response)?; Ok(()) } /// Upload the provided database to the remote repository. The database is provided in raw /// form as a byte buffer. fn upload(&mut self, database_name: &str, database_bytes: Vec<u8>) -> Result<(), UpmError> { let url: String = self.make_url(UPLOAD_CMD); // Thanks to Sean (seanmonstar) for helping to translate this code to multipart code // of reqwest let part = multipart::Part::bytes(database_bytes.clone()) .file_name(database_name.to_string()) .mime_str(DATABASE_MIME_TYPE)?; let form = multipart::Form::new().part(UPM_UPLOAD_FIELD_NAME, part); // Send request let mut response = self.client.post(&url).multipart(form).send()?; // Process response self.check_response(&mut response)?; Ok(()) } /// Construct a URL by appending the provided string to the repository URL, adding a separating /// slash character if needed. fn make_url(&self, path_component: &str) -> String { if self.url.ends_with('/') { format!("{}{}", self.url, path_component) } else { format!("{}/{}", self.url, path_component) } } /// Confirm that the HTTP response was successful and valid. fn
(&self, response: &mut reqwest::Response) -> Result<(), UpmError> { if !response.status().is_success() { return Err(UpmError::Sync(format!("{}", response.status()))); } let mut response_code = String::new(); response.read_to_string(&mut response_code)?; if response_code.len() > UPM_MAX_RESPONSE_CODE_LENGTH { return Err(UpmError::Sync(format!( "Unexpected response from server ({} bytes)", response_code.len() ))); } if response_code != UPM_SUCCESS { return Err(UpmError::Sync(format!("Server error: {}", response_code))); } Ok(()) } } /// Download a database from the remote repository without performing any sync operation with a /// local database. This is useful when downloading an existing remote database for the first /// time. pub fn download<P: AsRef<Path>>( repo_url: &str, repo_username: &str, repo_password: &str, database_filename: P, ) -> Result<Vec<u8>, UpmError> { let mut repo = Repository::new(repo_url, repo_username, repo_password)?; let name = Database::path_to_name(&database_filename)?; repo.download(&name) } /// Synchronize the local and remote databases using the UPM sync protocol. If an optional remote /// password is provided, it will be used when decrypting the remote database; otherwise, the /// password of the local database will be used. Return true if the caller needs to reload the /// local database. /// /// The sync logic is as follows: /// /// 1. Download the current remote database from the provided URL. /// - Attempt to decrypt this database with the master password. /// - If decryption fails, return /// [`UpmError::BadPassword`](../error/enum.UpmError.html#variant.BadPassword). (The caller /// may wish to prompt the user for the remote password, then try again.) /// 2. Take action based on the revisions of the local and remote database: /// - If the local revision is greater than the remote revision, upload the local database to /// the remote repository (overwriting the pre-existing remote database). /// - If the local revision is less than the remote revision, replace the local database with /// the remote database (overwriting the pre-existing local database). /// - If the local revision is the same as the remote revision, then do nothing. /// 3. The caller may wish to mimic the behavior of the UPM Java application by considering the /// local database to be dirty if it has not been synced in 5 minutes. /// /// NOTE: It is theoretically possible for two UPM clients to revision the database separately /// before syncing, and result in a situation where one will "win" and the other will have its /// changes silently lost. The caller should exercise the appropriate level of paranoia to /// mitigate this risk. For example, prompting for sync before the user begins making a /// modification, and marking the database as dirty after 5 minutes. pub fn sync(database: &Database, remote_password: Option<&str>) -> Result<SyncResult, UpmError> { // Collect all the facts. if database.sync_url.is_empty() { return Err(UpmError::NoSyncURL); } if database.sync_credentials.is_empty() { return Err(UpmError::NoSyncCredentials); } let sync_account = match database.account(&database.sync_credentials) { Some(a) => a, None => return Err(UpmError::NoSyncCredentials), }; let database_filename = match database.path() { Some(f) => f, None => return Err(UpmError::NoDatabaseFilename), }; let database_name = match database.name() { Some(n) => n, None => return Err(UpmError::NoDatabaseFilename), }; let local_password = match database.password() { Some(p) => p, None => return Err(UpmError::NoDatabasePassword), }; let remote_password = match remote_password { Some(p) => p, None => local_password, }; // 1. Download the remote database. // If the remote database has a different password than the local // database, we will return UpmError::BadPassword and the caller can // prompt the user for the remote password, and call this function // again with Some(remote_password). let mut repo = Repository::new( &database.sync_url, &sync_account.user, &sync_account.password, )?; let remote_exists; let mut remote_database = match repo.download(database_name) { Ok(bytes) => { remote_exists = true; Database::load_from_bytes(&bytes, remote_password)? } Err(UpmError::SyncDatabaseNotFound) => { // No remote database with that name exists, so this must be a fresh sync. // We'll use a stub database with revision 0. remote_exists = false; Database::new() } Err(e) => return Err(e), }; // 2. Copy databases as needed. if database.sync_revision > remote_database.sync_revision { // Copy the local database to the remote. // First, upload a backup copy in case something goes wrong between delete() and upload(). if super::PARANOID_BACKUPS { let backup_database_path = backup::generate_backup_filename(&PathBuf::from(database_name))?; let backup_database_name = backup_database_path.to_str(); if let Some(backup_database_name) = backup_database_name { repo.upload( backup_database_name, database.save_to_bytes(remote_password)?, )?; } } // Delete the existing remote database, if it exists. if remote_exists { repo.delete(&database_name)?; } // Upload the local database to the remote. Make sure to re-encrypt with the local // password, in case it has been changed recently. repo.upload(database_name, database.save_to_bytes(local_password)?)?; Ok(SyncResult::RemoteSynced) } else if database.sync_revision < remote_database.sync_revision { // Replace the local database with the remote database remote_database.set_path(&database_filename)?; remote_database.save()?; // The caller should reload the local database when it receives this result. Ok(SyncResult::LocalSynced) } else { // Revisions are the same -- do nothing. Ok(SyncResult::NeitherSynced) } }
check_response
identifier_name
sync.rs
//! This module supports synchronizing a UPM database with a copy on a remote repository. The //! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and //! "delete" primitives of the UPM sync protocol. use reqwest::multipart; use std::io::Read; use std::path::{Path, PathBuf}; use std::str; use std::time::Duration; use backup; use database::Database; use error::UpmError; /// The UPM sync protocol's delete command. This is appended to the repository URL. const DELETE_CMD: &'static str = "deletefile.php"; /// The UPM sync protocol's upload command. This is appended to the repository URL. const UPLOAD_CMD: &'static str = "upload.php"; /// This field name is used for the database file when uploading. const UPM_UPLOAD_FIELD_NAME: &'static str = "userfile"; /// Abort the operation if the server doesn't respond for this time interval. const TIMEOUT_SECS: u64 = 10; /// The UPM sync protocol returns an HTTP body of "OK" if the request was successful, otherwise it /// returns one of these error codes: FILE_DOESNT_EXIST, FILE_WASNT_DELETED, FILE_ALREADY_EXISTS, /// FILE_WASNT_MOVED, FILE_WASNT_UPLOADED const UPM_SUCCESS: &'static str = "OK"; /// UPM sync protocol responses should never be longer than this size. const UPM_MAX_RESPONSE_CODE_LENGTH: usize = 64; /// The MIME type used when uploading a database. const DATABASE_MIME_TYPE: &'static str = "application/octet-stream"; impl From<reqwest::Error> for UpmError { /// Convert a reqwest error into a `UpmError`. fn from(err: reqwest::Error) -> UpmError { UpmError::Sync(format!("{}", err)) } } /// A successful sync will result in one of these three conditions. pub enum SyncResult { /// The remote repository's copy of the database was replaced with the local copy. RemoteSynced, /// The local database was replaced with the remote repository's copy. LocalSynced, /// Neither the local database nor the remote database was changed, since they were both the /// same revision. NeitherSynced, } /// Provide basic access to the remote repository. struct Repository { url: String, http_username: String, http_password: String, client: reqwest::Client, } impl Repository { /// Create a new `Repository` struct with the provided URL and credentials. fn new(url: &str, http_username: &str, http_password: &str) -> Result<Repository, UpmError> { // Create a new reqwest client. let client = reqwest::Client::builder() .timeout(Duration::from_secs(TIMEOUT_SECS)) .build()?; Ok(Repository { url: String::from(url), http_username: String::from(http_username), http_password: String::from(http_password), client, }) } // // Provide the three operations of the UPM sync protocol: // Download, delete, and upload. // /// Download the remote database with the provided name. The database is returned in raw form /// as a byte buffer. fn download(&mut self, database_name: &str) -> Result<Vec<u8>, UpmError> { let url = self.make_url(database_name); // Send request let mut response = self .client .get(&url) .basic_auth(self.http_username.clone(), Some(self.http_password.clone())) .send()?; // Process response if !response.status().is_success() { return match response.status() { reqwest::StatusCode::NOT_FOUND => Err(UpmError::SyncDatabaseNotFound), _ => Err(UpmError::Sync(format!("{}", response.status()))), }; } let mut data: Vec<u8> = Vec::new(); response.read_to_end(&mut data)?; Ok(data) } /// Delete the specified database from the remote repository. fn delete(&mut self, database_name: &str) -> Result<(), UpmError> { let url = self.make_url(DELETE_CMD); // Send request let mut response = self .client .post(&url) .basic_auth(self.http_username.clone(), Some(self.http_password.clone())) .form(&[("fileToDelete", database_name)]) .send()?; // Process response self.check_response(&mut response)?; Ok(()) } /// Upload the provided database to the remote repository. The database is provided in raw /// form as a byte buffer. fn upload(&mut self, database_name: &str, database_bytes: Vec<u8>) -> Result<(), UpmError> { let url: String = self.make_url(UPLOAD_CMD); // Thanks to Sean (seanmonstar) for helping to translate this code to multipart code // of reqwest let part = multipart::Part::bytes(database_bytes.clone()) .file_name(database_name.to_string()) .mime_str(DATABASE_MIME_TYPE)?; let form = multipart::Form::new().part(UPM_UPLOAD_FIELD_NAME, part); // Send request let mut response = self.client.post(&url).multipart(form).send()?; // Process response self.check_response(&mut response)?; Ok(()) } /// Construct a URL by appending the provided string to the repository URL, adding a separating /// slash character if needed. fn make_url(&self, path_component: &str) -> String { if self.url.ends_with('/') { format!("{}{}", self.url, path_component) } else { format!("{}/{}", self.url, path_component) } } /// Confirm that the HTTP response was successful and valid. fn check_response(&self, response: &mut reqwest::Response) -> Result<(), UpmError> { if !response.status().is_success() { return Err(UpmError::Sync(format!("{}", response.status()))); } let mut response_code = String::new(); response.read_to_string(&mut response_code)?; if response_code.len() > UPM_MAX_RESPONSE_CODE_LENGTH { return Err(UpmError::Sync(format!( "Unexpected response from server ({} bytes)", response_code.len() ))); } if response_code != UPM_SUCCESS { return Err(UpmError::Sync(format!("Server error: {}", response_code))); } Ok(()) } } /// Download a database from the remote repository without performing any sync operation with a /// local database. This is useful when downloading an existing remote database for the first /// time. pub fn download<P: AsRef<Path>>( repo_url: &str, repo_username: &str, repo_password: &str, database_filename: P, ) -> Result<Vec<u8>, UpmError> { let mut repo = Repository::new(repo_url, repo_username, repo_password)?; let name = Database::path_to_name(&database_filename)?; repo.download(&name) } /// Synchronize the local and remote databases using the UPM sync protocol. If an optional remote /// password is provided, it will be used when decrypting the remote database; otherwise, the /// password of the local database will be used. Return true if the caller needs to reload the /// local database. /// /// The sync logic is as follows: /// /// 1. Download the current remote database from the provided URL. /// - Attempt to decrypt this database with the master password. /// - If decryption fails, return /// [`UpmError::BadPassword`](../error/enum.UpmError.html#variant.BadPassword). (The caller /// may wish to prompt the user for the remote password, then try again.) /// 2. Take action based on the revisions of the local and remote database: /// - If the local revision is greater than the remote revision, upload the local database to /// the remote repository (overwriting the pre-existing remote database). /// - If the local revision is less than the remote revision, replace the local database with /// the remote database (overwriting the pre-existing local database). /// - If the local revision is the same as the remote revision, then do nothing. /// 3. The caller may wish to mimic the behavior of the UPM Java application by considering the /// local database to be dirty if it has not been synced in 5 minutes. /// /// NOTE: It is theoretically possible for two UPM clients to revision the database separately /// before syncing, and result in a situation where one will "win" and the other will have its /// changes silently lost. The caller should exercise the appropriate level of paranoia to /// mitigate this risk. For example, prompting for sync before the user begins making a /// modification, and marking the database as dirty after 5 minutes. pub fn sync(database: &Database, remote_password: Option<&str>) -> Result<SyncResult, UpmError>
{ // Collect all the facts. if database.sync_url.is_empty() { return Err(UpmError::NoSyncURL); } if database.sync_credentials.is_empty() { return Err(UpmError::NoSyncCredentials); } let sync_account = match database.account(&database.sync_credentials) { Some(a) => a, None => return Err(UpmError::NoSyncCredentials), }; let database_filename = match database.path() { Some(f) => f, None => return Err(UpmError::NoDatabaseFilename), }; let database_name = match database.name() { Some(n) => n, None => return Err(UpmError::NoDatabaseFilename), }; let local_password = match database.password() { Some(p) => p, None => return Err(UpmError::NoDatabasePassword), }; let remote_password = match remote_password { Some(p) => p, None => local_password, }; // 1. Download the remote database. // If the remote database has a different password than the local // database, we will return UpmError::BadPassword and the caller can // prompt the user for the remote password, and call this function // again with Some(remote_password). let mut repo = Repository::new( &database.sync_url, &sync_account.user, &sync_account.password, )?; let remote_exists; let mut remote_database = match repo.download(database_name) { Ok(bytes) => { remote_exists = true; Database::load_from_bytes(&bytes, remote_password)? } Err(UpmError::SyncDatabaseNotFound) => { // No remote database with that name exists, so this must be a fresh sync. // We'll use a stub database with revision 0. remote_exists = false; Database::new() } Err(e) => return Err(e), }; // 2. Copy databases as needed. if database.sync_revision > remote_database.sync_revision { // Copy the local database to the remote. // First, upload a backup copy in case something goes wrong between delete() and upload(). if super::PARANOID_BACKUPS { let backup_database_path = backup::generate_backup_filename(&PathBuf::from(database_name))?; let backup_database_name = backup_database_path.to_str(); if let Some(backup_database_name) = backup_database_name { repo.upload( backup_database_name, database.save_to_bytes(remote_password)?, )?; } } // Delete the existing remote database, if it exists. if remote_exists { repo.delete(&database_name)?; } // Upload the local database to the remote. Make sure to re-encrypt with the local // password, in case it has been changed recently. repo.upload(database_name, database.save_to_bytes(local_password)?)?; Ok(SyncResult::RemoteSynced) } else if database.sync_revision < remote_database.sync_revision { // Replace the local database with the remote database remote_database.set_path(&database_filename)?; remote_database.save()?; // The caller should reload the local database when it receives this result. Ok(SyncResult::LocalSynced) } else { // Revisions are the same -- do nothing. Ok(SyncResult::NeitherSynced) } }
identifier_body
de.py
import os import numpy as np import pandas as pd from scvi.dataset import GeneExpressionDataset from scvi.models import VAE from scvi.inference import UnsupervisedTrainer import torch import anndata import plotly.graph_objects as go import io import requests import urllib from io import StringIO import boto3 import datetime import sys from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail import datetime dt_started = datetime.datetime.utcnow() url = (sys.argv[1]) print(datetime.datetime.now()) print(' ### ### ### starting to process...') print(url) AWS_S3_ACCESS_KEY = (sys.argv[2]) AWS_S3_SECRET = (sys.argv[3]) sendgrid_key = (sys.argv[4]) sendgrid_name = (sys.argv[5]) save_path = "/home/ubuntu/" sys.stdout = open('log_file.txt', 'w') sys.stderr = sys.stdout # if True: try: vae_file_name = 'CPT_vae_cpu2.pkl' adata = anndata.read('./wormcells-data-2020-03-30.h5ad') adata.var = adata.var.reset_index() adata.var.index = adata.var['gene_id'] adata.var.index = adata.var.index.rename('index') gene_dataset = GeneExpressionDataset() # we provide the `batch_indices` so that scvi can perform batch correction gene_dataset.populate_from_data( adata.X, gene_names=adata.var.index.values, cell_types=adata.obs['cell_type'].values, batch_indices=adata.obs['experiment'].cat.codes.values, ) vae = VAE(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches) trainer = UnsupervisedTrainer( vae, gene_dataset, train_size=0.75, use_cuda=False, frequency=1, ) # LOAD full_file_save_path = os.path.join(save_path, vae_file_name) trainer.model.load_state_dict(torch.load(full_file_save_path)) trainer.model.eval() print(' ### ### ### loaded vae') print(datetime.datetime.now()) # n_epochs = 5 # lr = 0.001 # full_file_save_path = os.path.join(save_path, vae_file_name) # trainer.train(n_epochs=n_epochs, lr=lr) # torch.save(trainer.model.state_dict(), full_file_save_path) # train_test_results = pd.DataFrame(trainer.history).rename(columns={'elbo_train_set':'Train', 'elbo_test_set':'Test'}) # print(train_test_results) full = trainer.create_posterior(trainer.model, gene_dataset, indices=np.arange(len(gene_dataset))) latent, batch_indices, labels = full.sequential().get_latent() batch_indices = batch_indices.ravel() print(' ### ### ### computed full posterior') print(' ### ### ### url = ', url) # read submission csv and fetch selected cells submission = pd.read_csv(io.StringIO(requests.get(url).content.decode('utf-8')), index_col=0) selected_cells_csv_string = submission.to_csv(index=False).replace('\n', '<br>') # reconstruct user email from submission url email = url.split('https://scvi-differential-expression.s3.us-east-2.amazonaws.com/submissions/')[1] email = email.split('%25')[0] email = email.replace('%40', '@') # create masks for cell selection according to submission # start with all entries false cell_idx1 = adata.obs['cell_type'] == '000000' for _, entry in submission[['cell_type1', 'experiment1']].dropna().iterrows(): cell = entry['cell_type1'].strip() experiment = entry['experiment1'].strip() curr_boolean = (adata.obs['cell_type'] == cell) & (adata.obs['experiment'] == experiment) cell_idx1 = (cell_idx1 | curr_boolean) cell_idx2 = adata.obs['cell_type'] == '000000' for _, entry in submission[['cell_type2', 'experiment2']].dropna().iterrows(): cell = entry['cell_type2'].strip() experiment = entry['experiment2'].strip() curr_boolean = (adata.obs['cell_type'] == cell) & (adata.obs['experiment'] == experiment) cell_idx2 = (cell_idx2 | curr_boolean) print(' ### ### ### computed idxs') n_samples = 10000 M_permutation = 10000 de_change = full.differential_expression_score( idx1=cell_idx1.values, # we use the same cells as chosen before idx2=cell_idx2.values, mode='change', # set to the new change mode n_samples=n_samples, M_permutation=M_permutation, ) print(' ### ### ### finished DE!') print(datetime.datetime.now()) # manipulate the DE results for plotting # we use the `mean` entru in de_chage, it is the scVI posterior log2 fold change de_change['log10_pvalue'] = np.log10(de_change['proba_not_de']) # we take absolute values of the first bayes factor as the one to use on the volcano plot # bayes1 and bayes2 should be roughtly the same, except with opposite signs de_change['abs_bayes_factor'] = np.abs(de_change['bayes_factor']) de_change = de_change.join(adata.var, how='inner') # manipulate the DE results for plotting de = de_change.copy() de['gene_color'] = 'rgba(100, 100, 100, 0.2)' for gene in submission['selected_genes'].dropna().values: gene = gene.strip() de['gene_color'][de['gene_name'].str.contains(gene)] = 'rgba(0, 0,255, 1)' de['gene_color'][de['gene_id'].str.contains(gene)] = 'rgba(0, 0,255, 1)' de_result_csv = de[ ['proba_not_de', 'log10_pvalue', 'bayes_factor', 'lfc_mean', 'lfc_median', 'lfc_std', 'lfc_min', 'lfc_max', 'gene_id', 'gene_name', 'gene_description']] print(' ### ### ### Creating plot') try: jobname = submission['job_name'][0] except: jobname = ' ' de['gene_description_html'] = de['gene_description'].str.replace('\. ', '.<br>') string_bf_list = [str(bf) for bf in np.round(de['bayes_factor'].values, 3)] de['bayes_factor_string'] = string_bf_list fig = go.Figure( data=go.Scatter( x=de["lfc_mean"].round(3) , y=-de["log10_pvalue"].round(3) , mode='markers' , marker=dict(color=de['gene_color']) , hoverinfo='text' , text=de['gene_description_html'] , customdata=de.gene_name.astype(str) + '<br>' + de.gene_id.values + \ '<br>Bayes Factor: \t' + de.bayes_factor_string + \ '<br>-log10(p-value): \t' + de["log10_pvalue"].round(3).astype(str) + \ '<br>log2 FC mean: \t' + de["lfc_mean"].round(3).astype(str) + \ '<br>log2 FC median: \t' + de["lfc_median"].round(3).astype(str) + \ '<br>log2 FC std: \t' + de["lfc_std"].round(3).astype(str) , hovertemplate='%{customdata} <br><extra>%{text}</extra>' ) , layout={ "title": {"text": "Differential expression on C. elegans single cell data <br> " + jobname + " <br> <a href=" + url + ">" + url + '</a>' , 'x': 0.5 } , 'xaxis': {'title': {"text": "log2 fold change"}} , 'yaxis': {'title': {"text": "-log10(p-value)"}} } ) ### SAVE RESULTS AND SEND MAIL #### # construct the filename for saving the results filename = url.split('https://scvi-differential-expression.s3.us-east-2.amazonaws.com/submissions/')[1] filename = filename.replace('%40', '@') filename = filename.replace('%25', '@') filename = filename.replace('.csv', '') csv_buffer = StringIO() de_result_csv.to_csv(csv_buffer) csvfilename = 'csv/' + filename + '-results.csv' htmlfilename = 'plots/' + filename + '-results.html' print(' ### ### ### Putting files in s3...') client = boto3.client('s3', aws_access_key_id=AWS_S3_ACCESS_KEY, aws_secret_access_key=AWS_S3_SECRET ) client.put_object( Body=csv_buffer.getvalue(), Bucket='scvi-differential-expression', Key=csvfilename, ACL='public-read' ) html_buffer = StringIO() fig.write_html(html_buffer, auto_open=True) client.put_object( Body=html_buffer.getvalue(), Bucket='scvi-differential-expression', Key=htmlfilename, ACL='public-read' ) csv_url = 'https://scvi-differential-expression.s3.us-east-2.amazonaws.com/' + urllib.parse.quote(csvfilename) html_url = 'https://scvi-differential-expression.s3.us-east-2.amazonaws.com/' + urllib.parse.quote(htmlfilename) print(' ### ### ### Files uploaded successfully') dt_ended = datetime.datetime.utcnow() total_time = str(int((dt_ended - dt_started).total_seconds())) email_body = f' Your 🌋 wormcells-de 💥 C. elegans single cell differential expression results: <br> {jobname} <br><br> <a href="{csv_url}">CSV file with results</a> <br> <a href="{html_url}">Vocano plot</a> <br> <a href="{url}">Your cell selection</a> <br> Processing time: {total_time}s <br> <br> <br> Thanks <br> Eduardo' print(' ### ### ### Email created') message = Mail( from_email='eduardo@wormbase.org', to_emails=email, subject='C. elegans single cell differential expression results', html_content=email_body) sg = SendGridAPIClient(sendgrid_key) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) print(' ********************* Email sent ********************') print(' ****************** Total time (s):', end = ' ') print(total_time) print('Terminating... ') instance_id = requests.get("http://169.254.169.254/latest/meta-data/instance-id").text session = boto3.Session(region_name='us-east-2', aws_access_key_id=AWS_S3_ACCESS_KEY, aws_secret_access_key=AWS_S3_SECRET) ec2 = session.resource('ec2', region_name='us-east-2') ec2.instances.filter(InstanceIds=[instance_id]).terminate() # if False: except: print(' XXXXXXXXXXXXXXXX SOMETHING FAILED XXXXXXXXXXXXXXX') filename = url.split('https://scvi-differential-expression.s3.us-east-2.amazonaws.com/submissions/')[1] filename = filename.replace('%40', '@') filename = filename.replace('%25', '@')
logs = open('log_file.txt', 'r').read() logs_buffer = StringIO() logs_buffer.write(logs) csv_buffer = StringIO() logsfilename = 'logs/' + filename + '-logs.txt' print(' ### ### ### Putting log in s3...') client = boto3.client('s3', aws_access_key_id=AWS_S3_ACCESS_KEY, aws_secret_access_key=AWS_S3_SECRET ) client.put_object( Body=logs_buffer.getvalue(), Bucket='scvi-differential-expression', Key=logsfilename, ACL='public-read' ) print(' ### ### ### Log in s3. Sending email...') message = Mail( from_email='eduardo@wormbase.org', to_emails='veigabeltrame@gmail.com', subject='SOMETHING WENT WRONG!!!!111', html_content=logs) sg = SendGridAPIClient(sendgrid_key) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) print(' ### ### ### Email sent. Done.') # print('Terminating... ') # instance_id = requests.get("http://169.254.169.254/latest/meta-data/instance-id").text # # session = boto3.Session(region_name='us-east-2', # aws_access_key_id=AWS_S3_ACCESS_KEY, # aws_secret_access_key=AWS_S3_SECRET) # ec2 = session.resource('ec2', region_name='us-east-2') # ec2.instances.filter(InstanceIds = [instance_id]).terminate()
filename = filename.replace('.csv', '')
random_line_split
de.py
import os import numpy as np import pandas as pd from scvi.dataset import GeneExpressionDataset from scvi.models import VAE from scvi.inference import UnsupervisedTrainer import torch import anndata import plotly.graph_objects as go import io import requests import urllib from io import StringIO import boto3 import datetime import sys from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail import datetime dt_started = datetime.datetime.utcnow() url = (sys.argv[1]) print(datetime.datetime.now()) print(' ### ### ### starting to process...') print(url) AWS_S3_ACCESS_KEY = (sys.argv[2]) AWS_S3_SECRET = (sys.argv[3]) sendgrid_key = (sys.argv[4]) sendgrid_name = (sys.argv[5]) save_path = "/home/ubuntu/" sys.stdout = open('log_file.txt', 'w') sys.stderr = sys.stdout # if True: try: vae_file_name = 'CPT_vae_cpu2.pkl' adata = anndata.read('./wormcells-data-2020-03-30.h5ad') adata.var = adata.var.reset_index() adata.var.index = adata.var['gene_id'] adata.var.index = adata.var.index.rename('index') gene_dataset = GeneExpressionDataset() # we provide the `batch_indices` so that scvi can perform batch correction gene_dataset.populate_from_data( adata.X, gene_names=adata.var.index.values, cell_types=adata.obs['cell_type'].values, batch_indices=adata.obs['experiment'].cat.codes.values, ) vae = VAE(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches) trainer = UnsupervisedTrainer( vae, gene_dataset, train_size=0.75, use_cuda=False, frequency=1, ) # LOAD full_file_save_path = os.path.join(save_path, vae_file_name) trainer.model.load_state_dict(torch.load(full_file_save_path)) trainer.model.eval() print(' ### ### ### loaded vae') print(datetime.datetime.now()) # n_epochs = 5 # lr = 0.001 # full_file_save_path = os.path.join(save_path, vae_file_name) # trainer.train(n_epochs=n_epochs, lr=lr) # torch.save(trainer.model.state_dict(), full_file_save_path) # train_test_results = pd.DataFrame(trainer.history).rename(columns={'elbo_train_set':'Train', 'elbo_test_set':'Test'}) # print(train_test_results) full = trainer.create_posterior(trainer.model, gene_dataset, indices=np.arange(len(gene_dataset))) latent, batch_indices, labels = full.sequential().get_latent() batch_indices = batch_indices.ravel() print(' ### ### ### computed full posterior') print(' ### ### ### url = ', url) # read submission csv and fetch selected cells submission = pd.read_csv(io.StringIO(requests.get(url).content.decode('utf-8')), index_col=0) selected_cells_csv_string = submission.to_csv(index=False).replace('\n', '<br>') # reconstruct user email from submission url email = url.split('https://scvi-differential-expression.s3.us-east-2.amazonaws.com/submissions/')[1] email = email.split('%25')[0] email = email.replace('%40', '@') # create masks for cell selection according to submission # start with all entries false cell_idx1 = adata.obs['cell_type'] == '000000' for _, entry in submission[['cell_type1', 'experiment1']].dropna().iterrows():
cell_idx2 = adata.obs['cell_type'] == '000000' for _, entry in submission[['cell_type2', 'experiment2']].dropna().iterrows(): cell = entry['cell_type2'].strip() experiment = entry['experiment2'].strip() curr_boolean = (adata.obs['cell_type'] == cell) & (adata.obs['experiment'] == experiment) cell_idx2 = (cell_idx2 | curr_boolean) print(' ### ### ### computed idxs') n_samples = 10000 M_permutation = 10000 de_change = full.differential_expression_score( idx1=cell_idx1.values, # we use the same cells as chosen before idx2=cell_idx2.values, mode='change', # set to the new change mode n_samples=n_samples, M_permutation=M_permutation, ) print(' ### ### ### finished DE!') print(datetime.datetime.now()) # manipulate the DE results for plotting # we use the `mean` entru in de_chage, it is the scVI posterior log2 fold change de_change['log10_pvalue'] = np.log10(de_change['proba_not_de']) # we take absolute values of the first bayes factor as the one to use on the volcano plot # bayes1 and bayes2 should be roughtly the same, except with opposite signs de_change['abs_bayes_factor'] = np.abs(de_change['bayes_factor']) de_change = de_change.join(adata.var, how='inner') # manipulate the DE results for plotting de = de_change.copy() de['gene_color'] = 'rgba(100, 100, 100, 0.2)' for gene in submission['selected_genes'].dropna().values: gene = gene.strip() de['gene_color'][de['gene_name'].str.contains(gene)] = 'rgba(0, 0,255, 1)' de['gene_color'][de['gene_id'].str.contains(gene)] = 'rgba(0, 0,255, 1)' de_result_csv = de[ ['proba_not_de', 'log10_pvalue', 'bayes_factor', 'lfc_mean', 'lfc_median', 'lfc_std', 'lfc_min', 'lfc_max', 'gene_id', 'gene_name', 'gene_description']] print(' ### ### ### Creating plot') try: jobname = submission['job_name'][0] except: jobname = ' ' de['gene_description_html'] = de['gene_description'].str.replace('\. ', '.<br>') string_bf_list = [str(bf) for bf in np.round(de['bayes_factor'].values, 3)] de['bayes_factor_string'] = string_bf_list fig = go.Figure( data=go.Scatter( x=de["lfc_mean"].round(3) , y=-de["log10_pvalue"].round(3) , mode='markers' , marker=dict(color=de['gene_color']) , hoverinfo='text' , text=de['gene_description_html'] , customdata=de.gene_name.astype(str) + '<br>' + de.gene_id.values + \ '<br>Bayes Factor: \t' + de.bayes_factor_string + \ '<br>-log10(p-value): \t' + de["log10_pvalue"].round(3).astype(str) + \ '<br>log2 FC mean: \t' + de["lfc_mean"].round(3).astype(str) + \ '<br>log2 FC median: \t' + de["lfc_median"].round(3).astype(str) + \ '<br>log2 FC std: \t' + de["lfc_std"].round(3).astype(str) , hovertemplate='%{customdata} <br><extra>%{text}</extra>' ) , layout={ "title": {"text": "Differential expression on C. elegans single cell data <br> " + jobname + " <br> <a href=" + url + ">" + url + '</a>' , 'x': 0.5 } , 'xaxis': {'title': {"text": "log2 fold change"}} , 'yaxis': {'title': {"text": "-log10(p-value)"}} } ) ### SAVE RESULTS AND SEND MAIL #### # construct the filename for saving the results filename = url.split('https://scvi-differential-expression.s3.us-east-2.amazonaws.com/submissions/')[1] filename = filename.replace('%40', '@') filename = filename.replace('%25', '@') filename = filename.replace('.csv', '') csv_buffer = StringIO() de_result_csv.to_csv(csv_buffer) csvfilename = 'csv/' + filename + '-results.csv' htmlfilename = 'plots/' + filename + '-results.html' print(' ### ### ### Putting files in s3...') client = boto3.client('s3', aws_access_key_id=AWS_S3_ACCESS_KEY, aws_secret_access_key=AWS_S3_SECRET ) client.put_object( Body=csv_buffer.getvalue(), Bucket='scvi-differential-expression', Key=csvfilename, ACL='public-read' ) html_buffer = StringIO() fig.write_html(html_buffer, auto_open=True) client.put_object( Body=html_buffer.getvalue(), Bucket='scvi-differential-expression', Key=htmlfilename, ACL='public-read' ) csv_url = 'https://scvi-differential-expression.s3.us-east-2.amazonaws.com/' + urllib.parse.quote(csvfilename) html_url = 'https://scvi-differential-expression.s3.us-east-2.amazonaws.com/' + urllib.parse.quote(htmlfilename) print(' ### ### ### Files uploaded successfully') dt_ended = datetime.datetime.utcnow() total_time = str(int((dt_ended - dt_started).total_seconds())) email_body = f' Your 🌋 wormcells-de 💥 C. elegans single cell differential expression results: <br> {jobname} <br><br> <a href="{csv_url}">CSV file with results</a> <br> <a href="{html_url}">Vocano plot</a> <br> <a href="{url}">Your cell selection</a> <br> Processing time: {total_time}s <br> <br> <br> Thanks <br> Eduardo' print(' ### ### ### Email created') message = Mail( from_email='eduardo@wormbase.org', to_emails=email, subject='C. elegans single cell differential expression results', html_content=email_body) sg = SendGridAPIClient(sendgrid_key) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) print(' ********************* Email sent ********************') print(' ****************** Total time (s):', end = ' ') print(total_time) print('Terminating... ') instance_id = requests.get("http://169.254.169.254/latest/meta-data/instance-id").text session = boto3.Session(region_name='us-east-2', aws_access_key_id=AWS_S3_ACCESS_KEY, aws_secret_access_key=AWS_S3_SECRET) ec2 = session.resource('ec2', region_name='us-east-2') ec2.instances.filter(InstanceIds=[instance_id]).terminate() # if False: except: print(' XXXXXXXXXXXXXXXX SOMETHING FAILED XXXXXXXXXXXXXXX') filename = url.split('https://scvi-differential-expression.s3.us-east-2.amazonaws.com/submissions/')[1] filename = filename.replace('%40', '@') filename = filename.replace('%25', '@') filename = filename.replace('.csv', '') logs = open('log_file.txt', 'r').read() logs_buffer = StringIO() logs_buffer.write(logs) csv_buffer = StringIO() logsfilename = 'logs/' + filename + '-logs.txt' print(' ### ### ### Putting log in s3...') client = boto3.client('s3', aws_access_key_id=AWS_S3_ACCESS_KEY, aws_secret_access_key=AWS_S3_SECRET ) client.put_object( Body=logs_buffer.getvalue(), Bucket='scvi-differential-expression', Key=logsfilename, ACL='public-read' ) print(' ### ### ### Log in s3. Sending email...') message = Mail( from_email='eduardo@wormbase.org', to_emails='veigabeltrame@gmail.com', subject='SOMETHING WENT WRONG!!!!111', html_content=logs) sg = SendGridAPIClient(sendgrid_key) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) print(' ### ### ### Email sent. Done.') # print('Terminating... ') # instance_id = requests.get("http://169.254.169.254/latest/meta-data/instance-id").text # # session = boto3.Session(region_name='us-east-2', # aws_access_key_id=AWS_S3_ACCESS_KEY, # aws_secret_access_key=AWS_S3_SECRET) # ec2 = session.resource('ec2', region_name='us-east-2') # ec2.instances.filter(InstanceIds = [instance_id]).terminate()
cell = entry['cell_type1'].strip() experiment = entry['experiment1'].strip() curr_boolean = (adata.obs['cell_type'] == cell) & (adata.obs['experiment'] == experiment) cell_idx1 = (cell_idx1 | curr_boolean)
conditional_block
SceneL5.js
/* * COMP3801 Winter 2017 Lab 5 * * Scene object - define model placement in world coordinates */ /* * Constructor for Scene object. This object holds a list of models to render, * and a transform for each one. The list is defined in a JSON file. The * field named "models" in the JSON file defines the list. This field is an * array of objects. Each object contains the "modelURL", a scale factor, * and the placement of the model frame in world frame as vec3 values for the * "location" point and "xBasis", "yBasis", and "zBasis" vectors for the frame. * The scale factor should be applied to the points before applying the frame * transform. * * @param canvasID - string ID of canvas in which to render * @param sceneURL - URL of JSON file containing scene definition */ var isDown = false; var isOrigin = true; var initialOrigin; var hasResetRot = false; function Scene(canvasID, sceneURL) { // Set up WebGL context var t = this; this.canvasID = canvasID; var canvas = this.canvas = document.getElementById(canvasID); if (!canvas) { alert("Canvas ID '" + canvasID + "' not found."); return; } var gl = this.gl = WebGLUtils.setupWebGL(this.canvas); if (!gl) { alert("WebGL isn't available in this browser"); return; } // Add key press event handler canvas.addEventListener("keypress", function(event) { t.KeyInput(event); }); canvas.addEventListener("mousedown", function(event) {t.MouseDown(event); }); canvas.addEventListener("mouseup", function(event) {t.MouseUp(event) }); canvas.addEventListener("mousemove", function(event) {t.MouseDrag(event) }); // Load the scene definition var jScene = this.jScene = LoadJSON(sceneURL); if (jScene === null) return; // scene load failed (LoadJSON alerts on error) // Set up WebGL rendering settings gl.viewport(0, 0, canvas.width, canvas.height); gl.enable(gl.DEPTH_TEST); var bgColor = [ 0, 0, 0, 1 ]; if ("bgColor" in jScene)
gl.clearColor(bgColor[0], bgColor[1], bgColor[2], bgColor[3]); // Set up User Interface elements this.fovSliderID = canvasID + "-fov-slider"; this.fovSlider = document.getElementById(this.fovSliderID); this.nearSliderID = canvasID + "-near-slider"; this.nearSlider = document.getElementById(this.nearSliderID); this.farSliderID = canvasID + "-far-slider"; this.farSlider = document.getElementById(this.farSliderID); this.zSliderID = canvasID + "-z-slider"; this.zSlider = document.getElementById((this.zSliderID)); this.perspectiveCheckBoxID = canvasID + "-projection"; this.perspectiveCheckBox = document.getElementById(this.perspectiveCheckBoxID); // Get the initial camera parameters (copy values so we can change them // without modifying the jScene object, we might want the original values // to do a reset. this.ResetCamera(); // Load each model in the scene var loadedModels = this.loadedModels = []; // array of models var numPaths = 0; for (var i = 0; i < jScene.models.length; ++i) { // Load model from JSON and add to loadedModels array var jModel = jScene.models[i]; var model = new JSONModel(gl, jModel.modelURL); if (model === null) return; // failed to load a model // if(jModel.path != null) {numPaths++; console.log("Paths Inc"); } if(!model.p) { loadedModels.push(model); } //console.log("Model pushed: " + loadedModels.length); } this.preRotationDegrees = 0.0; this.postRotationDegrees = 0.0; this.Nextiteration = Array.apply(null, Array(jScene.models.length)).map(function (x) { return 0; }); // Start rendering requestAnimationFrame(function() { t.Render(); } ); }; var hasReached = true; var lastPosition = 0; var etol = 0; var rotX = 0; var rotY = 0; Scene.prototype.Render = function() { var gl = this.gl; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var camera = this.camera; // Compute aspect ratio of canvas var aspect = this.canvas.width / this.canvas.height; // Build projection matrix var projection = []; camera.FOVdeg = parseFloat(this.fovSlider.value); camera.near = parseFloat(this.nearSlider.value); camera.far = parseFloat(this.farSlider.value); camera.location[2] = parseFloat(this.zSlider.value); camera.perspective = this.perspectiveCheckBox.checked; if (camera.perspective) { projection = perspective(camera.FOVdeg, aspect, camera.near, camera.far); } else { projection = ortho(-aspect, aspect, -1.0, 1.0, camera.near, camera.far); } // Build view transform and initialize matrix stack var matrixStack = new MatrixStack; if(hasResetRot) { matrixStack.LoadMatrix( lookAt(camera.location, camera.lookAt, camera.approxUp)); } else { matrixStack.LoadMatrix( mult(mult(lookAt(camera.location, camera.lookAt, camera.approxUp),rotateX(rotX)), rotateY(rotY))); } //console.log(camera.lookAt); // Render each loaded object with its transform for (var i = 0; i < this.loadedModels.length; ++i) { // Build transform from JSON and add to transforms array var jModel = this.jScene.models[i]; var ms = scalem(jModel.scale); var mt; if(jModel.path != null){//&& etol < 500){ etol++; if(hasReached == true) { lastPosition = jModel.location; console.log("hasReached CHANGED; lastPostion: "+ lastPosition); hasReached=false; } jModel.location = add(jModel.location, scale(jModel.speed, normalize(subtract(jModel.path[this.Nextiteration[i]], jModel.location)))); var checkDiffX = Math.abs(jModel.location[0] - jModel.path[this.Nextiteration[i]][0]); var checkDiffY = Math.abs(jModel.location[1] - jModel.path[this.Nextiteration[i]][1]); var checkDiffZ = Math.abs(jModel.location[2] - jModel.path[this.Nextiteration[i]][2]); // console.log("POSITION UPDATE: \n\t\t\t lastPosition: " + lastPosition // + "\n\t\t\t Next Position: " + jModel.path[this.Nextiteration[i]] // + "\n\t\t\t moved: " + scale(jModel.speed, normalize(subtract(jModel.path[this.Nextiteration[i]], lastPosition))) // + "\n\t\t\t Current Position: " + jModel.location // + "\n\t\t\t Δgoal: " + (checkDiffX + checkDiffY + checkDiffZ) // + "\n\t\t\t Remaining Dests = " + (jModel.path.length - (this.Nextiteration[i]+1))); if((checkDiffX + checkDiffY + checkDiffZ) <= jModel.speed) //Click here to find one neat trick to deal with floating point errors { lastPosition = jModel.location hasReached = true; if((jModel.path.length - (this.Nextiteration[i]+1)) == 0){ this.Nextiteration[i] = 0; } else { this.Nextiteration[i]++; } } } //Update camera lookat info if(!isOrigin) this.camera.lookAt = this.jScene.models[lookAtModel].location; mt = translate(jModel.location); var mry = rotateY(this.preRotationDegrees); var mf = mat4(jModel.xBasis[0], jModel.yBasis[0], jModel.zBasis[0], 0.0, jModel.xBasis[1], jModel.yBasis[1], jModel.zBasis[1], 0.0, jModel.xBasis[2], jModel.yBasis[2], jModel.zBasis[2], 0.0, 0.0, 0.0, 0.0, 1.0); var transform = mult(mt, mult(mf, mult(mry,ms))); matrixStack.PushMatrix(); matrixStack.MultMatrix(transform); this.loadedModels[i].Render(projection, matrixStack); matrixStack.PopMatrix(); this.preRotationDegrees += 0.1; if (this.preRotationDegrees > 180) this.preRotationDegrees -= 360; } var t = this; requestAnimationFrame(function() { t.Render(); } ); }; Scene.prototype.ResetCamera = function() { // Copy the camera parameters from the jScene object. The copy's values // are independent of the originals, so changes won't affect the originals. this.camera = {}; this.camera.location = this.jScene.camera.location.slice(); this.camera.lookAt = this.jScene.camera.lookAt.slice(); this.camera.approxUp = this.jScene.camera.approxUp.slice(); this.camera.FOVdeg = this.jScene.camera.FOVdeg; this.camera.near = this.jScene.camera.near; this.camera.far = this.jScene.camera.far; this.camera.perspective = this.jScene.camera.perspective; // Set UI elements to the values defined in the scene files this.fovSlider.value = this.camera.FOVdeg; SliderUpdate(this.fovSliderID + "-output", this.camera.FOVdeg); this.nearSlider.value = this.camera.near; SliderUpdate(this.nearSliderID + "-output", this.camera.near); this.farSlider.value = this.camera.far; SliderUpdate(this.farSliderID + "-output", this.camera.far); this.zSlider.value = this.camera.location[2]; SliderUpdate(this.zSliderID + "-output", this.camera.location[2]); this.perspectiveCheckBox.checked = this.camera.perspective; }; var lookAtModel = 0; Scene.prototype.KeyInput = function(event) { // Get character from event var c = String.fromCharCode(event.which); console.log("keyboard input character = " + c); // this line may be removed // If numeric, switch view to selected object var atModel = parseInt(c); if (!isNaN(atModel) && (c <= this.jScene.models.length)) { if(c == 0) { //Reset Camera this.camera.lookAt = this.jScene.camera.lookAt; this.camera.location = this.jScene.camera.location; this.camera.approxUp = this.jScene.camera.approxUp; isOrigin = true; hasResetRot = false; } else { isOrigin = false; } lookAtModel = (atModel != 0) ? atModel-1 : lookAtModel; //When changing lookAt to a new model, we reset the cameras rotation. //Yeah...I know this is a terrible way of doing the drag rotation, but I had already implemented a lot //of it by the time I realized. if(hasResetRot == false) { rotX = 0; rotY = 0; hasResetRot = true; } } }; Scene.prototype.MouseDown = function(event) { isDown = true; }; Scene.prototype.MouseUp = function(event) { isDown = false; }; var oldX = 0; var oldY = 0; Scene.prototype.MouseDrag = function(event) { var canvas = this.canvas; var tempLOC = this.camera.location; var tempLA = this.camera.lookAt; if(isDown == true){ if(event.clientY - oldY < 0) { rotY += 1; oldY = event.clientY; } else { rotY += -1; oldY = event.clientY; } if(event.clientX > oldX) { rotX += 1; oldX = event.clientX; } else { rotX += -1; oldX = event.clientX; } hasResetRot = false; }; }
{ bgColor = jScene["bgColor"]; }
conditional_block
SceneL5.js
/* * COMP3801 Winter 2017 Lab 5 * * Scene object - define model placement in world coordinates */ /* * Constructor for Scene object. This object holds a list of models to render, * and a transform for each one. The list is defined in a JSON file. The * field named "models" in the JSON file defines the list. This field is an * array of objects. Each object contains the "modelURL", a scale factor, * and the placement of the model frame in world frame as vec3 values for the * "location" point and "xBasis", "yBasis", and "zBasis" vectors for the frame. * The scale factor should be applied to the points before applying the frame * transform. * * @param canvasID - string ID of canvas in which to render * @param sceneURL - URL of JSON file containing scene definition */ var isDown = false; var isOrigin = true; var initialOrigin; var hasResetRot = false; function
(canvasID, sceneURL) { // Set up WebGL context var t = this; this.canvasID = canvasID; var canvas = this.canvas = document.getElementById(canvasID); if (!canvas) { alert("Canvas ID '" + canvasID + "' not found."); return; } var gl = this.gl = WebGLUtils.setupWebGL(this.canvas); if (!gl) { alert("WebGL isn't available in this browser"); return; } // Add key press event handler canvas.addEventListener("keypress", function(event) { t.KeyInput(event); }); canvas.addEventListener("mousedown", function(event) {t.MouseDown(event); }); canvas.addEventListener("mouseup", function(event) {t.MouseUp(event) }); canvas.addEventListener("mousemove", function(event) {t.MouseDrag(event) }); // Load the scene definition var jScene = this.jScene = LoadJSON(sceneURL); if (jScene === null) return; // scene load failed (LoadJSON alerts on error) // Set up WebGL rendering settings gl.viewport(0, 0, canvas.width, canvas.height); gl.enable(gl.DEPTH_TEST); var bgColor = [ 0, 0, 0, 1 ]; if ("bgColor" in jScene) { bgColor = jScene["bgColor"]; } gl.clearColor(bgColor[0], bgColor[1], bgColor[2], bgColor[3]); // Set up User Interface elements this.fovSliderID = canvasID + "-fov-slider"; this.fovSlider = document.getElementById(this.fovSliderID); this.nearSliderID = canvasID + "-near-slider"; this.nearSlider = document.getElementById(this.nearSliderID); this.farSliderID = canvasID + "-far-slider"; this.farSlider = document.getElementById(this.farSliderID); this.zSliderID = canvasID + "-z-slider"; this.zSlider = document.getElementById((this.zSliderID)); this.perspectiveCheckBoxID = canvasID + "-projection"; this.perspectiveCheckBox = document.getElementById(this.perspectiveCheckBoxID); // Get the initial camera parameters (copy values so we can change them // without modifying the jScene object, we might want the original values // to do a reset. this.ResetCamera(); // Load each model in the scene var loadedModels = this.loadedModels = []; // array of models var numPaths = 0; for (var i = 0; i < jScene.models.length; ++i) { // Load model from JSON and add to loadedModels array var jModel = jScene.models[i]; var model = new JSONModel(gl, jModel.modelURL); if (model === null) return; // failed to load a model // if(jModel.path != null) {numPaths++; console.log("Paths Inc"); } if(!model.p) { loadedModels.push(model); } //console.log("Model pushed: " + loadedModels.length); } this.preRotationDegrees = 0.0; this.postRotationDegrees = 0.0; this.Nextiteration = Array.apply(null, Array(jScene.models.length)).map(function (x) { return 0; }); // Start rendering requestAnimationFrame(function() { t.Render(); } ); }; var hasReached = true; var lastPosition = 0; var etol = 0; var rotX = 0; var rotY = 0; Scene.prototype.Render = function() { var gl = this.gl; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var camera = this.camera; // Compute aspect ratio of canvas var aspect = this.canvas.width / this.canvas.height; // Build projection matrix var projection = []; camera.FOVdeg = parseFloat(this.fovSlider.value); camera.near = parseFloat(this.nearSlider.value); camera.far = parseFloat(this.farSlider.value); camera.location[2] = parseFloat(this.zSlider.value); camera.perspective = this.perspectiveCheckBox.checked; if (camera.perspective) { projection = perspective(camera.FOVdeg, aspect, camera.near, camera.far); } else { projection = ortho(-aspect, aspect, -1.0, 1.0, camera.near, camera.far); } // Build view transform and initialize matrix stack var matrixStack = new MatrixStack; if(hasResetRot) { matrixStack.LoadMatrix( lookAt(camera.location, camera.lookAt, camera.approxUp)); } else { matrixStack.LoadMatrix( mult(mult(lookAt(camera.location, camera.lookAt, camera.approxUp),rotateX(rotX)), rotateY(rotY))); } //console.log(camera.lookAt); // Render each loaded object with its transform for (var i = 0; i < this.loadedModels.length; ++i) { // Build transform from JSON and add to transforms array var jModel = this.jScene.models[i]; var ms = scalem(jModel.scale); var mt; if(jModel.path != null){//&& etol < 500){ etol++; if(hasReached == true) { lastPosition = jModel.location; console.log("hasReached CHANGED; lastPostion: "+ lastPosition); hasReached=false; } jModel.location = add(jModel.location, scale(jModel.speed, normalize(subtract(jModel.path[this.Nextiteration[i]], jModel.location)))); var checkDiffX = Math.abs(jModel.location[0] - jModel.path[this.Nextiteration[i]][0]); var checkDiffY = Math.abs(jModel.location[1] - jModel.path[this.Nextiteration[i]][1]); var checkDiffZ = Math.abs(jModel.location[2] - jModel.path[this.Nextiteration[i]][2]); // console.log("POSITION UPDATE: \n\t\t\t lastPosition: " + lastPosition // + "\n\t\t\t Next Position: " + jModel.path[this.Nextiteration[i]] // + "\n\t\t\t moved: " + scale(jModel.speed, normalize(subtract(jModel.path[this.Nextiteration[i]], lastPosition))) // + "\n\t\t\t Current Position: " + jModel.location // + "\n\t\t\t Δgoal: " + (checkDiffX + checkDiffY + checkDiffZ) // + "\n\t\t\t Remaining Dests = " + (jModel.path.length - (this.Nextiteration[i]+1))); if((checkDiffX + checkDiffY + checkDiffZ) <= jModel.speed) //Click here to find one neat trick to deal with floating point errors { lastPosition = jModel.location hasReached = true; if((jModel.path.length - (this.Nextiteration[i]+1)) == 0){ this.Nextiteration[i] = 0; } else { this.Nextiteration[i]++; } } } //Update camera lookat info if(!isOrigin) this.camera.lookAt = this.jScene.models[lookAtModel].location; mt = translate(jModel.location); var mry = rotateY(this.preRotationDegrees); var mf = mat4(jModel.xBasis[0], jModel.yBasis[0], jModel.zBasis[0], 0.0, jModel.xBasis[1], jModel.yBasis[1], jModel.zBasis[1], 0.0, jModel.xBasis[2], jModel.yBasis[2], jModel.zBasis[2], 0.0, 0.0, 0.0, 0.0, 1.0); var transform = mult(mt, mult(mf, mult(mry,ms))); matrixStack.PushMatrix(); matrixStack.MultMatrix(transform); this.loadedModels[i].Render(projection, matrixStack); matrixStack.PopMatrix(); this.preRotationDegrees += 0.1; if (this.preRotationDegrees > 180) this.preRotationDegrees -= 360; } var t = this; requestAnimationFrame(function() { t.Render(); } ); }; Scene.prototype.ResetCamera = function() { // Copy the camera parameters from the jScene object. The copy's values // are independent of the originals, so changes won't affect the originals. this.camera = {}; this.camera.location = this.jScene.camera.location.slice(); this.camera.lookAt = this.jScene.camera.lookAt.slice(); this.camera.approxUp = this.jScene.camera.approxUp.slice(); this.camera.FOVdeg = this.jScene.camera.FOVdeg; this.camera.near = this.jScene.camera.near; this.camera.far = this.jScene.camera.far; this.camera.perspective = this.jScene.camera.perspective; // Set UI elements to the values defined in the scene files this.fovSlider.value = this.camera.FOVdeg; SliderUpdate(this.fovSliderID + "-output", this.camera.FOVdeg); this.nearSlider.value = this.camera.near; SliderUpdate(this.nearSliderID + "-output", this.camera.near); this.farSlider.value = this.camera.far; SliderUpdate(this.farSliderID + "-output", this.camera.far); this.zSlider.value = this.camera.location[2]; SliderUpdate(this.zSliderID + "-output", this.camera.location[2]); this.perspectiveCheckBox.checked = this.camera.perspective; }; var lookAtModel = 0; Scene.prototype.KeyInput = function(event) { // Get character from event var c = String.fromCharCode(event.which); console.log("keyboard input character = " + c); // this line may be removed // If numeric, switch view to selected object var atModel = parseInt(c); if (!isNaN(atModel) && (c <= this.jScene.models.length)) { if(c == 0) { //Reset Camera this.camera.lookAt = this.jScene.camera.lookAt; this.camera.location = this.jScene.camera.location; this.camera.approxUp = this.jScene.camera.approxUp; isOrigin = true; hasResetRot = false; } else { isOrigin = false; } lookAtModel = (atModel != 0) ? atModel-1 : lookAtModel; //When changing lookAt to a new model, we reset the cameras rotation. //Yeah...I know this is a terrible way of doing the drag rotation, but I had already implemented a lot //of it by the time I realized. if(hasResetRot == false) { rotX = 0; rotY = 0; hasResetRot = true; } } }; Scene.prototype.MouseDown = function(event) { isDown = true; }; Scene.prototype.MouseUp = function(event) { isDown = false; }; var oldX = 0; var oldY = 0; Scene.prototype.MouseDrag = function(event) { var canvas = this.canvas; var tempLOC = this.camera.location; var tempLA = this.camera.lookAt; if(isDown == true){ if(event.clientY - oldY < 0) { rotY += 1; oldY = event.clientY; } else { rotY += -1; oldY = event.clientY; } if(event.clientX > oldX) { rotX += 1; oldX = event.clientX; } else { rotX += -1; oldX = event.clientX; } hasResetRot = false; }; }
Scene
identifier_name
SceneL5.js
/* * COMP3801 Winter 2017 Lab 5 * * Scene object - define model placement in world coordinates */ /* * Constructor for Scene object. This object holds a list of models to render, * and a transform for each one. The list is defined in a JSON file. The * field named "models" in the JSON file defines the list. This field is an * array of objects. Each object contains the "modelURL", a scale factor, * and the placement of the model frame in world frame as vec3 values for the * "location" point and "xBasis", "yBasis", and "zBasis" vectors for the frame. * The scale factor should be applied to the points before applying the frame * transform. * * @param canvasID - string ID of canvas in which to render * @param sceneURL - URL of JSON file containing scene definition */ var isDown = false; var isOrigin = true; var initialOrigin; var hasResetRot = false; function Scene(canvasID, sceneURL)
; var hasReached = true; var lastPosition = 0; var etol = 0; var rotX = 0; var rotY = 0; Scene.prototype.Render = function() { var gl = this.gl; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var camera = this.camera; // Compute aspect ratio of canvas var aspect = this.canvas.width / this.canvas.height; // Build projection matrix var projection = []; camera.FOVdeg = parseFloat(this.fovSlider.value); camera.near = parseFloat(this.nearSlider.value); camera.far = parseFloat(this.farSlider.value); camera.location[2] = parseFloat(this.zSlider.value); camera.perspective = this.perspectiveCheckBox.checked; if (camera.perspective) { projection = perspective(camera.FOVdeg, aspect, camera.near, camera.far); } else { projection = ortho(-aspect, aspect, -1.0, 1.0, camera.near, camera.far); } // Build view transform and initialize matrix stack var matrixStack = new MatrixStack; if(hasResetRot) { matrixStack.LoadMatrix( lookAt(camera.location, camera.lookAt, camera.approxUp)); } else { matrixStack.LoadMatrix( mult(mult(lookAt(camera.location, camera.lookAt, camera.approxUp),rotateX(rotX)), rotateY(rotY))); } //console.log(camera.lookAt); // Render each loaded object with its transform for (var i = 0; i < this.loadedModels.length; ++i) { // Build transform from JSON and add to transforms array var jModel = this.jScene.models[i]; var ms = scalem(jModel.scale); var mt; if(jModel.path != null){//&& etol < 500){ etol++; if(hasReached == true) { lastPosition = jModel.location; console.log("hasReached CHANGED; lastPostion: "+ lastPosition); hasReached=false; } jModel.location = add(jModel.location, scale(jModel.speed, normalize(subtract(jModel.path[this.Nextiteration[i]], jModel.location)))); var checkDiffX = Math.abs(jModel.location[0] - jModel.path[this.Nextiteration[i]][0]); var checkDiffY = Math.abs(jModel.location[1] - jModel.path[this.Nextiteration[i]][1]); var checkDiffZ = Math.abs(jModel.location[2] - jModel.path[this.Nextiteration[i]][2]); // console.log("POSITION UPDATE: \n\t\t\t lastPosition: " + lastPosition // + "\n\t\t\t Next Position: " + jModel.path[this.Nextiteration[i]] // + "\n\t\t\t moved: " + scale(jModel.speed, normalize(subtract(jModel.path[this.Nextiteration[i]], lastPosition))) // + "\n\t\t\t Current Position: " + jModel.location // + "\n\t\t\t Δgoal: " + (checkDiffX + checkDiffY + checkDiffZ) // + "\n\t\t\t Remaining Dests = " + (jModel.path.length - (this.Nextiteration[i]+1))); if((checkDiffX + checkDiffY + checkDiffZ) <= jModel.speed) //Click here to find one neat trick to deal with floating point errors { lastPosition = jModel.location hasReached = true; if((jModel.path.length - (this.Nextiteration[i]+1)) == 0){ this.Nextiteration[i] = 0; } else { this.Nextiteration[i]++; } } } //Update camera lookat info if(!isOrigin) this.camera.lookAt = this.jScene.models[lookAtModel].location; mt = translate(jModel.location); var mry = rotateY(this.preRotationDegrees); var mf = mat4(jModel.xBasis[0], jModel.yBasis[0], jModel.zBasis[0], 0.0, jModel.xBasis[1], jModel.yBasis[1], jModel.zBasis[1], 0.0, jModel.xBasis[2], jModel.yBasis[2], jModel.zBasis[2], 0.0, 0.0, 0.0, 0.0, 1.0); var transform = mult(mt, mult(mf, mult(mry,ms))); matrixStack.PushMatrix(); matrixStack.MultMatrix(transform); this.loadedModels[i].Render(projection, matrixStack); matrixStack.PopMatrix(); this.preRotationDegrees += 0.1; if (this.preRotationDegrees > 180) this.preRotationDegrees -= 360; } var t = this; requestAnimationFrame(function() { t.Render(); } ); }; Scene.prototype.ResetCamera = function() { // Copy the camera parameters from the jScene object. The copy's values // are independent of the originals, so changes won't affect the originals. this.camera = {}; this.camera.location = this.jScene.camera.location.slice(); this.camera.lookAt = this.jScene.camera.lookAt.slice(); this.camera.approxUp = this.jScene.camera.approxUp.slice(); this.camera.FOVdeg = this.jScene.camera.FOVdeg; this.camera.near = this.jScene.camera.near; this.camera.far = this.jScene.camera.far; this.camera.perspective = this.jScene.camera.perspective; // Set UI elements to the values defined in the scene files this.fovSlider.value = this.camera.FOVdeg; SliderUpdate(this.fovSliderID + "-output", this.camera.FOVdeg); this.nearSlider.value = this.camera.near; SliderUpdate(this.nearSliderID + "-output", this.camera.near); this.farSlider.value = this.camera.far; SliderUpdate(this.farSliderID + "-output", this.camera.far); this.zSlider.value = this.camera.location[2]; SliderUpdate(this.zSliderID + "-output", this.camera.location[2]); this.perspectiveCheckBox.checked = this.camera.perspective; }; var lookAtModel = 0; Scene.prototype.KeyInput = function(event) { // Get character from event var c = String.fromCharCode(event.which); console.log("keyboard input character = " + c); // this line may be removed // If numeric, switch view to selected object var atModel = parseInt(c); if (!isNaN(atModel) && (c <= this.jScene.models.length)) { if(c == 0) { //Reset Camera this.camera.lookAt = this.jScene.camera.lookAt; this.camera.location = this.jScene.camera.location; this.camera.approxUp = this.jScene.camera.approxUp; isOrigin = true; hasResetRot = false; } else { isOrigin = false; } lookAtModel = (atModel != 0) ? atModel-1 : lookAtModel; //When changing lookAt to a new model, we reset the cameras rotation. //Yeah...I know this is a terrible way of doing the drag rotation, but I had already implemented a lot //of it by the time I realized. if(hasResetRot == false) { rotX = 0; rotY = 0; hasResetRot = true; } } }; Scene.prototype.MouseDown = function(event) { isDown = true; }; Scene.prototype.MouseUp = function(event) { isDown = false; }; var oldX = 0; var oldY = 0; Scene.prototype.MouseDrag = function(event) { var canvas = this.canvas; var tempLOC = this.camera.location; var tempLA = this.camera.lookAt; if(isDown == true){ if(event.clientY - oldY < 0) { rotY += 1; oldY = event.clientY; } else { rotY += -1; oldY = event.clientY; } if(event.clientX > oldX) { rotX += 1; oldX = event.clientX; } else { rotX += -1; oldX = event.clientX; } hasResetRot = false; }; }
{ // Set up WebGL context var t = this; this.canvasID = canvasID; var canvas = this.canvas = document.getElementById(canvasID); if (!canvas) { alert("Canvas ID '" + canvasID + "' not found."); return; } var gl = this.gl = WebGLUtils.setupWebGL(this.canvas); if (!gl) { alert("WebGL isn't available in this browser"); return; } // Add key press event handler canvas.addEventListener("keypress", function(event) { t.KeyInput(event); }); canvas.addEventListener("mousedown", function(event) {t.MouseDown(event); }); canvas.addEventListener("mouseup", function(event) {t.MouseUp(event) }); canvas.addEventListener("mousemove", function(event) {t.MouseDrag(event) }); // Load the scene definition var jScene = this.jScene = LoadJSON(sceneURL); if (jScene === null) return; // scene load failed (LoadJSON alerts on error) // Set up WebGL rendering settings gl.viewport(0, 0, canvas.width, canvas.height); gl.enable(gl.DEPTH_TEST); var bgColor = [ 0, 0, 0, 1 ]; if ("bgColor" in jScene) { bgColor = jScene["bgColor"]; } gl.clearColor(bgColor[0], bgColor[1], bgColor[2], bgColor[3]); // Set up User Interface elements this.fovSliderID = canvasID + "-fov-slider"; this.fovSlider = document.getElementById(this.fovSliderID); this.nearSliderID = canvasID + "-near-slider"; this.nearSlider = document.getElementById(this.nearSliderID); this.farSliderID = canvasID + "-far-slider"; this.farSlider = document.getElementById(this.farSliderID); this.zSliderID = canvasID + "-z-slider"; this.zSlider = document.getElementById((this.zSliderID)); this.perspectiveCheckBoxID = canvasID + "-projection"; this.perspectiveCheckBox = document.getElementById(this.perspectiveCheckBoxID); // Get the initial camera parameters (copy values so we can change them // without modifying the jScene object, we might want the original values // to do a reset. this.ResetCamera(); // Load each model in the scene var loadedModels = this.loadedModels = []; // array of models var numPaths = 0; for (var i = 0; i < jScene.models.length; ++i) { // Load model from JSON and add to loadedModels array var jModel = jScene.models[i]; var model = new JSONModel(gl, jModel.modelURL); if (model === null) return; // failed to load a model // if(jModel.path != null) {numPaths++; console.log("Paths Inc"); } if(!model.p) { loadedModels.push(model); } //console.log("Model pushed: " + loadedModels.length); } this.preRotationDegrees = 0.0; this.postRotationDegrees = 0.0; this.Nextiteration = Array.apply(null, Array(jScene.models.length)).map(function (x) { return 0; }); // Start rendering requestAnimationFrame(function() { t.Render(); } ); }
identifier_body
SceneL5.js
/* * COMP3801 Winter 2017 Lab 5 * * Scene object - define model placement in world coordinates */ /* * Constructor for Scene object. This object holds a list of models to render, * and a transform for each one. The list is defined in a JSON file. The * field named "models" in the JSON file defines the list. This field is an * array of objects. Each object contains the "modelURL", a scale factor, * and the placement of the model frame in world frame as vec3 values for the * "location" point and "xBasis", "yBasis", and "zBasis" vectors for the frame. * The scale factor should be applied to the points before applying the frame * transform. * * @param canvasID - string ID of canvas in which to render * @param sceneURL - URL of JSON file containing scene definition */ var isDown = false; var isOrigin = true; var initialOrigin; var hasResetRot = false; function Scene(canvasID, sceneURL) { // Set up WebGL context var t = this; this.canvasID = canvasID; var canvas = this.canvas = document.getElementById(canvasID); if (!canvas) { alert("Canvas ID '" + canvasID + "' not found."); return; } var gl = this.gl = WebGLUtils.setupWebGL(this.canvas); if (!gl) { alert("WebGL isn't available in this browser"); return; } // Add key press event handler canvas.addEventListener("keypress", function(event) { t.KeyInput(event); }); canvas.addEventListener("mousedown", function(event) {t.MouseDown(event); }); canvas.addEventListener("mouseup", function(event) {t.MouseUp(event) }); canvas.addEventListener("mousemove", function(event) {t.MouseDrag(event) }); // Load the scene definition var jScene = this.jScene = LoadJSON(sceneURL); if (jScene === null) return; // scene load failed (LoadJSON alerts on error) // Set up WebGL rendering settings gl.viewport(0, 0, canvas.width, canvas.height); gl.enable(gl.DEPTH_TEST); var bgColor = [ 0, 0, 0, 1 ]; if ("bgColor" in jScene) { bgColor = jScene["bgColor"]; } gl.clearColor(bgColor[0], bgColor[1], bgColor[2], bgColor[3]); // Set up User Interface elements this.fovSliderID = canvasID + "-fov-slider"; this.fovSlider = document.getElementById(this.fovSliderID); this.nearSliderID = canvasID + "-near-slider"; this.nearSlider = document.getElementById(this.nearSliderID); this.farSliderID = canvasID + "-far-slider"; this.farSlider = document.getElementById(this.farSliderID); this.zSliderID = canvasID + "-z-slider"; this.zSlider = document.getElementById((this.zSliderID)); this.perspectiveCheckBoxID = canvasID + "-projection"; this.perspectiveCheckBox = document.getElementById(this.perspectiveCheckBoxID); // Get the initial camera parameters (copy values so we can change them // without modifying the jScene object, we might want the original values // to do a reset. this.ResetCamera(); // Load each model in the scene var loadedModels = this.loadedModels = []; // array of models var numPaths = 0; for (var i = 0; i < jScene.models.length; ++i) { // Load model from JSON and add to loadedModels array var jModel = jScene.models[i]; var model = new JSONModel(gl, jModel.modelURL); if (model === null) return; // failed to load a model // if(jModel.path != null) {numPaths++; console.log("Paths Inc"); } if(!model.p) { loadedModels.push(model); } //console.log("Model pushed: " + loadedModels.length); } this.preRotationDegrees = 0.0; this.postRotationDegrees = 0.0; this.Nextiteration = Array.apply(null, Array(jScene.models.length)).map(function (x) { return 0; }); // Start rendering requestAnimationFrame(function() { t.Render(); } ); }; var hasReached = true; var lastPosition = 0; var etol = 0; var rotX = 0; var rotY = 0; Scene.prototype.Render = function() { var gl = this.gl; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var camera = this.camera; // Compute aspect ratio of canvas var aspect = this.canvas.width / this.canvas.height; // Build projection matrix var projection = []; camera.FOVdeg = parseFloat(this.fovSlider.value); camera.near = parseFloat(this.nearSlider.value); camera.far = parseFloat(this.farSlider.value); camera.location[2] = parseFloat(this.zSlider.value);
projection = perspective(camera.FOVdeg, aspect, camera.near, camera.far); } else { projection = ortho(-aspect, aspect, -1.0, 1.0, camera.near, camera.far); } // Build view transform and initialize matrix stack var matrixStack = new MatrixStack; if(hasResetRot) { matrixStack.LoadMatrix( lookAt(camera.location, camera.lookAt, camera.approxUp)); } else { matrixStack.LoadMatrix( mult(mult(lookAt(camera.location, camera.lookAt, camera.approxUp),rotateX(rotX)), rotateY(rotY))); } //console.log(camera.lookAt); // Render each loaded object with its transform for (var i = 0; i < this.loadedModels.length; ++i) { // Build transform from JSON and add to transforms array var jModel = this.jScene.models[i]; var ms = scalem(jModel.scale); var mt; if(jModel.path != null){//&& etol < 500){ etol++; if(hasReached == true) { lastPosition = jModel.location; console.log("hasReached CHANGED; lastPostion: "+ lastPosition); hasReached=false; } jModel.location = add(jModel.location, scale(jModel.speed, normalize(subtract(jModel.path[this.Nextiteration[i]], jModel.location)))); var checkDiffX = Math.abs(jModel.location[0] - jModel.path[this.Nextiteration[i]][0]); var checkDiffY = Math.abs(jModel.location[1] - jModel.path[this.Nextiteration[i]][1]); var checkDiffZ = Math.abs(jModel.location[2] - jModel.path[this.Nextiteration[i]][2]); // console.log("POSITION UPDATE: \n\t\t\t lastPosition: " + lastPosition // + "\n\t\t\t Next Position: " + jModel.path[this.Nextiteration[i]] // + "\n\t\t\t moved: " + scale(jModel.speed, normalize(subtract(jModel.path[this.Nextiteration[i]], lastPosition))) // + "\n\t\t\t Current Position: " + jModel.location // + "\n\t\t\t Δgoal: " + (checkDiffX + checkDiffY + checkDiffZ) // + "\n\t\t\t Remaining Dests = " + (jModel.path.length - (this.Nextiteration[i]+1))); if((checkDiffX + checkDiffY + checkDiffZ) <= jModel.speed) //Click here to find one neat trick to deal with floating point errors { lastPosition = jModel.location hasReached = true; if((jModel.path.length - (this.Nextiteration[i]+1)) == 0){ this.Nextiteration[i] = 0; } else { this.Nextiteration[i]++; } } } //Update camera lookat info if(!isOrigin) this.camera.lookAt = this.jScene.models[lookAtModel].location; mt = translate(jModel.location); var mry = rotateY(this.preRotationDegrees); var mf = mat4(jModel.xBasis[0], jModel.yBasis[0], jModel.zBasis[0], 0.0, jModel.xBasis[1], jModel.yBasis[1], jModel.zBasis[1], 0.0, jModel.xBasis[2], jModel.yBasis[2], jModel.zBasis[2], 0.0, 0.0, 0.0, 0.0, 1.0); var transform = mult(mt, mult(mf, mult(mry,ms))); matrixStack.PushMatrix(); matrixStack.MultMatrix(transform); this.loadedModels[i].Render(projection, matrixStack); matrixStack.PopMatrix(); this.preRotationDegrees += 0.1; if (this.preRotationDegrees > 180) this.preRotationDegrees -= 360; } var t = this; requestAnimationFrame(function() { t.Render(); } ); }; Scene.prototype.ResetCamera = function() { // Copy the camera parameters from the jScene object. The copy's values // are independent of the originals, so changes won't affect the originals. this.camera = {}; this.camera.location = this.jScene.camera.location.slice(); this.camera.lookAt = this.jScene.camera.lookAt.slice(); this.camera.approxUp = this.jScene.camera.approxUp.slice(); this.camera.FOVdeg = this.jScene.camera.FOVdeg; this.camera.near = this.jScene.camera.near; this.camera.far = this.jScene.camera.far; this.camera.perspective = this.jScene.camera.perspective; // Set UI elements to the values defined in the scene files this.fovSlider.value = this.camera.FOVdeg; SliderUpdate(this.fovSliderID + "-output", this.camera.FOVdeg); this.nearSlider.value = this.camera.near; SliderUpdate(this.nearSliderID + "-output", this.camera.near); this.farSlider.value = this.camera.far; SliderUpdate(this.farSliderID + "-output", this.camera.far); this.zSlider.value = this.camera.location[2]; SliderUpdate(this.zSliderID + "-output", this.camera.location[2]); this.perspectiveCheckBox.checked = this.camera.perspective; }; var lookAtModel = 0; Scene.prototype.KeyInput = function(event) { // Get character from event var c = String.fromCharCode(event.which); console.log("keyboard input character = " + c); // this line may be removed // If numeric, switch view to selected object var atModel = parseInt(c); if (!isNaN(atModel) && (c <= this.jScene.models.length)) { if(c == 0) { //Reset Camera this.camera.lookAt = this.jScene.camera.lookAt; this.camera.location = this.jScene.camera.location; this.camera.approxUp = this.jScene.camera.approxUp; isOrigin = true; hasResetRot = false; } else { isOrigin = false; } lookAtModel = (atModel != 0) ? atModel-1 : lookAtModel; //When changing lookAt to a new model, we reset the cameras rotation. //Yeah...I know this is a terrible way of doing the drag rotation, but I had already implemented a lot //of it by the time I realized. if(hasResetRot == false) { rotX = 0; rotY = 0; hasResetRot = true; } } }; Scene.prototype.MouseDown = function(event) { isDown = true; }; Scene.prototype.MouseUp = function(event) { isDown = false; }; var oldX = 0; var oldY = 0; Scene.prototype.MouseDrag = function(event) { var canvas = this.canvas; var tempLOC = this.camera.location; var tempLA = this.camera.lookAt; if(isDown == true){ if(event.clientY - oldY < 0) { rotY += 1; oldY = event.clientY; } else { rotY += -1; oldY = event.clientY; } if(event.clientX > oldX) { rotX += 1; oldX = event.clientX; } else { rotX += -1; oldX = event.clientX; } hasResetRot = false; }; }
camera.perspective = this.perspectiveCheckBox.checked; if (camera.perspective) {
random_line_split
main.go
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "errors" "expvar" "flag" "fmt" "io/ioutil" "net" "net/http" "os" "path" "strings" "sync" "time" graphite "github.com/cyberdelia/go-metrics-graphite" "github.com/facebookgo/pidfile" "github.com/rcrowley/go-metrics" "github.com/rcrowley/go-metrics/exp" log "github.com/sirupsen/logrus" "github.com/streadway/amqp" _ "net/http/pprof" ) var ( pidFileLocation = flag.String("pid-file", "", "PID file location") checkConfiguration = flag.Bool("check", false, "Check the configuration file and exit") debug = flag.Bool("debug", false, "Enable debugging mode") ) var version = "3.7.0" var inputChannelSize = 100000 var outputChannelSize = 1000000 var wg sync.WaitGroup var config Configuration type Status struct { InputEventCount metrics.Meter InputByteCount metrics.Meter OutputEventCount metrics.Meter OutputByteCount metrics.Meter ErrorCount metrics.Meter InputChannelCount metrics.Gauge OutputChannelCount metrics.Gauge IsConnected bool LastConnectTime time.Time StartTime time.Time LastConnectError string ErrorTime time.Time Healthy metrics.Healthcheck sync.RWMutex } var status Status var ( results chan string outputErrors chan error ) func init() { flag.Parse() } func setupMetrics() { status.InputEventCount = metrics.NewRegisteredMeter("core.input.events", metrics.DefaultRegistry) status.InputByteCount = metrics.NewRegisteredMeter("core.input.data", metrics.DefaultRegistry) status.OutputEventCount = metrics.NewRegisteredMeter("core.output.events", metrics.DefaultRegistry) status.OutputByteCount = metrics.NewRegisteredMeter("core.output.data", metrics.DefaultRegistry) status.ErrorCount = metrics.NewRegisteredMeter("errors", metrics.DefaultRegistry) status.InputChannelCount = metrics.NewRegisteredGauge("core.channel.input.events", metrics.DefaultRegistry) status.OutputChannelCount = metrics.NewRegisteredGauge("core.channel.output.events", metrics.DefaultRegistry) status.Healthy = metrics.NewHealthcheck(func(h metrics.Healthcheck) { if status.IsConnected { h.Healthy() } else { h.Unhealthy(errors.New("Event Forwarder is not connected")) } }) metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry) metrics.Register("connection_status", expvar.Func(func() interface{} { res := make(map[string]interface{}, 0) res["last_connect_time"] = status.LastConnectTime res["last_error_text"] = status.LastConnectError res["last_error_time"] = status.ErrorTime if status.IsConnected { res["connected"] = true res["uptime"] = time.Now().Sub(status.LastConnectTime).Seconds() } else { res["connected"] = false res["uptime"] = 0.0 } return res })) metrics.Register("uptime", expvar.Func(func() interface{} { return time.Now().Sub(status.StartTime).Seconds() })) metrics.Register("subscribed_events", expvar.Func(func() interface{} { return config.EventTypes })) results = make(chan string, outputChannelSize) outputErrors = make(chan error) status.StartTime = time.Now() } /* * Types */ type OutputHandler interface { Initialize(string) error Go(messages <-chan string, errorChan chan<- error) error String() string Statistics() interface{} Key() string } /* * worker */ // TODO: change this into an error channel func reportError(d string, errmsg string, err error) { status.ErrorCount.Mark(1) log.Debugf("%s when processing %s: %s", errmsg, d, err) } func reportBundleDetails(routingKey string, body []byte, headers amqp.Table) { log.Errorf("Error while processing message through routing key %s:", routingKey) var env *CbEnvironmentMsg env, err := createEnvMessage(headers) if err != nil { log.Errorf(" Message was received from sensor %d; hostname %s", env.Endpoint.GetSensorId(), env.Endpoint.GetSensorHostName()) } if len(body) < 4 { log.Info(" Message is less than 4 bytes long; malformed") } else { log.Info(" First four bytes of message were:") log.Errorf(" %s", hex.Dump(body[0:4])) } /* * We are going to store this bundle in the DebugStore */ if config.DebugFlag { h := md5.New() h.Write(body) var fullFilePath string fullFilePath = path.Join(config.DebugStore, fmt.Sprintf("/event-forwarder-%X", h.Sum(nil))) log.Debugf("Writing Bundle to disk: %s", fullFilePath) ioutil.WriteFile(fullFilePath, body, 0444) } } func monitorChannels(ticker *time.Ticker, inputChannel chan<- amqp.Delivery, outputChannel chan<- string) { for range ticker.C { status.InputChannelCount.Update(int64(len(inputChannel))) status.OutputChannelCount.Update(int64(len(outputChannel))) } } func processMessage(body []byte, routingKey, contentType string, headers amqp.Table, exchangeName string) { status.InputEventCount.Mark(1) status.InputByteCount.Mark(int64(len(body))) var err error var msgs []map[string]interface{} // // Process message based on ContentType // //log.Errorf("PROCESS MESSAGE CALLED ROUTINGKEY = %s contentType = %s exchange = %s ",routingKey, contentType, exchangeName) if contentType == "application/zip" { msgs, err = ProcessRawZipBundle(routingKey, body, headers) if err != nil { reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process raw zip bundle", err) return } } else if contentType == "application/protobuf" { // if we receive a protobuf through the raw sensor exchange, it's actually a protobuf "bundle" and not a // single protobuf if exchangeName == "api.rawsensordata" { msgs, err = ProcessProtobufBundle(routingKey, body, headers)
reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process body", err) return } else if msg != nil { msgs = make([]map[string]interface{}, 0, 1) msgs = append(msgs, msg) } } } else if contentType == "application/json" { // Note for simplicity in implementation we are assuming the JSON output by the Cb server // is an object (that is, the top level JSON object is a dictionary and not an array or scalar value) var msg map[string]interface{} decoder := json.NewDecoder(bytes.NewReader(body)) // Ensure that we decode numbers in the JSON as integers and *not* float64s decoder.UseNumber() if err := decoder.Decode(&msg); err != nil { reportError(string(body), "Received error when unmarshaling JSON body", err) return } msgs, err = ProcessJSONMessage(msg, routingKey) } else { reportError(string(body), "Unknown content-type", errors.New(contentType)) return } for _, msg := range msgs { err = outputMessage(msg) if err != nil { reportError(string(body), "Error marshaling message", err) } } } func outputMessage(msg map[string]interface{}) error { var err error // // Marshal result into the correct output format // msg["cb_server"] = config.ServerName // Remove keys that have been configured to be removed for _, v := range config.RemoveFromOutput { delete(msg, v) } var outmsg string switch config.OutputFormat { case JSONOutputFormat: var b []byte b, err = json.Marshal(msg) outmsg = string(b) case LEEFOutputFormat: outmsg, err = Encode(msg) default: panic("Impossible: invalid output_format, exiting immediately") } if len(outmsg) > 0 && err == nil { status.OutputEventCount.Mark(1) status.OutputByteCount.Mark(int64(len(outmsg))) results <- string(outmsg) } else { return err } return nil } func splitDelivery(deliveries <-chan amqp.Delivery, messages chan<- amqp.Delivery) { defer close(messages) for delivery := range deliveries { messages <- delivery } } func worker(deliveries <-chan amqp.Delivery) { defer wg.Done() for delivery := range deliveries { processMessage(delivery.Body, delivery.RoutingKey, delivery.ContentType, delivery.Headers, delivery.Exchange) } log.Info("Worker exiting") } func logFileProcessingLoop() <-chan error { errChan := make(chan error) spawnTailer := func(fName string, label string) { log.Debugf("Spawn tailer: %s", fName) _, deliveries, err := NewFileConsumer(fName) if err != nil { status.LastConnectError = err.Error() status.ErrorTime = time.Now() errChan <- err } for delivery := range deliveries { log.Debugf("Trying to deliver log message %s", delivery) msgMap := make(map[string]interface{}) msgMap["message"] = strings.TrimSuffix(delivery, "\n") msgMap["type"] = label outputMessage(msgMap) } } /* maps audit log labels to event types AUDIT_TYPES = { "cb-audit-isolation": Audit_Log_Isolation, "cb-audit-banning": Audit_Log_Banning, "cb-audit-live-response": Audit_Log_Liveresponse, "cb-audit-useractivity": Audit_Log_Useractivity } */ go spawnTailer("/var/log/cb/audit/live-response.log", "audit.log.liveresponse") go spawnTailer("/var/log/cb/audit/banning.log", "audit.log.banning") go spawnTailer("/var/log/cb/audit/isolation.log", "audit.log.isolation") go spawnTailer("/var/log/cb/audit/useractivity.log", "audit.log.useractivity") return errChan } func messageProcessingLoop(uri, queueName, consumerTag string) error { var dialer AMQPDialer if config.CannedInput { md := NewMockAMQPDialer() mockChan, _ := md.Connection.Channel() go RunCannedData(mockChan) dialer = md } else { dialer = StreadwayAMQPDialer{} } var c *Consumer = NewConsumer(uri, queueName, consumerTag, config.UseRawSensorExchange, config.EventTypes, dialer) messages := make(chan amqp.Delivery, inputChannelSize) deliveries, err := c.Connect() if err != nil { status.LastConnectError = err.Error() status.ErrorTime = time.Now() return err } status.LastConnectTime = time.Now() status.IsConnected = true numProcessors := config.NumProcessors log.Infof("Starting %d message processors\n", numProcessors) wg.Add(numProcessors) if config.RunMetrics { go monitorChannels(time.NewTicker(100*time.Millisecond), messages, results) } go splitDelivery(deliveries, messages) for i := 0; i < numProcessors; i++ { go worker(messages) } for { select { case outputError := <-outputErrors: log.Errorf("ERROR during output: %s", outputError.Error()) // hack to exit if the error happens while we are writing to a file if config.OutputType == FileOutputType || config.OutputType == SplunkOutputType || config.OutputType == HTTPOutputType || config.OutputType == S3OutputType || config.OutputType == SyslogOutputType { log.Error("File output error; exiting immediately.") c.Shutdown() wg.Wait() os.Exit(1) } case closeError := <-c.connectionErrors: status.IsConnected = false status.LastConnectError = closeError.Error() status.ErrorTime = time.Now() log.Errorf("Connection error: %s", closeError.Error()) // This assumes that after the error, workers don't get any more messagesa nd will eventually return log.Info("Waiting for all workers to exit") wg.Wait() log.Info("All workers have exited") return closeError } } log.Info("Loop exited for unknown reason") c.Shutdown() wg.Wait() return nil } func startOutputs() error { // Configure the specific output. // Valid options are: 'udp', 'tcp', 'file', 's3', 'syslog' ,"http",'splunk' var outputHandler OutputHandler parameters := config.OutputParameters switch config.OutputType { case FileOutputType: outputHandler = &FileOutput{} case TCPOutputType: outputHandler = &NetOutput{} parameters = "tcp:" + parameters case UDPOutputType: outputHandler = &NetOutput{} parameters = "udp:" + parameters case S3OutputType: outputHandler = &BundledOutput{behavior: &S3Behavior{}} case SyslogOutputType: outputHandler = &SyslogOutput{} case HTTPOutputType: outputHandler = &BundledOutput{behavior: &HTTPBehavior{}} case SplunkOutputType: outputHandler = &BundledOutput{behavior: &SplunkBehavior{}} case KafkaOutputType: outputHandler = &KafkaOutput{} default: return fmt.Errorf("No valid output handler found (%d)", config.OutputType) } err := outputHandler.Initialize(parameters) if err != nil { return err } metrics.Register("output_status", expvar.Func(func() interface{} { ret := make(map[string]interface{}) ret[outputHandler.Key()] = outputHandler.Statistics() switch config.OutputFormat { case LEEFOutputFormat: ret["format"] = "leef" case JSONOutputFormat: ret["format"] = "json" } switch config.OutputType { case FileOutputType: ret["type"] = "file" case UDPOutputType: ret["type"] = "net" case TCPOutputType: ret["type"] = "net" case S3OutputType: ret["type"] = "s3" case HTTPOutputType: ret["type"] = "http" case SplunkOutputType: ret["type"] = "splunk" } return ret })) log.Infof("Initialized output: %s\n", outputHandler.String()) return outputHandler.Go(results, outputErrors) } func main() { hostname, err := os.Hostname() if err != nil { log.Fatal(err) } configLocation := "/etc/cb/integrations/event-forwarder/cb-event-forwarder.conf" if flag.NArg() > 0 { configLocation = flag.Arg(0) } log.Infof("Using config file %s\n", configLocation) config, err = ParseConfig(configLocation) if err != nil { log.Fatal(err) } if !config.RunMetrics { log.Infof("Running without metrics") metrics.UseNilMetrics = true } else { metrics.UseNilMetrics = false log.Infof("Running with metrics") } setupMetrics() if *checkConfiguration { if err := startOutputs(); err != nil { log.Fatal(err) } os.Exit(0) } defaultPidFileLocation := "/run/cb/integrations/cb-event-forwarder/cb-event-forwarder.pid" if *pidFileLocation == "" { *pidFileLocation = defaultPidFileLocation } log.Infof("PID file will be written to %s\n", *pidFileLocation) pidfile.SetPidfilePath(*pidFileLocation) err = pidfile.Write() if err != nil { log.Warn("Could not write PID file: %s\n", err) } addrs, err := net.InterfaceAddrs() if err != nil { log.Fatal("Could not get IP addresses") } log.Infof("cb-event-forwarder version %s starting", version) exportedVersion := &expvar.String{} metrics.Register("version", exportedVersion) if *debug { exportedVersion.Set(version + " (debugging on)") log.Debugf("*** Debugging enabled: messages may be sent via http://%s:%d/debug/sendmessage ***", hostname, config.HTTPServerPort) log.SetLevel(log.DebugLevel) } else { exportedVersion.Set(version) } metrics.Register("debug", expvar.Func(func() interface{} { return *debug })) for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { log.Infof("Interface address %s", ipnet.IP.String()) } } log.Infof("Configured to capture events: %v", config.EventTypes) if err := startOutputs(); err != nil { log.Fatalf("Could not startOutputs: %s", err) } if *debug { http.HandleFunc("/debug/sendmessage", func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { msg := make([]byte, r.ContentLength) _, err := r.Body.Read(msg) var parsedMsg map[string]interface{} err = json.Unmarshal(msg, &parsedMsg) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } err = outputMessage(parsedMsg) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } log.Errorf("Sent test message: %s\n", string(msg)) } else { err = outputMessage(map[string]interface{}{ "type": "debug.message", "message": fmt.Sprintf("Debugging test message sent at %s", time.Now().String()), }) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } log.Info("Sent test debugging message") } errMsg, _ := json.Marshal(map[string]string{"status": "success"}) _, _ = w.Write(errMsg) }) } http.HandleFunc("/debug/healthcheck", func(w http.ResponseWriter, r *http.Request) { if !status.IsConnected { payload, _ := json.Marshal(map[string]interface{}{"status": "FORWARDER IS NOT CONNECTED", "error": status.LastConnectError}) http.Error(w, string(payload), http.StatusNetworkAuthenticationRequired) } else { payload, _ := json.Marshal(map[string]interface{}{"status": "FORWARDER IS CONNECTED"}) w.Write(payload) } }) go http.ListenAndServe(fmt.Sprintf(":%d", config.HTTPServerPort), nil) queueName := fmt.Sprintf("cb-event-forwarder:%s:%d", hostname, os.Getpid()) if config.AMQPQueueName != "" { queueName = config.AMQPQueueName } go func(consumerNumber int) { log.Infof("Starting AMQP loop %d to %s on queue %s", consumerNumber, config.AMQPURL(), queueName) for { err := messageProcessingLoop(config.AMQPURL(), queueName, fmt.Sprintf("go-event-consumer-%d", consumerNumber)) log.Infof("AMQP loop %d exited: %s. Sleeping for 30 seconds then retrying.", consumerNumber, err) time.Sleep(30 * time.Second) } }(1) if config.AuditLog == true { log.Info("starting log file processing loop") go func() { errChan := logFileProcessingLoop() for { select { case err := <-errChan: log.Infof("%v", err) } } }() } else { log.Info("Not starting file processing loop") } //Try to send to metrics to carbon if configured to do so if config.CarbonMetricsEndpoint != nil && config.RunMetrics { //log.Infof("Trying to resolve TCP ADDR for %s\n", *config.CarbonMetricsEndpoint) addr, err := net.ResolveTCPAddr("tcp4", *config.CarbonMetricsEndpoint) if err != nil { log.Panicf("Failing resolving carbon endpoint %v", err) } go graphite.Graphite(metrics.DefaultRegistry, 1*time.Second, config.MetricTag, addr) log.Infof("Sending metrics to graphite") } exp.Exp(metrics.DefaultRegistry) for { time.Sleep(30 * time.Second) } log.Info("cb-event-forwarder exiting") }
//log.Infof("Process Protobuf bundle returned %d messages and error = %v",len(msgs),err) } else { msg, err := ProcessProtobufMessage(routingKey, body, headers) if err != nil {
random_line_split
main.go
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "errors" "expvar" "flag" "fmt" "io/ioutil" "net" "net/http" "os" "path" "strings" "sync" "time" graphite "github.com/cyberdelia/go-metrics-graphite" "github.com/facebookgo/pidfile" "github.com/rcrowley/go-metrics" "github.com/rcrowley/go-metrics/exp" log "github.com/sirupsen/logrus" "github.com/streadway/amqp" _ "net/http/pprof" ) var ( pidFileLocation = flag.String("pid-file", "", "PID file location") checkConfiguration = flag.Bool("check", false, "Check the configuration file and exit") debug = flag.Bool("debug", false, "Enable debugging mode") ) var version = "3.7.0" var inputChannelSize = 100000 var outputChannelSize = 1000000 var wg sync.WaitGroup var config Configuration type Status struct { InputEventCount metrics.Meter InputByteCount metrics.Meter OutputEventCount metrics.Meter OutputByteCount metrics.Meter ErrorCount metrics.Meter InputChannelCount metrics.Gauge OutputChannelCount metrics.Gauge IsConnected bool LastConnectTime time.Time StartTime time.Time LastConnectError string ErrorTime time.Time Healthy metrics.Healthcheck sync.RWMutex } var status Status var ( results chan string outputErrors chan error ) func init() { flag.Parse() } func setupMetrics() { status.InputEventCount = metrics.NewRegisteredMeter("core.input.events", metrics.DefaultRegistry) status.InputByteCount = metrics.NewRegisteredMeter("core.input.data", metrics.DefaultRegistry) status.OutputEventCount = metrics.NewRegisteredMeter("core.output.events", metrics.DefaultRegistry) status.OutputByteCount = metrics.NewRegisteredMeter("core.output.data", metrics.DefaultRegistry) status.ErrorCount = metrics.NewRegisteredMeter("errors", metrics.DefaultRegistry) status.InputChannelCount = metrics.NewRegisteredGauge("core.channel.input.events", metrics.DefaultRegistry) status.OutputChannelCount = metrics.NewRegisteredGauge("core.channel.output.events", metrics.DefaultRegistry) status.Healthy = metrics.NewHealthcheck(func(h metrics.Healthcheck) { if status.IsConnected { h.Healthy() } else { h.Unhealthy(errors.New("Event Forwarder is not connected")) } }) metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry) metrics.Register("connection_status", expvar.Func(func() interface{} { res := make(map[string]interface{}, 0) res["last_connect_time"] = status.LastConnectTime res["last_error_text"] = status.LastConnectError res["last_error_time"] = status.ErrorTime if status.IsConnected { res["connected"] = true res["uptime"] = time.Now().Sub(status.LastConnectTime).Seconds() } else { res["connected"] = false res["uptime"] = 0.0 } return res })) metrics.Register("uptime", expvar.Func(func() interface{} { return time.Now().Sub(status.StartTime).Seconds() })) metrics.Register("subscribed_events", expvar.Func(func() interface{} { return config.EventTypes })) results = make(chan string, outputChannelSize) outputErrors = make(chan error) status.StartTime = time.Now() } /* * Types */ type OutputHandler interface { Initialize(string) error Go(messages <-chan string, errorChan chan<- error) error String() string Statistics() interface{} Key() string } /* * worker */ // TODO: change this into an error channel func reportError(d string, errmsg string, err error) { status.ErrorCount.Mark(1) log.Debugf("%s when processing %s: %s", errmsg, d, err) } func reportBundleDetails(routingKey string, body []byte, headers amqp.Table) { log.Errorf("Error while processing message through routing key %s:", routingKey) var env *CbEnvironmentMsg env, err := createEnvMessage(headers) if err != nil { log.Errorf(" Message was received from sensor %d; hostname %s", env.Endpoint.GetSensorId(), env.Endpoint.GetSensorHostName()) } if len(body) < 4 { log.Info(" Message is less than 4 bytes long; malformed") } else { log.Info(" First four bytes of message were:") log.Errorf(" %s", hex.Dump(body[0:4])) } /* * We are going to store this bundle in the DebugStore */ if config.DebugFlag { h := md5.New() h.Write(body) var fullFilePath string fullFilePath = path.Join(config.DebugStore, fmt.Sprintf("/event-forwarder-%X", h.Sum(nil))) log.Debugf("Writing Bundle to disk: %s", fullFilePath) ioutil.WriteFile(fullFilePath, body, 0444) } } func monitorChannels(ticker *time.Ticker, inputChannel chan<- amqp.Delivery, outputChannel chan<- string) { for range ticker.C
} func processMessage(body []byte, routingKey, contentType string, headers amqp.Table, exchangeName string) { status.InputEventCount.Mark(1) status.InputByteCount.Mark(int64(len(body))) var err error var msgs []map[string]interface{} // // Process message based on ContentType // //log.Errorf("PROCESS MESSAGE CALLED ROUTINGKEY = %s contentType = %s exchange = %s ",routingKey, contentType, exchangeName) if contentType == "application/zip" { msgs, err = ProcessRawZipBundle(routingKey, body, headers) if err != nil { reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process raw zip bundle", err) return } } else if contentType == "application/protobuf" { // if we receive a protobuf through the raw sensor exchange, it's actually a protobuf "bundle" and not a // single protobuf if exchangeName == "api.rawsensordata" { msgs, err = ProcessProtobufBundle(routingKey, body, headers) //log.Infof("Process Protobuf bundle returned %d messages and error = %v",len(msgs),err) } else { msg, err := ProcessProtobufMessage(routingKey, body, headers) if err != nil { reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process body", err) return } else if msg != nil { msgs = make([]map[string]interface{}, 0, 1) msgs = append(msgs, msg) } } } else if contentType == "application/json" { // Note for simplicity in implementation we are assuming the JSON output by the Cb server // is an object (that is, the top level JSON object is a dictionary and not an array or scalar value) var msg map[string]interface{} decoder := json.NewDecoder(bytes.NewReader(body)) // Ensure that we decode numbers in the JSON as integers and *not* float64s decoder.UseNumber() if err := decoder.Decode(&msg); err != nil { reportError(string(body), "Received error when unmarshaling JSON body", err) return } msgs, err = ProcessJSONMessage(msg, routingKey) } else { reportError(string(body), "Unknown content-type", errors.New(contentType)) return } for _, msg := range msgs { err = outputMessage(msg) if err != nil { reportError(string(body), "Error marshaling message", err) } } } func outputMessage(msg map[string]interface{}) error { var err error // // Marshal result into the correct output format // msg["cb_server"] = config.ServerName // Remove keys that have been configured to be removed for _, v := range config.RemoveFromOutput { delete(msg, v) } var outmsg string switch config.OutputFormat { case JSONOutputFormat: var b []byte b, err = json.Marshal(msg) outmsg = string(b) case LEEFOutputFormat: outmsg, err = Encode(msg) default: panic("Impossible: invalid output_format, exiting immediately") } if len(outmsg) > 0 && err == nil { status.OutputEventCount.Mark(1) status.OutputByteCount.Mark(int64(len(outmsg))) results <- string(outmsg) } else { return err } return nil } func splitDelivery(deliveries <-chan amqp.Delivery, messages chan<- amqp.Delivery) { defer close(messages) for delivery := range deliveries { messages <- delivery } } func worker(deliveries <-chan amqp.Delivery) { defer wg.Done() for delivery := range deliveries { processMessage(delivery.Body, delivery.RoutingKey, delivery.ContentType, delivery.Headers, delivery.Exchange) } log.Info("Worker exiting") } func logFileProcessingLoop() <-chan error { errChan := make(chan error) spawnTailer := func(fName string, label string) { log.Debugf("Spawn tailer: %s", fName) _, deliveries, err := NewFileConsumer(fName) if err != nil { status.LastConnectError = err.Error() status.ErrorTime = time.Now() errChan <- err } for delivery := range deliveries { log.Debugf("Trying to deliver log message %s", delivery) msgMap := make(map[string]interface{}) msgMap["message"] = strings.TrimSuffix(delivery, "\n") msgMap["type"] = label outputMessage(msgMap) } } /* maps audit log labels to event types AUDIT_TYPES = { "cb-audit-isolation": Audit_Log_Isolation, "cb-audit-banning": Audit_Log_Banning, "cb-audit-live-response": Audit_Log_Liveresponse, "cb-audit-useractivity": Audit_Log_Useractivity } */ go spawnTailer("/var/log/cb/audit/live-response.log", "audit.log.liveresponse") go spawnTailer("/var/log/cb/audit/banning.log", "audit.log.banning") go spawnTailer("/var/log/cb/audit/isolation.log", "audit.log.isolation") go spawnTailer("/var/log/cb/audit/useractivity.log", "audit.log.useractivity") return errChan } func messageProcessingLoop(uri, queueName, consumerTag string) error { var dialer AMQPDialer if config.CannedInput { md := NewMockAMQPDialer() mockChan, _ := md.Connection.Channel() go RunCannedData(mockChan) dialer = md } else { dialer = StreadwayAMQPDialer{} } var c *Consumer = NewConsumer(uri, queueName, consumerTag, config.UseRawSensorExchange, config.EventTypes, dialer) messages := make(chan amqp.Delivery, inputChannelSize) deliveries, err := c.Connect() if err != nil { status.LastConnectError = err.Error() status.ErrorTime = time.Now() return err } status.LastConnectTime = time.Now() status.IsConnected = true numProcessors := config.NumProcessors log.Infof("Starting %d message processors\n", numProcessors) wg.Add(numProcessors) if config.RunMetrics { go monitorChannels(time.NewTicker(100*time.Millisecond), messages, results) } go splitDelivery(deliveries, messages) for i := 0; i < numProcessors; i++ { go worker(messages) } for { select { case outputError := <-outputErrors: log.Errorf("ERROR during output: %s", outputError.Error()) // hack to exit if the error happens while we are writing to a file if config.OutputType == FileOutputType || config.OutputType == SplunkOutputType || config.OutputType == HTTPOutputType || config.OutputType == S3OutputType || config.OutputType == SyslogOutputType { log.Error("File output error; exiting immediately.") c.Shutdown() wg.Wait() os.Exit(1) } case closeError := <-c.connectionErrors: status.IsConnected = false status.LastConnectError = closeError.Error() status.ErrorTime = time.Now() log.Errorf("Connection error: %s", closeError.Error()) // This assumes that after the error, workers don't get any more messagesa nd will eventually return log.Info("Waiting for all workers to exit") wg.Wait() log.Info("All workers have exited") return closeError } } log.Info("Loop exited for unknown reason") c.Shutdown() wg.Wait() return nil } func startOutputs() error { // Configure the specific output. // Valid options are: 'udp', 'tcp', 'file', 's3', 'syslog' ,"http",'splunk' var outputHandler OutputHandler parameters := config.OutputParameters switch config.OutputType { case FileOutputType: outputHandler = &FileOutput{} case TCPOutputType: outputHandler = &NetOutput{} parameters = "tcp:" + parameters case UDPOutputType: outputHandler = &NetOutput{} parameters = "udp:" + parameters case S3OutputType: outputHandler = &BundledOutput{behavior: &S3Behavior{}} case SyslogOutputType: outputHandler = &SyslogOutput{} case HTTPOutputType: outputHandler = &BundledOutput{behavior: &HTTPBehavior{}} case SplunkOutputType: outputHandler = &BundledOutput{behavior: &SplunkBehavior{}} case KafkaOutputType: outputHandler = &KafkaOutput{} default: return fmt.Errorf("No valid output handler found (%d)", config.OutputType) } err := outputHandler.Initialize(parameters) if err != nil { return err } metrics.Register("output_status", expvar.Func(func() interface{} { ret := make(map[string]interface{}) ret[outputHandler.Key()] = outputHandler.Statistics() switch config.OutputFormat { case LEEFOutputFormat: ret["format"] = "leef" case JSONOutputFormat: ret["format"] = "json" } switch config.OutputType { case FileOutputType: ret["type"] = "file" case UDPOutputType: ret["type"] = "net" case TCPOutputType: ret["type"] = "net" case S3OutputType: ret["type"] = "s3" case HTTPOutputType: ret["type"] = "http" case SplunkOutputType: ret["type"] = "splunk" } return ret })) log.Infof("Initialized output: %s\n", outputHandler.String()) return outputHandler.Go(results, outputErrors) } func main() { hostname, err := os.Hostname() if err != nil { log.Fatal(err) } configLocation := "/etc/cb/integrations/event-forwarder/cb-event-forwarder.conf" if flag.NArg() > 0 { configLocation = flag.Arg(0) } log.Infof("Using config file %s\n", configLocation) config, err = ParseConfig(configLocation) if err != nil { log.Fatal(err) } if !config.RunMetrics { log.Infof("Running without metrics") metrics.UseNilMetrics = true } else { metrics.UseNilMetrics = false log.Infof("Running with metrics") } setupMetrics() if *checkConfiguration { if err := startOutputs(); err != nil { log.Fatal(err) } os.Exit(0) } defaultPidFileLocation := "/run/cb/integrations/cb-event-forwarder/cb-event-forwarder.pid" if *pidFileLocation == "" { *pidFileLocation = defaultPidFileLocation } log.Infof("PID file will be written to %s\n", *pidFileLocation) pidfile.SetPidfilePath(*pidFileLocation) err = pidfile.Write() if err != nil { log.Warn("Could not write PID file: %s\n", err) } addrs, err := net.InterfaceAddrs() if err != nil { log.Fatal("Could not get IP addresses") } log.Infof("cb-event-forwarder version %s starting", version) exportedVersion := &expvar.String{} metrics.Register("version", exportedVersion) if *debug { exportedVersion.Set(version + " (debugging on)") log.Debugf("*** Debugging enabled: messages may be sent via http://%s:%d/debug/sendmessage ***", hostname, config.HTTPServerPort) log.SetLevel(log.DebugLevel) } else { exportedVersion.Set(version) } metrics.Register("debug", expvar.Func(func() interface{} { return *debug })) for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { log.Infof("Interface address %s", ipnet.IP.String()) } } log.Infof("Configured to capture events: %v", config.EventTypes) if err := startOutputs(); err != nil { log.Fatalf("Could not startOutputs: %s", err) } if *debug { http.HandleFunc("/debug/sendmessage", func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { msg := make([]byte, r.ContentLength) _, err := r.Body.Read(msg) var parsedMsg map[string]interface{} err = json.Unmarshal(msg, &parsedMsg) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } err = outputMessage(parsedMsg) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } log.Errorf("Sent test message: %s\n", string(msg)) } else { err = outputMessage(map[string]interface{}{ "type": "debug.message", "message": fmt.Sprintf("Debugging test message sent at %s", time.Now().String()), }) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } log.Info("Sent test debugging message") } errMsg, _ := json.Marshal(map[string]string{"status": "success"}) _, _ = w.Write(errMsg) }) } http.HandleFunc("/debug/healthcheck", func(w http.ResponseWriter, r *http.Request) { if !status.IsConnected { payload, _ := json.Marshal(map[string]interface{}{"status": "FORWARDER IS NOT CONNECTED", "error": status.LastConnectError}) http.Error(w, string(payload), http.StatusNetworkAuthenticationRequired) } else { payload, _ := json.Marshal(map[string]interface{}{"status": "FORWARDER IS CONNECTED"}) w.Write(payload) } }) go http.ListenAndServe(fmt.Sprintf(":%d", config.HTTPServerPort), nil) queueName := fmt.Sprintf("cb-event-forwarder:%s:%d", hostname, os.Getpid()) if config.AMQPQueueName != "" { queueName = config.AMQPQueueName } go func(consumerNumber int) { log.Infof("Starting AMQP loop %d to %s on queue %s", consumerNumber, config.AMQPURL(), queueName) for { err := messageProcessingLoop(config.AMQPURL(), queueName, fmt.Sprintf("go-event-consumer-%d", consumerNumber)) log.Infof("AMQP loop %d exited: %s. Sleeping for 30 seconds then retrying.", consumerNumber, err) time.Sleep(30 * time.Second) } }(1) if config.AuditLog == true { log.Info("starting log file processing loop") go func() { errChan := logFileProcessingLoop() for { select { case err := <-errChan: log.Infof("%v", err) } } }() } else { log.Info("Not starting file processing loop") } //Try to send to metrics to carbon if configured to do so if config.CarbonMetricsEndpoint != nil && config.RunMetrics { //log.Infof("Trying to resolve TCP ADDR for %s\n", *config.CarbonMetricsEndpoint) addr, err := net.ResolveTCPAddr("tcp4", *config.CarbonMetricsEndpoint) if err != nil { log.Panicf("Failing resolving carbon endpoint %v", err) } go graphite.Graphite(metrics.DefaultRegistry, 1*time.Second, config.MetricTag, addr) log.Infof("Sending metrics to graphite") } exp.Exp(metrics.DefaultRegistry) for { time.Sleep(30 * time.Second) } log.Info("cb-event-forwarder exiting") }
{ status.InputChannelCount.Update(int64(len(inputChannel))) status.OutputChannelCount.Update(int64(len(outputChannel))) }
conditional_block
main.go
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "errors" "expvar" "flag" "fmt" "io/ioutil" "net" "net/http" "os" "path" "strings" "sync" "time" graphite "github.com/cyberdelia/go-metrics-graphite" "github.com/facebookgo/pidfile" "github.com/rcrowley/go-metrics" "github.com/rcrowley/go-metrics/exp" log "github.com/sirupsen/logrus" "github.com/streadway/amqp" _ "net/http/pprof" ) var ( pidFileLocation = flag.String("pid-file", "", "PID file location") checkConfiguration = flag.Bool("check", false, "Check the configuration file and exit") debug = flag.Bool("debug", false, "Enable debugging mode") ) var version = "3.7.0" var inputChannelSize = 100000 var outputChannelSize = 1000000 var wg sync.WaitGroup var config Configuration type Status struct { InputEventCount metrics.Meter InputByteCount metrics.Meter OutputEventCount metrics.Meter OutputByteCount metrics.Meter ErrorCount metrics.Meter InputChannelCount metrics.Gauge OutputChannelCount metrics.Gauge IsConnected bool LastConnectTime time.Time StartTime time.Time LastConnectError string ErrorTime time.Time Healthy metrics.Healthcheck sync.RWMutex } var status Status var ( results chan string outputErrors chan error ) func init() { flag.Parse() } func setupMetrics() { status.InputEventCount = metrics.NewRegisteredMeter("core.input.events", metrics.DefaultRegistry) status.InputByteCount = metrics.NewRegisteredMeter("core.input.data", metrics.DefaultRegistry) status.OutputEventCount = metrics.NewRegisteredMeter("core.output.events", metrics.DefaultRegistry) status.OutputByteCount = metrics.NewRegisteredMeter("core.output.data", metrics.DefaultRegistry) status.ErrorCount = metrics.NewRegisteredMeter("errors", metrics.DefaultRegistry) status.InputChannelCount = metrics.NewRegisteredGauge("core.channel.input.events", metrics.DefaultRegistry) status.OutputChannelCount = metrics.NewRegisteredGauge("core.channel.output.events", metrics.DefaultRegistry) status.Healthy = metrics.NewHealthcheck(func(h metrics.Healthcheck) { if status.IsConnected { h.Healthy() } else { h.Unhealthy(errors.New("Event Forwarder is not connected")) } }) metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry) metrics.Register("connection_status", expvar.Func(func() interface{} { res := make(map[string]interface{}, 0) res["last_connect_time"] = status.LastConnectTime res["last_error_text"] = status.LastConnectError res["last_error_time"] = status.ErrorTime if status.IsConnected { res["connected"] = true res["uptime"] = time.Now().Sub(status.LastConnectTime).Seconds() } else { res["connected"] = false res["uptime"] = 0.0 } return res })) metrics.Register("uptime", expvar.Func(func() interface{} { return time.Now().Sub(status.StartTime).Seconds() })) metrics.Register("subscribed_events", expvar.Func(func() interface{} { return config.EventTypes })) results = make(chan string, outputChannelSize) outputErrors = make(chan error) status.StartTime = time.Now() } /* * Types */ type OutputHandler interface { Initialize(string) error Go(messages <-chan string, errorChan chan<- error) error String() string Statistics() interface{} Key() string } /* * worker */ // TODO: change this into an error channel func reportError(d string, errmsg string, err error) { status.ErrorCount.Mark(1) log.Debugf("%s when processing %s: %s", errmsg, d, err) } func reportBundleDetails(routingKey string, body []byte, headers amqp.Table) { log.Errorf("Error while processing message through routing key %s:", routingKey) var env *CbEnvironmentMsg env, err := createEnvMessage(headers) if err != nil { log.Errorf(" Message was received from sensor %d; hostname %s", env.Endpoint.GetSensorId(), env.Endpoint.GetSensorHostName()) } if len(body) < 4 { log.Info(" Message is less than 4 bytes long; malformed") } else { log.Info(" First four bytes of message were:") log.Errorf(" %s", hex.Dump(body[0:4])) } /* * We are going to store this bundle in the DebugStore */ if config.DebugFlag { h := md5.New() h.Write(body) var fullFilePath string fullFilePath = path.Join(config.DebugStore, fmt.Sprintf("/event-forwarder-%X", h.Sum(nil))) log.Debugf("Writing Bundle to disk: %s", fullFilePath) ioutil.WriteFile(fullFilePath, body, 0444) } } func monitorChannels(ticker *time.Ticker, inputChannel chan<- amqp.Delivery, outputChannel chan<- string) { for range ticker.C { status.InputChannelCount.Update(int64(len(inputChannel))) status.OutputChannelCount.Update(int64(len(outputChannel))) } } func processMessage(body []byte, routingKey, contentType string, headers amqp.Table, exchangeName string) { status.InputEventCount.Mark(1) status.InputByteCount.Mark(int64(len(body))) var err error var msgs []map[string]interface{} // // Process message based on ContentType // //log.Errorf("PROCESS MESSAGE CALLED ROUTINGKEY = %s contentType = %s exchange = %s ",routingKey, contentType, exchangeName) if contentType == "application/zip" { msgs, err = ProcessRawZipBundle(routingKey, body, headers) if err != nil { reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process raw zip bundle", err) return } } else if contentType == "application/protobuf" { // if we receive a protobuf through the raw sensor exchange, it's actually a protobuf "bundle" and not a // single protobuf if exchangeName == "api.rawsensordata" { msgs, err = ProcessProtobufBundle(routingKey, body, headers) //log.Infof("Process Protobuf bundle returned %d messages and error = %v",len(msgs),err) } else { msg, err := ProcessProtobufMessage(routingKey, body, headers) if err != nil { reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process body", err) return } else if msg != nil { msgs = make([]map[string]interface{}, 0, 1) msgs = append(msgs, msg) } } } else if contentType == "application/json" { // Note for simplicity in implementation we are assuming the JSON output by the Cb server // is an object (that is, the top level JSON object is a dictionary and not an array or scalar value) var msg map[string]interface{} decoder := json.NewDecoder(bytes.NewReader(body)) // Ensure that we decode numbers in the JSON as integers and *not* float64s decoder.UseNumber() if err := decoder.Decode(&msg); err != nil { reportError(string(body), "Received error when unmarshaling JSON body", err) return } msgs, err = ProcessJSONMessage(msg, routingKey) } else { reportError(string(body), "Unknown content-type", errors.New(contentType)) return } for _, msg := range msgs { err = outputMessage(msg) if err != nil { reportError(string(body), "Error marshaling message", err) } } } func outputMessage(msg map[string]interface{}) error { var err error // // Marshal result into the correct output format // msg["cb_server"] = config.ServerName // Remove keys that have been configured to be removed for _, v := range config.RemoveFromOutput { delete(msg, v) } var outmsg string switch config.OutputFormat { case JSONOutputFormat: var b []byte b, err = json.Marshal(msg) outmsg = string(b) case LEEFOutputFormat: outmsg, err = Encode(msg) default: panic("Impossible: invalid output_format, exiting immediately") } if len(outmsg) > 0 && err == nil { status.OutputEventCount.Mark(1) status.OutputByteCount.Mark(int64(len(outmsg))) results <- string(outmsg) } else { return err } return nil } func splitDelivery(deliveries <-chan amqp.Delivery, messages chan<- amqp.Delivery) { defer close(messages) for delivery := range deliveries { messages <- delivery } } func worker(deliveries <-chan amqp.Delivery) { defer wg.Done() for delivery := range deliveries { processMessage(delivery.Body, delivery.RoutingKey, delivery.ContentType, delivery.Headers, delivery.Exchange) } log.Info("Worker exiting") } func logFileProcessingLoop() <-chan error { errChan := make(chan error) spawnTailer := func(fName string, label string) { log.Debugf("Spawn tailer: %s", fName) _, deliveries, err := NewFileConsumer(fName) if err != nil { status.LastConnectError = err.Error() status.ErrorTime = time.Now() errChan <- err } for delivery := range deliveries { log.Debugf("Trying to deliver log message %s", delivery) msgMap := make(map[string]interface{}) msgMap["message"] = strings.TrimSuffix(delivery, "\n") msgMap["type"] = label outputMessage(msgMap) } } /* maps audit log labels to event types AUDIT_TYPES = { "cb-audit-isolation": Audit_Log_Isolation, "cb-audit-banning": Audit_Log_Banning, "cb-audit-live-response": Audit_Log_Liveresponse, "cb-audit-useractivity": Audit_Log_Useractivity } */ go spawnTailer("/var/log/cb/audit/live-response.log", "audit.log.liveresponse") go spawnTailer("/var/log/cb/audit/banning.log", "audit.log.banning") go spawnTailer("/var/log/cb/audit/isolation.log", "audit.log.isolation") go spawnTailer("/var/log/cb/audit/useractivity.log", "audit.log.useractivity") return errChan } func messageProcessingLoop(uri, queueName, consumerTag string) error
func startOutputs() error { // Configure the specific output. // Valid options are: 'udp', 'tcp', 'file', 's3', 'syslog' ,"http",'splunk' var outputHandler OutputHandler parameters := config.OutputParameters switch config.OutputType { case FileOutputType: outputHandler = &FileOutput{} case TCPOutputType: outputHandler = &NetOutput{} parameters = "tcp:" + parameters case UDPOutputType: outputHandler = &NetOutput{} parameters = "udp:" + parameters case S3OutputType: outputHandler = &BundledOutput{behavior: &S3Behavior{}} case SyslogOutputType: outputHandler = &SyslogOutput{} case HTTPOutputType: outputHandler = &BundledOutput{behavior: &HTTPBehavior{}} case SplunkOutputType: outputHandler = &BundledOutput{behavior: &SplunkBehavior{}} case KafkaOutputType: outputHandler = &KafkaOutput{} default: return fmt.Errorf("No valid output handler found (%d)", config.OutputType) } err := outputHandler.Initialize(parameters) if err != nil { return err } metrics.Register("output_status", expvar.Func(func() interface{} { ret := make(map[string]interface{}) ret[outputHandler.Key()] = outputHandler.Statistics() switch config.OutputFormat { case LEEFOutputFormat: ret["format"] = "leef" case JSONOutputFormat: ret["format"] = "json" } switch config.OutputType { case FileOutputType: ret["type"] = "file" case UDPOutputType: ret["type"] = "net" case TCPOutputType: ret["type"] = "net" case S3OutputType: ret["type"] = "s3" case HTTPOutputType: ret["type"] = "http" case SplunkOutputType: ret["type"] = "splunk" } return ret })) log.Infof("Initialized output: %s\n", outputHandler.String()) return outputHandler.Go(results, outputErrors) } func main() { hostname, err := os.Hostname() if err != nil { log.Fatal(err) } configLocation := "/etc/cb/integrations/event-forwarder/cb-event-forwarder.conf" if flag.NArg() > 0 { configLocation = flag.Arg(0) } log.Infof("Using config file %s\n", configLocation) config, err = ParseConfig(configLocation) if err != nil { log.Fatal(err) } if !config.RunMetrics { log.Infof("Running without metrics") metrics.UseNilMetrics = true } else { metrics.UseNilMetrics = false log.Infof("Running with metrics") } setupMetrics() if *checkConfiguration { if err := startOutputs(); err != nil { log.Fatal(err) } os.Exit(0) } defaultPidFileLocation := "/run/cb/integrations/cb-event-forwarder/cb-event-forwarder.pid" if *pidFileLocation == "" { *pidFileLocation = defaultPidFileLocation } log.Infof("PID file will be written to %s\n", *pidFileLocation) pidfile.SetPidfilePath(*pidFileLocation) err = pidfile.Write() if err != nil { log.Warn("Could not write PID file: %s\n", err) } addrs, err := net.InterfaceAddrs() if err != nil { log.Fatal("Could not get IP addresses") } log.Infof("cb-event-forwarder version %s starting", version) exportedVersion := &expvar.String{} metrics.Register("version", exportedVersion) if *debug { exportedVersion.Set(version + " (debugging on)") log.Debugf("*** Debugging enabled: messages may be sent via http://%s:%d/debug/sendmessage ***", hostname, config.HTTPServerPort) log.SetLevel(log.DebugLevel) } else { exportedVersion.Set(version) } metrics.Register("debug", expvar.Func(func() interface{} { return *debug })) for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { log.Infof("Interface address %s", ipnet.IP.String()) } } log.Infof("Configured to capture events: %v", config.EventTypes) if err := startOutputs(); err != nil { log.Fatalf("Could not startOutputs: %s", err) } if *debug { http.HandleFunc("/debug/sendmessage", func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { msg := make([]byte, r.ContentLength) _, err := r.Body.Read(msg) var parsedMsg map[string]interface{} err = json.Unmarshal(msg, &parsedMsg) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } err = outputMessage(parsedMsg) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } log.Errorf("Sent test message: %s\n", string(msg)) } else { err = outputMessage(map[string]interface{}{ "type": "debug.message", "message": fmt.Sprintf("Debugging test message sent at %s", time.Now().String()), }) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } log.Info("Sent test debugging message") } errMsg, _ := json.Marshal(map[string]string{"status": "success"}) _, _ = w.Write(errMsg) }) } http.HandleFunc("/debug/healthcheck", func(w http.ResponseWriter, r *http.Request) { if !status.IsConnected { payload, _ := json.Marshal(map[string]interface{}{"status": "FORWARDER IS NOT CONNECTED", "error": status.LastConnectError}) http.Error(w, string(payload), http.StatusNetworkAuthenticationRequired) } else { payload, _ := json.Marshal(map[string]interface{}{"status": "FORWARDER IS CONNECTED"}) w.Write(payload) } }) go http.ListenAndServe(fmt.Sprintf(":%d", config.HTTPServerPort), nil) queueName := fmt.Sprintf("cb-event-forwarder:%s:%d", hostname, os.Getpid()) if config.AMQPQueueName != "" { queueName = config.AMQPQueueName } go func(consumerNumber int) { log.Infof("Starting AMQP loop %d to %s on queue %s", consumerNumber, config.AMQPURL(), queueName) for { err := messageProcessingLoop(config.AMQPURL(), queueName, fmt.Sprintf("go-event-consumer-%d", consumerNumber)) log.Infof("AMQP loop %d exited: %s. Sleeping for 30 seconds then retrying.", consumerNumber, err) time.Sleep(30 * time.Second) } }(1) if config.AuditLog == true { log.Info("starting log file processing loop") go func() { errChan := logFileProcessingLoop() for { select { case err := <-errChan: log.Infof("%v", err) } } }() } else { log.Info("Not starting file processing loop") } //Try to send to metrics to carbon if configured to do so if config.CarbonMetricsEndpoint != nil && config.RunMetrics { //log.Infof("Trying to resolve TCP ADDR for %s\n", *config.CarbonMetricsEndpoint) addr, err := net.ResolveTCPAddr("tcp4", *config.CarbonMetricsEndpoint) if err != nil { log.Panicf("Failing resolving carbon endpoint %v", err) } go graphite.Graphite(metrics.DefaultRegistry, 1*time.Second, config.MetricTag, addr) log.Infof("Sending metrics to graphite") } exp.Exp(metrics.DefaultRegistry) for { time.Sleep(30 * time.Second) } log.Info("cb-event-forwarder exiting") }
{ var dialer AMQPDialer if config.CannedInput { md := NewMockAMQPDialer() mockChan, _ := md.Connection.Channel() go RunCannedData(mockChan) dialer = md } else { dialer = StreadwayAMQPDialer{} } var c *Consumer = NewConsumer(uri, queueName, consumerTag, config.UseRawSensorExchange, config.EventTypes, dialer) messages := make(chan amqp.Delivery, inputChannelSize) deliveries, err := c.Connect() if err != nil { status.LastConnectError = err.Error() status.ErrorTime = time.Now() return err } status.LastConnectTime = time.Now() status.IsConnected = true numProcessors := config.NumProcessors log.Infof("Starting %d message processors\n", numProcessors) wg.Add(numProcessors) if config.RunMetrics { go monitorChannels(time.NewTicker(100*time.Millisecond), messages, results) } go splitDelivery(deliveries, messages) for i := 0; i < numProcessors; i++ { go worker(messages) } for { select { case outputError := <-outputErrors: log.Errorf("ERROR during output: %s", outputError.Error()) // hack to exit if the error happens while we are writing to a file if config.OutputType == FileOutputType || config.OutputType == SplunkOutputType || config.OutputType == HTTPOutputType || config.OutputType == S3OutputType || config.OutputType == SyslogOutputType { log.Error("File output error; exiting immediately.") c.Shutdown() wg.Wait() os.Exit(1) } case closeError := <-c.connectionErrors: status.IsConnected = false status.LastConnectError = closeError.Error() status.ErrorTime = time.Now() log.Errorf("Connection error: %s", closeError.Error()) // This assumes that after the error, workers don't get any more messagesa nd will eventually return log.Info("Waiting for all workers to exit") wg.Wait() log.Info("All workers have exited") return closeError } } log.Info("Loop exited for unknown reason") c.Shutdown() wg.Wait() return nil }
identifier_body
main.go
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "errors" "expvar" "flag" "fmt" "io/ioutil" "net" "net/http" "os" "path" "strings" "sync" "time" graphite "github.com/cyberdelia/go-metrics-graphite" "github.com/facebookgo/pidfile" "github.com/rcrowley/go-metrics" "github.com/rcrowley/go-metrics/exp" log "github.com/sirupsen/logrus" "github.com/streadway/amqp" _ "net/http/pprof" ) var ( pidFileLocation = flag.String("pid-file", "", "PID file location") checkConfiguration = flag.Bool("check", false, "Check the configuration file and exit") debug = flag.Bool("debug", false, "Enable debugging mode") ) var version = "3.7.0" var inputChannelSize = 100000 var outputChannelSize = 1000000 var wg sync.WaitGroup var config Configuration type Status struct { InputEventCount metrics.Meter InputByteCount metrics.Meter OutputEventCount metrics.Meter OutputByteCount metrics.Meter ErrorCount metrics.Meter InputChannelCount metrics.Gauge OutputChannelCount metrics.Gauge IsConnected bool LastConnectTime time.Time StartTime time.Time LastConnectError string ErrorTime time.Time Healthy metrics.Healthcheck sync.RWMutex } var status Status var ( results chan string outputErrors chan error ) func init() { flag.Parse() } func setupMetrics() { status.InputEventCount = metrics.NewRegisteredMeter("core.input.events", metrics.DefaultRegistry) status.InputByteCount = metrics.NewRegisteredMeter("core.input.data", metrics.DefaultRegistry) status.OutputEventCount = metrics.NewRegisteredMeter("core.output.events", metrics.DefaultRegistry) status.OutputByteCount = metrics.NewRegisteredMeter("core.output.data", metrics.DefaultRegistry) status.ErrorCount = metrics.NewRegisteredMeter("errors", metrics.DefaultRegistry) status.InputChannelCount = metrics.NewRegisteredGauge("core.channel.input.events", metrics.DefaultRegistry) status.OutputChannelCount = metrics.NewRegisteredGauge("core.channel.output.events", metrics.DefaultRegistry) status.Healthy = metrics.NewHealthcheck(func(h metrics.Healthcheck) { if status.IsConnected { h.Healthy() } else { h.Unhealthy(errors.New("Event Forwarder is not connected")) } }) metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry) metrics.Register("connection_status", expvar.Func(func() interface{} { res := make(map[string]interface{}, 0) res["last_connect_time"] = status.LastConnectTime res["last_error_text"] = status.LastConnectError res["last_error_time"] = status.ErrorTime if status.IsConnected { res["connected"] = true res["uptime"] = time.Now().Sub(status.LastConnectTime).Seconds() } else { res["connected"] = false res["uptime"] = 0.0 } return res })) metrics.Register("uptime", expvar.Func(func() interface{} { return time.Now().Sub(status.StartTime).Seconds() })) metrics.Register("subscribed_events", expvar.Func(func() interface{} { return config.EventTypes })) results = make(chan string, outputChannelSize) outputErrors = make(chan error) status.StartTime = time.Now() } /* * Types */ type OutputHandler interface { Initialize(string) error Go(messages <-chan string, errorChan chan<- error) error String() string Statistics() interface{} Key() string } /* * worker */ // TODO: change this into an error channel func reportError(d string, errmsg string, err error) { status.ErrorCount.Mark(1) log.Debugf("%s when processing %s: %s", errmsg, d, err) } func reportBundleDetails(routingKey string, body []byte, headers amqp.Table) { log.Errorf("Error while processing message through routing key %s:", routingKey) var env *CbEnvironmentMsg env, err := createEnvMessage(headers) if err != nil { log.Errorf(" Message was received from sensor %d; hostname %s", env.Endpoint.GetSensorId(), env.Endpoint.GetSensorHostName()) } if len(body) < 4 { log.Info(" Message is less than 4 bytes long; malformed") } else { log.Info(" First four bytes of message were:") log.Errorf(" %s", hex.Dump(body[0:4])) } /* * We are going to store this bundle in the DebugStore */ if config.DebugFlag { h := md5.New() h.Write(body) var fullFilePath string fullFilePath = path.Join(config.DebugStore, fmt.Sprintf("/event-forwarder-%X", h.Sum(nil))) log.Debugf("Writing Bundle to disk: %s", fullFilePath) ioutil.WriteFile(fullFilePath, body, 0444) } } func monitorChannels(ticker *time.Ticker, inputChannel chan<- amqp.Delivery, outputChannel chan<- string) { for range ticker.C { status.InputChannelCount.Update(int64(len(inputChannel))) status.OutputChannelCount.Update(int64(len(outputChannel))) } } func processMessage(body []byte, routingKey, contentType string, headers amqp.Table, exchangeName string) { status.InputEventCount.Mark(1) status.InputByteCount.Mark(int64(len(body))) var err error var msgs []map[string]interface{} // // Process message based on ContentType // //log.Errorf("PROCESS MESSAGE CALLED ROUTINGKEY = %s contentType = %s exchange = %s ",routingKey, contentType, exchangeName) if contentType == "application/zip" { msgs, err = ProcessRawZipBundle(routingKey, body, headers) if err != nil { reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process raw zip bundle", err) return } } else if contentType == "application/protobuf" { // if we receive a protobuf through the raw sensor exchange, it's actually a protobuf "bundle" and not a // single protobuf if exchangeName == "api.rawsensordata" { msgs, err = ProcessProtobufBundle(routingKey, body, headers) //log.Infof("Process Protobuf bundle returned %d messages and error = %v",len(msgs),err) } else { msg, err := ProcessProtobufMessage(routingKey, body, headers) if err != nil { reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process body", err) return } else if msg != nil { msgs = make([]map[string]interface{}, 0, 1) msgs = append(msgs, msg) } } } else if contentType == "application/json" { // Note for simplicity in implementation we are assuming the JSON output by the Cb server // is an object (that is, the top level JSON object is a dictionary and not an array or scalar value) var msg map[string]interface{} decoder := json.NewDecoder(bytes.NewReader(body)) // Ensure that we decode numbers in the JSON as integers and *not* float64s decoder.UseNumber() if err := decoder.Decode(&msg); err != nil { reportError(string(body), "Received error when unmarshaling JSON body", err) return } msgs, err = ProcessJSONMessage(msg, routingKey) } else { reportError(string(body), "Unknown content-type", errors.New(contentType)) return } for _, msg := range msgs { err = outputMessage(msg) if err != nil { reportError(string(body), "Error marshaling message", err) } } } func outputMessage(msg map[string]interface{}) error { var err error // // Marshal result into the correct output format // msg["cb_server"] = config.ServerName // Remove keys that have been configured to be removed for _, v := range config.RemoveFromOutput { delete(msg, v) } var outmsg string switch config.OutputFormat { case JSONOutputFormat: var b []byte b, err = json.Marshal(msg) outmsg = string(b) case LEEFOutputFormat: outmsg, err = Encode(msg) default: panic("Impossible: invalid output_format, exiting immediately") } if len(outmsg) > 0 && err == nil { status.OutputEventCount.Mark(1) status.OutputByteCount.Mark(int64(len(outmsg))) results <- string(outmsg) } else { return err } return nil } func splitDelivery(deliveries <-chan amqp.Delivery, messages chan<- amqp.Delivery) { defer close(messages) for delivery := range deliveries { messages <- delivery } } func
(deliveries <-chan amqp.Delivery) { defer wg.Done() for delivery := range deliveries { processMessage(delivery.Body, delivery.RoutingKey, delivery.ContentType, delivery.Headers, delivery.Exchange) } log.Info("Worker exiting") } func logFileProcessingLoop() <-chan error { errChan := make(chan error) spawnTailer := func(fName string, label string) { log.Debugf("Spawn tailer: %s", fName) _, deliveries, err := NewFileConsumer(fName) if err != nil { status.LastConnectError = err.Error() status.ErrorTime = time.Now() errChan <- err } for delivery := range deliveries { log.Debugf("Trying to deliver log message %s", delivery) msgMap := make(map[string]interface{}) msgMap["message"] = strings.TrimSuffix(delivery, "\n") msgMap["type"] = label outputMessage(msgMap) } } /* maps audit log labels to event types AUDIT_TYPES = { "cb-audit-isolation": Audit_Log_Isolation, "cb-audit-banning": Audit_Log_Banning, "cb-audit-live-response": Audit_Log_Liveresponse, "cb-audit-useractivity": Audit_Log_Useractivity } */ go spawnTailer("/var/log/cb/audit/live-response.log", "audit.log.liveresponse") go spawnTailer("/var/log/cb/audit/banning.log", "audit.log.banning") go spawnTailer("/var/log/cb/audit/isolation.log", "audit.log.isolation") go spawnTailer("/var/log/cb/audit/useractivity.log", "audit.log.useractivity") return errChan } func messageProcessingLoop(uri, queueName, consumerTag string) error { var dialer AMQPDialer if config.CannedInput { md := NewMockAMQPDialer() mockChan, _ := md.Connection.Channel() go RunCannedData(mockChan) dialer = md } else { dialer = StreadwayAMQPDialer{} } var c *Consumer = NewConsumer(uri, queueName, consumerTag, config.UseRawSensorExchange, config.EventTypes, dialer) messages := make(chan amqp.Delivery, inputChannelSize) deliveries, err := c.Connect() if err != nil { status.LastConnectError = err.Error() status.ErrorTime = time.Now() return err } status.LastConnectTime = time.Now() status.IsConnected = true numProcessors := config.NumProcessors log.Infof("Starting %d message processors\n", numProcessors) wg.Add(numProcessors) if config.RunMetrics { go monitorChannels(time.NewTicker(100*time.Millisecond), messages, results) } go splitDelivery(deliveries, messages) for i := 0; i < numProcessors; i++ { go worker(messages) } for { select { case outputError := <-outputErrors: log.Errorf("ERROR during output: %s", outputError.Error()) // hack to exit if the error happens while we are writing to a file if config.OutputType == FileOutputType || config.OutputType == SplunkOutputType || config.OutputType == HTTPOutputType || config.OutputType == S3OutputType || config.OutputType == SyslogOutputType { log.Error("File output error; exiting immediately.") c.Shutdown() wg.Wait() os.Exit(1) } case closeError := <-c.connectionErrors: status.IsConnected = false status.LastConnectError = closeError.Error() status.ErrorTime = time.Now() log.Errorf("Connection error: %s", closeError.Error()) // This assumes that after the error, workers don't get any more messagesa nd will eventually return log.Info("Waiting for all workers to exit") wg.Wait() log.Info("All workers have exited") return closeError } } log.Info("Loop exited for unknown reason") c.Shutdown() wg.Wait() return nil } func startOutputs() error { // Configure the specific output. // Valid options are: 'udp', 'tcp', 'file', 's3', 'syslog' ,"http",'splunk' var outputHandler OutputHandler parameters := config.OutputParameters switch config.OutputType { case FileOutputType: outputHandler = &FileOutput{} case TCPOutputType: outputHandler = &NetOutput{} parameters = "tcp:" + parameters case UDPOutputType: outputHandler = &NetOutput{} parameters = "udp:" + parameters case S3OutputType: outputHandler = &BundledOutput{behavior: &S3Behavior{}} case SyslogOutputType: outputHandler = &SyslogOutput{} case HTTPOutputType: outputHandler = &BundledOutput{behavior: &HTTPBehavior{}} case SplunkOutputType: outputHandler = &BundledOutput{behavior: &SplunkBehavior{}} case KafkaOutputType: outputHandler = &KafkaOutput{} default: return fmt.Errorf("No valid output handler found (%d)", config.OutputType) } err := outputHandler.Initialize(parameters) if err != nil { return err } metrics.Register("output_status", expvar.Func(func() interface{} { ret := make(map[string]interface{}) ret[outputHandler.Key()] = outputHandler.Statistics() switch config.OutputFormat { case LEEFOutputFormat: ret["format"] = "leef" case JSONOutputFormat: ret["format"] = "json" } switch config.OutputType { case FileOutputType: ret["type"] = "file" case UDPOutputType: ret["type"] = "net" case TCPOutputType: ret["type"] = "net" case S3OutputType: ret["type"] = "s3" case HTTPOutputType: ret["type"] = "http" case SplunkOutputType: ret["type"] = "splunk" } return ret })) log.Infof("Initialized output: %s\n", outputHandler.String()) return outputHandler.Go(results, outputErrors) } func main() { hostname, err := os.Hostname() if err != nil { log.Fatal(err) } configLocation := "/etc/cb/integrations/event-forwarder/cb-event-forwarder.conf" if flag.NArg() > 0 { configLocation = flag.Arg(0) } log.Infof("Using config file %s\n", configLocation) config, err = ParseConfig(configLocation) if err != nil { log.Fatal(err) } if !config.RunMetrics { log.Infof("Running without metrics") metrics.UseNilMetrics = true } else { metrics.UseNilMetrics = false log.Infof("Running with metrics") } setupMetrics() if *checkConfiguration { if err := startOutputs(); err != nil { log.Fatal(err) } os.Exit(0) } defaultPidFileLocation := "/run/cb/integrations/cb-event-forwarder/cb-event-forwarder.pid" if *pidFileLocation == "" { *pidFileLocation = defaultPidFileLocation } log.Infof("PID file will be written to %s\n", *pidFileLocation) pidfile.SetPidfilePath(*pidFileLocation) err = pidfile.Write() if err != nil { log.Warn("Could not write PID file: %s\n", err) } addrs, err := net.InterfaceAddrs() if err != nil { log.Fatal("Could not get IP addresses") } log.Infof("cb-event-forwarder version %s starting", version) exportedVersion := &expvar.String{} metrics.Register("version", exportedVersion) if *debug { exportedVersion.Set(version + " (debugging on)") log.Debugf("*** Debugging enabled: messages may be sent via http://%s:%d/debug/sendmessage ***", hostname, config.HTTPServerPort) log.SetLevel(log.DebugLevel) } else { exportedVersion.Set(version) } metrics.Register("debug", expvar.Func(func() interface{} { return *debug })) for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { log.Infof("Interface address %s", ipnet.IP.String()) } } log.Infof("Configured to capture events: %v", config.EventTypes) if err := startOutputs(); err != nil { log.Fatalf("Could not startOutputs: %s", err) } if *debug { http.HandleFunc("/debug/sendmessage", func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { msg := make([]byte, r.ContentLength) _, err := r.Body.Read(msg) var parsedMsg map[string]interface{} err = json.Unmarshal(msg, &parsedMsg) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } err = outputMessage(parsedMsg) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } log.Errorf("Sent test message: %s\n", string(msg)) } else { err = outputMessage(map[string]interface{}{ "type": "debug.message", "message": fmt.Sprintf("Debugging test message sent at %s", time.Now().String()), }) if err != nil { errMsg, _ := json.Marshal(map[string]string{"status": "error", "error": err.Error()}) _, _ = w.Write(errMsg) return } log.Info("Sent test debugging message") } errMsg, _ := json.Marshal(map[string]string{"status": "success"}) _, _ = w.Write(errMsg) }) } http.HandleFunc("/debug/healthcheck", func(w http.ResponseWriter, r *http.Request) { if !status.IsConnected { payload, _ := json.Marshal(map[string]interface{}{"status": "FORWARDER IS NOT CONNECTED", "error": status.LastConnectError}) http.Error(w, string(payload), http.StatusNetworkAuthenticationRequired) } else { payload, _ := json.Marshal(map[string]interface{}{"status": "FORWARDER IS CONNECTED"}) w.Write(payload) } }) go http.ListenAndServe(fmt.Sprintf(":%d", config.HTTPServerPort), nil) queueName := fmt.Sprintf("cb-event-forwarder:%s:%d", hostname, os.Getpid()) if config.AMQPQueueName != "" { queueName = config.AMQPQueueName } go func(consumerNumber int) { log.Infof("Starting AMQP loop %d to %s on queue %s", consumerNumber, config.AMQPURL(), queueName) for { err := messageProcessingLoop(config.AMQPURL(), queueName, fmt.Sprintf("go-event-consumer-%d", consumerNumber)) log.Infof("AMQP loop %d exited: %s. Sleeping for 30 seconds then retrying.", consumerNumber, err) time.Sleep(30 * time.Second) } }(1) if config.AuditLog == true { log.Info("starting log file processing loop") go func() { errChan := logFileProcessingLoop() for { select { case err := <-errChan: log.Infof("%v", err) } } }() } else { log.Info("Not starting file processing loop") } //Try to send to metrics to carbon if configured to do so if config.CarbonMetricsEndpoint != nil && config.RunMetrics { //log.Infof("Trying to resolve TCP ADDR for %s\n", *config.CarbonMetricsEndpoint) addr, err := net.ResolveTCPAddr("tcp4", *config.CarbonMetricsEndpoint) if err != nil { log.Panicf("Failing resolving carbon endpoint %v", err) } go graphite.Graphite(metrics.DefaultRegistry, 1*time.Second, config.MetricTag, addr) log.Infof("Sending metrics to graphite") } exp.Exp(metrics.DefaultRegistry) for { time.Sleep(30 * time.Second) } log.Info("cb-event-forwarder exiting") }
worker
identifier_name
index.py
''' imports reading list from mangaupdates.com to mangadex.org requires: beautifulsoup4 chromedriver-binary (to be installed in python3 directory) PyYAML selenium ./credentials.yaml mu_username: <account name> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import yaml # constants # delays MANGA_UPDATES_DELAY = 0 # seconds for manga updates to load, usually can be set to 0 MANGADEX_DELAY = 2 # seconds for mangadex to load (jQuery takes forever) # overwrite all progress on mangadex for manga update's progress # make sure you really want this changed OVERWRITE_PROGRESS = False # urls mu_url = 'https://www.mangaupdates.com/mylist.html' mu_url_wish_list = 'https://www.mangaupdates.com/mylist.html?list=wish' mu_url_complete_list = 'https://www.mangaupdates.com/mylist.html?list=complete' mu_url_unfinished_list = 'https://www.mangaupdates.com/mylist.html?list=unfinished' mu_url_on_hold_list = 'https://www.mangaupdates.com/mylist.html?list=hold' md_base_url = 'https://mangadex.org' md_login_url = 'https://mangadex.org/login' md_search_url = 'https://mangadex.org/quick_search/' def manga_updates_list(driver, url=mu_url): ''' gets list's unique urls and titles ''' driver.get(url) # parse urls and titles of list soup = BeautifulSoup(driver.page_source, 'html.parser') reading_list = soup.find("table", {"id": "list_table"}) title_url_list = reading_list.find_all("a", {"title": "Series Info"}) href_list = [a.get("href") for a in title_url_list] # main title is not featured in associated names title_list = [u.get_text() for u in title_url_list] return href_list, title_list def manga_updates_reading_progress(driver, reading_list):
def manga_updates_all_titles(driver, url=mu_url): ''' get a list of titles and returns a dict of manga_updates_url: set(all titles) ''' all_titles = {} href_list, title_list = manga_updates_list(driver, url) # initially fill with known values for i in range(len(title_list)): new_title_set = set() new_title_set.add(title_list[i]) all_titles[href_list[i]] = new_title_set # scrape each individual page for alternative titles for manga_urls in href_list: driver.get(manga_urls) time.sleep(MANGA_UPDATES_DELAY) # alternate titles are under first sContainer, third sContent soup = BeautifulSoup(driver.page_source, 'html.parser') title_html = soup.find_all("div", {"class": "sContent"})[3] title_list = title_html.find_all(text=True) title_list = [title.strip(' \t\n\r') for title in title_list if title != '\n'] all_titles[manga_urls].update(title_list) return all_titles def is_english(s): ''' tests to see if the characters are english MangaDex does not have non-english characters titles ''' try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True def mangadex_import(all_titles, driver, type="reading"): ''' imports to correct list base on an all_titles dict all_titles: manga_updates_url: set(titles) ''' x_path_string = "" if type == "reading": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@id, '1')]" elif type == "completed": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '2')]" elif type == "on hold": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '3')]" elif type == "plan to read": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '4')]" elif type == "dropped": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '5')]" else: raise Exception( "import type should be: 'reading', 'completed', 'on hold', 'plan to read', 'dropped'") # start searching for titles in all_titles.values(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") driver.get(md_search_url+query) time.sleep(MANGADEX_DELAY) # wait for jQuery to load try: manga_entries = driver.find_elements_by_class_name( "manga-entry") if manga_entries: try: manga_entries[0].find_element_by_xpath( "//button[contains(@class, 'btn-secondary') and contains(@class, 'dropdown-toggle')]").click() manga_entries[0].find_elements_by_xpath(x_path_string)[ 0].click() except: print("already imported:", title_name) pass break # a valid title has been found except: pass def mangadex_import_progress(all_titles, driver, progress): ''' imports chapter and volume information for items in reading list ''' for key, titles in all_titles.items(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") driver.get(md_search_url+query) time.sleep(MANGADEX_DELAY) # wait for jQuery to load try: manga_entries = driver.find_elements_by_class_name( "manga-entry") if manga_entries: try: driver.find_elements_by_class_name( "manga-entry")[0].find_element_by_class_name( "manga_title").click() time.sleep(MANGADEX_DELAY) # edit menu volume, chapter = progress[key] driver.find_element_by_id("edit_progress").click() # find inputs vol_input = driver.find_element_by_id("volume") ch_input = driver.find_element_by_id("chapter") # input new value driver.execute_script( "arguments[0].setAttribute('value', arguments[1])", vol_input, volume) driver.execute_script( "arguments[0].setAttribute('value', arguments[1])", ch_input, chapter) # submit driver.find_element_by_id( "edit_progress_button").click() except: print("overwrite progress import error occurred") pass break # a valid title has been found except: pass def main(): # get credentials credentials = {} with open('credentials.yaml') as f: credentials = yaml.load(f) # set driver options options = webdriver.chrome.options.Options() options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-ssl-errors') driver = webdriver.Chrome(options=options) driver.get(mu_url) time.sleep(MANGA_UPDATES_DELAY) # manga updates authenticate username = driver.find_element_by_xpath("//input[@name='username']") password = driver.find_element_by_xpath("//input[@name='password']") submit = driver.find_element_by_xpath("//input[@src='images/login.gif']") username.send_keys(credentials['mu_username']) password.send_keys(credentials['mu_password']) submit.click() time.sleep(MANGA_UPDATES_DELAY) # get lists reading_list = manga_updates_all_titles(driver, mu_url) wish_list = manga_updates_all_titles(driver, mu_url_wish_list) complete_list = manga_updates_all_titles(driver, mu_url_complete_list) unfinished_list = manga_updates_all_titles(driver, mu_url_unfinished_list) on_hold_list = manga_updates_all_titles(driver, mu_url_on_hold_list) reading_list_progress = manga_updates_reading_progress( driver, reading_list) # login to mangadex driver.get(md_login_url) time.sleep(MANGADEX_DELAY) username = driver.find_element_by_id("login_username") password = driver.find_element_by_id("login_password") submit = driver.find_element_by_id("login_button") username.send_keys(credentials['md_username']) password.send_keys(credentials['md_password']) submit.click() # mangadex can be slow sometimes time.sleep(MANGADEX_DELAY) # import to mangadex mangadex_import(reading_list, driver) mangadex_import(wish_list, driver, "plan to read") mangadex_import(complete_list, driver, "completed") mangadex_import(unfinished_list, driver, "dropped") mangadex_import(on_hold_list, driver, "on hold") # handle importing of chapters if OVERWRITE_PROGRESS: mangadex_import_progress(reading_list, driver, reading_list_progress) # exit selenium driver.quit() if __name__ == "__main__": main()
''' gets reading list and returns dict of url: (volume number, chapter number) ''' reading_progress = dict() for url in reading_list.keys(): driver.get(url) time.sleep(MANGA_UPDATES_DELAY) soup = BeautifulSoup(driver.page_source, 'html.parser') volume, chapter = soup.find("td", {"id": "showList"}).find_all("b") volume = "".join([x for x in list(list(volume)[0]) if x.isdigit()]) chapter = "".join([x for x in list(list(chapter)[0]) if x.isdigit()]) reading_progress[url] = (int(volume), int(chapter)) return reading_progress
identifier_body
index.py
''' imports reading list from mangaupdates.com to mangadex.org requires: beautifulsoup4 chromedriver-binary (to be installed in python3 directory) PyYAML selenium ./credentials.yaml mu_username: <account name> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import yaml # constants # delays MANGA_UPDATES_DELAY = 0 # seconds for manga updates to load, usually can be set to 0 MANGADEX_DELAY = 2 # seconds for mangadex to load (jQuery takes forever) # overwrite all progress on mangadex for manga update's progress # make sure you really want this changed OVERWRITE_PROGRESS = False # urls mu_url = 'https://www.mangaupdates.com/mylist.html' mu_url_wish_list = 'https://www.mangaupdates.com/mylist.html?list=wish' mu_url_complete_list = 'https://www.mangaupdates.com/mylist.html?list=complete' mu_url_unfinished_list = 'https://www.mangaupdates.com/mylist.html?list=unfinished' mu_url_on_hold_list = 'https://www.mangaupdates.com/mylist.html?list=hold' md_base_url = 'https://mangadex.org' md_login_url = 'https://mangadex.org/login' md_search_url = 'https://mangadex.org/quick_search/' def manga_updates_list(driver, url=mu_url): ''' gets list's unique urls and titles ''' driver.get(url) # parse urls and titles of list soup = BeautifulSoup(driver.page_source, 'html.parser') reading_list = soup.find("table", {"id": "list_table"}) title_url_list = reading_list.find_all("a", {"title": "Series Info"}) href_list = [a.get("href") for a in title_url_list] # main title is not featured in associated names title_list = [u.get_text() for u in title_url_list] return href_list, title_list def manga_updates_reading_progress(driver, reading_list): ''' gets reading list and returns dict of url: (volume number, chapter number) ''' reading_progress = dict() for url in reading_list.keys():
return reading_progress def manga_updates_all_titles(driver, url=mu_url): ''' get a list of titles and returns a dict of manga_updates_url: set(all titles) ''' all_titles = {} href_list, title_list = manga_updates_list(driver, url) # initially fill with known values for i in range(len(title_list)): new_title_set = set() new_title_set.add(title_list[i]) all_titles[href_list[i]] = new_title_set # scrape each individual page for alternative titles for manga_urls in href_list: driver.get(manga_urls) time.sleep(MANGA_UPDATES_DELAY) # alternate titles are under first sContainer, third sContent soup = BeautifulSoup(driver.page_source, 'html.parser') title_html = soup.find_all("div", {"class": "sContent"})[3] title_list = title_html.find_all(text=True) title_list = [title.strip(' \t\n\r') for title in title_list if title != '\n'] all_titles[manga_urls].update(title_list) return all_titles def is_english(s): ''' tests to see if the characters are english MangaDex does not have non-english characters titles ''' try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True def mangadex_import(all_titles, driver, type="reading"): ''' imports to correct list base on an all_titles dict all_titles: manga_updates_url: set(titles) ''' x_path_string = "" if type == "reading": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@id, '1')]" elif type == "completed": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '2')]" elif type == "on hold": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '3')]" elif type == "plan to read": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '4')]" elif type == "dropped": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '5')]" else: raise Exception( "import type should be: 'reading', 'completed', 'on hold', 'plan to read', 'dropped'") # start searching for titles in all_titles.values(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") driver.get(md_search_url+query) time.sleep(MANGADEX_DELAY) # wait for jQuery to load try: manga_entries = driver.find_elements_by_class_name( "manga-entry") if manga_entries: try: manga_entries[0].find_element_by_xpath( "//button[contains(@class, 'btn-secondary') and contains(@class, 'dropdown-toggle')]").click() manga_entries[0].find_elements_by_xpath(x_path_string)[ 0].click() except: print("already imported:", title_name) pass break # a valid title has been found except: pass def mangadex_import_progress(all_titles, driver, progress): ''' imports chapter and volume information for items in reading list ''' for key, titles in all_titles.items(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") driver.get(md_search_url+query) time.sleep(MANGADEX_DELAY) # wait for jQuery to load try: manga_entries = driver.find_elements_by_class_name( "manga-entry") if manga_entries: try: driver.find_elements_by_class_name( "manga-entry")[0].find_element_by_class_name( "manga_title").click() time.sleep(MANGADEX_DELAY) # edit menu volume, chapter = progress[key] driver.find_element_by_id("edit_progress").click() # find inputs vol_input = driver.find_element_by_id("volume") ch_input = driver.find_element_by_id("chapter") # input new value driver.execute_script( "arguments[0].setAttribute('value', arguments[1])", vol_input, volume) driver.execute_script( "arguments[0].setAttribute('value', arguments[1])", ch_input, chapter) # submit driver.find_element_by_id( "edit_progress_button").click() except: print("overwrite progress import error occurred") pass break # a valid title has been found except: pass def main(): # get credentials credentials = {} with open('credentials.yaml') as f: credentials = yaml.load(f) # set driver options options = webdriver.chrome.options.Options() options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-ssl-errors') driver = webdriver.Chrome(options=options) driver.get(mu_url) time.sleep(MANGA_UPDATES_DELAY) # manga updates authenticate username = driver.find_element_by_xpath("//input[@name='username']") password = driver.find_element_by_xpath("//input[@name='password']") submit = driver.find_element_by_xpath("//input[@src='images/login.gif']") username.send_keys(credentials['mu_username']) password.send_keys(credentials['mu_password']) submit.click() time.sleep(MANGA_UPDATES_DELAY) # get lists reading_list = manga_updates_all_titles(driver, mu_url) wish_list = manga_updates_all_titles(driver, mu_url_wish_list) complete_list = manga_updates_all_titles(driver, mu_url_complete_list) unfinished_list = manga_updates_all_titles(driver, mu_url_unfinished_list) on_hold_list = manga_updates_all_titles(driver, mu_url_on_hold_list) reading_list_progress = manga_updates_reading_progress( driver, reading_list) # login to mangadex driver.get(md_login_url) time.sleep(MANGADEX_DELAY) username = driver.find_element_by_id("login_username") password = driver.find_element_by_id("login_password") submit = driver.find_element_by_id("login_button") username.send_keys(credentials['md_username']) password.send_keys(credentials['md_password']) submit.click() # mangadex can be slow sometimes time.sleep(MANGADEX_DELAY) # import to mangadex mangadex_import(reading_list, driver) mangadex_import(wish_list, driver, "plan to read") mangadex_import(complete_list, driver, "completed") mangadex_import(unfinished_list, driver, "dropped") mangadex_import(on_hold_list, driver, "on hold") # handle importing of chapters if OVERWRITE_PROGRESS: mangadex_import_progress(reading_list, driver, reading_list_progress) # exit selenium driver.quit() if __name__ == "__main__": main()
driver.get(url) time.sleep(MANGA_UPDATES_DELAY) soup = BeautifulSoup(driver.page_source, 'html.parser') volume, chapter = soup.find("td", {"id": "showList"}).find_all("b") volume = "".join([x for x in list(list(volume)[0]) if x.isdigit()]) chapter = "".join([x for x in list(list(chapter)[0]) if x.isdigit()]) reading_progress[url] = (int(volume), int(chapter))
conditional_block
index.py
''' imports reading list from mangaupdates.com to mangadex.org requires: beautifulsoup4 chromedriver-binary (to be installed in python3 directory) PyYAML selenium ./credentials.yaml mu_username: <account name> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import yaml # constants # delays MANGA_UPDATES_DELAY = 0 # seconds for manga updates to load, usually can be set to 0 MANGADEX_DELAY = 2 # seconds for mangadex to load (jQuery takes forever) # overwrite all progress on mangadex for manga update's progress # make sure you really want this changed OVERWRITE_PROGRESS = False # urls mu_url = 'https://www.mangaupdates.com/mylist.html'
mu_url_on_hold_list = 'https://www.mangaupdates.com/mylist.html?list=hold' md_base_url = 'https://mangadex.org' md_login_url = 'https://mangadex.org/login' md_search_url = 'https://mangadex.org/quick_search/' def manga_updates_list(driver, url=mu_url): ''' gets list's unique urls and titles ''' driver.get(url) # parse urls and titles of list soup = BeautifulSoup(driver.page_source, 'html.parser') reading_list = soup.find("table", {"id": "list_table"}) title_url_list = reading_list.find_all("a", {"title": "Series Info"}) href_list = [a.get("href") for a in title_url_list] # main title is not featured in associated names title_list = [u.get_text() for u in title_url_list] return href_list, title_list def manga_updates_reading_progress(driver, reading_list): ''' gets reading list and returns dict of url: (volume number, chapter number) ''' reading_progress = dict() for url in reading_list.keys(): driver.get(url) time.sleep(MANGA_UPDATES_DELAY) soup = BeautifulSoup(driver.page_source, 'html.parser') volume, chapter = soup.find("td", {"id": "showList"}).find_all("b") volume = "".join([x for x in list(list(volume)[0]) if x.isdigit()]) chapter = "".join([x for x in list(list(chapter)[0]) if x.isdigit()]) reading_progress[url] = (int(volume), int(chapter)) return reading_progress def manga_updates_all_titles(driver, url=mu_url): ''' get a list of titles and returns a dict of manga_updates_url: set(all titles) ''' all_titles = {} href_list, title_list = manga_updates_list(driver, url) # initially fill with known values for i in range(len(title_list)): new_title_set = set() new_title_set.add(title_list[i]) all_titles[href_list[i]] = new_title_set # scrape each individual page for alternative titles for manga_urls in href_list: driver.get(manga_urls) time.sleep(MANGA_UPDATES_DELAY) # alternate titles are under first sContainer, third sContent soup = BeautifulSoup(driver.page_source, 'html.parser') title_html = soup.find_all("div", {"class": "sContent"})[3] title_list = title_html.find_all(text=True) title_list = [title.strip(' \t\n\r') for title in title_list if title != '\n'] all_titles[manga_urls].update(title_list) return all_titles def is_english(s): ''' tests to see if the characters are english MangaDex does not have non-english characters titles ''' try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True def mangadex_import(all_titles, driver, type="reading"): ''' imports to correct list base on an all_titles dict all_titles: manga_updates_url: set(titles) ''' x_path_string = "" if type == "reading": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@id, '1')]" elif type == "completed": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '2')]" elif type == "on hold": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '3')]" elif type == "plan to read": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '4')]" elif type == "dropped": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '5')]" else: raise Exception( "import type should be: 'reading', 'completed', 'on hold', 'plan to read', 'dropped'") # start searching for titles in all_titles.values(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") driver.get(md_search_url+query) time.sleep(MANGADEX_DELAY) # wait for jQuery to load try: manga_entries = driver.find_elements_by_class_name( "manga-entry") if manga_entries: try: manga_entries[0].find_element_by_xpath( "//button[contains(@class, 'btn-secondary') and contains(@class, 'dropdown-toggle')]").click() manga_entries[0].find_elements_by_xpath(x_path_string)[ 0].click() except: print("already imported:", title_name) pass break # a valid title has been found except: pass def mangadex_import_progress(all_titles, driver, progress): ''' imports chapter and volume information for items in reading list ''' for key, titles in all_titles.items(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") driver.get(md_search_url+query) time.sleep(MANGADEX_DELAY) # wait for jQuery to load try: manga_entries = driver.find_elements_by_class_name( "manga-entry") if manga_entries: try: driver.find_elements_by_class_name( "manga-entry")[0].find_element_by_class_name( "manga_title").click() time.sleep(MANGADEX_DELAY) # edit menu volume, chapter = progress[key] driver.find_element_by_id("edit_progress").click() # find inputs vol_input = driver.find_element_by_id("volume") ch_input = driver.find_element_by_id("chapter") # input new value driver.execute_script( "arguments[0].setAttribute('value', arguments[1])", vol_input, volume) driver.execute_script( "arguments[0].setAttribute('value', arguments[1])", ch_input, chapter) # submit driver.find_element_by_id( "edit_progress_button").click() except: print("overwrite progress import error occurred") pass break # a valid title has been found except: pass def main(): # get credentials credentials = {} with open('credentials.yaml') as f: credentials = yaml.load(f) # set driver options options = webdriver.chrome.options.Options() options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-ssl-errors') driver = webdriver.Chrome(options=options) driver.get(mu_url) time.sleep(MANGA_UPDATES_DELAY) # manga updates authenticate username = driver.find_element_by_xpath("//input[@name='username']") password = driver.find_element_by_xpath("//input[@name='password']") submit = driver.find_element_by_xpath("//input[@src='images/login.gif']") username.send_keys(credentials['mu_username']) password.send_keys(credentials['mu_password']) submit.click() time.sleep(MANGA_UPDATES_DELAY) # get lists reading_list = manga_updates_all_titles(driver, mu_url) wish_list = manga_updates_all_titles(driver, mu_url_wish_list) complete_list = manga_updates_all_titles(driver, mu_url_complete_list) unfinished_list = manga_updates_all_titles(driver, mu_url_unfinished_list) on_hold_list = manga_updates_all_titles(driver, mu_url_on_hold_list) reading_list_progress = manga_updates_reading_progress( driver, reading_list) # login to mangadex driver.get(md_login_url) time.sleep(MANGADEX_DELAY) username = driver.find_element_by_id("login_username") password = driver.find_element_by_id("login_password") submit = driver.find_element_by_id("login_button") username.send_keys(credentials['md_username']) password.send_keys(credentials['md_password']) submit.click() # mangadex can be slow sometimes time.sleep(MANGADEX_DELAY) # import to mangadex mangadex_import(reading_list, driver) mangadex_import(wish_list, driver, "plan to read") mangadex_import(complete_list, driver, "completed") mangadex_import(unfinished_list, driver, "dropped") mangadex_import(on_hold_list, driver, "on hold") # handle importing of chapters if OVERWRITE_PROGRESS: mangadex_import_progress(reading_list, driver, reading_list_progress) # exit selenium driver.quit() if __name__ == "__main__": main()
mu_url_wish_list = 'https://www.mangaupdates.com/mylist.html?list=wish' mu_url_complete_list = 'https://www.mangaupdates.com/mylist.html?list=complete' mu_url_unfinished_list = 'https://www.mangaupdates.com/mylist.html?list=unfinished'
random_line_split
index.py
''' imports reading list from mangaupdates.com to mangadex.org requires: beautifulsoup4 chromedriver-binary (to be installed in python3 directory) PyYAML selenium ./credentials.yaml mu_username: <account name> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import yaml # constants # delays MANGA_UPDATES_DELAY = 0 # seconds for manga updates to load, usually can be set to 0 MANGADEX_DELAY = 2 # seconds for mangadex to load (jQuery takes forever) # overwrite all progress on mangadex for manga update's progress # make sure you really want this changed OVERWRITE_PROGRESS = False # urls mu_url = 'https://www.mangaupdates.com/mylist.html' mu_url_wish_list = 'https://www.mangaupdates.com/mylist.html?list=wish' mu_url_complete_list = 'https://www.mangaupdates.com/mylist.html?list=complete' mu_url_unfinished_list = 'https://www.mangaupdates.com/mylist.html?list=unfinished' mu_url_on_hold_list = 'https://www.mangaupdates.com/mylist.html?list=hold' md_base_url = 'https://mangadex.org' md_login_url = 'https://mangadex.org/login' md_search_url = 'https://mangadex.org/quick_search/' def manga_updates_list(driver, url=mu_url): ''' gets list's unique urls and titles ''' driver.get(url) # parse urls and titles of list soup = BeautifulSoup(driver.page_source, 'html.parser') reading_list = soup.find("table", {"id": "list_table"}) title_url_list = reading_list.find_all("a", {"title": "Series Info"}) href_list = [a.get("href") for a in title_url_list] # main title is not featured in associated names title_list = [u.get_text() for u in title_url_list] return href_list, title_list def manga_updates_reading_progress(driver, reading_list): ''' gets reading list and returns dict of url: (volume number, chapter number) ''' reading_progress = dict() for url in reading_list.keys(): driver.get(url) time.sleep(MANGA_UPDATES_DELAY) soup = BeautifulSoup(driver.page_source, 'html.parser') volume, chapter = soup.find("td", {"id": "showList"}).find_all("b") volume = "".join([x for x in list(list(volume)[0]) if x.isdigit()]) chapter = "".join([x for x in list(list(chapter)[0]) if x.isdigit()]) reading_progress[url] = (int(volume), int(chapter)) return reading_progress def manga_updates_all_titles(driver, url=mu_url): ''' get a list of titles and returns a dict of manga_updates_url: set(all titles) ''' all_titles = {} href_list, title_list = manga_updates_list(driver, url) # initially fill with known values for i in range(len(title_list)): new_title_set = set() new_title_set.add(title_list[i]) all_titles[href_list[i]] = new_title_set # scrape each individual page for alternative titles for manga_urls in href_list: driver.get(manga_urls) time.sleep(MANGA_UPDATES_DELAY) # alternate titles are under first sContainer, third sContent soup = BeautifulSoup(driver.page_source, 'html.parser') title_html = soup.find_all("div", {"class": "sContent"})[3] title_list = title_html.find_all(text=True) title_list = [title.strip(' \t\n\r') for title in title_list if title != '\n'] all_titles[manga_urls].update(title_list) return all_titles def is_english(s): ''' tests to see if the characters are english MangaDex does not have non-english characters titles ''' try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True def mangadex_import(all_titles, driver, type="reading"): ''' imports to correct list base on an all_titles dict all_titles: manga_updates_url: set(titles) ''' x_path_string = "" if type == "reading": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@id, '1')]" elif type == "completed": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '2')]" elif type == "on hold": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '3')]" elif type == "plan to read": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '4')]" elif type == "dropped": x_path_string = "//a[contains(@class, 'manga_follow_button') and contains(@class, 'dropdown-item') and contains(@id, '5')]" else: raise Exception( "import type should be: 'reading', 'completed', 'on hold', 'plan to read', 'dropped'") # start searching for titles in all_titles.values(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") driver.get(md_search_url+query) time.sleep(MANGADEX_DELAY) # wait for jQuery to load try: manga_entries = driver.find_elements_by_class_name( "manga-entry") if manga_entries: try: manga_entries[0].find_element_by_xpath( "//button[contains(@class, 'btn-secondary') and contains(@class, 'dropdown-toggle')]").click() manga_entries[0].find_elements_by_xpath(x_path_string)[ 0].click() except: print("already imported:", title_name) pass break # a valid title has been found except: pass def
(all_titles, driver, progress): ''' imports chapter and volume information for items in reading list ''' for key, titles in all_titles.items(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") driver.get(md_search_url+query) time.sleep(MANGADEX_DELAY) # wait for jQuery to load try: manga_entries = driver.find_elements_by_class_name( "manga-entry") if manga_entries: try: driver.find_elements_by_class_name( "manga-entry")[0].find_element_by_class_name( "manga_title").click() time.sleep(MANGADEX_DELAY) # edit menu volume, chapter = progress[key] driver.find_element_by_id("edit_progress").click() # find inputs vol_input = driver.find_element_by_id("volume") ch_input = driver.find_element_by_id("chapter") # input new value driver.execute_script( "arguments[0].setAttribute('value', arguments[1])", vol_input, volume) driver.execute_script( "arguments[0].setAttribute('value', arguments[1])", ch_input, chapter) # submit driver.find_element_by_id( "edit_progress_button").click() except: print("overwrite progress import error occurred") pass break # a valid title has been found except: pass def main(): # get credentials credentials = {} with open('credentials.yaml') as f: credentials = yaml.load(f) # set driver options options = webdriver.chrome.options.Options() options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-ssl-errors') driver = webdriver.Chrome(options=options) driver.get(mu_url) time.sleep(MANGA_UPDATES_DELAY) # manga updates authenticate username = driver.find_element_by_xpath("//input[@name='username']") password = driver.find_element_by_xpath("//input[@name='password']") submit = driver.find_element_by_xpath("//input[@src='images/login.gif']") username.send_keys(credentials['mu_username']) password.send_keys(credentials['mu_password']) submit.click() time.sleep(MANGA_UPDATES_DELAY) # get lists reading_list = manga_updates_all_titles(driver, mu_url) wish_list = manga_updates_all_titles(driver, mu_url_wish_list) complete_list = manga_updates_all_titles(driver, mu_url_complete_list) unfinished_list = manga_updates_all_titles(driver, mu_url_unfinished_list) on_hold_list = manga_updates_all_titles(driver, mu_url_on_hold_list) reading_list_progress = manga_updates_reading_progress( driver, reading_list) # login to mangadex driver.get(md_login_url) time.sleep(MANGADEX_DELAY) username = driver.find_element_by_id("login_username") password = driver.find_element_by_id("login_password") submit = driver.find_element_by_id("login_button") username.send_keys(credentials['md_username']) password.send_keys(credentials['md_password']) submit.click() # mangadex can be slow sometimes time.sleep(MANGADEX_DELAY) # import to mangadex mangadex_import(reading_list, driver) mangadex_import(wish_list, driver, "plan to read") mangadex_import(complete_list, driver, "completed") mangadex_import(unfinished_list, driver, "dropped") mangadex_import(on_hold_list, driver, "on hold") # handle importing of chapters if OVERWRITE_PROGRESS: mangadex_import_progress(reading_list, driver, reading_list_progress) # exit selenium driver.quit() if __name__ == "__main__": main()
mangadex_import_progress
identifier_name
inter.go
// copyright Matthias Büchse, 2019 package main import ( "database/sql" "encoding/json" "errors" "fmt" "io" "log" "net/http" "sort" "strconv" "strings" "text/template" "time" "unicode" ) type Inter interface { Serialize(wr io.Writer, objects objectMap, obj object) error } func formatDate(layout string, date interface{}) string { var dateStr string switch v := date.(type) { case json.Number: dateStr = string(v) case string: dateStr = v default: dateStr = "" } i64, err := strconv.ParseInt(dateStr, 10, 64) if err != nil { log.Fatal(err) } return time.Unix(i64, 0).Format(layout) } func friendly(objects objectMap, key string) interface{} { return objects[key]["friendlyId"] } func joinStrings(delim string, args []interface{}) string { sargs := make([]string, len(args)) for i, arg := range args { sargs[i] = arg.(string) } return strings.Join(sargs, delim) } type myTemplate struct { tmpl *template.Template } func NewInter(templatePath string) Inter { result := myTemplate{template.New("blubb")} t := result.tmpl t.Funcs(map[string]interface{}{"formatDate": formatDate, "friendly": friendly, "joinStrings": joinStrings}) template.Must(t.ParseGlob(templatePath + "/*")) return result } func (template myTemplate) Serialize(wr io.Writer, objects objectMap, obj object) error { // obviously not re-entrant restore := func() { delete(objects, "_current") } defer restore() objects["_current"] = obj return template.tmpl.ExecuteTemplate(wr, obj[K_TYPE].(string), objects) } const ( SKIP = -1 INFO = 0 HINT = 1 ERROR = 2 MAX = 2 ) type remark struct { line int text string severity int skip int } // for sorting type RemarkSlice []*remark func (p RemarkSlice) Len() int { return len(p) } func (p RemarkSlice) Less(i, j int) bool { return p[i].line < p[j].line } func (p RemarkSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (r remark) Format() string { if r.severity == SKIP { return "" } else if r.severity == ERROR { return fmt.Sprintf("#! >>>>>>>>>>>>>>>>>>>> %v <<<<<<<<<<<<<<<<<<<<\n", r.text) } else if r.severity == HINT { return fmt.Sprintf("#: >>>>>>>> %v <<<<<<<<\n", r.text) } else { return fmt.Sprintf("#: %v\n", r.text) } } type Remarks struct { histo [MAX + 1]int severity int descriptors []*remark } func New() *Remarks { return &Remarks{[MAX + 1]int{}, 0, make([]*remark, 0)} } func (rs *Remarks) add(r *remark) { rs.descriptors = append(rs.descriptors, r) if r.severity > rs.severity { rs.severity = r.severity } if r.severity >= 0 && r.severity <= MAX { rs.histo[r.severity]++ } } func (rs *Remarks) AddError(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), ERROR, 0}) } func (rs *Remarks) AddHint(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), HINT, 0}) } func (rs *Remarks) AddInfo(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), INFO, 0}) } func (rs *Remarks) AddRemover(line int) { r := &remark{line: line, severity: SKIP, skip: 1} rs.descriptors = append(rs.descriptors, r) } func (rs *Remarks) Embed(contentLines []string) string { content := "" cl := 0 sort.Sort(RemarkSlice(rs.descriptors)) for _, ed := range rs.descriptors { if ed.line-cl >= 0 { content += strings.Join(contentLines[cl:ed.line], "\n") if ed.line-cl > 0 { content += "\n" } cl = ed.line + ed.skip } content += ed.Format() } content += strings.Join(contentLines[cl:], "\n") return content } func (rs *Remarks) Severity() int { return rs.severity } func (rs *Remarks) Histo(severity int) int { if severity >= 0 && severity <= MAX { return rs.histo[severity] } return 0 } type HeaderTransfer interface { collectFriendly(friendly *[]string) transfer(obj object, lookup map[string]object) } type Header struct { line int transfer HeaderTransfer } type objectDescriptor struct { start int initial []string header map[string]Header body []string } type HeaderParser interface { parse(value string) (HeaderTransfer, error) } type verbatimString struct { targetKey string values []string noTrim bool // default: trim spaces (so much for "verbatim") } type verbatimList struct { targetKey string } type referenceList struct { targetKey string } type dateField struct { targetKey string } type snippetField struct{} type verbatimTransfer struct { targetKey string value interface{} } type referenceTransfer struct { targetKey string friendly []string } type snippetTransfer object func (vt *verbatimTransfer) collectFriendly(friendly *[]string) { } func (vt *verbatimTransfer) transfer(obj object, lookup map[string]object) { if vt.value == nil { delete(obj, vt.targetKey) } else { obj[vt.targetKey] = vt.value } } func (vs verbatimString) parse(value string) (HeaderTransfer, error) { if !vs.noTrim { value = strings.TrimSpace(value) } var ivalue interface{} = value if vs.values != nil { i := -1 for j, v := range vs.values { if value == v { i = j break } } if i == -1 { return nil, fmt.Errorf("field value needs to be one of: %v", vs.values) } if value == "" { // FAT DOG: if we have a fixed set of possible values, "" means <remove field> ivalue = nil } } return &verbatimTransfer{vs.targetKey, ivalue}, nil } func parseList(value string) []string { // CAUTION: separator is COMMA followed by SPACE, because (e.g.) URLs may contain commas (but not spaces) values := strings.Split(value, ", ") for i, v := range values { values[i] = strings.TrimSpace(v) } if len(values) >= 1 && values[len(values)-1] == "" { // handle empty list as well as trailing comma values = values[:len(values)-1] } return values } func (vl verbatimList) parse(value string) (HeaderTransfer, error) { return &verbatimTransfer{vl.targetKey, parseList(value)}, nil } func (rt *referenceTransfer) collectFriendly(friendly *[]string) { *friendly = append(*friendly, rt.friendly...) } func (rt *referenceTransfer) transfer(obj object, lookup map[string]object) { fIds := make([]interface{}, len(rt.friendly)) for i, f := range rt.friendly { fIds[i] = lookup[f][K_ID] } obj[rt.targetKey] = interface{}(fIds) } func (rl referenceList) parse(value string) (HeaderTransfer, error) { return &referenceTransfer{rl.targetKey, parseList(value)}, nil } func (df dateField) parse(value string) (HeaderTransfer, error) { t, err := time.Parse("2006-01-02 15:04:05 -0700", strings.TrimSpace(value)) if err != nil { return nil, err } return &verbatimTransfer{df.targetKey, strconv.FormatInt(t.Unix(), 10)}, nil } func findQuote(s, start, end string) string { i1 := strings.Index(s, start) if i1 == -1 { return "" } i2 := strings.Index(s[i1+len(start):], end) if i2 == -1 { return "" } return s[i1+len(start) : i1+len(start)+i2] } func resolveRedirects(url *string) error { req, err := http.NewRequest("HEAD", *url, nil) if err != nil { return err } resp, err := http.DefaultClient.Do(req) if err != nil { return err } *url = resp.Request.URL.String() return nil } func (sf snippetField) parse(value string) (HeaderTransfer, error) { st := make(snippetTransfer) if strings.Index(value, `.statista.com/`) != -1 { if sourceUrl := findQuote(value, `<a href="`, `"`); sourceUrl != "" { st["sourceUrl"] = sourceUrl } else { return st, errors.New(`could not find source url; expected «<a href="..."»`) } if imageUrl := findQuote(value, `<img src="`, `"`); imageUrl != "" { st["imageUrl"] = imageUrl } else { return st, errors.New(`could not find image url; expected «<img src="..."»`) } if altText := findQuote(value, ` alt="`, `"`); altText != "" { st["name"] = altText } else { return st, errors.New(`could not find title; expected «alt="..."»`) } maxWidth := strings.TrimSpace(findQuote(value, `max-width:`, `px;`)) if maxWidth == "1000" { st["kind"] = "statista/statistik" } else if maxWidth == "960" { st["kind"] = "statista/infografik" } else { return st, errors.New(`could not determine kind; expected «max-width:...px;»`) } } else if strings.Index(value, `.amazon.de/`) != -1 { if purchaseUrl := findQuote(value, ` href="`, `"`); purchaseUrl != "" { st["buyUrl"] = purchaseUrl } else { return st, errors.New(`could not find purchase url; expected « href="..."»`) } if imageUrl := findQuote(value, ` src="`, `"`); imageUrl != "" { if strings.HasPrefix(imageUrl, "//") { imageUrl = "http:" + imageUrl } if err := resolveRedirects(&imageUrl); err != nil { return st, err } st["imageUrl"] = imageUrl } else { return st, errors.New(`could not find image url; expected « src="..."»`) } } else { return st, errors.New(`snippet not recognized; expected to find «.statista.com/» or «.amazon.de/»`) } return st, nil } func (st snippetTransfer) collectFriendly(friendly *[]string) { } func (st snippetTransfer) transfer(obj object, lookup map[string]object) { for k, v := range st { obj[k] = v } } func CollectFriendly(ods ...objectDescriptor) []string { friendly := ma
sing(ht HeaderTransfer, lookup map[string]object) []string { friendly := make([]string, 0) ht.collectFriendly(&friendly) missing := make([]string, 0) for _, f := range friendly { if _, present := lookup[f]; !present { missing = append(missing, f) } } return missing } var headerParsers = map[string]HeaderParser{ "friendly-id": verbatimString{targetKey: "friendlyId"}, "date": dateField{"date"}, "title": verbatimString{targetKey: "name"}, "tags": referenceList{"$tags"}, "source-urls": verbatimList{"sourceUrls"}, "paraph": verbatimString{targetKey: "paraph"}, "visibility": verbatimString{targetKey: "visibility", values: []string{"", "editor"}}, "dateline": verbatimString{targetKey: "dateline"}, "image-url": verbatimString{targetKey: "imageUrl"}, "image-credits": verbatimString{targetKey: "imageCredits"}, "image-source": verbatimString{targetKey: "imageSource"}, "image-text": verbatimString{targetKey: "imageText"}, "components": referenceList{"$components"}, "speaker": verbatimString{targetKey: "speaker"}, "position": verbatimString{targetKey: "position"}, "sources": verbatimString{targetKey: "sources"}, "snippet": snippetField{}, "kind": verbatimString{targetKey: "kind", values: []string{"statista/statistik", "statista/infografik"}}, "source-url": verbatimString{targetKey: "sourceUrl"}, "origin": verbatimString{targetKey: "origin"}, "origin-url": verbatimString{targetKey: "originUrl"}, "authors": verbatimString{targetKey: "authors"}, "publisher": verbatimString{targetKey: "publisher"}, "purchase-url": verbatimString{targetKey: "purchaseUrl"}, } func computeHeaderLookup(data map[string]string) map[string]map[string]bool { result := make(map[string]map[string]bool, len(data)) for key, fieldstr := range data { fields := strings.Split(strings.ToLower(fieldstr), " ") set := make(map[string]bool, len(fields)) for _, f := range fields { set[strings.TrimSpace(f)] = true } result[key] = set } return result } var validHeaders = computeHeaderLookup(map[string]string{ "COMPONENT": "Friendly-Id Date Title Tags Source-Urls", "EVENT": "Friendly-Id Date Paraph Visibility Tags Dateline Title Image-Url Image-Credits Image-Source Image-Text Components", "STATEMENT": "Friendly-Id Date Paraph Visibility Tags Speaker Position Image-Url Image-Credits Image-Source Sources Source-Urls", "STATISTIC": "Friendly-Id Date Paraph Visibility Tags Snippet Kind Title Source-Url Image-Url Origin Origin-Url", "BOOK": "Friendly-Id Date Paraph Visibility Tags Authors Title Publisher Snippet Image-Url Purchase-Url", }) var hasBody = map[string]bool{ "COMPONENT": true, "STATEMENT": true, } func parseInter(contentLines []string, remarks *Remarks) (ods []objectDescriptor) { ods = make([]objectDescriptor, 0) if len(contentLines) == 0 { return } contentLines = append(append(contentLines, ""), "") // sentinel for storing the final object cod := objectDescriptor{start: -1} blanks := 0 fieldStart := 0 headerKey := "" headerValue := "" finishField := func() { hk := headerKey if hk == "" { return } headerKey = "" if !validHeaders[cod.initial[0]][hk] { remarks.AddError(fieldStart, "invalid header field: %v", hk) return } parser, present := headerParsers[hk] if !present { remarks.AddError(fieldStart, "unknown header field: %v", hk) } ht, err := parser.parse(headerValue) if err != nil { remarks.AddError(fieldStart, "error parsing field: %v", err.Error()) return } cod.header[hk] = Header{fieldStart, ht} } for i, l := range contentLines { // no trimming yet, for whitespace makes a difference (continuation of header field) if l == "" { blanks += 1 if cod.start == -1 { continue // !!! } if headerKey != "" { finishField() } if blanks == 2 || !hasBody[cod.initial[0]] { ods = append(ods, cod) cod = objectDescriptor{start: -1} continue // !!! } if cod.body == nil { cod.body = make([]string, 0) } else { cod.body = append(cod.body, "") } continue // !!! } // blanks only counts consecutive EMPTY lines; a line containing only a comment is ignored, but not counted! blanks = 0 // body takes preference before comments (no special handling of # in body) if cod.body != nil { cod.body = append(cod.body, l) continue // !!! } // a comment is either prefixed by "#"" at the beginning of the line or by " #" otherwise ci := 0 if !strings.HasPrefix(l, "#") { ci = strings.Index(l, " #") } if ci != -1 { if ci == 0 { // disallow header continuation finishField() // remove remark if strings.HasPrefix(l, "#!") || strings.HasPrefix(l, "#:") { remarks.AddRemover(i) } } l = l[:ci] } if l == "" { continue // !!! } if cod.start == -1 { cod.initial = strings.SplitN(l, " ", 2) for j, ini := range cod.initial { cod.initial[j] = strings.TrimSpace(ini) } if len(cod.initial) != 2 || strings.IndexByte(cod.initial[1], ' ') != -1 { remarks.AddError(i, "expected initial line of the form 'TYPE id'") } else { if _, present := validHeaders[cod.initial[0]]; present { cod.start = i cod.header = make(map[string]Header) } else { remarks.AddError(i, "unknown type: %v", cod.initial[0]) } } continue // !!! } if headerKey != "" && unicode.IsSpace(rune(l[0])) { // continuation of previous header; do NOT trim trailing space! (see below) headerValue += " " + strings.TrimLeftFunc(l, unicode.IsSpace) continue // !!! } hs := strings.SplitN(l, ":", 2) if len(hs) != 2 { remarks.AddError(i, "expected header line of the form 'Key: Value'") } else { finishField() fieldStart = i headerKey = strings.ToLower(hs[0]) if _, present := cod.header[headerKey]; present { remarks.AddError(i, "redeclared header field: %v", headerKey) } // do NOT trim trailing space for it may carry semantics (such as trailing COMMA SPACE) headerValue = strings.TrimLeftFunc(hs[1], unicode.IsSpace) } } return } func computeFriendly(title string) string { fields := strings.Fields(strings.Map(func(r rune) rune { if unicode.IsLetter(r) { return unicode.ToLower(r) } else { return ' ' } }, title)) l := 0 i := 0 for l < 33 && i < len(fields) { l += len(fields[i]) l += 1 i++ } if l < 33 { return "" } return strings.Join(fields[:i], "-") } func applyToObjects(db *sql.DB, ods []objectDescriptor, objects objectMap, remarks *Remarks, initialVersion string) error { friendlyMap := make(map[string]object) // collect references and load them from the database friendly := CollectFriendly(ods...) if err := objects.queryByFriendly(db, friendly, nil); err != nil { return err } for _, obj := range objects { if friendly, ok := obj["friendlyId"].(string); ok { friendlyMap[friendly] = obj } } // load objects from database (those that exist anyway) keys := make([]string, len(ods)) for i, od := range ods { keys[i] = od.initial[1] } if err := objects.queryByKeys(db, keys); err != nil { return err } // transfer fields from objectDescriptors into objects for odi, od := range ods { obj, present := objects[od.initial[1]] if !present { obj = object{K_TYPE: strings.ToLower(od.initial[0]), K_ID: od.initial[1], K_VERSION: initialVersion} objects[od.initial[1]] = obj } for _, h := range od.header { missing := CollectMissing(h.transfer, friendlyMap) if len(missing) == 0 { h.transfer.transfer(obj, friendlyMap) } else { for _, m := range missing { remarks.AddError(h.line, "NOT FOUND: %v", m) } } } // handle body if od.body == nil { delete(obj, "content") } else { obj["content"] = strings.Join(od.body, "\n") } // handle non-extant components :( if _, present := obj["$components"]; !present && obj[K_TYPE] == "event" { i := odi for ; i > 0 && ods[i-1].initial[0] == "COMPONENT"; i-- { } if i < odi { cs := make([]interface{}, odi-i) for j := i; j < odi; j++ { cs[j-i] = ods[j].initial[1] } obj["$components"] = interface{}(cs) } } // handle non-extant friendlyId if friendly, present := obj["friendlyId"]; present { keys := make([]string, 0) if err := objects.queryByFriendly(db, []string{friendly.(string)}, &keys); err != nil { return err } if len(keys) != 0 && keys[0] != od.initial[1] { remarks.AddError(od.start, "Friendly-Id already taken") } } else { friendly := "" if title, ok := obj["content"].(string); ok { friendly = computeFriendly(title) } if title, ok := obj["name"].(string); friendly == "" && ok { friendly = computeFriendly(title) } if friendly != "" { friendlyBase := friendly for fi := 0; ; fi++ { // I'm afraid we have to check for uniqueness if fi != 0 { friendly = friendlyBase + "-" + strconv.Itoa(fi) } keys := make([]string, 0) if err := objects.queryByFriendly(db, []string{friendly}, &keys); err != nil { return err } if len(keys) == 0 { break } } obj["friendlyId"] = friendly friendlyMap[friendly] = obj } else { remarks.AddError(od.start, "could not compute Friendly-Id; check title or text body") } } } return nil }
ke([]string, 0) for _, od := range ods { for _, h := range od.header { h.transfer.collectFriendly(&friendly) } } return friendly } func CollectMis
identifier_body
inter.go
// copyright Matthias Büchse, 2019 package main import ( "database/sql" "encoding/json" "errors" "fmt" "io" "log" "net/http" "sort" "strconv" "strings" "text/template" "time" "unicode" ) type Inter interface { Serialize(wr io.Writer, objects objectMap, obj object) error } func formatDate(layout string, date interface{}) string { var dateStr string switch v := date.(type) { case json.Number: dateStr = string(v) case string: dateStr = v default: dateStr = "" } i64, err := strconv.ParseInt(dateStr, 10, 64) if err != nil { log.Fatal(err) } return time.Unix(i64, 0).Format(layout) } func friendly(objects objectMap, key string) interface{} { return objects[key]["friendlyId"] } func joinStrings(delim string, args []interface{}) string { sargs := make([]string, len(args)) for i, arg := range args { sargs[i] = arg.(string) } return strings.Join(sargs, delim) } type myTemplate struct { tmpl *template.Template } func NewInter(templatePath string) Inter { result := myTemplate{template.New("blubb")} t := result.tmpl t.Funcs(map[string]interface{}{"formatDate": formatDate, "friendly": friendly, "joinStrings": joinStrings}) template.Must(t.ParseGlob(templatePath + "/*")) return result } func (template myTemplate) Serialize(wr io.Writer, objects objectMap, obj object) error { // obviously not re-entrant restore := func() { delete(objects, "_current") } defer restore() objects["_current"] = obj return template.tmpl.ExecuteTemplate(wr, obj[K_TYPE].(string), objects) } const ( SKIP = -1 INFO = 0 HINT = 1 ERROR = 2 MAX = 2 ) type remark struct { line int text string severity int skip int } // for sorting type RemarkSlice []*remark func (p RemarkSlice) Len() int { return len(p) } func (p RemarkSlice) Less(i, j int) bool { return p[i].line < p[j].line } func (p RemarkSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (r remark) Format() string { if r.severity == SKIP { return "" } else if r.severity == ERROR { return fmt.Sprintf("#! >>>>>>>>>>>>>>>>>>>> %v <<<<<<<<<<<<<<<<<<<<\n", r.text) } else if r.severity == HINT { return fmt.Sprintf("#: >>>>>>>> %v <<<<<<<<\n", r.text) } else { return fmt.Sprintf("#: %v\n", r.text) } } type Remarks struct { histo [MAX + 1]int severity int descriptors []*remark } func New() *Remarks { return &Remarks{[MAX + 1]int{}, 0, make([]*remark, 0)} } func (rs *Remarks) add(r *remark) { rs.descriptors = append(rs.descriptors, r) if r.severity > rs.severity { rs.severity = r.severity } if r.severity >= 0 && r.severity <= MAX { rs.histo[r.severity]++ } } func (rs *Remarks) AddError(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), ERROR, 0}) } func (rs *Remarks) AddHint(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), HINT, 0}) } func (rs *Remarks) AddInfo(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), INFO, 0}) } func (rs *Remarks) AddRemover(line int) { r := &remark{line: line, severity: SKIP, skip: 1} rs.descriptors = append(rs.descriptors, r) } func (rs *Remarks) E
contentLines []string) string { content := "" cl := 0 sort.Sort(RemarkSlice(rs.descriptors)) for _, ed := range rs.descriptors { if ed.line-cl >= 0 { content += strings.Join(contentLines[cl:ed.line], "\n") if ed.line-cl > 0 { content += "\n" } cl = ed.line + ed.skip } content += ed.Format() } content += strings.Join(contentLines[cl:], "\n") return content } func (rs *Remarks) Severity() int { return rs.severity } func (rs *Remarks) Histo(severity int) int { if severity >= 0 && severity <= MAX { return rs.histo[severity] } return 0 } type HeaderTransfer interface { collectFriendly(friendly *[]string) transfer(obj object, lookup map[string]object) } type Header struct { line int transfer HeaderTransfer } type objectDescriptor struct { start int initial []string header map[string]Header body []string } type HeaderParser interface { parse(value string) (HeaderTransfer, error) } type verbatimString struct { targetKey string values []string noTrim bool // default: trim spaces (so much for "verbatim") } type verbatimList struct { targetKey string } type referenceList struct { targetKey string } type dateField struct { targetKey string } type snippetField struct{} type verbatimTransfer struct { targetKey string value interface{} } type referenceTransfer struct { targetKey string friendly []string } type snippetTransfer object func (vt *verbatimTransfer) collectFriendly(friendly *[]string) { } func (vt *verbatimTransfer) transfer(obj object, lookup map[string]object) { if vt.value == nil { delete(obj, vt.targetKey) } else { obj[vt.targetKey] = vt.value } } func (vs verbatimString) parse(value string) (HeaderTransfer, error) { if !vs.noTrim { value = strings.TrimSpace(value) } var ivalue interface{} = value if vs.values != nil { i := -1 for j, v := range vs.values { if value == v { i = j break } } if i == -1 { return nil, fmt.Errorf("field value needs to be one of: %v", vs.values) } if value == "" { // FAT DOG: if we have a fixed set of possible values, "" means <remove field> ivalue = nil } } return &verbatimTransfer{vs.targetKey, ivalue}, nil } func parseList(value string) []string { // CAUTION: separator is COMMA followed by SPACE, because (e.g.) URLs may contain commas (but not spaces) values := strings.Split(value, ", ") for i, v := range values { values[i] = strings.TrimSpace(v) } if len(values) >= 1 && values[len(values)-1] == "" { // handle empty list as well as trailing comma values = values[:len(values)-1] } return values } func (vl verbatimList) parse(value string) (HeaderTransfer, error) { return &verbatimTransfer{vl.targetKey, parseList(value)}, nil } func (rt *referenceTransfer) collectFriendly(friendly *[]string) { *friendly = append(*friendly, rt.friendly...) } func (rt *referenceTransfer) transfer(obj object, lookup map[string]object) { fIds := make([]interface{}, len(rt.friendly)) for i, f := range rt.friendly { fIds[i] = lookup[f][K_ID] } obj[rt.targetKey] = interface{}(fIds) } func (rl referenceList) parse(value string) (HeaderTransfer, error) { return &referenceTransfer{rl.targetKey, parseList(value)}, nil } func (df dateField) parse(value string) (HeaderTransfer, error) { t, err := time.Parse("2006-01-02 15:04:05 -0700", strings.TrimSpace(value)) if err != nil { return nil, err } return &verbatimTransfer{df.targetKey, strconv.FormatInt(t.Unix(), 10)}, nil } func findQuote(s, start, end string) string { i1 := strings.Index(s, start) if i1 == -1 { return "" } i2 := strings.Index(s[i1+len(start):], end) if i2 == -1 { return "" } return s[i1+len(start) : i1+len(start)+i2] } func resolveRedirects(url *string) error { req, err := http.NewRequest("HEAD", *url, nil) if err != nil { return err } resp, err := http.DefaultClient.Do(req) if err != nil { return err } *url = resp.Request.URL.String() return nil } func (sf snippetField) parse(value string) (HeaderTransfer, error) { st := make(snippetTransfer) if strings.Index(value, `.statista.com/`) != -1 { if sourceUrl := findQuote(value, `<a href="`, `"`); sourceUrl != "" { st["sourceUrl"] = sourceUrl } else { return st, errors.New(`could not find source url; expected «<a href="..."»`) } if imageUrl := findQuote(value, `<img src="`, `"`); imageUrl != "" { st["imageUrl"] = imageUrl } else { return st, errors.New(`could not find image url; expected «<img src="..."»`) } if altText := findQuote(value, ` alt="`, `"`); altText != "" { st["name"] = altText } else { return st, errors.New(`could not find title; expected «alt="..."»`) } maxWidth := strings.TrimSpace(findQuote(value, `max-width:`, `px;`)) if maxWidth == "1000" { st["kind"] = "statista/statistik" } else if maxWidth == "960" { st["kind"] = "statista/infografik" } else { return st, errors.New(`could not determine kind; expected «max-width:...px;»`) } } else if strings.Index(value, `.amazon.de/`) != -1 { if purchaseUrl := findQuote(value, ` href="`, `"`); purchaseUrl != "" { st["buyUrl"] = purchaseUrl } else { return st, errors.New(`could not find purchase url; expected « href="..."»`) } if imageUrl := findQuote(value, ` src="`, `"`); imageUrl != "" { if strings.HasPrefix(imageUrl, "//") { imageUrl = "http:" + imageUrl } if err := resolveRedirects(&imageUrl); err != nil { return st, err } st["imageUrl"] = imageUrl } else { return st, errors.New(`could not find image url; expected « src="..."»`) } } else { return st, errors.New(`snippet not recognized; expected to find «.statista.com/» or «.amazon.de/»`) } return st, nil } func (st snippetTransfer) collectFriendly(friendly *[]string) { } func (st snippetTransfer) transfer(obj object, lookup map[string]object) { for k, v := range st { obj[k] = v } } func CollectFriendly(ods ...objectDescriptor) []string { friendly := make([]string, 0) for _, od := range ods { for _, h := range od.header { h.transfer.collectFriendly(&friendly) } } return friendly } func CollectMissing(ht HeaderTransfer, lookup map[string]object) []string { friendly := make([]string, 0) ht.collectFriendly(&friendly) missing := make([]string, 0) for _, f := range friendly { if _, present := lookup[f]; !present { missing = append(missing, f) } } return missing } var headerParsers = map[string]HeaderParser{ "friendly-id": verbatimString{targetKey: "friendlyId"}, "date": dateField{"date"}, "title": verbatimString{targetKey: "name"}, "tags": referenceList{"$tags"}, "source-urls": verbatimList{"sourceUrls"}, "paraph": verbatimString{targetKey: "paraph"}, "visibility": verbatimString{targetKey: "visibility", values: []string{"", "editor"}}, "dateline": verbatimString{targetKey: "dateline"}, "image-url": verbatimString{targetKey: "imageUrl"}, "image-credits": verbatimString{targetKey: "imageCredits"}, "image-source": verbatimString{targetKey: "imageSource"}, "image-text": verbatimString{targetKey: "imageText"}, "components": referenceList{"$components"}, "speaker": verbatimString{targetKey: "speaker"}, "position": verbatimString{targetKey: "position"}, "sources": verbatimString{targetKey: "sources"}, "snippet": snippetField{}, "kind": verbatimString{targetKey: "kind", values: []string{"statista/statistik", "statista/infografik"}}, "source-url": verbatimString{targetKey: "sourceUrl"}, "origin": verbatimString{targetKey: "origin"}, "origin-url": verbatimString{targetKey: "originUrl"}, "authors": verbatimString{targetKey: "authors"}, "publisher": verbatimString{targetKey: "publisher"}, "purchase-url": verbatimString{targetKey: "purchaseUrl"}, } func computeHeaderLookup(data map[string]string) map[string]map[string]bool { result := make(map[string]map[string]bool, len(data)) for key, fieldstr := range data { fields := strings.Split(strings.ToLower(fieldstr), " ") set := make(map[string]bool, len(fields)) for _, f := range fields { set[strings.TrimSpace(f)] = true } result[key] = set } return result } var validHeaders = computeHeaderLookup(map[string]string{ "COMPONENT": "Friendly-Id Date Title Tags Source-Urls", "EVENT": "Friendly-Id Date Paraph Visibility Tags Dateline Title Image-Url Image-Credits Image-Source Image-Text Components", "STATEMENT": "Friendly-Id Date Paraph Visibility Tags Speaker Position Image-Url Image-Credits Image-Source Sources Source-Urls", "STATISTIC": "Friendly-Id Date Paraph Visibility Tags Snippet Kind Title Source-Url Image-Url Origin Origin-Url", "BOOK": "Friendly-Id Date Paraph Visibility Tags Authors Title Publisher Snippet Image-Url Purchase-Url", }) var hasBody = map[string]bool{ "COMPONENT": true, "STATEMENT": true, } func parseInter(contentLines []string, remarks *Remarks) (ods []objectDescriptor) { ods = make([]objectDescriptor, 0) if len(contentLines) == 0 { return } contentLines = append(append(contentLines, ""), "") // sentinel for storing the final object cod := objectDescriptor{start: -1} blanks := 0 fieldStart := 0 headerKey := "" headerValue := "" finishField := func() { hk := headerKey if hk == "" { return } headerKey = "" if !validHeaders[cod.initial[0]][hk] { remarks.AddError(fieldStart, "invalid header field: %v", hk) return } parser, present := headerParsers[hk] if !present { remarks.AddError(fieldStart, "unknown header field: %v", hk) } ht, err := parser.parse(headerValue) if err != nil { remarks.AddError(fieldStart, "error parsing field: %v", err.Error()) return } cod.header[hk] = Header{fieldStart, ht} } for i, l := range contentLines { // no trimming yet, for whitespace makes a difference (continuation of header field) if l == "" { blanks += 1 if cod.start == -1 { continue // !!! } if headerKey != "" { finishField() } if blanks == 2 || !hasBody[cod.initial[0]] { ods = append(ods, cod) cod = objectDescriptor{start: -1} continue // !!! } if cod.body == nil { cod.body = make([]string, 0) } else { cod.body = append(cod.body, "") } continue // !!! } // blanks only counts consecutive EMPTY lines; a line containing only a comment is ignored, but not counted! blanks = 0 // body takes preference before comments (no special handling of # in body) if cod.body != nil { cod.body = append(cod.body, l) continue // !!! } // a comment is either prefixed by "#"" at the beginning of the line or by " #" otherwise ci := 0 if !strings.HasPrefix(l, "#") { ci = strings.Index(l, " #") } if ci != -1 { if ci == 0 { // disallow header continuation finishField() // remove remark if strings.HasPrefix(l, "#!") || strings.HasPrefix(l, "#:") { remarks.AddRemover(i) } } l = l[:ci] } if l == "" { continue // !!! } if cod.start == -1 { cod.initial = strings.SplitN(l, " ", 2) for j, ini := range cod.initial { cod.initial[j] = strings.TrimSpace(ini) } if len(cod.initial) != 2 || strings.IndexByte(cod.initial[1], ' ') != -1 { remarks.AddError(i, "expected initial line of the form 'TYPE id'") } else { if _, present := validHeaders[cod.initial[0]]; present { cod.start = i cod.header = make(map[string]Header) } else { remarks.AddError(i, "unknown type: %v", cod.initial[0]) } } continue // !!! } if headerKey != "" && unicode.IsSpace(rune(l[0])) { // continuation of previous header; do NOT trim trailing space! (see below) headerValue += " " + strings.TrimLeftFunc(l, unicode.IsSpace) continue // !!! } hs := strings.SplitN(l, ":", 2) if len(hs) != 2 { remarks.AddError(i, "expected header line of the form 'Key: Value'") } else { finishField() fieldStart = i headerKey = strings.ToLower(hs[0]) if _, present := cod.header[headerKey]; present { remarks.AddError(i, "redeclared header field: %v", headerKey) } // do NOT trim trailing space for it may carry semantics (such as trailing COMMA SPACE) headerValue = strings.TrimLeftFunc(hs[1], unicode.IsSpace) } } return } func computeFriendly(title string) string { fields := strings.Fields(strings.Map(func(r rune) rune { if unicode.IsLetter(r) { return unicode.ToLower(r) } else { return ' ' } }, title)) l := 0 i := 0 for l < 33 && i < len(fields) { l += len(fields[i]) l += 1 i++ } if l < 33 { return "" } return strings.Join(fields[:i], "-") } func applyToObjects(db *sql.DB, ods []objectDescriptor, objects objectMap, remarks *Remarks, initialVersion string) error { friendlyMap := make(map[string]object) // collect references and load them from the database friendly := CollectFriendly(ods...) if err := objects.queryByFriendly(db, friendly, nil); err != nil { return err } for _, obj := range objects { if friendly, ok := obj["friendlyId"].(string); ok { friendlyMap[friendly] = obj } } // load objects from database (those that exist anyway) keys := make([]string, len(ods)) for i, od := range ods { keys[i] = od.initial[1] } if err := objects.queryByKeys(db, keys); err != nil { return err } // transfer fields from objectDescriptors into objects for odi, od := range ods { obj, present := objects[od.initial[1]] if !present { obj = object{K_TYPE: strings.ToLower(od.initial[0]), K_ID: od.initial[1], K_VERSION: initialVersion} objects[od.initial[1]] = obj } for _, h := range od.header { missing := CollectMissing(h.transfer, friendlyMap) if len(missing) == 0 { h.transfer.transfer(obj, friendlyMap) } else { for _, m := range missing { remarks.AddError(h.line, "NOT FOUND: %v", m) } } } // handle body if od.body == nil { delete(obj, "content") } else { obj["content"] = strings.Join(od.body, "\n") } // handle non-extant components :( if _, present := obj["$components"]; !present && obj[K_TYPE] == "event" { i := odi for ; i > 0 && ods[i-1].initial[0] == "COMPONENT"; i-- { } if i < odi { cs := make([]interface{}, odi-i) for j := i; j < odi; j++ { cs[j-i] = ods[j].initial[1] } obj["$components"] = interface{}(cs) } } // handle non-extant friendlyId if friendly, present := obj["friendlyId"]; present { keys := make([]string, 0) if err := objects.queryByFriendly(db, []string{friendly.(string)}, &keys); err != nil { return err } if len(keys) != 0 && keys[0] != od.initial[1] { remarks.AddError(od.start, "Friendly-Id already taken") } } else { friendly := "" if title, ok := obj["content"].(string); ok { friendly = computeFriendly(title) } if title, ok := obj["name"].(string); friendly == "" && ok { friendly = computeFriendly(title) } if friendly != "" { friendlyBase := friendly for fi := 0; ; fi++ { // I'm afraid we have to check for uniqueness if fi != 0 { friendly = friendlyBase + "-" + strconv.Itoa(fi) } keys := make([]string, 0) if err := objects.queryByFriendly(db, []string{friendly}, &keys); err != nil { return err } if len(keys) == 0 { break } } obj["friendlyId"] = friendly friendlyMap[friendly] = obj } else { remarks.AddError(od.start, "could not compute Friendly-Id; check title or text body") } } } return nil }
mbed(
identifier_name
inter.go
// copyright Matthias Büchse, 2019 package main import ( "database/sql" "encoding/json" "errors" "fmt" "io" "log" "net/http" "sort" "strconv" "strings" "text/template" "time" "unicode" ) type Inter interface { Serialize(wr io.Writer, objects objectMap, obj object) error } func formatDate(layout string, date interface{}) string { var dateStr string switch v := date.(type) { case json.Number: dateStr = string(v) case string: dateStr = v default: dateStr = "" } i64, err := strconv.ParseInt(dateStr, 10, 64) if err != nil { log.Fatal(err) } return time.Unix(i64, 0).Format(layout) } func friendly(objects objectMap, key string) interface{} { return objects[key]["friendlyId"] } func joinStrings(delim string, args []interface{}) string { sargs := make([]string, len(args)) for i, arg := range args { sargs[i] = arg.(string) } return strings.Join(sargs, delim) } type myTemplate struct { tmpl *template.Template } func NewInter(templatePath string) Inter { result := myTemplate{template.New("blubb")} t := result.tmpl t.Funcs(map[string]interface{}{"formatDate": formatDate, "friendly": friendly, "joinStrings": joinStrings}) template.Must(t.ParseGlob(templatePath + "/*")) return result } func (template myTemplate) Serialize(wr io.Writer, objects objectMap, obj object) error { // obviously not re-entrant restore := func() { delete(objects, "_current") } defer restore() objects["_current"] = obj return template.tmpl.ExecuteTemplate(wr, obj[K_TYPE].(string), objects) } const ( SKIP = -1 INFO = 0 HINT = 1 ERROR = 2 MAX = 2 ) type remark struct { line int text string severity int skip int } // for sorting type RemarkSlice []*remark func (p RemarkSlice) Len() int { return len(p) } func (p RemarkSlice) Less(i, j int) bool { return p[i].line < p[j].line } func (p RemarkSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (r remark) Format() string { if r.severity == SKIP { return "" } else if r.severity == ERROR { return fmt.Sprintf("#! >>>>>>>>>>>>>>>>>>>> %v <<<<<<<<<<<<<<<<<<<<\n", r.text) } else if r.severity == HINT { return fmt.Sprintf("#: >>>>>>>> %v <<<<<<<<\n", r.text) } else { return fmt.Sprintf("#: %v\n", r.text) } } type Remarks struct { histo [MAX + 1]int severity int descriptors []*remark } func New() *Remarks { return &Remarks{[MAX + 1]int{}, 0, make([]*remark, 0)} } func (rs *Remarks) add(r *remark) { rs.descriptors = append(rs.descriptors, r) if r.severity > rs.severity { rs.severity = r.severity } if r.severity >= 0 && r.severity <= MAX { rs.histo[r.severity]++ } } func (rs *Remarks) AddError(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), ERROR, 0}) } func (rs *Remarks) AddHint(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), HINT, 0}) } func (rs *Remarks) AddInfo(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), INFO, 0}) } func (rs *Remarks) AddRemover(line int) { r := &remark{line: line, severity: SKIP, skip: 1} rs.descriptors = append(rs.descriptors, r) } func (rs *Remarks) Embed(contentLines []string) string { content := "" cl := 0 sort.Sort(RemarkSlice(rs.descriptors)) for _, ed := range rs.descriptors { if ed.line-cl >= 0 { content += strings.Join(contentLines[cl:ed.line], "\n") if ed.line-cl > 0 { content += "\n" } cl = ed.line + ed.skip } content += ed.Format() } content += strings.Join(contentLines[cl:], "\n") return content } func (rs *Remarks) Severity() int { return rs.severity } func (rs *Remarks) Histo(severity int) int { if severity >= 0 && severity <= MAX { return rs.histo[severity] } return 0 } type HeaderTransfer interface { collectFriendly(friendly *[]string) transfer(obj object, lookup map[string]object) } type Header struct { line int transfer HeaderTransfer } type objectDescriptor struct { start int initial []string header map[string]Header body []string } type HeaderParser interface { parse(value string) (HeaderTransfer, error) } type verbatimString struct { targetKey string values []string noTrim bool // default: trim spaces (so much for "verbatim") } type verbatimList struct { targetKey string } type referenceList struct { targetKey string } type dateField struct { targetKey string } type snippetField struct{} type verbatimTransfer struct { targetKey string value interface{} }
friendly []string } type snippetTransfer object func (vt *verbatimTransfer) collectFriendly(friendly *[]string) { } func (vt *verbatimTransfer) transfer(obj object, lookup map[string]object) { if vt.value == nil { delete(obj, vt.targetKey) } else { obj[vt.targetKey] = vt.value } } func (vs verbatimString) parse(value string) (HeaderTransfer, error) { if !vs.noTrim { value = strings.TrimSpace(value) } var ivalue interface{} = value if vs.values != nil { i := -1 for j, v := range vs.values { if value == v { i = j break } } if i == -1 { return nil, fmt.Errorf("field value needs to be one of: %v", vs.values) } if value == "" { // FAT DOG: if we have a fixed set of possible values, "" means <remove field> ivalue = nil } } return &verbatimTransfer{vs.targetKey, ivalue}, nil } func parseList(value string) []string { // CAUTION: separator is COMMA followed by SPACE, because (e.g.) URLs may contain commas (but not spaces) values := strings.Split(value, ", ") for i, v := range values { values[i] = strings.TrimSpace(v) } if len(values) >= 1 && values[len(values)-1] == "" { // handle empty list as well as trailing comma values = values[:len(values)-1] } return values } func (vl verbatimList) parse(value string) (HeaderTransfer, error) { return &verbatimTransfer{vl.targetKey, parseList(value)}, nil } func (rt *referenceTransfer) collectFriendly(friendly *[]string) { *friendly = append(*friendly, rt.friendly...) } func (rt *referenceTransfer) transfer(obj object, lookup map[string]object) { fIds := make([]interface{}, len(rt.friendly)) for i, f := range rt.friendly { fIds[i] = lookup[f][K_ID] } obj[rt.targetKey] = interface{}(fIds) } func (rl referenceList) parse(value string) (HeaderTransfer, error) { return &referenceTransfer{rl.targetKey, parseList(value)}, nil } func (df dateField) parse(value string) (HeaderTransfer, error) { t, err := time.Parse("2006-01-02 15:04:05 -0700", strings.TrimSpace(value)) if err != nil { return nil, err } return &verbatimTransfer{df.targetKey, strconv.FormatInt(t.Unix(), 10)}, nil } func findQuote(s, start, end string) string { i1 := strings.Index(s, start) if i1 == -1 { return "" } i2 := strings.Index(s[i1+len(start):], end) if i2 == -1 { return "" } return s[i1+len(start) : i1+len(start)+i2] } func resolveRedirects(url *string) error { req, err := http.NewRequest("HEAD", *url, nil) if err != nil { return err } resp, err := http.DefaultClient.Do(req) if err != nil { return err } *url = resp.Request.URL.String() return nil } func (sf snippetField) parse(value string) (HeaderTransfer, error) { st := make(snippetTransfer) if strings.Index(value, `.statista.com/`) != -1 { if sourceUrl := findQuote(value, `<a href="`, `"`); sourceUrl != "" { st["sourceUrl"] = sourceUrl } else { return st, errors.New(`could not find source url; expected «<a href="..."»`) } if imageUrl := findQuote(value, `<img src="`, `"`); imageUrl != "" { st["imageUrl"] = imageUrl } else { return st, errors.New(`could not find image url; expected «<img src="..."»`) } if altText := findQuote(value, ` alt="`, `"`); altText != "" { st["name"] = altText } else { return st, errors.New(`could not find title; expected «alt="..."»`) } maxWidth := strings.TrimSpace(findQuote(value, `max-width:`, `px;`)) if maxWidth == "1000" { st["kind"] = "statista/statistik" } else if maxWidth == "960" { st["kind"] = "statista/infografik" } else { return st, errors.New(`could not determine kind; expected «max-width:...px;»`) } } else if strings.Index(value, `.amazon.de/`) != -1 { if purchaseUrl := findQuote(value, ` href="`, `"`); purchaseUrl != "" { st["buyUrl"] = purchaseUrl } else { return st, errors.New(`could not find purchase url; expected « href="..."»`) } if imageUrl := findQuote(value, ` src="`, `"`); imageUrl != "" { if strings.HasPrefix(imageUrl, "//") { imageUrl = "http:" + imageUrl } if err := resolveRedirects(&imageUrl); err != nil { return st, err } st["imageUrl"] = imageUrl } else { return st, errors.New(`could not find image url; expected « src="..."»`) } } else { return st, errors.New(`snippet not recognized; expected to find «.statista.com/» or «.amazon.de/»`) } return st, nil } func (st snippetTransfer) collectFriendly(friendly *[]string) { } func (st snippetTransfer) transfer(obj object, lookup map[string]object) { for k, v := range st { obj[k] = v } } func CollectFriendly(ods ...objectDescriptor) []string { friendly := make([]string, 0) for _, od := range ods { for _, h := range od.header { h.transfer.collectFriendly(&friendly) } } return friendly } func CollectMissing(ht HeaderTransfer, lookup map[string]object) []string { friendly := make([]string, 0) ht.collectFriendly(&friendly) missing := make([]string, 0) for _, f := range friendly { if _, present := lookup[f]; !present { missing = append(missing, f) } } return missing } var headerParsers = map[string]HeaderParser{ "friendly-id": verbatimString{targetKey: "friendlyId"}, "date": dateField{"date"}, "title": verbatimString{targetKey: "name"}, "tags": referenceList{"$tags"}, "source-urls": verbatimList{"sourceUrls"}, "paraph": verbatimString{targetKey: "paraph"}, "visibility": verbatimString{targetKey: "visibility", values: []string{"", "editor"}}, "dateline": verbatimString{targetKey: "dateline"}, "image-url": verbatimString{targetKey: "imageUrl"}, "image-credits": verbatimString{targetKey: "imageCredits"}, "image-source": verbatimString{targetKey: "imageSource"}, "image-text": verbatimString{targetKey: "imageText"}, "components": referenceList{"$components"}, "speaker": verbatimString{targetKey: "speaker"}, "position": verbatimString{targetKey: "position"}, "sources": verbatimString{targetKey: "sources"}, "snippet": snippetField{}, "kind": verbatimString{targetKey: "kind", values: []string{"statista/statistik", "statista/infografik"}}, "source-url": verbatimString{targetKey: "sourceUrl"}, "origin": verbatimString{targetKey: "origin"}, "origin-url": verbatimString{targetKey: "originUrl"}, "authors": verbatimString{targetKey: "authors"}, "publisher": verbatimString{targetKey: "publisher"}, "purchase-url": verbatimString{targetKey: "purchaseUrl"}, } func computeHeaderLookup(data map[string]string) map[string]map[string]bool { result := make(map[string]map[string]bool, len(data)) for key, fieldstr := range data { fields := strings.Split(strings.ToLower(fieldstr), " ") set := make(map[string]bool, len(fields)) for _, f := range fields { set[strings.TrimSpace(f)] = true } result[key] = set } return result } var validHeaders = computeHeaderLookup(map[string]string{ "COMPONENT": "Friendly-Id Date Title Tags Source-Urls", "EVENT": "Friendly-Id Date Paraph Visibility Tags Dateline Title Image-Url Image-Credits Image-Source Image-Text Components", "STATEMENT": "Friendly-Id Date Paraph Visibility Tags Speaker Position Image-Url Image-Credits Image-Source Sources Source-Urls", "STATISTIC": "Friendly-Id Date Paraph Visibility Tags Snippet Kind Title Source-Url Image-Url Origin Origin-Url", "BOOK": "Friendly-Id Date Paraph Visibility Tags Authors Title Publisher Snippet Image-Url Purchase-Url", }) var hasBody = map[string]bool{ "COMPONENT": true, "STATEMENT": true, } func parseInter(contentLines []string, remarks *Remarks) (ods []objectDescriptor) { ods = make([]objectDescriptor, 0) if len(contentLines) == 0 { return } contentLines = append(append(contentLines, ""), "") // sentinel for storing the final object cod := objectDescriptor{start: -1} blanks := 0 fieldStart := 0 headerKey := "" headerValue := "" finishField := func() { hk := headerKey if hk == "" { return } headerKey = "" if !validHeaders[cod.initial[0]][hk] { remarks.AddError(fieldStart, "invalid header field: %v", hk) return } parser, present := headerParsers[hk] if !present { remarks.AddError(fieldStart, "unknown header field: %v", hk) } ht, err := parser.parse(headerValue) if err != nil { remarks.AddError(fieldStart, "error parsing field: %v", err.Error()) return } cod.header[hk] = Header{fieldStart, ht} } for i, l := range contentLines { // no trimming yet, for whitespace makes a difference (continuation of header field) if l == "" { blanks += 1 if cod.start == -1 { continue // !!! } if headerKey != "" { finishField() } if blanks == 2 || !hasBody[cod.initial[0]] { ods = append(ods, cod) cod = objectDescriptor{start: -1} continue // !!! } if cod.body == nil { cod.body = make([]string, 0) } else { cod.body = append(cod.body, "") } continue // !!! } // blanks only counts consecutive EMPTY lines; a line containing only a comment is ignored, but not counted! blanks = 0 // body takes preference before comments (no special handling of # in body) if cod.body != nil { cod.body = append(cod.body, l) continue // !!! } // a comment is either prefixed by "#"" at the beginning of the line or by " #" otherwise ci := 0 if !strings.HasPrefix(l, "#") { ci = strings.Index(l, " #") } if ci != -1 { if ci == 0 { // disallow header continuation finishField() // remove remark if strings.HasPrefix(l, "#!") || strings.HasPrefix(l, "#:") { remarks.AddRemover(i) } } l = l[:ci] } if l == "" { continue // !!! } if cod.start == -1 { cod.initial = strings.SplitN(l, " ", 2) for j, ini := range cod.initial { cod.initial[j] = strings.TrimSpace(ini) } if len(cod.initial) != 2 || strings.IndexByte(cod.initial[1], ' ') != -1 { remarks.AddError(i, "expected initial line of the form 'TYPE id'") } else { if _, present := validHeaders[cod.initial[0]]; present { cod.start = i cod.header = make(map[string]Header) } else { remarks.AddError(i, "unknown type: %v", cod.initial[0]) } } continue // !!! } if headerKey != "" && unicode.IsSpace(rune(l[0])) { // continuation of previous header; do NOT trim trailing space! (see below) headerValue += " " + strings.TrimLeftFunc(l, unicode.IsSpace) continue // !!! } hs := strings.SplitN(l, ":", 2) if len(hs) != 2 { remarks.AddError(i, "expected header line of the form 'Key: Value'") } else { finishField() fieldStart = i headerKey = strings.ToLower(hs[0]) if _, present := cod.header[headerKey]; present { remarks.AddError(i, "redeclared header field: %v", headerKey) } // do NOT trim trailing space for it may carry semantics (such as trailing COMMA SPACE) headerValue = strings.TrimLeftFunc(hs[1], unicode.IsSpace) } } return } func computeFriendly(title string) string { fields := strings.Fields(strings.Map(func(r rune) rune { if unicode.IsLetter(r) { return unicode.ToLower(r) } else { return ' ' } }, title)) l := 0 i := 0 for l < 33 && i < len(fields) { l += len(fields[i]) l += 1 i++ } if l < 33 { return "" } return strings.Join(fields[:i], "-") } func applyToObjects(db *sql.DB, ods []objectDescriptor, objects objectMap, remarks *Remarks, initialVersion string) error { friendlyMap := make(map[string]object) // collect references and load them from the database friendly := CollectFriendly(ods...) if err := objects.queryByFriendly(db, friendly, nil); err != nil { return err } for _, obj := range objects { if friendly, ok := obj["friendlyId"].(string); ok { friendlyMap[friendly] = obj } } // load objects from database (those that exist anyway) keys := make([]string, len(ods)) for i, od := range ods { keys[i] = od.initial[1] } if err := objects.queryByKeys(db, keys); err != nil { return err } // transfer fields from objectDescriptors into objects for odi, od := range ods { obj, present := objects[od.initial[1]] if !present { obj = object{K_TYPE: strings.ToLower(od.initial[0]), K_ID: od.initial[1], K_VERSION: initialVersion} objects[od.initial[1]] = obj } for _, h := range od.header { missing := CollectMissing(h.transfer, friendlyMap) if len(missing) == 0 { h.transfer.transfer(obj, friendlyMap) } else { for _, m := range missing { remarks.AddError(h.line, "NOT FOUND: %v", m) } } } // handle body if od.body == nil { delete(obj, "content") } else { obj["content"] = strings.Join(od.body, "\n") } // handle non-extant components :( if _, present := obj["$components"]; !present && obj[K_TYPE] == "event" { i := odi for ; i > 0 && ods[i-1].initial[0] == "COMPONENT"; i-- { } if i < odi { cs := make([]interface{}, odi-i) for j := i; j < odi; j++ { cs[j-i] = ods[j].initial[1] } obj["$components"] = interface{}(cs) } } // handle non-extant friendlyId if friendly, present := obj["friendlyId"]; present { keys := make([]string, 0) if err := objects.queryByFriendly(db, []string{friendly.(string)}, &keys); err != nil { return err } if len(keys) != 0 && keys[0] != od.initial[1] { remarks.AddError(od.start, "Friendly-Id already taken") } } else { friendly := "" if title, ok := obj["content"].(string); ok { friendly = computeFriendly(title) } if title, ok := obj["name"].(string); friendly == "" && ok { friendly = computeFriendly(title) } if friendly != "" { friendlyBase := friendly for fi := 0; ; fi++ { // I'm afraid we have to check for uniqueness if fi != 0 { friendly = friendlyBase + "-" + strconv.Itoa(fi) } keys := make([]string, 0) if err := objects.queryByFriendly(db, []string{friendly}, &keys); err != nil { return err } if len(keys) == 0 { break } } obj["friendlyId"] = friendly friendlyMap[friendly] = obj } else { remarks.AddError(od.start, "could not compute Friendly-Id; check title or text body") } } } return nil }
type referenceTransfer struct { targetKey string
random_line_split
inter.go
// copyright Matthias Büchse, 2019 package main import ( "database/sql" "encoding/json" "errors" "fmt" "io" "log" "net/http" "sort" "strconv" "strings" "text/template" "time" "unicode" ) type Inter interface { Serialize(wr io.Writer, objects objectMap, obj object) error } func formatDate(layout string, date interface{}) string { var dateStr string switch v := date.(type) { case json.Number: dateStr = string(v) case string: dateStr = v default: dateStr = "" } i64, err := strconv.ParseInt(dateStr, 10, 64) if err != nil { log.Fatal(err) } return time.Unix(i64, 0).Format(layout) } func friendly(objects objectMap, key string) interface{} { return objects[key]["friendlyId"] } func joinStrings(delim string, args []interface{}) string { sargs := make([]string, len(args)) for i, arg := range args { sargs[i] = arg.(string) } return strings.Join(sargs, delim) } type myTemplate struct { tmpl *template.Template } func NewInter(templatePath string) Inter { result := myTemplate{template.New("blubb")} t := result.tmpl t.Funcs(map[string]interface{}{"formatDate": formatDate, "friendly": friendly, "joinStrings": joinStrings}) template.Must(t.ParseGlob(templatePath + "/*")) return result } func (template myTemplate) Serialize(wr io.Writer, objects objectMap, obj object) error { // obviously not re-entrant restore := func() { delete(objects, "_current") } defer restore() objects["_current"] = obj return template.tmpl.ExecuteTemplate(wr, obj[K_TYPE].(string), objects) } const ( SKIP = -1 INFO = 0 HINT = 1 ERROR = 2 MAX = 2 ) type remark struct { line int text string severity int skip int } // for sorting type RemarkSlice []*remark func (p RemarkSlice) Len() int { return len(p) } func (p RemarkSlice) Less(i, j int) bool { return p[i].line < p[j].line } func (p RemarkSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (r remark) Format() string { if r.severity == SKIP { return "" } else if r.severity == ERROR { return fmt.Sprintf("#! >>>>>>>>>>>>>>>>>>>> %v <<<<<<<<<<<<<<<<<<<<\n", r.text) } else if r.severity == HINT { return fmt.Sprintf("#: >>>>>>>> %v <<<<<<<<\n", r.text) } else { return fmt.Sprintf("#: %v\n", r.text) } } type Remarks struct { histo [MAX + 1]int severity int descriptors []*remark } func New() *Remarks { return &Remarks{[MAX + 1]int{}, 0, make([]*remark, 0)} } func (rs *Remarks) add(r *remark) { rs.descriptors = append(rs.descriptors, r) if r.severity > rs.severity { rs.severity = r.severity } if r.severity >= 0 && r.severity <= MAX { rs.histo[r.severity]++ } } func (rs *Remarks) AddError(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), ERROR, 0}) } func (rs *Remarks) AddHint(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), HINT, 0}) } func (rs *Remarks) AddInfo(line int, text string, args ...interface{}) { rs.add(&remark{line, fmt.Sprintf(text, args...), INFO, 0}) } func (rs *Remarks) AddRemover(line int) { r := &remark{line: line, severity: SKIP, skip: 1} rs.descriptors = append(rs.descriptors, r) } func (rs *Remarks) Embed(contentLines []string) string { content := "" cl := 0 sort.Sort(RemarkSlice(rs.descriptors)) for _, ed := range rs.descriptors { if ed.line-cl >= 0 { content += strings.Join(contentLines[cl:ed.line], "\n") if ed.line-cl > 0 { content += "\n" } cl = ed.line + ed.skip } content += ed.Format() } content += strings.Join(contentLines[cl:], "\n") return content } func (rs *Remarks) Severity() int { return rs.severity } func (rs *Remarks) Histo(severity int) int { if severity >= 0 && severity <= MAX { return rs.histo[severity] } return 0 } type HeaderTransfer interface { collectFriendly(friendly *[]string) transfer(obj object, lookup map[string]object) } type Header struct { line int transfer HeaderTransfer } type objectDescriptor struct { start int initial []string header map[string]Header body []string } type HeaderParser interface { parse(value string) (HeaderTransfer, error) } type verbatimString struct { targetKey string values []string noTrim bool // default: trim spaces (so much for "verbatim") } type verbatimList struct { targetKey string } type referenceList struct { targetKey string } type dateField struct { targetKey string } type snippetField struct{} type verbatimTransfer struct { targetKey string value interface{} } type referenceTransfer struct { targetKey string friendly []string } type snippetTransfer object func (vt *verbatimTransfer) collectFriendly(friendly *[]string) { } func (vt *verbatimTransfer) transfer(obj object, lookup map[string]object) { if vt.value == nil { delete(obj, vt.targetKey) } else { obj[vt.targetKey] = vt.value } } func (vs verbatimString) parse(value string) (HeaderTransfer, error) { if !vs.noTrim { value = strings.TrimSpace(value) } var ivalue interface{} = value if vs.values != nil { i := -1 for j, v := range vs.values { if value == v { i = j break } } if i == -1 { return nil, fmt.Errorf("field value needs to be one of: %v", vs.values) } if value == "" { // FAT DOG: if we have a fixed set of possible values, "" means <remove field> ivalue = nil } } return &verbatimTransfer{vs.targetKey, ivalue}, nil } func parseList(value string) []string { // CAUTION: separator is COMMA followed by SPACE, because (e.g.) URLs may contain commas (but not spaces) values := strings.Split(value, ", ") for i, v := range values {
if len(values) >= 1 && values[len(values)-1] == "" { // handle empty list as well as trailing comma values = values[:len(values)-1] } return values } func (vl verbatimList) parse(value string) (HeaderTransfer, error) { return &verbatimTransfer{vl.targetKey, parseList(value)}, nil } func (rt *referenceTransfer) collectFriendly(friendly *[]string) { *friendly = append(*friendly, rt.friendly...) } func (rt *referenceTransfer) transfer(obj object, lookup map[string]object) { fIds := make([]interface{}, len(rt.friendly)) for i, f := range rt.friendly { fIds[i] = lookup[f][K_ID] } obj[rt.targetKey] = interface{}(fIds) } func (rl referenceList) parse(value string) (HeaderTransfer, error) { return &referenceTransfer{rl.targetKey, parseList(value)}, nil } func (df dateField) parse(value string) (HeaderTransfer, error) { t, err := time.Parse("2006-01-02 15:04:05 -0700", strings.TrimSpace(value)) if err != nil { return nil, err } return &verbatimTransfer{df.targetKey, strconv.FormatInt(t.Unix(), 10)}, nil } func findQuote(s, start, end string) string { i1 := strings.Index(s, start) if i1 == -1 { return "" } i2 := strings.Index(s[i1+len(start):], end) if i2 == -1 { return "" } return s[i1+len(start) : i1+len(start)+i2] } func resolveRedirects(url *string) error { req, err := http.NewRequest("HEAD", *url, nil) if err != nil { return err } resp, err := http.DefaultClient.Do(req) if err != nil { return err } *url = resp.Request.URL.String() return nil } func (sf snippetField) parse(value string) (HeaderTransfer, error) { st := make(snippetTransfer) if strings.Index(value, `.statista.com/`) != -1 { if sourceUrl := findQuote(value, `<a href="`, `"`); sourceUrl != "" { st["sourceUrl"] = sourceUrl } else { return st, errors.New(`could not find source url; expected «<a href="..."»`) } if imageUrl := findQuote(value, `<img src="`, `"`); imageUrl != "" { st["imageUrl"] = imageUrl } else { return st, errors.New(`could not find image url; expected «<img src="..."»`) } if altText := findQuote(value, ` alt="`, `"`); altText != "" { st["name"] = altText } else { return st, errors.New(`could not find title; expected «alt="..."»`) } maxWidth := strings.TrimSpace(findQuote(value, `max-width:`, `px;`)) if maxWidth == "1000" { st["kind"] = "statista/statistik" } else if maxWidth == "960" { st["kind"] = "statista/infografik" } else { return st, errors.New(`could not determine kind; expected «max-width:...px;»`) } } else if strings.Index(value, `.amazon.de/`) != -1 { if purchaseUrl := findQuote(value, ` href="`, `"`); purchaseUrl != "" { st["buyUrl"] = purchaseUrl } else { return st, errors.New(`could not find purchase url; expected « href="..."»`) } if imageUrl := findQuote(value, ` src="`, `"`); imageUrl != "" { if strings.HasPrefix(imageUrl, "//") { imageUrl = "http:" + imageUrl } if err := resolveRedirects(&imageUrl); err != nil { return st, err } st["imageUrl"] = imageUrl } else { return st, errors.New(`could not find image url; expected « src="..."»`) } } else { return st, errors.New(`snippet not recognized; expected to find «.statista.com/» or «.amazon.de/»`) } return st, nil } func (st snippetTransfer) collectFriendly(friendly *[]string) { } func (st snippetTransfer) transfer(obj object, lookup map[string]object) { for k, v := range st { obj[k] = v } } func CollectFriendly(ods ...objectDescriptor) []string { friendly := make([]string, 0) for _, od := range ods { for _, h := range od.header { h.transfer.collectFriendly(&friendly) } } return friendly } func CollectMissing(ht HeaderTransfer, lookup map[string]object) []string { friendly := make([]string, 0) ht.collectFriendly(&friendly) missing := make([]string, 0) for _, f := range friendly { if _, present := lookup[f]; !present { missing = append(missing, f) } } return missing } var headerParsers = map[string]HeaderParser{ "friendly-id": verbatimString{targetKey: "friendlyId"}, "date": dateField{"date"}, "title": verbatimString{targetKey: "name"}, "tags": referenceList{"$tags"}, "source-urls": verbatimList{"sourceUrls"}, "paraph": verbatimString{targetKey: "paraph"}, "visibility": verbatimString{targetKey: "visibility", values: []string{"", "editor"}}, "dateline": verbatimString{targetKey: "dateline"}, "image-url": verbatimString{targetKey: "imageUrl"}, "image-credits": verbatimString{targetKey: "imageCredits"}, "image-source": verbatimString{targetKey: "imageSource"}, "image-text": verbatimString{targetKey: "imageText"}, "components": referenceList{"$components"}, "speaker": verbatimString{targetKey: "speaker"}, "position": verbatimString{targetKey: "position"}, "sources": verbatimString{targetKey: "sources"}, "snippet": snippetField{}, "kind": verbatimString{targetKey: "kind", values: []string{"statista/statistik", "statista/infografik"}}, "source-url": verbatimString{targetKey: "sourceUrl"}, "origin": verbatimString{targetKey: "origin"}, "origin-url": verbatimString{targetKey: "originUrl"}, "authors": verbatimString{targetKey: "authors"}, "publisher": verbatimString{targetKey: "publisher"}, "purchase-url": verbatimString{targetKey: "purchaseUrl"}, } func computeHeaderLookup(data map[string]string) map[string]map[string]bool { result := make(map[string]map[string]bool, len(data)) for key, fieldstr := range data { fields := strings.Split(strings.ToLower(fieldstr), " ") set := make(map[string]bool, len(fields)) for _, f := range fields { set[strings.TrimSpace(f)] = true } result[key] = set } return result } var validHeaders = computeHeaderLookup(map[string]string{ "COMPONENT": "Friendly-Id Date Title Tags Source-Urls", "EVENT": "Friendly-Id Date Paraph Visibility Tags Dateline Title Image-Url Image-Credits Image-Source Image-Text Components", "STATEMENT": "Friendly-Id Date Paraph Visibility Tags Speaker Position Image-Url Image-Credits Image-Source Sources Source-Urls", "STATISTIC": "Friendly-Id Date Paraph Visibility Tags Snippet Kind Title Source-Url Image-Url Origin Origin-Url", "BOOK": "Friendly-Id Date Paraph Visibility Tags Authors Title Publisher Snippet Image-Url Purchase-Url", }) var hasBody = map[string]bool{ "COMPONENT": true, "STATEMENT": true, } func parseInter(contentLines []string, remarks *Remarks) (ods []objectDescriptor) { ods = make([]objectDescriptor, 0) if len(contentLines) == 0 { return } contentLines = append(append(contentLines, ""), "") // sentinel for storing the final object cod := objectDescriptor{start: -1} blanks := 0 fieldStart := 0 headerKey := "" headerValue := "" finishField := func() { hk := headerKey if hk == "" { return } headerKey = "" if !validHeaders[cod.initial[0]][hk] { remarks.AddError(fieldStart, "invalid header field: %v", hk) return } parser, present := headerParsers[hk] if !present { remarks.AddError(fieldStart, "unknown header field: %v", hk) } ht, err := parser.parse(headerValue) if err != nil { remarks.AddError(fieldStart, "error parsing field: %v", err.Error()) return } cod.header[hk] = Header{fieldStart, ht} } for i, l := range contentLines { // no trimming yet, for whitespace makes a difference (continuation of header field) if l == "" { blanks += 1 if cod.start == -1 { continue // !!! } if headerKey != "" { finishField() } if blanks == 2 || !hasBody[cod.initial[0]] { ods = append(ods, cod) cod = objectDescriptor{start: -1} continue // !!! } if cod.body == nil { cod.body = make([]string, 0) } else { cod.body = append(cod.body, "") } continue // !!! } // blanks only counts consecutive EMPTY lines; a line containing only a comment is ignored, but not counted! blanks = 0 // body takes preference before comments (no special handling of # in body) if cod.body != nil { cod.body = append(cod.body, l) continue // !!! } // a comment is either prefixed by "#"" at the beginning of the line or by " #" otherwise ci := 0 if !strings.HasPrefix(l, "#") { ci = strings.Index(l, " #") } if ci != -1 { if ci == 0 { // disallow header continuation finishField() // remove remark if strings.HasPrefix(l, "#!") || strings.HasPrefix(l, "#:") { remarks.AddRemover(i) } } l = l[:ci] } if l == "" { continue // !!! } if cod.start == -1 { cod.initial = strings.SplitN(l, " ", 2) for j, ini := range cod.initial { cod.initial[j] = strings.TrimSpace(ini) } if len(cod.initial) != 2 || strings.IndexByte(cod.initial[1], ' ') != -1 { remarks.AddError(i, "expected initial line of the form 'TYPE id'") } else { if _, present := validHeaders[cod.initial[0]]; present { cod.start = i cod.header = make(map[string]Header) } else { remarks.AddError(i, "unknown type: %v", cod.initial[0]) } } continue // !!! } if headerKey != "" && unicode.IsSpace(rune(l[0])) { // continuation of previous header; do NOT trim trailing space! (see below) headerValue += " " + strings.TrimLeftFunc(l, unicode.IsSpace) continue // !!! } hs := strings.SplitN(l, ":", 2) if len(hs) != 2 { remarks.AddError(i, "expected header line of the form 'Key: Value'") } else { finishField() fieldStart = i headerKey = strings.ToLower(hs[0]) if _, present := cod.header[headerKey]; present { remarks.AddError(i, "redeclared header field: %v", headerKey) } // do NOT trim trailing space for it may carry semantics (such as trailing COMMA SPACE) headerValue = strings.TrimLeftFunc(hs[1], unicode.IsSpace) } } return } func computeFriendly(title string) string { fields := strings.Fields(strings.Map(func(r rune) rune { if unicode.IsLetter(r) { return unicode.ToLower(r) } else { return ' ' } }, title)) l := 0 i := 0 for l < 33 && i < len(fields) { l += len(fields[i]) l += 1 i++ } if l < 33 { return "" } return strings.Join(fields[:i], "-") } func applyToObjects(db *sql.DB, ods []objectDescriptor, objects objectMap, remarks *Remarks, initialVersion string) error { friendlyMap := make(map[string]object) // collect references and load them from the database friendly := CollectFriendly(ods...) if err := objects.queryByFriendly(db, friendly, nil); err != nil { return err } for _, obj := range objects { if friendly, ok := obj["friendlyId"].(string); ok { friendlyMap[friendly] = obj } } // load objects from database (those that exist anyway) keys := make([]string, len(ods)) for i, od := range ods { keys[i] = od.initial[1] } if err := objects.queryByKeys(db, keys); err != nil { return err } // transfer fields from objectDescriptors into objects for odi, od := range ods { obj, present := objects[od.initial[1]] if !present { obj = object{K_TYPE: strings.ToLower(od.initial[0]), K_ID: od.initial[1], K_VERSION: initialVersion} objects[od.initial[1]] = obj } for _, h := range od.header { missing := CollectMissing(h.transfer, friendlyMap) if len(missing) == 0 { h.transfer.transfer(obj, friendlyMap) } else { for _, m := range missing { remarks.AddError(h.line, "NOT FOUND: %v", m) } } } // handle body if od.body == nil { delete(obj, "content") } else { obj["content"] = strings.Join(od.body, "\n") } // handle non-extant components :( if _, present := obj["$components"]; !present && obj[K_TYPE] == "event" { i := odi for ; i > 0 && ods[i-1].initial[0] == "COMPONENT"; i-- { } if i < odi { cs := make([]interface{}, odi-i) for j := i; j < odi; j++ { cs[j-i] = ods[j].initial[1] } obj["$components"] = interface{}(cs) } } // handle non-extant friendlyId if friendly, present := obj["friendlyId"]; present { keys := make([]string, 0) if err := objects.queryByFriendly(db, []string{friendly.(string)}, &keys); err != nil { return err } if len(keys) != 0 && keys[0] != od.initial[1] { remarks.AddError(od.start, "Friendly-Id already taken") } } else { friendly := "" if title, ok := obj["content"].(string); ok { friendly = computeFriendly(title) } if title, ok := obj["name"].(string); friendly == "" && ok { friendly = computeFriendly(title) } if friendly != "" { friendlyBase := friendly for fi := 0; ; fi++ { // I'm afraid we have to check for uniqueness if fi != 0 { friendly = friendlyBase + "-" + strconv.Itoa(fi) } keys := make([]string, 0) if err := objects.queryByFriendly(db, []string{friendly}, &keys); err != nil { return err } if len(keys) == 0 { break } } obj["friendlyId"] = friendly friendlyMap[friendly] = obj } else { remarks.AddError(od.start, "could not compute Friendly-Id; check title or text body") } } } return nil }
values[i] = strings.TrimSpace(v) }
conditional_block
tab2.page.ts
import { Component, ViewChild, Injectable, Inject } from '@angular/core'; import {trigger, state, style, animate, transition } from '@angular/animations'; import { NavController, LoadingController, ToastController} from '@ionic/angular'; import { AudioService } from '../services/audio.service'; import {FormControl} from '@angular/forms'; import {CANPLAY, LOADEDMETADATA, PLAYING, TIMEUPDATE, LOADSTART, RESET} from '../Interface/MediaAction'; import {Store} from '@ngrx/store'; import { GetAudioService } from '../services/get-audio.service'; import {pluck, filter, map, distinctUntilChanged} from 'rxjs/operators'; import { AppConfig } from '../Interface/AppConfig'; import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx'; import { File } from '@ionic-native/file/ngx'; import { AdMobService } from '../services/ad-mob.service'; import { PlaylistService } from '../providers/playlist.service'; import { AnimationService, AnimationBuilder } from 'css-animator'; import { MusicControls } from '@ionic-native/music-controls/ngx'; @Component({ selector: 'app-tab2', templateUrl: 'tab2.page.html', styleUrls: ['tab2.page.scss'], animations: [ trigger('showHide', [ state( 'active', style({ opacity: 1 }) ), state( 'inactive', style({ opacity: 0 }) ), transition('inactive => active', animate('250ms ease-in')), transition('active => inactive', animate('250ms ease-out')) ]), trigger('fadeInOut', [ state('void', style({ opacity: '0' })), state('*', style({ opacity: '1' })), transition('void <=> *', animate('150ms ease-in')) ]) ] }) @Injectable() export class Tab2Page { defaultImage: string = "assets/icon.png"; files: any = []; hfiles: any = []; seekbar: FormControl = new FormControl('seekbar'); state: any = {}; onSeekState: boolean; currentFile: any = {}; currentDL: any = {}; displayFooter = 'inactive'; loggedIn: Boolean; type_ent = []; newData = []; nImg = []; cpage = 1; nextUrl = ''; hnextUrl = ''; endscroll = true; arl = []; musicState: any = {size: '', time: ''}; downloadFile: any; private fileTransfer: FileTransferObject; error; bsearch=false; timeOutToSearch=undefined; timeOutLoad=undefined; query:string = ""; tlong=false; msgUnload; kfile=[]; isDL=false; playlist : any=[]; settings:any = { automatic:false, showImage:true, randomly:false, statistic:true, autoplay:false, cats:[], player:true } myUser = { type_login:1, user_data:{}, }; loader=false; users:any; DEV=true; private animator: AnimationBuilder; constructor( @Inject(FileTransfer) private transfer: FileTransfer, @Inject(File) private file: File, @Inject(ToastController) public toastController: ToastController, public navCtrl: NavController, public audioProvider: AudioService, public loadingCtrl: LoadingController, public cloudProvider: GetAudioService, private admobFreeService: AdMobService, private bd: PlaylistService, @Inject(AnimationService) animationService: AnimationService, @Inject(MusicControls) private musicControls: MusicControls, private store: Store<any> ) { this.animator = animationService.builder(); let i = this.randomInt(1,30) ; if(i<15){ this.showRewardVideo(); } this.bd.getMenu().then((res:any)=>{ if(res!=null) { this.settings=res; this.player=this.settings.player; } }); } public keySeachUp(e) { if(this.query!=""){ this.files = this.filterItems(this.query); if(this.files.length==0){ this.setMsg("Nothing found."); } }else{ this.files = this.hfiles; } this.arrange(); } filterItems(searchTerm) { return this.files.filter(item => { return item.nom.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1; }); } async removeFromPlaylist(file){ const r = await this.bd.removeMusic(file).then((res)=> { this.files=[]; if(res!=null){ this.files = res; } if(this.files.length==0){ this.setMsg("Your playlist is empty."); } this.presentToast(file.nom+ " remove from playlist."); }); } async getPlayl() { const data = await this.bd.getAllMusic().then(res => { if(res !=null){ this.files = res; this.autoplay(); this.arrange(); }else{ this.setMsg("Your playlist is empty, slide item to left to add music in your playlist."); } }); } setMsg(e){ this.tlong = true; this.msgUnload=e; } player: boolean = true; async togglePlayer(e){ if(this.player){ this.animateHide(e,'flipOutX').then(()=>{ this.player = !this.player; }); } else { this.player = await !this.player; this.animateShow(e,'bounceIn').then(()=>{ }); } } emitAnimate(e){ this.animator.setType(e.anim).show(e.el).then(()=>{}); } animateHide(l,e) { return this.animator.setType(e).hide(l); } animateShow(l,e) { return this.animator.setType(e).show(l); } toggleSearch() { this.bsearch=!this.bsearch; if(this.bsearch){ this.hfiles = this.files; }else{ this.files=this.hfiles; this.arrange(); } } arrange(){ if(this.currentFile.media){ for (let i = 0; i < this.files.length; i++) { if(this.files[i].id_pub===this.currentFile.media.id_pub){ this.currentFile.index=i; break; }else{ continue;} } } } async presentToast(msg) { const toast = await this.toastController.create({ message: msg, duration: 3000 }); toast.present(); } setFormat(e){ if(e<1000){ return e+""; }else if (e>=1000 && e<999999){ return Math.ceil((e/1000))+"K"; } else if (e>=1000000 && e<999999999){ return Math.ceil((e/1000000))+"M"; }else{ return "~"; } } async addView(id) { const data = await this.cloudProvider.addView('Bo/@Hb/addView/' + id).then(res => { }); } addNewMusic() { for (let i = 0; i < this.newData.length; i++) { this.files.unshift(this.newData[i]); } } public getAvatar(url, file, index) { if (url == null) { url = 'default.png'; } return AppConfig.getAvatar(url); } log(t) { console.log(t); } randomInt(min, max) { // min and max included return Math.floor(Math.random() * (max - min + 1) + min); } // tslint:disable-next-line:use-lifecycle-interface ngOnInit(){ this.admobFreeService.BannerAd(); } showInterstitial() { this.admobFreeService.InterstitialAd(); } showRewardVideo() { this.admobFreeService.RewardVideoAd(); } ionViewWillUnload() { this.stop(); this.currentFile={}; } initInfo(){ this.state.info= { id_pub:null, link_pub :"", artist:"", title:"Nothing is play", playing: false }; } ionViewWillEnter(){ this.store.select('appState').subscribe((value: any) => { this.state.media = value.media; this.initInfo(); if(value.info){ this.state.info = value.info; } }); // Updating the Seekbar based on currentTime this.store .select('appState') .pipe( pluck('media', 'timeSec'), filter(value => value !== undefined), map((value: any) => Number.parseInt(value)), distinctUntilChanged() ) .subscribe((value: any) => { this.seekbar.setValue(value); }); this.bd.getMenu().then(res=>{ this.getPlayl(); if(res!=null) { this.settings = res; this.player = this.settings.player; } }); } openFile(file, index) { // tslint:disable-next-line:indent this.addView(file.id_pub); const media = { id_pub:file.id_pub, link_pub : file.link_pub, artist: file.nom_ent, title: file.nom, playing: true }; const n = Number(this.files[index].get_access) + 1; this.files[index].get_access = n; this.playStream(media,index); let i = this.randomInt(1, 10); if (i < 8) { this.showInterstitial(); } } resetState() { this.audioProvider.stop(); this.store.dispatch({ type: RESET }); this.musicControls.destroy(); } islistening(file){ if(this.state.media.duration && this.state.info && this.state.info.playing && this.state.info.id_pub==file.id_pub){ return true; } return false; } setupControl(f,dir=0){ this.musicControls.create({ track : f.title, // optional, default : '' artist : f.artist, // optional, default : '' cover :this.getAvatar(f.avatar_ent,null,0), // optional, default : nothing // cover can be a local path (use fullpath 'file:///storage/emulated/...', or only 'my_image.jpg' if my_image.jpg is in the www folder of your app) // or a remote url ('http://...', 'https://...', 'ftp://...') isPlaying : true, // optional, default : true dismissable : true, // optional, default : false // hide previous/next/close buttons: hasPrev : false, // show previous button, optional, default: true hasNext : false, // show next button, optional, default: true hasClose : true, // show close button, optional, default: false // iOS only, optional album : 'Absolution', // optional, default: '' duration :0, // optional, default: 0 elapsed : 10, // optional, default: 0 hasSkipForward : true, // show skip forward button, optional, default: false hasSkipBackward : true, // show skip backward button, optional, default: false skipForwardInterval: 15, // display number for skip forward, optional, default: 0 skipBackwardInterval: 15, // display number for skip backward, optional, default: 0 hasScrubbing: false, // enable scrubbing from control center and lockscreen progress bar, optional // Android only, optional // text displayed in the status bar when the notification (and the ticker) are updated, optional ticker : 'Now playing "'+f.title+'"', // All icons default to their built-in android equivalents playIcon: 'media_play', pauseIcon: 'media_pause', prevIcon: 'media_prev', nextIcon: 'media_next', closeIcon: 'media_close', notificationIcon: 'notification' }); this.musicControls.subscribe().subscribe(action => { this.events(action); }); this.musicControls.listen(); // activates the observable above } events(action){ const message = JSON.parse(action).message; switch(message) { case 'music-controls-next': //this.musicControls.destroy(); //this.next(); break; case 'music-controls-previous': //this.musicControls.destroy(); //this.previous(); break; case 'music-controls-pause': this.pause(); break; case 'music-controls-play': this.play(); break; case 'music-controls-destroy': this.stop(); break; // External controls (iOS only) case 'music-controls-toggle-play-pause' : // Do something break; case 'music-controls-seek-to': const seekToInSeconds = JSON.parse(action).position; this.musicControls.updateElapsed({ elapsed: seekToInSeconds, isPlaying: true }); this.onSeekEndNew(seekToInSeconds); break; case 'music-controls-skip-forward': // Do something break; case 'music-controls-skip-backward': // Do something break; // Headset events (Android only) // All media button events are listed below case 'music-controls-media-button' : // Do something break; case 'music-controls-headset-unplugged': this.pause(); // Do something break; case 'music-controls-headset-plugged': // Do something break; default: break; } } onSeekEndNew(event) { if (this.onSeekState) { this.audioProvider.seekTo(event); this.play(); } else { this.audioProvider.seekTo(event); } } playStream(media, index) { let file = media; this.resetState(); this.setupControl(media,0); this.state.info=media; this.player=this.settings.player; this.audioProvider.playStream(file).subscribe( event => { const audioObj = event.target; switch (event.type) { case 'canplay': this.currentFile = { index, media, state: 2 }; return this.store.dispatch({ type: CANPLAY, payload: { value: true,mediaInfo:file } }); case 'loadedmetadata': return this.store.dispatch({ type: LOADEDMETADATA, payload: { mediaInfo:file, value: true, data: { time: this.audioProvider.formatTime( audioObj.duration * 1000, 'HH:mm:ss' ), timeSec: audioObj.duration, mediaType: 'mp3' } } }); case 'playing': this.musicControls.updateIsPlaying(true); return this.store.dispatch({ type: PLAYING, payload: { value: true } }); case 'pause': this.musicControls.updateIsPlaying(false); return this.store.dispatch({ type: PLAYING, payload: { value: false } }); case 'timeupdate': this.chechToplayNext(audioObj.currentTime,audioObj.duration); this.musicState.size = this.audioProvider.formatTime( audioObj.duration * 1000, 'HH:mm:ss' ); this.musicState.time = this.audioProvider.formatTime(audioObj.currentTime * 1000, 'HH:mm:ss'); return this.store.dispatch({ type: TIMEUPDATE, payload: { timeSec: audioObj.currentTime, time: this.audioProvider.formatTime( audioObj.currentTime * 1000, 'HH:mm:ss' ) } }); case 'loadstart': this.log("LOADSTART IS CALL"); return this.store.dispatch({ type: LOADSTART, payload: { value: true, mediaInfo:file} }); } }); } pause() { this.audioProvider.pause(); this.currentFile.state = 1; } play() { if(this.state.info.playing){ this.pause(); } this.audioProvider.play(); this.currentFile.state = 2; } stop() { this.reset(); this.audioProvider.stop(); this.currentFile={}; this.state.media ={}; this.initInfo(); } getH(h){ if(h!=null){ let m =h.split(":"); let n=""; if(m[0]!="00"){ n=m[0]+":"; } n+=m[1]+":"+m[2]; return n; } return ""; } chechToplayNext(ta,tb){ if(this.settings.automatic && ta==tb){ this.next(); } } next() { if (this.currentFile.index < this.files.length - 1) { let index = this.currentFile.index + 1; index = this.getNext(index); const file = this.files[index]; this.openFile(file, index); } } previous() { if (this.currentFile.index > 0) { // tslint:disable-next-line:prefer-const let index = this.currentFile.index - 1; index = this.getNext(index); // tslint:disable-next-line:prefer-const let file = this.files[index]; this.openFile(file, index); } } autoplay(){ if(this.settings.autoplay && !this.currentFile.media){ let index = this.randomInt(0,this.files.length-1); let f= this.files[index]; if(f!=null){ this.openFile(f,index); } } } ionViewDidLoad() { this.admobFreeService.BannerAd(); } getNext(index){ if(this.settings.randomly){ return this.randomInt(0,(this.files.length-1)); } return index; } onSeekStart() { this.onSeekState = this.state.info.playing; if (this.onSeekState) { this.pause(); } } onSeekEnd(event)
reset() { this.resetState(); this.currentFile = {}; this.displayFooter = 'inactive'; } }
{ if (this.onSeekState) { this.audioProvider.seekTo(event.target.value); this.play(); } else { this.audioProvider.seekTo(event.target.value); } }
identifier_body
tab2.page.ts
import { Component, ViewChild, Injectable, Inject } from '@angular/core'; import {trigger, state, style, animate, transition } from '@angular/animations'; import { NavController, LoadingController, ToastController} from '@ionic/angular'; import { AudioService } from '../services/audio.service'; import {FormControl} from '@angular/forms'; import {CANPLAY, LOADEDMETADATA, PLAYING, TIMEUPDATE, LOADSTART, RESET} from '../Interface/MediaAction'; import {Store} from '@ngrx/store'; import { GetAudioService } from '../services/get-audio.service'; import {pluck, filter, map, distinctUntilChanged} from 'rxjs/operators'; import { AppConfig } from '../Interface/AppConfig'; import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx'; import { File } from '@ionic-native/file/ngx'; import { AdMobService } from '../services/ad-mob.service'; import { PlaylistService } from '../providers/playlist.service'; import { AnimationService, AnimationBuilder } from 'css-animator'; import { MusicControls } from '@ionic-native/music-controls/ngx'; @Component({ selector: 'app-tab2', templateUrl: 'tab2.page.html', styleUrls: ['tab2.page.scss'], animations: [ trigger('showHide', [ state( 'active', style({ opacity: 1 }) ), state( 'inactive', style({ opacity: 0 }) ), transition('inactive => active', animate('250ms ease-in')), transition('active => inactive', animate('250ms ease-out')) ]), trigger('fadeInOut', [ state('void', style({ opacity: '0' })), state('*', style({ opacity: '1' })), transition('void <=> *', animate('150ms ease-in')) ]) ] }) @Injectable() export class Tab2Page { defaultImage: string = "assets/icon.png"; files: any = []; hfiles: any = []; seekbar: FormControl = new FormControl('seekbar'); state: any = {}; onSeekState: boolean; currentFile: any = {}; currentDL: any = {}; displayFooter = 'inactive'; loggedIn: Boolean; type_ent = []; newData = []; nImg = []; cpage = 1; nextUrl = ''; hnextUrl = ''; endscroll = true; arl = []; musicState: any = {size: '', time: ''}; downloadFile: any; private fileTransfer: FileTransferObject; error; bsearch=false; timeOutToSearch=undefined; timeOutLoad=undefined; query:string = ""; tlong=false; msgUnload; kfile=[]; isDL=false; playlist : any=[]; settings:any = { automatic:false, showImage:true, randomly:false, statistic:true, autoplay:false, cats:[], player:true } myUser = { type_login:1, user_data:{}, }; loader=false; users:any; DEV=true; private animator: AnimationBuilder; constructor( @Inject(FileTransfer) private transfer: FileTransfer, @Inject(File) private file: File, @Inject(ToastController) public toastController: ToastController, public navCtrl: NavController, public audioProvider: AudioService, public loadingCtrl: LoadingController, public cloudProvider: GetAudioService, private admobFreeService: AdMobService, private bd: PlaylistService, @Inject(AnimationService) animationService: AnimationService, @Inject(MusicControls) private musicControls: MusicControls, private store: Store<any> ) { this.animator = animationService.builder(); let i = this.randomInt(1,30) ; if(i<15){ this.showRewardVideo(); } this.bd.getMenu().then((res:any)=>{ if(res!=null) { this.settings=res; this.player=this.settings.player; } }); } public keySeachUp(e) { if(this.query!=""){ this.files = this.filterItems(this.query); if(this.files.length==0){ this.setMsg("Nothing found."); } }else{ this.files = this.hfiles; } this.arrange(); } filterItems(searchTerm) { return this.files.filter(item => { return item.nom.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1; }); } async removeFromPlaylist(file){ const r = await this.bd.removeMusic(file).then((res)=> { this.files=[]; if(res!=null){ this.files = res; } if(this.files.length==0){ this.setMsg("Your playlist is empty."); } this.presentToast(file.nom+ " remove from playlist."); }); } async getPlayl() { const data = await this.bd.getAllMusic().then(res => { if(res !=null){ this.files = res; this.autoplay(); this.arrange(); }else{ this.setMsg("Your playlist is empty, slide item to left to add music in your playlist."); } }); } setMsg(e){ this.tlong = true; this.msgUnload=e; } player: boolean = true; async togglePlayer(e){ if(this.player){ this.animateHide(e,'flipOutX').then(()=>{ this.player = !this.player; }); } else { this.player = await !this.player; this.animateShow(e,'bounceIn').then(()=>{ }); } } emitAnimate(e){ this.animator.setType(e.anim).show(e.el).then(()=>{}); } animateHide(l,e) { return this.animator.setType(e).hide(l); } animateShow(l,e) { return this.animator.setType(e).show(l); } toggleSearch() { this.bsearch=!this.bsearch; if(this.bsearch){ this.hfiles = this.files; }else{ this.files=this.hfiles; this.arrange(); } } arrange(){ if(this.currentFile.media){ for (let i = 0; i < this.files.length; i++) { if(this.files[i].id_pub===this.currentFile.media.id_pub){ this.currentFile.index=i; break; }else
} } } async presentToast(msg) { const toast = await this.toastController.create({ message: msg, duration: 3000 }); toast.present(); } setFormat(e){ if(e<1000){ return e+""; }else if (e>=1000 && e<999999){ return Math.ceil((e/1000))+"K"; } else if (e>=1000000 && e<999999999){ return Math.ceil((e/1000000))+"M"; }else{ return "~"; } } async addView(id) { const data = await this.cloudProvider.addView('Bo/@Hb/addView/' + id).then(res => { }); } addNewMusic() { for (let i = 0; i < this.newData.length; i++) { this.files.unshift(this.newData[i]); } } public getAvatar(url, file, index) { if (url == null) { url = 'default.png'; } return AppConfig.getAvatar(url); } log(t) { console.log(t); } randomInt(min, max) { // min and max included return Math.floor(Math.random() * (max - min + 1) + min); } // tslint:disable-next-line:use-lifecycle-interface ngOnInit(){ this.admobFreeService.BannerAd(); } showInterstitial() { this.admobFreeService.InterstitialAd(); } showRewardVideo() { this.admobFreeService.RewardVideoAd(); } ionViewWillUnload() { this.stop(); this.currentFile={}; } initInfo(){ this.state.info= { id_pub:null, link_pub :"", artist:"", title:"Nothing is play", playing: false }; } ionViewWillEnter(){ this.store.select('appState').subscribe((value: any) => { this.state.media = value.media; this.initInfo(); if(value.info){ this.state.info = value.info; } }); // Updating the Seekbar based on currentTime this.store .select('appState') .pipe( pluck('media', 'timeSec'), filter(value => value !== undefined), map((value: any) => Number.parseInt(value)), distinctUntilChanged() ) .subscribe((value: any) => { this.seekbar.setValue(value); }); this.bd.getMenu().then(res=>{ this.getPlayl(); if(res!=null) { this.settings = res; this.player = this.settings.player; } }); } openFile(file, index) { // tslint:disable-next-line:indent this.addView(file.id_pub); const media = { id_pub:file.id_pub, link_pub : file.link_pub, artist: file.nom_ent, title: file.nom, playing: true }; const n = Number(this.files[index].get_access) + 1; this.files[index].get_access = n; this.playStream(media,index); let i = this.randomInt(1, 10); if (i < 8) { this.showInterstitial(); } } resetState() { this.audioProvider.stop(); this.store.dispatch({ type: RESET }); this.musicControls.destroy(); } islistening(file){ if(this.state.media.duration && this.state.info && this.state.info.playing && this.state.info.id_pub==file.id_pub){ return true; } return false; } setupControl(f,dir=0){ this.musicControls.create({ track : f.title, // optional, default : '' artist : f.artist, // optional, default : '' cover :this.getAvatar(f.avatar_ent,null,0), // optional, default : nothing // cover can be a local path (use fullpath 'file:///storage/emulated/...', or only 'my_image.jpg' if my_image.jpg is in the www folder of your app) // or a remote url ('http://...', 'https://...', 'ftp://...') isPlaying : true, // optional, default : true dismissable : true, // optional, default : false // hide previous/next/close buttons: hasPrev : false, // show previous button, optional, default: true hasNext : false, // show next button, optional, default: true hasClose : true, // show close button, optional, default: false // iOS only, optional album : 'Absolution', // optional, default: '' duration :0, // optional, default: 0 elapsed : 10, // optional, default: 0 hasSkipForward : true, // show skip forward button, optional, default: false hasSkipBackward : true, // show skip backward button, optional, default: false skipForwardInterval: 15, // display number for skip forward, optional, default: 0 skipBackwardInterval: 15, // display number for skip backward, optional, default: 0 hasScrubbing: false, // enable scrubbing from control center and lockscreen progress bar, optional // Android only, optional // text displayed in the status bar when the notification (and the ticker) are updated, optional ticker : 'Now playing "'+f.title+'"', // All icons default to their built-in android equivalents playIcon: 'media_play', pauseIcon: 'media_pause', prevIcon: 'media_prev', nextIcon: 'media_next', closeIcon: 'media_close', notificationIcon: 'notification' }); this.musicControls.subscribe().subscribe(action => { this.events(action); }); this.musicControls.listen(); // activates the observable above } events(action){ const message = JSON.parse(action).message; switch(message) { case 'music-controls-next': //this.musicControls.destroy(); //this.next(); break; case 'music-controls-previous': //this.musicControls.destroy(); //this.previous(); break; case 'music-controls-pause': this.pause(); break; case 'music-controls-play': this.play(); break; case 'music-controls-destroy': this.stop(); break; // External controls (iOS only) case 'music-controls-toggle-play-pause' : // Do something break; case 'music-controls-seek-to': const seekToInSeconds = JSON.parse(action).position; this.musicControls.updateElapsed({ elapsed: seekToInSeconds, isPlaying: true }); this.onSeekEndNew(seekToInSeconds); break; case 'music-controls-skip-forward': // Do something break; case 'music-controls-skip-backward': // Do something break; // Headset events (Android only) // All media button events are listed below case 'music-controls-media-button' : // Do something break; case 'music-controls-headset-unplugged': this.pause(); // Do something break; case 'music-controls-headset-plugged': // Do something break; default: break; } } onSeekEndNew(event) { if (this.onSeekState) { this.audioProvider.seekTo(event); this.play(); } else { this.audioProvider.seekTo(event); } } playStream(media, index) { let file = media; this.resetState(); this.setupControl(media,0); this.state.info=media; this.player=this.settings.player; this.audioProvider.playStream(file).subscribe( event => { const audioObj = event.target; switch (event.type) { case 'canplay': this.currentFile = { index, media, state: 2 }; return this.store.dispatch({ type: CANPLAY, payload: { value: true,mediaInfo:file } }); case 'loadedmetadata': return this.store.dispatch({ type: LOADEDMETADATA, payload: { mediaInfo:file, value: true, data: { time: this.audioProvider.formatTime( audioObj.duration * 1000, 'HH:mm:ss' ), timeSec: audioObj.duration, mediaType: 'mp3' } } }); case 'playing': this.musicControls.updateIsPlaying(true); return this.store.dispatch({ type: PLAYING, payload: { value: true } }); case 'pause': this.musicControls.updateIsPlaying(false); return this.store.dispatch({ type: PLAYING, payload: { value: false } }); case 'timeupdate': this.chechToplayNext(audioObj.currentTime,audioObj.duration); this.musicState.size = this.audioProvider.formatTime( audioObj.duration * 1000, 'HH:mm:ss' ); this.musicState.time = this.audioProvider.formatTime(audioObj.currentTime * 1000, 'HH:mm:ss'); return this.store.dispatch({ type: TIMEUPDATE, payload: { timeSec: audioObj.currentTime, time: this.audioProvider.formatTime( audioObj.currentTime * 1000, 'HH:mm:ss' ) } }); case 'loadstart': this.log("LOADSTART IS CALL"); return this.store.dispatch({ type: LOADSTART, payload: { value: true, mediaInfo:file} }); } }); } pause() { this.audioProvider.pause(); this.currentFile.state = 1; } play() { if(this.state.info.playing){ this.pause(); } this.audioProvider.play(); this.currentFile.state = 2; } stop() { this.reset(); this.audioProvider.stop(); this.currentFile={}; this.state.media ={}; this.initInfo(); } getH(h){ if(h!=null){ let m =h.split(":"); let n=""; if(m[0]!="00"){ n=m[0]+":"; } n+=m[1]+":"+m[2]; return n; } return ""; } chechToplayNext(ta,tb){ if(this.settings.automatic && ta==tb){ this.next(); } } next() { if (this.currentFile.index < this.files.length - 1) { let index = this.currentFile.index + 1; index = this.getNext(index); const file = this.files[index]; this.openFile(file, index); } } previous() { if (this.currentFile.index > 0) { // tslint:disable-next-line:prefer-const let index = this.currentFile.index - 1; index = this.getNext(index); // tslint:disable-next-line:prefer-const let file = this.files[index]; this.openFile(file, index); } } autoplay(){ if(this.settings.autoplay && !this.currentFile.media){ let index = this.randomInt(0,this.files.length-1); let f= this.files[index]; if(f!=null){ this.openFile(f,index); } } } ionViewDidLoad() { this.admobFreeService.BannerAd(); } getNext(index){ if(this.settings.randomly){ return this.randomInt(0,(this.files.length-1)); } return index; } onSeekStart() { this.onSeekState = this.state.info.playing; if (this.onSeekState) { this.pause(); } } onSeekEnd(event) { if (this.onSeekState) { this.audioProvider.seekTo(event.target.value); this.play(); } else { this.audioProvider.seekTo(event.target.value); } } reset() { this.resetState(); this.currentFile = {}; this.displayFooter = 'inactive'; } }
{ continue;}
conditional_block
tab2.page.ts
import { Component, ViewChild, Injectable, Inject } from '@angular/core'; import {trigger, state, style, animate, transition } from '@angular/animations'; import { NavController, LoadingController, ToastController} from '@ionic/angular'; import { AudioService } from '../services/audio.service'; import {FormControl} from '@angular/forms'; import {CANPLAY, LOADEDMETADATA, PLAYING, TIMEUPDATE, LOADSTART, RESET} from '../Interface/MediaAction'; import {Store} from '@ngrx/store'; import { GetAudioService } from '../services/get-audio.service'; import {pluck, filter, map, distinctUntilChanged} from 'rxjs/operators'; import { AppConfig } from '../Interface/AppConfig'; import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx'; import { File } from '@ionic-native/file/ngx'; import { AdMobService } from '../services/ad-mob.service'; import { PlaylistService } from '../providers/playlist.service'; import { AnimationService, AnimationBuilder } from 'css-animator'; import { MusicControls } from '@ionic-native/music-controls/ngx'; @Component({ selector: 'app-tab2', templateUrl: 'tab2.page.html', styleUrls: ['tab2.page.scss'], animations: [ trigger('showHide', [ state( 'active', style({ opacity: 1 }) ), state( 'inactive', style({ opacity: 0 }) ), transition('inactive => active', animate('250ms ease-in')), transition('active => inactive', animate('250ms ease-out')) ]), trigger('fadeInOut', [ state('void', style({ opacity: '0' })), state('*', style({ opacity: '1' })), transition('void <=> *', animate('150ms ease-in')) ]) ] }) @Injectable() export class Tab2Page { defaultImage: string = "assets/icon.png"; files: any = []; hfiles: any = []; seekbar: FormControl = new FormControl('seekbar'); state: any = {}; onSeekState: boolean; currentFile: any = {}; currentDL: any = {}; displayFooter = 'inactive'; loggedIn: Boolean; type_ent = []; newData = []; nImg = []; cpage = 1; nextUrl = ''; hnextUrl = ''; endscroll = true; arl = []; musicState: any = {size: '', time: ''}; downloadFile: any; private fileTransfer: FileTransferObject; error; bsearch=false; timeOutToSearch=undefined; timeOutLoad=undefined; query:string = ""; tlong=false; msgUnload; kfile=[]; isDL=false; playlist : any=[]; settings:any = { automatic:false, showImage:true, randomly:false, statistic:true, autoplay:false, cats:[], player:true } myUser = { type_login:1, user_data:{}, }; loader=false; users:any; DEV=true; private animator: AnimationBuilder; constructor( @Inject(FileTransfer) private transfer: FileTransfer, @Inject(File) private file: File, @Inject(ToastController) public toastController: ToastController, public navCtrl: NavController, public audioProvider: AudioService, public loadingCtrl: LoadingController, public cloudProvider: GetAudioService, private admobFreeService: AdMobService, private bd: PlaylistService, @Inject(AnimationService) animationService: AnimationService, @Inject(MusicControls) private musicControls: MusicControls, private store: Store<any> ) { this.animator = animationService.builder(); let i = this.randomInt(1,30) ; if(i<15){ this.showRewardVideo(); } this.bd.getMenu().then((res:any)=>{ if(res!=null) { this.settings=res; this.player=this.settings.player; } }); } public keySeachUp(e) { if(this.query!=""){ this.files = this.filterItems(this.query); if(this.files.length==0){ this.setMsg("Nothing found."); } }else{ this.files = this.hfiles; } this.arrange(); } filterItems(searchTerm) { return this.files.filter(item => { return item.nom.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1; }); } async removeFromPlaylist(file){ const r = await this.bd.removeMusic(file).then((res)=> { this.files=[]; if(res!=null){ this.files = res; } if(this.files.length==0){ this.setMsg("Your playlist is empty."); } this.presentToast(file.nom+ " remove from playlist."); }); } async getPlayl() { const data = await this.bd.getAllMusic().then(res => { if(res !=null){ this.files = res; this.autoplay(); this.arrange(); }else{ this.setMsg("Your playlist is empty, slide item to left to add music in your playlist."); } }); } setMsg(e){ this.tlong = true; this.msgUnload=e; } player: boolean = true; async togglePlayer(e){ if(this.player){ this.animateHide(e,'flipOutX').then(()=>{ this.player = !this.player; }); } else { this.player = await !this.player; this.animateShow(e,'bounceIn').then(()=>{ }); } } emitAnimate(e){ this.animator.setType(e.anim).show(e.el).then(()=>{}); } animateHide(l,e) { return this.animator.setType(e).hide(l); } animateShow(l,e) { return this.animator.setType(e).show(l); } toggleSearch() { this.bsearch=!this.bsearch; if(this.bsearch){ this.hfiles = this.files; }else{ this.files=this.hfiles; this.arrange(); } } arrange(){ if(this.currentFile.media){ for (let i = 0; i < this.files.length; i++) { if(this.files[i].id_pub===this.currentFile.media.id_pub){ this.currentFile.index=i; break; }else{ continue;} } } } async presentToast(msg) { const toast = await this.toastController.create({ message: msg, duration: 3000 }); toast.present(); } setFormat(e){ if(e<1000){ return e+""; }else if (e>=1000 && e<999999){ return Math.ceil((e/1000))+"K"; } else if (e>=1000000 && e<999999999){ return Math.ceil((e/1000000))+"M"; }else{ return "~"; } } async addView(id) { const data = await this.cloudProvider.addView('Bo/@Hb/addView/' + id).then(res => { }); } addNewMusic() { for (let i = 0; i < this.newData.length; i++) { this.files.unshift(this.newData[i]); } } public getAvatar(url, file, index) { if (url == null) { url = 'default.png'; } return AppConfig.getAvatar(url); } log(t) { console.log(t); } randomInt(min, max) { // min and max included return Math.floor(Math.random() * (max - min + 1) + min); } // tslint:disable-next-line:use-lifecycle-interface ngOnInit(){ this.admobFreeService.BannerAd(); } showInterstitial() { this.admobFreeService.InterstitialAd(); } showRewardVideo() { this.admobFreeService.RewardVideoAd(); } ionViewWillUnload() { this.stop(); this.currentFile={}; } initInfo(){ this.state.info= { id_pub:null, link_pub :"", artist:"", title:"Nothing is play", playing: false }; } ionViewWillEnter(){ this.store.select('appState').subscribe((value: any) => { this.state.media = value.media; this.initInfo(); if(value.info){ this.state.info = value.info; } }); // Updating the Seekbar based on currentTime this.store .select('appState') .pipe( pluck('media', 'timeSec'), filter(value => value !== undefined), map((value: any) => Number.parseInt(value)), distinctUntilChanged() ) .subscribe((value: any) => { this.seekbar.setValue(value); }); this.bd.getMenu().then(res=>{ this.getPlayl(); if(res!=null) { this.settings = res; this.player = this.settings.player; } }); } openFile(file, index) { // tslint:disable-next-line:indent this.addView(file.id_pub); const media = { id_pub:file.id_pub, link_pub : file.link_pub, artist: file.nom_ent, title: file.nom, playing: true }; const n = Number(this.files[index].get_access) + 1; this.files[index].get_access = n; this.playStream(media,index); let i = this.randomInt(1, 10); if (i < 8) { this.showInterstitial(); } } resetState() { this.audioProvider.stop(); this.store.dispatch({ type: RESET }); this.musicControls.destroy(); } islistening(file){ if(this.state.media.duration && this.state.info && this.state.info.playing && this.state.info.id_pub==file.id_pub){ return true; } return false; } setupControl(f,dir=0){ this.musicControls.create({ track : f.title, // optional, default : '' artist : f.artist, // optional, default : '' cover :this.getAvatar(f.avatar_ent,null,0), // optional, default : nothing // cover can be a local path (use fullpath 'file:///storage/emulated/...', or only 'my_image.jpg' if my_image.jpg is in the www folder of your app) // or a remote url ('http://...', 'https://...', 'ftp://...') isPlaying : true, // optional, default : true dismissable : true, // optional, default : false // hide previous/next/close buttons: hasPrev : false, // show previous button, optional, default: true hasNext : false, // show next button, optional, default: true hasClose : true, // show close button, optional, default: false // iOS only, optional album : 'Absolution', // optional, default: '' duration :0, // optional, default: 0 elapsed : 10, // optional, default: 0 hasSkipForward : true, // show skip forward button, optional, default: false hasSkipBackward : true, // show skip backward button, optional, default: false skipForwardInterval: 15, // display number for skip forward, optional, default: 0 skipBackwardInterval: 15, // display number for skip backward, optional, default: 0 hasScrubbing: false, // enable scrubbing from control center and lockscreen progress bar, optional // Android only, optional // text displayed in the status bar when the notification (and the ticker) are updated, optional ticker : 'Now playing "'+f.title+'"', // All icons default to their built-in android equivalents playIcon: 'media_play', pauseIcon: 'media_pause', prevIcon: 'media_prev', nextIcon: 'media_next', closeIcon: 'media_close', notificationIcon: 'notification' }); this.musicControls.subscribe().subscribe(action => { this.events(action); }); this.musicControls.listen(); // activates the observable above } events(action){ const message = JSON.parse(action).message; switch(message) { case 'music-controls-next': //this.musicControls.destroy(); //this.next(); break; case 'music-controls-previous': //this.musicControls.destroy(); //this.previous(); break; case 'music-controls-pause': this.pause(); break; case 'music-controls-play': this.play(); break; case 'music-controls-destroy': this.stop(); break; // External controls (iOS only) case 'music-controls-toggle-play-pause' : // Do something break; case 'music-controls-seek-to': const seekToInSeconds = JSON.parse(action).position; this.musicControls.updateElapsed({ elapsed: seekToInSeconds, isPlaying: true }); this.onSeekEndNew(seekToInSeconds); break; case 'music-controls-skip-forward': // Do something break; case 'music-controls-skip-backward': // Do something break; // Headset events (Android only) // All media button events are listed below case 'music-controls-media-button' : // Do something break; case 'music-controls-headset-unplugged': this.pause(); // Do something break; case 'music-controls-headset-plugged': // Do something break; default: break; } } onSeekEndNew(event) { if (this.onSeekState) { this.audioProvider.seekTo(event); this.play(); } else { this.audioProvider.seekTo(event); } } playStream(media, index) { let file = media; this.resetState(); this.setupControl(media,0); this.state.info=media; this.player=this.settings.player; this.audioProvider.playStream(file).subscribe( event => { const audioObj = event.target; switch (event.type) { case 'canplay': this.currentFile = { index, media, state: 2 }; return this.store.dispatch({ type: CANPLAY, payload: { value: true,mediaInfo:file } }); case 'loadedmetadata': return this.store.dispatch({ type: LOADEDMETADATA, payload: { mediaInfo:file, value: true, data: { time: this.audioProvider.formatTime( audioObj.duration * 1000, 'HH:mm:ss' ), timeSec: audioObj.duration, mediaType: 'mp3' } } }); case 'playing': this.musicControls.updateIsPlaying(true); return this.store.dispatch({ type: PLAYING, payload: { value: true } }); case 'pause': this.musicControls.updateIsPlaying(false); return this.store.dispatch({ type: PLAYING, payload: { value: false } }); case 'timeupdate': this.chechToplayNext(audioObj.currentTime,audioObj.duration); this.musicState.size = this.audioProvider.formatTime( audioObj.duration * 1000, 'HH:mm:ss' ); this.musicState.time = this.audioProvider.formatTime(audioObj.currentTime * 1000, 'HH:mm:ss'); return this.store.dispatch({ type: TIMEUPDATE, payload: { timeSec: audioObj.currentTime, time: this.audioProvider.formatTime( audioObj.currentTime * 1000, 'HH:mm:ss' ) } }); case 'loadstart': this.log("LOADSTART IS CALL");
return this.store.dispatch({ type: LOADSTART, payload: { value: true, mediaInfo:file} }); } }); } pause() { this.audioProvider.pause(); this.currentFile.state = 1; } play() { if(this.state.info.playing){ this.pause(); } this.audioProvider.play(); this.currentFile.state = 2; } stop() { this.reset(); this.audioProvider.stop(); this.currentFile={}; this.state.media ={}; this.initInfo(); } getH(h){ if(h!=null){ let m =h.split(":"); let n=""; if(m[0]!="00"){ n=m[0]+":"; } n+=m[1]+":"+m[2]; return n; } return ""; } chechToplayNext(ta,tb){ if(this.settings.automatic && ta==tb){ this.next(); } } next() { if (this.currentFile.index < this.files.length - 1) { let index = this.currentFile.index + 1; index = this.getNext(index); const file = this.files[index]; this.openFile(file, index); } } previous() { if (this.currentFile.index > 0) { // tslint:disable-next-line:prefer-const let index = this.currentFile.index - 1; index = this.getNext(index); // tslint:disable-next-line:prefer-const let file = this.files[index]; this.openFile(file, index); } } autoplay(){ if(this.settings.autoplay && !this.currentFile.media){ let index = this.randomInt(0,this.files.length-1); let f= this.files[index]; if(f!=null){ this.openFile(f,index); } } } ionViewDidLoad() { this.admobFreeService.BannerAd(); } getNext(index){ if(this.settings.randomly){ return this.randomInt(0,(this.files.length-1)); } return index; } onSeekStart() { this.onSeekState = this.state.info.playing; if (this.onSeekState) { this.pause(); } } onSeekEnd(event) { if (this.onSeekState) { this.audioProvider.seekTo(event.target.value); this.play(); } else { this.audioProvider.seekTo(event.target.value); } } reset() { this.resetState(); this.currentFile = {}; this.displayFooter = 'inactive'; } }
random_line_split
tab2.page.ts
import { Component, ViewChild, Injectable, Inject } from '@angular/core'; import {trigger, state, style, animate, transition } from '@angular/animations'; import { NavController, LoadingController, ToastController} from '@ionic/angular'; import { AudioService } from '../services/audio.service'; import {FormControl} from '@angular/forms'; import {CANPLAY, LOADEDMETADATA, PLAYING, TIMEUPDATE, LOADSTART, RESET} from '../Interface/MediaAction'; import {Store} from '@ngrx/store'; import { GetAudioService } from '../services/get-audio.service'; import {pluck, filter, map, distinctUntilChanged} from 'rxjs/operators'; import { AppConfig } from '../Interface/AppConfig'; import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx'; import { File } from '@ionic-native/file/ngx'; import { AdMobService } from '../services/ad-mob.service'; import { PlaylistService } from '../providers/playlist.service'; import { AnimationService, AnimationBuilder } from 'css-animator'; import { MusicControls } from '@ionic-native/music-controls/ngx'; @Component({ selector: 'app-tab2', templateUrl: 'tab2.page.html', styleUrls: ['tab2.page.scss'], animations: [ trigger('showHide', [ state( 'active', style({ opacity: 1 }) ), state( 'inactive', style({ opacity: 0 }) ), transition('inactive => active', animate('250ms ease-in')), transition('active => inactive', animate('250ms ease-out')) ]), trigger('fadeInOut', [ state('void', style({ opacity: '0' })), state('*', style({ opacity: '1' })), transition('void <=> *', animate('150ms ease-in')) ]) ] }) @Injectable() export class Tab2Page { defaultImage: string = "assets/icon.png"; files: any = []; hfiles: any = []; seekbar: FormControl = new FormControl('seekbar'); state: any = {}; onSeekState: boolean; currentFile: any = {}; currentDL: any = {}; displayFooter = 'inactive'; loggedIn: Boolean; type_ent = []; newData = []; nImg = []; cpage = 1; nextUrl = ''; hnextUrl = ''; endscroll = true; arl = []; musicState: any = {size: '', time: ''}; downloadFile: any; private fileTransfer: FileTransferObject; error; bsearch=false; timeOutToSearch=undefined; timeOutLoad=undefined; query:string = ""; tlong=false; msgUnload; kfile=[]; isDL=false; playlist : any=[]; settings:any = { automatic:false, showImage:true, randomly:false, statistic:true, autoplay:false, cats:[], player:true } myUser = { type_login:1, user_data:{}, }; loader=false; users:any; DEV=true; private animator: AnimationBuilder; constructor( @Inject(FileTransfer) private transfer: FileTransfer, @Inject(File) private file: File, @Inject(ToastController) public toastController: ToastController, public navCtrl: NavController, public audioProvider: AudioService, public loadingCtrl: LoadingController, public cloudProvider: GetAudioService, private admobFreeService: AdMobService, private bd: PlaylistService, @Inject(AnimationService) animationService: AnimationService, @Inject(MusicControls) private musicControls: MusicControls, private store: Store<any> ) { this.animator = animationService.builder(); let i = this.randomInt(1,30) ; if(i<15){ this.showRewardVideo(); } this.bd.getMenu().then((res:any)=>{ if(res!=null) { this.settings=res; this.player=this.settings.player; } }); } public keySeachUp(e) { if(this.query!=""){ this.files = this.filterItems(this.query); if(this.files.length==0){ this.setMsg("Nothing found."); } }else{ this.files = this.hfiles; } this.arrange(); } filterItems(searchTerm) { return this.files.filter(item => { return item.nom.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1; }); } async removeFromPlaylist(file){ const r = await this.bd.removeMusic(file).then((res)=> { this.files=[]; if(res!=null){ this.files = res; } if(this.files.length==0){ this.setMsg("Your playlist is empty."); } this.presentToast(file.nom+ " remove from playlist."); }); } async getPlayl() { const data = await this.bd.getAllMusic().then(res => { if(res !=null){ this.files = res; this.autoplay(); this.arrange(); }else{ this.setMsg("Your playlist is empty, slide item to left to add music in your playlist."); } }); } setMsg(e){ this.tlong = true; this.msgUnload=e; } player: boolean = true; async togglePlayer(e){ if(this.player){ this.animateHide(e,'flipOutX').then(()=>{ this.player = !this.player; }); } else { this.player = await !this.player; this.animateShow(e,'bounceIn').then(()=>{ }); } } emitAnimate(e){ this.animator.setType(e.anim).show(e.el).then(()=>{}); } animateHide(l,e) { return this.animator.setType(e).hide(l); } animateShow(l,e) { return this.animator.setType(e).show(l); } toggleSearch() { this.bsearch=!this.bsearch; if(this.bsearch){ this.hfiles = this.files; }else{ this.files=this.hfiles; this.arrange(); } } arrange(){ if(this.currentFile.media){ for (let i = 0; i < this.files.length; i++) { if(this.files[i].id_pub===this.currentFile.media.id_pub){ this.currentFile.index=i; break; }else{ continue;} } } } async presentToast(msg) { const toast = await this.toastController.create({ message: msg, duration: 3000 }); toast.present(); } setFormat(e){ if(e<1000){ return e+""; }else if (e>=1000 && e<999999){ return Math.ceil((e/1000))+"K"; } else if (e>=1000000 && e<999999999){ return Math.ceil((e/1000000))+"M"; }else{ return "~"; } } async addView(id) { const data = await this.cloudProvider.addView('Bo/@Hb/addView/' + id).then(res => { }); } addNewMusic() { for (let i = 0; i < this.newData.length; i++) { this.files.unshift(this.newData[i]); } } public getAvatar(url, file, index) { if (url == null) { url = 'default.png'; } return AppConfig.getAvatar(url); } log(t) { console.log(t); } randomInt(min, max) { // min and max included return Math.floor(Math.random() * (max - min + 1) + min); } // tslint:disable-next-line:use-lifecycle-interface ngOnInit(){ this.admobFreeService.BannerAd(); } showInterstitial() { this.admobFreeService.InterstitialAd(); } showRewardVideo() { this.admobFreeService.RewardVideoAd(); } ionViewWillUnload() { this.stop(); this.currentFile={}; } initInfo(){ this.state.info= { id_pub:null, link_pub :"", artist:"", title:"Nothing is play", playing: false }; } ionViewWillEnter(){ this.store.select('appState').subscribe((value: any) => { this.state.media = value.media; this.initInfo(); if(value.info){ this.state.info = value.info; } }); // Updating the Seekbar based on currentTime this.store .select('appState') .pipe( pluck('media', 'timeSec'), filter(value => value !== undefined), map((value: any) => Number.parseInt(value)), distinctUntilChanged() ) .subscribe((value: any) => { this.seekbar.setValue(value); }); this.bd.getMenu().then(res=>{ this.getPlayl(); if(res!=null) { this.settings = res; this.player = this.settings.player; } }); } openFile(file, index) { // tslint:disable-next-line:indent this.addView(file.id_pub); const media = { id_pub:file.id_pub, link_pub : file.link_pub, artist: file.nom_ent, title: file.nom, playing: true }; const n = Number(this.files[index].get_access) + 1; this.files[index].get_access = n; this.playStream(media,index); let i = this.randomInt(1, 10); if (i < 8) { this.showInterstitial(); } } resetState() { this.audioProvider.stop(); this.store.dispatch({ type: RESET }); this.musicControls.destroy(); } islistening(file){ if(this.state.media.duration && this.state.info && this.state.info.playing && this.state.info.id_pub==file.id_pub){ return true; } return false; } setupControl(f,dir=0){ this.musicControls.create({ track : f.title, // optional, default : '' artist : f.artist, // optional, default : '' cover :this.getAvatar(f.avatar_ent,null,0), // optional, default : nothing // cover can be a local path (use fullpath 'file:///storage/emulated/...', or only 'my_image.jpg' if my_image.jpg is in the www folder of your app) // or a remote url ('http://...', 'https://...', 'ftp://...') isPlaying : true, // optional, default : true dismissable : true, // optional, default : false // hide previous/next/close buttons: hasPrev : false, // show previous button, optional, default: true hasNext : false, // show next button, optional, default: true hasClose : true, // show close button, optional, default: false // iOS only, optional album : 'Absolution', // optional, default: '' duration :0, // optional, default: 0 elapsed : 10, // optional, default: 0 hasSkipForward : true, // show skip forward button, optional, default: false hasSkipBackward : true, // show skip backward button, optional, default: false skipForwardInterval: 15, // display number for skip forward, optional, default: 0 skipBackwardInterval: 15, // display number for skip backward, optional, default: 0 hasScrubbing: false, // enable scrubbing from control center and lockscreen progress bar, optional // Android only, optional // text displayed in the status bar when the notification (and the ticker) are updated, optional ticker : 'Now playing "'+f.title+'"', // All icons default to their built-in android equivalents playIcon: 'media_play', pauseIcon: 'media_pause', prevIcon: 'media_prev', nextIcon: 'media_next', closeIcon: 'media_close', notificationIcon: 'notification' }); this.musicControls.subscribe().subscribe(action => { this.events(action); }); this.musicControls.listen(); // activates the observable above }
(action){ const message = JSON.parse(action).message; switch(message) { case 'music-controls-next': //this.musicControls.destroy(); //this.next(); break; case 'music-controls-previous': //this.musicControls.destroy(); //this.previous(); break; case 'music-controls-pause': this.pause(); break; case 'music-controls-play': this.play(); break; case 'music-controls-destroy': this.stop(); break; // External controls (iOS only) case 'music-controls-toggle-play-pause' : // Do something break; case 'music-controls-seek-to': const seekToInSeconds = JSON.parse(action).position; this.musicControls.updateElapsed({ elapsed: seekToInSeconds, isPlaying: true }); this.onSeekEndNew(seekToInSeconds); break; case 'music-controls-skip-forward': // Do something break; case 'music-controls-skip-backward': // Do something break; // Headset events (Android only) // All media button events are listed below case 'music-controls-media-button' : // Do something break; case 'music-controls-headset-unplugged': this.pause(); // Do something break; case 'music-controls-headset-plugged': // Do something break; default: break; } } onSeekEndNew(event) { if (this.onSeekState) { this.audioProvider.seekTo(event); this.play(); } else { this.audioProvider.seekTo(event); } } playStream(media, index) { let file = media; this.resetState(); this.setupControl(media,0); this.state.info=media; this.player=this.settings.player; this.audioProvider.playStream(file).subscribe( event => { const audioObj = event.target; switch (event.type) { case 'canplay': this.currentFile = { index, media, state: 2 }; return this.store.dispatch({ type: CANPLAY, payload: { value: true,mediaInfo:file } }); case 'loadedmetadata': return this.store.dispatch({ type: LOADEDMETADATA, payload: { mediaInfo:file, value: true, data: { time: this.audioProvider.formatTime( audioObj.duration * 1000, 'HH:mm:ss' ), timeSec: audioObj.duration, mediaType: 'mp3' } } }); case 'playing': this.musicControls.updateIsPlaying(true); return this.store.dispatch({ type: PLAYING, payload: { value: true } }); case 'pause': this.musicControls.updateIsPlaying(false); return this.store.dispatch({ type: PLAYING, payload: { value: false } }); case 'timeupdate': this.chechToplayNext(audioObj.currentTime,audioObj.duration); this.musicState.size = this.audioProvider.formatTime( audioObj.duration * 1000, 'HH:mm:ss' ); this.musicState.time = this.audioProvider.formatTime(audioObj.currentTime * 1000, 'HH:mm:ss'); return this.store.dispatch({ type: TIMEUPDATE, payload: { timeSec: audioObj.currentTime, time: this.audioProvider.formatTime( audioObj.currentTime * 1000, 'HH:mm:ss' ) } }); case 'loadstart': this.log("LOADSTART IS CALL"); return this.store.dispatch({ type: LOADSTART, payload: { value: true, mediaInfo:file} }); } }); } pause() { this.audioProvider.pause(); this.currentFile.state = 1; } play() { if(this.state.info.playing){ this.pause(); } this.audioProvider.play(); this.currentFile.state = 2; } stop() { this.reset(); this.audioProvider.stop(); this.currentFile={}; this.state.media ={}; this.initInfo(); } getH(h){ if(h!=null){ let m =h.split(":"); let n=""; if(m[0]!="00"){ n=m[0]+":"; } n+=m[1]+":"+m[2]; return n; } return ""; } chechToplayNext(ta,tb){ if(this.settings.automatic && ta==tb){ this.next(); } } next() { if (this.currentFile.index < this.files.length - 1) { let index = this.currentFile.index + 1; index = this.getNext(index); const file = this.files[index]; this.openFile(file, index); } } previous() { if (this.currentFile.index > 0) { // tslint:disable-next-line:prefer-const let index = this.currentFile.index - 1; index = this.getNext(index); // tslint:disable-next-line:prefer-const let file = this.files[index]; this.openFile(file, index); } } autoplay(){ if(this.settings.autoplay && !this.currentFile.media){ let index = this.randomInt(0,this.files.length-1); let f= this.files[index]; if(f!=null){ this.openFile(f,index); } } } ionViewDidLoad() { this.admobFreeService.BannerAd(); } getNext(index){ if(this.settings.randomly){ return this.randomInt(0,(this.files.length-1)); } return index; } onSeekStart() { this.onSeekState = this.state.info.playing; if (this.onSeekState) { this.pause(); } } onSeekEnd(event) { if (this.onSeekState) { this.audioProvider.seekTo(event.target.value); this.play(); } else { this.audioProvider.seekTo(event.target.value); } } reset() { this.resetState(); this.currentFile = {}; this.displayFooter = 'inactive'; } }
events
identifier_name
model.rs
#![allow(unused_unsafe)] use crate::com::*; use crate::consts::*; use crate::texture::*; use raw_window_handle::HasRawWindowHandle; use winapi::_core::f32::consts::PI; use winapi::_core::mem; use winapi::shared::basetsd::UINT16; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::HANDLE; use winapi::shared::windef::HWND; use winapi::shared::winerror::HRESULT; use winapi::vc::limits::UINT_MAX; use winit::platform::windows::*; use winit::window::Window; struct ArrayIterator3<T> { item: [T; 3], index: usize, } impl<T: Copy> ArrayIterator3<T> { pub fn new(item: [T; 3]) -> ArrayIterator3<T> { ArrayIterator3 { item: item, index: 0, } } } impl<T: Copy> Iterator for ArrayIterator3<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { match self.index < self.item.len() { true =>
false => None, } } } #[allow(dead_code)] pub struct DxModel { // Window aspect_ratio: f32, // D3D12 Targets device: ComRc<ID3D12Device>, command_queue: ComRc<ID3D12CommandQueue>, swap_chain: ComRc<IDXGISwapChain3>, dc_dev: ComRc<IDCompositionDevice>, dc_target: ComRc<IDCompositionTarget>, dc_visual: ComRc<IDCompositionVisual>, frame_index: u32, rtv_heap: ComRc<ID3D12DescriptorHeap>, srv_heap: ComRc<ID3D12DescriptorHeap>, rtv_descriptor_size: u32, render_targets: Vec<ComRc<ID3D12Resource>>, command_allocator: ComRc<ID3D12CommandAllocator>, // D3D12 Assets root_signature: ComRc<ID3D12RootSignature>, pipeline_state: ComRc<ID3D12PipelineState>, command_list: ComRc<ID3D12GraphicsCommandList>, // App resources. vertex_buffer: ComRc<ID3D12Resource>, vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW, index_buffer: ComRc<ID3D12Resource>, index_buffer_view: D3D12_INDEX_BUFFER_VIEW, texture: ComRc<ID3D12Resource>, // Synchronization objects. fence: ComRc<ID3D12Fence>, fence_value: u64, fence_event: HANDLE, // Pipeline objects. rotation_radians: f32, viewport: D3D12_VIEWPORT, scissor_rect: D3D12_RECT, } impl DxModel { pub fn new(window: &Window) -> Result<DxModel, HRESULT> { // window params let size = window.inner_size(); println!("inner_size={:?}", size); let hwnd = window.raw_window_handle(); let aspect_ratio = (size.width as f32) / (size.height as f32); let viewport = D3D12_VIEWPORT { Width: size.width as _, Height: size.height as _, MaxDepth: 1.0_f32, ..unsafe { mem::zeroed() } }; let scissor_rect = D3D12_RECT { right: size.width as _, bottom: size.height as _, ..unsafe { mem::zeroed() } }; // Enable the D3D12 debug layer. #[cfg(build = "debug")] { let debugController = d3d12_get_debug_interface::<ID3D12Debug>()?; unsafe { debugController.EnableDebugLayer() } } let factory = create_dxgi_factory1::<IDXGIFactory4>()?; // d3d12デバイスの作成 // ハードウェアデバイスが取得できなければ // WARPデバイスを取得する let device = factory.d3d12_create_best_device()?; // コマンドキューの作成 let command_queue = { let desc = D3D12_COMMAND_QUEUE_DESC { Flags: D3D12_COMMAND_QUEUE_FLAG_NONE, Type: D3D12_COMMAND_LIST_TYPE_DIRECT, NodeMask: 0, Priority: 0, }; device.create_command_queue::<ID3D12CommandQueue>(&desc)? }; // swap chainの作成 let swap_chain = { let desc = DXGI_SWAP_CHAIN_DESC1 { BufferCount: FRAME_COUNT, Width: size.width, Height: size.height, Format: DXGI_FORMAT_R8G8B8A8_UNORM, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, AlphaMode: DXGI_ALPHA_MODE_PREMULTIPLIED, Flags: 0, Scaling: 0, Stereo: 0, }; factory .create_swap_chain_for_composition(&command_queue, &desc)? .query_interface::<IDXGISwapChain3>()? }; // DirectComposition 設定 let dc_dev = dcomp_create_device::<IDCompositionDevice>(None)?; let dc_target = dc_dev.create_target_for_hwnd(hwnd, true)?; let dc_visual = dc_dev.create_visual()?; dc_visual.set_content(&swap_chain)?; dc_target.set_root(&dc_visual)?; dc_dev.commit()?; // このサンプルはフルスクリーンへの遷移をサポートしません。 factory.make_window_association(hwnd, DXGI_MWA_NO_ALT_ENTER)?; let mut frame_index = swap_chain.get_current_back_buffer_index(); // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. let rtv_heap = { let desc = D3D12_DESCRIPTOR_HEAP_DESC { NumDescriptors: FRAME_COUNT, Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0, }; device.create_descriptor_heap::<ID3D12DescriptorHeap>(&desc)? }; // Describe and create a shader resource view (SRV) heap for the texture. let srv_heap = { let desc = D3D12_DESCRIPTOR_HEAP_DESC { NumDescriptors: 1, Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }; device.create_descriptor_heap::<ID3D12DescriptorHeap>(&desc)? }; let rtv_descriptor_size = device.get_descriptor_handle_increment_size(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); // フレームバッファの作成 let render_targets = { let mut rtv_handle = rtv_heap.get_cpu_descriptor_handle_for_heap_start(); let mut targets: Vec<ComRc<ID3D12Resource>> = Vec::with_capacity(FRAME_COUNT as usize); for n in 0..FRAME_COUNT { let target = swap_chain.get_buffer::<ID3D12Resource>(n)?; device.create_render_target_view(&target, None, rtv_handle); rtv_handle.offset(1, rtv_descriptor_size); targets.push(target); } targets }; // コマンドアロケータ let command_allocator = device.create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; //------------------------------------------------------------------ // LoadAssets(d3d12の描画初期化) //------------------------------------------------------------------ // Create the root signature. let root_signature = { let ranges = { let range = D3D12_DESCRIPTOR_RANGE::new(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); [range] }; let root_parameters = { let a = D3D12_ROOT_PARAMETER::new_constants(1, 0, 0, D3D12_SHADER_VISIBILITY_VERTEX); let b = D3D12_ROOT_PARAMETER::new_descriptor_table( &ranges, D3D12_SHADER_VISIBILITY_PIXEL, ); [a, b] }; let samplers = unsafe { let mut sampler = mem::zeroed::<D3D12_STATIC_SAMPLER_DESC>(); sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.MipLODBias = 0.0; sampler.MaxAnisotropy = 0; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; sampler.MinLOD = 0.0; sampler.MaxLOD = D3D12_FLOAT32_MAX; sampler.ShaderRegister = 0; sampler.RegisterSpace = 0; sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; [sampler] }; let desc = D3D12_ROOT_SIGNATURE_DESC::new( &root_parameters, &samplers, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, ); let (signature, _error) = d3d12_serialize_root_signature(&desc, D3D_ROOT_SIGNATURE_VERSION_1)?; device.create_root_signature::<ID3D12RootSignature>( 0, signature.get_buffer_pointer(), signature.get_buffer_size(), )? }; // Create the pipeline state, which includes compiling and loading shaders. let pipeline_state = { let flags: u32 = { #[cfg(debug)] { D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION } #[cfg(not(debug))] { 0 } }; let file = "resources\\shaders.hlsl"; let (vertex_shader, _) = d3d_compile_from_file(file, None, None, "VSMain", "vs_5_0", flags, 0)?; let (pixel_shader, _) = d3d_compile_from_file(file, None, None, "PSMain", "ps_5_0", flags, 0)?; // Define the vertex input layout. let input_element_descs = { let a = D3D12_INPUT_ELEMENT_DESC::new( *t::POSITION, 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0, ); let b = D3D12_INPUT_ELEMENT_DESC::new( *t::TEXCOORD, 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0, ); [a, b] }; let alpha_blend = { let mut desc: D3D12_BLEND_DESC = unsafe { mem::zeroed() }; desc.AlphaToCoverageEnable = FALSE; desc.IndependentBlendEnable = FALSE; desc.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { BlendEnable: TRUE, LogicOpEnable: FALSE, SrcBlend: D3D12_BLEND_ONE, DestBlend: D3D12_BLEND_INV_SRC_ALPHA, BlendOp: D3D12_BLEND_OP_ADD, SrcBlendAlpha: D3D12_BLEND_ONE, DestBlendAlpha: D3D12_BLEND_INV_SRC_ALPHA, BlendOpAlpha: D3D12_BLEND_OP_ADD, LogicOp: D3D12_LOGIC_OP_CLEAR, RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL as u8, }; desc }; // Describe and create the graphics pipeline state object (PSO). let pso_desc = { let mut desc: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { mem::zeroed() }; desc.InputLayout = input_element_descs.layout(); desc.pRootSignature = to_mut_ptr(root_signature.as_ptr()); desc.VS = D3D12_SHADER_BYTECODE::new(&vertex_shader); desc.PS = D3D12_SHADER_BYTECODE::new(&pixel_shader); desc.RasterizerState = D3D12_RASTERIZER_DESC::default(); desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; desc.BlendState = alpha_blend; desc.DepthStencilState.DepthEnable = FALSE; desc.DepthStencilState.StencilEnable = FALSE; desc.SampleMask = UINT_MAX; desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; desc.NumRenderTargets = 1; desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc }; device.create_graphics_pipeline_state(&pso_desc)? }; // Create the command list. let command_list = device.create_command_list::<ID3D12GraphicsCommandList>( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, &command_allocator, &pipeline_state, )?; // Create the vertex buffer. let (vertex_buffer, vertex_buffer_view) = { // Define the geometry for a circle. let items = (-1..CIRCLE_SEGMENTS) .map(|i| match i { -1 => { let pos = [0_f32, 0_f32, 0_f32]; let uv = [0.5_f32, 0.5_f32]; Vertex::new(pos, uv) } _ => { let theta = PI * 2.0_f32 * (i as f32) / (CIRCLE_SEGMENTS as f32); let x = theta.sin(); let y = theta.cos(); let pos = [x, y * aspect_ratio, 0.0_f32]; let uv = [x * 0.5_f32 + 0.5_f32, y * 0.5_f32 + 0.5_f32]; Vertex::new(pos, uv) } }) .collect::<Vec<_>>(); println!("{:?}", items); let size_of = mem::size_of::<Vertex>(); let size = size_of * items.len(); let p = items.as_ptr(); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(size as u64); let buffer = device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )?; // Copy the triangle data to the vertex buffer. let read_range = D3D12_RANGE::new(0, 0); // We do not intend to read from this resource on the CPU. buffer.map(0, Some(&read_range))?.memcpy(p, size); // Initialize the vertex buffer view. let view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: buffer.get_gpu_virtual_address(), SizeInBytes: size as u32, StrideInBytes: size_of as u32, }; (buffer, view) }; // Create the index buffer let (index_buffer, index_buffer_view) = { // Define the geometry for a circle. let items = (0..CIRCLE_SEGMENTS) .map(|i| { let a = 0 as UINT16; let b = (1 + i) as UINT16; let c = (2 + i) as UINT16; [a, b, c] }) .flat_map(|a| ArrayIterator3::new(a)) .collect::<Vec<_>>(); let size_of = mem::size_of::<UINT16>(); let size = size_of * items.len(); let p = items.as_ptr(); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(size as u64); let buffer = device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )?; // Copy the index data to the index buffer. let read_range = D3D12_RANGE::new(0, 0); // We do not intend to read from this resource on the CPU. buffer.map(0, Some(&read_range))?.memcpy(p, size); // Intialize the index buffer view let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: buffer.get_gpu_virtual_address(), SizeInBytes: size as u32, Format: DXGI_FORMAT_R16_UINT, }; (buffer, view) }; // Create the texture. // Note: ComPtr's are CPU objects but this resource needs to stay in scope until // the command list that references it has finished executing on the GPU. // We will flush the GPU at the end of this method to ensure the resource is not // prematurely destroyed. // texture_upload_heapの開放タイミングがGPUへのフラッシュ後になるように // 所有権を関数スコープに追い出しておく let (_texture_upload_heap, texture) = { // Describe and create a Texture2D. let texture_desc = D3D12_RESOURCE_DESC::new( D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE, ); let texture = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_DEFAULT); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &texture_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, )? }; let upload_buffer_size = texture.get_required_intermediate_size(0, 1)?; // Create the GPU upload buffer. let texture_upload_heap = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(upload_buffer_size); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )? }; // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. let texture_bytes = generate_texture_data(); let texture_data = { let ptr = texture_bytes.as_ptr(); let row_pitch = ((TEXTURE_WIDTH as usize) * mem::size_of::<u32>()) as isize; let slice_pitch = row_pitch * (TEXTURE_HEIGHT as isize); [D3D12_SUBRESOURCE_DATA { pData: ptr as _, RowPitch: row_pitch, SlicePitch: slice_pitch, }] }; let _ = command_list.update_subresources_as_heap( &texture, &texture_upload_heap, 0, &texture_data, )?; { let barrier = D3D12_RESOURCE_BARRIER::transition( &texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, ); command_list.resource_barrier(1, &barrier); } // Describe and create a SRV for the texture. { let desc = unsafe { let mut desc = mem::zeroed::<D3D12_SHADER_RESOURCE_VIEW_DESC>(); desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; desc.Format = texture_desc.Format; desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; { let mut t = desc.u.Texture2D_mut(); t.MipLevels = 1; } desc }; device.create_shader_resource_view( &texture, &desc, srv_heap.get_cpu_descriptor_handle_for_heap_start(), ); } (texture_upload_heap, texture) }; // Close the command list and execute it to begin the initial GPU setup. { command_list.close()?; let a: &ID3D12GraphicsCommandList = &command_list; command_queue.execute_command_lists(&[a]); } // Create synchronization objects and wait until assets have been uploaded to the GPU. let (fence, fence_value, fence_event) = { let fence = device.create_fence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE)?; let mut fence_value = 1_u64; // Create an event handle to use for frame synchronization. let fence_event = create_event(None, false, false, None)?; // Wait for the command list to execute; we are reusing the same command // list in our main loop but for now, we just want to wait for setup to // complete before continuing. wait_for_previous_frame( &swap_chain, &command_queue, &fence, fence_event, &mut fence_value, &mut frame_index, )?; (fence, fence_value, fence_event) }; //------------------------------------------------------------------ // result //------------------------------------------------------------------ Ok(DxModel { aspect_ratio: aspect_ratio, device: device, command_queue: command_queue, swap_chain: swap_chain, dc_dev: dc_dev, dc_target: dc_target, dc_visual: dc_visual, frame_index: frame_index, rtv_heap: rtv_heap, srv_heap: srv_heap, rtv_descriptor_size: rtv_descriptor_size, render_targets: render_targets, command_allocator: command_allocator, root_signature: root_signature, pipeline_state: pipeline_state, command_list: command_list, vertex_buffer: vertex_buffer, vertex_buffer_view: vertex_buffer_view, index_buffer: index_buffer, index_buffer_view: index_buffer_view, texture: texture, fence: fence, fence_value: fence_value, fence_event: fence_event, rotation_radians: 0_f32, viewport: viewport, scissor_rect: scissor_rect, }) } pub fn render(&mut self) -> Result<(), HRESULT> { { self.populate_command_list()?; } { let command_queue = &self.command_queue; let command_list = &self.command_list; let swap_chain = &self.swap_chain; command_queue.execute_command_lists(&[command_list]); swap_chain.present(1, 0)?; } { self.wait_for_previous_frame()?; } Ok(()) } /// 描画コマンドリストを構築する fn populate_command_list(&mut self) -> Result<(), HRESULT> { let command_allocator = self.command_allocator.as_ref(); let command_list = self.command_list.as_ref(); let pipeline_state = self.pipeline_state.as_ref(); let root_signature = self.root_signature.as_ref(); let srv_heap = self.srv_heap.as_ref(); let rtv_heap = self.rtv_heap.as_ref(); let rtv_descriptor_size = self.rtv_descriptor_size; let viewport = &self.viewport; let scissor_rect = &self.scissor_rect; let render_targets = self.render_targets.as_slice(); let frame_index = self.frame_index as usize; let vertex_buffer_view = &self.vertex_buffer_view; let index_buffer_view = &self.index_buffer_view; // Command list allocators can only be reset when the associated // command lists have finished execution on the GPU; apps should use // fences to determine GPU execution progress. command_allocator.reset()?; // However, when ExecuteCommandList() is called on a particular command // list, that command list can then be reset at any time and must be before // re-recording. command_list.reset(command_allocator, pipeline_state)?; // Set necessary state. command_list.set_graphics_root_signature(root_signature); let pp_heaps = [srv_heap]; command_list.set_descriptor_heaps(&pp_heaps); self.rotation_radians += 0.02_f32; let rotation_radians = self.rotation_radians; command_list.set_graphics_root_f32_constant(0, rotation_radians, 0); command_list.set_graphics_root_descriptor_table( 1, srv_heap.get_gpu_descriptor_handle_for_heap_start(), ); let viewports = [*viewport]; command_list.rs_set_viewports(&viewports); let scissor_rects = [*scissor_rect]; command_list.rs_set_scissor_rects(&scissor_rects); // Indicate that the back buffer will be used as a render target. { let barrier = D3D12_RESOURCE_BARRIER::transition( &render_targets[frame_index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET, ); command_list.resource_barrier(1, &barrier); } let mut rtv_handle = rtv_heap.get_cpu_descriptor_handle_for_heap_start(); rtv_handle.offset(frame_index as _, rtv_descriptor_size); let rtv_handles = [rtv_handle]; command_list.om_set_render_targets(&rtv_handles, false, None); // Record commands. let clear_color = [0_f32; 4]; let no_rects = []; command_list.clear_render_target_view(rtv_handle, &clear_color, &no_rects); command_list.ia_set_primitive_topology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); let vertex_buffer_views = [vertex_buffer_view.clone()]; command_list.ia_set_vertex_buffers(0, &vertex_buffer_views); command_list.ia_set_index_buffer(index_buffer_view); command_list.draw_indexed_instanced((CIRCLE_SEGMENTS * 3) as _, 1, 0, 0, 0); // Indicate that the back buffer will now be used to present. { let barrier = D3D12_RESOURCE_BARRIER::transition( &render_targets[frame_index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT, ); command_list.resource_barrier(1, &barrier); } command_list.close()?; Ok(()) } fn wait_for_previous_frame(&mut self) -> Result<(), HRESULT> { let mut fence_value = self.fence_value; let mut frame_index = self.frame_index; wait_for_previous_frame( &self.swap_chain, &self.command_queue, &self.fence, self.fence_event, &mut fence_value, &mut frame_index, )?; self.fence_value = fence_value; self.frame_index = frame_index; Ok(()) } } // WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE. // This is code implemented as such for simplicity. The D3D12HelloFrameBuffering // sample illustrates how to use fences for efficient resource usage and to // maximize GPU utilization. fn wait_for_previous_frame( swap_chain: &IDXGISwapChain3, command_queue: &ID3D12CommandQueue, fence: &ID3D12Fence, event: HANDLE, fence_value: &mut u64, frame_index: &mut u32, ) -> Result<(), HRESULT> { // Signal and increment the fence value. let old_fence_value = *fence_value; command_queue.signal(fence, old_fence_value)?; *fence_value += 1; // Wait until the previous frame is finished. fence.wait_infinite(old_fence_value, event)?; *frame_index = swap_chain.get_current_back_buffer_index(); Ok(()) }
{ let rc = self.item[self.index]; self.index += 1; Some(rc) }
conditional_block
model.rs
#![allow(unused_unsafe)] use crate::com::*; use crate::consts::*; use crate::texture::*; use raw_window_handle::HasRawWindowHandle; use winapi::_core::f32::consts::PI; use winapi::_core::mem; use winapi::shared::basetsd::UINT16; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::HANDLE; use winapi::shared::windef::HWND; use winapi::shared::winerror::HRESULT; use winapi::vc::limits::UINT_MAX; use winit::platform::windows::*; use winit::window::Window; struct ArrayIterator3<T> { item: [T; 3], index: usize, } impl<T: Copy> ArrayIterator3<T> { pub fn new(item: [T; 3]) -> ArrayIterator3<T> { ArrayIterator3 { item: item, index: 0, } } } impl<T: Copy> Iterator for ArrayIterator3<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { match self.index < self.item.len() { true => { let rc = self.item[self.index]; self.index += 1; Some(rc) } false => None, } } } #[allow(dead_code)] pub struct DxModel { // Window aspect_ratio: f32, // D3D12 Targets device: ComRc<ID3D12Device>, command_queue: ComRc<ID3D12CommandQueue>, swap_chain: ComRc<IDXGISwapChain3>, dc_dev: ComRc<IDCompositionDevice>, dc_target: ComRc<IDCompositionTarget>, dc_visual: ComRc<IDCompositionVisual>, frame_index: u32, rtv_heap: ComRc<ID3D12DescriptorHeap>, srv_heap: ComRc<ID3D12DescriptorHeap>, rtv_descriptor_size: u32, render_targets: Vec<ComRc<ID3D12Resource>>, command_allocator: ComRc<ID3D12CommandAllocator>, // D3D12 Assets root_signature: ComRc<ID3D12RootSignature>, pipeline_state: ComRc<ID3D12PipelineState>, command_list: ComRc<ID3D12GraphicsCommandList>, // App resources. vertex_buffer: ComRc<ID3D12Resource>, vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW, index_buffer: ComRc<ID3D12Resource>, index_buffer_view: D3D12_INDEX_BUFFER_VIEW, texture: ComRc<ID3D12Resource>, // Synchronization objects. fence: ComRc<ID3D12Fence>, fence_value: u64, fence_event: HANDLE, // Pipeline objects. rotation_radians: f32, viewport: D3D12_VIEWPORT, scissor_rect: D3D12_RECT, } impl DxModel { pub fn
(window: &Window) -> Result<DxModel, HRESULT> { // window params let size = window.inner_size(); println!("inner_size={:?}", size); let hwnd = window.raw_window_handle(); let aspect_ratio = (size.width as f32) / (size.height as f32); let viewport = D3D12_VIEWPORT { Width: size.width as _, Height: size.height as _, MaxDepth: 1.0_f32, ..unsafe { mem::zeroed() } }; let scissor_rect = D3D12_RECT { right: size.width as _, bottom: size.height as _, ..unsafe { mem::zeroed() } }; // Enable the D3D12 debug layer. #[cfg(build = "debug")] { let debugController = d3d12_get_debug_interface::<ID3D12Debug>()?; unsafe { debugController.EnableDebugLayer() } } let factory = create_dxgi_factory1::<IDXGIFactory4>()?; // d3d12デバイスの作成 // ハードウェアデバイスが取得できなければ // WARPデバイスを取得する let device = factory.d3d12_create_best_device()?; // コマンドキューの作成 let command_queue = { let desc = D3D12_COMMAND_QUEUE_DESC { Flags: D3D12_COMMAND_QUEUE_FLAG_NONE, Type: D3D12_COMMAND_LIST_TYPE_DIRECT, NodeMask: 0, Priority: 0, }; device.create_command_queue::<ID3D12CommandQueue>(&desc)? }; // swap chainの作成 let swap_chain = { let desc = DXGI_SWAP_CHAIN_DESC1 { BufferCount: FRAME_COUNT, Width: size.width, Height: size.height, Format: DXGI_FORMAT_R8G8B8A8_UNORM, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, AlphaMode: DXGI_ALPHA_MODE_PREMULTIPLIED, Flags: 0, Scaling: 0, Stereo: 0, }; factory .create_swap_chain_for_composition(&command_queue, &desc)? .query_interface::<IDXGISwapChain3>()? }; // DirectComposition 設定 let dc_dev = dcomp_create_device::<IDCompositionDevice>(None)?; let dc_target = dc_dev.create_target_for_hwnd(hwnd, true)?; let dc_visual = dc_dev.create_visual()?; dc_visual.set_content(&swap_chain)?; dc_target.set_root(&dc_visual)?; dc_dev.commit()?; // このサンプルはフルスクリーンへの遷移をサポートしません。 factory.make_window_association(hwnd, DXGI_MWA_NO_ALT_ENTER)?; let mut frame_index = swap_chain.get_current_back_buffer_index(); // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. let rtv_heap = { let desc = D3D12_DESCRIPTOR_HEAP_DESC { NumDescriptors: FRAME_COUNT, Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0, }; device.create_descriptor_heap::<ID3D12DescriptorHeap>(&desc)? }; // Describe and create a shader resource view (SRV) heap for the texture. let srv_heap = { let desc = D3D12_DESCRIPTOR_HEAP_DESC { NumDescriptors: 1, Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }; device.create_descriptor_heap::<ID3D12DescriptorHeap>(&desc)? }; let rtv_descriptor_size = device.get_descriptor_handle_increment_size(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); // フレームバッファの作成 let render_targets = { let mut rtv_handle = rtv_heap.get_cpu_descriptor_handle_for_heap_start(); let mut targets: Vec<ComRc<ID3D12Resource>> = Vec::with_capacity(FRAME_COUNT as usize); for n in 0..FRAME_COUNT { let target = swap_chain.get_buffer::<ID3D12Resource>(n)?; device.create_render_target_view(&target, None, rtv_handle); rtv_handle.offset(1, rtv_descriptor_size); targets.push(target); } targets }; // コマンドアロケータ let command_allocator = device.create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; //------------------------------------------------------------------ // LoadAssets(d3d12の描画初期化) //------------------------------------------------------------------ // Create the root signature. let root_signature = { let ranges = { let range = D3D12_DESCRIPTOR_RANGE::new(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); [range] }; let root_parameters = { let a = D3D12_ROOT_PARAMETER::new_constants(1, 0, 0, D3D12_SHADER_VISIBILITY_VERTEX); let b = D3D12_ROOT_PARAMETER::new_descriptor_table( &ranges, D3D12_SHADER_VISIBILITY_PIXEL, ); [a, b] }; let samplers = unsafe { let mut sampler = mem::zeroed::<D3D12_STATIC_SAMPLER_DESC>(); sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.MipLODBias = 0.0; sampler.MaxAnisotropy = 0; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; sampler.MinLOD = 0.0; sampler.MaxLOD = D3D12_FLOAT32_MAX; sampler.ShaderRegister = 0; sampler.RegisterSpace = 0; sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; [sampler] }; let desc = D3D12_ROOT_SIGNATURE_DESC::new( &root_parameters, &samplers, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, ); let (signature, _error) = d3d12_serialize_root_signature(&desc, D3D_ROOT_SIGNATURE_VERSION_1)?; device.create_root_signature::<ID3D12RootSignature>( 0, signature.get_buffer_pointer(), signature.get_buffer_size(), )? }; // Create the pipeline state, which includes compiling and loading shaders. let pipeline_state = { let flags: u32 = { #[cfg(debug)] { D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION } #[cfg(not(debug))] { 0 } }; let file = "resources\\shaders.hlsl"; let (vertex_shader, _) = d3d_compile_from_file(file, None, None, "VSMain", "vs_5_0", flags, 0)?; let (pixel_shader, _) = d3d_compile_from_file(file, None, None, "PSMain", "ps_5_0", flags, 0)?; // Define the vertex input layout. let input_element_descs = { let a = D3D12_INPUT_ELEMENT_DESC::new( *t::POSITION, 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0, ); let b = D3D12_INPUT_ELEMENT_DESC::new( *t::TEXCOORD, 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0, ); [a, b] }; let alpha_blend = { let mut desc: D3D12_BLEND_DESC = unsafe { mem::zeroed() }; desc.AlphaToCoverageEnable = FALSE; desc.IndependentBlendEnable = FALSE; desc.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { BlendEnable: TRUE, LogicOpEnable: FALSE, SrcBlend: D3D12_BLEND_ONE, DestBlend: D3D12_BLEND_INV_SRC_ALPHA, BlendOp: D3D12_BLEND_OP_ADD, SrcBlendAlpha: D3D12_BLEND_ONE, DestBlendAlpha: D3D12_BLEND_INV_SRC_ALPHA, BlendOpAlpha: D3D12_BLEND_OP_ADD, LogicOp: D3D12_LOGIC_OP_CLEAR, RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL as u8, }; desc }; // Describe and create the graphics pipeline state object (PSO). let pso_desc = { let mut desc: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { mem::zeroed() }; desc.InputLayout = input_element_descs.layout(); desc.pRootSignature = to_mut_ptr(root_signature.as_ptr()); desc.VS = D3D12_SHADER_BYTECODE::new(&vertex_shader); desc.PS = D3D12_SHADER_BYTECODE::new(&pixel_shader); desc.RasterizerState = D3D12_RASTERIZER_DESC::default(); desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; desc.BlendState = alpha_blend; desc.DepthStencilState.DepthEnable = FALSE; desc.DepthStencilState.StencilEnable = FALSE; desc.SampleMask = UINT_MAX; desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; desc.NumRenderTargets = 1; desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc }; device.create_graphics_pipeline_state(&pso_desc)? }; // Create the command list. let command_list = device.create_command_list::<ID3D12GraphicsCommandList>( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, &command_allocator, &pipeline_state, )?; // Create the vertex buffer. let (vertex_buffer, vertex_buffer_view) = { // Define the geometry for a circle. let items = (-1..CIRCLE_SEGMENTS) .map(|i| match i { -1 => { let pos = [0_f32, 0_f32, 0_f32]; let uv = [0.5_f32, 0.5_f32]; Vertex::new(pos, uv) } _ => { let theta = PI * 2.0_f32 * (i as f32) / (CIRCLE_SEGMENTS as f32); let x = theta.sin(); let y = theta.cos(); let pos = [x, y * aspect_ratio, 0.0_f32]; let uv = [x * 0.5_f32 + 0.5_f32, y * 0.5_f32 + 0.5_f32]; Vertex::new(pos, uv) } }) .collect::<Vec<_>>(); println!("{:?}", items); let size_of = mem::size_of::<Vertex>(); let size = size_of * items.len(); let p = items.as_ptr(); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(size as u64); let buffer = device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )?; // Copy the triangle data to the vertex buffer. let read_range = D3D12_RANGE::new(0, 0); // We do not intend to read from this resource on the CPU. buffer.map(0, Some(&read_range))?.memcpy(p, size); // Initialize the vertex buffer view. let view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: buffer.get_gpu_virtual_address(), SizeInBytes: size as u32, StrideInBytes: size_of as u32, }; (buffer, view) }; // Create the index buffer let (index_buffer, index_buffer_view) = { // Define the geometry for a circle. let items = (0..CIRCLE_SEGMENTS) .map(|i| { let a = 0 as UINT16; let b = (1 + i) as UINT16; let c = (2 + i) as UINT16; [a, b, c] }) .flat_map(|a| ArrayIterator3::new(a)) .collect::<Vec<_>>(); let size_of = mem::size_of::<UINT16>(); let size = size_of * items.len(); let p = items.as_ptr(); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(size as u64); let buffer = device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )?; // Copy the index data to the index buffer. let read_range = D3D12_RANGE::new(0, 0); // We do not intend to read from this resource on the CPU. buffer.map(0, Some(&read_range))?.memcpy(p, size); // Intialize the index buffer view let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: buffer.get_gpu_virtual_address(), SizeInBytes: size as u32, Format: DXGI_FORMAT_R16_UINT, }; (buffer, view) }; // Create the texture. // Note: ComPtr's are CPU objects but this resource needs to stay in scope until // the command list that references it has finished executing on the GPU. // We will flush the GPU at the end of this method to ensure the resource is not // prematurely destroyed. // texture_upload_heapの開放タイミングがGPUへのフラッシュ後になるように // 所有権を関数スコープに追い出しておく let (_texture_upload_heap, texture) = { // Describe and create a Texture2D. let texture_desc = D3D12_RESOURCE_DESC::new( D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE, ); let texture = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_DEFAULT); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &texture_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, )? }; let upload_buffer_size = texture.get_required_intermediate_size(0, 1)?; // Create the GPU upload buffer. let texture_upload_heap = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(upload_buffer_size); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )? }; // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. let texture_bytes = generate_texture_data(); let texture_data = { let ptr = texture_bytes.as_ptr(); let row_pitch = ((TEXTURE_WIDTH as usize) * mem::size_of::<u32>()) as isize; let slice_pitch = row_pitch * (TEXTURE_HEIGHT as isize); [D3D12_SUBRESOURCE_DATA { pData: ptr as _, RowPitch: row_pitch, SlicePitch: slice_pitch, }] }; let _ = command_list.update_subresources_as_heap( &texture, &texture_upload_heap, 0, &texture_data, )?; { let barrier = D3D12_RESOURCE_BARRIER::transition( &texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, ); command_list.resource_barrier(1, &barrier); } // Describe and create a SRV for the texture. { let desc = unsafe { let mut desc = mem::zeroed::<D3D12_SHADER_RESOURCE_VIEW_DESC>(); desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; desc.Format = texture_desc.Format; desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; { let mut t = desc.u.Texture2D_mut(); t.MipLevels = 1; } desc }; device.create_shader_resource_view( &texture, &desc, srv_heap.get_cpu_descriptor_handle_for_heap_start(), ); } (texture_upload_heap, texture) }; // Close the command list and execute it to begin the initial GPU setup. { command_list.close()?; let a: &ID3D12GraphicsCommandList = &command_list; command_queue.execute_command_lists(&[a]); } // Create synchronization objects and wait until assets have been uploaded to the GPU. let (fence, fence_value, fence_event) = { let fence = device.create_fence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE)?; let mut fence_value = 1_u64; // Create an event handle to use for frame synchronization. let fence_event = create_event(None, false, false, None)?; // Wait for the command list to execute; we are reusing the same command // list in our main loop but for now, we just want to wait for setup to // complete before continuing. wait_for_previous_frame( &swap_chain, &command_queue, &fence, fence_event, &mut fence_value, &mut frame_index, )?; (fence, fence_value, fence_event) }; //------------------------------------------------------------------ // result //------------------------------------------------------------------ Ok(DxModel { aspect_ratio: aspect_ratio, device: device, command_queue: command_queue, swap_chain: swap_chain, dc_dev: dc_dev, dc_target: dc_target, dc_visual: dc_visual, frame_index: frame_index, rtv_heap: rtv_heap, srv_heap: srv_heap, rtv_descriptor_size: rtv_descriptor_size, render_targets: render_targets, command_allocator: command_allocator, root_signature: root_signature, pipeline_state: pipeline_state, command_list: command_list, vertex_buffer: vertex_buffer, vertex_buffer_view: vertex_buffer_view, index_buffer: index_buffer, index_buffer_view: index_buffer_view, texture: texture, fence: fence, fence_value: fence_value, fence_event: fence_event, rotation_radians: 0_f32, viewport: viewport, scissor_rect: scissor_rect, }) } pub fn render(&mut self) -> Result<(), HRESULT> { { self.populate_command_list()?; } { let command_queue = &self.command_queue; let command_list = &self.command_list; let swap_chain = &self.swap_chain; command_queue.execute_command_lists(&[command_list]); swap_chain.present(1, 0)?; } { self.wait_for_previous_frame()?; } Ok(()) } /// 描画コマンドリストを構築する fn populate_command_list(&mut self) -> Result<(), HRESULT> { let command_allocator = self.command_allocator.as_ref(); let command_list = self.command_list.as_ref(); let pipeline_state = self.pipeline_state.as_ref(); let root_signature = self.root_signature.as_ref(); let srv_heap = self.srv_heap.as_ref(); let rtv_heap = self.rtv_heap.as_ref(); let rtv_descriptor_size = self.rtv_descriptor_size; let viewport = &self.viewport; let scissor_rect = &self.scissor_rect; let render_targets = self.render_targets.as_slice(); let frame_index = self.frame_index as usize; let vertex_buffer_view = &self.vertex_buffer_view; let index_buffer_view = &self.index_buffer_view; // Command list allocators can only be reset when the associated // command lists have finished execution on the GPU; apps should use // fences to determine GPU execution progress. command_allocator.reset()?; // However, when ExecuteCommandList() is called on a particular command // list, that command list can then be reset at any time and must be before // re-recording. command_list.reset(command_allocator, pipeline_state)?; // Set necessary state. command_list.set_graphics_root_signature(root_signature); let pp_heaps = [srv_heap]; command_list.set_descriptor_heaps(&pp_heaps); self.rotation_radians += 0.02_f32; let rotation_radians = self.rotation_radians; command_list.set_graphics_root_f32_constant(0, rotation_radians, 0); command_list.set_graphics_root_descriptor_table( 1, srv_heap.get_gpu_descriptor_handle_for_heap_start(), ); let viewports = [*viewport]; command_list.rs_set_viewports(&viewports); let scissor_rects = [*scissor_rect]; command_list.rs_set_scissor_rects(&scissor_rects); // Indicate that the back buffer will be used as a render target. { let barrier = D3D12_RESOURCE_BARRIER::transition( &render_targets[frame_index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET, ); command_list.resource_barrier(1, &barrier); } let mut rtv_handle = rtv_heap.get_cpu_descriptor_handle_for_heap_start(); rtv_handle.offset(frame_index as _, rtv_descriptor_size); let rtv_handles = [rtv_handle]; command_list.om_set_render_targets(&rtv_handles, false, None); // Record commands. let clear_color = [0_f32; 4]; let no_rects = []; command_list.clear_render_target_view(rtv_handle, &clear_color, &no_rects); command_list.ia_set_primitive_topology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); let vertex_buffer_views = [vertex_buffer_view.clone()]; command_list.ia_set_vertex_buffers(0, &vertex_buffer_views); command_list.ia_set_index_buffer(index_buffer_view); command_list.draw_indexed_instanced((CIRCLE_SEGMENTS * 3) as _, 1, 0, 0, 0); // Indicate that the back buffer will now be used to present. { let barrier = D3D12_RESOURCE_BARRIER::transition( &render_targets[frame_index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT, ); command_list.resource_barrier(1, &barrier); } command_list.close()?; Ok(()) } fn wait_for_previous_frame(&mut self) -> Result<(), HRESULT> { let mut fence_value = self.fence_value; let mut frame_index = self.frame_index; wait_for_previous_frame( &self.swap_chain, &self.command_queue, &self.fence, self.fence_event, &mut fence_value, &mut frame_index, )?; self.fence_value = fence_value; self.frame_index = frame_index; Ok(()) } } // WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE. // This is code implemented as such for simplicity. The D3D12HelloFrameBuffering // sample illustrates how to use fences for efficient resource usage and to // maximize GPU utilization. fn wait_for_previous_frame( swap_chain: &IDXGISwapChain3, command_queue: &ID3D12CommandQueue, fence: &ID3D12Fence, event: HANDLE, fence_value: &mut u64, frame_index: &mut u32, ) -> Result<(), HRESULT> { // Signal and increment the fence value. let old_fence_value = *fence_value; command_queue.signal(fence, old_fence_value)?; *fence_value += 1; // Wait until the previous frame is finished. fence.wait_infinite(old_fence_value, event)?; *frame_index = swap_chain.get_current_back_buffer_index(); Ok(()) }
new
identifier_name
model.rs
#![allow(unused_unsafe)] use crate::com::*; use crate::consts::*; use crate::texture::*; use raw_window_handle::HasRawWindowHandle; use winapi::_core::f32::consts::PI; use winapi::_core::mem; use winapi::shared::basetsd::UINT16; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::HANDLE; use winapi::shared::windef::HWND; use winapi::shared::winerror::HRESULT; use winapi::vc::limits::UINT_MAX; use winit::platform::windows::*; use winit::window::Window; struct ArrayIterator3<T> { item: [T; 3], index: usize, } impl<T: Copy> ArrayIterator3<T> { pub fn new(item: [T; 3]) -> ArrayIterator3<T> { ArrayIterator3 { item: item, index: 0, } } } impl<T: Copy> Iterator for ArrayIterator3<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { match self.index < self.item.len() { true => { let rc = self.item[self.index]; self.index += 1; Some(rc) } false => None, } } } #[allow(dead_code)] pub struct DxModel { // Window aspect_ratio: f32, // D3D12 Targets device: ComRc<ID3D12Device>, command_queue: ComRc<ID3D12CommandQueue>, swap_chain: ComRc<IDXGISwapChain3>, dc_dev: ComRc<IDCompositionDevice>, dc_target: ComRc<IDCompositionTarget>, dc_visual: ComRc<IDCompositionVisual>, frame_index: u32, rtv_heap: ComRc<ID3D12DescriptorHeap>, srv_heap: ComRc<ID3D12DescriptorHeap>, rtv_descriptor_size: u32, render_targets: Vec<ComRc<ID3D12Resource>>, command_allocator: ComRc<ID3D12CommandAllocator>, // D3D12 Assets root_signature: ComRc<ID3D12RootSignature>, pipeline_state: ComRc<ID3D12PipelineState>, command_list: ComRc<ID3D12GraphicsCommandList>, // App resources. vertex_buffer: ComRc<ID3D12Resource>, vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW, index_buffer: ComRc<ID3D12Resource>, index_buffer_view: D3D12_INDEX_BUFFER_VIEW, texture: ComRc<ID3D12Resource>, // Synchronization objects. fence: ComRc<ID3D12Fence>, fence_value: u64, fence_event: HANDLE, // Pipeline objects. rotation_radians: f32, viewport: D3D12_VIEWPORT, scissor_rect: D3D12_RECT, } impl DxModel { pub fn new(window: &Window) -> Result<DxModel, HRESULT> { // window params let size = window.inner_size(); println!("inner_size={:?}", size); let hwnd = window.raw_window_handle(); let aspect_ratio = (size.width as f32) / (size.height as f32); let viewport = D3D12_VIEWPORT { Width: size.width as _, Height: size.height as _, MaxDepth: 1.0_f32, ..unsafe { mem::zeroed() } }; let scissor_rect = D3D12_RECT { right: size.width as _, bottom: size.height as _, ..unsafe { mem::zeroed() } }; // Enable the D3D12 debug layer. #[cfg(build = "debug")] { let debugController = d3d12_get_debug_interface::<ID3D12Debug>()?; unsafe { debugController.EnableDebugLayer() } } let factory = create_dxgi_factory1::<IDXGIFactory4>()?; // d3d12デバイスの作成 // ハードウェアデバイスが取得できなければ // WARPデバイスを取得する let device = factory.d3d12_create_best_device()?; // コマンドキューの作成 let command_queue = { let desc = D3D12_COMMAND_QUEUE_DESC { Flags: D3D12_COMMAND_QUEUE_FLAG_NONE, Type: D3D12_COMMAND_LIST_TYPE_DIRECT, NodeMask: 0, Priority: 0, }; device.create_command_queue::<ID3D12CommandQueue>(&desc)? }; // swap chainの作成 let swap_chain = { let desc = DXGI_SWAP_CHAIN_DESC1 { BufferCount: FRAME_COUNT, Width: size.width, Height: size.height, Format: DXGI_FORMAT_R8G8B8A8_UNORM, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, AlphaMode: DXGI_ALPHA_MODE_PREMULTIPLIED, Flags: 0, Scaling: 0, Stereo: 0, }; factory .create_swap_chain_for_composition(&command_queue, &desc)? .query_interface::<IDXGISwapChain3>()? }; // DirectComposition 設定 let dc_dev = dcomp_create_device::<IDCompositionDevice>(None)?; let dc_target = dc_dev.create_target_for_hwnd(hwnd, true)?; let dc_visual = dc_dev.create_visual()?; dc_visual.set_content(&swap_chain)?; dc_target.set_root(&dc_visual)?; dc_dev.commit()?; // このサンプルはフルスクリーンへの遷移をサポートしません。 factory.make_window_association(hwnd, DXGI_MWA_NO_ALT_ENTER)?; let mut frame_index = swap_chain.get_current_back_buffer_index(); // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. let rtv_heap = { let desc = D3D12_DESCRIPTOR_HEAP_DESC { NumDescriptors: FRAME_COUNT, Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0, }; device.create_descriptor_heap::<ID3D12DescriptorHeap>(&desc)? }; // Describe and create a shader resource view (SRV) heap for the texture. let srv_heap = { let desc = D3D12_DESCRIPTOR_HEAP_DESC { NumDescriptors: 1, Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }; device.create_descriptor_heap::<ID3D12DescriptorHeap>(&desc)? }; let rtv_descriptor_size = device.get_descriptor_handle_increment_size(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); // フレームバッファの作成 let render_targets = { let mut rtv_handle = rtv_heap.get_cpu_descriptor_handle_for_heap_start(); let mut targets: Vec<ComRc<ID3D12Resource>> = Vec::with_capacity(FRAME_COUNT as usize); for n in 0..FRAME_COUNT { let target = swap_chain.get_buffer::<ID3D12Resource>(n)?; device.create_render_target_view(&target, None, rtv_handle); rtv_handle.offset(1, rtv_descriptor_size); targets.push(target); } targets }; // コマンドアロケータ let command_allocator = device.create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; //------------------------------------------------------------------ // LoadAssets(d3d12の描画初期化) //------------------------------------------------------------------ // Create the root signature. let root_signature = { let ranges = { let range = D3D12_DESCRIPTOR_RANGE::new(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); [range] }; let root_parameters = { let a = D3D12_ROOT_PARAMETER::new_constants(1, 0, 0, D3D12_SHADER_VISIBILITY_VERTEX); let b = D3D12_ROOT_PARAMETER::new_descriptor_table( &ranges, D3D12_SHADER_VISIBILITY_PIXEL, ); [a, b] }; let samplers = unsafe { let mut sampler = mem::zeroed::<D3D12_STATIC_SAMPLER_DESC>(); sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.MipLODBias = 0.0; sampler.MaxAnisotropy = 0; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; sampler.MinLOD = 0.0; sampler.MaxLOD = D3D12_FLOAT32_MAX; sampler.ShaderRegister = 0; sampler.RegisterSpace = 0; sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; [sampler] }; let desc = D3D12_ROOT_SIGNATURE_DESC::new( &root_parameters, &samplers, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, ); let (signature, _error) = d3d12_serialize_root_signature(&desc, D3D_ROOT_SIGNATURE_VERSION_1)?; device.create_root_signature::<ID3D12RootSignature>( 0, signature.get_buffer_pointer(), signature.get_buffer_size(), )? }; // Create the pipeline state, which includes compiling and loading shaders. let pipeline_state = { let flags: u32 = { #[cfg(debug)] { D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION } #[cfg(not(debug))] { 0 } }; let file = "resources\\shaders.hlsl"; let (vertex_shader, _) = d3d_compile_from_file(file, None, None, "VSMain", "vs_5_0", flags, 0)?; let (pixel_shader, _) = d3d_compile_from_file(file, None, None, "PSMain", "ps_5_0", flags, 0)?; // Define the vertex input layout. let input_element_descs = { let a = D3D12_INPUT_ELEMENT_DESC::new( *t::POSITION, 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0, ); let b = D3D12_INPUT_ELEMENT_DESC::new( *t::TEXCOORD, 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0, ); [a, b] }; let alpha_blend = { let mut desc: D3D12_BLEND_DESC = unsafe { mem::zeroed() }; desc.AlphaToCoverageEnable = FALSE; desc.IndependentBlendEnable = FALSE; desc.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { BlendEnable: TRUE, LogicOpEnable: FALSE, SrcBlend: D3D12_BLEND_ONE, DestBlend: D3D12_BLEND_INV_SRC_ALPHA, BlendOp: D3D12_BLEND_OP_ADD, SrcBlendAlpha: D3D12_BLEND_ONE, DestBlendAlpha: D3D12_BLEND_INV_SRC_ALPHA, BlendOpAlpha: D3D12_BLEND_OP_ADD, LogicOp: D3D12_LOGIC_OP_CLEAR, RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL as u8, }; desc }; // Describe and create the graphics pipeline state object (PSO). let pso_desc = { let mut desc: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { mem::zeroed() }; desc.InputLayout = input_element_descs.layout(); desc.pRootSignature = to_mut_ptr(root_signature.as_ptr()); desc.VS = D3D12_SHADER_BYTECODE::new(&vertex_shader); desc.PS = D3D12_SHADER_BYTECODE::new(&pixel_shader); desc.RasterizerState = D3D12_RASTERIZER_DESC::default(); desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; desc.BlendState = alpha_blend; desc.DepthStencilState.DepthEnable = FALSE; desc.DepthStencilState.StencilEnable = FALSE; desc.SampleMask = UINT_MAX; desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; desc.NumRenderTargets = 1; desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc }; device.create_graphics_pipeline_state(&pso_desc)? }; // Create the command list. let command_list = device.create_command_list::<ID3D12GraphicsCommandList>( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, &command_allocator, &pipeline_state, )?; // Create the vertex buffer. let (vertex_buffer, vertex_buffer_view) = { // Define the geometry for a circle. let items = (-1..CIRCLE_SEGMENTS) .map(|i| match i { -1 => { let pos = [0_f32, 0_f32, 0_f32]; let uv = [0.5_f32, 0.5_f32]; Vertex::new(pos, uv) } _ => { let theta = PI * 2.0_f32 * (i as f32) / (CIRCLE_SEGMENTS as f32); let x = theta.sin(); let y = theta.cos(); let pos = [x, y * aspect_ratio, 0.0_f32]; let uv = [x * 0.5_f32 + 0.5_f32, y * 0.5_f32 + 0.5_f32]; Vertex::new(pos, uv) } }) .collect::<Vec<_>>(); println!("{:?}", items); let size_of = mem::size_of::<Vertex>(); let size = size_of * items.len(); let p = items.as_ptr(); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(size as u64); let buffer = device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )?; // Copy the triangle data to the vertex buffer. let read_range = D3D12_RANGE::new(0, 0); // We do not intend to read from this resource on the CPU. buffer.map(0, Some(&read_range))?.memcpy(p, size); // Initialize the vertex buffer view. let view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: buffer.get_gpu_virtual_address(), SizeInBytes: size as u32, StrideInBytes: size_of as u32, }; (buffer, view) }; // Create the index buffer let (index_buffer, index_buffer_view) = { // Define the geometry for a circle. let items = (0..CIRCLE_SEGMENTS) .map(|i| { let a = 0 as UINT16; let b = (1 + i) as UINT16; let c = (2 + i) as UINT16; [a, b, c] }) .flat_map(|a| ArrayIterator3::new(a)) .collect::<Vec<_>>(); let size_of = mem::size_of::<UINT16>(); let size = size_of * items.len(); let p = items.as_ptr(); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(size as u64); let buffer = device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )?; // Copy the index data to the index buffer. let read_range = D3D12_RANGE::new(0, 0); // We do not intend to read from this resource on the CPU. buffer.map(0, Some(&read_range))?.memcpy(p, size); // Intialize the index buffer view let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: buffer.get_gpu_virtual_address(), SizeInBytes: size as u32, Format: DXGI_FORMAT_R16_UINT, }; (buffer, view) }; // Create the texture. // Note: ComPtr's are CPU objects but this resource needs to stay in scope until // the command list that references it has finished executing on the GPU. // We will flush the GPU at the end of this method to ensure the resource is not // prematurely destroyed. // texture_upload_heapの開放タイミングがGPUへのフラッシュ後になるように // 所有権を関数スコープに追い出しておく let (_texture_upload_heap, texture) = { // Describe and create a Texture2D. let texture_desc = D3D12_RESOURCE_DESC::new( D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE, ); let texture = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_DEFAULT); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &texture_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, )? }; let upload_buffer_size = texture.get_required_intermediate_size(0, 1)?; // Create the GPU upload buffer. let texture_upload_heap = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(upload_buffer_size); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )? }; // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. let texture_bytes = generate_texture_data(); let texture_data = { let ptr = texture_bytes.as_ptr(); let row_pitch = ((TEXTURE_WIDTH as usize) * mem::size_of::<u32>()) as isize; let slice_pitch = row_pitch * (TEXTURE_HEIGHT as isize); [D3D12_SUBRESOURCE_DATA { pData: ptr as _, RowPitch: row_pitch, SlicePitch: slice_pitch, }] }; let _ = command_list.update_subresources_as_heap( &texture, &texture_upload_heap, 0, &texture_data, )?; { let barrier = D3D12_RESOURCE_BARRIER::transition( &texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, ); command_list.resource_barrier(1, &barrier); } // Describe and create a SRV for the texture. { let desc = unsafe { let mut desc = mem::zeroed::<D3D12_SHADER_RESOURCE_VIEW_DESC>(); desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; desc.Format = texture_desc.Format; desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; { let mut t = desc.u.Texture2D_mut(); t.MipLevels = 1; } desc }; device.create_shader_resource_view( &texture, &desc, srv_heap.get_cpu_descriptor_handle_for_heap_start(), ); } (texture_upload_heap, texture) }; // Close the command list and execute it to begin the initial GPU setup. { command_list.close()?; let a: &ID3D12GraphicsCommandList = &command_list; command_queue.execute_command_lists(&[a]); } // Create synchronization objects and wait until assets have been uploaded to the GPU. let (fence, fence_value, fence_event) = { let fence = device.create_fence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE)?; let mut fence_value = 1_u64; // Create an event handle to use for frame synchronization. let fence_event = create_event(None, false, false, None)?; // Wait for the command list to execute; we are reusing the same command // list in our main loop but for now, we just want to wait for setup to // complete before continuing. wait_for_previous_frame( &swap_chain, &command_queue, &fence, fence_event, &mut fence_value, &mut frame_index, )?; (fence, fence_value, fence_event) }; //------------------------------------------------------------------ // result //------------------------------------------------------------------ Ok(DxModel { aspect_ratio: aspect_ratio, device: device, command_queue: command_queue, swap_chain: swap_chain, dc_dev: dc_dev, dc_target: dc_target, dc_visual: dc_visual, frame_index: frame_index, rtv_heap: rtv_heap, srv_heap: srv_heap, rtv_descriptor_size: rtv_descriptor_size, render_targets: render_targets, command_allocator: command_allocator, root_signature: root_signature, pipeline_state: pipeline_state, command_list: command_list, vertex_buffer: vertex_buffer, vertex_buffer_view: vertex_buffer_view, index_buffer: index_buffer, index_buffer_view: index_buffer_view, texture: texture, fence: fence, fence_value: fence_value, fence_event: fence_event, rotation_radians: 0_f32, viewport: viewport, scissor_rect: scissor_rect, }) } pub fn render(&mut self) -> Result<(), HRESULT> { { self.populate_command_list()?; } { let command_queue = &self.command_queue; let command_list = &self.command_list; let swap_chain = &self.swap_chain; command_queue.execute_command_lists(&[command_list]); swap_chain.present(1, 0)?; } { self.wait_for_previous_frame()?; } Ok(()) } /// 描画コマンドリストを構築する fn populate_command_list(&mut self) -> Result<(), HRESULT> { let command_allocator = self.command_allocator.as_ref(); let command_list = self.command_list.as_ref(); let pipeline_state = self.pipeline_state.as_ref(); let root_signature = self.root_signature.as_ref(); let srv_heap = self.srv_heap.as_ref(); let rtv_heap = self.rtv
&mut fence_value, &mut frame_index, )?; self.fence_value = fence_value; self.frame_index = frame_index; Ok(()) } } // WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE. // This is code implemented as such for simplicity. The D3D12HelloFrameBuffering // sample illustrates how to use fences for efficient resource usage and to // maximize GPU utilization. fn wait_for_previous_frame( swap_chain: &IDXGISwapChain3, command_queue: &ID3D12CommandQueue, fence: &ID3D12Fence, event: HANDLE, fence_value: &mut u64, frame_index: &mut u32, ) -> Result<(), HRESULT> { // Signal and increment the fence value. let old_fence_value = *fence_value; command_queue.signal(fence, old_fence_value)?; *fence_value += 1; // Wait until the previous frame is finished. fence.wait_infinite(old_fence_value, event)?; *frame_index = swap_chain.get_current_back_buffer_index(); Ok(()) }
_heap.as_ref(); let rtv_descriptor_size = self.rtv_descriptor_size; let viewport = &self.viewport; let scissor_rect = &self.scissor_rect; let render_targets = self.render_targets.as_slice(); let frame_index = self.frame_index as usize; let vertex_buffer_view = &self.vertex_buffer_view; let index_buffer_view = &self.index_buffer_view; // Command list allocators can only be reset when the associated // command lists have finished execution on the GPU; apps should use // fences to determine GPU execution progress. command_allocator.reset()?; // However, when ExecuteCommandList() is called on a particular command // list, that command list can then be reset at any time and must be before // re-recording. command_list.reset(command_allocator, pipeline_state)?; // Set necessary state. command_list.set_graphics_root_signature(root_signature); let pp_heaps = [srv_heap]; command_list.set_descriptor_heaps(&pp_heaps); self.rotation_radians += 0.02_f32; let rotation_radians = self.rotation_radians; command_list.set_graphics_root_f32_constant(0, rotation_radians, 0); command_list.set_graphics_root_descriptor_table( 1, srv_heap.get_gpu_descriptor_handle_for_heap_start(), ); let viewports = [*viewport]; command_list.rs_set_viewports(&viewports); let scissor_rects = [*scissor_rect]; command_list.rs_set_scissor_rects(&scissor_rects); // Indicate that the back buffer will be used as a render target. { let barrier = D3D12_RESOURCE_BARRIER::transition( &render_targets[frame_index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET, ); command_list.resource_barrier(1, &barrier); } let mut rtv_handle = rtv_heap.get_cpu_descriptor_handle_for_heap_start(); rtv_handle.offset(frame_index as _, rtv_descriptor_size); let rtv_handles = [rtv_handle]; command_list.om_set_render_targets(&rtv_handles, false, None); // Record commands. let clear_color = [0_f32; 4]; let no_rects = []; command_list.clear_render_target_view(rtv_handle, &clear_color, &no_rects); command_list.ia_set_primitive_topology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); let vertex_buffer_views = [vertex_buffer_view.clone()]; command_list.ia_set_vertex_buffers(0, &vertex_buffer_views); command_list.ia_set_index_buffer(index_buffer_view); command_list.draw_indexed_instanced((CIRCLE_SEGMENTS * 3) as _, 1, 0, 0, 0); // Indicate that the back buffer will now be used to present. { let barrier = D3D12_RESOURCE_BARRIER::transition( &render_targets[frame_index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT, ); command_list.resource_barrier(1, &barrier); } command_list.close()?; Ok(()) } fn wait_for_previous_frame(&mut self) -> Result<(), HRESULT> { let mut fence_value = self.fence_value; let mut frame_index = self.frame_index; wait_for_previous_frame( &self.swap_chain, &self.command_queue, &self.fence, self.fence_event,
identifier_body
model.rs
#![allow(unused_unsafe)] use crate::com::*; use crate::consts::*; use crate::texture::*; use raw_window_handle::HasRawWindowHandle; use winapi::_core::f32::consts::PI; use winapi::_core::mem; use winapi::shared::basetsd::UINT16; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::HANDLE; use winapi::shared::windef::HWND; use winapi::shared::winerror::HRESULT; use winapi::vc::limits::UINT_MAX; use winit::platform::windows::*; use winit::window::Window; struct ArrayIterator3<T> { item: [T; 3], index: usize, } impl<T: Copy> ArrayIterator3<T> { pub fn new(item: [T; 3]) -> ArrayIterator3<T> { ArrayIterator3 { item: item, index: 0, } } } impl<T: Copy> Iterator for ArrayIterator3<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { match self.index < self.item.len() { true => { let rc = self.item[self.index]; self.index += 1; Some(rc) } false => None, } } } #[allow(dead_code)] pub struct DxModel { // Window aspect_ratio: f32, // D3D12 Targets device: ComRc<ID3D12Device>, command_queue: ComRc<ID3D12CommandQueue>, swap_chain: ComRc<IDXGISwapChain3>, dc_dev: ComRc<IDCompositionDevice>, dc_target: ComRc<IDCompositionTarget>, dc_visual: ComRc<IDCompositionVisual>, frame_index: u32, rtv_heap: ComRc<ID3D12DescriptorHeap>, srv_heap: ComRc<ID3D12DescriptorHeap>, rtv_descriptor_size: u32, render_targets: Vec<ComRc<ID3D12Resource>>, command_allocator: ComRc<ID3D12CommandAllocator>, // D3D12 Assets root_signature: ComRc<ID3D12RootSignature>, pipeline_state: ComRc<ID3D12PipelineState>, command_list: ComRc<ID3D12GraphicsCommandList>, // App resources. vertex_buffer: ComRc<ID3D12Resource>, vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW, index_buffer: ComRc<ID3D12Resource>, index_buffer_view: D3D12_INDEX_BUFFER_VIEW, texture: ComRc<ID3D12Resource>, // Synchronization objects. fence: ComRc<ID3D12Fence>, fence_value: u64, fence_event: HANDLE, // Pipeline objects. rotation_radians: f32, viewport: D3D12_VIEWPORT, scissor_rect: D3D12_RECT, } impl DxModel { pub fn new(window: &Window) -> Result<DxModel, HRESULT> { // window params let size = window.inner_size(); println!("inner_size={:?}", size); let hwnd = window.raw_window_handle(); let aspect_ratio = (size.width as f32) / (size.height as f32); let viewport = D3D12_VIEWPORT { Width: size.width as _, Height: size.height as _, MaxDepth: 1.0_f32, ..unsafe { mem::zeroed() } }; let scissor_rect = D3D12_RECT { right: size.width as _, bottom: size.height as _, ..unsafe { mem::zeroed() } }; // Enable the D3D12 debug layer. #[cfg(build = "debug")] { let debugController = d3d12_get_debug_interface::<ID3D12Debug>()?; unsafe { debugController.EnableDebugLayer() } } let factory = create_dxgi_factory1::<IDXGIFactory4>()?; // d3d12デバイスの作成 // ハードウェアデバイスが取得できなければ // WARPデバイスを取得する let device = factory.d3d12_create_best_device()?; // コマンドキューの作成 let command_queue = { let desc = D3D12_COMMAND_QUEUE_DESC { Flags: D3D12_COMMAND_QUEUE_FLAG_NONE, Type: D3D12_COMMAND_LIST_TYPE_DIRECT, NodeMask: 0, Priority: 0, }; device.create_command_queue::<ID3D12CommandQueue>(&desc)? }; // swap chainの作成 let swap_chain = { let desc = DXGI_SWAP_CHAIN_DESC1 { BufferCount: FRAME_COUNT, Width: size.width, Height: size.height, Format: DXGI_FORMAT_R8G8B8A8_UNORM, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, AlphaMode: DXGI_ALPHA_MODE_PREMULTIPLIED, Flags: 0, Scaling: 0, Stereo: 0, }; factory .create_swap_chain_for_composition(&command_queue, &desc)? .query_interface::<IDXGISwapChain3>()? }; // DirectComposition 設定 let dc_dev = dcomp_create_device::<IDCompositionDevice>(None)?; let dc_target = dc_dev.create_target_for_hwnd(hwnd, true)?; let dc_visual = dc_dev.create_visual()?; dc_visual.set_content(&swap_chain)?; dc_target.set_root(&dc_visual)?; dc_dev.commit()?; // このサンプルはフルスクリーンへの遷移をサポートしません。 factory.make_window_association(hwnd, DXGI_MWA_NO_ALT_ENTER)?; let mut frame_index = swap_chain.get_current_back_buffer_index(); // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. let rtv_heap = { let desc = D3D12_DESCRIPTOR_HEAP_DESC { NumDescriptors: FRAME_COUNT, Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0, }; device.create_descriptor_heap::<ID3D12DescriptorHeap>(&desc)? }; // Describe and create a shader resource view (SRV) heap for the texture. let srv_heap = { let desc = D3D12_DESCRIPTOR_HEAP_DESC { NumDescriptors: 1, Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }; device.create_descriptor_heap::<ID3D12DescriptorHeap>(&desc)? }; let rtv_descriptor_size = device.get_descriptor_handle_increment_size(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); // フレームバッファの作成 let render_targets = { let mut rtv_handle = rtv_heap.get_cpu_descriptor_handle_for_heap_start(); let mut targets: Vec<ComRc<ID3D12Resource>> = Vec::with_capacity(FRAME_COUNT as usize); for n in 0..FRAME_COUNT { let target = swap_chain.get_buffer::<ID3D12Resource>(n)?; device.create_render_target_view(&target, None, rtv_handle); rtv_handle.offset(1, rtv_descriptor_size); targets.push(target); } targets }; // コマンドアロケータ let command_allocator = device.create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; //------------------------------------------------------------------ // LoadAssets(d3d12の描画初期化) //------------------------------------------------------------------ // Create the root signature. let root_signature = { let ranges = { let range = D3D12_DESCRIPTOR_RANGE::new(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); [range] }; let root_parameters = { let a = D3D12_ROOT_PARAMETER::new_constants(1, 0, 0, D3D12_SHADER_VISIBILITY_VERTEX); let b = D3D12_ROOT_PARAMETER::new_descriptor_table( &ranges, D3D12_SHADER_VISIBILITY_PIXEL, ); [a, b] }; let samplers = unsafe { let mut sampler = mem::zeroed::<D3D12_STATIC_SAMPLER_DESC>(); sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; sampler.MipLODBias = 0.0; sampler.MaxAnisotropy = 0; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; sampler.MinLOD = 0.0; sampler.MaxLOD = D3D12_FLOAT32_MAX; sampler.ShaderRegister = 0; sampler.RegisterSpace = 0; sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; [sampler] }; let desc = D3D12_ROOT_SIGNATURE_DESC::new( &root_parameters, &samplers, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, ); let (signature, _error) = d3d12_serialize_root_signature(&desc, D3D_ROOT_SIGNATURE_VERSION_1)?; device.create_root_signature::<ID3D12RootSignature>( 0, signature.get_buffer_pointer(), signature.get_buffer_size(), )? }; // Create the pipeline state, which includes compiling and loading shaders. let pipeline_state = { let flags: u32 = { #[cfg(debug)] { D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION } #[cfg(not(debug))] { 0 } }; let file = "resources\\shaders.hlsl"; let (vertex_shader, _) = d3d_compile_from_file(file, None, None, "VSMain", "vs_5_0", flags, 0)?; let (pixel_shader, _) = d3d_compile_from_file(file, None, None, "PSMain", "ps_5_0", flags, 0)?; // Define the vertex input layout. let input_element_descs = { let a = D3D12_INPUT_ELEMENT_DESC::new( *t::POSITION, 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0, ); let b = D3D12_INPUT_ELEMENT_DESC::new( *t::TEXCOORD, 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0, ); [a, b] }; let alpha_blend = { let mut desc: D3D12_BLEND_DESC = unsafe { mem::zeroed() }; desc.AlphaToCoverageEnable = FALSE; desc.IndependentBlendEnable = FALSE; desc.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { BlendEnable: TRUE, LogicOpEnable: FALSE, SrcBlend: D3D12_BLEND_ONE, DestBlend: D3D12_BLEND_INV_SRC_ALPHA, BlendOp: D3D12_BLEND_OP_ADD, SrcBlendAlpha: D3D12_BLEND_ONE, DestBlendAlpha: D3D12_BLEND_INV_SRC_ALPHA, BlendOpAlpha: D3D12_BLEND_OP_ADD, LogicOp: D3D12_LOGIC_OP_CLEAR, RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL as u8, }; desc }; // Describe and create the graphics pipeline state object (PSO). let pso_desc = { let mut desc: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { mem::zeroed() }; desc.InputLayout = input_element_descs.layout(); desc.pRootSignature = to_mut_ptr(root_signature.as_ptr()); desc.VS = D3D12_SHADER_BYTECODE::new(&vertex_shader); desc.PS = D3D12_SHADER_BYTECODE::new(&pixel_shader); desc.RasterizerState = D3D12_RASTERIZER_DESC::default(); desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; desc.BlendState = alpha_blend; desc.DepthStencilState.DepthEnable = FALSE; desc.DepthStencilState.StencilEnable = FALSE; desc.SampleMask = UINT_MAX; desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; desc.NumRenderTargets = 1; desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc }; device.create_graphics_pipeline_state(&pso_desc)? }; // Create the command list. let command_list = device.create_command_list::<ID3D12GraphicsCommandList>( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, &command_allocator, &pipeline_state, )?; // Create the vertex buffer. let (vertex_buffer, vertex_buffer_view) = { // Define the geometry for a circle. let items = (-1..CIRCLE_SEGMENTS) .map(|i| match i { -1 => { let pos = [0_f32, 0_f32, 0_f32]; let uv = [0.5_f32, 0.5_f32]; Vertex::new(pos, uv) } _ => { let theta = PI * 2.0_f32 * (i as f32) / (CIRCLE_SEGMENTS as f32); let x = theta.sin(); let y = theta.cos(); let pos = [x, y * aspect_ratio, 0.0_f32]; let uv = [x * 0.5_f32 + 0.5_f32, y * 0.5_f32 + 0.5_f32]; Vertex::new(pos, uv) } }) .collect::<Vec<_>>(); println!("{:?}", items); let size_of = mem::size_of::<Vertex>(); let size = size_of * items.len(); let p = items.as_ptr(); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(size as u64); let buffer = device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )?; // Copy the triangle data to the vertex buffer. let read_range = D3D12_RANGE::new(0, 0); // We do not intend to read from this resource on the CPU. buffer.map(0, Some(&read_range))?.memcpy(p, size); // Initialize the vertex buffer view. let view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: buffer.get_gpu_virtual_address(), SizeInBytes: size as u32, StrideInBytes: size_of as u32, }; (buffer, view) }; // Create the index buffer let (index_buffer, index_buffer_view) = { // Define the geometry for a circle. let items = (0..CIRCLE_SEGMENTS) .map(|i| { let a = 0 as UINT16; let b = (1 + i) as UINT16; let c = (2 + i) as UINT16; [a, b, c] }) .flat_map(|a| ArrayIterator3::new(a)) .collect::<Vec<_>>(); let size_of = mem::size_of::<UINT16>(); let size = size_of * items.len(); let p = items.as_ptr(); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(size as u64); let buffer = device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )?; // Copy the index data to the index buffer. let read_range = D3D12_RANGE::new(0, 0); // We do not intend to read from this resource on the CPU. buffer.map(0, Some(&read_range))?.memcpy(p, size); // Intialize the index buffer view let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: buffer.get_gpu_virtual_address(), SizeInBytes: size as u32, Format: DXGI_FORMAT_R16_UINT, }; (buffer, view) }; // Create the texture. // Note: ComPtr's are CPU objects but this resource needs to stay in scope until // the command list that references it has finished executing on the GPU. // We will flush the GPU at the end of this method to ensure the resource is not // prematurely destroyed. // texture_upload_heapの開放タイミングがGPUへのフラッシュ後になるように // 所有権を関数スコープに追い出しておく let (_texture_upload_heap, texture) = { // Describe and create a Texture2D. let texture_desc = D3D12_RESOURCE_DESC::new( D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE, ); let texture = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_DEFAULT); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &texture_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, )? }; let upload_buffer_size = texture.get_required_intermediate_size(0, 1)?; // Create the GPU upload buffer. let texture_upload_heap = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_UPLOAD); let desc = D3D12_RESOURCE_DESC::buffer(upload_buffer_size); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, )? }; // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. let texture_bytes = generate_texture_data(); let texture_data = { let ptr = texture_bytes.as_ptr(); let row_pitch = ((TEXTURE_WIDTH as usize) * mem::size_of::<u32>()) as isize; let slice_pitch = row_pitch * (TEXTURE_HEIGHT as isize); [D3D12_SUBRESOURCE_DATA { pData: ptr as _, RowPitch: row_pitch, SlicePitch: slice_pitch, }] }; let _ = command_list.update_subresources_as_heap( &texture, &texture_upload_heap, 0, &texture_data, )?; { let barrier = D3D12_RESOURCE_BARRIER::transition( &texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, ); command_list.resource_barrier(1, &barrier); } // Describe and create a SRV for the texture. { let desc = unsafe { let mut desc = mem::zeroed::<D3D12_SHADER_RESOURCE_VIEW_DESC>(); desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; desc.Format = texture_desc.Format; desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; { let mut t = desc.u.Texture2D_mut(); t.MipLevels = 1; } desc }; device.create_shader_resource_view( &texture, &desc, srv_heap.get_cpu_descriptor_handle_for_heap_start(), ); } (texture_upload_heap, texture) }; // Close the command list and execute it to begin the initial GPU setup. { command_list.close()?; let a: &ID3D12GraphicsCommandList = &command_list; command_queue.execute_command_lists(&[a]); } // Create synchronization objects and wait until assets have been uploaded to the GPU. let (fence, fence_value, fence_event) = { let fence = device.create_fence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE)?; let mut fence_value = 1_u64; // Create an event handle to use for frame synchronization. let fence_event = create_event(None, false, false, None)?; // Wait for the command list to execute; we are reusing the same command // list in our main loop but for now, we just want to wait for setup to // complete before continuing. wait_for_previous_frame( &swap_chain, &command_queue, &fence, fence_event, &mut fence_value, &mut frame_index, )?; (fence, fence_value, fence_event) }; //------------------------------------------------------------------ // result //------------------------------------------------------------------ Ok(DxModel { aspect_ratio: aspect_ratio, device: device, command_queue: command_queue, swap_chain: swap_chain, dc_dev: dc_dev, dc_target: dc_target, dc_visual: dc_visual, frame_index: frame_index, rtv_heap: rtv_heap, srv_heap: srv_heap, rtv_descriptor_size: rtv_descriptor_size, render_targets: render_targets, command_allocator: command_allocator, root_signature: root_signature, pipeline_state: pipeline_state, command_list: command_list, vertex_buffer: vertex_buffer, vertex_buffer_view: vertex_buffer_view, index_buffer: index_buffer, index_buffer_view: index_buffer_view, texture: texture, fence: fence, fence_value: fence_value, fence_event: fence_event, rotation_radians: 0_f32, viewport: viewport, scissor_rect: scissor_rect, }) } pub fn render(&mut self) -> Result<(), HRESULT> { { self.populate_command_list()?; } { let command_queue = &self.command_queue; let command_list = &self.command_list; let swap_chain = &self.swap_chain; command_queue.execute_command_lists(&[command_list]); swap_chain.present(1, 0)?; } { self.wait_for_previous_frame()?; } Ok(()) } /// 描画コマンドリストを構築する fn populate_command_list(&mut self) -> Result<(), HRESULT> { let command_allocator = self.command_allocator.as_ref(); let command_list = self.command_list.as_ref(); let pipeline_state = self.pipeline_state.as_ref(); let root_signature = self.root_signature.as_ref(); let srv_heap = self.srv_heap.as_ref(); let rtv_heap = self.rtv_heap.as_ref(); let rtv_descriptor_size = self.rtv_descriptor_size; let viewport = &self.viewport; let scissor_rect = &self.scissor_rect; let render_targets = self.render_targets.as_slice(); let frame_index = self.frame_index as usize; let vertex_buffer_view = &self.vertex_buffer_view; let index_buffer_view = &self.index_buffer_view; // Command list allocators can only be reset when the associated // command lists have finished execution on the GPU; apps should use // fences to determine GPU execution progress. command_allocator.reset()?; // However, when ExecuteCommandList() is called on a particular command // list, that command list can then be reset at any time and must be before // re-recording. command_list.reset(command_allocator, pipeline_state)?; // Set necessary state. command_list.set_graphics_root_signature(root_signature); let pp_heaps = [srv_heap]; command_list.set_descriptor_heaps(&pp_heaps); self.rotation_radians += 0.02_f32; let rotation_radians = self.rotation_radians; command_list.set_graphics_root_f32_constant(0, rotation_radians, 0); command_list.set_graphics_root_descriptor_table( 1, srv_heap.get_gpu_descriptor_handle_for_heap_start(), ); let viewports = [*viewport]; command_list.rs_set_viewports(&viewports); let scissor_rects = [*scissor_rect]; command_list.rs_set_scissor_rects(&scissor_rects); // Indicate that the back buffer will be used as a render target. { let barrier = D3D12_RESOURCE_BARRIER::transition( &render_targets[frame_index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET, ); command_list.resource_barrier(1, &barrier); } let mut rtv_handle = rtv_heap.get_cpu_descriptor_handle_for_heap_start(); rtv_handle.offset(frame_index as _, rtv_descriptor_size); let rtv_handles = [rtv_handle]; command_list.om_set_render_targets(&rtv_handles, false, None); // Record commands. let clear_color = [0_f32; 4]; let no_rects = []; command_list.clear_render_target_view(rtv_handle, &clear_color, &no_rects); command_list.ia_set_primitive_topology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); let vertex_buffer_views = [vertex_buffer_view.clone()]; command_list.ia_set_vertex_buffers(0, &vertex_buffer_views); command_list.ia_set_index_buffer(index_buffer_view); command_list.draw_indexed_instanced((CIRCLE_SEGMENTS * 3) as _, 1, 0, 0, 0); // Indicate that the back buffer will now be used to present. { let barrier = D3D12_RESOURCE_BARRIER::transition( &render_targets[frame_index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT, ); command_list.resource_barrier(1, &barrier); } command_list.close()?; Ok(()) } fn wait_for_previous_frame(&mut self) -> Result<(), HRESULT> { let mut fence_value = self.fence_value; let mut frame_index = self.frame_index; wait_for_previous_frame( &self.swap_chain, &self.command_queue, &self.fence, self.fence_event, &mut fence_value, &mut frame_index, )?; self.fence_value = fence_value; self.frame_index = frame_index;
// This is code implemented as such for simplicity. The D3D12HelloFrameBuffering // sample illustrates how to use fences for efficient resource usage and to // maximize GPU utilization. fn wait_for_previous_frame( swap_chain: &IDXGISwapChain3, command_queue: &ID3D12CommandQueue, fence: &ID3D12Fence, event: HANDLE, fence_value: &mut u64, frame_index: &mut u32, ) -> Result<(), HRESULT> { // Signal and increment the fence value. let old_fence_value = *fence_value; command_queue.signal(fence, old_fence_value)?; *fence_value += 1; // Wait until the previous frame is finished. fence.wait_infinite(old_fence_value, event)?; *frame_index = swap_chain.get_current_back_buffer_index(); Ok(()) }
Ok(()) } } // WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE.
random_line_split
art_tree.go
// Pacakge art provides a golang implementation of Adaptive Radix Trees package art import ( "bytes" _ "math" _ "os" ) type ArtTree struct { root *ArtNode size int64 } // Creates and returns a new Art Tree with a nil root and a size of 0. func NewArtTree() *ArtTree { return &ArtTree{root: nil, size: 0} } type Result struct { Key []byte Value interface{} } func (t *ArtTree) EachChanResult() chan Result { return t.EachChanResultFrom(t.root) } func (t *ArtTree) EachChanResultFrom(start *ArtNode) chan Result { outChan := make(chan Result) go func() { if start != nil { for n := range t.EachChanFrom(start) { if n.IsLeaf() { outChan <- Result{n.key, n.value} } } } close(outChan) }() return outChan } // Finds the starting node for a prefix search and returns an array of all the objects under it func (t *ArtTree) PrefixSearch(key []byte) []interface{} { ret := make([]interface{}, 0) for r := range t.PrefixSearchChan(key) { ret = append(ret, r.Value) } return ret } func (t *ArtTree) PrefixSearchChan(key []byte) chan Result { return t.EachChanResultFrom(t.searchHelper(t.root, key, 0)) } // Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) Search(key []byte) interface{} { key = ensureNullTerminatedKey(key) foundNode := t.searchHelper(t.root, key, 0) if foundNode != nil && foundNode.IsMatch(key) { return foundNode.value } return nil } // Recursive search helper function that traverses the tree. // Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) searchHelper(current *ArtNode, key []byte, depth int) *ArtNode { // While we have nodes to search if current != nil { maxKeyIndex := len(key) - 1 if depth > maxKeyIndex { return current } // Check if the current is a match (including prefix match) if current.IsLeaf() && len(current.key) >= len(key) && bytes.Equal(key, current.key[0:len(key)]) { return current } // Check if our key mismatches the current compressed path prefixMismatch := current.PrefixMismatch(key, depth) if prefixMismatch == current.prefixLen { // whole prefix matches depth += current.prefixLen if depth > maxKeyIndex { return current } } else if prefixMismatch == len(key)-depth { // consumed whole key return current } else { // mismatch return nil } // Find the next node at the specified index, and update depth. return t.searchHelper(*(current.FindChild(key[depth])), key, depth+1) } return nil } // Inserts the passed in value that is indexed by the passed in key into the ArtTree. func (t *ArtTree) Insert(key []byte, value interface{}) { key = ensureNullTerminatedKey(key) t.insertHelper(t.root, &t.root, key, value, 0) } // Recursive helper function that traverses the tree until an insertion point is found. // There are four methods of insertion: // // If the current node is null, a new node is created with the passed in key-value pair // and inserted at the current position. // // If the current node is a leaf node, it will expand to a new ArtNode of type NODE4 // to contain itself and a new leaf node containing the passed in key-value pair. // // If the current node's prefix differs from the key at a specified depth, // a new ArtNode of type NODE4 is created to contain the current node and the new leaf node // with an adjusted prefix to account for the mismatch. // // If there is no child at the specified key at the current depth of traversal, a new leaf node // is created and inserted at this position. func (t *ArtTree) insertHelper(current *ArtNode, currentRef **ArtNode, key []byte, value interface{}, depth int) { // @spec: Usually, the leaf can // simply be inserted into an existing inner node, after growing // it if necessary. if current == nil { *currentRef = NewLeafNode(key, value) t.size += 1 return } // @spec: If, because of lazy expansion, // an existing leaf is encountered, it is replaced by a new // inner node storing the existing and the new leaf if current.IsLeaf() { // TODO Determine if we should overwrite keys if they are attempted to overwritten. // Currently, we bail if the key matches. if current.IsMatch(key) { return } // Create a new Inner Node to contain the new Leaf and the current node. newNode4 := NewNode4() newLeafNode := NewLeafNode(key, value) // Determine the longest common prefix between our current node and the key limit := current.LongestCommonPrefix(newLeafNode, depth) newNode4.prefixLen = limit memcpy(newNode4.prefix, key[depth:], min(newNode4.prefixLen, MAX_PREFIX_LEN)) *currentRef = newNode4 // Add both children to the new Inner Node newNode4.AddChild(current.key[depth+newNode4.prefixLen], current) newNode4.AddChild(key[depth+newNode4.prefixLen], newLeafNode) t.size += 1 return } // @spec: Another special case occurs if the key of the new leaf // differs from a compressed path: A new inner node is created // above the current node and the compressed paths are adjusted accordingly. if current.prefixLen != 0 { mismatch := current.PrefixMismatch(key, depth) // If the key differs from the compressed path if mismatch != current.prefixLen { // Create a new Inner Node that will contain the current node // and the desired insertion key newNode4 := NewNode4() *currentRef = newNode4 newNode4.prefixLen = mismatch // Copy the mismatched prefix into the new inner node. memcpy(newNode4.prefix, current.prefix, mismatch) // Adjust prefixes so they fit underneath the new inner node if current.prefixLen < MAX_PREFIX_LEN { newNode4.AddChild(current.prefix[mismatch], current) current.prefixLen -= (mismatch + 1) memmove(current.prefix, current.prefix[mismatch+1:], min(current.prefixLen, MAX_PREFIX_LEN)) } else { current.prefixLen -= (mismatch + 1) minKey := current.Minimum().key newNode4.AddChild(minKey[depth+mismatch], current) memmove(current.prefix, minKey[depth+mismatch+1:], min(current.prefixLen, MAX_PREFIX_LEN)) } // Attach the desired insertion key newLeafNode := NewLeafNode(key, value) newNode4.AddChild(key[depth+mismatch], newLeafNode) t.size += 1 return } depth += current.prefixLen } // Find the next child next := current.FindChild(key[depth]) // If we found a child that matches the key at the current depth if *next != nil { // Recurse, and keep looking for an insertion point t.insertHelper(*next, next, key, value, depth+1) } else { // Otherwise, Add the child at the current position. current.AddChild(key[depth], NewLeafNode(key, value)) t.size += 1 } } // Removes the child that is accessed by the passed in key. func (t *ArtTree) Remove(key []byte) { key = ensureNullTerminatedKey(key) t.removeHelper(t.root, &t.root, key, 0) } // Recursive helper for Removing child nodes. // There are two methods for removal: // // If the current node is a leaf and matches the specified key, remove it. // // If the next child at the specifed key and depth matches, // the current node shall remove it accordingly. func (t *ArtTree) removeHelper(current *ArtNode, currentRef **ArtNode, key []byte, depth int) { // Bail early if we are at a nil node. if current == nil { return } // If the current node matches, remove it. if current.IsLeaf() { if current.IsMatch(key) { *currentRef = nil t.size -= 1 return } } // If the current node contains a prefix length if current.prefixLen != 0 { // Bail out if we encounter a mismatch mismatch := current.PrefixMismatch(key, depth) if mismatch != current.prefixLen { return } // Increase traversal depth depth += current.prefixLen } // Find the next child next := current.FindChild(key[depth]) // Let the Inner Node handle the removal logic if the child is a match if *next != nil && (*next).IsLeaf() && (*next).IsMatch(key)
else { t.removeHelper(*next, next, key, depth+1) } } // Convenience method for EachPreorder func (t *ArtTree) Each(callback func(*ArtNode)) { for n := range t.EachChanFrom(t.root) { callback(n) } } func (t *ArtTree) EachChan() chan *ArtNode { return t.EachChanFrom(t.root) } func (t *ArtTree) EachChanFrom(start *ArtNode) chan *ArtNode { nodeChan := make(chan *ArtNode) go func() { t.eachHelper(start, nodeChan) close(nodeChan) }() return nodeChan } // Recursive helper for iterative over the ArtTree. Iterates over all nodes in the tree, // putting the found nodes on the channel func (t *ArtTree) eachHelper(current *ArtNode, dest chan *ArtNode) { // Bail early if there's no node to iterate over if current == nil { return } dest <- current // Art Nodes of type NODE48 do not necessarily store their children in sorted order. // So we must instead iterate over their keys, acccess the children, and iterate properly. if current.nodeType == NODE48 { for i := 0; i < len(current.keys); i++ { index := current.keys[byte(i)] if index > 0 { next := current.children[index-1] if next != nil { // Recurse t.eachHelper(next, dest) } } } // Art Nodes of type NODE4, NODE16, and NODE256 keep their children in order, // So we can access them iteratively. } else { for i := 0; i < len(current.children); i++ { next := current.children[i] if next != nil { // Recurse t.eachHelper(next, dest) } } } } func memcpy(dest []byte, src []byte, numBytes int) { for i := 0; i < numBytes && i < len(src) && i < len(dest); i++ { dest[i] = src[i] } } func memmove(dest []byte, src []byte, numBytes int) { for i := 0; i < numBytes; i++ { dest[i] = src[i] } } // Returns the passed in key as a null terminated byte array // if it is not already null terminated. func ensureNullTerminatedKey(key []byte) []byte { index := bytes.Index(key, []byte{0}) // Is there a null terminated character? if index < 0 { // Append one. key = append(key, byte(0)) } return key }
{ current.RemoveChild(key[depth]) t.size -= 1 // Otherwise, recurse. t.size -= 1 }
conditional_block
art_tree.go
// Pacakge art provides a golang implementation of Adaptive Radix Trees package art import ( "bytes" _ "math" _ "os" ) type ArtTree struct { root *ArtNode size int64 } // Creates and returns a new Art Tree with a nil root and a size of 0. func NewArtTree() *ArtTree { return &ArtTree{root: nil, size: 0} } type Result struct { Key []byte Value interface{} } func (t *ArtTree) EachChanResult() chan Result { return t.EachChanResultFrom(t.root) } func (t *ArtTree) EachChanResultFrom(start *ArtNode) chan Result { outChan := make(chan Result) go func() { if start != nil { for n := range t.EachChanFrom(start) { if n.IsLeaf() { outChan <- Result{n.key, n.value} } } } close(outChan) }() return outChan } // Finds the starting node for a prefix search and returns an array of all the objects under it func (t *ArtTree) PrefixSearch(key []byte) []interface{} { ret := make([]interface{}, 0) for r := range t.PrefixSearchChan(key) { ret = append(ret, r.Value) } return ret } func (t *ArtTree) PrefixSearchChan(key []byte) chan Result { return t.EachChanResultFrom(t.searchHelper(t.root, key, 0)) } // Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) Search(key []byte) interface{} { key = ensureNullTerminatedKey(key) foundNode := t.searchHelper(t.root, key, 0) if foundNode != nil && foundNode.IsMatch(key) { return foundNode.value } return nil } // Recursive search helper function that traverses the tree. // Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) searchHelper(current *ArtNode, key []byte, depth int) *ArtNode { // While we have nodes to search if current != nil { maxKeyIndex := len(key) - 1 if depth > maxKeyIndex { return current }
return current } // Check if our key mismatches the current compressed path prefixMismatch := current.PrefixMismatch(key, depth) if prefixMismatch == current.prefixLen { // whole prefix matches depth += current.prefixLen if depth > maxKeyIndex { return current } } else if prefixMismatch == len(key)-depth { // consumed whole key return current } else { // mismatch return nil } // Find the next node at the specified index, and update depth. return t.searchHelper(*(current.FindChild(key[depth])), key, depth+1) } return nil } // Inserts the passed in value that is indexed by the passed in key into the ArtTree. func (t *ArtTree) Insert(key []byte, value interface{}) { key = ensureNullTerminatedKey(key) t.insertHelper(t.root, &t.root, key, value, 0) } // Recursive helper function that traverses the tree until an insertion point is found. // There are four methods of insertion: // // If the current node is null, a new node is created with the passed in key-value pair // and inserted at the current position. // // If the current node is a leaf node, it will expand to a new ArtNode of type NODE4 // to contain itself and a new leaf node containing the passed in key-value pair. // // If the current node's prefix differs from the key at a specified depth, // a new ArtNode of type NODE4 is created to contain the current node and the new leaf node // with an adjusted prefix to account for the mismatch. // // If there is no child at the specified key at the current depth of traversal, a new leaf node // is created and inserted at this position. func (t *ArtTree) insertHelper(current *ArtNode, currentRef **ArtNode, key []byte, value interface{}, depth int) { // @spec: Usually, the leaf can // simply be inserted into an existing inner node, after growing // it if necessary. if current == nil { *currentRef = NewLeafNode(key, value) t.size += 1 return } // @spec: If, because of lazy expansion, // an existing leaf is encountered, it is replaced by a new // inner node storing the existing and the new leaf if current.IsLeaf() { // TODO Determine if we should overwrite keys if they are attempted to overwritten. // Currently, we bail if the key matches. if current.IsMatch(key) { return } // Create a new Inner Node to contain the new Leaf and the current node. newNode4 := NewNode4() newLeafNode := NewLeafNode(key, value) // Determine the longest common prefix between our current node and the key limit := current.LongestCommonPrefix(newLeafNode, depth) newNode4.prefixLen = limit memcpy(newNode4.prefix, key[depth:], min(newNode4.prefixLen, MAX_PREFIX_LEN)) *currentRef = newNode4 // Add both children to the new Inner Node newNode4.AddChild(current.key[depth+newNode4.prefixLen], current) newNode4.AddChild(key[depth+newNode4.prefixLen], newLeafNode) t.size += 1 return } // @spec: Another special case occurs if the key of the new leaf // differs from a compressed path: A new inner node is created // above the current node and the compressed paths are adjusted accordingly. if current.prefixLen != 0 { mismatch := current.PrefixMismatch(key, depth) // If the key differs from the compressed path if mismatch != current.prefixLen { // Create a new Inner Node that will contain the current node // and the desired insertion key newNode4 := NewNode4() *currentRef = newNode4 newNode4.prefixLen = mismatch // Copy the mismatched prefix into the new inner node. memcpy(newNode4.prefix, current.prefix, mismatch) // Adjust prefixes so they fit underneath the new inner node if current.prefixLen < MAX_PREFIX_LEN { newNode4.AddChild(current.prefix[mismatch], current) current.prefixLen -= (mismatch + 1) memmove(current.prefix, current.prefix[mismatch+1:], min(current.prefixLen, MAX_PREFIX_LEN)) } else { current.prefixLen -= (mismatch + 1) minKey := current.Minimum().key newNode4.AddChild(minKey[depth+mismatch], current) memmove(current.prefix, minKey[depth+mismatch+1:], min(current.prefixLen, MAX_PREFIX_LEN)) } // Attach the desired insertion key newLeafNode := NewLeafNode(key, value) newNode4.AddChild(key[depth+mismatch], newLeafNode) t.size += 1 return } depth += current.prefixLen } // Find the next child next := current.FindChild(key[depth]) // If we found a child that matches the key at the current depth if *next != nil { // Recurse, and keep looking for an insertion point t.insertHelper(*next, next, key, value, depth+1) } else { // Otherwise, Add the child at the current position. current.AddChild(key[depth], NewLeafNode(key, value)) t.size += 1 } } // Removes the child that is accessed by the passed in key. func (t *ArtTree) Remove(key []byte) { key = ensureNullTerminatedKey(key) t.removeHelper(t.root, &t.root, key, 0) } // Recursive helper for Removing child nodes. // There are two methods for removal: // // If the current node is a leaf and matches the specified key, remove it. // // If the next child at the specifed key and depth matches, // the current node shall remove it accordingly. func (t *ArtTree) removeHelper(current *ArtNode, currentRef **ArtNode, key []byte, depth int) { // Bail early if we are at a nil node. if current == nil { return } // If the current node matches, remove it. if current.IsLeaf() { if current.IsMatch(key) { *currentRef = nil t.size -= 1 return } } // If the current node contains a prefix length if current.prefixLen != 0 { // Bail out if we encounter a mismatch mismatch := current.PrefixMismatch(key, depth) if mismatch != current.prefixLen { return } // Increase traversal depth depth += current.prefixLen } // Find the next child next := current.FindChild(key[depth]) // Let the Inner Node handle the removal logic if the child is a match if *next != nil && (*next).IsLeaf() && (*next).IsMatch(key) { current.RemoveChild(key[depth]) t.size -= 1 // Otherwise, recurse. t.size -= 1 } else { t.removeHelper(*next, next, key, depth+1) } } // Convenience method for EachPreorder func (t *ArtTree) Each(callback func(*ArtNode)) { for n := range t.EachChanFrom(t.root) { callback(n) } } func (t *ArtTree) EachChan() chan *ArtNode { return t.EachChanFrom(t.root) } func (t *ArtTree) EachChanFrom(start *ArtNode) chan *ArtNode { nodeChan := make(chan *ArtNode) go func() { t.eachHelper(start, nodeChan) close(nodeChan) }() return nodeChan } // Recursive helper for iterative over the ArtTree. Iterates over all nodes in the tree, // putting the found nodes on the channel func (t *ArtTree) eachHelper(current *ArtNode, dest chan *ArtNode) { // Bail early if there's no node to iterate over if current == nil { return } dest <- current // Art Nodes of type NODE48 do not necessarily store their children in sorted order. // So we must instead iterate over their keys, acccess the children, and iterate properly. if current.nodeType == NODE48 { for i := 0; i < len(current.keys); i++ { index := current.keys[byte(i)] if index > 0 { next := current.children[index-1] if next != nil { // Recurse t.eachHelper(next, dest) } } } // Art Nodes of type NODE4, NODE16, and NODE256 keep their children in order, // So we can access them iteratively. } else { for i := 0; i < len(current.children); i++ { next := current.children[i] if next != nil { // Recurse t.eachHelper(next, dest) } } } } func memcpy(dest []byte, src []byte, numBytes int) { for i := 0; i < numBytes && i < len(src) && i < len(dest); i++ { dest[i] = src[i] } } func memmove(dest []byte, src []byte, numBytes int) { for i := 0; i < numBytes; i++ { dest[i] = src[i] } } // Returns the passed in key as a null terminated byte array // if it is not already null terminated. func ensureNullTerminatedKey(key []byte) []byte { index := bytes.Index(key, []byte{0}) // Is there a null terminated character? if index < 0 { // Append one. key = append(key, byte(0)) } return key }
// Check if the current is a match (including prefix match) if current.IsLeaf() && len(current.key) >= len(key) && bytes.Equal(key, current.key[0:len(key)]) {
random_line_split
art_tree.go
// Pacakge art provides a golang implementation of Adaptive Radix Trees package art import ( "bytes" _ "math" _ "os" ) type ArtTree struct { root *ArtNode size int64 } // Creates and returns a new Art Tree with a nil root and a size of 0. func NewArtTree() *ArtTree { return &ArtTree{root: nil, size: 0} } type Result struct { Key []byte Value interface{} } func (t *ArtTree) EachChanResult() chan Result { return t.EachChanResultFrom(t.root) } func (t *ArtTree) EachChanResultFrom(start *ArtNode) chan Result { outChan := make(chan Result) go func() { if start != nil { for n := range t.EachChanFrom(start) { if n.IsLeaf() { outChan <- Result{n.key, n.value} } } } close(outChan) }() return outChan } // Finds the starting node for a prefix search and returns an array of all the objects under it func (t *ArtTree) PrefixSearch(key []byte) []interface{} { ret := make([]interface{}, 0) for r := range t.PrefixSearchChan(key) { ret = append(ret, r.Value) } return ret } func (t *ArtTree) PrefixSearchChan(key []byte) chan Result
// Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) Search(key []byte) interface{} { key = ensureNullTerminatedKey(key) foundNode := t.searchHelper(t.root, key, 0) if foundNode != nil && foundNode.IsMatch(key) { return foundNode.value } return nil } // Recursive search helper function that traverses the tree. // Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) searchHelper(current *ArtNode, key []byte, depth int) *ArtNode { // While we have nodes to search if current != nil { maxKeyIndex := len(key) - 1 if depth > maxKeyIndex { return current } // Check if the current is a match (including prefix match) if current.IsLeaf() && len(current.key) >= len(key) && bytes.Equal(key, current.key[0:len(key)]) { return current } // Check if our key mismatches the current compressed path prefixMismatch := current.PrefixMismatch(key, depth) if prefixMismatch == current.prefixLen { // whole prefix matches depth += current.prefixLen if depth > maxKeyIndex { return current } } else if prefixMismatch == len(key)-depth { // consumed whole key return current } else { // mismatch return nil } // Find the next node at the specified index, and update depth. return t.searchHelper(*(current.FindChild(key[depth])), key, depth+1) } return nil } // Inserts the passed in value that is indexed by the passed in key into the ArtTree. func (t *ArtTree) Insert(key []byte, value interface{}) { key = ensureNullTerminatedKey(key) t.insertHelper(t.root, &t.root, key, value, 0) } // Recursive helper function that traverses the tree until an insertion point is found. // There are four methods of insertion: // // If the current node is null, a new node is created with the passed in key-value pair // and inserted at the current position. // // If the current node is a leaf node, it will expand to a new ArtNode of type NODE4 // to contain itself and a new leaf node containing the passed in key-value pair. // // If the current node's prefix differs from the key at a specified depth, // a new ArtNode of type NODE4 is created to contain the current node and the new leaf node // with an adjusted prefix to account for the mismatch. // // If there is no child at the specified key at the current depth of traversal, a new leaf node // is created and inserted at this position. func (t *ArtTree) insertHelper(current *ArtNode, currentRef **ArtNode, key []byte, value interface{}, depth int) { // @spec: Usually, the leaf can // simply be inserted into an existing inner node, after growing // it if necessary. if current == nil { *currentRef = NewLeafNode(key, value) t.size += 1 return } // @spec: If, because of lazy expansion, // an existing leaf is encountered, it is replaced by a new // inner node storing the existing and the new leaf if current.IsLeaf() { // TODO Determine if we should overwrite keys if they are attempted to overwritten. // Currently, we bail if the key matches. if current.IsMatch(key) { return } // Create a new Inner Node to contain the new Leaf and the current node. newNode4 := NewNode4() newLeafNode := NewLeafNode(key, value) // Determine the longest common prefix between our current node and the key limit := current.LongestCommonPrefix(newLeafNode, depth) newNode4.prefixLen = limit memcpy(newNode4.prefix, key[depth:], min(newNode4.prefixLen, MAX_PREFIX_LEN)) *currentRef = newNode4 // Add both children to the new Inner Node newNode4.AddChild(current.key[depth+newNode4.prefixLen], current) newNode4.AddChild(key[depth+newNode4.prefixLen], newLeafNode) t.size += 1 return } // @spec: Another special case occurs if the key of the new leaf // differs from a compressed path: A new inner node is created // above the current node and the compressed paths are adjusted accordingly. if current.prefixLen != 0 { mismatch := current.PrefixMismatch(key, depth) // If the key differs from the compressed path if mismatch != current.prefixLen { // Create a new Inner Node that will contain the current node // and the desired insertion key newNode4 := NewNode4() *currentRef = newNode4 newNode4.prefixLen = mismatch // Copy the mismatched prefix into the new inner node. memcpy(newNode4.prefix, current.prefix, mismatch) // Adjust prefixes so they fit underneath the new inner node if current.prefixLen < MAX_PREFIX_LEN { newNode4.AddChild(current.prefix[mismatch], current) current.prefixLen -= (mismatch + 1) memmove(current.prefix, current.prefix[mismatch+1:], min(current.prefixLen, MAX_PREFIX_LEN)) } else { current.prefixLen -= (mismatch + 1) minKey := current.Minimum().key newNode4.AddChild(minKey[depth+mismatch], current) memmove(current.prefix, minKey[depth+mismatch+1:], min(current.prefixLen, MAX_PREFIX_LEN)) } // Attach the desired insertion key newLeafNode := NewLeafNode(key, value) newNode4.AddChild(key[depth+mismatch], newLeafNode) t.size += 1 return } depth += current.prefixLen } // Find the next child next := current.FindChild(key[depth]) // If we found a child that matches the key at the current depth if *next != nil { // Recurse, and keep looking for an insertion point t.insertHelper(*next, next, key, value, depth+1) } else { // Otherwise, Add the child at the current position. current.AddChild(key[depth], NewLeafNode(key, value)) t.size += 1 } } // Removes the child that is accessed by the passed in key. func (t *ArtTree) Remove(key []byte) { key = ensureNullTerminatedKey(key) t.removeHelper(t.root, &t.root, key, 0) } // Recursive helper for Removing child nodes. // There are two methods for removal: // // If the current node is a leaf and matches the specified key, remove it. // // If the next child at the specifed key and depth matches, // the current node shall remove it accordingly. func (t *ArtTree) removeHelper(current *ArtNode, currentRef **ArtNode, key []byte, depth int) { // Bail early if we are at a nil node. if current == nil { return } // If the current node matches, remove it. if current.IsLeaf() { if current.IsMatch(key) { *currentRef = nil t.size -= 1 return } } // If the current node contains a prefix length if current.prefixLen != 0 { // Bail out if we encounter a mismatch mismatch := current.PrefixMismatch(key, depth) if mismatch != current.prefixLen { return } // Increase traversal depth depth += current.prefixLen } // Find the next child next := current.FindChild(key[depth]) // Let the Inner Node handle the removal logic if the child is a match if *next != nil && (*next).IsLeaf() && (*next).IsMatch(key) { current.RemoveChild(key[depth]) t.size -= 1 // Otherwise, recurse. t.size -= 1 } else { t.removeHelper(*next, next, key, depth+1) } } // Convenience method for EachPreorder func (t *ArtTree) Each(callback func(*ArtNode)) { for n := range t.EachChanFrom(t.root) { callback(n) } } func (t *ArtTree) EachChan() chan *ArtNode { return t.EachChanFrom(t.root) } func (t *ArtTree) EachChanFrom(start *ArtNode) chan *ArtNode { nodeChan := make(chan *ArtNode) go func() { t.eachHelper(start, nodeChan) close(nodeChan) }() return nodeChan } // Recursive helper for iterative over the ArtTree. Iterates over all nodes in the tree, // putting the found nodes on the channel func (t *ArtTree) eachHelper(current *ArtNode, dest chan *ArtNode) { // Bail early if there's no node to iterate over if current == nil { return } dest <- current // Art Nodes of type NODE48 do not necessarily store their children in sorted order. // So we must instead iterate over their keys, acccess the children, and iterate properly. if current.nodeType == NODE48 { for i := 0; i < len(current.keys); i++ { index := current.keys[byte(i)] if index > 0 { next := current.children[index-1] if next != nil { // Recurse t.eachHelper(next, dest) } } } // Art Nodes of type NODE4, NODE16, and NODE256 keep their children in order, // So we can access them iteratively. } else { for i := 0; i < len(current.children); i++ { next := current.children[i] if next != nil { // Recurse t.eachHelper(next, dest) } } } } func memcpy(dest []byte, src []byte, numBytes int) { for i := 0; i < numBytes && i < len(src) && i < len(dest); i++ { dest[i] = src[i] } } func memmove(dest []byte, src []byte, numBytes int) { for i := 0; i < numBytes; i++ { dest[i] = src[i] } } // Returns the passed in key as a null terminated byte array // if it is not already null terminated. func ensureNullTerminatedKey(key []byte) []byte { index := bytes.Index(key, []byte{0}) // Is there a null terminated character? if index < 0 { // Append one. key = append(key, byte(0)) } return key }
{ return t.EachChanResultFrom(t.searchHelper(t.root, key, 0)) }
identifier_body
art_tree.go
// Pacakge art provides a golang implementation of Adaptive Radix Trees package art import ( "bytes" _ "math" _ "os" ) type ArtTree struct { root *ArtNode size int64 } // Creates and returns a new Art Tree with a nil root and a size of 0. func NewArtTree() *ArtTree { return &ArtTree{root: nil, size: 0} } type Result struct { Key []byte Value interface{} } func (t *ArtTree) EachChanResult() chan Result { return t.EachChanResultFrom(t.root) } func (t *ArtTree) EachChanResultFrom(start *ArtNode) chan Result { outChan := make(chan Result) go func() { if start != nil { for n := range t.EachChanFrom(start) { if n.IsLeaf() { outChan <- Result{n.key, n.value} } } } close(outChan) }() return outChan } // Finds the starting node for a prefix search and returns an array of all the objects under it func (t *ArtTree) PrefixSearch(key []byte) []interface{} { ret := make([]interface{}, 0) for r := range t.PrefixSearchChan(key) { ret = append(ret, r.Value) } return ret } func (t *ArtTree) PrefixSearchChan(key []byte) chan Result { return t.EachChanResultFrom(t.searchHelper(t.root, key, 0)) } // Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) Search(key []byte) interface{} { key = ensureNullTerminatedKey(key) foundNode := t.searchHelper(t.root, key, 0) if foundNode != nil && foundNode.IsMatch(key) { return foundNode.value } return nil } // Recursive search helper function that traverses the tree. // Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) searchHelper(current *ArtNode, key []byte, depth int) *ArtNode { // While we have nodes to search if current != nil { maxKeyIndex := len(key) - 1 if depth > maxKeyIndex { return current } // Check if the current is a match (including prefix match) if current.IsLeaf() && len(current.key) >= len(key) && bytes.Equal(key, current.key[0:len(key)]) { return current } // Check if our key mismatches the current compressed path prefixMismatch := current.PrefixMismatch(key, depth) if prefixMismatch == current.prefixLen { // whole prefix matches depth += current.prefixLen if depth > maxKeyIndex { return current } } else if prefixMismatch == len(key)-depth { // consumed whole key return current } else { // mismatch return nil } // Find the next node at the specified index, and update depth. return t.searchHelper(*(current.FindChild(key[depth])), key, depth+1) } return nil } // Inserts the passed in value that is indexed by the passed in key into the ArtTree. func (t *ArtTree) Insert(key []byte, value interface{}) { key = ensureNullTerminatedKey(key) t.insertHelper(t.root, &t.root, key, value, 0) } // Recursive helper function that traverses the tree until an insertion point is found. // There are four methods of insertion: // // If the current node is null, a new node is created with the passed in key-value pair // and inserted at the current position. // // If the current node is a leaf node, it will expand to a new ArtNode of type NODE4 // to contain itself and a new leaf node containing the passed in key-value pair. // // If the current node's prefix differs from the key at a specified depth, // a new ArtNode of type NODE4 is created to contain the current node and the new leaf node // with an adjusted prefix to account for the mismatch. // // If there is no child at the specified key at the current depth of traversal, a new leaf node // is created and inserted at this position. func (t *ArtTree) insertHelper(current *ArtNode, currentRef **ArtNode, key []byte, value interface{}, depth int) { // @spec: Usually, the leaf can // simply be inserted into an existing inner node, after growing // it if necessary. if current == nil { *currentRef = NewLeafNode(key, value) t.size += 1 return } // @spec: If, because of lazy expansion, // an existing leaf is encountered, it is replaced by a new // inner node storing the existing and the new leaf if current.IsLeaf() { // TODO Determine if we should overwrite keys if they are attempted to overwritten. // Currently, we bail if the key matches. if current.IsMatch(key) { return } // Create a new Inner Node to contain the new Leaf and the current node. newNode4 := NewNode4() newLeafNode := NewLeafNode(key, value) // Determine the longest common prefix between our current node and the key limit := current.LongestCommonPrefix(newLeafNode, depth) newNode4.prefixLen = limit memcpy(newNode4.prefix, key[depth:], min(newNode4.prefixLen, MAX_PREFIX_LEN)) *currentRef = newNode4 // Add both children to the new Inner Node newNode4.AddChild(current.key[depth+newNode4.prefixLen], current) newNode4.AddChild(key[depth+newNode4.prefixLen], newLeafNode) t.size += 1 return } // @spec: Another special case occurs if the key of the new leaf // differs from a compressed path: A new inner node is created // above the current node and the compressed paths are adjusted accordingly. if current.prefixLen != 0 { mismatch := current.PrefixMismatch(key, depth) // If the key differs from the compressed path if mismatch != current.prefixLen { // Create a new Inner Node that will contain the current node // and the desired insertion key newNode4 := NewNode4() *currentRef = newNode4 newNode4.prefixLen = mismatch // Copy the mismatched prefix into the new inner node. memcpy(newNode4.prefix, current.prefix, mismatch) // Adjust prefixes so they fit underneath the new inner node if current.prefixLen < MAX_PREFIX_LEN { newNode4.AddChild(current.prefix[mismatch], current) current.prefixLen -= (mismatch + 1) memmove(current.prefix, current.prefix[mismatch+1:], min(current.prefixLen, MAX_PREFIX_LEN)) } else { current.prefixLen -= (mismatch + 1) minKey := current.Minimum().key newNode4.AddChild(minKey[depth+mismatch], current) memmove(current.prefix, minKey[depth+mismatch+1:], min(current.prefixLen, MAX_PREFIX_LEN)) } // Attach the desired insertion key newLeafNode := NewLeafNode(key, value) newNode4.AddChild(key[depth+mismatch], newLeafNode) t.size += 1 return } depth += current.prefixLen } // Find the next child next := current.FindChild(key[depth]) // If we found a child that matches the key at the current depth if *next != nil { // Recurse, and keep looking for an insertion point t.insertHelper(*next, next, key, value, depth+1) } else { // Otherwise, Add the child at the current position. current.AddChild(key[depth], NewLeafNode(key, value)) t.size += 1 } } // Removes the child that is accessed by the passed in key. func (t *ArtTree)
(key []byte) { key = ensureNullTerminatedKey(key) t.removeHelper(t.root, &t.root, key, 0) } // Recursive helper for Removing child nodes. // There are two methods for removal: // // If the current node is a leaf and matches the specified key, remove it. // // If the next child at the specifed key and depth matches, // the current node shall remove it accordingly. func (t *ArtTree) removeHelper(current *ArtNode, currentRef **ArtNode, key []byte, depth int) { // Bail early if we are at a nil node. if current == nil { return } // If the current node matches, remove it. if current.IsLeaf() { if current.IsMatch(key) { *currentRef = nil t.size -= 1 return } } // If the current node contains a prefix length if current.prefixLen != 0 { // Bail out if we encounter a mismatch mismatch := current.PrefixMismatch(key, depth) if mismatch != current.prefixLen { return } // Increase traversal depth depth += current.prefixLen } // Find the next child next := current.FindChild(key[depth]) // Let the Inner Node handle the removal logic if the child is a match if *next != nil && (*next).IsLeaf() && (*next).IsMatch(key) { current.RemoveChild(key[depth]) t.size -= 1 // Otherwise, recurse. t.size -= 1 } else { t.removeHelper(*next, next, key, depth+1) } } // Convenience method for EachPreorder func (t *ArtTree) Each(callback func(*ArtNode)) { for n := range t.EachChanFrom(t.root) { callback(n) } } func (t *ArtTree) EachChan() chan *ArtNode { return t.EachChanFrom(t.root) } func (t *ArtTree) EachChanFrom(start *ArtNode) chan *ArtNode { nodeChan := make(chan *ArtNode) go func() { t.eachHelper(start, nodeChan) close(nodeChan) }() return nodeChan } // Recursive helper for iterative over the ArtTree. Iterates over all nodes in the tree, // putting the found nodes on the channel func (t *ArtTree) eachHelper(current *ArtNode, dest chan *ArtNode) { // Bail early if there's no node to iterate over if current == nil { return } dest <- current // Art Nodes of type NODE48 do not necessarily store their children in sorted order. // So we must instead iterate over their keys, acccess the children, and iterate properly. if current.nodeType == NODE48 { for i := 0; i < len(current.keys); i++ { index := current.keys[byte(i)] if index > 0 { next := current.children[index-1] if next != nil { // Recurse t.eachHelper(next, dest) } } } // Art Nodes of type NODE4, NODE16, and NODE256 keep their children in order, // So we can access them iteratively. } else { for i := 0; i < len(current.children); i++ { next := current.children[i] if next != nil { // Recurse t.eachHelper(next, dest) } } } } func memcpy(dest []byte, src []byte, numBytes int) { for i := 0; i < numBytes && i < len(src) && i < len(dest); i++ { dest[i] = src[i] } } func memmove(dest []byte, src []byte, numBytes int) { for i := 0; i < numBytes; i++ { dest[i] = src[i] } } // Returns the passed in key as a null terminated byte array // if it is not already null terminated. func ensureNullTerminatedKey(key []byte) []byte { index := bytes.Index(key, []byte{0}) // Is there a null terminated character? if index < 0 { // Append one. key = append(key, byte(0)) } return key }
Remove
identifier_name
lib.rs
//! Configures and runs the outbound proxy. //! //! The outound proxy is responsible for routing traffic from the local //! application to external network endpoints. #![deny(warnings, rust_2018_idioms)] use linkerd2_app_core::{ classify, config::Config, dns, drain, dst::DstAddr, errors, http_request_authority_addr, http_request_host_addr, http_request_l5d_override_dst_addr, http_request_orig_dst_addr, identity, proxy::{ self, core::resolve::Resolve, discover, http::{ balance, canonicalize, client, fallback, header_from_target, insert, metrics as http_metrics, normalize_uri, profiles, retry, router, settings, strip_header, }, Server, }, reconnect, serve, spans::SpanConverter, svc, trace, trace_context, transport::{self, connect, tls, OrigDstAddr}, Addr, Conditional, DispatchDeadline, CANONICAL_DST_HEADER, DST_OVERRIDE_HEADER, L5D_CLIENT_ID, L5D_REMOTE_IP, L5D_REQUIRE_ID, L5D_SERVER_ID, }; use opencensus_proto::trace::v1 as oc; use std::collections::HashMap; use std::time::Duration; use tokio::sync::mpsc; use tower_grpc::{self as grpc, generic::client::GrpcService}; use tracing::{debug, info_span}; #[allow(dead_code)] // TODO #2597 mod add_remote_ip_on_rsp; #[allow(dead_code)] // TODO #2597 mod add_server_id_on_rsp; mod endpoint; mod orig_proto_upgrade; mod require_identity_on_endpoint; mod resolve; pub use self::endpoint::Endpoint; pub use self::resolve::resolve; const EWMA_DEFAULT_RTT: Duration = Duration::from_millis(30); const EWMA_DECAY: Duration = Duration::from_secs(10); pub fn
<A, R, P>( config: &Config, local_identity: tls::Conditional<identity::Local>, listen: transport::Listen<A>, resolve: R, dns_resolver: dns::Resolver, profiles_client: linkerd2_app_core::profiles::Client<P>, tap_layer: linkerd2_app_core::tap::Layer, handle_time: http_metrics::handle_time::Scope, endpoint_http_metrics: linkerd2_app_core::HttpEndpointMetricsRegistry, route_http_metrics: linkerd2_app_core::HttpRouteMetricsRegistry, retry_http_metrics: linkerd2_app_core::HttpRouteMetricsRegistry, transport_metrics: linkerd2_app_core::transport::MetricsRegistry, span_sink: Option<mpsc::Sender<oc::Span>>, drain: drain::Watch, ) where A: OrigDstAddr + Send + 'static, R: Resolve<DstAddr, Endpoint = Endpoint> + Clone + Send + Sync + 'static, R::Future: Send, R::Resolution: Send, P: GrpcService<grpc::BoxBody> + Clone + Send + Sync + 'static, P::ResponseBody: Send, <P::ResponseBody as grpc::Body>::Data: Send, P::Future: Send, { let capacity = config.outbound_router_capacity; let max_idle_age = config.outbound_router_max_idle_age; let max_in_flight = config.outbound_max_requests_in_flight; let canonicalize_timeout = config.dns_canonicalize_timeout; let dispatch_timeout = config.outbound_dispatch_timeout; let mut trace_labels = HashMap::new(); trace_labels.insert("direction".to_string(), "outbound".to_string()); // Establishes connections to remote peers (for both TCP // forwarding and HTTP proxying). let connect = svc::stack(connect::svc(config.outbound_connect_keepalive)) .push(tls::client::layer(local_identity)) .push_timeout(config.outbound_connect_timeout) .push(transport_metrics.layer_connect(TransportLabels)); let trace_context_layer = trace_context::layer( span_sink .clone() .map(|span_sink| SpanConverter::client(span_sink, trace_labels.clone())), ); // Instantiates an HTTP client for for a `client::Config` let client_stack = connect .clone() .push(client::layer(config.h2_settings)) .push(reconnect::layer({ let backoff = config.outbound_connect_backoff.clone(); move |_| Ok(backoff.stream()) })) .push(trace_context_layer) .push(normalize_uri::layer()); // A per-`outbound::Endpoint` stack that: // // 1. Records http metrics with per-endpoint labels. // 2. Instruments `tap` inspection. // 3. Changes request/response versions when the endpoint // supports protocol upgrade (and the request may be upgraded). // 4. Appends `l5d-server-id` to responses coming back iff meshed // TLS was used on the connection. // 5. Routes requests to the correct client (based on the // request version and headers). // 6. Strips any `l5d-server-id` that may have been received from // the server, before we apply our own. let endpoint_stack = client_stack .serves::<Endpoint>() .push(strip_header::response::layer(L5D_REMOTE_IP)) .push(strip_header::response::layer(L5D_SERVER_ID)) .push(strip_header::request::layer(L5D_REQUIRE_ID)) // disabled due to information leagkage //.push(add_remote_ip_on_rsp::layer()) //.push(add_server_id_on_rsp::layer()) .push(orig_proto_upgrade::layer()) .push(tap_layer.clone()) .push(http_metrics::layer::<_, classify::Response>( endpoint_http_metrics, )) .push(require_identity_on_endpoint::layer()) .push(trace::layer(|endpoint: &Endpoint| { info_span!("endpoint", ?endpoint) })); // A per-`dst::Route` layer that uses profile data to configure // a per-route layer. // // 1. The `classify` module installs a `classify::Response` // extension into each request so that all lower metrics // implementations can use the route-specific configuration. // 2. A timeout is optionally enabled if the target `dst::Route` // specifies a timeout. This goes before `retry` to cap // retries. // 3. Retries are optionally enabled depending on if the route // is retryable. let dst_route_layer = svc::layers() .push(insert::target::layer()) .push(http_metrics::layer::<_, classify::Response>( retry_http_metrics.clone(), )) .push(retry::layer(retry_http_metrics.clone())) .push(proxy::http::timeout::layer()) .push(http_metrics::layer::<_, classify::Response>( route_http_metrics, )) .push(classify::layer()) .push_buffer_pending(max_in_flight, DispatchDeadline::extract); // Routes requests to their original destination endpoints. Used as // a fallback when service discovery has no endpoints for a destination. // // If the `l5d-require-id` header is present, then that identity is // used as the server name when connecting to the endpoint. let orig_dst_router_layer = svc::layers() .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), Endpoint::from_request, )); // Resolves the target via the control plane and balances requests // over all endpoints returned from the destination service. const DISCOVER_UPDATE_BUFFER_CAPACITY: usize = 2; let balancer_layer = svc::layers() .push_spawn_ready() .push(discover::Layer::new( DISCOVER_UPDATE_BUFFER_CAPACITY, resolve, )) .push(balance::layer(EWMA_DEFAULT_RTT, EWMA_DECAY)); // If the balancer fails to be created, i.e., because it is unresolvable, // fall back to using a router that dispatches request to the // application-selected original destination. let distributor = endpoint_stack .push(fallback::layer(balancer_layer, orig_dst_router_layer)) .serves::<DstAddr>() .push(trace::layer( |dst: &DstAddr| info_span!("concrete", dst.concrete = %dst.dst_concrete()), )); // A per-`DstAddr` stack that does the following: // // 1. Adds the `CANONICAL_DST_HEADER` from the `DstAddr`. // 2. Determines the profile of the destination and applies // per-route policy. // 3. Creates a load balancer , configured by resolving the // `DstAddr` with a resolver. let dst_stack = distributor .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(profiles::router::layer(profiles_client, dst_route_layer)) .push(header_from_target::layer(CANONICAL_DST_HEADER)); // Routes request using the `DstAddr` extension. // // This is shared across addr-stacks so that multiple addrs that // canonicalize to the same DstAddr use the same dst-stack service. let dst_router = dst_stack .push(trace::layer( |dst: &DstAddr| info_span!("logical", dst.logical = %dst.dst_logical()), )) .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), |req: &http::Request<_>| { req.extensions() .get::<Addr>() .cloned() .map(|addr| DstAddr::outbound(addr, settings::Settings::from_request(req))) }, )) .into_inner() .make(); // Canonicalizes the request-specified `Addr` via DNS, and // annotates each request with a refined `Addr` so that it may be // routed by the dst_router. let addr_stack = svc::stack(svc::Shared::new(dst_router)) .push(canonicalize::layer(dns_resolver, canonicalize_timeout)); // Routes requests to an `Addr`: // // 1. If the request had an `l5d-override-dst` header, this value // is used. // // 2. If the request is HTTP/2 and has an :authority, this value // is used. // // 3. If the request is absolute-form HTTP/1, the URI's // authority is used. // // 4. If the request has an HTTP/1 Host header, it is used. // // 5. Finally, if the Source had an SO_ORIGINAL_DST, this TCP // address is used. let addr_router = addr_stack .push(strip_header::request::layer(L5D_CLIENT_ID)) .push(strip_header::request::layer(DST_OVERRIDE_HEADER)) .push(insert::target::layer()) .push(trace::layer(|addr: &Addr| info_span!("addr", %addr))) .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), |req: &http::Request<_>| { http_request_l5d_override_dst_addr(req) .map(|override_addr| { debug!("using dst-override"); override_addr }) .or_else(|_| http_request_authority_addr(req)) .or_else(|_| http_request_host_addr(req)) .or_else(|_| http_request_orig_dst_addr(req)) .ok() }, )) .into_inner() .make(); // Share a single semaphore across all requests to signal when // the proxy is overloaded. let admission_control = svc::stack(addr_router) .push_concurrency_limit(max_in_flight) .push_load_shed(); let trace_context_layer = trace_context::layer( span_sink.map(|span_sink| SpanConverter::server(span_sink, trace_labels)), ); // Instantiates an HTTP service for each `Source` using the // shared `addr_router`. The `Source` is stored in the request's // extensions so that it can be used by the `addr_router`. let server_stack = svc::stack(svc::Shared::new(admission_control)) .push(insert::layer(move || { DispatchDeadline::after(dispatch_timeout) })) .push(insert::target::layer()) .push(errors::layer()) .push(trace::layer( |src: &tls::accept::Meta| info_span!("source", target.addr = %src.addrs.target_addr()), )) .push(trace_context_layer) .push(handle_time.layer()); let skip_ports = std::sync::Arc::new(config.outbound_ports_disable_protocol_detection.clone()); let proxy = Server::new( TransportLabels, transport_metrics, svc::stack(connect) .push(svc::map_target::layer(Endpoint::from)) .into_inner(), server_stack, config.h2_settings, drain.clone(), skip_ports.clone(), ); let no_tls: tls::Conditional<identity::Local> = Conditional::None(tls::ReasonForNoPeerName::Loopback.into()); let accept = tls::AcceptTls::new(no_tls, proxy).with_skip_ports(skip_ports); serve::spawn(listen, accept, drain); } #[derive(Copy, Clone, Debug)] struct TransportLabels; impl transport::metrics::TransportLabels<Endpoint> for TransportLabels { type Labels = transport::labels::Key; fn transport_labels(&self, endpoint: &Endpoint) -> Self::Labels { transport::labels::Key::connect("outbound", endpoint.identity.as_ref()) } } impl transport::metrics::TransportLabels<proxy::server::Protocol> for TransportLabels { type Labels = transport::labels::Key; fn transport_labels(&self, proto: &proxy::server::Protocol) -> Self::Labels { transport::labels::Key::accept("outbound", proto.tls.peer_identity.as_ref()) } }
spawn
identifier_name
lib.rs
//! Configures and runs the outbound proxy. //! //! The outound proxy is responsible for routing traffic from the local //! application to external network endpoints. #![deny(warnings, rust_2018_idioms)] use linkerd2_app_core::{ classify, config::Config, dns, drain, dst::DstAddr, errors, http_request_authority_addr, http_request_host_addr, http_request_l5d_override_dst_addr, http_request_orig_dst_addr, identity, proxy::{ self, core::resolve::Resolve, discover, http::{ balance, canonicalize, client, fallback, header_from_target, insert, metrics as http_metrics, normalize_uri, profiles, retry, router, settings, strip_header, }, Server, }, reconnect, serve, spans::SpanConverter, svc, trace, trace_context, transport::{self, connect, tls, OrigDstAddr}, Addr, Conditional, DispatchDeadline, CANONICAL_DST_HEADER, DST_OVERRIDE_HEADER, L5D_CLIENT_ID, L5D_REMOTE_IP, L5D_REQUIRE_ID, L5D_SERVER_ID, }; use opencensus_proto::trace::v1 as oc; use std::collections::HashMap; use std::time::Duration; use tokio::sync::mpsc; use tower_grpc::{self as grpc, generic::client::GrpcService}; use tracing::{debug, info_span}; #[allow(dead_code)] // TODO #2597 mod add_remote_ip_on_rsp; #[allow(dead_code)] // TODO #2597 mod add_server_id_on_rsp; mod endpoint; mod orig_proto_upgrade; mod require_identity_on_endpoint; mod resolve; pub use self::endpoint::Endpoint; pub use self::resolve::resolve; const EWMA_DEFAULT_RTT: Duration = Duration::from_millis(30); const EWMA_DECAY: Duration = Duration::from_secs(10); pub fn spawn<A, R, P>( config: &Config, local_identity: tls::Conditional<identity::Local>, listen: transport::Listen<A>, resolve: R, dns_resolver: dns::Resolver, profiles_client: linkerd2_app_core::profiles::Client<P>, tap_layer: linkerd2_app_core::tap::Layer, handle_time: http_metrics::handle_time::Scope, endpoint_http_metrics: linkerd2_app_core::HttpEndpointMetricsRegistry, route_http_metrics: linkerd2_app_core::HttpRouteMetricsRegistry, retry_http_metrics: linkerd2_app_core::HttpRouteMetricsRegistry, transport_metrics: linkerd2_app_core::transport::MetricsRegistry, span_sink: Option<mpsc::Sender<oc::Span>>, drain: drain::Watch, ) where A: OrigDstAddr + Send + 'static, R: Resolve<DstAddr, Endpoint = Endpoint> + Clone + Send + Sync + 'static, R::Future: Send, R::Resolution: Send, P: GrpcService<grpc::BoxBody> + Clone + Send + Sync + 'static, P::ResponseBody: Send, <P::ResponseBody as grpc::Body>::Data: Send, P::Future: Send, { let capacity = config.outbound_router_capacity; let max_idle_age = config.outbound_router_max_idle_age; let max_in_flight = config.outbound_max_requests_in_flight; let canonicalize_timeout = config.dns_canonicalize_timeout; let dispatch_timeout = config.outbound_dispatch_timeout; let mut trace_labels = HashMap::new(); trace_labels.insert("direction".to_string(), "outbound".to_string()); // Establishes connections to remote peers (for both TCP // forwarding and HTTP proxying). let connect = svc::stack(connect::svc(config.outbound_connect_keepalive)) .push(tls::client::layer(local_identity)) .push_timeout(config.outbound_connect_timeout) .push(transport_metrics.layer_connect(TransportLabels)); let trace_context_layer = trace_context::layer( span_sink .clone() .map(|span_sink| SpanConverter::client(span_sink, trace_labels.clone())), ); // Instantiates an HTTP client for for a `client::Config` let client_stack = connect .clone() .push(client::layer(config.h2_settings)) .push(reconnect::layer({ let backoff = config.outbound_connect_backoff.clone(); move |_| Ok(backoff.stream()) })) .push(trace_context_layer) .push(normalize_uri::layer()); // A per-`outbound::Endpoint` stack that: // // 1. Records http metrics with per-endpoint labels. // 2. Instruments `tap` inspection. // 3. Changes request/response versions when the endpoint // supports protocol upgrade (and the request may be upgraded). // 4. Appends `l5d-server-id` to responses coming back iff meshed // TLS was used on the connection. // 5. Routes requests to the correct client (based on the // request version and headers). // 6. Strips any `l5d-server-id` that may have been received from // the server, before we apply our own. let endpoint_stack = client_stack .serves::<Endpoint>() .push(strip_header::response::layer(L5D_REMOTE_IP)) .push(strip_header::response::layer(L5D_SERVER_ID)) .push(strip_header::request::layer(L5D_REQUIRE_ID)) // disabled due to information leagkage //.push(add_remote_ip_on_rsp::layer()) //.push(add_server_id_on_rsp::layer()) .push(orig_proto_upgrade::layer()) .push(tap_layer.clone()) .push(http_metrics::layer::<_, classify::Response>( endpoint_http_metrics, )) .push(require_identity_on_endpoint::layer()) .push(trace::layer(|endpoint: &Endpoint| { info_span!("endpoint", ?endpoint) })); // A per-`dst::Route` layer that uses profile data to configure // a per-route layer. // // 1. The `classify` module installs a `classify::Response` // extension into each request so that all lower metrics // implementations can use the route-specific configuration. // 2. A timeout is optionally enabled if the target `dst::Route` // specifies a timeout. This goes before `retry` to cap // retries. // 3. Retries are optionally enabled depending on if the route // is retryable. let dst_route_layer = svc::layers() .push(insert::target::layer()) .push(http_metrics::layer::<_, classify::Response>( retry_http_metrics.clone(), )) .push(retry::layer(retry_http_metrics.clone())) .push(proxy::http::timeout::layer()) .push(http_metrics::layer::<_, classify::Response>( route_http_metrics, )) .push(classify::layer()) .push_buffer_pending(max_in_flight, DispatchDeadline::extract); // Routes requests to their original destination endpoints. Used as // a fallback when service discovery has no endpoints for a destination. // // If the `l5d-require-id` header is present, then that identity is // used as the server name when connecting to the endpoint. let orig_dst_router_layer = svc::layers() .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), Endpoint::from_request, )); // Resolves the target via the control plane and balances requests // over all endpoints returned from the destination service. const DISCOVER_UPDATE_BUFFER_CAPACITY: usize = 2; let balancer_layer = svc::layers() .push_spawn_ready() .push(discover::Layer::new( DISCOVER_UPDATE_BUFFER_CAPACITY, resolve, )) .push(balance::layer(EWMA_DEFAULT_RTT, EWMA_DECAY)); // If the balancer fails to be created, i.e., because it is unresolvable, // fall back to using a router that dispatches request to the // application-selected original destination. let distributor = endpoint_stack .push(fallback::layer(balancer_layer, orig_dst_router_layer)) .serves::<DstAddr>() .push(trace::layer( |dst: &DstAddr| info_span!("concrete", dst.concrete = %dst.dst_concrete()), )); // A per-`DstAddr` stack that does the following: // // 1. Adds the `CANONICAL_DST_HEADER` from the `DstAddr`. // 2. Determines the profile of the destination and applies // per-route policy. // 3. Creates a load balancer , configured by resolving the // `DstAddr` with a resolver. let dst_stack = distributor .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(profiles::router::layer(profiles_client, dst_route_layer)) .push(header_from_target::layer(CANONICAL_DST_HEADER)); // Routes request using the `DstAddr` extension. // // This is shared across addr-stacks so that multiple addrs that // canonicalize to the same DstAddr use the same dst-stack service. let dst_router = dst_stack .push(trace::layer( |dst: &DstAddr| info_span!("logical", dst.logical = %dst.dst_logical()), )) .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), |req: &http::Request<_>| { req.extensions() .get::<Addr>() .cloned() .map(|addr| DstAddr::outbound(addr, settings::Settings::from_request(req))) }, )) .into_inner() .make(); // Canonicalizes the request-specified `Addr` via DNS, and // annotates each request with a refined `Addr` so that it may be // routed by the dst_router. let addr_stack = svc::stack(svc::Shared::new(dst_router)) .push(canonicalize::layer(dns_resolver, canonicalize_timeout)); // Routes requests to an `Addr`: // // 1. If the request had an `l5d-override-dst` header, this value // is used. // // 2. If the request is HTTP/2 and has an :authority, this value // is used. // // 3. If the request is absolute-form HTTP/1, the URI's // authority is used. // // 4. If the request has an HTTP/1 Host header, it is used. // // 5. Finally, if the Source had an SO_ORIGINAL_DST, this TCP // address is used. let addr_router = addr_stack .push(strip_header::request::layer(L5D_CLIENT_ID)) .push(strip_header::request::layer(DST_OVERRIDE_HEADER)) .push(insert::target::layer()) .push(trace::layer(|addr: &Addr| info_span!("addr", %addr))) .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), |req: &http::Request<_>| { http_request_l5d_override_dst_addr(req) .map(|override_addr| { debug!("using dst-override"); override_addr }) .or_else(|_| http_request_authority_addr(req)) .or_else(|_| http_request_host_addr(req)) .or_else(|_| http_request_orig_dst_addr(req)) .ok() }, )) .into_inner() .make(); // Share a single semaphore across all requests to signal when // the proxy is overloaded. let admission_control = svc::stack(addr_router) .push_concurrency_limit(max_in_flight) .push_load_shed(); let trace_context_layer = trace_context::layer( span_sink.map(|span_sink| SpanConverter::server(span_sink, trace_labels)), ); // Instantiates an HTTP service for each `Source` using the // shared `addr_router`. The `Source` is stored in the request's // extensions so that it can be used by the `addr_router`. let server_stack = svc::stack(svc::Shared::new(admission_control)) .push(insert::layer(move || { DispatchDeadline::after(dispatch_timeout) })) .push(insert::target::layer()) .push(errors::layer()) .push(trace::layer( |src: &tls::accept::Meta| info_span!("source", target.addr = %src.addrs.target_addr()), )) .push(trace_context_layer) .push(handle_time.layer()); let skip_ports = std::sync::Arc::new(config.outbound_ports_disable_protocol_detection.clone()); let proxy = Server::new( TransportLabels, transport_metrics, svc::stack(connect) .push(svc::map_target::layer(Endpoint::from)) .into_inner(), server_stack, config.h2_settings, drain.clone(), skip_ports.clone(), ); let no_tls: tls::Conditional<identity::Local> = Conditional::None(tls::ReasonForNoPeerName::Loopback.into()); let accept = tls::AcceptTls::new(no_tls, proxy).with_skip_ports(skip_ports); serve::spawn(listen, accept, drain); } #[derive(Copy, Clone, Debug)] struct TransportLabels; impl transport::metrics::TransportLabels<Endpoint> for TransportLabels { type Labels = transport::labels::Key; fn transport_labels(&self, endpoint: &Endpoint) -> Self::Labels
} impl transport::metrics::TransportLabels<proxy::server::Protocol> for TransportLabels { type Labels = transport::labels::Key; fn transport_labels(&self, proto: &proxy::server::Protocol) -> Self::Labels { transport::labels::Key::accept("outbound", proto.tls.peer_identity.as_ref()) } }
{ transport::labels::Key::connect("outbound", endpoint.identity.as_ref()) }
identifier_body
lib.rs
//! Configures and runs the outbound proxy. //! //! The outound proxy is responsible for routing traffic from the local //! application to external network endpoints. #![deny(warnings, rust_2018_idioms)] use linkerd2_app_core::{ classify, config::Config, dns, drain, dst::DstAddr, errors, http_request_authority_addr, http_request_host_addr, http_request_l5d_override_dst_addr, http_request_orig_dst_addr, identity, proxy::{ self, core::resolve::Resolve, discover, http::{ balance, canonicalize, client, fallback, header_from_target, insert, metrics as http_metrics, normalize_uri, profiles, retry, router, settings, strip_header, }, Server, }, reconnect, serve, spans::SpanConverter, svc, trace, trace_context, transport::{self, connect, tls, OrigDstAddr}, Addr, Conditional, DispatchDeadline, CANONICAL_DST_HEADER, DST_OVERRIDE_HEADER, L5D_CLIENT_ID, L5D_REMOTE_IP, L5D_REQUIRE_ID, L5D_SERVER_ID, }; use opencensus_proto::trace::v1 as oc; use std::collections::HashMap; use std::time::Duration; use tokio::sync::mpsc; use tower_grpc::{self as grpc, generic::client::GrpcService}; use tracing::{debug, info_span}; #[allow(dead_code)] // TODO #2597 mod add_remote_ip_on_rsp; #[allow(dead_code)] // TODO #2597 mod add_server_id_on_rsp; mod endpoint; mod orig_proto_upgrade; mod require_identity_on_endpoint; mod resolve; pub use self::endpoint::Endpoint; pub use self::resolve::resolve; const EWMA_DEFAULT_RTT: Duration = Duration::from_millis(30); const EWMA_DECAY: Duration = Duration::from_secs(10); pub fn spawn<A, R, P>( config: &Config, local_identity: tls::Conditional<identity::Local>, listen: transport::Listen<A>, resolve: R, dns_resolver: dns::Resolver, profiles_client: linkerd2_app_core::profiles::Client<P>, tap_layer: linkerd2_app_core::tap::Layer, handle_time: http_metrics::handle_time::Scope, endpoint_http_metrics: linkerd2_app_core::HttpEndpointMetricsRegistry, route_http_metrics: linkerd2_app_core::HttpRouteMetricsRegistry, retry_http_metrics: linkerd2_app_core::HttpRouteMetricsRegistry, transport_metrics: linkerd2_app_core::transport::MetricsRegistry, span_sink: Option<mpsc::Sender<oc::Span>>, drain: drain::Watch, ) where A: OrigDstAddr + Send + 'static, R: Resolve<DstAddr, Endpoint = Endpoint> + Clone + Send + Sync + 'static, R::Future: Send, R::Resolution: Send, P: GrpcService<grpc::BoxBody> + Clone + Send + Sync + 'static, P::ResponseBody: Send, <P::ResponseBody as grpc::Body>::Data: Send, P::Future: Send, { let capacity = config.outbound_router_capacity; let max_idle_age = config.outbound_router_max_idle_age; let max_in_flight = config.outbound_max_requests_in_flight; let canonicalize_timeout = config.dns_canonicalize_timeout; let dispatch_timeout = config.outbound_dispatch_timeout; let mut trace_labels = HashMap::new(); trace_labels.insert("direction".to_string(), "outbound".to_string()); // Establishes connections to remote peers (for both TCP // forwarding and HTTP proxying). let connect = svc::stack(connect::svc(config.outbound_connect_keepalive)) .push(tls::client::layer(local_identity)) .push_timeout(config.outbound_connect_timeout) .push(transport_metrics.layer_connect(TransportLabels)); let trace_context_layer = trace_context::layer( span_sink .clone() .map(|span_sink| SpanConverter::client(span_sink, trace_labels.clone())), ); // Instantiates an HTTP client for for a `client::Config` let client_stack = connect .clone() .push(client::layer(config.h2_settings)) .push(reconnect::layer({ let backoff = config.outbound_connect_backoff.clone(); move |_| Ok(backoff.stream()) })) .push(trace_context_layer) .push(normalize_uri::layer()); // A per-`outbound::Endpoint` stack that: // // 1. Records http metrics with per-endpoint labels. // 2. Instruments `tap` inspection. // 3. Changes request/response versions when the endpoint // supports protocol upgrade (and the request may be upgraded). // 4. Appends `l5d-server-id` to responses coming back iff meshed // TLS was used on the connection. // 5. Routes requests to the correct client (based on the // request version and headers). // 6. Strips any `l5d-server-id` that may have been received from // the server, before we apply our own. let endpoint_stack = client_stack .serves::<Endpoint>() .push(strip_header::response::layer(L5D_REMOTE_IP)) .push(strip_header::response::layer(L5D_SERVER_ID)) .push(strip_header::request::layer(L5D_REQUIRE_ID)) // disabled due to information leagkage //.push(add_remote_ip_on_rsp::layer()) //.push(add_server_id_on_rsp::layer()) .push(orig_proto_upgrade::layer()) .push(tap_layer.clone()) .push(http_metrics::layer::<_, classify::Response>( endpoint_http_metrics, )) .push(require_identity_on_endpoint::layer()) .push(trace::layer(|endpoint: &Endpoint| { info_span!("endpoint", ?endpoint) })); // A per-`dst::Route` layer that uses profile data to configure // a per-route layer. // // 1. The `classify` module installs a `classify::Response` // extension into each request so that all lower metrics // implementations can use the route-specific configuration. // 2. A timeout is optionally enabled if the target `dst::Route` // specifies a timeout. This goes before `retry` to cap // retries. // 3. Retries are optionally enabled depending on if the route // is retryable. let dst_route_layer = svc::layers() .push(insert::target::layer()) .push(http_metrics::layer::<_, classify::Response>( retry_http_metrics.clone(), )) .push(retry::layer(retry_http_metrics.clone())) .push(proxy::http::timeout::layer()) .push(http_metrics::layer::<_, classify::Response>( route_http_metrics, )) .push(classify::layer()) .push_buffer_pending(max_in_flight, DispatchDeadline::extract); // Routes requests to their original destination endpoints. Used as // a fallback when service discovery has no endpoints for a destination. // // If the `l5d-require-id` header is present, then that identity is // used as the server name when connecting to the endpoint. let orig_dst_router_layer = svc::layers() .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), Endpoint::from_request, )); // Resolves the target via the control plane and balances requests // over all endpoints returned from the destination service. const DISCOVER_UPDATE_BUFFER_CAPACITY: usize = 2; let balancer_layer = svc::layers() .push_spawn_ready() .push(discover::Layer::new( DISCOVER_UPDATE_BUFFER_CAPACITY, resolve, )) .push(balance::layer(EWMA_DEFAULT_RTT, EWMA_DECAY)); // If the balancer fails to be created, i.e., because it is unresolvable, // fall back to using a router that dispatches request to the // application-selected original destination. let distributor = endpoint_stack .push(fallback::layer(balancer_layer, orig_dst_router_layer)) .serves::<DstAddr>() .push(trace::layer( |dst: &DstAddr| info_span!("concrete", dst.concrete = %dst.dst_concrete()), )); // A per-`DstAddr` stack that does the following: // // 1. Adds the `CANONICAL_DST_HEADER` from the `DstAddr`. // 2. Determines the profile of the destination and applies // per-route policy. // 3. Creates a load balancer , configured by resolving the // `DstAddr` with a resolver. let dst_stack = distributor .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(profiles::router::layer(profiles_client, dst_route_layer)) .push(header_from_target::layer(CANONICAL_DST_HEADER));
// // This is shared across addr-stacks so that multiple addrs that // canonicalize to the same DstAddr use the same dst-stack service. let dst_router = dst_stack .push(trace::layer( |dst: &DstAddr| info_span!("logical", dst.logical = %dst.dst_logical()), )) .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), |req: &http::Request<_>| { req.extensions() .get::<Addr>() .cloned() .map(|addr| DstAddr::outbound(addr, settings::Settings::from_request(req))) }, )) .into_inner() .make(); // Canonicalizes the request-specified `Addr` via DNS, and // annotates each request with a refined `Addr` so that it may be // routed by the dst_router. let addr_stack = svc::stack(svc::Shared::new(dst_router)) .push(canonicalize::layer(dns_resolver, canonicalize_timeout)); // Routes requests to an `Addr`: // // 1. If the request had an `l5d-override-dst` header, this value // is used. // // 2. If the request is HTTP/2 and has an :authority, this value // is used. // // 3. If the request is absolute-form HTTP/1, the URI's // authority is used. // // 4. If the request has an HTTP/1 Host header, it is used. // // 5. Finally, if the Source had an SO_ORIGINAL_DST, this TCP // address is used. let addr_router = addr_stack .push(strip_header::request::layer(L5D_CLIENT_ID)) .push(strip_header::request::layer(DST_OVERRIDE_HEADER)) .push(insert::target::layer()) .push(trace::layer(|addr: &Addr| info_span!("addr", %addr))) .push_buffer_pending(max_in_flight, DispatchDeadline::extract) .push(router::layer( router::Config::new(capacity, max_idle_age), |req: &http::Request<_>| { http_request_l5d_override_dst_addr(req) .map(|override_addr| { debug!("using dst-override"); override_addr }) .or_else(|_| http_request_authority_addr(req)) .or_else(|_| http_request_host_addr(req)) .or_else(|_| http_request_orig_dst_addr(req)) .ok() }, )) .into_inner() .make(); // Share a single semaphore across all requests to signal when // the proxy is overloaded. let admission_control = svc::stack(addr_router) .push_concurrency_limit(max_in_flight) .push_load_shed(); let trace_context_layer = trace_context::layer( span_sink.map(|span_sink| SpanConverter::server(span_sink, trace_labels)), ); // Instantiates an HTTP service for each `Source` using the // shared `addr_router`. The `Source` is stored in the request's // extensions so that it can be used by the `addr_router`. let server_stack = svc::stack(svc::Shared::new(admission_control)) .push(insert::layer(move || { DispatchDeadline::after(dispatch_timeout) })) .push(insert::target::layer()) .push(errors::layer()) .push(trace::layer( |src: &tls::accept::Meta| info_span!("source", target.addr = %src.addrs.target_addr()), )) .push(trace_context_layer) .push(handle_time.layer()); let skip_ports = std::sync::Arc::new(config.outbound_ports_disable_protocol_detection.clone()); let proxy = Server::new( TransportLabels, transport_metrics, svc::stack(connect) .push(svc::map_target::layer(Endpoint::from)) .into_inner(), server_stack, config.h2_settings, drain.clone(), skip_ports.clone(), ); let no_tls: tls::Conditional<identity::Local> = Conditional::None(tls::ReasonForNoPeerName::Loopback.into()); let accept = tls::AcceptTls::new(no_tls, proxy).with_skip_ports(skip_ports); serve::spawn(listen, accept, drain); } #[derive(Copy, Clone, Debug)] struct TransportLabels; impl transport::metrics::TransportLabels<Endpoint> for TransportLabels { type Labels = transport::labels::Key; fn transport_labels(&self, endpoint: &Endpoint) -> Self::Labels { transport::labels::Key::connect("outbound", endpoint.identity.as_ref()) } } impl transport::metrics::TransportLabels<proxy::server::Protocol> for TransportLabels { type Labels = transport::labels::Key; fn transport_labels(&self, proto: &proxy::server::Protocol) -> Self::Labels { transport::labels::Key::accept("outbound", proto.tls.peer_identity.as_ref()) } }
// Routes request using the `DstAddr` extension.
random_line_split
lib.rs
use reqwest::Client; use serde::{Deserialize, Serialize}; pub use url::Url; /// Data types to interract with the folder API. Check [FolderApi](folder::FolderApi) for the /// available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Folder-Api) pub mod folder; /// Data types and builders to interact with the passwords API. Check /// [PasswordApi](password::PasswordApi) for the available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Password-Api) pub mod password; /// Actions available for the service API. Check [ServiceApi](service::ServiceApi) for more /// information. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Service-Api) pub mod service; /// Data types, helpers and builders to interact with the settings API. Check /// [SettingsApi](settings::SettingsApi) for the available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Settings-Api) pub mod settings; /// Data types, helpers and builders to interact with the share API. Check /// [ShareApi](share::ShareApi) for the available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Share-Api) for more /// information. pub mod share; /// Data types, helpers and builders to interact with the tag API. Check /// [TagApi](tag::TagApi) for the available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Tag-Api) pub mod tag; /// Data types and helpers to access the Token API. Check [TokenApi](token::TokenApi) for the /// available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Token-Api) pub mod token; // TODO: sort the session required methods from the non-session required mod utils; pub use utils::{QueryKind, SearchQuery}; mod private { pub trait Sealed {} impl Sealed for super::settings::UserSettings {} impl Sealed for super::settings::ServerSettings {} impl Sealed for super::settings::ClientSettings {} } #[derive(Debug)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8, } impl std::fmt::Display for Color { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { write!(fmt, "#{:02x}{:02x}{:02x}", self.red, self.green, self.blue) } } impl Serialize for Color { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(&format!( "#{:02x}{:02x}{:02x}", self.red, self.green, self.blue )) } } impl<'de> Deserialize<'de> for Color { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct StrVisitor; impl<'de> serde::de::Visitor<'de> for StrVisitor { type Value = Color; fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { write!(fmt, "an hex color of the form #abcdef as a string") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: serde::de::Error, { if value.len() == 7 { if !value.starts_with('#') { Err(E::custom("expected the color to start with `#`")) } else { let mut result = [0u8; 3]; hex::decode_to_slice(value.trim_start_matches('#'), &mut result).map_err( |e| E::custom(format!("Could not parse hex string: {:?}", e)), )?; Ok(Color { red: result[0], green: result[1], blue: result[2], }) } } else { Err(E::custom(format!( "Expected a string of length 7, got length: {}", value.len() ))) } } } deserializer.deserialize_str(StrVisitor) } } /// Errors #[derive(thiserror::Error, Debug)] pub enum Error { #[error("error in communicating with the API")] ApiError(#[from] reqwest::Error), #[error("could not connect to the passwords API")] ConnectionFailed, #[error("could not cleanly disconnect from the passwords API")] DisconnectionFailed, #[error("last shutdown time is in the future")] TimeError(#[from] std::time::SystemTimeError), #[error("setting was not valid in this context")] InvalidSetting, #[error("serde error")] Serde(#[from] serde_json::Error), #[error("endpoint error: {}", .0.message)] EndpointError(EndpointError), #[error("error in the login flow: request returned {0}")] LoginFlowError(u16), } #[derive(Serialize, Deserialize, Debug)] pub struct
{ status: String, id: u64, message: String, } #[derive(Serialize, Deserialize)] #[serde(untagged)] pub enum EndpointResponse<T> { Error(EndpointError), Success(T), } /// Represent how to first connect to a nextcloud instance /// The best way to obtain some is using [Login flow /// v2](https://docs.nextcloud.com/server/19/developer_manual/client_apis/LoginFlow/index.html#login-flow-v2). /// You can use [register_login_flow_2](LoginDetails::register_login_flow_2) to do this authentication #[derive(Serialize, Deserialize, Debug, Clone)] pub struct LoginDetails { pub server: Url, #[serde(rename = "loginName")] pub login_name: String, #[serde(rename = "appPassword")] pub app_password: String, } impl LoginDetails { /// Login with the login flow v2 to the server. The `auth_callback` is given the URL where the /// user will grant the permissions, this function should not block (or the authentication will /// never finish) waiting for the end of the login_flow. pub async fn register_login_flow_2( server: Url, mut auth_callback: impl FnMut(Url), ) -> Result<Self, Error> { #[derive(Deserialize)] struct Poll { token: String, endpoint: Url, } #[derive(Deserialize)] struct PollRequest { poll: Poll, login: Url, } #[derive(Serialize)] struct Token { token: String, } let client = reqwest::Client::new(); let resp = client .post(&format!("{}index.php/login/v2", server)) .send() .await?; if !resp.status().is_success() { return Err(Error::LoginFlowError(resp.status().as_u16())); } let resp: PollRequest = resp.json().await?; log::debug!("Got poll request for login_flow_v2"); auth_callback(resp.login); let token = Token { token: resp.poll.token, }; let details: LoginDetails = loop { let poll = client .post(resp.poll.endpoint.as_str()) .form(&token) .send() .await?; log::debug!("Polled endpoint"); match poll.status().as_u16() { 404 => { log::debug!("Not ready, need to retry"); tokio::time::delay_for(std::time::Duration::from_millis(100)).await } 200 => break poll.json().await?, code => return Err(Error::LoginFlowError(code)), } }; Ok(details) } } /// The state needed to re-connect to a nextcloud instance #[derive(Serialize, Deserialize, Clone)] pub struct ResumeState { server_url: Url, password_url: String, keepalive: u64, session_id: String, shutdown_time: std::time::SystemTime, login: String, password: String, } /// The main entrypoint to the nextcloud API pub struct AuthenticatedApi { server_url: Url, client: Client, passwords_url: String, session_id: String, keepalive: u64, login: String, password: String, } impl AuthenticatedApi { /// Return the URL of the nextcloud instance pub fn server(&self) -> &Url { &self.server_url } async fn reqwest<D: serde::Serialize>( &self, endpoint: impl AsRef<str>, method: reqwest::Method, data: D, ) -> Result<reqwest::Response, reqwest::Error> { self.client .request( method, &format!("{}/{}", self.passwords_url, endpoint.as_ref()), ) .json(&data) .header("X-API-SESSION", &self.session_id) .basic_auth(&self.login, Some(&self.password)) .send() .await } pub(crate) async fn bytes_request<D: serde::Serialize>( &self, endpoint: impl AsRef<str>, method: reqwest::Method, data: D, ) -> Result<bytes::Bytes, Error> { let r = self.reqwest(endpoint, method, data).await?; r.bytes().await.map_err(Into::into) } async fn passwords_request<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, method: reqwest::Method, data: D, ) -> Result<R, Error> { let r = self.reqwest(endpoint, method, data).await?; let text = r.text().await?; let resp = serde_json::from_str(&text).map_err(|e| { log::warn!("Response could not be read: {}", text); e })?; match resp { EndpointResponse::Success(r) => Ok(r), EndpointResponse::Error(e) => Err(Error::EndpointError(e)), } } pub(crate) async fn passwords_get<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, data: D, ) -> Result<R, Error> { self.passwords_request(endpoint, reqwest::Method::GET, data) .await } pub(crate) async fn passwords_post<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, data: D, ) -> Result<R, Error> { self.passwords_request(endpoint, reqwest::Method::POST, data) .await } pub(crate) async fn passwords_delete<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, data: D, ) -> Result<R, Error> { self.passwords_request(endpoint, reqwest::Method::DELETE, data) .await } pub(crate) async fn passwords_patch<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, data: D, ) -> Result<R, Error> { self.passwords_request(endpoint, reqwest::Method::PATCH, data) .await } /// Access the Password API #[inline] pub fn password(&self) -> password::PasswordApi<'_> { password::PasswordApi { api: self } } /// Access the Settings API #[inline] pub fn settings(&self) -> settings::SettingsApi<'_> { settings::SettingsApi { api: self } } /// Access the Folder API #[inline] pub fn folder(&self) -> folder::FolderApi<'_> { folder::FolderApi { api: self } } /// Access the Share API #[inline] pub fn share(&self) -> share::ShareApi<'_> { share::ShareApi { api: self } } #[inline] pub fn service(&self) -> service::ServiceApi<'_> { service::ServiceApi { api: self } } /// Resume a connection to the API using the state. Also gives the session ID pub async fn resume_session(resume_state: ResumeState) -> Result<(Self, String), Error> { if resume_state.shutdown_time.elapsed()?.as_secs() > resume_state.keepalive { log::debug!("Session was too old, creating new session"); AuthenticatedApi::new_session(LoginDetails { server: resume_state.server_url, login_name: resume_state.login, app_password: resume_state.password, }) .await } else { log::debug!("Calling keepalive"); #[derive(Deserialize)] struct Keepalive { success: bool, } let client = Client::new(); let api = AuthenticatedApi { server_url: resume_state.server_url, client, passwords_url: resume_state.password_url, session_id: resume_state.session_id, keepalive: resume_state.keepalive, login: resume_state.login, password: resume_state.password, }; let s: Keepalive = api.passwords_get("1.0/session/keepalive", ()).await?; assert!(s.success); let session_id = api.session_id.clone(); Ok((api, session_id)) } } /// Create a new session to the API, returns the session ID pub async fn new_session(login_details: LoginDetails) -> Result<(Self, String), Error> { #[derive(Serialize, Deserialize, Debug)] struct OpenSession { success: bool, keys: Vec<String>, } let client = Client::new(); let passwords_url = format!("{}index.php/apps/passwords/api/", login_details.server); let session_request = client .request( reqwest::Method::POST, &format!("{}/1.0/session/open", passwords_url), ) .basic_auth(&login_details.login_name, Some(&login_details.app_password)) .send() .await?; let session_id: String = session_request .headers() .get("X-API-SESSION") .expect("no api session header") .to_str() .expect("api session is not ascii") .into(); let session: OpenSession = session_request.json().await?; if !session.success { Err(Error::ConnectionFailed)? } let mut api = AuthenticatedApi { server_url: login_details.server, passwords_url, client, login: login_details.login_name, password: login_details.app_password, session_id: session_id.clone(), keepalive: 0, }; api.keepalive = api.settings().get().session_lifetime().await?; log::debug!("Session keepalive is: {}", api.keepalive); Ok((api, session_id)) } /// Disconnect from the session pub async fn disconnect(self) -> Result<(), Error> { #[derive(Deserialize)] struct CloseSession { success: bool, } let s: CloseSession = self.passwords_get("1.0/session/close", ()).await.unwrap(); if !s.success { Err(Error::DisconnectionFailed) } else { Ok(()) } } /// Get the state to be able to resume this session pub fn get_state(&self) -> ResumeState { ResumeState { server_url: self.server_url.clone(), password_url: self.passwords_url.clone(), keepalive: self.keepalive, session_id: self.session_id.clone(), login: self.login.clone(), password: self.password.clone(), shutdown_time: std::time::SystemTime::now(), } } } #[cfg(test)] mod tests {}
EndpointError
identifier_name
lib.rs
use reqwest::Client; use serde::{Deserialize, Serialize}; pub use url::Url; /// Data types to interract with the folder API. Check [FolderApi](folder::FolderApi) for the /// available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Folder-Api) pub mod folder; /// Data types and builders to interact with the passwords API. Check /// [PasswordApi](password::PasswordApi) for the available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Password-Api) pub mod password; /// Actions available for the service API. Check [ServiceApi](service::ServiceApi) for more /// information. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Service-Api) pub mod service; /// Data types, helpers and builders to interact with the settings API. Check /// [SettingsApi](settings::SettingsApi) for the available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Settings-Api) pub mod settings; /// Data types, helpers and builders to interact with the share API. Check /// [ShareApi](share::ShareApi) for the available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Share-Api) for more /// information. pub mod share; /// Data types, helpers and builders to interact with the tag API. Check /// [TagApi](tag::TagApi) for the available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Tag-Api) pub mod tag; /// Data types and helpers to access the Token API. Check [TokenApi](token::TokenApi) for the /// available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Token-Api) pub mod token; // TODO: sort the session required methods from the non-session required mod utils; pub use utils::{QueryKind, SearchQuery}; mod private { pub trait Sealed {} impl Sealed for super::settings::UserSettings {} impl Sealed for super::settings::ServerSettings {} impl Sealed for super::settings::ClientSettings {} } #[derive(Debug)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8, } impl std::fmt::Display for Color { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { write!(fmt, "#{:02x}{:02x}{:02x}", self.red, self.green, self.blue) } } impl Serialize for Color { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(&format!( "#{:02x}{:02x}{:02x}", self.red, self.green, self.blue )) } } impl<'de> Deserialize<'de> for Color { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct StrVisitor; impl<'de> serde::de::Visitor<'de> for StrVisitor { type Value = Color; fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { write!(fmt, "an hex color of the form #abcdef as a string") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: serde::de::Error, { if value.len() == 7 { if !value.starts_with('#') { Err(E::custom("expected the color to start with `#`")) } else { let mut result = [0u8; 3]; hex::decode_to_slice(value.trim_start_matches('#'), &mut result).map_err( |e| E::custom(format!("Could not parse hex string: {:?}", e)), )?; Ok(Color { red: result[0], green: result[1], blue: result[2], }) } } else { Err(E::custom(format!( "Expected a string of length 7, got length: {}", value.len() ))) } } } deserializer.deserialize_str(StrVisitor) } } /// Errors #[derive(thiserror::Error, Debug)] pub enum Error { #[error("error in communicating with the API")] ApiError(#[from] reqwest::Error), #[error("could not connect to the passwords API")] ConnectionFailed, #[error("could not cleanly disconnect from the passwords API")] DisconnectionFailed, #[error("last shutdown time is in the future")] TimeError(#[from] std::time::SystemTimeError), #[error("setting was not valid in this context")] InvalidSetting, #[error("serde error")] Serde(#[from] serde_json::Error), #[error("endpoint error: {}", .0.message)] EndpointError(EndpointError), #[error("error in the login flow: request returned {0}")] LoginFlowError(u16), } #[derive(Serialize, Deserialize, Debug)] pub struct EndpointError { status: String, id: u64, message: String, } #[derive(Serialize, Deserialize)] #[serde(untagged)] pub enum EndpointResponse<T> { Error(EndpointError), Success(T), } /// Represent how to first connect to a nextcloud instance /// The best way to obtain some is using [Login flow /// v2](https://docs.nextcloud.com/server/19/developer_manual/client_apis/LoginFlow/index.html#login-flow-v2). /// You can use [register_login_flow_2](LoginDetails::register_login_flow_2) to do this authentication #[derive(Serialize, Deserialize, Debug, Clone)] pub struct LoginDetails { pub server: Url, #[serde(rename = "loginName")] pub login_name: String, #[serde(rename = "appPassword")] pub app_password: String, } impl LoginDetails { /// Login with the login flow v2 to the server. The `auth_callback` is given the URL where the /// user will grant the permissions, this function should not block (or the authentication will /// never finish) waiting for the end of the login_flow. pub async fn register_login_flow_2( server: Url, mut auth_callback: impl FnMut(Url), ) -> Result<Self, Error> { #[derive(Deserialize)] struct Poll { token: String, endpoint: Url, } #[derive(Deserialize)] struct PollRequest { poll: Poll, login: Url, } #[derive(Serialize)] struct Token { token: String, } let client = reqwest::Client::new(); let resp = client .post(&format!("{}index.php/login/v2", server)) .send() .await?; if !resp.status().is_success() { return Err(Error::LoginFlowError(resp.status().as_u16())); } let resp: PollRequest = resp.json().await?; log::debug!("Got poll request for login_flow_v2"); auth_callback(resp.login); let token = Token { token: resp.poll.token, }; let details: LoginDetails = loop { let poll = client .post(resp.poll.endpoint.as_str()) .form(&token) .send() .await?; log::debug!("Polled endpoint"); match poll.status().as_u16() { 404 => { log::debug!("Not ready, need to retry"); tokio::time::delay_for(std::time::Duration::from_millis(100)).await } 200 => break poll.json().await?, code => return Err(Error::LoginFlowError(code)), } }; Ok(details) } } /// The state needed to re-connect to a nextcloud instance #[derive(Serialize, Deserialize, Clone)] pub struct ResumeState { server_url: Url, password_url: String, keepalive: u64, session_id: String, shutdown_time: std::time::SystemTime, login: String, password: String, } /// The main entrypoint to the nextcloud API pub struct AuthenticatedApi { server_url: Url, client: Client, passwords_url: String, session_id: String, keepalive: u64, login: String, password: String, } impl AuthenticatedApi { /// Return the URL of the nextcloud instance pub fn server(&self) -> &Url { &self.server_url } async fn reqwest<D: serde::Serialize>( &self, endpoint: impl AsRef<str>, method: reqwest::Method, data: D, ) -> Result<reqwest::Response, reqwest::Error> { self.client .request( method, &format!("{}/{}", self.passwords_url, endpoint.as_ref()), ) .json(&data) .header("X-API-SESSION", &self.session_id) .basic_auth(&self.login, Some(&self.password)) .send() .await } pub(crate) async fn bytes_request<D: serde::Serialize>( &self, endpoint: impl AsRef<str>, method: reqwest::Method, data: D, ) -> Result<bytes::Bytes, Error> { let r = self.reqwest(endpoint, method, data).await?; r.bytes().await.map_err(Into::into) } async fn passwords_request<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, method: reqwest::Method, data: D, ) -> Result<R, Error> { let r = self.reqwest(endpoint, method, data).await?; let text = r.text().await?; let resp = serde_json::from_str(&text).map_err(|e| { log::warn!("Response could not be read: {}", text); e })?; match resp { EndpointResponse::Success(r) => Ok(r), EndpointResponse::Error(e) => Err(Error::EndpointError(e)), } } pub(crate) async fn passwords_get<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, data: D, ) -> Result<R, Error> { self.passwords_request(endpoint, reqwest::Method::GET, data) .await } pub(crate) async fn passwords_post<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, data: D, ) -> Result<R, Error> { self.passwords_request(endpoint, reqwest::Method::POST, data) .await } pub(crate) async fn passwords_delete<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, data: D, ) -> Result<R, Error> { self.passwords_request(endpoint, reqwest::Method::DELETE, data) .await } pub(crate) async fn passwords_patch<R: serde::de::DeserializeOwned, D: serde::Serialize>( &self, endpoint: impl AsRef<str>, data: D, ) -> Result<R, Error> { self.passwords_request(endpoint, reqwest::Method::PATCH, data) .await } /// Access the Password API #[inline] pub fn password(&self) -> password::PasswordApi<'_> { password::PasswordApi { api: self } } /// Access the Settings API #[inline] pub fn settings(&self) -> settings::SettingsApi<'_> { settings::SettingsApi { api: self } } /// Access the Folder API #[inline] pub fn folder(&self) -> folder::FolderApi<'_> { folder::FolderApi { api: self } } /// Access the Share API #[inline] pub fn share(&self) -> share::ShareApi<'_> { share::ShareApi { api: self } } #[inline] pub fn service(&self) -> service::ServiceApi<'_> { service::ServiceApi { api: self } } /// Resume a connection to the API using the state. Also gives the session ID pub async fn resume_session(resume_state: ResumeState) -> Result<(Self, String), Error> { if resume_state.shutdown_time.elapsed()?.as_secs() > resume_state.keepalive { log::debug!("Session was too old, creating new session"); AuthenticatedApi::new_session(LoginDetails { server: resume_state.server_url, login_name: resume_state.login, app_password: resume_state.password, }) .await } else { log::debug!("Calling keepalive"); #[derive(Deserialize)] struct Keepalive { success: bool, } let client = Client::new(); let api = AuthenticatedApi { server_url: resume_state.server_url, client, passwords_url: resume_state.password_url, session_id: resume_state.session_id, keepalive: resume_state.keepalive, login: resume_state.login, password: resume_state.password, }; let s: Keepalive = api.passwords_get("1.0/session/keepalive", ()).await?; assert!(s.success); let session_id = api.session_id.clone(); Ok((api, session_id)) } } /// Create a new session to the API, returns the session ID pub async fn new_session(login_details: LoginDetails) -> Result<(Self, String), Error> { #[derive(Serialize, Deserialize, Debug)] struct OpenSession { success: bool, keys: Vec<String>, } let client = Client::new(); let passwords_url = format!("{}index.php/apps/passwords/api/", login_details.server); let session_request = client .request( reqwest::Method::POST, &format!("{}/1.0/session/open", passwords_url), ) .basic_auth(&login_details.login_name, Some(&login_details.app_password)) .send() .await?; let session_id: String = session_request .headers() .get("X-API-SESSION") .expect("no api session header") .to_str() .expect("api session is not ascii") .into(); let session: OpenSession = session_request.json().await?; if !session.success { Err(Error::ConnectionFailed)? } let mut api = AuthenticatedApi { server_url: login_details.server, passwords_url, client, login: login_details.login_name, password: login_details.app_password, session_id: session_id.clone(), keepalive: 0, }; api.keepalive = api.settings().get().session_lifetime().await?; log::debug!("Session keepalive is: {}", api.keepalive);
/// Disconnect from the session pub async fn disconnect(self) -> Result<(), Error> { #[derive(Deserialize)] struct CloseSession { success: bool, } let s: CloseSession = self.passwords_get("1.0/session/close", ()).await.unwrap(); if !s.success { Err(Error::DisconnectionFailed) } else { Ok(()) } } /// Get the state to be able to resume this session pub fn get_state(&self) -> ResumeState { ResumeState { server_url: self.server_url.clone(), password_url: self.passwords_url.clone(), keepalive: self.keepalive, session_id: self.session_id.clone(), login: self.login.clone(), password: self.password.clone(), shutdown_time: std::time::SystemTime::now(), } } } #[cfg(test)] mod tests {}
Ok((api, session_id)) }
random_line_split
infinite-article-origin.js
/* * jQuery throttle / debounce - v1.1 - 3/7/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function (b, c) { var $ = b.jQuery || b.Cowboy || (b.Cowboy = {}), a; $.throttle = a = function (e, f, j, i) { var h, d = 0; if (typeof f !== "boolean") { i = j; j = f; f = c } function g() { var o = this, m = +new Date() - d, n = arguments; function l() { d = +new Date(); j.apply(o, n) } function k() { h = c } if (i && !h) { l() } h && clearTimeout(h); if (i === c && m > e) { l() } else { if (f !== true) { h = setTimeout(i ? k : l, i === c ? e - m : e) } } } if ($.guid) { g.guid = j.guid = j.guid || $.guid++ } return g }; $.debounce = function (d, e, f) { return f === c ? a(d, e, false) : a(d, f, e !== false) } })(this); /** * Set up the object that will hold our infinte scroll code * @type {Object} */ var webmd = window.webmd || {}; // run just 1 time - using closure. webmd.getCurrentUrl = webmd.getCurrentUrl || (function () { var url = document.location.href.replace(/[\?#].*$/, ''); return function () { return url; }; }.call()); webmd.Scrolling = { Debounce: 'Debounce', DebounceNumber: 500 }; webmd.getDebounceNumber = function (str) { var qs = unescape(str).split('&').filter(function (param) { return param.indexOf(webmd.Scrolling.Debounce) !== -1; })[0]; var no = 0; if (qs) { no = parseInt(qs.replace(/^[\?#]?\w+=/, '')); } return no; }; (function ($) { /** * Doing some checks here. If the program is sponsored or a special report we add * a class so we can handle it in a custom manner */ if ((typeof window.s_sponsor_program != 'undefined' && window.s_sponsor_program)) { $('html').addClass('inProgram'); } webmd.infiniteScroll = webmd.infiniteScroll || { index: 0, init: function (obj) { // If there aren't any pages in the // article, then we don't need to start // an infinite article if (!this.hasPages()) { return false; } // Start a count of DFP ads so we can // give each one a unique ID this.dfpAdNumber = 0; this.opts = $.extend({}, this.defaults, obj); this.enableInfiniteScroll(); this.setUpAdContainers(); this.bindEvents(); }, /** * Handles initial pageview on load. If there * is only one page, we pass 99, otherwise, we * pass the page number we are on * @return {Boolean} If there ARE pages, return False, * otherwise, return true. */ hasPages: function () { var pcount = $('section.page').length, self = this; if ((pcount === 1) || pcount === 0) { webmd.metrics.dpv({ iCount: 99, pageName: webmd.getCurrentUrl(), refresh: false }); // append end-of-article ad since this is a 1-page article var adContainer = $('<div/>', {class: 'inStreamAd'}); $('.article .attribution').append(adContainer); // cache the value of the pageview id so we can later use to update the pvid of the bottom ad call window.pvid = window.s_pageview_id; return false; } else { webmd.metrics.dpv({ iCount: 1, pageName: webmd.getCurrentUrl(), refresh: false }); // william: var dno = webmd.getDebounceNumber(document.location.search); if (!isNaN(dno)) { webmd.Scrolling.DebounceNumber = dno; } console.log('hasPages should be here: ', webmd.Scrolling.DebounceNumber); return true; } }, /** * Pretty self explanatory here. We do all of our binding * in here, in an up front manner, so we can keep it organized * and clean. */ bindEvents: function () { var self = this; /** * Attach listener to scroll event so we can do our infinite * scroll stuff. */ self.opts.scrollTarget.on('scroll', function () { /** * The container that is defined in the init config has a * data attr [data-infinite-scroll]. This data attr is a * bool value and will tell you if inifinite scroll is enabled * or disabled. * Refere to -> enableInfiniteScroll function */ if (self.opts.container.data('infinite-scroll')) { /** * This checks to see if we have scrolled far enough * down the page to start loading in the next page. */ self.checkForLoad(); } }); self.opts.container.on('loadContent', function () { /** * Temporarily disable infinite scroll so we don't * keep firing it while we load the content we need. * This is expecially helpful when loading in AJAX content. */ self.disableInfiniteScroll(); /** * Currently uses non ajax call by default, but this * can be set up to use an ajax call. */ self.loadContent(); }); /** * When we have the content we need, have the ads loaded, and * we have fired a page view call, the contentLoaded event gets * fired. When it's fired we know it's ok to re-enable infnite scroll * and get ready to do the next page. */ self.opts.container.on('contentLoaded', function () { self.enableInfiniteScroll(); }); /** * Disables infinite scrolling when the content is loading * or when there are no pages left to load. */ self.opts.container.on('disableInfinite', function () { self.disableInfiniteScroll(); }); }, /** * Iterate through the pages and insert ad container divs * so we can later populate those divs with ads as we scroll */ setUpAdContainers: function () { var self = this; var lastPageNum = $('section.page:last').data('page-number'); /** * Loop through all the pages and add an Ad container to them * This lets us easily give the container an ID to target them * later. COULD PROB BE IN THE XSL, but we did it here bc * the number of ads was changing a lot. */ $('section.page').each(function (i, elm) { var adContainer = $('<div/>', {class: 'inStreamAd'}), $elm = $(elm), pageNum = $elm.data('page-number'); /** * if it's the first page, go ahead and put an ad * in since the page is already showing. */ if ($elm.is('#page-1')) { $elm.append(adContainer); setTimeout(function () { self.insertAd($('#page-1'), true); }, 0); /** * we have to put the ad in a different place if * it's the last page. */ } else if ($(elm).data('page-number') === lastPageNum) { $(elm).addClass('last'); $('.article .attribution').append(adContainer); } else { $elm.append(adContainer); } }); }, /** * Set up so Infinite scroll is backwards compatible * with DE. * ------ NOT REALLY NEEDED NOW FOR CORE SINCE WE ROLLED OUT DFP ------ * @return {String} The ad server type, Either DFP or Default */ checkAdServerType: function () { this.adServer = 'defaultServer'; if (typeof webmd.ads2 != 'undefined' && webmd.ads2.isInitialized()) { this.adServer = 'dfp'; } else { this.adServer = 'defaultServer'; } return this.adServer; }, /** * We check the amount we have scrolled and see if * that is far enough to load the next piece of infinite * content. */ checkForLoad: function () { var target = this.opts.scrollTarget, container = this.opts.container, windowHeight = window.innerHeight ? window.innerHeight : $(window).height(), contentTop = $(this.opts.content + ':visible:last').offset().top, diff = windowHeight - $(this.opts.content + ':visible:last').height(), mayLoadContent = $(window).scrollTop() >= (contentTop - diff - this.opts.heightOffset); /** * If we've scrolled far enough, trigger the load content event * signaling that it's ok to load content. */ if (mayLoadContent) { this.opts.container.trigger('loadContent'); } }, /** * Used to make sure the content is loaded before * a page is faded in. Goes with the next function that * disables infinite scroll. Useful when Ajaxing content in */ enableInfiniteScroll: function () { this.opts.container.data('infinite-scroll', true); }, /** * Disables infinite scrolling when the content is loading * or when there are no pages left to load. */ disableInfiniteScroll: function () { this.opts.container.data('infinite-scroll', false); }, /** * Gets called when the page is a scroll * position that is ready to load content. * It calls a default of nonAjaxCall since we currently * have all the pages upfront. */ loadContent: function () { this.nonAjaxCall(); }, /** * Shows the next page * @param {Object} $elm jquery object of current page */ showNext: function ($elm) { $elm.next().show(); }, /** * Makes the metrics call to webmd.metrics.dpv * @param {Objec} Object with params for the metrics call. */ metricsCall: function (obj) { webmd.metrics.dpv(obj); }, /** * Checks to see which ad system we are using and * then inserts the add into the appropriate page * @param {Object} target jQuery object */ insertAd: function (target, firstAd) { if (this.checkAdServerType() === 'defaultServer') { this.callDefaultAd(target); } else { this.callDFPHouseAd(target); } }, /** * Creates a default ad with the DE server * @param {Object} target jQuery selector object */ callDefaultAd: function (target) { // Start function to create new pvid function replaceAdParam(srcStr, pName, pValue) { var paramRegEx = new RegExp("\\b" + pName + "=[^&#\"']*"); srcStr = srcStr.replace(paramRegEx, pName + "=" + pValue); return srcStr; } // Random Num Generator for pvid function randomNum() { var randomNumber = Math.round(999999999 * Math.random()); return randomNumber; } var pvid = this.s_pageview_id, adTag = $('#top_ad script')[1].src, transId = randomNum(), tileId = randomNum(); // Reprocess AdTag adTag = adTag.replace(/amp;/g, ''); adTag = adTag.replace('js.ng', 'html.ng'); adTag = replaceAdParam(adTag, "pvid", pvid); adTag = replaceAdParam(adTag, "transactionID", transId); adTag = replaceAdParam(adTag, "tile", tileId); /** * Create an iFrame that will hold our ad * @type {Object} */ var $iframe = $('<iframe/>').attr({ src: adTag, height: 50, width: 320, margin: 0, padding: 0, marginwidth: 0, marginheight: 0, frameborder: 0, scrolling: 'no', marginLeft: '-20px', class: 'dynamic-house-ad' }); if (target.is('.last')) { $('.attribution .inStreamAd') .append('<div class="ad_label">Advertisement</div>') .append($iframe); } else { $('.inStreamAd', target) .append('<div class="ad_label">Advertisement</div>') .append($iframe); } }, /** * Creates an ad call that goes with DFP ad server * @param {Object}} target jQuery selector object for * where the ad will get inserted */ callDFPHouseAd: function (target) { var num = $(target).data('page-number') || 'ad-1', adId = 'infinite-ad-' + num, adContainer = $(target).find('.inStreamAd'); if (target.is('.last')) { adContainer = $('.attribution .inStreamAd'); // cache the value of the pageview id so we can later use to update the pvid of the bottom ad call window.pvid = window.s_pageview_id; } var domStr = '<div class="ad_label">Advertisement</div><div id="' + adId + '">'; adContainer.append(domStr); // force a new co-relation id for dynamic ads calls if (typeof googletag != 'undefined') { googletag.cmd.push(function () { googletag.pubads().updateCorrelator(); }); } /** * pass the number of the ad in the series. * example: for a page with seven 2026 ad units, setting pg = 4 tells the ad server that this is the fourth 2026 ad in the series */ webmd.ads2.setPageTarget('pg', isNaN(num) ? 1 : num); webmd.ads2.defineAd({ id: adId, pos: '2026', sizes: [[300, 50], [300, 51], [300, 250], [300, 253], [320, 50], [320, 51]] }); // keep track of the current page number this.index = num; }, /** * We need a new pvid for each infinite page * ad call. This creates that. * @return {Number} */ createInfinitePageviewId: function () { var self = this; // getting the date, getting the seconds from epoch, slicing off the first two characters as we only want 11 here var timestamp = new Date().getTime().toString().slice(2), // making an 8 digit random number (using toFixed to make sure it's always 8) randomNumber = Math.random().toFixed(8).substr(2, 8); // set the global variable to the 19 digit page view id self.s_pageview_id = timestamp + randomNumber; }, /** * If we are not making an Ajax call for the content, * then we just used the content that is on the page but * hidden on page load. * ---- IT'S CURRENTLY THE DEFAULT ---- */ nonAjaxCall: function () { var self = this; if (self.opts.beforeLoad !== null) { self.opts.beforeLoad(self.opts.content); } if (self.opts.afterLoad !== null) { self.opts.afterLoad($(self.opts.content)); } }, defaults: { moduleCount: -1, loadPattern: null, afterLoad: null, beforeLoad: null, container: null, content: 'page.html', contentData: {}, heightOffset: 0, scrollTarget: $(window), pageUrl: null } }; })(jQuery); // Init for Infinite Scroll Plugin $(function () { /** * Get the list of funded urls for which we want to allow in-article placements. * https://jira.webmd.net/browse/PPE-23261 * @param {string} dctmId The documentum id of the shared module containing list of funded urls */ var url = 'http://www' + webmd.url.getLifecycle() + '.m.webmd.com/modules/sponsor-box?id=091e9c5e812b356a'; $.ajax({ dataType: 'html', url: url, success: function (data) { var exclusionsList = $(data).find('.exception-list').html(); //create a new script tag in the DOM var s = document.createElement("script"); s.type = "text/javascript"; //put the exclusions object in the new script tag s.innerHTML = exclusionsList; //append nativeAdObj to the DOM $('head').append(s); }, error: function (xhr, status, error) { webmd.debug(xhr, status); }, complete: function () { webmd.nativeAd.init({container: '#page-1'}); } }); /** * huge if statement to see if we are going to run the infinite * code. This is used since revenue products are still paginated * as well as some special reports. * The first part of the if statement handles what happens when * we don't run infinite. Instead we build out pagination dynamically */ /** JIRA PPE-8670: added an extra condition to use infinite layout if article is sponsored & topic-targeted **/ if ((window.s_sponsor_program && window.s_package_type.indexOf('topic targeted') < 0) || window.s_package_name == "Mobile Ebola Virus Infection") { webmd.debug('Dont do infinite bc we are sponsored or special report'); webmd.infiniteScroll.hasPages(); //Get the url params so we can see what page //number we are on. Used to build out pagination links var urlParam = webmd.url.getParams(), lastPage = $('.page:last').data('page-number'), curPage = urlParam.page, prevPage, nextPage; //HTML for our pagination var paginationTemplate = '<div class="pagination"><div class="previous icon-arrow-left"><a href="#"></a></div><div class="next icon-arrow-right"><a href="#"></a></div><div class="pagination-wrapper"><div class="pagination-title">Page 1 of 4</div></div></div>'; //Insert our pagination after all the article text $('#textArea').after($(paginationTemplate)); if (typeof curPage === 'undefined' || curPage === 1 || location.search.indexOf('page=1') !== -1) { $('#textArea .loading_medium_png').remove(); $('.pagination').find('.previous').addClass('disabled'); $('.pagination').find('.previous a').on('click', function (e) { e.preventDefault(); }); $('.pagination').find('.pagination-title').text('Page 1' + ' of ' + lastPage); $('.pagination').find('.next a').attr('href', '?page=2'); } else { prevPage = parseInt(curPage) - 1; nextPage = parseInt(curPage) + 1; $('.pagination').find('.pagination-title').text('Page ' + parseInt(curPage) + ' of ' + lastPage); $('.pagination').find('.previous a').attr('href', '?page=' + prevPage); $('.pagination').find('.next a').attr('href', '?page=' + nextPage); if (parseInt(curPage) === lastPage) { $('.pagination').find('.next').addClass('disabled'); $('.pagination').find('.next a').on('click', function (e) { e.preventDefault(); }); } } var pageNumber = 1; if (typeof webmd.url.getParam('page') != 'undefined') { pageNumber = webmd.url.getParam('page'); } // hide from app view if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#page-' + pageNumber}); } } else { /** * This callback gets fired each time the document height changes. */ window.onElementHeightChange = function (elm, callback) { var lastHeight = elm.clientHeight, newHeight; (function run() { newHeight = elm.clientHeight; if (lastHeight != newHeight) { callback(); } lastHeight = newHeight; if (elm.onElementHeightChangeTimer) { clearTimeout(elm.onElementHeightChangeTimer); } elm.onElementHeightChangeTimer = setTimeout(run, 200); })(); }; /** * We need to recalculate the trigger point for every waypoint as we update the dom. */ window.onElementHeightChange(document.body, function () { jQuery.waypoints('refresh'); }); var articleInfinite = Object.create(webmd.infiniteScroll); articleInfinite.init({ container: $('.article.infinite'), content: '.page', heightOffset: 200, pageUrl: webmd.getCurrentUrl(), beforeLoad: function (contentClass) { $('.infinite .page:visible:last').next(); }, afterLoad: function (elementsLoaded) { var target = $('.infinite .page:visible:last'), targetNext = $(elementsLoaded).filter(':visible:last').next('.page'), hasAdhesive = false; if (targetNext.length === 0)
var targetNextNumber = targetNext.data('page-number'); webmd.infiniteScroll.showNext(target); var pageNumber = parseInt(targetNext.attr('id').slice(-1)); if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#' + targetNext.attr('id')}); } clearTimeout(window.pageViewTimeout); $(targetNext).waypoint(function () { window.pageViewTimeout = setTimeout(function () { webmd.infiniteScroll.metricsCall({ moduleName: 'pg-n-swipe', pageName: this.pageUrl, iCount: targetNextNumber, refresh: false }); if (!$('body').hasClass('adhesive_ad')) { if (targetNext.find('.inStreamAd').length > 0 || targetNext.is('.last')) { webmd.infiniteScroll.insertAd(targetNext, false); } } }, 0); }, { offset: '50%', triggerOnce: true }); this.container.trigger('contentLoaded'); } }); $('footer.attribution').waypoint(function () { setTimeout(function () { // force a new co-relation id if (typeof googletag != 'undefined') { googletag.pubads().updateCorrelator(); } /** * we need to manually update the pvid for the bottom ad to match the pvid of the top ad since technically they are on same page. * Also pass ad identifier to DFP (see https://jira.webmd.net/browse/PPE-53106). */ webmd.ads2.setPageTarget({ 'pvid': window.pvid || window.s_pageview_id, 'pg': $('.page').length + 1, 'al': 'cons_bot' }); webmd.ads2.defineAd({ id: 'ads2-pos-2026-ad_btm', pos: '2026', sizes: [[300, 50], [300, 51], [300, 250], [300, 253], [320, 50], [320, 51]], }); /** * clear the 'al' page target here after the bottom ad call so it doesn't get passed in subsequent ad calls. */ if (webmd.ads2.pageTarget.hasOwnProperty('al')) { delete webmd.ads2.pageTargets.al; googletag.pubads().clearTargeting('al'); } }, 500); }, { offset: '50%', triggerOnce: true }); } });
{ articleInfinite.opts.container.trigger('disableInfinite'); return; }
conditional_block
infinite-article-origin.js
/* * jQuery throttle / debounce - v1.1 - 3/7/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function (b, c) { var $ = b.jQuery || b.Cowboy || (b.Cowboy = {}), a; $.throttle = a = function (e, f, j, i) { var h, d = 0; if (typeof f !== "boolean") { i = j; j = f; f = c } function g() { var o = this, m = +new Date() - d, n = arguments; function l() { d = +new Date(); j.apply(o, n) } function k()
if (i && !h) { l() } h && clearTimeout(h); if (i === c && m > e) { l() } else { if (f !== true) { h = setTimeout(i ? k : l, i === c ? e - m : e) } } } if ($.guid) { g.guid = j.guid = j.guid || $.guid++ } return g }; $.debounce = function (d, e, f) { return f === c ? a(d, e, false) : a(d, f, e !== false) } })(this); /** * Set up the object that will hold our infinte scroll code * @type {Object} */ var webmd = window.webmd || {}; // run just 1 time - using closure. webmd.getCurrentUrl = webmd.getCurrentUrl || (function () { var url = document.location.href.replace(/[\?#].*$/, ''); return function () { return url; }; }.call()); webmd.Scrolling = { Debounce: 'Debounce', DebounceNumber: 500 }; webmd.getDebounceNumber = function (str) { var qs = unescape(str).split('&').filter(function (param) { return param.indexOf(webmd.Scrolling.Debounce) !== -1; })[0]; var no = 0; if (qs) { no = parseInt(qs.replace(/^[\?#]?\w+=/, '')); } return no; }; (function ($) { /** * Doing some checks here. If the program is sponsored or a special report we add * a class so we can handle it in a custom manner */ if ((typeof window.s_sponsor_program != 'undefined' && window.s_sponsor_program)) { $('html').addClass('inProgram'); } webmd.infiniteScroll = webmd.infiniteScroll || { index: 0, init: function (obj) { // If there aren't any pages in the // article, then we don't need to start // an infinite article if (!this.hasPages()) { return false; } // Start a count of DFP ads so we can // give each one a unique ID this.dfpAdNumber = 0; this.opts = $.extend({}, this.defaults, obj); this.enableInfiniteScroll(); this.setUpAdContainers(); this.bindEvents(); }, /** * Handles initial pageview on load. If there * is only one page, we pass 99, otherwise, we * pass the page number we are on * @return {Boolean} If there ARE pages, return False, * otherwise, return true. */ hasPages: function () { var pcount = $('section.page').length, self = this; if ((pcount === 1) || pcount === 0) { webmd.metrics.dpv({ iCount: 99, pageName: webmd.getCurrentUrl(), refresh: false }); // append end-of-article ad since this is a 1-page article var adContainer = $('<div/>', {class: 'inStreamAd'}); $('.article .attribution').append(adContainer); // cache the value of the pageview id so we can later use to update the pvid of the bottom ad call window.pvid = window.s_pageview_id; return false; } else { webmd.metrics.dpv({ iCount: 1, pageName: webmd.getCurrentUrl(), refresh: false }); // william: var dno = webmd.getDebounceNumber(document.location.search); if (!isNaN(dno)) { webmd.Scrolling.DebounceNumber = dno; } console.log('hasPages should be here: ', webmd.Scrolling.DebounceNumber); return true; } }, /** * Pretty self explanatory here. We do all of our binding * in here, in an up front manner, so we can keep it organized * and clean. */ bindEvents: function () { var self = this; /** * Attach listener to scroll event so we can do our infinite * scroll stuff. */ self.opts.scrollTarget.on('scroll', function () { /** * The container that is defined in the init config has a * data attr [data-infinite-scroll]. This data attr is a * bool value and will tell you if inifinite scroll is enabled * or disabled. * Refere to -> enableInfiniteScroll function */ if (self.opts.container.data('infinite-scroll')) { /** * This checks to see if we have scrolled far enough * down the page to start loading in the next page. */ self.checkForLoad(); } }); self.opts.container.on('loadContent', function () { /** * Temporarily disable infinite scroll so we don't * keep firing it while we load the content we need. * This is expecially helpful when loading in AJAX content. */ self.disableInfiniteScroll(); /** * Currently uses non ajax call by default, but this * can be set up to use an ajax call. */ self.loadContent(); }); /** * When we have the content we need, have the ads loaded, and * we have fired a page view call, the contentLoaded event gets * fired. When it's fired we know it's ok to re-enable infnite scroll * and get ready to do the next page. */ self.opts.container.on('contentLoaded', function () { self.enableInfiniteScroll(); }); /** * Disables infinite scrolling when the content is loading * or when there are no pages left to load. */ self.opts.container.on('disableInfinite', function () { self.disableInfiniteScroll(); }); }, /** * Iterate through the pages and insert ad container divs * so we can later populate those divs with ads as we scroll */ setUpAdContainers: function () { var self = this; var lastPageNum = $('section.page:last').data('page-number'); /** * Loop through all the pages and add an Ad container to them * This lets us easily give the container an ID to target them * later. COULD PROB BE IN THE XSL, but we did it here bc * the number of ads was changing a lot. */ $('section.page').each(function (i, elm) { var adContainer = $('<div/>', {class: 'inStreamAd'}), $elm = $(elm), pageNum = $elm.data('page-number'); /** * if it's the first page, go ahead and put an ad * in since the page is already showing. */ if ($elm.is('#page-1')) { $elm.append(adContainer); setTimeout(function () { self.insertAd($('#page-1'), true); }, 0); /** * we have to put the ad in a different place if * it's the last page. */ } else if ($(elm).data('page-number') === lastPageNum) { $(elm).addClass('last'); $('.article .attribution').append(adContainer); } else { $elm.append(adContainer); } }); }, /** * Set up so Infinite scroll is backwards compatible * with DE. * ------ NOT REALLY NEEDED NOW FOR CORE SINCE WE ROLLED OUT DFP ------ * @return {String} The ad server type, Either DFP or Default */ checkAdServerType: function () { this.adServer = 'defaultServer'; if (typeof webmd.ads2 != 'undefined' && webmd.ads2.isInitialized()) { this.adServer = 'dfp'; } else { this.adServer = 'defaultServer'; } return this.adServer; }, /** * We check the amount we have scrolled and see if * that is far enough to load the next piece of infinite * content. */ checkForLoad: function () { var target = this.opts.scrollTarget, container = this.opts.container, windowHeight = window.innerHeight ? window.innerHeight : $(window).height(), contentTop = $(this.opts.content + ':visible:last').offset().top, diff = windowHeight - $(this.opts.content + ':visible:last').height(), mayLoadContent = $(window).scrollTop() >= (contentTop - diff - this.opts.heightOffset); /** * If we've scrolled far enough, trigger the load content event * signaling that it's ok to load content. */ if (mayLoadContent) { this.opts.container.trigger('loadContent'); } }, /** * Used to make sure the content is loaded before * a page is faded in. Goes with the next function that * disables infinite scroll. Useful when Ajaxing content in */ enableInfiniteScroll: function () { this.opts.container.data('infinite-scroll', true); }, /** * Disables infinite scrolling when the content is loading * or when there are no pages left to load. */ disableInfiniteScroll: function () { this.opts.container.data('infinite-scroll', false); }, /** * Gets called when the page is a scroll * position that is ready to load content. * It calls a default of nonAjaxCall since we currently * have all the pages upfront. */ loadContent: function () { this.nonAjaxCall(); }, /** * Shows the next page * @param {Object} $elm jquery object of current page */ showNext: function ($elm) { $elm.next().show(); }, /** * Makes the metrics call to webmd.metrics.dpv * @param {Objec} Object with params for the metrics call. */ metricsCall: function (obj) { webmd.metrics.dpv(obj); }, /** * Checks to see which ad system we are using and * then inserts the add into the appropriate page * @param {Object} target jQuery object */ insertAd: function (target, firstAd) { if (this.checkAdServerType() === 'defaultServer') { this.callDefaultAd(target); } else { this.callDFPHouseAd(target); } }, /** * Creates a default ad with the DE server * @param {Object} target jQuery selector object */ callDefaultAd: function (target) { // Start function to create new pvid function replaceAdParam(srcStr, pName, pValue) { var paramRegEx = new RegExp("\\b" + pName + "=[^&#\"']*"); srcStr = srcStr.replace(paramRegEx, pName + "=" + pValue); return srcStr; } // Random Num Generator for pvid function randomNum() { var randomNumber = Math.round(999999999 * Math.random()); return randomNumber; } var pvid = this.s_pageview_id, adTag = $('#top_ad script')[1].src, transId = randomNum(), tileId = randomNum(); // Reprocess AdTag adTag = adTag.replace(/amp;/g, ''); adTag = adTag.replace('js.ng', 'html.ng'); adTag = replaceAdParam(adTag, "pvid", pvid); adTag = replaceAdParam(adTag, "transactionID", transId); adTag = replaceAdParam(adTag, "tile", tileId); /** * Create an iFrame that will hold our ad * @type {Object} */ var $iframe = $('<iframe/>').attr({ src: adTag, height: 50, width: 320, margin: 0, padding: 0, marginwidth: 0, marginheight: 0, frameborder: 0, scrolling: 'no', marginLeft: '-20px', class: 'dynamic-house-ad' }); if (target.is('.last')) { $('.attribution .inStreamAd') .append('<div class="ad_label">Advertisement</div>') .append($iframe); } else { $('.inStreamAd', target) .append('<div class="ad_label">Advertisement</div>') .append($iframe); } }, /** * Creates an ad call that goes with DFP ad server * @param {Object}} target jQuery selector object for * where the ad will get inserted */ callDFPHouseAd: function (target) { var num = $(target).data('page-number') || 'ad-1', adId = 'infinite-ad-' + num, adContainer = $(target).find('.inStreamAd'); if (target.is('.last')) { adContainer = $('.attribution .inStreamAd'); // cache the value of the pageview id so we can later use to update the pvid of the bottom ad call window.pvid = window.s_pageview_id; } var domStr = '<div class="ad_label">Advertisement</div><div id="' + adId + '">'; adContainer.append(domStr); // force a new co-relation id for dynamic ads calls if (typeof googletag != 'undefined') { googletag.cmd.push(function () { googletag.pubads().updateCorrelator(); }); } /** * pass the number of the ad in the series. * example: for a page with seven 2026 ad units, setting pg = 4 tells the ad server that this is the fourth 2026 ad in the series */ webmd.ads2.setPageTarget('pg', isNaN(num) ? 1 : num); webmd.ads2.defineAd({ id: adId, pos: '2026', sizes: [[300, 50], [300, 51], [300, 250], [300, 253], [320, 50], [320, 51]] }); // keep track of the current page number this.index = num; }, /** * We need a new pvid for each infinite page * ad call. This creates that. * @return {Number} */ createInfinitePageviewId: function () { var self = this; // getting the date, getting the seconds from epoch, slicing off the first two characters as we only want 11 here var timestamp = new Date().getTime().toString().slice(2), // making an 8 digit random number (using toFixed to make sure it's always 8) randomNumber = Math.random().toFixed(8).substr(2, 8); // set the global variable to the 19 digit page view id self.s_pageview_id = timestamp + randomNumber; }, /** * If we are not making an Ajax call for the content, * then we just used the content that is on the page but * hidden on page load. * ---- IT'S CURRENTLY THE DEFAULT ---- */ nonAjaxCall: function () { var self = this; if (self.opts.beforeLoad !== null) { self.opts.beforeLoad(self.opts.content); } if (self.opts.afterLoad !== null) { self.opts.afterLoad($(self.opts.content)); } }, defaults: { moduleCount: -1, loadPattern: null, afterLoad: null, beforeLoad: null, container: null, content: 'page.html', contentData: {}, heightOffset: 0, scrollTarget: $(window), pageUrl: null } }; })(jQuery); // Init for Infinite Scroll Plugin $(function () { /** * Get the list of funded urls for which we want to allow in-article placements. * https://jira.webmd.net/browse/PPE-23261 * @param {string} dctmId The documentum id of the shared module containing list of funded urls */ var url = 'http://www' + webmd.url.getLifecycle() + '.m.webmd.com/modules/sponsor-box?id=091e9c5e812b356a'; $.ajax({ dataType: 'html', url: url, success: function (data) { var exclusionsList = $(data).find('.exception-list').html(); //create a new script tag in the DOM var s = document.createElement("script"); s.type = "text/javascript"; //put the exclusions object in the new script tag s.innerHTML = exclusionsList; //append nativeAdObj to the DOM $('head').append(s); }, error: function (xhr, status, error) { webmd.debug(xhr, status); }, complete: function () { webmd.nativeAd.init({container: '#page-1'}); } }); /** * huge if statement to see if we are going to run the infinite * code. This is used since revenue products are still paginated * as well as some special reports. * The first part of the if statement handles what happens when * we don't run infinite. Instead we build out pagination dynamically */ /** JIRA PPE-8670: added an extra condition to use infinite layout if article is sponsored & topic-targeted **/ if ((window.s_sponsor_program && window.s_package_type.indexOf('topic targeted') < 0) || window.s_package_name == "Mobile Ebola Virus Infection") { webmd.debug('Dont do infinite bc we are sponsored or special report'); webmd.infiniteScroll.hasPages(); //Get the url params so we can see what page //number we are on. Used to build out pagination links var urlParam = webmd.url.getParams(), lastPage = $('.page:last').data('page-number'), curPage = urlParam.page, prevPage, nextPage; //HTML for our pagination var paginationTemplate = '<div class="pagination"><div class="previous icon-arrow-left"><a href="#"></a></div><div class="next icon-arrow-right"><a href="#"></a></div><div class="pagination-wrapper"><div class="pagination-title">Page 1 of 4</div></div></div>'; //Insert our pagination after all the article text $('#textArea').after($(paginationTemplate)); if (typeof curPage === 'undefined' || curPage === 1 || location.search.indexOf('page=1') !== -1) { $('#textArea .loading_medium_png').remove(); $('.pagination').find('.previous').addClass('disabled'); $('.pagination').find('.previous a').on('click', function (e) { e.preventDefault(); }); $('.pagination').find('.pagination-title').text('Page 1' + ' of ' + lastPage); $('.pagination').find('.next a').attr('href', '?page=2'); } else { prevPage = parseInt(curPage) - 1; nextPage = parseInt(curPage) + 1; $('.pagination').find('.pagination-title').text('Page ' + parseInt(curPage) + ' of ' + lastPage); $('.pagination').find('.previous a').attr('href', '?page=' + prevPage); $('.pagination').find('.next a').attr('href', '?page=' + nextPage); if (parseInt(curPage) === lastPage) { $('.pagination').find('.next').addClass('disabled'); $('.pagination').find('.next a').on('click', function (e) { e.preventDefault(); }); } } var pageNumber = 1; if (typeof webmd.url.getParam('page') != 'undefined') { pageNumber = webmd.url.getParam('page'); } // hide from app view if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#page-' + pageNumber}); } } else { /** * This callback gets fired each time the document height changes. */ window.onElementHeightChange = function (elm, callback) { var lastHeight = elm.clientHeight, newHeight; (function run() { newHeight = elm.clientHeight; if (lastHeight != newHeight) { callback(); } lastHeight = newHeight; if (elm.onElementHeightChangeTimer) { clearTimeout(elm.onElementHeightChangeTimer); } elm.onElementHeightChangeTimer = setTimeout(run, 200); })(); }; /** * We need to recalculate the trigger point for every waypoint as we update the dom. */ window.onElementHeightChange(document.body, function () { jQuery.waypoints('refresh'); }); var articleInfinite = Object.create(webmd.infiniteScroll); articleInfinite.init({ container: $('.article.infinite'), content: '.page', heightOffset: 200, pageUrl: webmd.getCurrentUrl(), beforeLoad: function (contentClass) { $('.infinite .page:visible:last').next(); }, afterLoad: function (elementsLoaded) { var target = $('.infinite .page:visible:last'), targetNext = $(elementsLoaded).filter(':visible:last').next('.page'), hasAdhesive = false; if (targetNext.length === 0) { articleInfinite.opts.container.trigger('disableInfinite'); return; } var targetNextNumber = targetNext.data('page-number'); webmd.infiniteScroll.showNext(target); var pageNumber = parseInt(targetNext.attr('id').slice(-1)); if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#' + targetNext.attr('id')}); } clearTimeout(window.pageViewTimeout); $(targetNext).waypoint(function () { window.pageViewTimeout = setTimeout(function () { webmd.infiniteScroll.metricsCall({ moduleName: 'pg-n-swipe', pageName: this.pageUrl, iCount: targetNextNumber, refresh: false }); if (!$('body').hasClass('adhesive_ad')) { if (targetNext.find('.inStreamAd').length > 0 || targetNext.is('.last')) { webmd.infiniteScroll.insertAd(targetNext, false); } } }, 0); }, { offset: '50%', triggerOnce: true }); this.container.trigger('contentLoaded'); } }); $('footer.attribution').waypoint(function () { setTimeout(function () { // force a new co-relation id if (typeof googletag != 'undefined') { googletag.pubads().updateCorrelator(); } /** * we need to manually update the pvid for the bottom ad to match the pvid of the top ad since technically they are on same page. * Also pass ad identifier to DFP (see https://jira.webmd.net/browse/PPE-53106). */ webmd.ads2.setPageTarget({ 'pvid': window.pvid || window.s_pageview_id, 'pg': $('.page').length + 1, 'al': 'cons_bot' }); webmd.ads2.defineAd({ id: 'ads2-pos-2026-ad_btm', pos: '2026', sizes: [[300, 50], [300, 51], [300, 250], [300, 253], [320, 50], [320, 51]], }); /** * clear the 'al' page target here after the bottom ad call so it doesn't get passed in subsequent ad calls. */ if (webmd.ads2.pageTarget.hasOwnProperty('al')) { delete webmd.ads2.pageTargets.al; googletag.pubads().clearTargeting('al'); } }, 500); }, { offset: '50%', triggerOnce: true }); } });
{ h = c }
identifier_body
infinite-article-origin.js
/* * jQuery throttle / debounce - v1.1 - 3/7/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function (b, c) { var $ = b.jQuery || b.Cowboy || (b.Cowboy = {}), a; $.throttle = a = function (e, f, j, i) { var h, d = 0; if (typeof f !== "boolean") { i = j; j = f; f = c } function g() { var o = this, m = +new Date() - d, n = arguments; function l() { d = +new Date(); j.apply(o, n) } function k() { h = c } if (i && !h) { l() } h && clearTimeout(h); if (i === c && m > e) { l() } else { if (f !== true) { h = setTimeout(i ? k : l, i === c ? e - m : e) } } } if ($.guid) { g.guid = j.guid = j.guid || $.guid++ } return g }; $.debounce = function (d, e, f) { return f === c ? a(d, e, false) : a(d, f, e !== false) } })(this); /** * Set up the object that will hold our infinte scroll code * @type {Object} */ var webmd = window.webmd || {}; // run just 1 time - using closure. webmd.getCurrentUrl = webmd.getCurrentUrl || (function () { var url = document.location.href.replace(/[\?#].*$/, ''); return function () { return url; }; }.call()); webmd.Scrolling = { Debounce: 'Debounce', DebounceNumber: 500 }; webmd.getDebounceNumber = function (str) { var qs = unescape(str).split('&').filter(function (param) { return param.indexOf(webmd.Scrolling.Debounce) !== -1; })[0]; var no = 0; if (qs) { no = parseInt(qs.replace(/^[\?#]?\w+=/, '')); } return no; }; (function ($) { /** * Doing some checks here. If the program is sponsored or a special report we add * a class so we can handle it in a custom manner */ if ((typeof window.s_sponsor_program != 'undefined' && window.s_sponsor_program)) { $('html').addClass('inProgram'); } webmd.infiniteScroll = webmd.infiniteScroll || { index: 0, init: function (obj) { // If there aren't any pages in the // article, then we don't need to start // an infinite article if (!this.hasPages()) { return false; } // Start a count of DFP ads so we can // give each one a unique ID this.dfpAdNumber = 0; this.opts = $.extend({}, this.defaults, obj); this.enableInfiniteScroll(); this.setUpAdContainers(); this.bindEvents(); }, /** * Handles initial pageview on load. If there * is only one page, we pass 99, otherwise, we * pass the page number we are on * @return {Boolean} If there ARE pages, return False, * otherwise, return true. */ hasPages: function () { var pcount = $('section.page').length, self = this; if ((pcount === 1) || pcount === 0) { webmd.metrics.dpv({ iCount: 99, pageName: webmd.getCurrentUrl(), refresh: false }); // append end-of-article ad since this is a 1-page article var adContainer = $('<div/>', {class: 'inStreamAd'}); $('.article .attribution').append(adContainer); // cache the value of the pageview id so we can later use to update the pvid of the bottom ad call window.pvid = window.s_pageview_id; return false; } else { webmd.metrics.dpv({ iCount: 1, pageName: webmd.getCurrentUrl(), refresh: false }); // william: var dno = webmd.getDebounceNumber(document.location.search); if (!isNaN(dno)) { webmd.Scrolling.DebounceNumber = dno; } console.log('hasPages should be here: ', webmd.Scrolling.DebounceNumber); return true; } }, /** * Pretty self explanatory here. We do all of our binding * in here, in an up front manner, so we can keep it organized * and clean. */ bindEvents: function () { var self = this; /** * Attach listener to scroll event so we can do our infinite * scroll stuff. */ self.opts.scrollTarget.on('scroll', function () { /** * The container that is defined in the init config has a * data attr [data-infinite-scroll]. This data attr is a * bool value and will tell you if inifinite scroll is enabled * or disabled. * Refere to -> enableInfiniteScroll function */ if (self.opts.container.data('infinite-scroll')) { /** * This checks to see if we have scrolled far enough * down the page to start loading in the next page. */ self.checkForLoad(); } }); self.opts.container.on('loadContent', function () { /** * Temporarily disable infinite scroll so we don't * keep firing it while we load the content we need. * This is expecially helpful when loading in AJAX content. */ self.disableInfiniteScroll(); /** * Currently uses non ajax call by default, but this * can be set up to use an ajax call. */ self.loadContent(); }); /** * When we have the content we need, have the ads loaded, and * we have fired a page view call, the contentLoaded event gets * fired. When it's fired we know it's ok to re-enable infnite scroll * and get ready to do the next page. */ self.opts.container.on('contentLoaded', function () { self.enableInfiniteScroll(); }); /** * Disables infinite scrolling when the content is loading * or when there are no pages left to load. */ self.opts.container.on('disableInfinite', function () { self.disableInfiniteScroll(); }); }, /** * Iterate through the pages and insert ad container divs * so we can later populate those divs with ads as we scroll */ setUpAdContainers: function () { var self = this; var lastPageNum = $('section.page:last').data('page-number'); /** * Loop through all the pages and add an Ad container to them * This lets us easily give the container an ID to target them * later. COULD PROB BE IN THE XSL, but we did it here bc * the number of ads was changing a lot. */ $('section.page').each(function (i, elm) { var adContainer = $('<div/>', {class: 'inStreamAd'}), $elm = $(elm), pageNum = $elm.data('page-number'); /** * if it's the first page, go ahead and put an ad * in since the page is already showing. */ if ($elm.is('#page-1')) { $elm.append(adContainer); setTimeout(function () { self.insertAd($('#page-1'), true); }, 0); /** * we have to put the ad in a different place if * it's the last page. */ } else if ($(elm).data('page-number') === lastPageNum) { $(elm).addClass('last'); $('.article .attribution').append(adContainer); } else { $elm.append(adContainer); } }); }, /** * Set up so Infinite scroll is backwards compatible * with DE. * ------ NOT REALLY NEEDED NOW FOR CORE SINCE WE ROLLED OUT DFP ------ * @return {String} The ad server type, Either DFP or Default */ checkAdServerType: function () { this.adServer = 'defaultServer'; if (typeof webmd.ads2 != 'undefined' && webmd.ads2.isInitialized()) { this.adServer = 'dfp'; } else { this.adServer = 'defaultServer'; } return this.adServer; }, /** * We check the amount we have scrolled and see if * that is far enough to load the next piece of infinite * content. */ checkForLoad: function () { var target = this.opts.scrollTarget, container = this.opts.container, windowHeight = window.innerHeight ? window.innerHeight : $(window).height(), contentTop = $(this.opts.content + ':visible:last').offset().top, diff = windowHeight - $(this.opts.content + ':visible:last').height(), mayLoadContent = $(window).scrollTop() >= (contentTop - diff - this.opts.heightOffset); /** * If we've scrolled far enough, trigger the load content event * signaling that it's ok to load content. */ if (mayLoadContent) { this.opts.container.trigger('loadContent'); } }, /** * Used to make sure the content is loaded before * a page is faded in. Goes with the next function that * disables infinite scroll. Useful when Ajaxing content in */ enableInfiniteScroll: function () { this.opts.container.data('infinite-scroll', true); }, /** * Disables infinite scrolling when the content is loading * or when there are no pages left to load. */ disableInfiniteScroll: function () { this.opts.container.data('infinite-scroll', false); }, /** * Gets called when the page is a scroll * position that is ready to load content. * It calls a default of nonAjaxCall since we currently * have all the pages upfront. */ loadContent: function () { this.nonAjaxCall(); }, /** * Shows the next page * @param {Object} $elm jquery object of current page */ showNext: function ($elm) { $elm.next().show(); }, /** * Makes the metrics call to webmd.metrics.dpv * @param {Objec} Object with params for the metrics call. */ metricsCall: function (obj) { webmd.metrics.dpv(obj); }, /** * Checks to see which ad system we are using and * then inserts the add into the appropriate page * @param {Object} target jQuery object */ insertAd: function (target, firstAd) { if (this.checkAdServerType() === 'defaultServer') { this.callDefaultAd(target); } else { this.callDFPHouseAd(target); } }, /** * Creates a default ad with the DE server * @param {Object} target jQuery selector object */ callDefaultAd: function (target) { // Start function to create new pvid function replaceAdParam(srcStr, pName, pValue) { var paramRegEx = new RegExp("\\b" + pName + "=[^&#\"']*"); srcStr = srcStr.replace(paramRegEx, pName + "=" + pValue); return srcStr; } // Random Num Generator for pvid function randomNum() { var randomNumber = Math.round(999999999 * Math.random()); return randomNumber; } var pvid = this.s_pageview_id, adTag = $('#top_ad script')[1].src, transId = randomNum(), tileId = randomNum(); // Reprocess AdTag adTag = adTag.replace(/amp;/g, ''); adTag = adTag.replace('js.ng', 'html.ng'); adTag = replaceAdParam(adTag, "pvid", pvid); adTag = replaceAdParam(adTag, "transactionID", transId); adTag = replaceAdParam(adTag, "tile", tileId); /** * Create an iFrame that will hold our ad * @type {Object} */ var $iframe = $('<iframe/>').attr({ src: adTag, height: 50, width: 320, margin: 0, padding: 0, marginwidth: 0, marginheight: 0, frameborder: 0, scrolling: 'no', marginLeft: '-20px', class: 'dynamic-house-ad' }); if (target.is('.last')) { $('.attribution .inStreamAd') .append('<div class="ad_label">Advertisement</div>') .append($iframe); } else { $('.inStreamAd', target) .append('<div class="ad_label">Advertisement</div>') .append($iframe); } }, /** * Creates an ad call that goes with DFP ad server * @param {Object}} target jQuery selector object for * where the ad will get inserted */ callDFPHouseAd: function (target) { var num = $(target).data('page-number') || 'ad-1', adId = 'infinite-ad-' + num, adContainer = $(target).find('.inStreamAd'); if (target.is('.last')) { adContainer = $('.attribution .inStreamAd'); // cache the value of the pageview id so we can later use to update the pvid of the bottom ad call window.pvid = window.s_pageview_id; } var domStr = '<div class="ad_label">Advertisement</div><div id="' + adId + '">'; adContainer.append(domStr); // force a new co-relation id for dynamic ads calls if (typeof googletag != 'undefined') { googletag.cmd.push(function () { googletag.pubads().updateCorrelator(); }); } /** * pass the number of the ad in the series. * example: for a page with seven 2026 ad units, setting pg = 4 tells the ad server that this is the fourth 2026 ad in the series */ webmd.ads2.setPageTarget('pg', isNaN(num) ? 1 : num); webmd.ads2.defineAd({ id: adId, pos: '2026', sizes: [[300, 50], [300, 51], [300, 250], [300, 253], [320, 50], [320, 51]] }); // keep track of the current page number this.index = num; }, /** * We need a new pvid for each infinite page * ad call. This creates that. * @return {Number} */ createInfinitePageviewId: function () { var self = this; // getting the date, getting the seconds from epoch, slicing off the first two characters as we only want 11 here var timestamp = new Date().getTime().toString().slice(2), // making an 8 digit random number (using toFixed to make sure it's always 8) randomNumber = Math.random().toFixed(8).substr(2, 8); // set the global variable to the 19 digit page view id self.s_pageview_id = timestamp + randomNumber; }, /** * If we are not making an Ajax call for the content, * then we just used the content that is on the page but * hidden on page load.
var self = this; if (self.opts.beforeLoad !== null) { self.opts.beforeLoad(self.opts.content); } if (self.opts.afterLoad !== null) { self.opts.afterLoad($(self.opts.content)); } }, defaults: { moduleCount: -1, loadPattern: null, afterLoad: null, beforeLoad: null, container: null, content: 'page.html', contentData: {}, heightOffset: 0, scrollTarget: $(window), pageUrl: null } }; })(jQuery); // Init for Infinite Scroll Plugin $(function () { /** * Get the list of funded urls for which we want to allow in-article placements. * https://jira.webmd.net/browse/PPE-23261 * @param {string} dctmId The documentum id of the shared module containing list of funded urls */ var url = 'http://www' + webmd.url.getLifecycle() + '.m.webmd.com/modules/sponsor-box?id=091e9c5e812b356a'; $.ajax({ dataType: 'html', url: url, success: function (data) { var exclusionsList = $(data).find('.exception-list').html(); //create a new script tag in the DOM var s = document.createElement("script"); s.type = "text/javascript"; //put the exclusions object in the new script tag s.innerHTML = exclusionsList; //append nativeAdObj to the DOM $('head').append(s); }, error: function (xhr, status, error) { webmd.debug(xhr, status); }, complete: function () { webmd.nativeAd.init({container: '#page-1'}); } }); /** * huge if statement to see if we are going to run the infinite * code. This is used since revenue products are still paginated * as well as some special reports. * The first part of the if statement handles what happens when * we don't run infinite. Instead we build out pagination dynamically */ /** JIRA PPE-8670: added an extra condition to use infinite layout if article is sponsored & topic-targeted **/ if ((window.s_sponsor_program && window.s_package_type.indexOf('topic targeted') < 0) || window.s_package_name == "Mobile Ebola Virus Infection") { webmd.debug('Dont do infinite bc we are sponsored or special report'); webmd.infiniteScroll.hasPages(); //Get the url params so we can see what page //number we are on. Used to build out pagination links var urlParam = webmd.url.getParams(), lastPage = $('.page:last').data('page-number'), curPage = urlParam.page, prevPage, nextPage; //HTML for our pagination var paginationTemplate = '<div class="pagination"><div class="previous icon-arrow-left"><a href="#"></a></div><div class="next icon-arrow-right"><a href="#"></a></div><div class="pagination-wrapper"><div class="pagination-title">Page 1 of 4</div></div></div>'; //Insert our pagination after all the article text $('#textArea').after($(paginationTemplate)); if (typeof curPage === 'undefined' || curPage === 1 || location.search.indexOf('page=1') !== -1) { $('#textArea .loading_medium_png').remove(); $('.pagination').find('.previous').addClass('disabled'); $('.pagination').find('.previous a').on('click', function (e) { e.preventDefault(); }); $('.pagination').find('.pagination-title').text('Page 1' + ' of ' + lastPage); $('.pagination').find('.next a').attr('href', '?page=2'); } else { prevPage = parseInt(curPage) - 1; nextPage = parseInt(curPage) + 1; $('.pagination').find('.pagination-title').text('Page ' + parseInt(curPage) + ' of ' + lastPage); $('.pagination').find('.previous a').attr('href', '?page=' + prevPage); $('.pagination').find('.next a').attr('href', '?page=' + nextPage); if (parseInt(curPage) === lastPage) { $('.pagination').find('.next').addClass('disabled'); $('.pagination').find('.next a').on('click', function (e) { e.preventDefault(); }); } } var pageNumber = 1; if (typeof webmd.url.getParam('page') != 'undefined') { pageNumber = webmd.url.getParam('page'); } // hide from app view if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#page-' + pageNumber}); } } else { /** * This callback gets fired each time the document height changes. */ window.onElementHeightChange = function (elm, callback) { var lastHeight = elm.clientHeight, newHeight; (function run() { newHeight = elm.clientHeight; if (lastHeight != newHeight) { callback(); } lastHeight = newHeight; if (elm.onElementHeightChangeTimer) { clearTimeout(elm.onElementHeightChangeTimer); } elm.onElementHeightChangeTimer = setTimeout(run, 200); })(); }; /** * We need to recalculate the trigger point for every waypoint as we update the dom. */ window.onElementHeightChange(document.body, function () { jQuery.waypoints('refresh'); }); var articleInfinite = Object.create(webmd.infiniteScroll); articleInfinite.init({ container: $('.article.infinite'), content: '.page', heightOffset: 200, pageUrl: webmd.getCurrentUrl(), beforeLoad: function (contentClass) { $('.infinite .page:visible:last').next(); }, afterLoad: function (elementsLoaded) { var target = $('.infinite .page:visible:last'), targetNext = $(elementsLoaded).filter(':visible:last').next('.page'), hasAdhesive = false; if (targetNext.length === 0) { articleInfinite.opts.container.trigger('disableInfinite'); return; } var targetNextNumber = targetNext.data('page-number'); webmd.infiniteScroll.showNext(target); var pageNumber = parseInt(targetNext.attr('id').slice(-1)); if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#' + targetNext.attr('id')}); } clearTimeout(window.pageViewTimeout); $(targetNext).waypoint(function () { window.pageViewTimeout = setTimeout(function () { webmd.infiniteScroll.metricsCall({ moduleName: 'pg-n-swipe', pageName: this.pageUrl, iCount: targetNextNumber, refresh: false }); if (!$('body').hasClass('adhesive_ad')) { if (targetNext.find('.inStreamAd').length > 0 || targetNext.is('.last')) { webmd.infiniteScroll.insertAd(targetNext, false); } } }, 0); }, { offset: '50%', triggerOnce: true }); this.container.trigger('contentLoaded'); } }); $('footer.attribution').waypoint(function () { setTimeout(function () { // force a new co-relation id if (typeof googletag != 'undefined') { googletag.pubads().updateCorrelator(); } /** * we need to manually update the pvid for the bottom ad to match the pvid of the top ad since technically they are on same page. * Also pass ad identifier to DFP (see https://jira.webmd.net/browse/PPE-53106). */ webmd.ads2.setPageTarget({ 'pvid': window.pvid || window.s_pageview_id, 'pg': $('.page').length + 1, 'al': 'cons_bot' }); webmd.ads2.defineAd({ id: 'ads2-pos-2026-ad_btm', pos: '2026', sizes: [[300, 50], [300, 51], [300, 250], [300, 253], [320, 50], [320, 51]], }); /** * clear the 'al' page target here after the bottom ad call so it doesn't get passed in subsequent ad calls. */ if (webmd.ads2.pageTarget.hasOwnProperty('al')) { delete webmd.ads2.pageTargets.al; googletag.pubads().clearTargeting('al'); } }, 500); }, { offset: '50%', triggerOnce: true }); } });
* ---- IT'S CURRENTLY THE DEFAULT ---- */ nonAjaxCall: function () {
random_line_split
infinite-article-origin.js
/* * jQuery throttle / debounce - v1.1 - 3/7/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function (b, c) { var $ = b.jQuery || b.Cowboy || (b.Cowboy = {}), a; $.throttle = a = function (e, f, j, i) { var h, d = 0; if (typeof f !== "boolean") { i = j; j = f; f = c } function
() { var o = this, m = +new Date() - d, n = arguments; function l() { d = +new Date(); j.apply(o, n) } function k() { h = c } if (i && !h) { l() } h && clearTimeout(h); if (i === c && m > e) { l() } else { if (f !== true) { h = setTimeout(i ? k : l, i === c ? e - m : e) } } } if ($.guid) { g.guid = j.guid = j.guid || $.guid++ } return g }; $.debounce = function (d, e, f) { return f === c ? a(d, e, false) : a(d, f, e !== false) } })(this); /** * Set up the object that will hold our infinte scroll code * @type {Object} */ var webmd = window.webmd || {}; // run just 1 time - using closure. webmd.getCurrentUrl = webmd.getCurrentUrl || (function () { var url = document.location.href.replace(/[\?#].*$/, ''); return function () { return url; }; }.call()); webmd.Scrolling = { Debounce: 'Debounce', DebounceNumber: 500 }; webmd.getDebounceNumber = function (str) { var qs = unescape(str).split('&').filter(function (param) { return param.indexOf(webmd.Scrolling.Debounce) !== -1; })[0]; var no = 0; if (qs) { no = parseInt(qs.replace(/^[\?#]?\w+=/, '')); } return no; }; (function ($) { /** * Doing some checks here. If the program is sponsored or a special report we add * a class so we can handle it in a custom manner */ if ((typeof window.s_sponsor_program != 'undefined' && window.s_sponsor_program)) { $('html').addClass('inProgram'); } webmd.infiniteScroll = webmd.infiniteScroll || { index: 0, init: function (obj) { // If there aren't any pages in the // article, then we don't need to start // an infinite article if (!this.hasPages()) { return false; } // Start a count of DFP ads so we can // give each one a unique ID this.dfpAdNumber = 0; this.opts = $.extend({}, this.defaults, obj); this.enableInfiniteScroll(); this.setUpAdContainers(); this.bindEvents(); }, /** * Handles initial pageview on load. If there * is only one page, we pass 99, otherwise, we * pass the page number we are on * @return {Boolean} If there ARE pages, return False, * otherwise, return true. */ hasPages: function () { var pcount = $('section.page').length, self = this; if ((pcount === 1) || pcount === 0) { webmd.metrics.dpv({ iCount: 99, pageName: webmd.getCurrentUrl(), refresh: false }); // append end-of-article ad since this is a 1-page article var adContainer = $('<div/>', {class: 'inStreamAd'}); $('.article .attribution').append(adContainer); // cache the value of the pageview id so we can later use to update the pvid of the bottom ad call window.pvid = window.s_pageview_id; return false; } else { webmd.metrics.dpv({ iCount: 1, pageName: webmd.getCurrentUrl(), refresh: false }); // william: var dno = webmd.getDebounceNumber(document.location.search); if (!isNaN(dno)) { webmd.Scrolling.DebounceNumber = dno; } console.log('hasPages should be here: ', webmd.Scrolling.DebounceNumber); return true; } }, /** * Pretty self explanatory here. We do all of our binding * in here, in an up front manner, so we can keep it organized * and clean. */ bindEvents: function () { var self = this; /** * Attach listener to scroll event so we can do our infinite * scroll stuff. */ self.opts.scrollTarget.on('scroll', function () { /** * The container that is defined in the init config has a * data attr [data-infinite-scroll]. This data attr is a * bool value and will tell you if inifinite scroll is enabled * or disabled. * Refere to -> enableInfiniteScroll function */ if (self.opts.container.data('infinite-scroll')) { /** * This checks to see if we have scrolled far enough * down the page to start loading in the next page. */ self.checkForLoad(); } }); self.opts.container.on('loadContent', function () { /** * Temporarily disable infinite scroll so we don't * keep firing it while we load the content we need. * This is expecially helpful when loading in AJAX content. */ self.disableInfiniteScroll(); /** * Currently uses non ajax call by default, but this * can be set up to use an ajax call. */ self.loadContent(); }); /** * When we have the content we need, have the ads loaded, and * we have fired a page view call, the contentLoaded event gets * fired. When it's fired we know it's ok to re-enable infnite scroll * and get ready to do the next page. */ self.opts.container.on('contentLoaded', function () { self.enableInfiniteScroll(); }); /** * Disables infinite scrolling when the content is loading * or when there are no pages left to load. */ self.opts.container.on('disableInfinite', function () { self.disableInfiniteScroll(); }); }, /** * Iterate through the pages and insert ad container divs * so we can later populate those divs with ads as we scroll */ setUpAdContainers: function () { var self = this; var lastPageNum = $('section.page:last').data('page-number'); /** * Loop through all the pages and add an Ad container to them * This lets us easily give the container an ID to target them * later. COULD PROB BE IN THE XSL, but we did it here bc * the number of ads was changing a lot. */ $('section.page').each(function (i, elm) { var adContainer = $('<div/>', {class: 'inStreamAd'}), $elm = $(elm), pageNum = $elm.data('page-number'); /** * if it's the first page, go ahead and put an ad * in since the page is already showing. */ if ($elm.is('#page-1')) { $elm.append(adContainer); setTimeout(function () { self.insertAd($('#page-1'), true); }, 0); /** * we have to put the ad in a different place if * it's the last page. */ } else if ($(elm).data('page-number') === lastPageNum) { $(elm).addClass('last'); $('.article .attribution').append(adContainer); } else { $elm.append(adContainer); } }); }, /** * Set up so Infinite scroll is backwards compatible * with DE. * ------ NOT REALLY NEEDED NOW FOR CORE SINCE WE ROLLED OUT DFP ------ * @return {String} The ad server type, Either DFP or Default */ checkAdServerType: function () { this.adServer = 'defaultServer'; if (typeof webmd.ads2 != 'undefined' && webmd.ads2.isInitialized()) { this.adServer = 'dfp'; } else { this.adServer = 'defaultServer'; } return this.adServer; }, /** * We check the amount we have scrolled and see if * that is far enough to load the next piece of infinite * content. */ checkForLoad: function () { var target = this.opts.scrollTarget, container = this.opts.container, windowHeight = window.innerHeight ? window.innerHeight : $(window).height(), contentTop = $(this.opts.content + ':visible:last').offset().top, diff = windowHeight - $(this.opts.content + ':visible:last').height(), mayLoadContent = $(window).scrollTop() >= (contentTop - diff - this.opts.heightOffset); /** * If we've scrolled far enough, trigger the load content event * signaling that it's ok to load content. */ if (mayLoadContent) { this.opts.container.trigger('loadContent'); } }, /** * Used to make sure the content is loaded before * a page is faded in. Goes with the next function that * disables infinite scroll. Useful when Ajaxing content in */ enableInfiniteScroll: function () { this.opts.container.data('infinite-scroll', true); }, /** * Disables infinite scrolling when the content is loading * or when there are no pages left to load. */ disableInfiniteScroll: function () { this.opts.container.data('infinite-scroll', false); }, /** * Gets called when the page is a scroll * position that is ready to load content. * It calls a default of nonAjaxCall since we currently * have all the pages upfront. */ loadContent: function () { this.nonAjaxCall(); }, /** * Shows the next page * @param {Object} $elm jquery object of current page */ showNext: function ($elm) { $elm.next().show(); }, /** * Makes the metrics call to webmd.metrics.dpv * @param {Objec} Object with params for the metrics call. */ metricsCall: function (obj) { webmd.metrics.dpv(obj); }, /** * Checks to see which ad system we are using and * then inserts the add into the appropriate page * @param {Object} target jQuery object */ insertAd: function (target, firstAd) { if (this.checkAdServerType() === 'defaultServer') { this.callDefaultAd(target); } else { this.callDFPHouseAd(target); } }, /** * Creates a default ad with the DE server * @param {Object} target jQuery selector object */ callDefaultAd: function (target) { // Start function to create new pvid function replaceAdParam(srcStr, pName, pValue) { var paramRegEx = new RegExp("\\b" + pName + "=[^&#\"']*"); srcStr = srcStr.replace(paramRegEx, pName + "=" + pValue); return srcStr; } // Random Num Generator for pvid function randomNum() { var randomNumber = Math.round(999999999 * Math.random()); return randomNumber; } var pvid = this.s_pageview_id, adTag = $('#top_ad script')[1].src, transId = randomNum(), tileId = randomNum(); // Reprocess AdTag adTag = adTag.replace(/amp;/g, ''); adTag = adTag.replace('js.ng', 'html.ng'); adTag = replaceAdParam(adTag, "pvid", pvid); adTag = replaceAdParam(adTag, "transactionID", transId); adTag = replaceAdParam(adTag, "tile", tileId); /** * Create an iFrame that will hold our ad * @type {Object} */ var $iframe = $('<iframe/>').attr({ src: adTag, height: 50, width: 320, margin: 0, padding: 0, marginwidth: 0, marginheight: 0, frameborder: 0, scrolling: 'no', marginLeft: '-20px', class: 'dynamic-house-ad' }); if (target.is('.last')) { $('.attribution .inStreamAd') .append('<div class="ad_label">Advertisement</div>') .append($iframe); } else { $('.inStreamAd', target) .append('<div class="ad_label">Advertisement</div>') .append($iframe); } }, /** * Creates an ad call that goes with DFP ad server * @param {Object}} target jQuery selector object for * where the ad will get inserted */ callDFPHouseAd: function (target) { var num = $(target).data('page-number') || 'ad-1', adId = 'infinite-ad-' + num, adContainer = $(target).find('.inStreamAd'); if (target.is('.last')) { adContainer = $('.attribution .inStreamAd'); // cache the value of the pageview id so we can later use to update the pvid of the bottom ad call window.pvid = window.s_pageview_id; } var domStr = '<div class="ad_label">Advertisement</div><div id="' + adId + '">'; adContainer.append(domStr); // force a new co-relation id for dynamic ads calls if (typeof googletag != 'undefined') { googletag.cmd.push(function () { googletag.pubads().updateCorrelator(); }); } /** * pass the number of the ad in the series. * example: for a page with seven 2026 ad units, setting pg = 4 tells the ad server that this is the fourth 2026 ad in the series */ webmd.ads2.setPageTarget('pg', isNaN(num) ? 1 : num); webmd.ads2.defineAd({ id: adId, pos: '2026', sizes: [[300, 50], [300, 51], [300, 250], [300, 253], [320, 50], [320, 51]] }); // keep track of the current page number this.index = num; }, /** * We need a new pvid for each infinite page * ad call. This creates that. * @return {Number} */ createInfinitePageviewId: function () { var self = this; // getting the date, getting the seconds from epoch, slicing off the first two characters as we only want 11 here var timestamp = new Date().getTime().toString().slice(2), // making an 8 digit random number (using toFixed to make sure it's always 8) randomNumber = Math.random().toFixed(8).substr(2, 8); // set the global variable to the 19 digit page view id self.s_pageview_id = timestamp + randomNumber; }, /** * If we are not making an Ajax call for the content, * then we just used the content that is on the page but * hidden on page load. * ---- IT'S CURRENTLY THE DEFAULT ---- */ nonAjaxCall: function () { var self = this; if (self.opts.beforeLoad !== null) { self.opts.beforeLoad(self.opts.content); } if (self.opts.afterLoad !== null) { self.opts.afterLoad($(self.opts.content)); } }, defaults: { moduleCount: -1, loadPattern: null, afterLoad: null, beforeLoad: null, container: null, content: 'page.html', contentData: {}, heightOffset: 0, scrollTarget: $(window), pageUrl: null } }; })(jQuery); // Init for Infinite Scroll Plugin $(function () { /** * Get the list of funded urls for which we want to allow in-article placements. * https://jira.webmd.net/browse/PPE-23261 * @param {string} dctmId The documentum id of the shared module containing list of funded urls */ var url = 'http://www' + webmd.url.getLifecycle() + '.m.webmd.com/modules/sponsor-box?id=091e9c5e812b356a'; $.ajax({ dataType: 'html', url: url, success: function (data) { var exclusionsList = $(data).find('.exception-list').html(); //create a new script tag in the DOM var s = document.createElement("script"); s.type = "text/javascript"; //put the exclusions object in the new script tag s.innerHTML = exclusionsList; //append nativeAdObj to the DOM $('head').append(s); }, error: function (xhr, status, error) { webmd.debug(xhr, status); }, complete: function () { webmd.nativeAd.init({container: '#page-1'}); } }); /** * huge if statement to see if we are going to run the infinite * code. This is used since revenue products are still paginated * as well as some special reports. * The first part of the if statement handles what happens when * we don't run infinite. Instead we build out pagination dynamically */ /** JIRA PPE-8670: added an extra condition to use infinite layout if article is sponsored & topic-targeted **/ if ((window.s_sponsor_program && window.s_package_type.indexOf('topic targeted') < 0) || window.s_package_name == "Mobile Ebola Virus Infection") { webmd.debug('Dont do infinite bc we are sponsored or special report'); webmd.infiniteScroll.hasPages(); //Get the url params so we can see what page //number we are on. Used to build out pagination links var urlParam = webmd.url.getParams(), lastPage = $('.page:last').data('page-number'), curPage = urlParam.page, prevPage, nextPage; //HTML for our pagination var paginationTemplate = '<div class="pagination"><div class="previous icon-arrow-left"><a href="#"></a></div><div class="next icon-arrow-right"><a href="#"></a></div><div class="pagination-wrapper"><div class="pagination-title">Page 1 of 4</div></div></div>'; //Insert our pagination after all the article text $('#textArea').after($(paginationTemplate)); if (typeof curPage === 'undefined' || curPage === 1 || location.search.indexOf('page=1') !== -1) { $('#textArea .loading_medium_png').remove(); $('.pagination').find('.previous').addClass('disabled'); $('.pagination').find('.previous a').on('click', function (e) { e.preventDefault(); }); $('.pagination').find('.pagination-title').text('Page 1' + ' of ' + lastPage); $('.pagination').find('.next a').attr('href', '?page=2'); } else { prevPage = parseInt(curPage) - 1; nextPage = parseInt(curPage) + 1; $('.pagination').find('.pagination-title').text('Page ' + parseInt(curPage) + ' of ' + lastPage); $('.pagination').find('.previous a').attr('href', '?page=' + prevPage); $('.pagination').find('.next a').attr('href', '?page=' + nextPage); if (parseInt(curPage) === lastPage) { $('.pagination').find('.next').addClass('disabled'); $('.pagination').find('.next a').on('click', function (e) { e.preventDefault(); }); } } var pageNumber = 1; if (typeof webmd.url.getParam('page') != 'undefined') { pageNumber = webmd.url.getParam('page'); } // hide from app view if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#page-' + pageNumber}); } } else { /** * This callback gets fired each time the document height changes. */ window.onElementHeightChange = function (elm, callback) { var lastHeight = elm.clientHeight, newHeight; (function run() { newHeight = elm.clientHeight; if (lastHeight != newHeight) { callback(); } lastHeight = newHeight; if (elm.onElementHeightChangeTimer) { clearTimeout(elm.onElementHeightChangeTimer); } elm.onElementHeightChangeTimer = setTimeout(run, 200); })(); }; /** * We need to recalculate the trigger point for every waypoint as we update the dom. */ window.onElementHeightChange(document.body, function () { jQuery.waypoints('refresh'); }); var articleInfinite = Object.create(webmd.infiniteScroll); articleInfinite.init({ container: $('.article.infinite'), content: '.page', heightOffset: 200, pageUrl: webmd.getCurrentUrl(), beforeLoad: function (contentClass) { $('.infinite .page:visible:last').next(); }, afterLoad: function (elementsLoaded) { var target = $('.infinite .page:visible:last'), targetNext = $(elementsLoaded).filter(':visible:last').next('.page'), hasAdhesive = false; if (targetNext.length === 0) { articleInfinite.opts.container.trigger('disableInfinite'); return; } var targetNextNumber = targetNext.data('page-number'); webmd.infiniteScroll.showNext(target); var pageNumber = parseInt(targetNext.attr('id').slice(-1)); if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#' + targetNext.attr('id')}); } clearTimeout(window.pageViewTimeout); $(targetNext).waypoint(function () { window.pageViewTimeout = setTimeout(function () { webmd.infiniteScroll.metricsCall({ moduleName: 'pg-n-swipe', pageName: this.pageUrl, iCount: targetNextNumber, refresh: false }); if (!$('body').hasClass('adhesive_ad')) { if (targetNext.find('.inStreamAd').length > 0 || targetNext.is('.last')) { webmd.infiniteScroll.insertAd(targetNext, false); } } }, 0); }, { offset: '50%', triggerOnce: true }); this.container.trigger('contentLoaded'); } }); $('footer.attribution').waypoint(function () { setTimeout(function () { // force a new co-relation id if (typeof googletag != 'undefined') { googletag.pubads().updateCorrelator(); } /** * we need to manually update the pvid for the bottom ad to match the pvid of the top ad since technically they are on same page. * Also pass ad identifier to DFP (see https://jira.webmd.net/browse/PPE-53106). */ webmd.ads2.setPageTarget({ 'pvid': window.pvid || window.s_pageview_id, 'pg': $('.page').length + 1, 'al': 'cons_bot' }); webmd.ads2.defineAd({ id: 'ads2-pos-2026-ad_btm', pos: '2026', sizes: [[300, 50], [300, 51], [300, 250], [300, 253], [320, 50], [320, 51]], }); /** * clear the 'al' page target here after the bottom ad call so it doesn't get passed in subsequent ad calls. */ if (webmd.ads2.pageTarget.hasOwnProperty('al')) { delete webmd.ads2.pageTargets.al; googletag.pubads().clearTargeting('al'); } }, 500); }, { offset: '50%', triggerOnce: true }); } });
g
identifier_name
main.rs
use shared::{ grid::{self as sg, Grid, GridTile, Coordinate}, input::read_stdin_lines }; use lazy_static::*; use regex::Regex; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] enum Tile { Clay, Sand, Spring, Water, WaterAtRest } struct Map { data: Vec<Vec<Tile>>, xstart: usize } impl Map { fn new(mut data: Vec<Vec<Tile>>, xstart: usize) -> Self
fn flow_down(&mut self, y: usize, x: usize) -> (usize, usize) { for yf in y+1 .. self.data.len() { if self.data[yf][x] == Tile::Sand { self.data[yf][x] = Tile::Water; } else if self.data[yf][x] != Tile::Water { return (yf - 1, x); } } (self.data.len(), x) } fn check_enclosed(&self, y: usize, x: usize) -> (Option<usize>, Option<usize>) { // Check left let (mut enclosed_left, mut enclosed_right) = (None, None); for xf in (0..x).rev() { if self.data[y][xf] == Tile::Clay || self.data[y + 1][xf] == Tile::Sand { enclosed_left = Some(xf + 1); break; } } for xf in x..self.data[y].len() { if self.data[y][xf] == Tile::Clay || self.data[y + 1][xf] == Tile::Sand { enclosed_right = Some(xf); break; } } (enclosed_left, enclosed_right) } fn update(&mut self) -> bool { // Find next flowable water tile let mut last = None; /* Lots of trial and error'd code below, lots of redundancies probably */ 'outer: for y in (0..self.data.len() - 1).rev() { for x in 0..self.data[y].len() { match self.data[y][x] { Tile::Spring | Tile::Water => { let below = self.data[y + 1][x]; // Do not try to flow water that's already flowing if x > 0 && x < self.data[y].len() - 1 && self.data[y][x - 1] == Tile::Water && self.data[y][x + 1] == Tile::Water { continue; } // Do not try to flow flowing water that's stopped at a left wall if x > 0 && self.data[y][x - 1] == Tile::Clay && self.data[y][x + 1] == Tile::Water { continue; } // Do not try to flow flowing water that's stopped at a right wall if x < self.data[y].len() - 1 && self.data[y][x + 1] == Tile::Clay && x > 0 && self.data[y][x - 1] == Tile::Water { continue; } // Try to flow water that is either hanging over sand or over resting water if below == Tile::Sand || below == Tile::WaterAtRest { last = Some(self.flow_down(y, x)); if last.unwrap().0 < self.data.len() { break 'outer; } } } _ => () } } } // No flowable water found, we are done here if let None = last { return false; } let last = last.unwrap(); if last.0 == self.data.len() { return false; // Dead flow } let (mut ec_left, mut ec_right) = self.check_enclosed(last.0, last.1); // Normalize enclosed spaces and resolve drops in the flow_right and flow_left helpers if let Some(l) = ec_left { if self.data[last.0 + 1][l - 1] == Tile::Sand { ec_left = None; } } if let Some(r) = ec_right { if self.data[last.0 + 1][r] == Tile::Sand { ec_right = None; } } // Keep flowing right until stopped or dropping let flow_right = |data: &mut Vec<Vec<Tile>>, tile| { for x in last.1.. { data[last.0][x] = tile; if data[last.0 + 1][x] == Tile::Sand || data[last.0][x + 1] == Tile::Water || x == data[last.0].len() - 1 || data[last.0][x + 1] == Tile::Clay { break; } } }; // Keep flowing left until stopped or dropping let flow_left = |data: &mut Vec<Vec<Tile>>, tile| { for x in (0..last.1 + 1).rev() { data[last.0][x] = tile; if data[last.0 + 1][x] == Tile::Sand || x == 0 || data[last.0][x - 1] == Tile::Clay || data[last.0][x - 1] == Tile::Water { break; } } }; // Try to pool or keep flowing sideways match (ec_left, ec_right) { (Some(l), Some(r)) => { // Enclosed on both sides, pool up for x in l..r { self.data[last.0][x] = Tile::WaterAtRest; } }, _ => { // Flow both directions until drop or stop flow_left(&mut self.data, Tile::Water); flow_right(&mut self.data, Tile::Water); } } // Extend spouts left and right that can be dropped in the next iteration if not fully enclosed if let Some(l) = ec_left { if self.data[last.0 + 1][l - 1] == Tile::Sand { self.data[last.0][l - 1] = Tile::Water; } } if let Some(r) = ec_right { if self.data[last.0 + 1][r] == Tile::Sand { self.data[last.0][r] = Tile::Water; } } true } fn count_water(&self, ystart: usize, yend: usize) -> (usize, usize) { let (mut flowing, mut at_rest) = (0, 0); for y in ystart..=yend { for x in 0..self.data[0].len() { match self.data[y][x] { Tile::Water => flowing += 1, Tile::WaterAtRest => at_rest += 1, _ => () } } } (flowing, at_rest) } } impl sg::Grid for Map { type Coord = sg::Coord; type Tile = Tile; fn bounds(&self) -> (Self::Coord, Self::Coord) { (sg::Coord::new(0, 0), sg::Coord::new(self.data.len(), self.data[0].len())) } fn tile_at(&self, c: &Self::Coord) -> &Self::Tile { &self.data[c.y()][c.x()] } } impl sg::GridTile for Tile { fn to_char(&self) -> char { match self { Tile::Clay => '#', Tile::Sand => '.', Tile::Spring => '+', Tile::Water => '|', Tile::WaterAtRest => '~' } } fn color(&self) -> sg::TileColor { match self { Tile::Clay => sg::TileColor::Foreground((sg::Color::Yellow, sg::Attribute::Bold)), Tile::Sand => sg::TileColor::Foreground((sg::Color::Yellow, sg::Attribute::None)), Tile::Spring => sg::TileColor::Foreground((sg::Color::Blue, sg::Attribute::Bold)), Tile::Water | Tile::WaterAtRest => sg::TileColor::Foreground((sg::Color::Blue, sg::Attribute::None)) } } } use std::ops::RangeInclusive; #[derive(Debug)] enum ScanEntry { RangeY(RangeInclusive<usize>, usize), RangeX(usize, RangeInclusive<usize>) } impl ScanEntry { fn parse(e: &String) -> Option<ScanEntry> { lazy_static! { static ref PAT: Regex = Regex::new(r"(x|y)=(\d+)(?:..(\d+))?").unwrap(); } let mut captures = PAT.captures_iter(e); let first_coord = captures.next()?; let second_coord = captures.next()?; if first_coord.get(1)?.as_str() == "x" { let x: usize = first_coord.get(2)?.as_str().parse().ok()?; let ys = second_coord.get(2)?.as_str().parse().ok()?; let ye = second_coord.get(3)?.as_str().parse().ok()?; Some(ScanEntry::RangeY(ys..=ye, x + 1)) } else if first_coord.get(1)?.as_str() == "y" { let y = first_coord.get(2)?.as_str().parse().ok()?; let xs: usize = second_coord.get(2)?.as_str().parse().ok()?; let xe: usize = second_coord.get(3)?.as_str().parse().ok()?; Some(ScanEntry::RangeX(y, (xs + 1)..=(xe + 1 ))) } else { None } } } use std::collections::HashSet; fn main() { let input = read_stdin_lines().expect("could not lock stdin"); let mut results = input.iter().filter_map(ScanEntry::parse).collect::<Vec<_>>(); let (cmin, cmax) = sg::Coord::numeric_limits(); let (mut min, mut max) = (sg::Coord::new(cmax, cmax), sg::Coord::new(cmin, cmin)); let clay = results.iter_mut().fold(HashSet::new(), |mut hs, res| { let mut update = |c: sg::Coord| { hs.insert(c); if c.0 > max.0 { max.0 = c.0; } if c.1 > max.1 { max.1 = c.1; } if c.0 < min.0 { min.0 = c.0; } if c.1 < min.1 { min.1 = c.1; } }; match res { ScanEntry::RangeX(y, xr) => { for x in xr { update(sg::Coord::new(*y, x)); } }, ScanEntry::RangeY(yr, x) => { for y in yr { update(sg::Coord::new(y, *x)); } } } hs }); let mut grid = Vec::with_capacity(max.y()); for y in 0..=max.y() { let mut r = Vec::with_capacity(max.x() - min.x()); for x in min.x() - 1 ..= max.x() + 1 { if clay.contains(&sg::Coord::new(y, x)) { r.push(Tile::Clay); } else { r.push(Tile::Sand); } } grid.push(r); } let mut grid = Map::new(grid, min.x()); for y in 0.. { if !grid.update() { break; } } grid.draw(); let (f, r) = grid.count_water(min.y(), max.y()); println!("Part 1: Total water tiles: {}", f + r); println!("Part 2: Remaining tiles: {}", r); }
{ data[0][500 - xstart + 2] = Tile::Spring; Map { data, xstart } }
identifier_body
main.rs
use shared::{ grid::{self as sg, Grid, GridTile, Coordinate}, input::read_stdin_lines }; use lazy_static::*; use regex::Regex; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] enum Tile { Clay, Sand, Spring, Water, WaterAtRest } struct Map { data: Vec<Vec<Tile>>, xstart: usize } impl Map { fn new(mut data: Vec<Vec<Tile>>, xstart: usize) -> Self { data[0][500 - xstart + 2] = Tile::Spring; Map { data, xstart } } fn flow_down(&mut self, y: usize, x: usize) -> (usize, usize) { for yf in y+1 .. self.data.len() { if self.data[yf][x] == Tile::Sand { self.data[yf][x] = Tile::Water; } else if self.data[yf][x] != Tile::Water { return (yf - 1, x); } } (self.data.len(), x) } fn check_enclosed(&self, y: usize, x: usize) -> (Option<usize>, Option<usize>) { // Check left let (mut enclosed_left, mut enclosed_right) = (None, None); for xf in (0..x).rev() { if self.data[y][xf] == Tile::Clay || self.data[y + 1][xf] == Tile::Sand { enclosed_left = Some(xf + 1); break; } } for xf in x..self.data[y].len() { if self.data[y][xf] == Tile::Clay || self.data[y + 1][xf] == Tile::Sand { enclosed_right = Some(xf); break; } } (enclosed_left, enclosed_right) } fn update(&mut self) -> bool { // Find next flowable water tile let mut last = None; /* Lots of trial and error'd code below, lots of redundancies probably */ 'outer: for y in (0..self.data.len() - 1).rev() { for x in 0..self.data[y].len() { match self.data[y][x] { Tile::Spring | Tile::Water => { let below = self.data[y + 1][x]; // Do not try to flow water that's already flowing if x > 0 && x < self.data[y].len() - 1 && self.data[y][x - 1] == Tile::Water && self.data[y][x + 1] == Tile::Water { continue; } // Do not try to flow flowing water that's stopped at a left wall if x > 0 && self.data[y][x - 1] == Tile::Clay && self.data[y][x + 1] == Tile::Water { continue; } // Do not try to flow flowing water that's stopped at a right wall if x < self.data[y].len() - 1 && self.data[y][x + 1] == Tile::Clay && x > 0 && self.data[y][x - 1] == Tile::Water { continue; } // Try to flow water that is either hanging over sand or over resting water if below == Tile::Sand || below == Tile::WaterAtRest { last = Some(self.flow_down(y, x)); if last.unwrap().0 < self.data.len() { break 'outer; } } } _ => () } } } // No flowable water found, we are done here if let None = last { return false; } let last = last.unwrap(); if last.0 == self.data.len() { return false; // Dead flow } let (mut ec_left, mut ec_right) = self.check_enclosed(last.0, last.1); // Normalize enclosed spaces and resolve drops in the flow_right and flow_left helpers if let Some(l) = ec_left { if self.data[last.0 + 1][l - 1] == Tile::Sand { ec_left = None; } } if let Some(r) = ec_right { if self.data[last.0 + 1][r] == Tile::Sand { ec_right = None; } } // Keep flowing right until stopped or dropping let flow_right = |data: &mut Vec<Vec<Tile>>, tile| { for x in last.1.. { data[last.0][x] = tile; if data[last.0 + 1][x] == Tile::Sand || data[last.0][x + 1] == Tile::Water || x == data[last.0].len() - 1 || data[last.0][x + 1] == Tile::Clay { break; } } }; // Keep flowing left until stopped or dropping let flow_left = |data: &mut Vec<Vec<Tile>>, tile| { for x in (0..last.1 + 1).rev() { data[last.0][x] = tile; if data[last.0 + 1][x] == Tile::Sand || x == 0 || data[last.0][x - 1] == Tile::Clay || data[last.0][x - 1] == Tile::Water { break; } } }; // Try to pool or keep flowing sideways match (ec_left, ec_right) { (Some(l), Some(r)) => { // Enclosed on both sides, pool up for x in l..r { self.data[last.0][x] = Tile::WaterAtRest; } }, _ => { // Flow both directions until drop or stop flow_left(&mut self.data, Tile::Water); flow_right(&mut self.data, Tile::Water); } } // Extend spouts left and right that can be dropped in the next iteration if not fully enclosed if let Some(l) = ec_left { if self.data[last.0 + 1][l - 1] == Tile::Sand { self.data[last.0][l - 1] = Tile::Water; } } if let Some(r) = ec_right { if self.data[last.0 + 1][r] == Tile::Sand { self.data[last.0][r] = Tile::Water; } } true } fn count_water(&self, ystart: usize, yend: usize) -> (usize, usize) { let (mut flowing, mut at_rest) = (0, 0); for y in ystart..=yend { for x in 0..self.data[0].len() { match self.data[y][x] { Tile::Water => flowing += 1, Tile::WaterAtRest => at_rest += 1, _ => () } } } (flowing, at_rest) } } impl sg::Grid for Map { type Coord = sg::Coord; type Tile = Tile; fn bounds(&self) -> (Self::Coord, Self::Coord) { (sg::Coord::new(0, 0), sg::Coord::new(self.data.len(), self.data[0].len())) } fn
(&self, c: &Self::Coord) -> &Self::Tile { &self.data[c.y()][c.x()] } } impl sg::GridTile for Tile { fn to_char(&self) -> char { match self { Tile::Clay => '#', Tile::Sand => '.', Tile::Spring => '+', Tile::Water => '|', Tile::WaterAtRest => '~' } } fn color(&self) -> sg::TileColor { match self { Tile::Clay => sg::TileColor::Foreground((sg::Color::Yellow, sg::Attribute::Bold)), Tile::Sand => sg::TileColor::Foreground((sg::Color::Yellow, sg::Attribute::None)), Tile::Spring => sg::TileColor::Foreground((sg::Color::Blue, sg::Attribute::Bold)), Tile::Water | Tile::WaterAtRest => sg::TileColor::Foreground((sg::Color::Blue, sg::Attribute::None)) } } } use std::ops::RangeInclusive; #[derive(Debug)] enum ScanEntry { RangeY(RangeInclusive<usize>, usize), RangeX(usize, RangeInclusive<usize>) } impl ScanEntry { fn parse(e: &String) -> Option<ScanEntry> { lazy_static! { static ref PAT: Regex = Regex::new(r"(x|y)=(\d+)(?:..(\d+))?").unwrap(); } let mut captures = PAT.captures_iter(e); let first_coord = captures.next()?; let second_coord = captures.next()?; if first_coord.get(1)?.as_str() == "x" { let x: usize = first_coord.get(2)?.as_str().parse().ok()?; let ys = second_coord.get(2)?.as_str().parse().ok()?; let ye = second_coord.get(3)?.as_str().parse().ok()?; Some(ScanEntry::RangeY(ys..=ye, x + 1)) } else if first_coord.get(1)?.as_str() == "y" { let y = first_coord.get(2)?.as_str().parse().ok()?; let xs: usize = second_coord.get(2)?.as_str().parse().ok()?; let xe: usize = second_coord.get(3)?.as_str().parse().ok()?; Some(ScanEntry::RangeX(y, (xs + 1)..=(xe + 1 ))) } else { None } } } use std::collections::HashSet; fn main() { let input = read_stdin_lines().expect("could not lock stdin"); let mut results = input.iter().filter_map(ScanEntry::parse).collect::<Vec<_>>(); let (cmin, cmax) = sg::Coord::numeric_limits(); let (mut min, mut max) = (sg::Coord::new(cmax, cmax), sg::Coord::new(cmin, cmin)); let clay = results.iter_mut().fold(HashSet::new(), |mut hs, res| { let mut update = |c: sg::Coord| { hs.insert(c); if c.0 > max.0 { max.0 = c.0; } if c.1 > max.1 { max.1 = c.1; } if c.0 < min.0 { min.0 = c.0; } if c.1 < min.1 { min.1 = c.1; } }; match res { ScanEntry::RangeX(y, xr) => { for x in xr { update(sg::Coord::new(*y, x)); } }, ScanEntry::RangeY(yr, x) => { for y in yr { update(sg::Coord::new(y, *x)); } } } hs }); let mut grid = Vec::with_capacity(max.y()); for y in 0..=max.y() { let mut r = Vec::with_capacity(max.x() - min.x()); for x in min.x() - 1 ..= max.x() + 1 { if clay.contains(&sg::Coord::new(y, x)) { r.push(Tile::Clay); } else { r.push(Tile::Sand); } } grid.push(r); } let mut grid = Map::new(grid, min.x()); for y in 0.. { if !grid.update() { break; } } grid.draw(); let (f, r) = grid.count_water(min.y(), max.y()); println!("Part 1: Total water tiles: {}", f + r); println!("Part 2: Remaining tiles: {}", r); }
tile_at
identifier_name
main.rs
use shared::{ grid::{self as sg, Grid, GridTile, Coordinate}, input::read_stdin_lines }; use lazy_static::*; use regex::Regex; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] enum Tile { Clay, Sand, Spring, Water, WaterAtRest } struct Map { data: Vec<Vec<Tile>>, xstart: usize } impl Map { fn new(mut data: Vec<Vec<Tile>>, xstart: usize) -> Self { data[0][500 - xstart + 2] = Tile::Spring; Map { data, xstart } } fn flow_down(&mut self, y: usize, x: usize) -> (usize, usize) { for yf in y+1 .. self.data.len() { if self.data[yf][x] == Tile::Sand { self.data[yf][x] = Tile::Water; } else if self.data[yf][x] != Tile::Water { return (yf - 1, x); } } (self.data.len(), x) } fn check_enclosed(&self, y: usize, x: usize) -> (Option<usize>, Option<usize>) { // Check left
let (mut enclosed_left, mut enclosed_right) = (None, None); for xf in (0..x).rev() { if self.data[y][xf] == Tile::Clay || self.data[y + 1][xf] == Tile::Sand { enclosed_left = Some(xf + 1); break; } } for xf in x..self.data[y].len() { if self.data[y][xf] == Tile::Clay || self.data[y + 1][xf] == Tile::Sand { enclosed_right = Some(xf); break; } } (enclosed_left, enclosed_right) } fn update(&mut self) -> bool { // Find next flowable water tile let mut last = None; /* Lots of trial and error'd code below, lots of redundancies probably */ 'outer: for y in (0..self.data.len() - 1).rev() { for x in 0..self.data[y].len() { match self.data[y][x] { Tile::Spring | Tile::Water => { let below = self.data[y + 1][x]; // Do not try to flow water that's already flowing if x > 0 && x < self.data[y].len() - 1 && self.data[y][x - 1] == Tile::Water && self.data[y][x + 1] == Tile::Water { continue; } // Do not try to flow flowing water that's stopped at a left wall if x > 0 && self.data[y][x - 1] == Tile::Clay && self.data[y][x + 1] == Tile::Water { continue; } // Do not try to flow flowing water that's stopped at a right wall if x < self.data[y].len() - 1 && self.data[y][x + 1] == Tile::Clay && x > 0 && self.data[y][x - 1] == Tile::Water { continue; } // Try to flow water that is either hanging over sand or over resting water if below == Tile::Sand || below == Tile::WaterAtRest { last = Some(self.flow_down(y, x)); if last.unwrap().0 < self.data.len() { break 'outer; } } } _ => () } } } // No flowable water found, we are done here if let None = last { return false; } let last = last.unwrap(); if last.0 == self.data.len() { return false; // Dead flow } let (mut ec_left, mut ec_right) = self.check_enclosed(last.0, last.1); // Normalize enclosed spaces and resolve drops in the flow_right and flow_left helpers if let Some(l) = ec_left { if self.data[last.0 + 1][l - 1] == Tile::Sand { ec_left = None; } } if let Some(r) = ec_right { if self.data[last.0 + 1][r] == Tile::Sand { ec_right = None; } } // Keep flowing right until stopped or dropping let flow_right = |data: &mut Vec<Vec<Tile>>, tile| { for x in last.1.. { data[last.0][x] = tile; if data[last.0 + 1][x] == Tile::Sand || data[last.0][x + 1] == Tile::Water || x == data[last.0].len() - 1 || data[last.0][x + 1] == Tile::Clay { break; } } }; // Keep flowing left until stopped or dropping let flow_left = |data: &mut Vec<Vec<Tile>>, tile| { for x in (0..last.1 + 1).rev() { data[last.0][x] = tile; if data[last.0 + 1][x] == Tile::Sand || x == 0 || data[last.0][x - 1] == Tile::Clay || data[last.0][x - 1] == Tile::Water { break; } } }; // Try to pool or keep flowing sideways match (ec_left, ec_right) { (Some(l), Some(r)) => { // Enclosed on both sides, pool up for x in l..r { self.data[last.0][x] = Tile::WaterAtRest; } }, _ => { // Flow both directions until drop or stop flow_left(&mut self.data, Tile::Water); flow_right(&mut self.data, Tile::Water); } } // Extend spouts left and right that can be dropped in the next iteration if not fully enclosed if let Some(l) = ec_left { if self.data[last.0 + 1][l - 1] == Tile::Sand { self.data[last.0][l - 1] = Tile::Water; } } if let Some(r) = ec_right { if self.data[last.0 + 1][r] == Tile::Sand { self.data[last.0][r] = Tile::Water; } } true } fn count_water(&self, ystart: usize, yend: usize) -> (usize, usize) { let (mut flowing, mut at_rest) = (0, 0); for y in ystart..=yend { for x in 0..self.data[0].len() { match self.data[y][x] { Tile::Water => flowing += 1, Tile::WaterAtRest => at_rest += 1, _ => () } } } (flowing, at_rest) } } impl sg::Grid for Map { type Coord = sg::Coord; type Tile = Tile; fn bounds(&self) -> (Self::Coord, Self::Coord) { (sg::Coord::new(0, 0), sg::Coord::new(self.data.len(), self.data[0].len())) } fn tile_at(&self, c: &Self::Coord) -> &Self::Tile { &self.data[c.y()][c.x()] } } impl sg::GridTile for Tile { fn to_char(&self) -> char { match self { Tile::Clay => '#', Tile::Sand => '.', Tile::Spring => '+', Tile::Water => '|', Tile::WaterAtRest => '~' } } fn color(&self) -> sg::TileColor { match self { Tile::Clay => sg::TileColor::Foreground((sg::Color::Yellow, sg::Attribute::Bold)), Tile::Sand => sg::TileColor::Foreground((sg::Color::Yellow, sg::Attribute::None)), Tile::Spring => sg::TileColor::Foreground((sg::Color::Blue, sg::Attribute::Bold)), Tile::Water | Tile::WaterAtRest => sg::TileColor::Foreground((sg::Color::Blue, sg::Attribute::None)) } } } use std::ops::RangeInclusive; #[derive(Debug)] enum ScanEntry { RangeY(RangeInclusive<usize>, usize), RangeX(usize, RangeInclusive<usize>) } impl ScanEntry { fn parse(e: &String) -> Option<ScanEntry> { lazy_static! { static ref PAT: Regex = Regex::new(r"(x|y)=(\d+)(?:..(\d+))?").unwrap(); } let mut captures = PAT.captures_iter(e); let first_coord = captures.next()?; let second_coord = captures.next()?; if first_coord.get(1)?.as_str() == "x" { let x: usize = first_coord.get(2)?.as_str().parse().ok()?; let ys = second_coord.get(2)?.as_str().parse().ok()?; let ye = second_coord.get(3)?.as_str().parse().ok()?; Some(ScanEntry::RangeY(ys..=ye, x + 1)) } else if first_coord.get(1)?.as_str() == "y" { let y = first_coord.get(2)?.as_str().parse().ok()?; let xs: usize = second_coord.get(2)?.as_str().parse().ok()?; let xe: usize = second_coord.get(3)?.as_str().parse().ok()?; Some(ScanEntry::RangeX(y, (xs + 1)..=(xe + 1 ))) } else { None } } } use std::collections::HashSet; fn main() { let input = read_stdin_lines().expect("could not lock stdin"); let mut results = input.iter().filter_map(ScanEntry::parse).collect::<Vec<_>>(); let (cmin, cmax) = sg::Coord::numeric_limits(); let (mut min, mut max) = (sg::Coord::new(cmax, cmax), sg::Coord::new(cmin, cmin)); let clay = results.iter_mut().fold(HashSet::new(), |mut hs, res| { let mut update = |c: sg::Coord| { hs.insert(c); if c.0 > max.0 { max.0 = c.0; } if c.1 > max.1 { max.1 = c.1; } if c.0 < min.0 { min.0 = c.0; } if c.1 < min.1 { min.1 = c.1; } }; match res { ScanEntry::RangeX(y, xr) => { for x in xr { update(sg::Coord::new(*y, x)); } }, ScanEntry::RangeY(yr, x) => { for y in yr { update(sg::Coord::new(y, *x)); } } } hs }); let mut grid = Vec::with_capacity(max.y()); for y in 0..=max.y() { let mut r = Vec::with_capacity(max.x() - min.x()); for x in min.x() - 1 ..= max.x() + 1 { if clay.contains(&sg::Coord::new(y, x)) { r.push(Tile::Clay); } else { r.push(Tile::Sand); } } grid.push(r); } let mut grid = Map::new(grid, min.x()); for y in 0.. { if !grid.update() { break; } } grid.draw(); let (f, r) = grid.count_water(min.y(), max.y()); println!("Part 1: Total water tiles: {}", f + r); println!("Part 2: Remaining tiles: {}", r); }
random_line_split
manager_test.go
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "context" "fmt" "sort" "sync" "testing" "time" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/gae/service/datastore" "go.chromium.org/luci/server/tq/tqtesting" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" cfgpb "go.chromium.org/luci/cv/api/config/v2" "go.chromium.org/luci/cv/internal/changelist" "go.chromium.org/luci/cv/internal/common" "go.chromium.org/luci/cv/internal/common/eventbox" "go.chromium.org/luci/cv/internal/configs/prjcfg/prjcfgtest" "go.chromium.org/luci/cv/internal/cvtesting" gf "go.chromium.org/luci/cv/internal/gerrit/gerritfake" "go.chromium.org/luci/cv/internal/gerrit/gobmap/gobmaptest" "go.chromium.org/luci/cv/internal/gerrit/poller" gerritupdater "go.chromium.org/luci/cv/internal/gerrit/updater" "go.chromium.org/luci/cv/internal/prjmanager" "go.chromium.org/luci/cv/internal/prjmanager/pmtest" "go.chromium.org/luci/cv/internal/prjmanager/prjpb" "go.chromium.org/luci/cv/internal/run" . "github.com/smartystreets/goconvey/convey" . "go.chromium.org/luci/common/testing/assertions" ) func TestProjectTQLateTasks(t *testing.T)
func TestProjectLifeCycle(t *testing.T) { t.Parallel() Convey("Project can be created, updated, deleted", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) _ = New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) const lProject = "infra" recipient := prjmanager.EventboxRecipient(ctx, lProject) Convey("with new project", func() { prjcfgtest.Create(ctx, lProject, singleRepoConfig("host", "repo")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) // Second event is a noop, but should still be consumed at once. So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events, ShouldHaveLength, 0) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 1) So(ps.Status, ShouldEqual, prjpb.Status_STARTED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Ensure first poller task gets executed. ct.Clock.Add(time.Hour) Convey("update config with incomplete runs", func() { err := datastore.Put( ctx, &run.Run{ID: common.RunID(lProject + "/111-beef"), CLs: common.CLIDs{111}}, &run.Run{ID: common.RunID(lProject + "/222-cafe"), CLs: common.CLIDs{222}}, ) So(err, ShouldBeNil) // This is what pmNotifier.notifyRunCreated func does, // but because it's private, it can't be called from this package. simulateRunCreated := func(suffix string) { e := &prjpb.Event{Event: &prjpb.Event_RunCreated{ RunCreated: &prjpb.RunCreated{ RunId: lProject + "/" + suffix, }, }} value, err := proto.Marshal(e) So(err, ShouldBeNil) So(eventbox.Emit(ctx, value, recipient), ShouldBeNil) } simulateRunCreated("111-beef") simulateRunCreated("222-cafe") prjcfgtest.Update(ctx, lProject, singleRepoConfig("host", "repo2")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, _, plog = loadProjectEntities(ctx, lProject) So(p.IncompleteRuns(), ShouldEqual, common.MakeRunIDs(lProject+"/111-beef", lProject+"/222-cafe")) So(plog, ShouldNotBeNil) So(runNotifier.popUpdateConfig(), ShouldResemble, p.IncompleteRuns()) Convey("disable project with incomplete runs", func() { prjcfgtest.Disable(ctx, lProject) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 3) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Should ask Runs to cancel themselves. reqs := make([]cancellationRequest, len(p.IncompleteRuns())) for i, runID := range p.IncompleteRuns() { reqs[i] = cancellationRequest{ id: runID, reason: fmt.Sprintf("CV is disabled for LUCI Project %q", lProject), } } So(runNotifier.popCancel(), ShouldResemble, reqs) Convey("wait for all IncompleteRuns to finish", func() { So(pmNotifier.NotifyRunFinished(ctx, common.RunID(lProject+"/111-beef")), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(p.IncompleteRuns(), ShouldResemble, common.MakeRunIDs(lProject+"/222-cafe")) So(plog, ShouldBeNil) // still STOPPING. So(pmNotifier.NotifyRunFinished(ctx, common.RunID(lProject+"/222-cafe")), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog = loadProjectEntities(ctx, lProject) So(ps.Status, ShouldEqual, prjpb.Status_STOPPED) So(p.IncompleteRuns(), ShouldBeEmpty) So(plog, ShouldNotBeNil) }) }) }) Convey("delete project without incomplete runs", func() { // No components means also no runs. p.State.Components = nil prjcfgtest.Delete(ctx, lProject) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 2) So(ps.Status, ShouldEqual, prjpb.Status_STOPPED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) }) }) }) } func TestProjectHandlesManyEvents(t *testing.T) { t.Parallel() Convey("PM handles many events", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() const lProject = "infra" const gHost = "host" const gRepo = "repo" recipient := prjmanager.EventboxRecipient(ctx, lProject) pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) pm := New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) cfg := singleRepoConfig(gHost, gRepo) cfg.ConfigGroups[0].CombineCls = &cfgpb.CombineCLs{ // Postpone creation of Runs, which isn't important in this test. StabilizationDelay: durationpb.New(time.Hour), } prjcfgtest.Create(ctx, lProject, cfg) gobmaptest.Update(ctx, lProject) // Put #43 CL directly w/o notifying the PM. cl43 := changelist.MustGobID(gHost, 43).MustCreateIfNotExists(ctx) cl43.Snapshot = &changelist.Snapshot{ ExternalUpdateTime: timestamppb.New(ct.Clock.Now()), LuciProject: lProject, MinEquivalentPatchset: 1, Patchset: 1, Kind: &changelist.Snapshot_Gerrit{Gerrit: &changelist.Gerrit{ Host: gHost, Info: gf.CI(43, gf.Project(gRepo), gf.Ref("refs/heads/main"), gf.CQ(+2, ct.Clock.Now(), gf.U("user-1"))), }}, } meta := prjcfgtest.MustExist(ctx, lProject) cl43.ApplicableConfig = &changelist.ApplicableConfig{ Projects: []*changelist.ApplicableConfig_Project{ {Name: lProject, ConfigGroupIds: []string{string(meta.ConfigGroupIDs[0])}}, }, } So(datastore.Put(ctx, cl43), ShouldBeNil) cl44 := changelist.MustGobID(gHost, 44).MustCreateIfNotExists(ctx) cl44.Snapshot = &changelist.Snapshot{ ExternalUpdateTime: timestamppb.New(ct.Clock.Now()), LuciProject: lProject, MinEquivalentPatchset: 1, Patchset: 1, Kind: &changelist.Snapshot_Gerrit{Gerrit: &changelist.Gerrit{ Info: gf.CI( 44, gf.Project(gRepo), gf.Ref("refs/heads/main"), gf.CQ(+2, ct.Clock.Now(), gf.U("user-1"))), }}, } cl44.ApplicableConfig = &changelist.ApplicableConfig{ Projects: []*changelist.ApplicableConfig_Project{ {Name: lProject, ConfigGroupIds: []string{string(meta.ConfigGroupIDs[0])}}, }, } So(datastore.Put(ctx, cl44), ShouldBeNil) // This event is the only event notifying PM about CL#43. So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl43, cl44)), ShouldBeNil) const n = 20 for i := 0; i < n; i++ { So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmNotifier.Poke(ctx, lProject), ShouldBeNil) // Simulate updating a CL. cl44.EVersion++ So(datastore.Put(ctx, cl44), ShouldBeNil) So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl44)), ShouldBeNil) } events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Expect the following events: // +1 from NotifyCLsUpdated on cl43 and cl44, // +3*n from loop. So(events, ShouldHaveLength, 3*n+1) // Run `w` concurrent PMs. const w = 20 now := ct.Clock.Now() errs := make(errors.MultiError, w) wg := sync.WaitGroup{} wg.Add(w) for i := 0; i < w; i++ { i := i go func() { defer wg.Done() errs[i] = pm.manageProject(ctx, lProject, now) }() } wg.Wait() // Exactly 1 of the workers must create PM entity, consume events and // poke the poller. p := prjmanager.Project{ID: lProject} So(datastore.Get(ctx, &p), ShouldBeNil) // Both cl43 and cl44 must have corresponding PCLs with latest EVersions. So(p.State.GetPcls(), ShouldHaveLength, 2) for _, pcl := range p.State.GetPcls() { switch common.CLID(pcl.GetClid()) { case cl43.ID: So(pcl.GetEversion(), ShouldEqual, cl43.EVersion) case cl44.ID: So(pcl.GetEversion(), ShouldEqual, cl44.EVersion) default: So("must not happen", ShouldBeTrue) } } events, err = eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events, ShouldBeEmpty) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // At least 1 worker must finish successfully. errCnt, _ := errs.Summary() t.Logf("%d/%d workers failed", errCnt, w) So(errCnt, ShouldBeLessThan, w) }) } func loadProjectEntities(ctx context.Context, luciProject string) ( *prjmanager.Project, *prjmanager.ProjectStateOffload, *prjmanager.ProjectLog, ) { p := &prjmanager.Project{ID: luciProject} switch err := datastore.Get(ctx, p); { case err == datastore.ErrNoSuchEntity: return nil, nil, nil case err != nil: panic(err) } key := datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject) ps := &prjmanager.ProjectStateOffload{Project: key} if err := datastore.Get(ctx, ps); err != nil { // ProjectStateOffload must exist if Project exists. panic(err) } plog := &prjmanager.ProjectLog{ Project: datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject), EVersion: p.EVersion, } switch err := datastore.Get(ctx, plog); { case err == datastore.ErrNoSuchEntity: return p, ps, nil case err != nil: panic(err) default: // Quick check invariant that plog replicates what's stored in Project & // ProjectStateOffload entities at the same EVersion. So(plog.EVersion, ShouldEqual, p.EVersion) So(plog.Status, ShouldEqual, ps.Status) So(plog.ConfigHash, ShouldEqual, ps.ConfigHash) So(plog.State, ShouldResembleProto, p.State) So(plog.Reasons, ShouldNotBeEmpty) return p, ps, plog } } func singleRepoConfig(gHost string, gRepos ...string) *cfgpb.Config { projects := make([]*cfgpb.ConfigGroup_Gerrit_Project, len(gRepos)) for i, gRepo := range gRepos { projects[i] = &cfgpb.ConfigGroup_Gerrit_Project{ Name: gRepo, RefRegexp: []string{"refs/heads/main"}, } } return &cfgpb.Config{ ConfigGroups: []*cfgpb.ConfigGroup{ { Name: "main", Gerrit: []*cfgpb.ConfigGroup_Gerrit{ { Url: "https://" + gHost + "/", Projects: projects, }, }, }, }, } } type runNotifierMock struct { m sync.Mutex cancel []cancellationRequest updateConfig common.RunIDs } type cancellationRequest struct { id common.RunID reason string } func (r *runNotifierMock) NotifyCLsUpdated(ctx context.Context, rid common.RunID, cls *changelist.CLUpdatedEvents) error { panic("not implemented") } func (r *runNotifierMock) Start(ctx context.Context, id common.RunID) error { return nil } func (r *runNotifierMock) PokeNow(ctx context.Context, id common.RunID) error { panic("not implemented") } func (r *runNotifierMock) Cancel(ctx context.Context, id common.RunID, reason string) error { r.m.Lock() r.cancel = append(r.cancel, cancellationRequest{id: id, reason: reason}) r.m.Unlock() return nil } func (r *runNotifierMock) UpdateConfig(ctx context.Context, id common.RunID, hash string, eversion int64) error { r.m.Lock() r.updateConfig = append(r.updateConfig, id) r.m.Unlock() return nil } func (r *runNotifierMock) popUpdateConfig() common.RunIDs { r.m.Lock() out := r.updateConfig r.updateConfig = nil r.m.Unlock() sort.Sort(out) return out } func (r *runNotifierMock) popCancel() []cancellationRequest { r.m.Lock() out := r.cancel r.cancel = nil r.m.Unlock() sort.Slice(out, func(i, j int) bool { return out[i].id < out[j].id }) return out } type tjMock struct{} func (t *tjMock) ScheduleCancelStale(ctx context.Context, clid common.CLID, prevMinEquivalentPatchset, currentMinEquivalentPatchset int32, eta time.Time) error { return nil }
{ t.Parallel() Convey("PM task does nothing if it comes too late", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) _ = New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) const lProject = "infra" recipient := prjmanager.EventboxRecipient(ctx, lProject) prjcfgtest.Create(ctx, lProject, singleRepoConfig("host", "repo")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) events1, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Simulate stuck TQ task, which gets executed with a huge delay. ct.Clock.Add(time.Hour) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) // It must not modify PM state nor consume events. So(datastore.Get(ctx, &prjmanager.Project{ID: lProject}), ShouldEqual, datastore.ErrNoSuchEntity) events2, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events2, ShouldResemble, events1) // But schedules new task instead. So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) // Next task coming ~on time proceeds normally. ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) So(datastore.Get(ctx, &prjmanager.Project{ID: lProject}), ShouldBeNil) events3, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events3, ShouldBeEmpty) }) }
identifier_body
manager_test.go
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "context" "fmt" "sort" "sync" "testing" "time" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/gae/service/datastore" "go.chromium.org/luci/server/tq/tqtesting" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" cfgpb "go.chromium.org/luci/cv/api/config/v2" "go.chromium.org/luci/cv/internal/changelist" "go.chromium.org/luci/cv/internal/common" "go.chromium.org/luci/cv/internal/common/eventbox" "go.chromium.org/luci/cv/internal/configs/prjcfg/prjcfgtest" "go.chromium.org/luci/cv/internal/cvtesting" gf "go.chromium.org/luci/cv/internal/gerrit/gerritfake" "go.chromium.org/luci/cv/internal/gerrit/gobmap/gobmaptest" "go.chromium.org/luci/cv/internal/gerrit/poller" gerritupdater "go.chromium.org/luci/cv/internal/gerrit/updater" "go.chromium.org/luci/cv/internal/prjmanager" "go.chromium.org/luci/cv/internal/prjmanager/pmtest" "go.chromium.org/luci/cv/internal/prjmanager/prjpb" "go.chromium.org/luci/cv/internal/run" . "github.com/smartystreets/goconvey/convey" . "go.chromium.org/luci/common/testing/assertions" ) func TestProjectTQLateTasks(t *testing.T) { t.Parallel() Convey("PM task does nothing if it comes too late", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) _ = New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) const lProject = "infra" recipient := prjmanager.EventboxRecipient(ctx, lProject) prjcfgtest.Create(ctx, lProject, singleRepoConfig("host", "repo")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) events1, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Simulate stuck TQ task, which gets executed with a huge delay. ct.Clock.Add(time.Hour) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) // It must not modify PM state nor consume events. So(datastore.Get(ctx, &prjmanager.Project{ID: lProject}), ShouldEqual, datastore.ErrNoSuchEntity) events2, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events2, ShouldResemble, events1) // But schedules new task instead. So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) // Next task coming ~on time proceeds normally. ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) So(datastore.Get(ctx, &prjmanager.Project{ID: lProject}), ShouldBeNil) events3, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events3, ShouldBeEmpty) }) } func TestProjectLifeCycle(t *testing.T) { t.Parallel() Convey("Project can be created, updated, deleted", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) _ = New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) const lProject = "infra" recipient := prjmanager.EventboxRecipient(ctx, lProject) Convey("with new project", func() { prjcfgtest.Create(ctx, lProject, singleRepoConfig("host", "repo")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) // Second event is a noop, but should still be consumed at once. So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events, ShouldHaveLength, 0) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 1) So(ps.Status, ShouldEqual, prjpb.Status_STARTED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Ensure first poller task gets executed. ct.Clock.Add(time.Hour) Convey("update config with incomplete runs", func() { err := datastore.Put( ctx, &run.Run{ID: common.RunID(lProject + "/111-beef"), CLs: common.CLIDs{111}}, &run.Run{ID: common.RunID(lProject + "/222-cafe"), CLs: common.CLIDs{222}}, ) So(err, ShouldBeNil) // This is what pmNotifier.notifyRunCreated func does, // but because it's private, it can't be called from this package. simulateRunCreated := func(suffix string) { e := &prjpb.Event{Event: &prjpb.Event_RunCreated{ RunCreated: &prjpb.RunCreated{ RunId: lProject + "/" + suffix, }, }} value, err := proto.Marshal(e) So(err, ShouldBeNil) So(eventbox.Emit(ctx, value, recipient), ShouldBeNil) } simulateRunCreated("111-beef") simulateRunCreated("222-cafe") prjcfgtest.Update(ctx, lProject, singleRepoConfig("host", "repo2")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, _, plog = loadProjectEntities(ctx, lProject) So(p.IncompleteRuns(), ShouldEqual, common.MakeRunIDs(lProject+"/111-beef", lProject+"/222-cafe")) So(plog, ShouldNotBeNil) So(runNotifier.popUpdateConfig(), ShouldResemble, p.IncompleteRuns()) Convey("disable project with incomplete runs", func() { prjcfgtest.Disable(ctx, lProject) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 3) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Should ask Runs to cancel themselves. reqs := make([]cancellationRequest, len(p.IncompleteRuns())) for i, runID := range p.IncompleteRuns() { reqs[i] = cancellationRequest{ id: runID, reason: fmt.Sprintf("CV is disabled for LUCI Project %q", lProject), } } So(runNotifier.popCancel(), ShouldResemble, reqs) Convey("wait for all IncompleteRuns to finish", func() { So(pmNotifier.NotifyRunFinished(ctx, common.RunID(lProject+"/111-beef")), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(p.IncompleteRuns(), ShouldResemble, common.MakeRunIDs(lProject+"/222-cafe")) So(plog, ShouldBeNil) // still STOPPING. So(pmNotifier.NotifyRunFinished(ctx, common.RunID(lProject+"/222-cafe")), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog = loadProjectEntities(ctx, lProject) So(ps.Status, ShouldEqual, prjpb.Status_STOPPED) So(p.IncompleteRuns(), ShouldBeEmpty) So(plog, ShouldNotBeNil) }) }) }) Convey("delete project without incomplete runs", func() { // No components means also no runs. p.State.Components = nil prjcfgtest.Delete(ctx, lProject) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 2) So(ps.Status, ShouldEqual, prjpb.Status_STOPPED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) }) }) }) } func TestProjectHandlesManyEvents(t *testing.T) { t.Parallel() Convey("PM handles many events", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() const lProject = "infra" const gHost = "host" const gRepo = "repo" recipient := prjmanager.EventboxRecipient(ctx, lProject) pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) pm := New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) cfg := singleRepoConfig(gHost, gRepo) cfg.ConfigGroups[0].CombineCls = &cfgpb.CombineCLs{ // Postpone creation of Runs, which isn't important in this test. StabilizationDelay: durationpb.New(time.Hour), } prjcfgtest.Create(ctx, lProject, cfg) gobmaptest.Update(ctx, lProject) // Put #43 CL directly w/o notifying the PM. cl43 := changelist.MustGobID(gHost, 43).MustCreateIfNotExists(ctx) cl43.Snapshot = &changelist.Snapshot{ ExternalUpdateTime: timestamppb.New(ct.Clock.Now()), LuciProject: lProject, MinEquivalentPatchset: 1, Patchset: 1, Kind: &changelist.Snapshot_Gerrit{Gerrit: &changelist.Gerrit{ Host: gHost, Info: gf.CI(43, gf.Project(gRepo), gf.Ref("refs/heads/main"), gf.CQ(+2, ct.Clock.Now(), gf.U("user-1"))), }}, } meta := prjcfgtest.MustExist(ctx, lProject) cl43.ApplicableConfig = &changelist.ApplicableConfig{ Projects: []*changelist.ApplicableConfig_Project{ {Name: lProject, ConfigGroupIds: []string{string(meta.ConfigGroupIDs[0])}}, }, } So(datastore.Put(ctx, cl43), ShouldBeNil) cl44 := changelist.MustGobID(gHost, 44).MustCreateIfNotExists(ctx) cl44.Snapshot = &changelist.Snapshot{ ExternalUpdateTime: timestamppb.New(ct.Clock.Now()), LuciProject: lProject, MinEquivalentPatchset: 1, Patchset: 1, Kind: &changelist.Snapshot_Gerrit{Gerrit: &changelist.Gerrit{ Info: gf.CI( 44, gf.Project(gRepo), gf.Ref("refs/heads/main"), gf.CQ(+2, ct.Clock.Now(), gf.U("user-1"))), }}, } cl44.ApplicableConfig = &changelist.ApplicableConfig{ Projects: []*changelist.ApplicableConfig_Project{ {Name: lProject, ConfigGroupIds: []string{string(meta.ConfigGroupIDs[0])}}, }, } So(datastore.Put(ctx, cl44), ShouldBeNil) // This event is the only event notifying PM about CL#43. So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl43, cl44)), ShouldBeNil) const n = 20 for i := 0; i < n; i++
events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Expect the following events: // +1 from NotifyCLsUpdated on cl43 and cl44, // +3*n from loop. So(events, ShouldHaveLength, 3*n+1) // Run `w` concurrent PMs. const w = 20 now := ct.Clock.Now() errs := make(errors.MultiError, w) wg := sync.WaitGroup{} wg.Add(w) for i := 0; i < w; i++ { i := i go func() { defer wg.Done() errs[i] = pm.manageProject(ctx, lProject, now) }() } wg.Wait() // Exactly 1 of the workers must create PM entity, consume events and // poke the poller. p := prjmanager.Project{ID: lProject} So(datastore.Get(ctx, &p), ShouldBeNil) // Both cl43 and cl44 must have corresponding PCLs with latest EVersions. So(p.State.GetPcls(), ShouldHaveLength, 2) for _, pcl := range p.State.GetPcls() { switch common.CLID(pcl.GetClid()) { case cl43.ID: So(pcl.GetEversion(), ShouldEqual, cl43.EVersion) case cl44.ID: So(pcl.GetEversion(), ShouldEqual, cl44.EVersion) default: So("must not happen", ShouldBeTrue) } } events, err = eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events, ShouldBeEmpty) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // At least 1 worker must finish successfully. errCnt, _ := errs.Summary() t.Logf("%d/%d workers failed", errCnt, w) So(errCnt, ShouldBeLessThan, w) }) } func loadProjectEntities(ctx context.Context, luciProject string) ( *prjmanager.Project, *prjmanager.ProjectStateOffload, *prjmanager.ProjectLog, ) { p := &prjmanager.Project{ID: luciProject} switch err := datastore.Get(ctx, p); { case err == datastore.ErrNoSuchEntity: return nil, nil, nil case err != nil: panic(err) } key := datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject) ps := &prjmanager.ProjectStateOffload{Project: key} if err := datastore.Get(ctx, ps); err != nil { // ProjectStateOffload must exist if Project exists. panic(err) } plog := &prjmanager.ProjectLog{ Project: datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject), EVersion: p.EVersion, } switch err := datastore.Get(ctx, plog); { case err == datastore.ErrNoSuchEntity: return p, ps, nil case err != nil: panic(err) default: // Quick check invariant that plog replicates what's stored in Project & // ProjectStateOffload entities at the same EVersion. So(plog.EVersion, ShouldEqual, p.EVersion) So(plog.Status, ShouldEqual, ps.Status) So(plog.ConfigHash, ShouldEqual, ps.ConfigHash) So(plog.State, ShouldResembleProto, p.State) So(plog.Reasons, ShouldNotBeEmpty) return p, ps, plog } } func singleRepoConfig(gHost string, gRepos ...string) *cfgpb.Config { projects := make([]*cfgpb.ConfigGroup_Gerrit_Project, len(gRepos)) for i, gRepo := range gRepos { projects[i] = &cfgpb.ConfigGroup_Gerrit_Project{ Name: gRepo, RefRegexp: []string{"refs/heads/main"}, } } return &cfgpb.Config{ ConfigGroups: []*cfgpb.ConfigGroup{ { Name: "main", Gerrit: []*cfgpb.ConfigGroup_Gerrit{ { Url: "https://" + gHost + "/", Projects: projects, }, }, }, }, } } type runNotifierMock struct { m sync.Mutex cancel []cancellationRequest updateConfig common.RunIDs } type cancellationRequest struct { id common.RunID reason string } func (r *runNotifierMock) NotifyCLsUpdated(ctx context.Context, rid common.RunID, cls *changelist.CLUpdatedEvents) error { panic("not implemented") } func (r *runNotifierMock) Start(ctx context.Context, id common.RunID) error { return nil } func (r *runNotifierMock) PokeNow(ctx context.Context, id common.RunID) error { panic("not implemented") } func (r *runNotifierMock) Cancel(ctx context.Context, id common.RunID, reason string) error { r.m.Lock() r.cancel = append(r.cancel, cancellationRequest{id: id, reason: reason}) r.m.Unlock() return nil } func (r *runNotifierMock) UpdateConfig(ctx context.Context, id common.RunID, hash string, eversion int64) error { r.m.Lock() r.updateConfig = append(r.updateConfig, id) r.m.Unlock() return nil } func (r *runNotifierMock) popUpdateConfig() common.RunIDs { r.m.Lock() out := r.updateConfig r.updateConfig = nil r.m.Unlock() sort.Sort(out) return out } func (r *runNotifierMock) popCancel() []cancellationRequest { r.m.Lock() out := r.cancel r.cancel = nil r.m.Unlock() sort.Slice(out, func(i, j int) bool { return out[i].id < out[j].id }) return out } type tjMock struct{} func (t *tjMock) ScheduleCancelStale(ctx context.Context, clid common.CLID, prevMinEquivalentPatchset, currentMinEquivalentPatchset int32, eta time.Time) error { return nil }
{ So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmNotifier.Poke(ctx, lProject), ShouldBeNil) // Simulate updating a CL. cl44.EVersion++ So(datastore.Put(ctx, cl44), ShouldBeNil) So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl44)), ShouldBeNil) }
conditional_block
manager_test.go
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "context" "fmt" "sort" "sync" "testing" "time" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/gae/service/datastore" "go.chromium.org/luci/server/tq/tqtesting" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" cfgpb "go.chromium.org/luci/cv/api/config/v2" "go.chromium.org/luci/cv/internal/changelist" "go.chromium.org/luci/cv/internal/common" "go.chromium.org/luci/cv/internal/common/eventbox" "go.chromium.org/luci/cv/internal/configs/prjcfg/prjcfgtest" "go.chromium.org/luci/cv/internal/cvtesting" gf "go.chromium.org/luci/cv/internal/gerrit/gerritfake" "go.chromium.org/luci/cv/internal/gerrit/gobmap/gobmaptest" "go.chromium.org/luci/cv/internal/gerrit/poller" gerritupdater "go.chromium.org/luci/cv/internal/gerrit/updater" "go.chromium.org/luci/cv/internal/prjmanager" "go.chromium.org/luci/cv/internal/prjmanager/pmtest" "go.chromium.org/luci/cv/internal/prjmanager/prjpb" "go.chromium.org/luci/cv/internal/run" . "github.com/smartystreets/goconvey/convey" . "go.chromium.org/luci/common/testing/assertions" ) func TestProjectTQLateTasks(t *testing.T) { t.Parallel() Convey("PM task does nothing if it comes too late", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) _ = New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) const lProject = "infra" recipient := prjmanager.EventboxRecipient(ctx, lProject) prjcfgtest.Create(ctx, lProject, singleRepoConfig("host", "repo")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) events1, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Simulate stuck TQ task, which gets executed with a huge delay. ct.Clock.Add(time.Hour) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) // It must not modify PM state nor consume events. So(datastore.Get(ctx, &prjmanager.Project{ID: lProject}), ShouldEqual, datastore.ErrNoSuchEntity) events2, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events2, ShouldResemble, events1) // But schedules new task instead. So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) // Next task coming ~on time proceeds normally. ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) So(datastore.Get(ctx, &prjmanager.Project{ID: lProject}), ShouldBeNil) events3, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events3, ShouldBeEmpty) }) } func TestProjectLifeCycle(t *testing.T) { t.Parallel() Convey("Project can be created, updated, deleted", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) _ = New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) const lProject = "infra" recipient := prjmanager.EventboxRecipient(ctx, lProject) Convey("with new project", func() { prjcfgtest.Create(ctx, lProject, singleRepoConfig("host", "repo")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) // Second event is a noop, but should still be consumed at once. So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events, ShouldHaveLength, 0) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 1) So(ps.Status, ShouldEqual, prjpb.Status_STARTED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Ensure first poller task gets executed. ct.Clock.Add(time.Hour) Convey("update config with incomplete runs", func() { err := datastore.Put( ctx, &run.Run{ID: common.RunID(lProject + "/111-beef"), CLs: common.CLIDs{111}}, &run.Run{ID: common.RunID(lProject + "/222-cafe"), CLs: common.CLIDs{222}}, ) So(err, ShouldBeNil) // This is what pmNotifier.notifyRunCreated func does, // but because it's private, it can't be called from this package. simulateRunCreated := func(suffix string) { e := &prjpb.Event{Event: &prjpb.Event_RunCreated{ RunCreated: &prjpb.RunCreated{ RunId: lProject + "/" + suffix, }, }} value, err := proto.Marshal(e) So(err, ShouldBeNil) So(eventbox.Emit(ctx, value, recipient), ShouldBeNil) } simulateRunCreated("111-beef") simulateRunCreated("222-cafe") prjcfgtest.Update(ctx, lProject, singleRepoConfig("host", "repo2")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, _, plog = loadProjectEntities(ctx, lProject) So(p.IncompleteRuns(), ShouldEqual, common.MakeRunIDs(lProject+"/111-beef", lProject+"/222-cafe")) So(plog, ShouldNotBeNil) So(runNotifier.popUpdateConfig(), ShouldResemble, p.IncompleteRuns()) Convey("disable project with incomplete runs", func() { prjcfgtest.Disable(ctx, lProject) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 3) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Should ask Runs to cancel themselves. reqs := make([]cancellationRequest, len(p.IncompleteRuns())) for i, runID := range p.IncompleteRuns() { reqs[i] = cancellationRequest{ id: runID, reason: fmt.Sprintf("CV is disabled for LUCI Project %q", lProject), } } So(runNotifier.popCancel(), ShouldResemble, reqs) Convey("wait for all IncompleteRuns to finish", func() { So(pmNotifier.NotifyRunFinished(ctx, common.RunID(lProject+"/111-beef")), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(p.IncompleteRuns(), ShouldResemble, common.MakeRunIDs(lProject+"/222-cafe")) So(plog, ShouldBeNil) // still STOPPING. So(pmNotifier.NotifyRunFinished(ctx, common.RunID(lProject+"/222-cafe")), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog = loadProjectEntities(ctx, lProject) So(ps.Status, ShouldEqual, prjpb.Status_STOPPED) So(p.IncompleteRuns(), ShouldBeEmpty) So(plog, ShouldNotBeNil) }) }) }) Convey("delete project without incomplete runs", func() { // No components means also no runs. p.State.Components = nil prjcfgtest.Delete(ctx, lProject) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 2) So(ps.Status, ShouldEqual, prjpb.Status_STOPPED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) }) }) }) } func TestProjectHandlesManyEvents(t *testing.T) { t.Parallel() Convey("PM handles many events", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() const lProject = "infra" const gHost = "host" const gRepo = "repo" recipient := prjmanager.EventboxRecipient(ctx, lProject) pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) pm := New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) cfg := singleRepoConfig(gHost, gRepo) cfg.ConfigGroups[0].CombineCls = &cfgpb.CombineCLs{ // Postpone creation of Runs, which isn't important in this test. StabilizationDelay: durationpb.New(time.Hour), } prjcfgtest.Create(ctx, lProject, cfg) gobmaptest.Update(ctx, lProject) // Put #43 CL directly w/o notifying the PM. cl43 := changelist.MustGobID(gHost, 43).MustCreateIfNotExists(ctx) cl43.Snapshot = &changelist.Snapshot{ ExternalUpdateTime: timestamppb.New(ct.Clock.Now()), LuciProject: lProject, MinEquivalentPatchset: 1, Patchset: 1, Kind: &changelist.Snapshot_Gerrit{Gerrit: &changelist.Gerrit{ Host: gHost, Info: gf.CI(43, gf.Project(gRepo), gf.Ref("refs/heads/main"), gf.CQ(+2, ct.Clock.Now(), gf.U("user-1"))), }}, } meta := prjcfgtest.MustExist(ctx, lProject) cl43.ApplicableConfig = &changelist.ApplicableConfig{ Projects: []*changelist.ApplicableConfig_Project{ {Name: lProject, ConfigGroupIds: []string{string(meta.ConfigGroupIDs[0])}}, }, } So(datastore.Put(ctx, cl43), ShouldBeNil) cl44 := changelist.MustGobID(gHost, 44).MustCreateIfNotExists(ctx) cl44.Snapshot = &changelist.Snapshot{ ExternalUpdateTime: timestamppb.New(ct.Clock.Now()), LuciProject: lProject, MinEquivalentPatchset: 1, Patchset: 1, Kind: &changelist.Snapshot_Gerrit{Gerrit: &changelist.Gerrit{ Info: gf.CI( 44, gf.Project(gRepo), gf.Ref("refs/heads/main"), gf.CQ(+2, ct.Clock.Now(), gf.U("user-1"))), }}, } cl44.ApplicableConfig = &changelist.ApplicableConfig{ Projects: []*changelist.ApplicableConfig_Project{ {Name: lProject, ConfigGroupIds: []string{string(meta.ConfigGroupIDs[0])}}, }, } So(datastore.Put(ctx, cl44), ShouldBeNil) // This event is the only event notifying PM about CL#43. So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl43, cl44)), ShouldBeNil) const n = 20 for i := 0; i < n; i++ { So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmNotifier.Poke(ctx, lProject), ShouldBeNil) // Simulate updating a CL. cl44.EVersion++ So(datastore.Put(ctx, cl44), ShouldBeNil) So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl44)), ShouldBeNil) } events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Expect the following events: // +1 from NotifyCLsUpdated on cl43 and cl44, // +3*n from loop. So(events, ShouldHaveLength, 3*n+1) // Run `w` concurrent PMs. const w = 20 now := ct.Clock.Now() errs := make(errors.MultiError, w) wg := sync.WaitGroup{} wg.Add(w) for i := 0; i < w; i++ { i := i go func() { defer wg.Done() errs[i] = pm.manageProject(ctx, lProject, now) }() } wg.Wait() // Exactly 1 of the workers must create PM entity, consume events and // poke the poller. p := prjmanager.Project{ID: lProject} So(datastore.Get(ctx, &p), ShouldBeNil) // Both cl43 and cl44 must have corresponding PCLs with latest EVersions. So(p.State.GetPcls(), ShouldHaveLength, 2) for _, pcl := range p.State.GetPcls() { switch common.CLID(pcl.GetClid()) { case cl43.ID: So(pcl.GetEversion(), ShouldEqual, cl43.EVersion) case cl44.ID: So(pcl.GetEversion(), ShouldEqual, cl44.EVersion) default: So("must not happen", ShouldBeTrue) } } events, err = eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events, ShouldBeEmpty) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // At least 1 worker must finish successfully. errCnt, _ := errs.Summary() t.Logf("%d/%d workers failed", errCnt, w) So(errCnt, ShouldBeLessThan, w) }) } func loadProjectEntities(ctx context.Context, luciProject string) ( *prjmanager.Project, *prjmanager.ProjectStateOffload, *prjmanager.ProjectLog, ) { p := &prjmanager.Project{ID: luciProject} switch err := datastore.Get(ctx, p); { case err == datastore.ErrNoSuchEntity: return nil, nil, nil case err != nil: panic(err) } key := datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject) ps := &prjmanager.ProjectStateOffload{Project: key} if err := datastore.Get(ctx, ps); err != nil { // ProjectStateOffload must exist if Project exists. panic(err) } plog := &prjmanager.ProjectLog{ Project: datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject), EVersion: p.EVersion, } switch err := datastore.Get(ctx, plog); { case err == datastore.ErrNoSuchEntity: return p, ps, nil case err != nil: panic(err) default: // Quick check invariant that plog replicates what's stored in Project & // ProjectStateOffload entities at the same EVersion. So(plog.EVersion, ShouldEqual, p.EVersion) So(plog.Status, ShouldEqual, ps.Status) So(plog.ConfigHash, ShouldEqual, ps.ConfigHash) So(plog.State, ShouldResembleProto, p.State) So(plog.Reasons, ShouldNotBeEmpty) return p, ps, plog } } func singleRepoConfig(gHost string, gRepos ...string) *cfgpb.Config { projects := make([]*cfgpb.ConfigGroup_Gerrit_Project, len(gRepos)) for i, gRepo := range gRepos { projects[i] = &cfgpb.ConfigGroup_Gerrit_Project{ Name: gRepo, RefRegexp: []string{"refs/heads/main"}, } } return &cfgpb.Config{ ConfigGroups: []*cfgpb.ConfigGroup{ { Name: "main", Gerrit: []*cfgpb.ConfigGroup_Gerrit{ { Url: "https://" + gHost + "/", Projects: projects, }, }, }, }, } } type runNotifierMock struct { m sync.Mutex cancel []cancellationRequest updateConfig common.RunIDs } type cancellationRequest struct { id common.RunID reason string } func (r *runNotifierMock) NotifyCLsUpdated(ctx context.Context, rid common.RunID, cls *changelist.CLUpdatedEvents) error { panic("not implemented") } func (r *runNotifierMock) Start(ctx context.Context, id common.RunID) error { return nil } func (r *runNotifierMock) PokeNow(ctx context.Context, id common.RunID) error { panic("not implemented") } func (r *runNotifierMock) Cancel(ctx context.Context, id common.RunID, reason string) error { r.m.Lock() r.cancel = append(r.cancel, cancellationRequest{id: id, reason: reason}) r.m.Unlock() return nil } func (r *runNotifierMock) UpdateConfig(ctx context.Context, id common.RunID, hash string, eversion int64) error { r.m.Lock() r.updateConfig = append(r.updateConfig, id) r.m.Unlock() return nil } func (r *runNotifierMock)
() common.RunIDs { r.m.Lock() out := r.updateConfig r.updateConfig = nil r.m.Unlock() sort.Sort(out) return out } func (r *runNotifierMock) popCancel() []cancellationRequest { r.m.Lock() out := r.cancel r.cancel = nil r.m.Unlock() sort.Slice(out, func(i, j int) bool { return out[i].id < out[j].id }) return out } type tjMock struct{} func (t *tjMock) ScheduleCancelStale(ctx context.Context, clid common.CLID, prevMinEquivalentPatchset, currentMinEquivalentPatchset int32, eta time.Time) error { return nil }
popUpdateConfig
identifier_name
manager_test.go
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "context" "fmt" "sort" "sync" "testing" "time" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/gae/service/datastore" "go.chromium.org/luci/server/tq/tqtesting" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" cfgpb "go.chromium.org/luci/cv/api/config/v2" "go.chromium.org/luci/cv/internal/changelist" "go.chromium.org/luci/cv/internal/common" "go.chromium.org/luci/cv/internal/common/eventbox" "go.chromium.org/luci/cv/internal/configs/prjcfg/prjcfgtest" "go.chromium.org/luci/cv/internal/cvtesting" gf "go.chromium.org/luci/cv/internal/gerrit/gerritfake" "go.chromium.org/luci/cv/internal/gerrit/gobmap/gobmaptest" "go.chromium.org/luci/cv/internal/gerrit/poller" gerritupdater "go.chromium.org/luci/cv/internal/gerrit/updater" "go.chromium.org/luci/cv/internal/prjmanager" "go.chromium.org/luci/cv/internal/prjmanager/pmtest" "go.chromium.org/luci/cv/internal/prjmanager/prjpb" "go.chromium.org/luci/cv/internal/run" . "github.com/smartystreets/goconvey/convey" . "go.chromium.org/luci/common/testing/assertions" ) func TestProjectTQLateTasks(t *testing.T) { t.Parallel() Convey("PM task does nothing if it comes too late", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) _ = New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) const lProject = "infra" recipient := prjmanager.EventboxRecipient(ctx, lProject) prjcfgtest.Create(ctx, lProject, singleRepoConfig("host", "repo")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) events1, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Simulate stuck TQ task, which gets executed with a huge delay. ct.Clock.Add(time.Hour) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) // It must not modify PM state nor consume events. So(datastore.Get(ctx, &prjmanager.Project{ID: lProject}), ShouldEqual, datastore.ErrNoSuchEntity) events2, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events2, ShouldResemble, events1) // But schedules new task instead. So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) // Next task coming ~on time proceeds normally. ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) So(datastore.Get(ctx, &prjmanager.Project{ID: lProject}), ShouldBeNil) events3, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events3, ShouldBeEmpty) }) } func TestProjectLifeCycle(t *testing.T) { t.Parallel() Convey("Project can be created, updated, deleted", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) _ = New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) const lProject = "infra" recipient := prjmanager.EventboxRecipient(ctx, lProject) Convey("with new project", func() { prjcfgtest.Create(ctx, lProject, singleRepoConfig("host", "repo")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) // Second event is a noop, but should still be consumed at once. So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events, ShouldHaveLength, 0) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 1) So(ps.Status, ShouldEqual, prjpb.Status_STARTED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Ensure first poller task gets executed. ct.Clock.Add(time.Hour) Convey("update config with incomplete runs", func() { err := datastore.Put( ctx, &run.Run{ID: common.RunID(lProject + "/111-beef"), CLs: common.CLIDs{111}}, &run.Run{ID: common.RunID(lProject + "/222-cafe"), CLs: common.CLIDs{222}}, ) So(err, ShouldBeNil) // This is what pmNotifier.notifyRunCreated func does, // but because it's private, it can't be called from this package. simulateRunCreated := func(suffix string) { e := &prjpb.Event{Event: &prjpb.Event_RunCreated{ RunCreated: &prjpb.RunCreated{ RunId: lProject + "/" + suffix, }, }} value, err := proto.Marshal(e) So(err, ShouldBeNil) So(eventbox.Emit(ctx, value, recipient), ShouldBeNil) } simulateRunCreated("111-beef") simulateRunCreated("222-cafe") prjcfgtest.Update(ctx, lProject, singleRepoConfig("host", "repo2")) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, _, plog = loadProjectEntities(ctx, lProject) So(p.IncompleteRuns(), ShouldEqual, common.MakeRunIDs(lProject+"/111-beef", lProject+"/222-cafe")) So(plog, ShouldNotBeNil) So(runNotifier.popUpdateConfig(), ShouldResemble, p.IncompleteRuns()) Convey("disable project with incomplete runs", func() { prjcfgtest.Disable(ctx, lProject) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 3) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Should ask Runs to cancel themselves. reqs := make([]cancellationRequest, len(p.IncompleteRuns())) for i, runID := range p.IncompleteRuns() { reqs[i] = cancellationRequest{ id: runID, reason: fmt.Sprintf("CV is disabled for LUCI Project %q", lProject), } } So(runNotifier.popCancel(), ShouldResemble, reqs) Convey("wait for all IncompleteRuns to finish", func() { So(pmNotifier.NotifyRunFinished(ctx, common.RunID(lProject+"/111-beef")), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(p.IncompleteRuns(), ShouldResemble, common.MakeRunIDs(lProject+"/222-cafe")) So(plog, ShouldBeNil) // still STOPPING. So(pmNotifier.NotifyRunFinished(ctx, common.RunID(lProject+"/222-cafe")), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog = loadProjectEntities(ctx, lProject) So(ps.Status, ShouldEqual, prjpb.Status_STOPPED) So(p.IncompleteRuns(), ShouldBeEmpty) So(plog, ShouldNotBeNil) }) }) }) Convey("delete project without incomplete runs", func() { // No components means also no runs. p.State.Components = nil prjcfgtest.Delete(ctx, lProject) So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) ct.TQ.Run(ctx, tqtesting.StopAfterTask(prjpb.ManageProjectTaskClass)) p, ps, plog := loadProjectEntities(ctx, lProject) So(p.EVersion, ShouldEqual, 2) So(ps.Status, ShouldEqual, prjpb.Status_STOPPED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) }) }) }) } func TestProjectHandlesManyEvents(t *testing.T) { t.Parallel() Convey("PM handles many events", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() const lProject = "infra" const gHost = "host" const gRepo = "repo" recipient := prjmanager.EventboxRecipient(ctx, lProject) pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) pm := New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) cfg := singleRepoConfig(gHost, gRepo) cfg.ConfigGroups[0].CombineCls = &cfgpb.CombineCLs{ // Postpone creation of Runs, which isn't important in this test. StabilizationDelay: durationpb.New(time.Hour), } prjcfgtest.Create(ctx, lProject, cfg) gobmaptest.Update(ctx, lProject) // Put #43 CL directly w/o notifying the PM. cl43 := changelist.MustGobID(gHost, 43).MustCreateIfNotExists(ctx) cl43.Snapshot = &changelist.Snapshot{ ExternalUpdateTime: timestamppb.New(ct.Clock.Now()), LuciProject: lProject, MinEquivalentPatchset: 1, Patchset: 1, Kind: &changelist.Snapshot_Gerrit{Gerrit: &changelist.Gerrit{ Host: gHost, Info: gf.CI(43, gf.Project(gRepo), gf.Ref("refs/heads/main"), gf.CQ(+2, ct.Clock.Now(), gf.U("user-1"))), }}, } meta := prjcfgtest.MustExist(ctx, lProject) cl43.ApplicableConfig = &changelist.ApplicableConfig{ Projects: []*changelist.ApplicableConfig_Project{ {Name: lProject, ConfigGroupIds: []string{string(meta.ConfigGroupIDs[0])}}, }, } So(datastore.Put(ctx, cl43), ShouldBeNil) cl44 := changelist.MustGobID(gHost, 44).MustCreateIfNotExists(ctx) cl44.Snapshot = &changelist.Snapshot{ ExternalUpdateTime: timestamppb.New(ct.Clock.Now()), LuciProject: lProject, MinEquivalentPatchset: 1, Patchset: 1, Kind: &changelist.Snapshot_Gerrit{Gerrit: &changelist.Gerrit{ Info: gf.CI( 44, gf.Project(gRepo), gf.Ref("refs/heads/main"), gf.CQ(+2, ct.Clock.Now(), gf.U("user-1"))), }}, } cl44.ApplicableConfig = &changelist.ApplicableConfig{ Projects: []*changelist.ApplicableConfig_Project{ {Name: lProject, ConfigGroupIds: []string{string(meta.ConfigGroupIDs[0])}}, }, } So(datastore.Put(ctx, cl44), ShouldBeNil) // This event is the only event notifying PM about CL#43. So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl43, cl44)), ShouldBeNil) const n = 20 for i := 0; i < n; i++ { So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmNotifier.Poke(ctx, lProject), ShouldBeNil) // Simulate updating a CL. cl44.EVersion++ So(datastore.Put(ctx, cl44), ShouldBeNil) So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl44)), ShouldBeNil) } events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Expect the following events: // +1 from NotifyCLsUpdated on cl43 and cl44, // +3*n from loop. So(events, ShouldHaveLength, 3*n+1) // Run `w` concurrent PMs. const w = 20 now := ct.Clock.Now() errs := make(errors.MultiError, w) wg := sync.WaitGroup{} wg.Add(w) for i := 0; i < w; i++ { i := i go func() { defer wg.Done() errs[i] = pm.manageProject(ctx, lProject, now) }() } wg.Wait() // Exactly 1 of the workers must create PM entity, consume events and // poke the poller. p := prjmanager.Project{ID: lProject} So(datastore.Get(ctx, &p), ShouldBeNil) // Both cl43 and cl44 must have corresponding PCLs with latest EVersions. So(p.State.GetPcls(), ShouldHaveLength, 2) for _, pcl := range p.State.GetPcls() { switch common.CLID(pcl.GetClid()) { case cl43.ID: So(pcl.GetEversion(), ShouldEqual, cl43.EVersion) case cl44.ID: So(pcl.GetEversion(), ShouldEqual, cl44.EVersion) default: So("must not happen", ShouldBeTrue) } } events, err = eventbox.List(ctx, recipient) So(err, ShouldBeNil) So(events, ShouldBeEmpty) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // At least 1 worker must finish successfully. errCnt, _ := errs.Summary() t.Logf("%d/%d workers failed", errCnt, w) So(errCnt, ShouldBeLessThan, w) }) } func loadProjectEntities(ctx context.Context, luciProject string) ( *prjmanager.Project, *prjmanager.ProjectStateOffload, *prjmanager.ProjectLog, ) { p := &prjmanager.Project{ID: luciProject} switch err := datastore.Get(ctx, p); { case err == datastore.ErrNoSuchEntity: return nil, nil, nil case err != nil: panic(err) }
key := datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject) ps := &prjmanager.ProjectStateOffload{Project: key} if err := datastore.Get(ctx, ps); err != nil { // ProjectStateOffload must exist if Project exists. panic(err) } plog := &prjmanager.ProjectLog{ Project: datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject), EVersion: p.EVersion, } switch err := datastore.Get(ctx, plog); { case err == datastore.ErrNoSuchEntity: return p, ps, nil case err != nil: panic(err) default: // Quick check invariant that plog replicates what's stored in Project & // ProjectStateOffload entities at the same EVersion. So(plog.EVersion, ShouldEqual, p.EVersion) So(plog.Status, ShouldEqual, ps.Status) So(plog.ConfigHash, ShouldEqual, ps.ConfigHash) So(plog.State, ShouldResembleProto, p.State) So(plog.Reasons, ShouldNotBeEmpty) return p, ps, plog } } func singleRepoConfig(gHost string, gRepos ...string) *cfgpb.Config { projects := make([]*cfgpb.ConfigGroup_Gerrit_Project, len(gRepos)) for i, gRepo := range gRepos { projects[i] = &cfgpb.ConfigGroup_Gerrit_Project{ Name: gRepo, RefRegexp: []string{"refs/heads/main"}, } } return &cfgpb.Config{ ConfigGroups: []*cfgpb.ConfigGroup{ { Name: "main", Gerrit: []*cfgpb.ConfigGroup_Gerrit{ { Url: "https://" + gHost + "/", Projects: projects, }, }, }, }, } } type runNotifierMock struct { m sync.Mutex cancel []cancellationRequest updateConfig common.RunIDs } type cancellationRequest struct { id common.RunID reason string } func (r *runNotifierMock) NotifyCLsUpdated(ctx context.Context, rid common.RunID, cls *changelist.CLUpdatedEvents) error { panic("not implemented") } func (r *runNotifierMock) Start(ctx context.Context, id common.RunID) error { return nil } func (r *runNotifierMock) PokeNow(ctx context.Context, id common.RunID) error { panic("not implemented") } func (r *runNotifierMock) Cancel(ctx context.Context, id common.RunID, reason string) error { r.m.Lock() r.cancel = append(r.cancel, cancellationRequest{id: id, reason: reason}) r.m.Unlock() return nil } func (r *runNotifierMock) UpdateConfig(ctx context.Context, id common.RunID, hash string, eversion int64) error { r.m.Lock() r.updateConfig = append(r.updateConfig, id) r.m.Unlock() return nil } func (r *runNotifierMock) popUpdateConfig() common.RunIDs { r.m.Lock() out := r.updateConfig r.updateConfig = nil r.m.Unlock() sort.Sort(out) return out } func (r *runNotifierMock) popCancel() []cancellationRequest { r.m.Lock() out := r.cancel r.cancel = nil r.m.Unlock() sort.Slice(out, func(i, j int) bool { return out[i].id < out[j].id }) return out } type tjMock struct{} func (t *tjMock) ScheduleCancelStale(ctx context.Context, clid common.CLID, prevMinEquivalentPatchset, currentMinEquivalentPatchset int32, eta time.Time) error { return nil }
random_line_split
point.js
// meant to be a wrapper around the graph functions with iterator // should be iterator and evaluatableIterator // // there needs to a way of caching the ptr subnodes // var pointLookup = {} function point(options){ this.nodePtr = copyArray(ptr); this.nodePtr.pop();this.nodePtr.pop(); this.ptr = options.ptr; this.childNumber = options.childNumber; this.id = options.id; this.parentId = options.parentId; this.pathList = options.pathList; pointLookup[this.id] = this; console.log(this.ptr); console.log("-----------------------"); this.node = getObject(this.ptr, graphLookup) var nextPtrs = this.pathList[this.ptr]; console.log(this.ptr); console.log(this.pathList); console.log(nextPtrs); console.log("============cool beanz===================="); // assume no parent = origin if (!this.parentId) { this.origin = this.id; } var p2 = copyArray(this.ptr); p2.pop();p2.pop(); this.superGroup = getObject(p2, graphLookup); this.label = this.superGroup.value; this.variables = []; // if theres no parentId, assume this to be the initial point this.children = []; //var nodeTypes = {"program":programComponents.prototype, "value":valueComponents.prototype}; var pp = this.ptr; var a1 = getObject([pp[0], pp[1], pp[2]], graphLookup); nodeName = a1.value; if (a1.types['program']) this.programName = nodeName; for (var i =0 ; i < nextPtrs.length; i++) { console.log("-----xxxx-----"); //var tpg = programs[this.programName]; //function pt() { }; //pt.prototype = Object.create(point.prototype); // mixin(pt.prototype, programComponents.prototype); // mixin(pt.prototype, tpg.prototype); //pt.constructor = point.prototype.constructor // console.log(nextPtrs); this.children[i] = new point({"ptr":nextPtrs[i], "id":mkguid(), "parentId":this.id, "childNumber":i, "pathList":this.pathList, "origin":this.origin}); i++; } } point.prototype.pointLookup = {}; point.prototype = { "setBeginPhrase": function() { //if (this.superGroup.types) // if (this.superGroup.types['program']) { this.phraseBegin = true; console.log(this.ptr); //this.isMixedIn = true; mixin(Phrase.prototype, this); //pt.constructor = point.prototype.constructor }, "getRootNode": function(){ var rootPtr = [this.ptr[0], this.ptr[1], this.ptr[2]]; }, // used for detecting discontinuity... // not sure this should ever be used, if dealing with a huge program, this would be slow as shit "isConnected": function(ptr){ var test = ptr; var isConnected = false; this.recurse = function(point) { if (isConnected) return true; for (var i = 0; i < this.pathList[point].length; i++) { for (var j = 0; j < this.pathList[point].length; j++) { if (this.pathList[point][j] == test) { isConnected=true return true; }else this.recurse(this.pathList[point][j]); } } } var point = pointLookup[this.origin]; this.recurse(point); return isConnected; }, /* "getNextNodes": { return this.pathList[this.ptr] }, */ "evaluate": function(){ //this.initPhrase(); console.log(this.superGroup); //this.evaluatePhrase(); }, "getPriorNode":function(){ return pointLookup[this.parentId]; }, "getNextSibling":function() { var siblingId = pointLookup[point.parentId].children[this.childNumber+1]; if (pointLookup[siblingId]) return pointLookup[siblingId]; else return undefined; }, "getPriorSibling":function() { var siblingId = pointLookup[point.parentId].children[this.childNumber-1]; if (pointLookup[siblingId]) return pointLookup[siblingId]; else return undefined; }, "getJSON":function() { return graphLookup[this.id].toJSON(this.ptr); }, /* "setProgramNodes":function() { var id = this.ptr[0]; var ptr = this.ptr; this.isProgram = false; if (this.node.types) if (this.node.types['program']) { this.programName = this.node.value; this.isProgram = true; } var a = copyArray(ptr); var c = []; this.parentProgramNames = []; while (a.length > 2) { a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['program']) { if (o.value != this.progs[this.progs.length-1]) { this.parentProgramNames.push(this.node.value); this.programName = o.node.value; //.push(o); this.isParam = true; //break; } } } }, */ // more unneeded shit "setTypeNodes":function() { var id = this.ptr[0]; var ptr = this.ptr; this.isProgram = false; if (this.node.types) if (this.node.types['root']) { this.rootName = this.node.value; this.isRoot = true; //this.isProgram = true; } var a = copyArray(ptr); var c = []; this.programs = []; while (a.length > 2) { //a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['root']) { //if (o.value != this.progs[this.progs.length-1]) { this.rootName = o.node.value; //.push(o); //break; //} } if (o.types['program']) { this.programs.push(this.node.value); } } }, } function System(pt) { this.rootPoint = pt; // pt.setBeginPhrase(); //this.evaluatePhrase(); this.traversedNodes = {}; pt.nextPhrases = []; //pt.phraseBegin = true; //this.evaluatePhrase(); //console.log(this.ptr); //this.isMixedIn = true; //mixin(Phrase.prototype, this); } System.prototype = { "setsData":function() { (this.nextPoint.node.type['root'] || !this.nextPoint.children) }, //rootPhrase "evaluate":function() { this.hasTraversed = false //rootPhrase = this; function recurse(p) { if (this.traversedNodes[p]){ this.traversals--; }else this.traversedNodes[p] = true; if (p.programName) { var programNodeId = p.node.ptr[0]; if (!this.programVars[programNodeId]) this.programVars[programNodeId] = []; this.programVars[programNodeId].push(p.id); } if (p.node.types['root']){ p.phraseBegin = true; } if (p.node.types) if ((p.node.types['root'] || p.children.length == 0) && !hasTraversed) { //p.phraseBegin = true p.setBeginPhrase(); //var rootItem = p; // not sure about this .. because the phrase might be part of a greater phrase.... // need to play around with this if (this.hasTraversed) { pointLookup[p.parentId].phraseEnd = true; //if (rootPhrase) { //if (this.hasTraversed) { this.traversals--; this.nextPhrases.push(p.id); if (this.traversals == 0) { // iterations > 0 and also next childrent arent all roots .. // if there's just one item in the linkage, this strategy will break // rootPhrase.renderPhrase({"}); this.completed = true; //rootPhrase.nextPhrases = nextPhrases }else { p.nextPhrase.push(new Phrase(pt)); } // need to re-evaluate the phrase if the phrase hasn't completed } } if (!this.completed) for (var i =0 ; i < p.children.length; i++) { if (i > 0) { this.traversals++; this.hasTraversed = true; //for (var g in this) console.log(g); this.recurse(p.children[i], p) } } } recurse(this); //this.renderPhrase(); }, "render":function() { var point = this.rootPoint; this.recurse = function() { point.evaluateNode(); for (var c in point.children) { var pc = point.children[c]; pc.evaluateNode(); } } this.recurse(point); //this.evaluateNode(); } } function Phrase() { } Phrase.prototype = { /* "processPhrase":function(pb) { var brk = false; var levels = {}; function recurse(item) { if (item.phraseEnd) brk = true; if (brk) return; for (var child in item.children) { var pc = child.node.ptr; pc.pop();pc.pop(); var pcj = pc.join(); var co = child.phraseBeginPoint; if (arrayHas(co.levels[pcj], child.id)) { co.levelCount[pcj]++; } if (co.levelCount[pcj] == co.levels[pcj].length) { child.evaluateNode(pcj); } // might need some more work on other various types of node configuration that require waiting } } pb.levels = levels; } */ } // Template much include onFunction and onParameter function UIClass() {}; // UIClass.prototype = Object.create(baseProgram.prototype); UIClass.prototype = { "getNameSpace":function() { //need to look back to find 'grid' location }, "mouseClickCallback":function(ptr) { // iterate through the next pieces... }, "evaluateNode":function(pcj) { var hier = graph.prototype.getValueOrder(this.nodePtr); console.log("hier: "+hier); var x = contains(hier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}}); console.log("x:"+x); return; var hl = hier.length-1; if (this.node.types) if (this.node['types']["root"]) { // if (hier[hl] == "UI") { // if (this.phraseBegin) // this.ptrProgs[this.id] = new UIProgram(this.id, graph(graphLookup[this.node.ptr[0]]).toJSON()); } // check namespace if (contains(hier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}})) { //if (contains(hier, {'contains':{'vals':['row'], 'contains':{'vals':['label', 'inputbox', 'button']}}})) { if (this.superGroup.value == 'text') { if (!this.phraseEnd) { var ptr = this.node.ptr; //var o = getObject(ptr,this.uiprog); //o.callback = UI.dispatchValue; //this.uiprog.setEvent( // // // switch (this.superGroup.value) { case "text": this.variable = this.node.ptr; break; case "type": this.variable = this.node.ptr; break; } /* if (this.superGroup.value == 'text') { //this.getLastValue();b //var a = copyArray(this.node.ptr); this.variable = this.node.ptr } if (this.sueprGroup.value == 'type') { } */ } if (this.phraseEnd) { var ptr = this.node.ptr; if (this.superGroup.value == 'text') { //this.getLastValue();b //var a = copyArray(this.node.ptr); var o = getObject(this.node.ptr, graphLookup); ptrProgs[this.id].copyChild(this.node.ptr); } } } if (this.superGroup.value == 'type' && !this.phraseEnd) { if (this.node.value == "onSubmit") { //var o = getObject(p2, graphLookup); //for serialization concerns might need to turn the joins into jsonifieds var prog = ptrProgs[this.id]; a[0] = prog.gid; var btn = getObject(a, graphLookup); ptrProgs[this.id].setEvent("handleMouseClick", 'exact', a, this.mouseClickCallback); //o.registerEvents('callback'); // i'd like it i } //uiObject } } }, "drawUI":function() { //var uni = new universe("rendered", true); //var node = graphLookup[this.id]; //var json = point.JSON; //this.gid = uni.addGraph(); //graphLookup[gid].setFromJSON(this.JSON); // might need to hash it... // this draws ui component this.onCondition(); } } function DateClass() { } DateClass.prototype = { "getIsoDate":function(point, callback) { this.direction = this.inheritDirection(); //"push"; //;// point.nextPoint;// = "set"; // setting data dispatches data to be set by another function this.iterValue = {"program":{"Numbers":new Date().toString()}} this.onCondition(); } } function UniverseClass() { } UniverseClass.prototype = { "serializePtrGraph":function(point) { this.direction = this.inheritDirection(); this.value = {"serializedPtrGraph":{"serializedStuff":"codeNotComplete"}} this.onCondition(); } } /* function getNextContext = { } getNextContext.prototype = { "getNextContext":function() { this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (o.isContext) { o.isContext = true; }else this(o); } } } } */ function setNextContext() { } setNextContext.prototype = { "setNextContext":function() { // search for element and set flag this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (!o.isProgram) { o.setContext();// = true; }else this(o); } } this.recurse(this); } } function DBClass() { } DBClass.prototype = { /* "getVariable":function() { }, */ "evaluateNode":function(pcj) { var p = pointLookup[this.phraseBeginPoint]; //var pp //p.node.ptr.pop().pop(); // //a better way to express more complex namespaces is to route the vectors through the desired parent node var nsc = item.namespace[pcj]; var items = p.phraseBeginPoint.levels[pcj]; for (var i =0; i < items.length; i++) { var item = pointLookup(items[i]); if (item.priorNode.node.id != item.node.id) { //might also be a foreach from the priorNode if (item.priorNode.variable) { var p = item.getValuePtr(item.node.ptr); p.pop(); var o = getObject(p, nsc); o[item.value] = item.priorNode.variable; } else // return all values associated with that node { } //getValueHierarchy(item.node.ptr); //item.priorNode.variable }else { if (item.nextNode.node.id != item.node.id) { var p = item.getValuePtr(item.node.ptr); p.pop(); var o = getObject(p, nsc); this.variable = o[item.value]; //this.variable = // return variable } } } dbLayer.query(nsc); //p.levels--; //if (p.levels == 0) // getDBItem(); // search the tree upward to find the common tree /* if (!this.phraseEnd) { } */ }, "onIterationComplete":function() { if (this.hasContext()) { dbLayer.saveData(this.getContext().value, this.onCondition) } }, "getRootValueNode":function() { // create a loop from here to the next context change storedData }, "getValueNode":function() { } } var pathsLookup; var programs = {"UI":UIClass, "DB":DBClass, "Universe":UniverseClass, "Date":DateClass}; var traverseProgram = function(ptr) { //var p2 = copyArray(ptr); var o = getObject(ptr, graphLookup); var cap = []; for (var i = 0; i < o.links.length; i++) { var link = o.links[i]; cap.concat(link.children.concat(link.parents)); } for (var i = 0; i < cap.length; i++) { var ctop = cap.gfx.bottom + cap.gfx.height; cap.push({'y':ctop, 'obj':cap[i]}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } cap.sort(function (a, b) { return (a.y <b.y) }) return cap; } function getSubNodes(ptr) { return new selectInternodeDescendants(ptr).descendants; //return links; } function sortNodeLinks(items) { for (var i = 0; i < cap.length; i++) { var ctop = cap.gfx.bottom + cap.gfx.height; cap.push({'y':ctop, 'obj':cap[i]}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } cap.sort(function (a, b) { return (a.y < b.y) }) var cappy = []; for (var i = 0; i < cap.length; i++) { cappy.push(cap[i].obj); } return cappy; } function
(ptr) { this.descendants = []; graph.prototype.recurseItems(selectInternodeDescendants.prototype.getNextChild()); } selectInternodeDescendants.prototype.getNextChild = function(ptr, obj) { for (var i = obj.index; i >=0 ;i--) { var link = obj[i]; //if (link.parents[0].length || link.children[0].length) this.descendants.push(obj[i].children.concat(obj[i].parents)); //return ptr; } } function getNextLinks(ptr, priorPtr) { this.ptr = ptr; var o = getObject (this.ptr, graphLookup); var cap = []; var a = o.children.concat(o.parents); for (var i = 0; i < o.length; i++) { if (a[i] != ptr) { var o = getObject(a[i], graphLookup); var ctop = o.gfx.bottom + o.gfx.height; cap.push({'y':ctop, 'obj':o}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } } cap.sort(function (a, b) { return (a.gfx.y > b.gfx.y) }) capy = []; var ly = cap[0].y; nc = []; for (var i = 0; i < cap.length; cap++) { var ct = capy[cap[i].y]; if (ct === undefined) { capy[cap[i].y] = [cap[i].obj] }else capy[cap[i].y].push(cap[i].obj); if (ly != cap[i]) { capy[ly].sort(function(a,b) { return ( a.z > b.z ); }) nc.concat(capy[ly]) } ly = cap[i].y; // = cap[i]; } return nc; } /* * the point should make the decision var traverseProgramCallback = function(p) { var g = p.children; for (var i =0; i < p.children.length; p++) {//while (p.hasNextPoint) { var p = point[i]; //while (p.hasNextSibling) { // d = point.nextSibling(); traverseProgram(p); } } */ /*V point(thisPtr, lastPtr, sp, lastSp, lastLastPtr, lastLastSp) { } */
selectInternodeDescendants
identifier_name
point.js
// meant to be a wrapper around the graph functions with iterator // should be iterator and evaluatableIterator // // there needs to a way of caching the ptr subnodes // var pointLookup = {} function point(options){ this.nodePtr = copyArray(ptr); this.nodePtr.pop();this.nodePtr.pop(); this.ptr = options.ptr; this.childNumber = options.childNumber; this.id = options.id; this.parentId = options.parentId; this.pathList = options.pathList; pointLookup[this.id] = this; console.log(this.ptr); console.log("-----------------------"); this.node = getObject(this.ptr, graphLookup) var nextPtrs = this.pathList[this.ptr]; console.log(this.ptr); console.log(this.pathList); console.log(nextPtrs); console.log("============cool beanz===================="); // assume no parent = origin if (!this.parentId) { this.origin = this.id; } var p2 = copyArray(this.ptr); p2.pop();p2.pop(); this.superGroup = getObject(p2, graphLookup); this.label = this.superGroup.value; this.variables = []; // if theres no parentId, assume this to be the initial point this.children = []; //var nodeTypes = {"program":programComponents.prototype, "value":valueComponents.prototype}; var pp = this.ptr; var a1 = getObject([pp[0], pp[1], pp[2]], graphLookup); nodeName = a1.value; if (a1.types['program']) this.programName = nodeName; for (var i =0 ; i < nextPtrs.length; i++) { console.log("-----xxxx-----"); //var tpg = programs[this.programName]; //function pt() { }; //pt.prototype = Object.create(point.prototype); // mixin(pt.prototype, programComponents.prototype); // mixin(pt.prototype, tpg.prototype); //pt.constructor = point.prototype.constructor // console.log(nextPtrs); this.children[i] = new point({"ptr":nextPtrs[i], "id":mkguid(), "parentId":this.id, "childNumber":i, "pathList":this.pathList, "origin":this.origin}); i++; } } point.prototype.pointLookup = {}; point.prototype = { "setBeginPhrase": function() { //if (this.superGroup.types) // if (this.superGroup.types['program']) { this.phraseBegin = true; console.log(this.ptr); //this.isMixedIn = true; mixin(Phrase.prototype, this); //pt.constructor = point.prototype.constructor }, "getRootNode": function(){ var rootPtr = [this.ptr[0], this.ptr[1], this.ptr[2]]; }, // used for detecting discontinuity... // not sure this should ever be used, if dealing with a huge program, this would be slow as shit "isConnected": function(ptr){ var test = ptr; var isConnected = false; this.recurse = function(point) { if (isConnected) return true; for (var i = 0; i < this.pathList[point].length; i++) { for (var j = 0; j < this.pathList[point].length; j++) { if (this.pathList[point][j] == test) { isConnected=true return true; }else this.recurse(this.pathList[point][j]); } } } var point = pointLookup[this.origin]; this.recurse(point); return isConnected; }, /* "getNextNodes": { return this.pathList[this.ptr] }, */ "evaluate": function(){ //this.initPhrase(); console.log(this.superGroup); //this.evaluatePhrase(); }, "getPriorNode":function(){ return pointLookup[this.parentId]; }, "getNextSibling":function() { var siblingId = pointLookup[point.parentId].children[this.childNumber+1]; if (pointLookup[siblingId]) return pointLookup[siblingId]; else return undefined; }, "getPriorSibling":function() { var siblingId = pointLookup[point.parentId].children[this.childNumber-1]; if (pointLookup[siblingId]) return pointLookup[siblingId]; else return undefined; }, "getJSON":function() { return graphLookup[this.id].toJSON(this.ptr); }, /* "setProgramNodes":function() { var id = this.ptr[0]; var ptr = this.ptr; this.isProgram = false; if (this.node.types) if (this.node.types['program']) { this.programName = this.node.value; this.isProgram = true; } var a = copyArray(ptr); var c = []; this.parentProgramNames = []; while (a.length > 2) { a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['program']) { if (o.value != this.progs[this.progs.length-1]) { this.parentProgramNames.push(this.node.value); this.programName = o.node.value; //.push(o); this.isParam = true; //break; } } } }, */ // more unneeded shit "setTypeNodes":function() { var id = this.ptr[0]; var ptr = this.ptr; this.isProgram = false; if (this.node.types) if (this.node.types['root']) { this.rootName = this.node.value; this.isRoot = true; //this.isProgram = true; } var a = copyArray(ptr); var c = []; this.programs = []; while (a.length > 2) { //a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['root']) { //if (o.value != this.progs[this.progs.length-1]) { this.rootName = o.node.value; //.push(o); //break; //} } if (o.types['program']) { this.programs.push(this.node.value); } } }, } function System(pt) { this.rootPoint = pt; // pt.setBeginPhrase(); //this.evaluatePhrase(); this.traversedNodes = {}; pt.nextPhrases = []; //pt.phraseBegin = true; //this.evaluatePhrase(); //console.log(this.ptr); //this.isMixedIn = true; //mixin(Phrase.prototype, this); } System.prototype = { "setsData":function() { (this.nextPoint.node.type['root'] || !this.nextPoint.children) }, //rootPhrase "evaluate":function() { this.hasTraversed = false //rootPhrase = this; function recurse(p) { if (this.traversedNodes[p]){ this.traversals--; }else this.traversedNodes[p] = true; if (p.programName) { var programNodeId = p.node.ptr[0]; if (!this.programVars[programNodeId]) this.programVars[programNodeId] = []; this.programVars[programNodeId].push(p.id); } if (p.node.types['root']){ p.phraseBegin = true; } if (p.node.types) if ((p.node.types['root'] || p.children.length == 0) && !hasTraversed) { //p.phraseBegin = true p.setBeginPhrase(); //var rootItem = p; // not sure about this .. because the phrase might be part of a greater phrase.... // need to play around with this if (this.hasTraversed) { pointLookup[p.parentId].phraseEnd = true; //if (rootPhrase) { //if (this.hasTraversed) { this.traversals--; this.nextPhrases.push(p.id); if (this.traversals == 0) { // iterations > 0 and also next childrent arent all roots .. // if there's just one item in the linkage, this strategy will break // rootPhrase.renderPhrase({"}); this.completed = true; //rootPhrase.nextPhrases = nextPhrases }else { p.nextPhrase.push(new Phrase(pt)); } // need to re-evaluate the phrase if the phrase hasn't completed } } if (!this.completed) for (var i =0 ; i < p.children.length; i++) { if (i > 0) { this.traversals++; this.hasTraversed = true; //for (var g in this) console.log(g); this.recurse(p.children[i], p) } } } recurse(this); //this.renderPhrase(); }, "render":function() { var point = this.rootPoint; this.recurse = function() { point.evaluateNode(); for (var c in point.children) { var pc = point.children[c]; pc.evaluateNode(); } } this.recurse(point); //this.evaluateNode(); } } function Phrase() { } Phrase.prototype = { /* "processPhrase":function(pb) { var brk = false; var levels = {}; function recurse(item) { if (item.phraseEnd) brk = true; if (brk) return; for (var child in item.children) { var pc = child.node.ptr; pc.pop();pc.pop(); var pcj = pc.join(); var co = child.phraseBeginPoint; if (arrayHas(co.levels[pcj], child.id)) { co.levelCount[pcj]++; } if (co.levelCount[pcj] == co.levels[pcj].length) { child.evaluateNode(pcj); } // might need some more work on other various types of node configuration that require waiting } } pb.levels = levels; } */ } // Template much include onFunction and onParameter function UIClass() {}; // UIClass.prototype = Object.create(baseProgram.prototype); UIClass.prototype = { "getNameSpace":function() { //need to look back to find 'grid' location }, "mouseClickCallback":function(ptr) { // iterate through the next pieces... }, "evaluateNode":function(pcj) { var hier = graph.prototype.getValueOrder(this.nodePtr); console.log("hier: "+hier); var x = contains(hier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}}); console.log("x:"+x); return; var hl = hier.length-1; if (this.node.types) if (this.node['types']["root"]) { // if (hier[hl] == "UI") { // if (this.phraseBegin) // this.ptrProgs[this.id] = new UIProgram(this.id, graph(graphLookup[this.node.ptr[0]]).toJSON()); } // check namespace if (contains(hier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}})) { //if (contains(hier, {'contains':{'vals':['row'], 'contains':{'vals':['label', 'inputbox', 'button']}}})) { if (this.superGroup.value == 'text') { if (!this.phraseEnd) { var ptr = this.node.ptr; //var o = getObject(ptr,this.uiprog); //o.callback = UI.dispatchValue; //this.uiprog.setEvent( // // // switch (this.superGroup.value) { case "text": this.variable = this.node.ptr; break; case "type": this.variable = this.node.ptr; break; } /* if (this.superGroup.value == 'text') { //this.getLastValue();b //var a = copyArray(this.node.ptr); this.variable = this.node.ptr } if (this.sueprGroup.value == 'type') { } */ } if (this.phraseEnd) { var ptr = this.node.ptr; if (this.superGroup.value == 'text') { //this.getLastValue();b //var a = copyArray(this.node.ptr); var o = getObject(this.node.ptr, graphLookup); ptrProgs[this.id].copyChild(this.node.ptr); } } } if (this.superGroup.value == 'type' && !this.phraseEnd) { if (this.node.value == "onSubmit") { //var o = getObject(p2, graphLookup); //for serialization concerns might need to turn the joins into jsonifieds var prog = ptrProgs[this.id]; a[0] = prog.gid; var btn = getObject(a, graphLookup); ptrProgs[this.id].setEvent("handleMouseClick", 'exact', a, this.mouseClickCallback); //o.registerEvents('callback'); // i'd like it i } //uiObject } } }, "drawUI":function() { //var uni = new universe("rendered", true); //var node = graphLookup[this.id]; //var json = point.JSON; //this.gid = uni.addGraph(); //graphLookup[gid].setFromJSON(this.JSON); // might need to hash it... // this draws ui component this.onCondition(); } } function DateClass() { } DateClass.prototype = { "getIsoDate":function(point, callback) { this.direction = this.inheritDirection(); //"push"; //;// point.nextPoint;// = "set"; // setting data dispatches data to be set by another function this.iterValue = {"program":{"Numbers":new Date().toString()}} this.onCondition(); } } function UniverseClass() { } UniverseClass.prototype = { "serializePtrGraph":function(point) { this.direction = this.inheritDirection(); this.value = {"serializedPtrGraph":{"serializedStuff":"codeNotComplete"}} this.onCondition(); } } /* function getNextContext = { } getNextContext.prototype = { "getNextContext":function() { this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (o.isContext) { o.isContext = true; }else this(o); } } } } */ function setNextContext()
setNextContext.prototype = { "setNextContext":function() { // search for element and set flag this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (!o.isProgram) { o.setContext();// = true; }else this(o); } } this.recurse(this); } } function DBClass() { } DBClass.prototype = { /* "getVariable":function() { }, */ "evaluateNode":function(pcj) { var p = pointLookup[this.phraseBeginPoint]; //var pp //p.node.ptr.pop().pop(); // //a better way to express more complex namespaces is to route the vectors through the desired parent node var nsc = item.namespace[pcj]; var items = p.phraseBeginPoint.levels[pcj]; for (var i =0; i < items.length; i++) { var item = pointLookup(items[i]); if (item.priorNode.node.id != item.node.id) { //might also be a foreach from the priorNode if (item.priorNode.variable) { var p = item.getValuePtr(item.node.ptr); p.pop(); var o = getObject(p, nsc); o[item.value] = item.priorNode.variable; } else // return all values associated with that node { } //getValueHierarchy(item.node.ptr); //item.priorNode.variable }else { if (item.nextNode.node.id != item.node.id) { var p = item.getValuePtr(item.node.ptr); p.pop(); var o = getObject(p, nsc); this.variable = o[item.value]; //this.variable = // return variable } } } dbLayer.query(nsc); //p.levels--; //if (p.levels == 0) // getDBItem(); // search the tree upward to find the common tree /* if (!this.phraseEnd) { } */ }, "onIterationComplete":function() { if (this.hasContext()) { dbLayer.saveData(this.getContext().value, this.onCondition) } }, "getRootValueNode":function() { // create a loop from here to the next context change storedData }, "getValueNode":function() { } } var pathsLookup; var programs = {"UI":UIClass, "DB":DBClass, "Universe":UniverseClass, "Date":DateClass}; var traverseProgram = function(ptr) { //var p2 = copyArray(ptr); var o = getObject(ptr, graphLookup); var cap = []; for (var i = 0; i < o.links.length; i++) { var link = o.links[i]; cap.concat(link.children.concat(link.parents)); } for (var i = 0; i < cap.length; i++) { var ctop = cap.gfx.bottom + cap.gfx.height; cap.push({'y':ctop, 'obj':cap[i]}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } cap.sort(function (a, b) { return (a.y <b.y) }) return cap; } function getSubNodes(ptr) { return new selectInternodeDescendants(ptr).descendants; //return links; } function sortNodeLinks(items) { for (var i = 0; i < cap.length; i++) { var ctop = cap.gfx.bottom + cap.gfx.height; cap.push({'y':ctop, 'obj':cap[i]}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } cap.sort(function (a, b) { return (a.y < b.y) }) var cappy = []; for (var i = 0; i < cap.length; i++) { cappy.push(cap[i].obj); } return cappy; } function selectInternodeDescendants(ptr) { this.descendants = []; graph.prototype.recurseItems(selectInternodeDescendants.prototype.getNextChild()); } selectInternodeDescendants.prototype.getNextChild = function(ptr, obj) { for (var i = obj.index; i >=0 ;i--) { var link = obj[i]; //if (link.parents[0].length || link.children[0].length) this.descendants.push(obj[i].children.concat(obj[i].parents)); //return ptr; } } function getNextLinks(ptr, priorPtr) { this.ptr = ptr; var o = getObject (this.ptr, graphLookup); var cap = []; var a = o.children.concat(o.parents); for (var i = 0; i < o.length; i++) { if (a[i] != ptr) { var o = getObject(a[i], graphLookup); var ctop = o.gfx.bottom + o.gfx.height; cap.push({'y':ctop, 'obj':o}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } } cap.sort(function (a, b) { return (a.gfx.y > b.gfx.y) }) capy = []; var ly = cap[0].y; nc = []; for (var i = 0; i < cap.length; cap++) { var ct = capy[cap[i].y]; if (ct === undefined) { capy[cap[i].y] = [cap[i].obj] }else capy[cap[i].y].push(cap[i].obj); if (ly != cap[i]) { capy[ly].sort(function(a,b) { return ( a.z > b.z ); }) nc.concat(capy[ly]) } ly = cap[i].y; // = cap[i]; } return nc; } /* * the point should make the decision var traverseProgramCallback = function(p) { var g = p.children; for (var i =0; i < p.children.length; p++) {//while (p.hasNextPoint) { var p = point[i]; //while (p.hasNextSibling) { // d = point.nextSibling(); traverseProgram(p); } } */ /*V point(thisPtr, lastPtr, sp, lastSp, lastLastPtr, lastLastSp) { } */
{ }
identifier_body
point.js
// meant to be a wrapper around the graph functions with iterator // should be iterator and evaluatableIterator // // there needs to a way of caching the ptr subnodes // var pointLookup = {} function point(options){ this.nodePtr = copyArray(ptr); this.nodePtr.pop();this.nodePtr.pop(); this.ptr = options.ptr; this.childNumber = options.childNumber; this.id = options.id; this.parentId = options.parentId; this.pathList = options.pathList; pointLookup[this.id] = this; console.log(this.ptr); console.log("-----------------------"); this.node = getObject(this.ptr, graphLookup) var nextPtrs = this.pathList[this.ptr]; console.log(this.ptr); console.log(this.pathList); console.log(nextPtrs); console.log("============cool beanz===================="); // assume no parent = origin if (!this.parentId) { this.origin = this.id; } var p2 = copyArray(this.ptr); p2.pop();p2.pop(); this.superGroup = getObject(p2, graphLookup); this.label = this.superGroup.value; this.variables = []; // if theres no parentId, assume this to be the initial point this.children = []; //var nodeTypes = {"program":programComponents.prototype, "value":valueComponents.prototype}; var pp = this.ptr; var a1 = getObject([pp[0], pp[1], pp[2]], graphLookup); nodeName = a1.value; if (a1.types['program']) this.programName = nodeName; for (var i =0 ; i < nextPtrs.length; i++) { console.log("-----xxxx-----"); //var tpg = programs[this.programName]; //function pt() { }; //pt.prototype = Object.create(point.prototype); // mixin(pt.prototype, programComponents.prototype); // mixin(pt.prototype, tpg.prototype); //pt.constructor = point.prototype.constructor // console.log(nextPtrs); this.children[i] = new point({"ptr":nextPtrs[i], "id":mkguid(), "parentId":this.id, "childNumber":i, "pathList":this.pathList, "origin":this.origin}); i++; } } point.prototype.pointLookup = {}; point.prototype = { "setBeginPhrase": function() { //if (this.superGroup.types) // if (this.superGroup.types['program']) { this.phraseBegin = true; console.log(this.ptr); //this.isMixedIn = true; mixin(Phrase.prototype, this); //pt.constructor = point.prototype.constructor }, "getRootNode": function(){ var rootPtr = [this.ptr[0], this.ptr[1], this.ptr[2]]; }, // used for detecting discontinuity... // not sure this should ever be used, if dealing with a huge program, this would be slow as shit "isConnected": function(ptr){ var test = ptr; var isConnected = false; this.recurse = function(point) { if (isConnected) return true; for (var i = 0; i < this.pathList[point].length; i++) { for (var j = 0; j < this.pathList[point].length; j++) { if (this.pathList[point][j] == test) { isConnected=true return true; }else this.recurse(this.pathList[point][j]); } } } var point = pointLookup[this.origin]; this.recurse(point); return isConnected; }, /* "getNextNodes": { return this.pathList[this.ptr] }, */ "evaluate": function(){ //this.initPhrase(); console.log(this.superGroup); //this.evaluatePhrase(); }, "getPriorNode":function(){ return pointLookup[this.parentId]; }, "getNextSibling":function() { var siblingId = pointLookup[point.parentId].children[this.childNumber+1]; if (pointLookup[siblingId]) return pointLookup[siblingId]; else return undefined; }, "getPriorSibling":function() { var siblingId = pointLookup[point.parentId].children[this.childNumber-1]; if (pointLookup[siblingId]) return pointLookup[siblingId]; else return undefined; }, "getJSON":function() { return graphLookup[this.id].toJSON(this.ptr); }, /* "setProgramNodes":function() { var id = this.ptr[0]; var ptr = this.ptr; this.isProgram = false; if (this.node.types) if (this.node.types['program']) { this.programName = this.node.value; this.isProgram = true; } var a = copyArray(ptr); var c = []; this.parentProgramNames = []; while (a.length > 2) { a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['program']) { if (o.value != this.progs[this.progs.length-1]) { this.parentProgramNames.push(this.node.value); this.programName = o.node.value; //.push(o); this.isParam = true; //break; } } } }, */ // more unneeded shit "setTypeNodes":function() { var id = this.ptr[0]; var ptr = this.ptr; this.isProgram = false; if (this.node.types) if (this.node.types['root']) { this.rootName = this.node.value; this.isRoot = true; //this.isProgram = true; } var a = copyArray(ptr); var c = []; this.programs = []; while (a.length > 2) { //a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['root']) { //if (o.value != this.progs[this.progs.length-1]) { this.rootName = o.node.value; //.push(o); //break; //} } if (o.types['program']) { this.programs.push(this.node.value); } } }, } function System(pt) { this.rootPoint = pt; // pt.setBeginPhrase(); //this.evaluatePhrase(); this.traversedNodes = {}; pt.nextPhrases = []; //pt.phraseBegin = true; //this.evaluatePhrase(); //console.log(this.ptr); //this.isMixedIn = true; //mixin(Phrase.prototype, this); } System.prototype = { "setsData":function() { (this.nextPoint.node.type['root'] || !this.nextPoint.children) }, //rootPhrase "evaluate":function() { this.hasTraversed = false //rootPhrase = this; function recurse(p) { if (this.traversedNodes[p]){ this.traversals--; }else this.traversedNodes[p] = true; if (p.programName) { var programNodeId = p.node.ptr[0]; if (!this.programVars[programNodeId]) this.programVars[programNodeId] = []; this.programVars[programNodeId].push(p.id); } if (p.node.types['root']){ p.phraseBegin = true; } if (p.node.types) if ((p.node.types['root'] || p.children.length == 0) && !hasTraversed) { //p.phraseBegin = true p.setBeginPhrase(); //var rootItem = p; // not sure about this .. because the phrase might be part of a greater phrase.... // need to play around with this if (this.hasTraversed) { pointLookup[p.parentId].phraseEnd = true; //if (rootPhrase) { //if (this.hasTraversed) { this.traversals--; this.nextPhrases.push(p.id); if (this.traversals == 0) { // iterations > 0 and also next childrent arent all roots .. // if there's just one item in the linkage, this strategy will break // rootPhrase.renderPhrase({"}); this.completed = true; //rootPhrase.nextPhrases = nextPhrases }else { p.nextPhrase.push(new Phrase(pt)); } // need to re-evaluate the phrase if the phrase hasn't completed } } if (!this.completed) for (var i =0 ; i < p.children.length; i++) { if (i > 0) { this.traversals++; this.hasTraversed = true; //for (var g in this) console.log(g); this.recurse(p.children[i], p) } } } recurse(this); //this.renderPhrase(); }, "render":function() { var point = this.rootPoint; this.recurse = function() { point.evaluateNode(); for (var c in point.children) { var pc = point.children[c]; pc.evaluateNode(); } } this.recurse(point); //this.evaluateNode(); } } function Phrase() { } Phrase.prototype = { /* "processPhrase":function(pb) { var brk = false; var levels = {}; function recurse(item) { if (item.phraseEnd) brk = true; if (brk) return; for (var child in item.children) { var pc = child.node.ptr; pc.pop();pc.pop(); var pcj = pc.join(); var co = child.phraseBeginPoint; if (arrayHas(co.levels[pcj], child.id)) { co.levelCount[pcj]++; } if (co.levelCount[pcj] == co.levels[pcj].length) { child.evaluateNode(pcj); } // might need some more work on other various types of node configuration that require waiting } } pb.levels = levels; } */ } // Template much include onFunction and onParameter function UIClass() {}; // UIClass.prototype = Object.create(baseProgram.prototype); UIClass.prototype = { "getNameSpace":function() { //need to look back to find 'grid' location }, "mouseClickCallback":function(ptr) { // iterate through the next pieces... }, "evaluateNode":function(pcj) { var hier = graph.prototype.getValueOrder(this.nodePtr); console.log("hier: "+hier); var x = contains(hier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}}); console.log("x:"+x); return; var hl = hier.length-1; if (this.node.types) if (this.node['types']["root"]) { // if (hier[hl] == "UI") { // if (this.phraseBegin) // this.ptrProgs[this.id] = new UIProgram(this.id, graph(graphLookup[this.node.ptr[0]]).toJSON()); } // check namespace if (contains(hier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}})) { //if (contains(hier, {'contains':{'vals':['row'], 'contains':{'vals':['label', 'inputbox', 'button']}}})) { if (this.superGroup.value == 'text') { if (!this.phraseEnd) { var ptr = this.node.ptr; //var o = getObject(ptr,this.uiprog); //o.callback = UI.dispatchValue; //this.uiprog.setEvent( // // // switch (this.superGroup.value) { case "text": this.variable = this.node.ptr; break; case "type": this.variable = this.node.ptr; break; } /* if (this.superGroup.value == 'text') { //this.getLastValue();b //var a = copyArray(this.node.ptr); this.variable = this.node.ptr } if (this.sueprGroup.value == 'type') { } */ } if (this.phraseEnd) { var ptr = this.node.ptr; if (this.superGroup.value == 'text') { //this.getLastValue();b //var a = copyArray(this.node.ptr); var o = getObject(this.node.ptr, graphLookup); ptrProgs[this.id].copyChild(this.node.ptr); } } } if (this.superGroup.value == 'type' && !this.phraseEnd) { if (this.node.value == "onSubmit") { //var o = getObject(p2, graphLookup); //for serialization concerns might need to turn the joins into jsonifieds var prog = ptrProgs[this.id]; a[0] = prog.gid; var btn = getObject(a, graphLookup); ptrProgs[this.id].setEvent("handleMouseClick", 'exact', a, this.mouseClickCallback); //o.registerEvents('callback'); // i'd like it i } //uiObject } } }, "drawUI":function() { //var uni = new universe("rendered", true); //var node = graphLookup[this.id]; //var json = point.JSON; //this.gid = uni.addGraph(); //graphLookup[gid].setFromJSON(this.JSON); // might need to hash it... // this draws ui component this.onCondition(); } } function DateClass() { } DateClass.prototype = { "getIsoDate":function(point, callback) { this.direction = this.inheritDirection(); //"push"; //;// point.nextPoint;// = "set"; // setting data dispatches data to be set by another function this.iterValue = {"program":{"Numbers":new Date().toString()}} this.onCondition(); } } function UniverseClass() { } UniverseClass.prototype = { "serializePtrGraph":function(point) { this.direction = this.inheritDirection(); this.value = {"serializedPtrGraph":{"serializedStuff":"codeNotComplete"}} this.onCondition(); } } /* function getNextContext = { } getNextContext.prototype = { "getNextContext":function() { this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (o.isContext) { o.isContext = true; }else this(o); } } } } */ function setNextContext() { } setNextContext.prototype = { "setNextContext":function() { // search for element and set flag this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (!o.isProgram) { o.setContext();// = true; }else this(o); } } this.recurse(this); } } function DBClass() { } DBClass.prototype = { /* "getVariable":function() { }, */ "evaluateNode":function(pcj) { var p = pointLookup[this.phraseBeginPoint]; //var pp //p.node.ptr.pop().pop(); // //a better way to express more complex namespaces is to route the vectors through the desired parent node var nsc = item.namespace[pcj]; var items = p.phraseBeginPoint.levels[pcj]; for (var i =0; i < items.length; i++) { var item = pointLookup(items[i]); if (item.priorNode.node.id != item.node.id) { //might also be a foreach from the priorNode if (item.priorNode.variable) { var p = item.getValuePtr(item.node.ptr); p.pop(); var o = getObject(p, nsc); o[item.value] = item.priorNode.variable; } else // return all values associated with that node { } //getValueHierarchy(item.node.ptr); //item.priorNode.variable }else { if (item.nextNode.node.id != item.node.id) { var p = item.getValuePtr(item.node.ptr); p.pop(); var o = getObject(p, nsc); this.variable = o[item.value]; //this.variable = // return variable } } } dbLayer.query(nsc); //p.levels--; //if (p.levels == 0) // getDBItem(); // search the tree upward to find the common tree /* if (!this.phraseEnd) { } */ }, "onIterationComplete":function() { if (this.hasContext()) { dbLayer.saveData(this.getContext().value, this.onCondition) } }, "getRootValueNode":function() { // create a loop from here to the next context change storedData }, "getValueNode":function() { } } var pathsLookup; var programs = {"UI":UIClass, "DB":DBClass, "Universe":UniverseClass, "Date":DateClass}; var traverseProgram = function(ptr) { //var p2 = copyArray(ptr); var o = getObject(ptr, graphLookup); var cap = []; for (var i = 0; i < o.links.length; i++) { var link = o.links[i]; cap.concat(link.children.concat(link.parents)); } for (var i = 0; i < cap.length; i++) { var ctop = cap.gfx.bottom + cap.gfx.height; cap.push({'y':ctop, 'obj':cap[i]}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } cap.sort(function (a, b) { return (a.y <b.y) }) return cap; } function getSubNodes(ptr) { return new selectInternodeDescendants(ptr).descendants; //return links; } function sortNodeLinks(items) { for (var i = 0; i < cap.length; i++) { var ctop = cap.gfx.bottom + cap.gfx.height; cap.push({'y':ctop, 'obj':cap[i]}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } cap.sort(function (a, b) { return (a.y < b.y) }) var cappy = []; for (var i = 0; i < cap.length; i++) { cappy.push(cap[i].obj); } return cappy; } function selectInternodeDescendants(ptr) { this.descendants = []; graph.prototype.recurseItems(selectInternodeDescendants.prototype.getNextChild()); } selectInternodeDescendants.prototype.getNextChild = function(ptr, obj) { for (var i = obj.index; i >=0 ;i--)
} function getNextLinks(ptr, priorPtr) { this.ptr = ptr; var o = getObject (this.ptr, graphLookup); var cap = []; var a = o.children.concat(o.parents); for (var i = 0; i < o.length; i++) { if (a[i] != ptr) { var o = getObject(a[i], graphLookup); var ctop = o.gfx.bottom + o.gfx.height; cap.push({'y':ctop, 'obj':o}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } } cap.sort(function (a, b) { return (a.gfx.y > b.gfx.y) }) capy = []; var ly = cap[0].y; nc = []; for (var i = 0; i < cap.length; cap++) { var ct = capy[cap[i].y]; if (ct === undefined) { capy[cap[i].y] = [cap[i].obj] }else capy[cap[i].y].push(cap[i].obj); if (ly != cap[i]) { capy[ly].sort(function(a,b) { return ( a.z > b.z ); }) nc.concat(capy[ly]) } ly = cap[i].y; // = cap[i]; } return nc; } /* * the point should make the decision var traverseProgramCallback = function(p) { var g = p.children; for (var i =0; i < p.children.length; p++) {//while (p.hasNextPoint) { var p = point[i]; //while (p.hasNextSibling) { // d = point.nextSibling(); traverseProgram(p); } } */ /*V point(thisPtr, lastPtr, sp, lastSp, lastLastPtr, lastLastSp) { } */
{ var link = obj[i]; //if (link.parents[0].length || link.children[0].length) this.descendants.push(obj[i].children.concat(obj[i].parents)); //return ptr; }
conditional_block
point.js
// meant to be a wrapper around the graph functions with iterator // should be iterator and evaluatableIterator // // there needs to a way of caching the ptr subnodes // var pointLookup = {} function point(options){ this.nodePtr = copyArray(ptr); this.nodePtr.pop();this.nodePtr.pop(); this.ptr = options.ptr; this.childNumber = options.childNumber; this.id = options.id; this.parentId = options.parentId; this.pathList = options.pathList; pointLookup[this.id] = this; console.log(this.ptr); console.log("-----------------------"); this.node = getObject(this.ptr, graphLookup) var nextPtrs = this.pathList[this.ptr]; console.log(this.ptr); console.log(this.pathList); console.log(nextPtrs); console.log("============cool beanz===================="); // assume no parent = origin if (!this.parentId) { this.origin = this.id; } var p2 = copyArray(this.ptr); p2.pop();p2.pop(); this.superGroup = getObject(p2, graphLookup); this.label = this.superGroup.value; this.variables = []; // if theres no parentId, assume this to be the initial point this.children = []; //var nodeTypes = {"program":programComponents.prototype, "value":valueComponents.prototype}; var pp = this.ptr; var a1 = getObject([pp[0], pp[1], pp[2]], graphLookup); nodeName = a1.value;
for (var i =0 ; i < nextPtrs.length; i++) { console.log("-----xxxx-----"); //var tpg = programs[this.programName]; //function pt() { }; //pt.prototype = Object.create(point.prototype); // mixin(pt.prototype, programComponents.prototype); // mixin(pt.prototype, tpg.prototype); //pt.constructor = point.prototype.constructor // console.log(nextPtrs); this.children[i] = new point({"ptr":nextPtrs[i], "id":mkguid(), "parentId":this.id, "childNumber":i, "pathList":this.pathList, "origin":this.origin}); i++; } } point.prototype.pointLookup = {}; point.prototype = { "setBeginPhrase": function() { //if (this.superGroup.types) // if (this.superGroup.types['program']) { this.phraseBegin = true; console.log(this.ptr); //this.isMixedIn = true; mixin(Phrase.prototype, this); //pt.constructor = point.prototype.constructor }, "getRootNode": function(){ var rootPtr = [this.ptr[0], this.ptr[1], this.ptr[2]]; }, // used for detecting discontinuity... // not sure this should ever be used, if dealing with a huge program, this would be slow as shit "isConnected": function(ptr){ var test = ptr; var isConnected = false; this.recurse = function(point) { if (isConnected) return true; for (var i = 0; i < this.pathList[point].length; i++) { for (var j = 0; j < this.pathList[point].length; j++) { if (this.pathList[point][j] == test) { isConnected=true return true; }else this.recurse(this.pathList[point][j]); } } } var point = pointLookup[this.origin]; this.recurse(point); return isConnected; }, /* "getNextNodes": { return this.pathList[this.ptr] }, */ "evaluate": function(){ //this.initPhrase(); console.log(this.superGroup); //this.evaluatePhrase(); }, "getPriorNode":function(){ return pointLookup[this.parentId]; }, "getNextSibling":function() { var siblingId = pointLookup[point.parentId].children[this.childNumber+1]; if (pointLookup[siblingId]) return pointLookup[siblingId]; else return undefined; }, "getPriorSibling":function() { var siblingId = pointLookup[point.parentId].children[this.childNumber-1]; if (pointLookup[siblingId]) return pointLookup[siblingId]; else return undefined; }, "getJSON":function() { return graphLookup[this.id].toJSON(this.ptr); }, /* "setProgramNodes":function() { var id = this.ptr[0]; var ptr = this.ptr; this.isProgram = false; if (this.node.types) if (this.node.types['program']) { this.programName = this.node.value; this.isProgram = true; } var a = copyArray(ptr); var c = []; this.parentProgramNames = []; while (a.length > 2) { a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['program']) { if (o.value != this.progs[this.progs.length-1]) { this.parentProgramNames.push(this.node.value); this.programName = o.node.value; //.push(o); this.isParam = true; //break; } } } }, */ // more unneeded shit "setTypeNodes":function() { var id = this.ptr[0]; var ptr = this.ptr; this.isProgram = false; if (this.node.types) if (this.node.types['root']) { this.rootName = this.node.value; this.isRoot = true; //this.isProgram = true; } var a = copyArray(ptr); var c = []; this.programs = []; while (a.length > 2) { //a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['root']) { //if (o.value != this.progs[this.progs.length-1]) { this.rootName = o.node.value; //.push(o); //break; //} } if (o.types['program']) { this.programs.push(this.node.value); } } }, } function System(pt) { this.rootPoint = pt; // pt.setBeginPhrase(); //this.evaluatePhrase(); this.traversedNodes = {}; pt.nextPhrases = []; //pt.phraseBegin = true; //this.evaluatePhrase(); //console.log(this.ptr); //this.isMixedIn = true; //mixin(Phrase.prototype, this); } System.prototype = { "setsData":function() { (this.nextPoint.node.type['root'] || !this.nextPoint.children) }, //rootPhrase "evaluate":function() { this.hasTraversed = false //rootPhrase = this; function recurse(p) { if (this.traversedNodes[p]){ this.traversals--; }else this.traversedNodes[p] = true; if (p.programName) { var programNodeId = p.node.ptr[0]; if (!this.programVars[programNodeId]) this.programVars[programNodeId] = []; this.programVars[programNodeId].push(p.id); } if (p.node.types['root']){ p.phraseBegin = true; } if (p.node.types) if ((p.node.types['root'] || p.children.length == 0) && !hasTraversed) { //p.phraseBegin = true p.setBeginPhrase(); //var rootItem = p; // not sure about this .. because the phrase might be part of a greater phrase.... // need to play around with this if (this.hasTraversed) { pointLookup[p.parentId].phraseEnd = true; //if (rootPhrase) { //if (this.hasTraversed) { this.traversals--; this.nextPhrases.push(p.id); if (this.traversals == 0) { // iterations > 0 and also next childrent arent all roots .. // if there's just one item in the linkage, this strategy will break // rootPhrase.renderPhrase({"}); this.completed = true; //rootPhrase.nextPhrases = nextPhrases }else { p.nextPhrase.push(new Phrase(pt)); } // need to re-evaluate the phrase if the phrase hasn't completed } } if (!this.completed) for (var i =0 ; i < p.children.length; i++) { if (i > 0) { this.traversals++; this.hasTraversed = true; //for (var g in this) console.log(g); this.recurse(p.children[i], p) } } } recurse(this); //this.renderPhrase(); }, "render":function() { var point = this.rootPoint; this.recurse = function() { point.evaluateNode(); for (var c in point.children) { var pc = point.children[c]; pc.evaluateNode(); } } this.recurse(point); //this.evaluateNode(); } } function Phrase() { } Phrase.prototype = { /* "processPhrase":function(pb) { var brk = false; var levels = {}; function recurse(item) { if (item.phraseEnd) brk = true; if (brk) return; for (var child in item.children) { var pc = child.node.ptr; pc.pop();pc.pop(); var pcj = pc.join(); var co = child.phraseBeginPoint; if (arrayHas(co.levels[pcj], child.id)) { co.levelCount[pcj]++; } if (co.levelCount[pcj] == co.levels[pcj].length) { child.evaluateNode(pcj); } // might need some more work on other various types of node configuration that require waiting } } pb.levels = levels; } */ } // Template much include onFunction and onParameter function UIClass() {}; // UIClass.prototype = Object.create(baseProgram.prototype); UIClass.prototype = { "getNameSpace":function() { //need to look back to find 'grid' location }, "mouseClickCallback":function(ptr) { // iterate through the next pieces... }, "evaluateNode":function(pcj) { var hier = graph.prototype.getValueOrder(this.nodePtr); console.log("hier: "+hier); var x = contains(hier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}}); console.log("x:"+x); return; var hl = hier.length-1; if (this.node.types) if (this.node['types']["root"]) { // if (hier[hl] == "UI") { // if (this.phraseBegin) // this.ptrProgs[this.id] = new UIProgram(this.id, graph(graphLookup[this.node.ptr[0]]).toJSON()); } // check namespace if (contains(hier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}})) { //if (contains(hier, {'contains':{'vals':['row'], 'contains':{'vals':['label', 'inputbox', 'button']}}})) { if (this.superGroup.value == 'text') { if (!this.phraseEnd) { var ptr = this.node.ptr; //var o = getObject(ptr,this.uiprog); //o.callback = UI.dispatchValue; //this.uiprog.setEvent( // // // switch (this.superGroup.value) { case "text": this.variable = this.node.ptr; break; case "type": this.variable = this.node.ptr; break; } /* if (this.superGroup.value == 'text') { //this.getLastValue();b //var a = copyArray(this.node.ptr); this.variable = this.node.ptr } if (this.sueprGroup.value == 'type') { } */ } if (this.phraseEnd) { var ptr = this.node.ptr; if (this.superGroup.value == 'text') { //this.getLastValue();b //var a = copyArray(this.node.ptr); var o = getObject(this.node.ptr, graphLookup); ptrProgs[this.id].copyChild(this.node.ptr); } } } if (this.superGroup.value == 'type' && !this.phraseEnd) { if (this.node.value == "onSubmit") { //var o = getObject(p2, graphLookup); //for serialization concerns might need to turn the joins into jsonifieds var prog = ptrProgs[this.id]; a[0] = prog.gid; var btn = getObject(a, graphLookup); ptrProgs[this.id].setEvent("handleMouseClick", 'exact', a, this.mouseClickCallback); //o.registerEvents('callback'); // i'd like it i } //uiObject } } }, "drawUI":function() { //var uni = new universe("rendered", true); //var node = graphLookup[this.id]; //var json = point.JSON; //this.gid = uni.addGraph(); //graphLookup[gid].setFromJSON(this.JSON); // might need to hash it... // this draws ui component this.onCondition(); } } function DateClass() { } DateClass.prototype = { "getIsoDate":function(point, callback) { this.direction = this.inheritDirection(); //"push"; //;// point.nextPoint;// = "set"; // setting data dispatches data to be set by another function this.iterValue = {"program":{"Numbers":new Date().toString()}} this.onCondition(); } } function UniverseClass() { } UniverseClass.prototype = { "serializePtrGraph":function(point) { this.direction = this.inheritDirection(); this.value = {"serializedPtrGraph":{"serializedStuff":"codeNotComplete"}} this.onCondition(); } } /* function getNextContext = { } getNextContext.prototype = { "getNextContext":function() { this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (o.isContext) { o.isContext = true; }else this(o); } } } } */ function setNextContext() { } setNextContext.prototype = { "setNextContext":function() { // search for element and set flag this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (!o.isProgram) { o.setContext();// = true; }else this(o); } } this.recurse(this); } } function DBClass() { } DBClass.prototype = { /* "getVariable":function() { }, */ "evaluateNode":function(pcj) { var p = pointLookup[this.phraseBeginPoint]; //var pp //p.node.ptr.pop().pop(); // //a better way to express more complex namespaces is to route the vectors through the desired parent node var nsc = item.namespace[pcj]; var items = p.phraseBeginPoint.levels[pcj]; for (var i =0; i < items.length; i++) { var item = pointLookup(items[i]); if (item.priorNode.node.id != item.node.id) { //might also be a foreach from the priorNode if (item.priorNode.variable) { var p = item.getValuePtr(item.node.ptr); p.pop(); var o = getObject(p, nsc); o[item.value] = item.priorNode.variable; } else // return all values associated with that node { } //getValueHierarchy(item.node.ptr); //item.priorNode.variable }else { if (item.nextNode.node.id != item.node.id) { var p = item.getValuePtr(item.node.ptr); p.pop(); var o = getObject(p, nsc); this.variable = o[item.value]; //this.variable = // return variable } } } dbLayer.query(nsc); //p.levels--; //if (p.levels == 0) // getDBItem(); // search the tree upward to find the common tree /* if (!this.phraseEnd) { } */ }, "onIterationComplete":function() { if (this.hasContext()) { dbLayer.saveData(this.getContext().value, this.onCondition) } }, "getRootValueNode":function() { // create a loop from here to the next context change storedData }, "getValueNode":function() { } } var pathsLookup; var programs = {"UI":UIClass, "DB":DBClass, "Universe":UniverseClass, "Date":DateClass}; var traverseProgram = function(ptr) { //var p2 = copyArray(ptr); var o = getObject(ptr, graphLookup); var cap = []; for (var i = 0; i < o.links.length; i++) { var link = o.links[i]; cap.concat(link.children.concat(link.parents)); } for (var i = 0; i < cap.length; i++) { var ctop = cap.gfx.bottom + cap.gfx.height; cap.push({'y':ctop, 'obj':cap[i]}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } cap.sort(function (a, b) { return (a.y <b.y) }) return cap; } function getSubNodes(ptr) { return new selectInternodeDescendants(ptr).descendants; //return links; } function sortNodeLinks(items) { for (var i = 0; i < cap.length; i++) { var ctop = cap.gfx.bottom + cap.gfx.height; cap.push({'y':ctop, 'obj':cap[i]}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } cap.sort(function (a, b) { return (a.y < b.y) }) var cappy = []; for (var i = 0; i < cap.length; i++) { cappy.push(cap[i].obj); } return cappy; } function selectInternodeDescendants(ptr) { this.descendants = []; graph.prototype.recurseItems(selectInternodeDescendants.prototype.getNextChild()); } selectInternodeDescendants.prototype.getNextChild = function(ptr, obj) { for (var i = obj.index; i >=0 ;i--) { var link = obj[i]; //if (link.parents[0].length || link.children[0].length) this.descendants.push(obj[i].children.concat(obj[i].parents)); //return ptr; } } function getNextLinks(ptr, priorPtr) { this.ptr = ptr; var o = getObject (this.ptr, graphLookup); var cap = []; var a = o.children.concat(o.parents); for (var i = 0; i < o.length; i++) { if (a[i] != ptr) { var o = getObject(a[i], graphLookup); var ctop = o.gfx.bottom + o.gfx.height; cap.push({'y':ctop, 'obj':o}); // o.gfx // need to re-index the 'gfx' component // it makes no sense as it currently is set // the 'label' gfx shouldn't be mixed with the index gfx } } cap.sort(function (a, b) { return (a.gfx.y > b.gfx.y) }) capy = []; var ly = cap[0].y; nc = []; for (var i = 0; i < cap.length; cap++) { var ct = capy[cap[i].y]; if (ct === undefined) { capy[cap[i].y] = [cap[i].obj] }else capy[cap[i].y].push(cap[i].obj); if (ly != cap[i]) { capy[ly].sort(function(a,b) { return ( a.z > b.z ); }) nc.concat(capy[ly]) } ly = cap[i].y; // = cap[i]; } return nc; } /* * the point should make the decision var traverseProgramCallback = function(p) { var g = p.children; for (var i =0; i < p.children.length; p++) {//while (p.hasNextPoint) { var p = point[i]; //while (p.hasNextSibling) { // d = point.nextSibling(); traverseProgram(p); } } */ /*V point(thisPtr, lastPtr, sp, lastSp, lastLastPtr, lastLastSp) { } */
if (a1.types['program']) this.programName = nodeName;
random_line_split
lib.rs
//! The solana-program-test provides a BanksClient-based test framework BPF programs use chrono_humanize::{Accuracy, HumanTime, Tense}; use log::*; use solana_banks_client::start_client; use solana_banks_server::banks_server::start_local_server; use solana_program::{ account_info::AccountInfo, entrypoint::ProgramResult, hash::Hash, instruction::Instruction, instruction::InstructionError, message::Message, native_token::sol_to_lamports, program_error::ProgramError, program_stubs, pubkey::Pubkey, rent::Rent, }; use solana_runtime::{ bank::{Bank, Builtin}, bank_forks::BankForks, genesis_utils::create_genesis_config_with_leader, }; use solana_sdk::{ account::Account, keyed_account::KeyedAccount, process_instruction::BpfComputeBudget, process_instruction::{InvokeContext, MockInvokeContext, ProcessInstructionWithContext}, signature::{Keypair, Signer}, }; use std::{ cell::RefCell, collections::HashMap, convert::TryFrom, fs::File, io::Read, path::{Path, PathBuf}, rc::Rc, sync::{Arc, RwLock}, }; // Export types so test clients can limit their solana crate dependencies pub use solana_banks_client::{BanksClient, BanksClientExt}; #[macro_use] extern crate solana_bpf_loader_program; pub fn to_instruction_error(error: ProgramError) -> InstructionError { match error { ProgramError::Custom(err) => InstructionError::Custom(err), ProgramError::InvalidArgument => InstructionError::InvalidArgument, ProgramError::InvalidInstructionData => InstructionError::InvalidInstructionData, ProgramError::InvalidAccountData => InstructionError::InvalidAccountData, ProgramError::AccountDataTooSmall => InstructionError::AccountDataTooSmall, ProgramError::InsufficientFunds => InstructionError::InsufficientFunds, ProgramError::IncorrectProgramId => InstructionError::IncorrectProgramId, ProgramError::MissingRequiredSignature => InstructionError::MissingRequiredSignature, ProgramError::AccountAlreadyInitialized => InstructionError::AccountAlreadyInitialized, ProgramError::UninitializedAccount => InstructionError::UninitializedAccount, ProgramError::NotEnoughAccountKeys => InstructionError::NotEnoughAccountKeys, ProgramError::AccountBorrowFailed => InstructionError::AccountBorrowFailed, ProgramError::MaxSeedLengthExceeded => InstructionError::MaxSeedLengthExceeded, ProgramError::InvalidSeeds => InstructionError::InvalidSeeds, } } thread_local! { static INVOKE_CONTEXT:RefCell<Rc<MockInvokeContext>> = RefCell::new(Rc::new(MockInvokeContext::default())); } pub fn builtin_process_instruction( process_instruction: solana_program::entrypoint::ProcessInstruction, program_id: &Pubkey, keyed_accounts: &[KeyedAccount], input: &[u8], invoke_context: &mut dyn InvokeContext, ) -> Result<(), InstructionError> { let mut mock_invoke_context = MockInvokeContext::default(); mock_invoke_context.programs = invoke_context.get_programs().to_vec(); mock_invoke_context.key = *program_id; // TODO: Populate MockInvokeContext more, or rework to avoid MockInvokeContext entirely. // The context being passed into the program is incomplete... let local_invoke_context = RefCell::new(Rc::new(mock_invoke_context)); swap_invoke_context(&local_invoke_context); // Copy all the accounts into a HashMap to ensure there are no duplicates let mut accounts: HashMap<Pubkey, Account> = keyed_accounts .iter() .map(|ka| (*ka.unsigned_key(), ka.account.borrow().clone())) .collect(); // Create shared references to each account's lamports/data/owner let account_refs: HashMap<_, _> = accounts .iter_mut() .map(|(key, account)| { ( *key, ( Rc::new(RefCell::new(&mut account.lamports)), Rc::new(RefCell::new(&mut account.data[..])), &account.owner, ), ) }) .collect(); // Create AccountInfos let account_infos: Vec<AccountInfo> = keyed_accounts .iter() .map(|keyed_account| { let key = keyed_account.unsigned_key(); let (lamports, data, owner) = &account_refs[key]; AccountInfo { key, is_signer: keyed_account.signer_key().is_some(), is_writable: keyed_account.is_writable(), lamports: lamports.clone(), data: data.clone(), owner, executable: keyed_account.executable().unwrap(), rent_epoch: keyed_account.rent_epoch().unwrap(), } }) .collect(); // Execute the BPF entrypoint let result = process_instruction(program_id, &account_infos, input).map_err(to_instruction_error); if result.is_ok() { // Commit changes to the KeyedAccounts for keyed_account in keyed_accounts { let mut account = keyed_account.account.borrow_mut(); let key = keyed_account.unsigned_key(); let (lamports, data, _owner) = &account_refs[key]; account.lamports = **lamports.borrow(); account.data = data.borrow().to_vec(); } } swap_invoke_context(&local_invoke_context); // Propagate logs back to caller's invoke context // (TODO: This goes away if MockInvokeContext usage can be removed) let logger = invoke_context.get_logger(); let logger = logger.borrow_mut(); for message in local_invoke_context.borrow().logger.log.borrow_mut().iter() { if logger.log_enabled() { logger.log(message); } } result } /// Converts a `solana-program`-style entrypoint into the runtime's entrypoint style, for /// use with `ProgramTest::add_program` #[macro_export] macro_rules! processor { ($process_instruction:expr) => { Some( |program_id: &Pubkey, keyed_accounts: &[solana_sdk::keyed_account::KeyedAccount], input: &[u8], invoke_context: &mut dyn solana_sdk::process_instruction::InvokeContext| { $crate::builtin_process_instruction( $process_instruction, program_id, keyed_accounts, input, invoke_context, ) }, ) }; } pub fn
(other_invoke_context: &RefCell<Rc<MockInvokeContext>>) { INVOKE_CONTEXT.with(|invoke_context| { invoke_context.swap(&other_invoke_context); }); } struct SyscallStubs {} impl program_stubs::SyscallStubs for SyscallStubs { fn sol_log(&self, message: &str) { INVOKE_CONTEXT.with(|invoke_context| { let invoke_context = invoke_context.borrow_mut(); let logger = invoke_context.get_logger(); let logger = logger.borrow_mut(); if logger.log_enabled() { logger.log(&format!("Program log: {}", message)); } }); } fn sol_invoke_signed( &self, instruction: &Instruction, account_infos: &[AccountInfo], signers_seeds: &[&[&[u8]]], ) -> ProgramResult { // // TODO: Merge the business logic between here and the BPF invoke path in // programs/bpf_loader/src/syscalls.rs // info!("SyscallStubs::sol_invoke_signed()"); let mut caller = Pubkey::default(); let mut mock_invoke_context = MockInvokeContext::default(); INVOKE_CONTEXT.with(|invoke_context| { let invoke_context = invoke_context.borrow_mut(); caller = *invoke_context.get_caller().expect("get_caller"); invoke_context.record_instruction(&instruction); mock_invoke_context.programs = invoke_context.get_programs().to_vec(); // TODO: Populate MockInvokeContext more, or rework to avoid MockInvokeContext entirely. // The context being passed into the program is incomplete... }); if instruction.accounts.len() + 1 != account_infos.len() { panic!( "Instruction accounts mismatch. Instruction contains {} accounts, with {} AccountInfos provided", instruction.accounts.len(), account_infos.len() ); } let message = Message::new(&[instruction.clone()], None); let program_id_index = message.instructions[0].program_id_index as usize; let program_id = message.account_keys[program_id_index]; let program_account_info = &account_infos[program_id_index]; if !program_account_info.executable { panic!("Program account is not executable"); } if program_account_info.is_writable { panic!("Program account is writable"); } fn ai_to_a(ai: &AccountInfo) -> Account { Account { lamports: ai.lamports(), data: ai.try_borrow_data().unwrap().to_vec(), owner: *ai.owner, executable: ai.executable, rent_epoch: ai.rent_epoch, } } let executable_accounts = vec![(program_id, RefCell::new(ai_to_a(program_account_info)))]; let mut accounts = vec![]; for instruction_account in &instruction.accounts { for account_info in account_infos { if *account_info.unsigned_key() == instruction_account.pubkey { if instruction_account.is_writable && !account_info.is_writable { panic!("Writeable mismatch for {}", instruction_account.pubkey); } if instruction_account.is_signer && !account_info.is_signer { let mut program_signer = false; for seeds in signers_seeds.iter() { let signer = Pubkey::create_program_address(&seeds, &caller).unwrap(); if instruction_account.pubkey == signer { program_signer = true; break; } } if !program_signer { panic!("Signer mismatch for {}", instruction_account.pubkey); } } accounts.push(Rc::new(RefCell::new(ai_to_a(account_info)))); break; } } } assert_eq!(accounts.len(), instruction.accounts.len()); solana_runtime::message_processor::MessageProcessor::process_cross_program_instruction( &message, &executable_accounts, &accounts, &mut mock_invoke_context, ) .map_err(|err| ProgramError::try_from(err).unwrap_or_else(|err| panic!("{}", err)))?; // Propagate logs back to caller's invoke context // (TODO: This goes away if MockInvokeContext usage can be removed) INVOKE_CONTEXT.with(|invoke_context| { let logger = invoke_context.borrow().get_logger(); let logger = logger.borrow_mut(); for message in mock_invoke_context.logger.log.borrow_mut().iter() { if logger.log_enabled() { logger.log(message); } } }); // Copy writeable account modifications back into the caller's AccountInfos for (i, instruction_account) in instruction.accounts.iter().enumerate() { if !instruction_account.is_writable { continue; } for account_info in account_infos { if *account_info.unsigned_key() == instruction_account.pubkey { let account = &accounts[i]; **account_info.try_borrow_mut_lamports().unwrap() = account.borrow().lamports; let mut data = account_info.try_borrow_mut_data()?; let new_data = &account.borrow().data; if data.len() != new_data.len() { // TODO: Figure out how to change the callers account data size panic!( "Account resizing ({} -> {}) not supported yet", data.len(), new_data.len() ); } data.clone_from_slice(new_data); } } } Ok(()) } } fn find_file(filename: &str) -> Option<PathBuf> { for path in &["", "tests/fixtures"] { let candidate = Path::new(path).join(&filename); if candidate.exists() { return Some(candidate); } } None } fn read_file<P: AsRef<Path>>(path: P) -> Vec<u8> { let path = path.as_ref(); let mut file = File::open(path) .unwrap_or_else(|err| panic!("Failed to open \"{}\": {}", path.display(), err)); let mut file_data = Vec::new(); file.read_to_end(&mut file_data) .unwrap_or_else(|err| panic!("Failed to read \"{}\": {}", path.display(), err)); file_data } pub struct ProgramTest { accounts: Vec<(Pubkey, Account)>, builtins: Vec<Builtin>, bpf_compute_max_units: Option<u64>, prefer_bpf: bool, } impl Default for ProgramTest { /// Initialize a new ProgramTest /// /// The `bpf` environment variable controls how BPF programs are selected during operation: /// `export bpf=1` -- use BPF programs if present, otherwise fall back to the /// native instruction processors provided with the test /// `export bpf=0` -- use native instruction processor if present, otherwise fall back to /// the BPF program /// (default) /// and the `ProgramTest::prefer_bpf()` method may be used to override the selection at runtime /// /// BPF program shared objects and account data files are searched for in /// * the current working directory (the default output location for `cargo build-bpf), /// * the `tests/fixtures` sub-directory /// fn default() -> Self { solana_logger::setup_with_default( "solana_bpf_loader=debug,\ solana_rbpf::vm=debug,\ solana_runtime::message_processor=info,\ solana_runtime::system_instruction_processor=trace,\ solana_program_test=info", ); let prefer_bpf = match std::env::var("bpf") { Ok(val) => !matches!(val.as_str(), "0" | ""), Err(_err) => false, }; Self { accounts: vec![], builtins: vec![], bpf_compute_max_units: None, prefer_bpf, } } } // Values returned by `ProgramTest::start` pub struct StartOutputs { pub banks_client: BanksClient, pub payer: Keypair, pub recent_blockhash: Hash, pub rent: Rent, } impl ProgramTest { pub fn new( program_name: &str, program_id: Pubkey, process_instruction: Option<ProcessInstructionWithContext>, ) -> Self { let mut me = Self::default(); me.add_program(program_name, program_id, process_instruction); me } /// Override default BPF program selection pub fn prefer_bpf(&mut self, prefer_bpf: bool) { self.prefer_bpf = prefer_bpf; } /// Override the BPF compute budget pub fn set_bpf_compute_max_units(&mut self, bpf_compute_max_units: u64) { self.bpf_compute_max_units = Some(bpf_compute_max_units); } /// Add an account to the test environment pub fn add_account(&mut self, address: Pubkey, account: Account) { self.accounts.push((address, account)); } /// Add an account to the test environment with the account data in the provided `filename` pub fn add_account_with_file_data( &mut self, address: Pubkey, lamports: u64, owner: Pubkey, filename: &str, ) { self.add_account( address, Account { lamports, data: read_file(find_file(filename).unwrap_or_else(|| { panic!("Unable to locate {}", filename); })), owner, executable: false, rent_epoch: 0, }, ); } /// Add an account to the test environment with the account data in the provided as a base 64 /// string pub fn add_account_with_base64_data( &mut self, address: Pubkey, lamports: u64, owner: Pubkey, data_base64: &str, ) { self.add_account( address, Account { lamports, data: base64::decode(data_base64) .unwrap_or_else(|err| panic!("Failed to base64 decode: {}", err)), owner, executable: false, rent_epoch: 0, }, ); } /// Add a BPF program to the test environment. /// /// `program_name` will also used to locate the BPF shared object in the current or fixtures /// directory. /// /// If `process_instruction` is provided, the natively built-program may be used instead of the /// BPF shared object depending on the `bpf` environment variable. pub fn add_program( &mut self, program_name: &str, program_id: Pubkey, process_instruction: Option<ProcessInstructionWithContext>, ) { let loader = solana_program::bpf_loader::id(); let program_file = find_file(&format!("{}.so", program_name)); if process_instruction.is_none() && program_file.is_none() { panic!("Unable to add program {} ({})", program_name, program_id); } if (program_file.is_some() && self.prefer_bpf) || process_instruction.is_none() { let program_file = program_file.unwrap_or_else(|| { panic!( "Program file data not available for {} ({})", program_name, program_id ); }); let data = read_file(&program_file); info!( "\"{}\" BPF program from {}{}", program_name, program_file.display(), std::fs::metadata(&program_file) .map(|metadata| { metadata .modified() .map(|time| { format!( ", modified {}", HumanTime::from(time) .to_text_en(Accuracy::Precise, Tense::Past) ) }) .ok() }) .ok() .flatten() .unwrap_or_else(|| "".to_string()) ); self.add_account( program_id, Account { lamports: Rent::default().minimum_balance(data.len()).min(1), data, owner: loader, executable: true, rent_epoch: 0, }, ); } else { info!("\"{}\" program loaded as native code", program_name); self.builtins.push(Builtin::new( program_name, program_id, process_instruction.unwrap_or_else(|| { panic!( "Program processor not available for {} ({})", program_name, program_id ); }), )); } } /// Start the test client /// /// Returns a `BanksClient` interface into the test environment as well as a payer `Keypair` /// with SOL for sending transactions pub async fn start(self) -> StartOutputs { { use std::sync::Once; static ONCE: Once = Once::new(); ONCE.call_once(|| { program_stubs::set_syscall_stubs(Box::new(SyscallStubs {})); }); } let bootstrap_validator_pubkey = Pubkey::new_unique(); let bootstrap_validator_stake_lamports = 42; let gci = create_genesis_config_with_leader( sol_to_lamports(1_000_000.0), &bootstrap_validator_pubkey, bootstrap_validator_stake_lamports, ); let mut genesis_config = gci.genesis_config; let rent = Rent::default(); genesis_config.rent = rent; genesis_config.fee_rate_governor = solana_program::fee_calculator::FeeRateGovernor::default(); let payer = gci.mint_keypair; debug!("Payer address: {}", payer.pubkey()); debug!("Genesis config: {}", genesis_config); let mut bank = Bank::new(&genesis_config); for loader in &[ solana_bpf_loader_deprecated_program!(), solana_bpf_loader_program!(), ] { bank.add_builtin(&loader.0, loader.1, loader.2); } // User-supplied additional builtins for builtin in self.builtins { bank.add_builtin( &builtin.name, builtin.id, builtin.process_instruction_with_context, ); } for (address, account) in self.accounts { if bank.get_account(&address).is_some() { panic!("An account at {} already exists", address); } bank.store_account(&address, &account); } bank.set_capitalization(); if let Some(max_units) = self.bpf_compute_max_units { bank.set_bpf_compute_budget(Some(BpfComputeBudget { max_units, ..BpfComputeBudget::default() })); } // Advance beyond slot 0 for a slightly more realistic test environment let bank = Arc::new(bank); let bank = Bank::new_from_parent(&bank, bank.collector_id(), bank.slot() + 1); debug!("Bank slot: {}", bank.slot()); let bank_forks = Arc::new(RwLock::new(BankForks::new(bank))); let transport = start_local_server(&bank_forks).await; let mut banks_client = start_client(transport) .await .unwrap_or_else(|err| panic!("Failed to start banks client: {}", err)); let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap(); StartOutputs { banks_client, payer, recent_blockhash, rent, } } }
swap_invoke_context
identifier_name
lib.rs
//! The solana-program-test provides a BanksClient-based test framework BPF programs use chrono_humanize::{Accuracy, HumanTime, Tense}; use log::*; use solana_banks_client::start_client; use solana_banks_server::banks_server::start_local_server; use solana_program::{ account_info::AccountInfo, entrypoint::ProgramResult, hash::Hash, instruction::Instruction, instruction::InstructionError, message::Message, native_token::sol_to_lamports, program_error::ProgramError, program_stubs, pubkey::Pubkey, rent::Rent, }; use solana_runtime::{ bank::{Bank, Builtin}, bank_forks::BankForks, genesis_utils::create_genesis_config_with_leader, }; use solana_sdk::{ account::Account, keyed_account::KeyedAccount, process_instruction::BpfComputeBudget, process_instruction::{InvokeContext, MockInvokeContext, ProcessInstructionWithContext}, signature::{Keypair, Signer}, }; use std::{ cell::RefCell, collections::HashMap, convert::TryFrom, fs::File, io::Read, path::{Path, PathBuf}, rc::Rc, sync::{Arc, RwLock}, }; // Export types so test clients can limit their solana crate dependencies pub use solana_banks_client::{BanksClient, BanksClientExt}; #[macro_use] extern crate solana_bpf_loader_program; pub fn to_instruction_error(error: ProgramError) -> InstructionError { match error { ProgramError::Custom(err) => InstructionError::Custom(err), ProgramError::InvalidArgument => InstructionError::InvalidArgument, ProgramError::InvalidInstructionData => InstructionError::InvalidInstructionData, ProgramError::InvalidAccountData => InstructionError::InvalidAccountData, ProgramError::AccountDataTooSmall => InstructionError::AccountDataTooSmall, ProgramError::InsufficientFunds => InstructionError::InsufficientFunds, ProgramError::IncorrectProgramId => InstructionError::IncorrectProgramId, ProgramError::MissingRequiredSignature => InstructionError::MissingRequiredSignature, ProgramError::AccountAlreadyInitialized => InstructionError::AccountAlreadyInitialized, ProgramError::UninitializedAccount => InstructionError::UninitializedAccount, ProgramError::NotEnoughAccountKeys => InstructionError::NotEnoughAccountKeys, ProgramError::AccountBorrowFailed => InstructionError::AccountBorrowFailed, ProgramError::MaxSeedLengthExceeded => InstructionError::MaxSeedLengthExceeded, ProgramError::InvalidSeeds => InstructionError::InvalidSeeds, } } thread_local! { static INVOKE_CONTEXT:RefCell<Rc<MockInvokeContext>> = RefCell::new(Rc::new(MockInvokeContext::default())); } pub fn builtin_process_instruction( process_instruction: solana_program::entrypoint::ProcessInstruction, program_id: &Pubkey, keyed_accounts: &[KeyedAccount], input: &[u8], invoke_context: &mut dyn InvokeContext, ) -> Result<(), InstructionError> { let mut mock_invoke_context = MockInvokeContext::default(); mock_invoke_context.programs = invoke_context.get_programs().to_vec(); mock_invoke_context.key = *program_id; // TODO: Populate MockInvokeContext more, or rework to avoid MockInvokeContext entirely. // The context being passed into the program is incomplete... let local_invoke_context = RefCell::new(Rc::new(mock_invoke_context)); swap_invoke_context(&local_invoke_context); // Copy all the accounts into a HashMap to ensure there are no duplicates let mut accounts: HashMap<Pubkey, Account> = keyed_accounts .iter() .map(|ka| (*ka.unsigned_key(), ka.account.borrow().clone())) .collect(); // Create shared references to each account's lamports/data/owner let account_refs: HashMap<_, _> = accounts .iter_mut() .map(|(key, account)| { ( *key, ( Rc::new(RefCell::new(&mut account.lamports)), Rc::new(RefCell::new(&mut account.data[..])), &account.owner, ), ) }) .collect(); // Create AccountInfos let account_infos: Vec<AccountInfo> = keyed_accounts .iter() .map(|keyed_account| { let key = keyed_account.unsigned_key(); let (lamports, data, owner) = &account_refs[key]; AccountInfo { key, is_signer: keyed_account.signer_key().is_some(), is_writable: keyed_account.is_writable(), lamports: lamports.clone(), data: data.clone(), owner, executable: keyed_account.executable().unwrap(), rent_epoch: keyed_account.rent_epoch().unwrap(), } }) .collect(); // Execute the BPF entrypoint let result = process_instruction(program_id, &account_infos, input).map_err(to_instruction_error); if result.is_ok() { // Commit changes to the KeyedAccounts for keyed_account in keyed_accounts { let mut account = keyed_account.account.borrow_mut(); let key = keyed_account.unsigned_key(); let (lamports, data, _owner) = &account_refs[key]; account.lamports = **lamports.borrow(); account.data = data.borrow().to_vec(); } } swap_invoke_context(&local_invoke_context); // Propagate logs back to caller's invoke context // (TODO: This goes away if MockInvokeContext usage can be removed) let logger = invoke_context.get_logger(); let logger = logger.borrow_mut(); for message in local_invoke_context.borrow().logger.log.borrow_mut().iter() { if logger.log_enabled() { logger.log(message); } } result } /// Converts a `solana-program`-style entrypoint into the runtime's entrypoint style, for /// use with `ProgramTest::add_program` #[macro_export] macro_rules! processor { ($process_instruction:expr) => { Some( |program_id: &Pubkey, keyed_accounts: &[solana_sdk::keyed_account::KeyedAccount], input: &[u8], invoke_context: &mut dyn solana_sdk::process_instruction::InvokeContext| { $crate::builtin_process_instruction( $process_instruction, program_id, keyed_accounts, input, invoke_context, ) }, ) }; } pub fn swap_invoke_context(other_invoke_context: &RefCell<Rc<MockInvokeContext>>) { INVOKE_CONTEXT.with(|invoke_context| { invoke_context.swap(&other_invoke_context); }); } struct SyscallStubs {} impl program_stubs::SyscallStubs for SyscallStubs { fn sol_log(&self, message: &str) { INVOKE_CONTEXT.with(|invoke_context| { let invoke_context = invoke_context.borrow_mut(); let logger = invoke_context.get_logger(); let logger = logger.borrow_mut(); if logger.log_enabled() { logger.log(&format!("Program log: {}", message)); } }); } fn sol_invoke_signed( &self, instruction: &Instruction, account_infos: &[AccountInfo], signers_seeds: &[&[&[u8]]], ) -> ProgramResult { // // TODO: Merge the business logic between here and the BPF invoke path in // programs/bpf_loader/src/syscalls.rs // info!("SyscallStubs::sol_invoke_signed()"); let mut caller = Pubkey::default(); let mut mock_invoke_context = MockInvokeContext::default(); INVOKE_CONTEXT.with(|invoke_context| { let invoke_context = invoke_context.borrow_mut(); caller = *invoke_context.get_caller().expect("get_caller"); invoke_context.record_instruction(&instruction); mock_invoke_context.programs = invoke_context.get_programs().to_vec(); // TODO: Populate MockInvokeContext more, or rework to avoid MockInvokeContext entirely. // The context being passed into the program is incomplete... }); if instruction.accounts.len() + 1 != account_infos.len() { panic!( "Instruction accounts mismatch. Instruction contains {} accounts, with {} AccountInfos provided", instruction.accounts.len(), account_infos.len() ); } let message = Message::new(&[instruction.clone()], None); let program_id_index = message.instructions[0].program_id_index as usize; let program_id = message.account_keys[program_id_index]; let program_account_info = &account_infos[program_id_index]; if !program_account_info.executable { panic!("Program account is not executable"); } if program_account_info.is_writable { panic!("Program account is writable"); } fn ai_to_a(ai: &AccountInfo) -> Account { Account { lamports: ai.lamports(), data: ai.try_borrow_data().unwrap().to_vec(), owner: *ai.owner, executable: ai.executable, rent_epoch: ai.rent_epoch, } } let executable_accounts = vec![(program_id, RefCell::new(ai_to_a(program_account_info)))]; let mut accounts = vec![]; for instruction_account in &instruction.accounts { for account_info in account_infos { if *account_info.unsigned_key() == instruction_account.pubkey { if instruction_account.is_writable && !account_info.is_writable { panic!("Writeable mismatch for {}", instruction_account.pubkey); } if instruction_account.is_signer && !account_info.is_signer { let mut program_signer = false; for seeds in signers_seeds.iter() { let signer = Pubkey::create_program_address(&seeds, &caller).unwrap(); if instruction_account.pubkey == signer { program_signer = true; break; } } if !program_signer { panic!("Signer mismatch for {}", instruction_account.pubkey); } } accounts.push(Rc::new(RefCell::new(ai_to_a(account_info)))); break; } } } assert_eq!(accounts.len(), instruction.accounts.len()); solana_runtime::message_processor::MessageProcessor::process_cross_program_instruction( &message, &executable_accounts, &accounts, &mut mock_invoke_context, ) .map_err(|err| ProgramError::try_from(err).unwrap_or_else(|err| panic!("{}", err)))?; // Propagate logs back to caller's invoke context // (TODO: This goes away if MockInvokeContext usage can be removed) INVOKE_CONTEXT.with(|invoke_context| { let logger = invoke_context.borrow().get_logger(); let logger = logger.borrow_mut(); for message in mock_invoke_context.logger.log.borrow_mut().iter() { if logger.log_enabled() { logger.log(message); } } }); // Copy writeable account modifications back into the caller's AccountInfos for (i, instruction_account) in instruction.accounts.iter().enumerate() { if !instruction_account.is_writable { continue; } for account_info in account_infos { if *account_info.unsigned_key() == instruction_account.pubkey { let account = &accounts[i]; **account_info.try_borrow_mut_lamports().unwrap() = account.borrow().lamports; let mut data = account_info.try_borrow_mut_data()?; let new_data = &account.borrow().data; if data.len() != new_data.len() { // TODO: Figure out how to change the callers account data size panic!( "Account resizing ({} -> {}) not supported yet", data.len(), new_data.len() ); } data.clone_from_slice(new_data); } } } Ok(()) } } fn find_file(filename: &str) -> Option<PathBuf> { for path in &["", "tests/fixtures"] { let candidate = Path::new(path).join(&filename); if candidate.exists() { return Some(candidate); } } None } fn read_file<P: AsRef<Path>>(path: P) -> Vec<u8> { let path = path.as_ref(); let mut file = File::open(path) .unwrap_or_else(|err| panic!("Failed to open \"{}\": {}", path.display(), err)); let mut file_data = Vec::new(); file.read_to_end(&mut file_data) .unwrap_or_else(|err| panic!("Failed to read \"{}\": {}", path.display(), err)); file_data } pub struct ProgramTest { accounts: Vec<(Pubkey, Account)>, builtins: Vec<Builtin>, bpf_compute_max_units: Option<u64>, prefer_bpf: bool, } impl Default for ProgramTest { /// Initialize a new ProgramTest /// /// The `bpf` environment variable controls how BPF programs are selected during operation: /// `export bpf=1` -- use BPF programs if present, otherwise fall back to the /// native instruction processors provided with the test /// `export bpf=0` -- use native instruction processor if present, otherwise fall back to /// the BPF program /// (default) /// and the `ProgramTest::prefer_bpf()` method may be used to override the selection at runtime /// /// BPF program shared objects and account data files are searched for in /// * the current working directory (the default output location for `cargo build-bpf), /// * the `tests/fixtures` sub-directory /// fn default() -> Self { solana_logger::setup_with_default( "solana_bpf_loader=debug,\ solana_rbpf::vm=debug,\ solana_runtime::message_processor=info,\ solana_runtime::system_instruction_processor=trace,\ solana_program_test=info", ); let prefer_bpf = match std::env::var("bpf") { Ok(val) => !matches!(val.as_str(), "0" | ""), Err(_err) => false, }; Self { accounts: vec![], builtins: vec![], bpf_compute_max_units: None, prefer_bpf, } } } // Values returned by `ProgramTest::start` pub struct StartOutputs { pub banks_client: BanksClient, pub payer: Keypair, pub recent_blockhash: Hash, pub rent: Rent, } impl ProgramTest { pub fn new( program_name: &str, program_id: Pubkey, process_instruction: Option<ProcessInstructionWithContext>, ) -> Self
/// Override default BPF program selection pub fn prefer_bpf(&mut self, prefer_bpf: bool) { self.prefer_bpf = prefer_bpf; } /// Override the BPF compute budget pub fn set_bpf_compute_max_units(&mut self, bpf_compute_max_units: u64) { self.bpf_compute_max_units = Some(bpf_compute_max_units); } /// Add an account to the test environment pub fn add_account(&mut self, address: Pubkey, account: Account) { self.accounts.push((address, account)); } /// Add an account to the test environment with the account data in the provided `filename` pub fn add_account_with_file_data( &mut self, address: Pubkey, lamports: u64, owner: Pubkey, filename: &str, ) { self.add_account( address, Account { lamports, data: read_file(find_file(filename).unwrap_or_else(|| { panic!("Unable to locate {}", filename); })), owner, executable: false, rent_epoch: 0, }, ); } /// Add an account to the test environment with the account data in the provided as a base 64 /// string pub fn add_account_with_base64_data( &mut self, address: Pubkey, lamports: u64, owner: Pubkey, data_base64: &str, ) { self.add_account( address, Account { lamports, data: base64::decode(data_base64) .unwrap_or_else(|err| panic!("Failed to base64 decode: {}", err)), owner, executable: false, rent_epoch: 0, }, ); } /// Add a BPF program to the test environment. /// /// `program_name` will also used to locate the BPF shared object in the current or fixtures /// directory. /// /// If `process_instruction` is provided, the natively built-program may be used instead of the /// BPF shared object depending on the `bpf` environment variable. pub fn add_program( &mut self, program_name: &str, program_id: Pubkey, process_instruction: Option<ProcessInstructionWithContext>, ) { let loader = solana_program::bpf_loader::id(); let program_file = find_file(&format!("{}.so", program_name)); if process_instruction.is_none() && program_file.is_none() { panic!("Unable to add program {} ({})", program_name, program_id); } if (program_file.is_some() && self.prefer_bpf) || process_instruction.is_none() { let program_file = program_file.unwrap_or_else(|| { panic!( "Program file data not available for {} ({})", program_name, program_id ); }); let data = read_file(&program_file); info!( "\"{}\" BPF program from {}{}", program_name, program_file.display(), std::fs::metadata(&program_file) .map(|metadata| { metadata .modified() .map(|time| { format!( ", modified {}", HumanTime::from(time) .to_text_en(Accuracy::Precise, Tense::Past) ) }) .ok() }) .ok() .flatten() .unwrap_or_else(|| "".to_string()) ); self.add_account( program_id, Account { lamports: Rent::default().minimum_balance(data.len()).min(1), data, owner: loader, executable: true, rent_epoch: 0, }, ); } else { info!("\"{}\" program loaded as native code", program_name); self.builtins.push(Builtin::new( program_name, program_id, process_instruction.unwrap_or_else(|| { panic!( "Program processor not available for {} ({})", program_name, program_id ); }), )); } } /// Start the test client /// /// Returns a `BanksClient` interface into the test environment as well as a payer `Keypair` /// with SOL for sending transactions pub async fn start(self) -> StartOutputs { { use std::sync::Once; static ONCE: Once = Once::new(); ONCE.call_once(|| { program_stubs::set_syscall_stubs(Box::new(SyscallStubs {})); }); } let bootstrap_validator_pubkey = Pubkey::new_unique(); let bootstrap_validator_stake_lamports = 42; let gci = create_genesis_config_with_leader( sol_to_lamports(1_000_000.0), &bootstrap_validator_pubkey, bootstrap_validator_stake_lamports, ); let mut genesis_config = gci.genesis_config; let rent = Rent::default(); genesis_config.rent = rent; genesis_config.fee_rate_governor = solana_program::fee_calculator::FeeRateGovernor::default(); let payer = gci.mint_keypair; debug!("Payer address: {}", payer.pubkey()); debug!("Genesis config: {}", genesis_config); let mut bank = Bank::new(&genesis_config); for loader in &[ solana_bpf_loader_deprecated_program!(), solana_bpf_loader_program!(), ] { bank.add_builtin(&loader.0, loader.1, loader.2); } // User-supplied additional builtins for builtin in self.builtins { bank.add_builtin( &builtin.name, builtin.id, builtin.process_instruction_with_context, ); } for (address, account) in self.accounts { if bank.get_account(&address).is_some() { panic!("An account at {} already exists", address); } bank.store_account(&address, &account); } bank.set_capitalization(); if let Some(max_units) = self.bpf_compute_max_units { bank.set_bpf_compute_budget(Some(BpfComputeBudget { max_units, ..BpfComputeBudget::default() })); } // Advance beyond slot 0 for a slightly more realistic test environment let bank = Arc::new(bank); let bank = Bank::new_from_parent(&bank, bank.collector_id(), bank.slot() + 1); debug!("Bank slot: {}", bank.slot()); let bank_forks = Arc::new(RwLock::new(BankForks::new(bank))); let transport = start_local_server(&bank_forks).await; let mut banks_client = start_client(transport) .await .unwrap_or_else(|err| panic!("Failed to start banks client: {}", err)); let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap(); StartOutputs { banks_client, payer, recent_blockhash, rent, } } }
{ let mut me = Self::default(); me.add_program(program_name, program_id, process_instruction); me }
identifier_body
lib.rs
//! The solana-program-test provides a BanksClient-based test framework BPF programs use chrono_humanize::{Accuracy, HumanTime, Tense}; use log::*; use solana_banks_client::start_client; use solana_banks_server::banks_server::start_local_server; use solana_program::{ account_info::AccountInfo, entrypoint::ProgramResult, hash::Hash, instruction::Instruction, instruction::InstructionError, message::Message, native_token::sol_to_lamports, program_error::ProgramError, program_stubs, pubkey::Pubkey, rent::Rent, }; use solana_runtime::{ bank::{Bank, Builtin}, bank_forks::BankForks, genesis_utils::create_genesis_config_with_leader, }; use solana_sdk::{ account::Account, keyed_account::KeyedAccount, process_instruction::BpfComputeBudget, process_instruction::{InvokeContext, MockInvokeContext, ProcessInstructionWithContext}, signature::{Keypair, Signer}, }; use std::{ cell::RefCell, collections::HashMap, convert::TryFrom, fs::File, io::Read, path::{Path, PathBuf}, rc::Rc, sync::{Arc, RwLock}, }; // Export types so test clients can limit their solana crate dependencies pub use solana_banks_client::{BanksClient, BanksClientExt}; #[macro_use] extern crate solana_bpf_loader_program; pub fn to_instruction_error(error: ProgramError) -> InstructionError { match error { ProgramError::Custom(err) => InstructionError::Custom(err), ProgramError::InvalidArgument => InstructionError::InvalidArgument, ProgramError::InvalidInstructionData => InstructionError::InvalidInstructionData, ProgramError::InvalidAccountData => InstructionError::InvalidAccountData, ProgramError::AccountDataTooSmall => InstructionError::AccountDataTooSmall, ProgramError::InsufficientFunds => InstructionError::InsufficientFunds, ProgramError::IncorrectProgramId => InstructionError::IncorrectProgramId, ProgramError::MissingRequiredSignature => InstructionError::MissingRequiredSignature, ProgramError::AccountAlreadyInitialized => InstructionError::AccountAlreadyInitialized, ProgramError::UninitializedAccount => InstructionError::UninitializedAccount, ProgramError::NotEnoughAccountKeys => InstructionError::NotEnoughAccountKeys, ProgramError::AccountBorrowFailed => InstructionError::AccountBorrowFailed, ProgramError::MaxSeedLengthExceeded => InstructionError::MaxSeedLengthExceeded, ProgramError::InvalidSeeds => InstructionError::InvalidSeeds, } } thread_local! { static INVOKE_CONTEXT:RefCell<Rc<MockInvokeContext>> = RefCell::new(Rc::new(MockInvokeContext::default())); } pub fn builtin_process_instruction( process_instruction: solana_program::entrypoint::ProcessInstruction, program_id: &Pubkey, keyed_accounts: &[KeyedAccount], input: &[u8], invoke_context: &mut dyn InvokeContext, ) -> Result<(), InstructionError> { let mut mock_invoke_context = MockInvokeContext::default(); mock_invoke_context.programs = invoke_context.get_programs().to_vec(); mock_invoke_context.key = *program_id; // TODO: Populate MockInvokeContext more, or rework to avoid MockInvokeContext entirely. // The context being passed into the program is incomplete... let local_invoke_context = RefCell::new(Rc::new(mock_invoke_context)); swap_invoke_context(&local_invoke_context); // Copy all the accounts into a HashMap to ensure there are no duplicates let mut accounts: HashMap<Pubkey, Account> = keyed_accounts .iter() .map(|ka| (*ka.unsigned_key(), ka.account.borrow().clone())) .collect(); // Create shared references to each account's lamports/data/owner let account_refs: HashMap<_, _> = accounts .iter_mut() .map(|(key, account)| { ( *key, ( Rc::new(RefCell::new(&mut account.lamports)), Rc::new(RefCell::new(&mut account.data[..])), &account.owner, ), ) }) .collect(); // Create AccountInfos let account_infos: Vec<AccountInfo> = keyed_accounts .iter() .map(|keyed_account| { let key = keyed_account.unsigned_key(); let (lamports, data, owner) = &account_refs[key]; AccountInfo { key, is_signer: keyed_account.signer_key().is_some(), is_writable: keyed_account.is_writable(), lamports: lamports.clone(), data: data.clone(), owner, executable: keyed_account.executable().unwrap(), rent_epoch: keyed_account.rent_epoch().unwrap(), } }) .collect(); // Execute the BPF entrypoint let result = process_instruction(program_id, &account_infos, input).map_err(to_instruction_error); if result.is_ok() { // Commit changes to the KeyedAccounts for keyed_account in keyed_accounts { let mut account = keyed_account.account.borrow_mut(); let key = keyed_account.unsigned_key(); let (lamports, data, _owner) = &account_refs[key]; account.lamports = **lamports.borrow(); account.data = data.borrow().to_vec(); } } swap_invoke_context(&local_invoke_context); // Propagate logs back to caller's invoke context // (TODO: This goes away if MockInvokeContext usage can be removed) let logger = invoke_context.get_logger(); let logger = logger.borrow_mut(); for message in local_invoke_context.borrow().logger.log.borrow_mut().iter() { if logger.log_enabled() { logger.log(message); } } result } /// Converts a `solana-program`-style entrypoint into the runtime's entrypoint style, for /// use with `ProgramTest::add_program` #[macro_export] macro_rules! processor { ($process_instruction:expr) => { Some( |program_id: &Pubkey, keyed_accounts: &[solana_sdk::keyed_account::KeyedAccount], input: &[u8], invoke_context: &mut dyn solana_sdk::process_instruction::InvokeContext| { $crate::builtin_process_instruction( $process_instruction, program_id, keyed_accounts, input, invoke_context, ) }, ) }; } pub fn swap_invoke_context(other_invoke_context: &RefCell<Rc<MockInvokeContext>>) { INVOKE_CONTEXT.with(|invoke_context| { invoke_context.swap(&other_invoke_context); }); } struct SyscallStubs {} impl program_stubs::SyscallStubs for SyscallStubs { fn sol_log(&self, message: &str) { INVOKE_CONTEXT.with(|invoke_context| { let invoke_context = invoke_context.borrow_mut(); let logger = invoke_context.get_logger(); let logger = logger.borrow_mut(); if logger.log_enabled() { logger.log(&format!("Program log: {}", message)); } }); } fn sol_invoke_signed( &self, instruction: &Instruction, account_infos: &[AccountInfo], signers_seeds: &[&[&[u8]]], ) -> ProgramResult { // // TODO: Merge the business logic between here and the BPF invoke path in // programs/bpf_loader/src/syscalls.rs // info!("SyscallStubs::sol_invoke_signed()"); let mut caller = Pubkey::default(); let mut mock_invoke_context = MockInvokeContext::default(); INVOKE_CONTEXT.with(|invoke_context| { let invoke_context = invoke_context.borrow_mut(); caller = *invoke_context.get_caller().expect("get_caller"); invoke_context.record_instruction(&instruction); mock_invoke_context.programs = invoke_context.get_programs().to_vec(); // TODO: Populate MockInvokeContext more, or rework to avoid MockInvokeContext entirely. // The context being passed into the program is incomplete... }); if instruction.accounts.len() + 1 != account_infos.len() { panic!( "Instruction accounts mismatch. Instruction contains {} accounts, with {} AccountInfos provided", instruction.accounts.len(), account_infos.len() ); } let message = Message::new(&[instruction.clone()], None); let program_id_index = message.instructions[0].program_id_index as usize; let program_id = message.account_keys[program_id_index]; let program_account_info = &account_infos[program_id_index]; if !program_account_info.executable { panic!("Program account is not executable"); } if program_account_info.is_writable { panic!("Program account is writable"); } fn ai_to_a(ai: &AccountInfo) -> Account { Account { lamports: ai.lamports(), data: ai.try_borrow_data().unwrap().to_vec(), owner: *ai.owner, executable: ai.executable, rent_epoch: ai.rent_epoch, } } let executable_accounts = vec![(program_id, RefCell::new(ai_to_a(program_account_info)))]; let mut accounts = vec![]; for instruction_account in &instruction.accounts { for account_info in account_infos { if *account_info.unsigned_key() == instruction_account.pubkey { if instruction_account.is_writable && !account_info.is_writable { panic!("Writeable mismatch for {}", instruction_account.pubkey); } if instruction_account.is_signer && !account_info.is_signer { let mut program_signer = false; for seeds in signers_seeds.iter() { let signer = Pubkey::create_program_address(&seeds, &caller).unwrap(); if instruction_account.pubkey == signer { program_signer = true; break; } } if !program_signer { panic!("Signer mismatch for {}", instruction_account.pubkey); } } accounts.push(Rc::new(RefCell::new(ai_to_a(account_info)))); break; } } } assert_eq!(accounts.len(), instruction.accounts.len()); solana_runtime::message_processor::MessageProcessor::process_cross_program_instruction( &message, &executable_accounts, &accounts, &mut mock_invoke_context, ) .map_err(|err| ProgramError::try_from(err).unwrap_or_else(|err| panic!("{}", err)))?; // Propagate logs back to caller's invoke context // (TODO: This goes away if MockInvokeContext usage can be removed) INVOKE_CONTEXT.with(|invoke_context| { let logger = invoke_context.borrow().get_logger(); let logger = logger.borrow_mut(); for message in mock_invoke_context.logger.log.borrow_mut().iter() { if logger.log_enabled() { logger.log(message); } } }); // Copy writeable account modifications back into the caller's AccountInfos for (i, instruction_account) in instruction.accounts.iter().enumerate() { if !instruction_account.is_writable { continue; } for account_info in account_infos { if *account_info.unsigned_key() == instruction_account.pubkey { let account = &accounts[i]; **account_info.try_borrow_mut_lamports().unwrap() = account.borrow().lamports; let mut data = account_info.try_borrow_mut_data()?; let new_data = &account.borrow().data; if data.len() != new_data.len() { // TODO: Figure out how to change the callers account data size panic!( "Account resizing ({} -> {}) not supported yet", data.len(), new_data.len() ); } data.clone_from_slice(new_data); } } } Ok(()) } } fn find_file(filename: &str) -> Option<PathBuf> { for path in &["", "tests/fixtures"] { let candidate = Path::new(path).join(&filename); if candidate.exists() { return Some(candidate); } } None } fn read_file<P: AsRef<Path>>(path: P) -> Vec<u8> { let path = path.as_ref(); let mut file = File::open(path) .unwrap_or_else(|err| panic!("Failed to open \"{}\": {}", path.display(), err)); let mut file_data = Vec::new(); file.read_to_end(&mut file_data) .unwrap_or_else(|err| panic!("Failed to read \"{}\": {}", path.display(), err)); file_data } pub struct ProgramTest { accounts: Vec<(Pubkey, Account)>, builtins: Vec<Builtin>, bpf_compute_max_units: Option<u64>, prefer_bpf: bool, } impl Default for ProgramTest { /// Initialize a new ProgramTest /// /// The `bpf` environment variable controls how BPF programs are selected during operation: /// `export bpf=1` -- use BPF programs if present, otherwise fall back to the /// native instruction processors provided with the test /// `export bpf=0` -- use native instruction processor if present, otherwise fall back to /// the BPF program /// (default) /// and the `ProgramTest::prefer_bpf()` method may be used to override the selection at runtime /// /// BPF program shared objects and account data files are searched for in /// * the current working directory (the default output location for `cargo build-bpf), /// * the `tests/fixtures` sub-directory /// fn default() -> Self { solana_logger::setup_with_default( "solana_bpf_loader=debug,\ solana_rbpf::vm=debug,\ solana_runtime::message_processor=info,\ solana_runtime::system_instruction_processor=trace,\ solana_program_test=info", ); let prefer_bpf = match std::env::var("bpf") { Ok(val) => !matches!(val.as_str(), "0" | ""), Err(_err) => false, }; Self { accounts: vec![], builtins: vec![], bpf_compute_max_units: None, prefer_bpf, } } } // Values returned by `ProgramTest::start` pub struct StartOutputs { pub banks_client: BanksClient, pub payer: Keypair, pub recent_blockhash: Hash, pub rent: Rent, } impl ProgramTest { pub fn new( program_name: &str, program_id: Pubkey, process_instruction: Option<ProcessInstructionWithContext>, ) -> Self { let mut me = Self::default(); me.add_program(program_name, program_id, process_instruction); me } /// Override default BPF program selection pub fn prefer_bpf(&mut self, prefer_bpf: bool) { self.prefer_bpf = prefer_bpf; } /// Override the BPF compute budget pub fn set_bpf_compute_max_units(&mut self, bpf_compute_max_units: u64) { self.bpf_compute_max_units = Some(bpf_compute_max_units); } /// Add an account to the test environment pub fn add_account(&mut self, address: Pubkey, account: Account) { self.accounts.push((address, account)); } /// Add an account to the test environment with the account data in the provided `filename` pub fn add_account_with_file_data( &mut self, address: Pubkey, lamports: u64, owner: Pubkey, filename: &str, ) { self.add_account( address, Account { lamports, data: read_file(find_file(filename).unwrap_or_else(|| { panic!("Unable to locate {}", filename); })), owner, executable: false, rent_epoch: 0, }, ); } /// Add an account to the test environment with the account data in the provided as a base 64 /// string pub fn add_account_with_base64_data( &mut self, address: Pubkey, lamports: u64, owner: Pubkey, data_base64: &str, ) { self.add_account( address, Account { lamports, data: base64::decode(data_base64) .unwrap_or_else(|err| panic!("Failed to base64 decode: {}", err)), owner, executable: false, rent_epoch: 0, }, ); } /// Add a BPF program to the test environment. /// /// `program_name` will also used to locate the BPF shared object in the current or fixtures /// directory. /// /// If `process_instruction` is provided, the natively built-program may be used instead of the /// BPF shared object depending on the `bpf` environment variable. pub fn add_program( &mut self, program_name: &str, program_id: Pubkey, process_instruction: Option<ProcessInstructionWithContext>, ) { let loader = solana_program::bpf_loader::id(); let program_file = find_file(&format!("{}.so", program_name)); if process_instruction.is_none() && program_file.is_none() { panic!("Unable to add program {} ({})", program_name, program_id);
if (program_file.is_some() && self.prefer_bpf) || process_instruction.is_none() { let program_file = program_file.unwrap_or_else(|| { panic!( "Program file data not available for {} ({})", program_name, program_id ); }); let data = read_file(&program_file); info!( "\"{}\" BPF program from {}{}", program_name, program_file.display(), std::fs::metadata(&program_file) .map(|metadata| { metadata .modified() .map(|time| { format!( ", modified {}", HumanTime::from(time) .to_text_en(Accuracy::Precise, Tense::Past) ) }) .ok() }) .ok() .flatten() .unwrap_or_else(|| "".to_string()) ); self.add_account( program_id, Account { lamports: Rent::default().minimum_balance(data.len()).min(1), data, owner: loader, executable: true, rent_epoch: 0, }, ); } else { info!("\"{}\" program loaded as native code", program_name); self.builtins.push(Builtin::new( program_name, program_id, process_instruction.unwrap_or_else(|| { panic!( "Program processor not available for {} ({})", program_name, program_id ); }), )); } } /// Start the test client /// /// Returns a `BanksClient` interface into the test environment as well as a payer `Keypair` /// with SOL for sending transactions pub async fn start(self) -> StartOutputs { { use std::sync::Once; static ONCE: Once = Once::new(); ONCE.call_once(|| { program_stubs::set_syscall_stubs(Box::new(SyscallStubs {})); }); } let bootstrap_validator_pubkey = Pubkey::new_unique(); let bootstrap_validator_stake_lamports = 42; let gci = create_genesis_config_with_leader( sol_to_lamports(1_000_000.0), &bootstrap_validator_pubkey, bootstrap_validator_stake_lamports, ); let mut genesis_config = gci.genesis_config; let rent = Rent::default(); genesis_config.rent = rent; genesis_config.fee_rate_governor = solana_program::fee_calculator::FeeRateGovernor::default(); let payer = gci.mint_keypair; debug!("Payer address: {}", payer.pubkey()); debug!("Genesis config: {}", genesis_config); let mut bank = Bank::new(&genesis_config); for loader in &[ solana_bpf_loader_deprecated_program!(), solana_bpf_loader_program!(), ] { bank.add_builtin(&loader.0, loader.1, loader.2); } // User-supplied additional builtins for builtin in self.builtins { bank.add_builtin( &builtin.name, builtin.id, builtin.process_instruction_with_context, ); } for (address, account) in self.accounts { if bank.get_account(&address).is_some() { panic!("An account at {} already exists", address); } bank.store_account(&address, &account); } bank.set_capitalization(); if let Some(max_units) = self.bpf_compute_max_units { bank.set_bpf_compute_budget(Some(BpfComputeBudget { max_units, ..BpfComputeBudget::default() })); } // Advance beyond slot 0 for a slightly more realistic test environment let bank = Arc::new(bank); let bank = Bank::new_from_parent(&bank, bank.collector_id(), bank.slot() + 1); debug!("Bank slot: {}", bank.slot()); let bank_forks = Arc::new(RwLock::new(BankForks::new(bank))); let transport = start_local_server(&bank_forks).await; let mut banks_client = start_client(transport) .await .unwrap_or_else(|err| panic!("Failed to start banks client: {}", err)); let recent_blockhash = banks_client.get_recent_blockhash().await.unwrap(); StartOutputs { banks_client, payer, recent_blockhash, rent, } } }
}
random_line_split
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /// Convert linear energy to logarithmic loudness. pub fn energy_to_loudness(energy: f64) -> f64 { // The non-test version is faster and more accurate but gives // slightly different results than the C version and fails the // tests because of that. #[cfg(test)] { 10.0 * (f64::ln(energy) / f64::ln(10.0)) - 0.691 } #[cfg(not(test))] { 10.0 * f64::log10(energy) - 0.691 } } /// Trait for abstracting over interleaved and planar samples. pub trait Samples<'a, T: 'a>: Sized { /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample(&self, channel: usize, func: impl FnMut(&'a T)); /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, func: impl FnMut(&'a T, U), ); /// Number of frames. fn frames(&self) -> usize; /// Number of channels. fn channels(&self) -> usize; /// Split into two at the given sample. fn split_at(self, sample: usize) -> (Self, Self); } /// Struct representing interleaved samples. pub struct Interleaved<'a, T> { /// Interleaved sample data. data: &'a [T], /// Number of channels. channels: usize, } impl<'a, T> Interleaved<'a, T> { /// Create a new wrapper around the interleaved channels and do a sanity check. pub fn new(data: &'a [T], channels: usize) -> Result<Self, crate::Error> { if channels == 0 { return Err(crate::Error::NoMem); } if data.len() % channels != 0 { return Err(crate::Error::NoMem); } Ok(Interleaved { data, channels }) } } impl<'a, T> Samples<'a, T> for Interleaved<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.channels); for v in self.data.chunks_exact(self.channels) { func(&v[channel]) } } #[inline] fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a T, U), ) { assert!(channel < self.channels); for (v, u) in self.data.chunks_exact(self.channels).zip(iter) { func(&v[channel], u) } } #[inline] fn frames(&self) -> usize { self.data.len() / self.channels } #[inline] fn channels(&self) -> usize { self.channels } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(sample * self.channels <= self.data.len()); let (fst, snd) = self.data.split_at(sample * self.channels); ( Interleaved { data: fst, channels: self.channels, }, Interleaved { data: snd, channels: self.channels, }, ) } } /// Struct representing interleaved samples. pub struct Planar<'a, T> { data: &'a [&'a [T]], start: usize, end: usize, } impl<'a, T> Planar<'a, T> { /// Create a new wrapper around the planar channels and do a sanity check. pub fn new(data: &'a [&'a [T]]) -> Result<Self, crate::Error> { if data.is_empty() { return Err(crate::Error::NoMem); } if data.iter().any(|d| data[0].len() != d.len()) { return Err(crate::Error::NoMem); } Ok(Planar { data, start: 0, end: data[0].len(), }) } } impl<'a, T> Samples<'a, T> for Planar<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.data.len()); for v in &self.data[channel][self.start..self.end] { func(v) } } #[inline] fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a T, U), ) { assert!(channel < self.data.len()); for (v, u) in self.data[channel][self.start..self.end].iter().zip(iter) { func(v, u) } } #[inline] fn frames(&self) -> usize { self.end - self.start } #[inline]
self.data.len() } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(self.start + sample <= self.end); ( Planar { data: self.data, start: self.start, end: self.start + sample, }, Planar { data: self.data, start: self.start + sample, end: self.end, }, ) } } /// Trait for converting samples into f32 in the range [0,1]. pub trait AsF32: Copy { fn as_f32_scaled(self) -> f32; } impl AsF32 for i16 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 / (-(std::i16::MIN as f32)) } } impl AsF32 for i32 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 / (-(std::i32::MIN as f32)) } } impl AsF32 for f32 { #[inline] fn as_f32_scaled(self) -> f32 { self } } impl AsF32 for f64 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 } } /// Trait for converting samples into f64 in the range [0,1]. pub trait AsF64: AsF32 + Copy + PartialOrd { const MAX: f64; fn as_f64(self) -> f64; #[inline] fn as_f64_scaled(self) -> f64 { self.as_f64() / Self::MAX } } impl AsF64 for i16 { const MAX: f64 = -(std::i16::MIN as f64); #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for i32 { const MAX: f64 = -(std::i32::MIN as f64); #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for f32 { const MAX: f64 = 1.0; #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for f64 { const MAX: f64 = 1.0; #[inline] fn as_f64(self) -> f64 { self } } #[cfg(test)] pub mod tests { #[derive(Clone, Debug)] pub struct Signal<T: FromF32> { pub data: Vec<T>, pub channels: u32, pub rate: u32, } pub trait FromF32: Copy + Clone + std::fmt::Debug + Send + Sync + 'static { fn from_f32(val: f32) -> Self; } impl FromF32 for i16 { fn from_f32(val: f32) -> Self { (val * (std::i16::MAX - 1) as f32) as i16 } } impl FromF32 for i32 { fn from_f32(val: f32) -> Self { (val * (std::i32::MAX - 1) as f32) as i32 } } impl FromF32 for f32 { fn from_f32(val: f32) -> Self { val } } impl FromF32 for f64 { fn from_f32(val: f32) -> Self { val as f64 } } impl<T: FromF32 + quickcheck::Arbitrary> quickcheck::Arbitrary for Signal<T> { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self { use rand::Rng; let channels = g.gen_range(1, 16); let rate = g.gen_range(16_000, 224_000); let num_frames = (rate as f64 * g.gen_range(0.0, 5.0)) as usize; let max = g.gen_range(0.0, 1.0); let freqs = [ g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), ]; let volumes = [ g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), ]; let volume_scale = 1.0 / volumes.iter().sum::<f32>(); let mut accumulators = [0.0; 4]; let steps = [ 2.0 * std::f32::consts::PI * freqs[0] / rate as f32, 2.0 * std::f32::consts::PI * freqs[1] / rate as f32, 2.0 * std::f32::consts::PI * freqs[2] / rate as f32, 2.0 * std::f32::consts::PI * freqs[3] / rate as f32, ]; let mut data = vec![T::from_f32(0.0); num_frames * channels as usize]; for frame in data.chunks_exact_mut(channels as usize) { let val = max * (f32::sin(accumulators[0]) * volumes[0] + f32::sin(accumulators[1]) * volumes[1] + f32::sin(accumulators[2]) * volumes[2] + f32::sin(accumulators[3]) * volumes[3]) / volume_scale; for sample in frame.iter_mut() { *sample = T::from_f32(val); } for (acc, step) in accumulators.iter_mut().zip(steps.iter()) { *acc += step; } } Signal { data, channels, rate, } } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { SignalShrinker::boxed(self.clone()) } } struct SignalShrinker<A: FromF32> { seed: Signal<A>, /// How many elements to take size: usize, /// Whether we tried with one channel already tried_one_channel: bool, } impl<A: FromF32 + quickcheck::Arbitrary> SignalShrinker<A> { fn boxed(seed: Signal<A>) -> Box<dyn Iterator<Item = Signal<A>>> { let channels = seed.channels; Box::new(SignalShrinker { seed, size: 0, tried_one_channel: channels == 1, }) } } impl<A> Iterator for SignalShrinker<A> where A: FromF32 + quickcheck::Arbitrary, { type Item = Signal<A>; fn next(&mut self) -> Option<Signal<A>> { if self.size < self.seed.data.len() { // Generate a smaller vector by removing size elements let xs1 = if self.tried_one_channel { Vec::from(&self.seed.data[..self.size]) } else { self.seed .data .iter() .cloned() .step_by(self.seed.channels as usize) .take(self.size) .collect() }; if self.size == 0 { self.size = if self.tried_one_channel { self.seed.channels as usize } else { 1 }; } else { self.size *= 2; } Some(Signal { data: xs1, channels: if self.tried_one_channel { self.seed.channels } else { 1 }, rate: self.seed.rate, }) } else if !self.tried_one_channel { self.tried_one_channel = true; self.size = 0; self.next() } else { None } } } }
fn channels(&self) -> usize {
random_line_split
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /// Convert linear energy to logarithmic loudness. pub fn energy_to_loudness(energy: f64) -> f64 { // The non-test version is faster and more accurate but gives // slightly different results than the C version and fails the // tests because of that. #[cfg(test)] { 10.0 * (f64::ln(energy) / f64::ln(10.0)) - 0.691 } #[cfg(not(test))] { 10.0 * f64::log10(energy) - 0.691 } } /// Trait for abstracting over interleaved and planar samples. pub trait Samples<'a, T: 'a>: Sized { /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample(&self, channel: usize, func: impl FnMut(&'a T)); /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, func: impl FnMut(&'a T, U), ); /// Number of frames. fn frames(&self) -> usize; /// Number of channels. fn channels(&self) -> usize; /// Split into two at the given sample. fn split_at(self, sample: usize) -> (Self, Self); } /// Struct representing interleaved samples. pub struct Interleaved<'a, T> { /// Interleaved sample data. data: &'a [T], /// Number of channels. channels: usize, } impl<'a, T> Interleaved<'a, T> { /// Create a new wrapper around the interleaved channels and do a sanity check. pub fn new(data: &'a [T], channels: usize) -> Result<Self, crate::Error> { if channels == 0 { return Err(crate::Error::NoMem); } if data.len() % channels != 0 { return Err(crate::Error::NoMem); } Ok(Interleaved { data, channels }) } } impl<'a, T> Samples<'a, T> for Interleaved<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.channels); for v in self.data.chunks_exact(self.channels) { func(&v[channel]) } } #[inline] fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a T, U), ) { assert!(channel < self.channels); for (v, u) in self.data.chunks_exact(self.channels).zip(iter) { func(&v[channel], u) } } #[inline] fn frames(&self) -> usize { self.data.len() / self.channels } #[inline] fn channels(&self) -> usize { self.channels } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(sample * self.channels <= self.data.len()); let (fst, snd) = self.data.split_at(sample * self.channels); ( Interleaved { data: fst, channels: self.channels, }, Interleaved { data: snd, channels: self.channels, }, ) } } /// Struct representing interleaved samples. pub struct Planar<'a, T> { data: &'a [&'a [T]], start: usize, end: usize, } impl<'a, T> Planar<'a, T> { /// Create a new wrapper around the planar channels and do a sanity check. pub fn new(data: &'a [&'a [T]]) -> Result<Self, crate::Error> { if data.is_empty() { return Err(crate::Error::NoMem); } if data.iter().any(|d| data[0].len() != d.len()) { return Err(crate::Error::NoMem); } Ok(Planar { data, start: 0, end: data[0].len(), }) } } impl<'a, T> Samples<'a, T> for Planar<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.data.len()); for v in &self.data[channel][self.start..self.end] { func(v) } } #[inline] fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a T, U), ) { assert!(channel < self.data.len()); for (v, u) in self.data[channel][self.start..self.end].iter().zip(iter) { func(v, u) } } #[inline] fn frames(&self) -> usize { self.end - self.start } #[inline] fn channels(&self) -> usize { self.data.len() } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(self.start + sample <= self.end); ( Planar { data: self.data, start: self.start, end: self.start + sample, }, Planar { data: self.data, start: self.start + sample, end: self.end, }, ) } } /// Trait for converting samples into f32 in the range [0,1]. pub trait AsF32: Copy { fn as_f32_scaled(self) -> f32; } impl AsF32 for i16 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 / (-(std::i16::MIN as f32)) } } impl AsF32 for i32 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 / (-(std::i32::MIN as f32)) } } impl AsF32 for f32 { #[inline] fn as_f32_scaled(self) -> f32 { self } } impl AsF32 for f64 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 } } /// Trait for converting samples into f64 in the range [0,1]. pub trait AsF64: AsF32 + Copy + PartialOrd { const MAX: f64; fn as_f64(self) -> f64; #[inline] fn as_f64_scaled(self) -> f64 { self.as_f64() / Self::MAX } } impl AsF64 for i16 { const MAX: f64 = -(std::i16::MIN as f64); #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for i32 { const MAX: f64 = -(std::i32::MIN as f64); #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for f32 { const MAX: f64 = 1.0; #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for f64 { const MAX: f64 = 1.0; #[inline] fn as_f64(self) -> f64 { self } } #[cfg(test)] pub mod tests { #[derive(Clone, Debug)] pub struct Signal<T: FromF32> { pub data: Vec<T>, pub channels: u32, pub rate: u32, } pub trait FromF32: Copy + Clone + std::fmt::Debug + Send + Sync + 'static { fn from_f32(val: f32) -> Self; } impl FromF32 for i16 { fn from_f32(val: f32) -> Self { (val * (std::i16::MAX - 1) as f32) as i16 } } impl FromF32 for i32 { fn from_f32(val: f32) -> Self { (val * (std::i32::MAX - 1) as f32) as i32 } } impl FromF32 for f32 { fn from_f32(val: f32) -> Self { val } } impl FromF32 for f64 { fn from_f32(val: f32) -> Self { val as f64 } } impl<T: FromF32 + quickcheck::Arbitrary> quickcheck::Arbitrary for Signal<T> { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self { use rand::Rng; let channels = g.gen_range(1, 16); let rate = g.gen_range(16_000, 224_000); let num_frames = (rate as f64 * g.gen_range(0.0, 5.0)) as usize; let max = g.gen_range(0.0, 1.0); let freqs = [ g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), ]; let volumes = [ g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), ]; let volume_scale = 1.0 / volumes.iter().sum::<f32>(); let mut accumulators = [0.0; 4]; let steps = [ 2.0 * std::f32::consts::PI * freqs[0] / rate as f32, 2.0 * std::f32::consts::PI * freqs[1] / rate as f32, 2.0 * std::f32::consts::PI * freqs[2] / rate as f32, 2.0 * std::f32::consts::PI * freqs[3] / rate as f32, ]; let mut data = vec![T::from_f32(0.0); num_frames * channels as usize]; for frame in data.chunks_exact_mut(channels as usize) { let val = max * (f32::sin(accumulators[0]) * volumes[0] + f32::sin(accumulators[1]) * volumes[1] + f32::sin(accumulators[2]) * volumes[2] + f32::sin(accumulators[3]) * volumes[3]) / volume_scale; for sample in frame.iter_mut() { *sample = T::from_f32(val); } for (acc, step) in accumulators.iter_mut().zip(steps.iter()) { *acc += step; } } Signal { data, channels, rate, } } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { SignalShrinker::boxed(self.clone()) } } struct SignalShrinker<A: FromF32> { seed: Signal<A>, /// How many elements to take size: usize, /// Whether we tried with one channel already tried_one_channel: bool, } impl<A: FromF32 + quickcheck::Arbitrary> SignalShrinker<A> { fn boxed(seed: Signal<A>) -> Box<dyn Iterator<Item = Signal<A>>> { let channels = seed.channels; Box::new(SignalShrinker { seed, size: 0, tried_one_channel: channels == 1, }) } } impl<A> Iterator for SignalShrinker<A> where A: FromF32 + quickcheck::Arbitrary, { type Item = Signal<A>; fn ne
mut self) -> Option<Signal<A>> { if self.size < self.seed.data.len() { // Generate a smaller vector by removing size elements let xs1 = if self.tried_one_channel { Vec::from(&self.seed.data[..self.size]) } else { self.seed .data .iter() .cloned() .step_by(self.seed.channels as usize) .take(self.size) .collect() }; if self.size == 0 { self.size = if self.tried_one_channel { self.seed.channels as usize } else { 1 }; } else { self.size *= 2; } Some(Signal { data: xs1, channels: if self.tried_one_channel { self.seed.channels } else { 1 }, rate: self.seed.rate, }) } else if !self.tried_one_channel { self.tried_one_channel = true; self.size = 0; self.next() } else { None } } } }
xt(&
identifier_name
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /// Convert linear energy to logarithmic loudness. pub fn energy_to_loudness(energy: f64) -> f64 { // The non-test version is faster and more accurate but gives // slightly different results than the C version and fails the // tests because of that. #[cfg(test)] { 10.0 * (f64::ln(energy) / f64::ln(10.0)) - 0.691 } #[cfg(not(test))] { 10.0 * f64::log10(energy) - 0.691 } } /// Trait for abstracting over interleaved and planar samples. pub trait Samples<'a, T: 'a>: Sized { /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample(&self, channel: usize, func: impl FnMut(&'a T)); /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, func: impl FnMut(&'a T, U), ); /// Number of frames. fn frames(&self) -> usize; /// Number of channels. fn channels(&self) -> usize; /// Split into two at the given sample. fn split_at(self, sample: usize) -> (Self, Self); } /// Struct representing interleaved samples. pub struct Interleaved<'a, T> { /// Interleaved sample data. data: &'a [T], /// Number of channels. channels: usize, } impl<'a, T> Interleaved<'a, T> { /// Create a new wrapper around the interleaved channels and do a sanity check. pub fn new(data: &'a [T], channels: usize) -> Result<Self, crate::Error> { if channels == 0 { return Err(crate::Error::NoMem); } if data.len() % channels != 0 { return Err(crate::Error::NoMem); } Ok(Interleaved { data, channels }) } } impl<'a, T> Samples<'a, T> for Interleaved<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.channels); for v in self.data.chunks_exact(self.channels) { func(&v[channel]) } } #[inline] fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a T, U), ) { assert!(channel < self.channels); for (v, u) in self.data.chunks_exact(self.channels).zip(iter) { func(&v[channel], u) } } #[inline] fn frames(&self) -> usize { self.data.len() / self.channels } #[inline] fn channels(&self) -> usize { self.channels } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(sample * self.channels <= self.data.len()); let (fst, snd) = self.data.split_at(sample * self.channels); ( Interleaved { data: fst, channels: self.channels, }, Interleaved { data: snd, channels: self.channels, }, ) } } /// Struct representing interleaved samples. pub struct Planar<'a, T> { data: &'a [&'a [T]], start: usize, end: usize, } impl<'a, T> Planar<'a, T> { /// Create a new wrapper around the planar channels and do a sanity check. pub fn new(data: &'a [&'a [T]]) -> Result<Self, crate::Error> { if data.is_empty() { return Err(crate::Error::NoMem); } if data.iter().any(|d| data[0].len() != d.len()) { return Err(crate::Error::NoMem); } Ok(Planar { data, start: 0, end: data[0].len(), }) } } impl<'a, T> Samples<'a, T> for Planar<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.data.len()); for v in &self.data[channel][self.start..self.end] { func(v) } } #[inline] fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a T, U), ) { assert!(channel < self.data.len()); for (v, u) in self.data[channel][self.start..self.end].iter().zip(iter) { func(v, u) } } #[inline] fn frames(&self) -> usize { self.end - self.start } #[inline] fn channels(&self) -> usize { self.data.len() } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(self.start + sample <= self.end); ( Planar { data: self.data, start: self.start, end: self.start + sample, }, Planar { data: self.data, start: self.start + sample, end: self.end, }, ) } } /// Trait for converting samples into f32 in the range [0,1]. pub trait AsF32: Copy { fn as_f32_scaled(self) -> f32; } impl AsF32 for i16 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 / (-(std::i16::MIN as f32)) } } impl AsF32 for i32 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 / (-(std::i32::MIN as f32)) } } impl AsF32 for f32 { #[inline] fn as_f32_scaled(self) -> f32 {
impl AsF32 for f64 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 } } /// Trait for converting samples into f64 in the range [0,1]. pub trait AsF64: AsF32 + Copy + PartialOrd { const MAX: f64; fn as_f64(self) -> f64; #[inline] fn as_f64_scaled(self) -> f64 { self.as_f64() / Self::MAX } } impl AsF64 for i16 { const MAX: f64 = -(std::i16::MIN as f64); #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for i32 { const MAX: f64 = -(std::i32::MIN as f64); #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for f32 { const MAX: f64 = 1.0; #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for f64 { const MAX: f64 = 1.0; #[inline] fn as_f64(self) -> f64 { self } } #[cfg(test)] pub mod tests { #[derive(Clone, Debug)] pub struct Signal<T: FromF32> { pub data: Vec<T>, pub channels: u32, pub rate: u32, } pub trait FromF32: Copy + Clone + std::fmt::Debug + Send + Sync + 'static { fn from_f32(val: f32) -> Self; } impl FromF32 for i16 { fn from_f32(val: f32) -> Self { (val * (std::i16::MAX - 1) as f32) as i16 } } impl FromF32 for i32 { fn from_f32(val: f32) -> Self { (val * (std::i32::MAX - 1) as f32) as i32 } } impl FromF32 for f32 { fn from_f32(val: f32) -> Self { val } } impl FromF32 for f64 { fn from_f32(val: f32) -> Self { val as f64 } } impl<T: FromF32 + quickcheck::Arbitrary> quickcheck::Arbitrary for Signal<T> { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self { use rand::Rng; let channels = g.gen_range(1, 16); let rate = g.gen_range(16_000, 224_000); let num_frames = (rate as f64 * g.gen_range(0.0, 5.0)) as usize; let max = g.gen_range(0.0, 1.0); let freqs = [ g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), ]; let volumes = [ g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), ]; let volume_scale = 1.0 / volumes.iter().sum::<f32>(); let mut accumulators = [0.0; 4]; let steps = [ 2.0 * std::f32::consts::PI * freqs[0] / rate as f32, 2.0 * std::f32::consts::PI * freqs[1] / rate as f32, 2.0 * std::f32::consts::PI * freqs[2] / rate as f32, 2.0 * std::f32::consts::PI * freqs[3] / rate as f32, ]; let mut data = vec![T::from_f32(0.0); num_frames * channels as usize]; for frame in data.chunks_exact_mut(channels as usize) { let val = max * (f32::sin(accumulators[0]) * volumes[0] + f32::sin(accumulators[1]) * volumes[1] + f32::sin(accumulators[2]) * volumes[2] + f32::sin(accumulators[3]) * volumes[3]) / volume_scale; for sample in frame.iter_mut() { *sample = T::from_f32(val); } for (acc, step) in accumulators.iter_mut().zip(steps.iter()) { *acc += step; } } Signal { data, channels, rate, } } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { SignalShrinker::boxed(self.clone()) } } struct SignalShrinker<A: FromF32> { seed: Signal<A>, /// How many elements to take size: usize, /// Whether we tried with one channel already tried_one_channel: bool, } impl<A: FromF32 + quickcheck::Arbitrary> SignalShrinker<A> { fn boxed(seed: Signal<A>) -> Box<dyn Iterator<Item = Signal<A>>> { let channels = seed.channels; Box::new(SignalShrinker { seed, size: 0, tried_one_channel: channels == 1, }) } } impl<A> Iterator for SignalShrinker<A> where A: FromF32 + quickcheck::Arbitrary, { type Item = Signal<A>; fn next(&mut self) -> Option<Signal<A>> { if self.size < self.seed.data.len() { // Generate a smaller vector by removing size elements let xs1 = if self.tried_one_channel { Vec::from(&self.seed.data[..self.size]) } else { self.seed .data .iter() .cloned() .step_by(self.seed.channels as usize) .take(self.size) .collect() }; if self.size == 0 { self.size = if self.tried_one_channel { self.seed.channels as usize } else { 1 }; } else { self.size *= 2; } Some(Signal { data: xs1, channels: if self.tried_one_channel { self.seed.channels } else { 1 }, rate: self.seed.rate, }) } else if !self.tried_one_channel { self.tried_one_channel = true; self.size = 0; self.next() } else { None } } } }
self } }
identifier_body
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /// Convert linear energy to logarithmic loudness. pub fn energy_to_loudness(energy: f64) -> f64 { // The non-test version is faster and more accurate but gives // slightly different results than the C version and fails the // tests because of that. #[cfg(test)] { 10.0 * (f64::ln(energy) / f64::ln(10.0)) - 0.691 } #[cfg(not(test))] { 10.0 * f64::log10(energy) - 0.691 } } /// Trait for abstracting over interleaved and planar samples. pub trait Samples<'a, T: 'a>: Sized { /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample(&self, channel: usize, func: impl FnMut(&'a T)); /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, func: impl FnMut(&'a T, U), ); /// Number of frames. fn frames(&self) -> usize; /// Number of channels. fn channels(&self) -> usize; /// Split into two at the given sample. fn split_at(self, sample: usize) -> (Self, Self); } /// Struct representing interleaved samples. pub struct Interleaved<'a, T> { /// Interleaved sample data. data: &'a [T], /// Number of channels. channels: usize, } impl<'a, T> Interleaved<'a, T> { /// Create a new wrapper around the interleaved channels and do a sanity check. pub fn new(data: &'a [T], channels: usize) -> Result<Self, crate::Error> { if channels == 0 { return Err(crate::Error::NoMem); } if data.len() % channels != 0 { return Err(crate::Error::NoMem); } Ok(Interleaved { data, channels }) } } impl<'a, T> Samples<'a, T> for Interleaved<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.channels); for v in self.data.chunks_exact(self.channels) { func(&v[channel]) } } #[inline] fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a T, U), ) { assert!(channel < self.channels); for (v, u) in self.data.chunks_exact(self.channels).zip(iter) { func(&v[channel], u) } } #[inline] fn frames(&self) -> usize { self.data.len() / self.channels } #[inline] fn channels(&self) -> usize { self.channels } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(sample * self.channels <= self.data.len()); let (fst, snd) = self.data.split_at(sample * self.channels); ( Interleaved { data: fst, channels: self.channels, }, Interleaved { data: snd, channels: self.channels, }, ) } } /// Struct representing interleaved samples. pub struct Planar<'a, T> { data: &'a [&'a [T]], start: usize, end: usize, } impl<'a, T> Planar<'a, T> { /// Create a new wrapper around the planar channels and do a sanity check. pub fn new(data: &'a [&'a [T]]) -> Result<Self, crate::Error> { if data.is_empty() { return Err(crate::Error::NoMem); } if data.iter().any(|d| data[0].len() != d.len()) { return Err(crate::Error::NoMem); } Ok(Planar { data, start: 0, end: data[0].len(), }) } } impl<'a, T> Samples<'a, T> for Planar<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.data.len()); for v in &self.data[channel][self.start..self.end] { func(v) } } #[inline] fn foreach_sample_zipped<U>( &self, channel: usize, iter: impl Iterator<Item = U>, mut func: impl FnMut(&'a T, U), ) { assert!(channel < self.data.len()); for (v, u) in self.data[channel][self.start..self.end].iter().zip(iter) { func(v, u) } } #[inline] fn frames(&self) -> usize { self.end - self.start } #[inline] fn channels(&self) -> usize { self.data.len() } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(self.start + sample <= self.end); ( Planar { data: self.data, start: self.start, end: self.start + sample, }, Planar { data: self.data, start: self.start + sample, end: self.end, }, ) } } /// Trait for converting samples into f32 in the range [0,1]. pub trait AsF32: Copy { fn as_f32_scaled(self) -> f32; } impl AsF32 for i16 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 / (-(std::i16::MIN as f32)) } } impl AsF32 for i32 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 / (-(std::i32::MIN as f32)) } } impl AsF32 for f32 { #[inline] fn as_f32_scaled(self) -> f32 { self } } impl AsF32 for f64 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 } } /// Trait for converting samples into f64 in the range [0,1]. pub trait AsF64: AsF32 + Copy + PartialOrd { const MAX: f64; fn as_f64(self) -> f64; #[inline] fn as_f64_scaled(self) -> f64 { self.as_f64() / Self::MAX } } impl AsF64 for i16 { const MAX: f64 = -(std::i16::MIN as f64); #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for i32 { const MAX: f64 = -(std::i32::MIN as f64); #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for f32 { const MAX: f64 = 1.0; #[inline] fn as_f64(self) -> f64 { self as f64 } } impl AsF64 for f64 { const MAX: f64 = 1.0; #[inline] fn as_f64(self) -> f64 { self } } #[cfg(test)] pub mod tests { #[derive(Clone, Debug)] pub struct Signal<T: FromF32> { pub data: Vec<T>, pub channels: u32, pub rate: u32, } pub trait FromF32: Copy + Clone + std::fmt::Debug + Send + Sync + 'static { fn from_f32(val: f32) -> Self; } impl FromF32 for i16 { fn from_f32(val: f32) -> Self { (val * (std::i16::MAX - 1) as f32) as i16 } } impl FromF32 for i32 { fn from_f32(val: f32) -> Self { (val * (std::i32::MAX - 1) as f32) as i32 } } impl FromF32 for f32 { fn from_f32(val: f32) -> Self { val } } impl FromF32 for f64 { fn from_f32(val: f32) -> Self { val as f64 } } impl<T: FromF32 + quickcheck::Arbitrary> quickcheck::Arbitrary for Signal<T> { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self { use rand::Rng; let channels = g.gen_range(1, 16); let rate = g.gen_range(16_000, 224_000); let num_frames = (rate as f64 * g.gen_range(0.0, 5.0)) as usize; let max = g.gen_range(0.0, 1.0); let freqs = [ g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), g.gen_range(20.0, 16_000.0), ]; let volumes = [ g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), g.gen_range(0.0, 1.0), ]; let volume_scale = 1.0 / volumes.iter().sum::<f32>(); let mut accumulators = [0.0; 4]; let steps = [ 2.0 * std::f32::consts::PI * freqs[0] / rate as f32, 2.0 * std::f32::consts::PI * freqs[1] / rate as f32, 2.0 * std::f32::consts::PI * freqs[2] / rate as f32, 2.0 * std::f32::consts::PI * freqs[3] / rate as f32, ]; let mut data = vec![T::from_f32(0.0); num_frames * channels as usize]; for frame in data.chunks_exact_mut(channels as usize) { let val = max * (f32::sin(accumulators[0]) * volumes[0] + f32::sin(accumulators[1]) * volumes[1] + f32::sin(accumulators[2]) * volumes[2] + f32::sin(accumulators[3]) * volumes[3]) / volume_scale; for sample in frame.iter_mut() { *sample = T::from_f32(val); } for (acc, step) in accumulators.iter_mut().zip(steps.iter()) { *acc += step; } } Signal { data, channels, rate, } } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { SignalShrinker::boxed(self.clone()) } } struct SignalShrinker<A: FromF32> { seed: Signal<A>, /// How many elements to take size: usize, /// Whether we tried with one channel already tried_one_channel: bool, } impl<A: FromF32 + quickcheck::Arbitrary> SignalShrinker<A> { fn boxed(seed: Signal<A>) -> Box<dyn Iterator<Item = Signal<A>>> { let channels = seed.channels; Box::new(SignalShrinker { seed, size: 0, tried_one_channel: channels == 1, }) } } impl<A> Iterator for SignalShrinker<A> where A: FromF32 + quickcheck::Arbitrary, { type Item = Signal<A>; fn next(&mut self) -> Option<Signal<A>> { if self.size < self.seed.data.len() { // Generate a smaller vector by removing size elements let xs1 = if self.tried_one_channel { Vec::from(&self.seed.data[..self.size]) } else { self.seed .data .iter() .cloned() .step_by(self.seed.channels as usize) .take(self.size) .collect() }; if self.size == 0 { self.size = if self.tried_one_channel {
lse { 1 }; } else { self.size *= 2; } Some(Signal { data: xs1, channels: if self.tried_one_channel { self.seed.channels } else { 1 }, rate: self.seed.rate, }) } else if !self.tried_one_channel { self.tried_one_channel = true; self.size = 0; self.next() } else { None } } } }
self.seed.channels as usize } e
conditional_block
libstore-impl.go
package libstore import ( "P2-f12/official/cacherpc" "P2-f12/official/lsplog" "P2-f12/official/storageproto" "fmt" "net/rpc" "os" "sort" "strings" "time" ) const ( GETRPCCLI = iota WANTLEASE CACHEGET CACHEPUT CACHEDEL RETRY_INTERVAL = time.Second RETRY_LIMIT = 5 QUERY_CACHE_INTERVAL = storageproto.QUERY_CACHE_SECONDS * time.Second QUERY_CACHE_THRESH = storageproto.QUERY_CACHE_THRESH ) // Structure for synchronous operation type syncop struct { op int key string value interface{} } // Pair of RPC client and error for channel usage type rpccli struct { cli *rpc.Client err error } // Pair of map results for channel usage type cachevalue struct { value interface{} found bool } type Libstore struct { // Data storage objects nodelist NodeList // list of associated servers rpcclis map[string]*rpc.Client // maps a hostport to an RPC client object cache map[string]interface{} // maps a key to a cached value getrequests map[string][]time.Time // maps a key to a list of times it has been Get requested // Basic parameters flags int myhostport string // Synchronization channels syncopchan chan *syncop clireplychan chan *rpccli cachereplychan chan *cachevalue successreplychan chan bool } func iNewLibstore(server string, myhostport string, flags int) (*Libstore, error) { ls := &Libstore{} ls.flags = flags ls.myhostport = myhostport ls.rpcclis = make(map[string]*rpc.Client) ls.cache = make(map[string]interface{}) ls.getrequests = make(map[string][]time.Time) ls.syncopchan = make(chan *syncop) ls.clireplychan = make(chan *rpccli) ls.cachereplychan = make(chan *cachevalue) ls.successreplychan = make(chan bool) // Create RPC connection to storage server cli, err := rpc.DialHTTP("tcp", server) if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", server) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[server] = cli // Get list of storage servers from master storage server // Retry on an interval if necessary args := storageproto.GetServersArgs{} var reply storageproto.RegisterReply ticker := time.NewTicker(RETRY_INTERVAL) for retryCount := 0; retryCount < RETRY_LIMIT; retryCount++ { err = cli.Call("StorageRPC.GetServers", args, &reply) if err != nil { return nil, err } if reply.Ready && reply.Servers != nil { ls.nodelist = reply.Servers // Sort the nodes by NodeID in ascending order sort.Sort(ls.nodelist) // Start the synchronized operation handler go ls.handleSyncOps() // Register RevokeLease method with RPC crpc := cacherpc.NewCacheRPC(ls) rpc.Register(crpc) return ls, nil } <-ticker.C } return nil, lsplog.MakeErr("Storage system not ready") } // Handler for all synchronous operations func (ls *Libstore) handleSyncOps() { for { syncop := <-ls.syncopchan switch syncop.op { case GETRPCCLI: cli, err := ls.getRPCClient(syncop.key) ls.clireplychan <- &rpccli{cli, err} case WANTLEASE: wantlease := ls.wantLease(syncop.key) ls.successreplychan <- wantlease case CACHEGET: value, found := ls.cache[syncop.key] ls.cachereplychan <- &cachevalue{value, found} case CACHEPUT: ls.cache[syncop.key] = syncop.value ls.successreplychan <- true case CACHEDEL: delete(ls.cache, syncop.key) ls.successreplychan <- true } } } // Retrieves RPC client for hostport either from cache or by connecting // Must be called synchronously func (ls *Libstore) getRPCClient(hostport string) (*rpc.Client, error) { cli, found := ls.rpcclis[hostport] // If server has not been connected to before, do so and cache the connection if !found {
if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", hostport) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[hostport] = cli } return cli, nil } // Return RPC client of server corresponding to the key func (ls *Libstore) getServer(key string) (*rpc.Client, error) { // Use beginning of key to group related keys together precolon := strings.Split(key, ":")[0] keyid := Storehash(precolon) // Locate server node by consistent hashing scheme var rpccli *rpccli for i, node := range ls.nodelist { if node.NodeID >= keyid { ls.syncopchan <- &syncop{GETRPCCLI, node.HostPort, nil} rpccli = <-ls.clireplychan return rpccli.cli, rpccli.err } // Set first node as default so that if no node has a greater node ID than the key, // consistent hashing wraps around if i == 0 { ls.syncopchan <- &syncop{GETRPCCLI, node.HostPort, nil} rpccli = <-ls.clireplychan } } return rpccli.cli, rpccli.err } // If this key has been frequently accessed recently, return true to indicate lease request // Must be called synchronously func (ls *Libstore) wantLease(key string) bool { if ls.myhostport == "" { return false } if ls.flags == ALWAYS_LEASE { return true } getrequests, found := ls.getrequests[key] now := time.Now() if !found { // If there are no previous requests for this key, store a new list with this one ls.getrequests[key] = []time.Time{now} } else { count := 0 // Check for lease request activation for _, time := range ls.getrequests[key] { if now.Sub(time) < QUERY_CACHE_INTERVAL { count++ } // If we find threshold - 1 recent usages of the key other than this one, // we should request a lease if count >= QUERY_CACHE_THRESH-1 { return true } } // Store this recent request for future wantLease checks ls.getrequests[key] = append(getrequests, now) } return false } // Get an element func (ls *Libstore) iGet(key string) (string, error) { // If key is in cache, return corresponding value ls.syncopchan <- &syncop{CACHEGET, key, nil} cachevalue := <-ls.cachereplychan if cachevalue.found { return cachevalue.value.(string), nil } // Check whether should request a lease ls.syncopchan <- &syncop{WANTLEASE, key, nil} wantlease := <-ls.successreplychan // Request value from the storage server args := &storageproto.GetArgs{key, wantlease, ls.myhostport} var reply storageproto.GetReply cli, err := ls.getServer(key) if err != nil { fmt.Fprintf(os.Stderr, "error in get server\n") return "", err } err = cli.Call("StorageRPC.Get", args, &reply) if err != nil { fmt.Fprintf(os.Stderr, "RPC failed: %s\n", err) return "", err } if reply.Status != storageproto.OK { return "", lsplog.MakeErr("Get failed: Storage error") } // If lease granted, set expiration timer and insert value into cache if reply.Lease.Granted { go ls.expireLease(key, time.Duration(reply.Lease.ValidSeconds)*time.Second) ls.syncopchan <- &syncop{CACHEPUT, key, reply.Value} <-ls.successreplychan } return reply.Value, nil } // Put an element func (ls *Libstore) iPut(key, value string) error { args := &storageproto.PutArgs{key, value} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.Put", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("Put failed: Storage error") } return nil } // Get a list func (ls *Libstore) iGetList(key string) ([]string, error) { // If key is in cache, return corresponding value ls.syncopchan <- &syncop{CACHEGET, key, nil} cachevalue := <-ls.cachereplychan if cachevalue.found { return cachevalue.value.([]string), nil } // Check whether should request a lease ls.syncopchan <- &syncop{WANTLEASE, key, nil} wantlease := <-ls.successreplychan // Request value from the storage server args := &storageproto.GetArgs{key, wantlease, ls.myhostport} var reply storageproto.GetListReply cli, err := ls.getServer(key) if err != nil { return nil, err } err = cli.Call("StorageRPC.GetList", args, &reply) if err != nil { return nil, err } if reply.Status == storageproto.EKEYNOTFOUND { return make([]string, 0), nil } else if reply.Status != storageproto.OK { return nil, lsplog.MakeErr("GetList failed: Storage error") } // If lease granted, set expiration timer and insert value into cache if reply.Lease.Granted { go ls.expireLease(key, time.Duration(reply.Lease.ValidSeconds)*time.Second) ls.syncopchan <- &syncop{CACHEPUT, key, reply.Value} <-ls.successreplychan } return reply.Value, nil } // Remove an element from a list func (ls *Libstore) iRemoveFromList(key, removeitem string) error { args := &storageproto.PutArgs{key, removeitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.RemoveFromList", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("RemoveFromList failed: Storage error") } return nil } // Append an element to a list func (ls *Libstore) iAppendToList(key, newitem string) error { args := &storageproto.PutArgs{key, newitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.AppendToList", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("AppendToList failed: Storage error") } return nil } // Revokes the lease when the time duration expires func (ls *Libstore) expireLease(key string, duration time.Duration) { <-time.After(duration) ls.syncopchan <- &syncop{CACHEDEL, key, nil} <-ls.successreplychan } // Revokes the lease corresponding to the key in the arguments when activated as a callback func (ls *Libstore) RevokeLease(args *storageproto.RevokeLeaseArgs, reply *storageproto.RevokeLeaseReply) error { ls.syncopchan <- &syncop{CACHEDEL, args.Key, nil} <-ls.successreplychan reply.Status = storageproto.OK return nil } // Implement sorting interface for storageproto.Node type NodeList []storageproto.Node func (nodes NodeList) Len() int { return len(nodes) } func (nodes NodeList) Swap(i, j int) { nodes[i], nodes[j] = nodes[j], nodes[i] } func (nodes NodeList) Less(i, j int) bool { return nodes[i].NodeID < nodes[j].NodeID }
var err error cli, err = rpc.DialHTTP("tcp", hostport)
random_line_split
libstore-impl.go
package libstore import ( "P2-f12/official/cacherpc" "P2-f12/official/lsplog" "P2-f12/official/storageproto" "fmt" "net/rpc" "os" "sort" "strings" "time" ) const ( GETRPCCLI = iota WANTLEASE CACHEGET CACHEPUT CACHEDEL RETRY_INTERVAL = time.Second RETRY_LIMIT = 5 QUERY_CACHE_INTERVAL = storageproto.QUERY_CACHE_SECONDS * time.Second QUERY_CACHE_THRESH = storageproto.QUERY_CACHE_THRESH ) // Structure for synchronous operation type syncop struct { op int key string value interface{} } // Pair of RPC client and error for channel usage type rpccli struct { cli *rpc.Client err error } // Pair of map results for channel usage type cachevalue struct { value interface{} found bool } type Libstore struct { // Data storage objects nodelist NodeList // list of associated servers rpcclis map[string]*rpc.Client // maps a hostport to an RPC client object cache map[string]interface{} // maps a key to a cached value getrequests map[string][]time.Time // maps a key to a list of times it has been Get requested // Basic parameters flags int myhostport string // Synchronization channels syncopchan chan *syncop clireplychan chan *rpccli cachereplychan chan *cachevalue successreplychan chan bool } func iNewLibstore(server string, myhostport string, flags int) (*Libstore, error) { ls := &Libstore{} ls.flags = flags ls.myhostport = myhostport ls.rpcclis = make(map[string]*rpc.Client) ls.cache = make(map[string]interface{}) ls.getrequests = make(map[string][]time.Time) ls.syncopchan = make(chan *syncop) ls.clireplychan = make(chan *rpccli) ls.cachereplychan = make(chan *cachevalue) ls.successreplychan = make(chan bool) // Create RPC connection to storage server cli, err := rpc.DialHTTP("tcp", server) if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", server) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[server] = cli // Get list of storage servers from master storage server // Retry on an interval if necessary args := storageproto.GetServersArgs{} var reply storageproto.RegisterReply ticker := time.NewTicker(RETRY_INTERVAL) for retryCount := 0; retryCount < RETRY_LIMIT; retryCount++ { err = cli.Call("StorageRPC.GetServers", args, &reply) if err != nil { return nil, err } if reply.Ready && reply.Servers != nil { ls.nodelist = reply.Servers // Sort the nodes by NodeID in ascending order sort.Sort(ls.nodelist) // Start the synchronized operation handler go ls.handleSyncOps() // Register RevokeLease method with RPC crpc := cacherpc.NewCacheRPC(ls) rpc.Register(crpc) return ls, nil } <-ticker.C } return nil, lsplog.MakeErr("Storage system not ready") } // Handler for all synchronous operations func (ls *Libstore) handleSyncOps() { for { syncop := <-ls.syncopchan switch syncop.op { case GETRPCCLI: cli, err := ls.getRPCClient(syncop.key) ls.clireplychan <- &rpccli{cli, err} case WANTLEASE: wantlease := ls.wantLease(syncop.key) ls.successreplychan <- wantlease case CACHEGET: value, found := ls.cache[syncop.key] ls.cachereplychan <- &cachevalue{value, found} case CACHEPUT: ls.cache[syncop.key] = syncop.value ls.successreplychan <- true case CACHEDEL: delete(ls.cache, syncop.key) ls.successreplychan <- true } } } // Retrieves RPC client for hostport either from cache or by connecting // Must be called synchronously func (ls *Libstore) getRPCClient(hostport string) (*rpc.Client, error) { cli, found := ls.rpcclis[hostport] // If server has not been connected to before, do so and cache the connection if !found { var err error cli, err = rpc.DialHTTP("tcp", hostport) if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", hostport) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[hostport] = cli } return cli, nil } // Return RPC client of server corresponding to the key func (ls *Libstore) getServer(key string) (*rpc.Client, error) { // Use beginning of key to group related keys together precolon := strings.Split(key, ":")[0] keyid := Storehash(precolon) // Locate server node by consistent hashing scheme var rpccli *rpccli for i, node := range ls.nodelist { if node.NodeID >= keyid { ls.syncopchan <- &syncop{GETRPCCLI, node.HostPort, nil} rpccli = <-ls.clireplychan return rpccli.cli, rpccli.err } // Set first node as default so that if no node has a greater node ID than the key, // consistent hashing wraps around if i == 0 { ls.syncopchan <- &syncop{GETRPCCLI, node.HostPort, nil} rpccli = <-ls.clireplychan } } return rpccli.cli, rpccli.err } // If this key has been frequently accessed recently, return true to indicate lease request // Must be called synchronously func (ls *Libstore) wantLease(key string) bool { if ls.myhostport == "" { return false } if ls.flags == ALWAYS_LEASE { return true } getrequests, found := ls.getrequests[key] now := time.Now() if !found { // If there are no previous requests for this key, store a new list with this one ls.getrequests[key] = []time.Time{now} } else { count := 0 // Check for lease request activation for _, time := range ls.getrequests[key] { if now.Sub(time) < QUERY_CACHE_INTERVAL { count++ } // If we find threshold - 1 recent usages of the key other than this one, // we should request a lease if count >= QUERY_CACHE_THRESH-1 { return true } } // Store this recent request for future wantLease checks ls.getrequests[key] = append(getrequests, now) } return false } // Get an element func (ls *Libstore) iGet(key string) (string, error) { // If key is in cache, return corresponding value ls.syncopchan <- &syncop{CACHEGET, key, nil} cachevalue := <-ls.cachereplychan if cachevalue.found { return cachevalue.value.(string), nil } // Check whether should request a lease ls.syncopchan <- &syncop{WANTLEASE, key, nil} wantlease := <-ls.successreplychan // Request value from the storage server args := &storageproto.GetArgs{key, wantlease, ls.myhostport} var reply storageproto.GetReply cli, err := ls.getServer(key) if err != nil { fmt.Fprintf(os.Stderr, "error in get server\n") return "", err } err = cli.Call("StorageRPC.Get", args, &reply) if err != nil { fmt.Fprintf(os.Stderr, "RPC failed: %s\n", err) return "", err } if reply.Status != storageproto.OK { return "", lsplog.MakeErr("Get failed: Storage error") } // If lease granted, set expiration timer and insert value into cache if reply.Lease.Granted { go ls.expireLease(key, time.Duration(reply.Lease.ValidSeconds)*time.Second) ls.syncopchan <- &syncop{CACHEPUT, key, reply.Value} <-ls.successreplychan } return reply.Value, nil } // Put an element func (ls *Libstore) iPut(key, value string) error { args := &storageproto.PutArgs{key, value} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.Put", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("Put failed: Storage error") } return nil } // Get a list func (ls *Libstore) iGetList(key string) ([]string, error) { // If key is in cache, return corresponding value ls.syncopchan <- &syncop{CACHEGET, key, nil} cachevalue := <-ls.cachereplychan if cachevalue.found { return cachevalue.value.([]string), nil } // Check whether should request a lease ls.syncopchan <- &syncop{WANTLEASE, key, nil} wantlease := <-ls.successreplychan // Request value from the storage server args := &storageproto.GetArgs{key, wantlease, ls.myhostport} var reply storageproto.GetListReply cli, err := ls.getServer(key) if err != nil { return nil, err } err = cli.Call("StorageRPC.GetList", args, &reply) if err != nil { return nil, err } if reply.Status == storageproto.EKEYNOTFOUND { return make([]string, 0), nil } else if reply.Status != storageproto.OK { return nil, lsplog.MakeErr("GetList failed: Storage error") } // If lease granted, set expiration timer and insert value into cache if reply.Lease.Granted { go ls.expireLease(key, time.Duration(reply.Lease.ValidSeconds)*time.Second) ls.syncopchan <- &syncop{CACHEPUT, key, reply.Value} <-ls.successreplychan } return reply.Value, nil } // Remove an element from a list func (ls *Libstore) iRemoveFromList(key, removeitem string) error { args := &storageproto.PutArgs{key, removeitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.RemoveFromList", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("RemoveFromList failed: Storage error") } return nil } // Append an element to a list func (ls *Libstore) iAppendToList(key, newitem string) error { args := &storageproto.PutArgs{key, newitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.AppendToList", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("AppendToList failed: Storage error") } return nil } // Revokes the lease when the time duration expires func (ls *Libstore) expireLease(key string, duration time.Duration) { <-time.After(duration) ls.syncopchan <- &syncop{CACHEDEL, key, nil} <-ls.successreplychan } // Revokes the lease corresponding to the key in the arguments when activated as a callback func (ls *Libstore)
(args *storageproto.RevokeLeaseArgs, reply *storageproto.RevokeLeaseReply) error { ls.syncopchan <- &syncop{CACHEDEL, args.Key, nil} <-ls.successreplychan reply.Status = storageproto.OK return nil } // Implement sorting interface for storageproto.Node type NodeList []storageproto.Node func (nodes NodeList) Len() int { return len(nodes) } func (nodes NodeList) Swap(i, j int) { nodes[i], nodes[j] = nodes[j], nodes[i] } func (nodes NodeList) Less(i, j int) bool { return nodes[i].NodeID < nodes[j].NodeID }
RevokeLease
identifier_name
libstore-impl.go
package libstore import ( "P2-f12/official/cacherpc" "P2-f12/official/lsplog" "P2-f12/official/storageproto" "fmt" "net/rpc" "os" "sort" "strings" "time" ) const ( GETRPCCLI = iota WANTLEASE CACHEGET CACHEPUT CACHEDEL RETRY_INTERVAL = time.Second RETRY_LIMIT = 5 QUERY_CACHE_INTERVAL = storageproto.QUERY_CACHE_SECONDS * time.Second QUERY_CACHE_THRESH = storageproto.QUERY_CACHE_THRESH ) // Structure for synchronous operation type syncop struct { op int key string value interface{} } // Pair of RPC client and error for channel usage type rpccli struct { cli *rpc.Client err error } // Pair of map results for channel usage type cachevalue struct { value interface{} found bool } type Libstore struct { // Data storage objects nodelist NodeList // list of associated servers rpcclis map[string]*rpc.Client // maps a hostport to an RPC client object cache map[string]interface{} // maps a key to a cached value getrequests map[string][]time.Time // maps a key to a list of times it has been Get requested // Basic parameters flags int myhostport string // Synchronization channels syncopchan chan *syncop clireplychan chan *rpccli cachereplychan chan *cachevalue successreplychan chan bool } func iNewLibstore(server string, myhostport string, flags int) (*Libstore, error) { ls := &Libstore{} ls.flags = flags ls.myhostport = myhostport ls.rpcclis = make(map[string]*rpc.Client) ls.cache = make(map[string]interface{}) ls.getrequests = make(map[string][]time.Time) ls.syncopchan = make(chan *syncop) ls.clireplychan = make(chan *rpccli) ls.cachereplychan = make(chan *cachevalue) ls.successreplychan = make(chan bool) // Create RPC connection to storage server cli, err := rpc.DialHTTP("tcp", server) if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", server) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[server] = cli // Get list of storage servers from master storage server // Retry on an interval if necessary args := storageproto.GetServersArgs{} var reply storageproto.RegisterReply ticker := time.NewTicker(RETRY_INTERVAL) for retryCount := 0; retryCount < RETRY_LIMIT; retryCount++ { err = cli.Call("StorageRPC.GetServers", args, &reply) if err != nil { return nil, err } if reply.Ready && reply.Servers != nil { ls.nodelist = reply.Servers // Sort the nodes by NodeID in ascending order sort.Sort(ls.nodelist) // Start the synchronized operation handler go ls.handleSyncOps() // Register RevokeLease method with RPC crpc := cacherpc.NewCacheRPC(ls) rpc.Register(crpc) return ls, nil } <-ticker.C } return nil, lsplog.MakeErr("Storage system not ready") } // Handler for all synchronous operations func (ls *Libstore) handleSyncOps() { for { syncop := <-ls.syncopchan switch syncop.op { case GETRPCCLI: cli, err := ls.getRPCClient(syncop.key) ls.clireplychan <- &rpccli{cli, err} case WANTLEASE: wantlease := ls.wantLease(syncop.key) ls.successreplychan <- wantlease case CACHEGET: value, found := ls.cache[syncop.key] ls.cachereplychan <- &cachevalue{value, found} case CACHEPUT: ls.cache[syncop.key] = syncop.value ls.successreplychan <- true case CACHEDEL: delete(ls.cache, syncop.key) ls.successreplychan <- true } } } // Retrieves RPC client for hostport either from cache or by connecting // Must be called synchronously func (ls *Libstore) getRPCClient(hostport string) (*rpc.Client, error) { cli, found := ls.rpcclis[hostport] // If server has not been connected to before, do so and cache the connection if !found { var err error cli, err = rpc.DialHTTP("tcp", hostport) if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", hostport) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[hostport] = cli } return cli, nil } // Return RPC client of server corresponding to the key func (ls *Libstore) getServer(key string) (*rpc.Client, error) { // Use beginning of key to group related keys together precolon := strings.Split(key, ":")[0] keyid := Storehash(precolon) // Locate server node by consistent hashing scheme var rpccli *rpccli for i, node := range ls.nodelist { if node.NodeID >= keyid { ls.syncopchan <- &syncop{GETRPCCLI, node.HostPort, nil} rpccli = <-ls.clireplychan return rpccli.cli, rpccli.err } // Set first node as default so that if no node has a greater node ID than the key, // consistent hashing wraps around if i == 0 { ls.syncopchan <- &syncop{GETRPCCLI, node.HostPort, nil} rpccli = <-ls.clireplychan } } return rpccli.cli, rpccli.err } // If this key has been frequently accessed recently, return true to indicate lease request // Must be called synchronously func (ls *Libstore) wantLease(key string) bool { if ls.myhostport == "" { return false } if ls.flags == ALWAYS_LEASE { return true } getrequests, found := ls.getrequests[key] now := time.Now() if !found { // If there are no previous requests for this key, store a new list with this one ls.getrequests[key] = []time.Time{now} } else { count := 0 // Check for lease request activation for _, time := range ls.getrequests[key] { if now.Sub(time) < QUERY_CACHE_INTERVAL { count++ } // If we find threshold - 1 recent usages of the key other than this one, // we should request a lease if count >= QUERY_CACHE_THRESH-1 { return true } } // Store this recent request for future wantLease checks ls.getrequests[key] = append(getrequests, now) } return false } // Get an element func (ls *Libstore) iGet(key string) (string, error) { // If key is in cache, return corresponding value ls.syncopchan <- &syncop{CACHEGET, key, nil} cachevalue := <-ls.cachereplychan if cachevalue.found { return cachevalue.value.(string), nil } // Check whether should request a lease ls.syncopchan <- &syncop{WANTLEASE, key, nil} wantlease := <-ls.successreplychan // Request value from the storage server args := &storageproto.GetArgs{key, wantlease, ls.myhostport} var reply storageproto.GetReply cli, err := ls.getServer(key) if err != nil { fmt.Fprintf(os.Stderr, "error in get server\n") return "", err } err = cli.Call("StorageRPC.Get", args, &reply) if err != nil { fmt.Fprintf(os.Stderr, "RPC failed: %s\n", err) return "", err } if reply.Status != storageproto.OK { return "", lsplog.MakeErr("Get failed: Storage error") } // If lease granted, set expiration timer and insert value into cache if reply.Lease.Granted { go ls.expireLease(key, time.Duration(reply.Lease.ValidSeconds)*time.Second) ls.syncopchan <- &syncop{CACHEPUT, key, reply.Value} <-ls.successreplychan } return reply.Value, nil } // Put an element func (ls *Libstore) iPut(key, value string) error { args := &storageproto.PutArgs{key, value} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.Put", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("Put failed: Storage error") } return nil } // Get a list func (ls *Libstore) iGetList(key string) ([]string, error) { // If key is in cache, return corresponding value ls.syncopchan <- &syncop{CACHEGET, key, nil} cachevalue := <-ls.cachereplychan if cachevalue.found { return cachevalue.value.([]string), nil } // Check whether should request a lease ls.syncopchan <- &syncop{WANTLEASE, key, nil} wantlease := <-ls.successreplychan // Request value from the storage server args := &storageproto.GetArgs{key, wantlease, ls.myhostport} var reply storageproto.GetListReply cli, err := ls.getServer(key) if err != nil { return nil, err } err = cli.Call("StorageRPC.GetList", args, &reply) if err != nil { return nil, err } if reply.Status == storageproto.EKEYNOTFOUND { return make([]string, 0), nil } else if reply.Status != storageproto.OK { return nil, lsplog.MakeErr("GetList failed: Storage error") } // If lease granted, set expiration timer and insert value into cache if reply.Lease.Granted { go ls.expireLease(key, time.Duration(reply.Lease.ValidSeconds)*time.Second) ls.syncopchan <- &syncop{CACHEPUT, key, reply.Value} <-ls.successreplychan } return reply.Value, nil } // Remove an element from a list func (ls *Libstore) iRemoveFromList(key, removeitem string) error { args := &storageproto.PutArgs{key, removeitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.RemoveFromList", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("RemoveFromList failed: Storage error") } return nil } // Append an element to a list func (ls *Libstore) iAppendToList(key, newitem string) error
// Revokes the lease when the time duration expires func (ls *Libstore) expireLease(key string, duration time.Duration) { <-time.After(duration) ls.syncopchan <- &syncop{CACHEDEL, key, nil} <-ls.successreplychan } // Revokes the lease corresponding to the key in the arguments when activated as a callback func (ls *Libstore) RevokeLease(args *storageproto.RevokeLeaseArgs, reply *storageproto.RevokeLeaseReply) error { ls.syncopchan <- &syncop{CACHEDEL, args.Key, nil} <-ls.successreplychan reply.Status = storageproto.OK return nil } // Implement sorting interface for storageproto.Node type NodeList []storageproto.Node func (nodes NodeList) Len() int { return len(nodes) } func (nodes NodeList) Swap(i, j int) { nodes[i], nodes[j] = nodes[j], nodes[i] } func (nodes NodeList) Less(i, j int) bool { return nodes[i].NodeID < nodes[j].NodeID }
{ args := &storageproto.PutArgs{key, newitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.AppendToList", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("AppendToList failed: Storage error") } return nil }
identifier_body
libstore-impl.go
package libstore import ( "P2-f12/official/cacherpc" "P2-f12/official/lsplog" "P2-f12/official/storageproto" "fmt" "net/rpc" "os" "sort" "strings" "time" ) const ( GETRPCCLI = iota WANTLEASE CACHEGET CACHEPUT CACHEDEL RETRY_INTERVAL = time.Second RETRY_LIMIT = 5 QUERY_CACHE_INTERVAL = storageproto.QUERY_CACHE_SECONDS * time.Second QUERY_CACHE_THRESH = storageproto.QUERY_CACHE_THRESH ) // Structure for synchronous operation type syncop struct { op int key string value interface{} } // Pair of RPC client and error for channel usage type rpccli struct { cli *rpc.Client err error } // Pair of map results for channel usage type cachevalue struct { value interface{} found bool } type Libstore struct { // Data storage objects nodelist NodeList // list of associated servers rpcclis map[string]*rpc.Client // maps a hostport to an RPC client object cache map[string]interface{} // maps a key to a cached value getrequests map[string][]time.Time // maps a key to a list of times it has been Get requested // Basic parameters flags int myhostport string // Synchronization channels syncopchan chan *syncop clireplychan chan *rpccli cachereplychan chan *cachevalue successreplychan chan bool } func iNewLibstore(server string, myhostport string, flags int) (*Libstore, error) { ls := &Libstore{} ls.flags = flags ls.myhostport = myhostport ls.rpcclis = make(map[string]*rpc.Client) ls.cache = make(map[string]interface{}) ls.getrequests = make(map[string][]time.Time) ls.syncopchan = make(chan *syncop) ls.clireplychan = make(chan *rpccli) ls.cachereplychan = make(chan *cachevalue) ls.successreplychan = make(chan bool) // Create RPC connection to storage server cli, err := rpc.DialHTTP("tcp", server) if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", server) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[server] = cli // Get list of storage servers from master storage server // Retry on an interval if necessary args := storageproto.GetServersArgs{} var reply storageproto.RegisterReply ticker := time.NewTicker(RETRY_INTERVAL) for retryCount := 0; retryCount < RETRY_LIMIT; retryCount++ { err = cli.Call("StorageRPC.GetServers", args, &reply) if err != nil { return nil, err } if reply.Ready && reply.Servers != nil { ls.nodelist = reply.Servers // Sort the nodes by NodeID in ascending order sort.Sort(ls.nodelist) // Start the synchronized operation handler go ls.handleSyncOps() // Register RevokeLease method with RPC crpc := cacherpc.NewCacheRPC(ls) rpc.Register(crpc) return ls, nil } <-ticker.C } return nil, lsplog.MakeErr("Storage system not ready") } // Handler for all synchronous operations func (ls *Libstore) handleSyncOps() { for { syncop := <-ls.syncopchan switch syncop.op { case GETRPCCLI: cli, err := ls.getRPCClient(syncop.key) ls.clireplychan <- &rpccli{cli, err} case WANTLEASE: wantlease := ls.wantLease(syncop.key) ls.successreplychan <- wantlease case CACHEGET: value, found := ls.cache[syncop.key] ls.cachereplychan <- &cachevalue{value, found} case CACHEPUT: ls.cache[syncop.key] = syncop.value ls.successreplychan <- true case CACHEDEL: delete(ls.cache, syncop.key) ls.successreplychan <- true } } } // Retrieves RPC client for hostport either from cache or by connecting // Must be called synchronously func (ls *Libstore) getRPCClient(hostport string) (*rpc.Client, error) { cli, found := ls.rpcclis[hostport] // If server has not been connected to before, do so and cache the connection if !found { var err error cli, err = rpc.DialHTTP("tcp", hostport) if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", hostport) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[hostport] = cli } return cli, nil } // Return RPC client of server corresponding to the key func (ls *Libstore) getServer(key string) (*rpc.Client, error) { // Use beginning of key to group related keys together precolon := strings.Split(key, ":")[0] keyid := Storehash(precolon) // Locate server node by consistent hashing scheme var rpccli *rpccli for i, node := range ls.nodelist { if node.NodeID >= keyid { ls.syncopchan <- &syncop{GETRPCCLI, node.HostPort, nil} rpccli = <-ls.clireplychan return rpccli.cli, rpccli.err } // Set first node as default so that if no node has a greater node ID than the key, // consistent hashing wraps around if i == 0 { ls.syncopchan <- &syncop{GETRPCCLI, node.HostPort, nil} rpccli = <-ls.clireplychan } } return rpccli.cli, rpccli.err } // If this key has been frequently accessed recently, return true to indicate lease request // Must be called synchronously func (ls *Libstore) wantLease(key string) bool { if ls.myhostport == "" { return false } if ls.flags == ALWAYS_LEASE { return true } getrequests, found := ls.getrequests[key] now := time.Now() if !found { // If there are no previous requests for this key, store a new list with this one ls.getrequests[key] = []time.Time{now} } else { count := 0 // Check for lease request activation for _, time := range ls.getrequests[key] { if now.Sub(time) < QUERY_CACHE_INTERVAL { count++ } // If we find threshold - 1 recent usages of the key other than this one, // we should request a lease if count >= QUERY_CACHE_THRESH-1 { return true } } // Store this recent request for future wantLease checks ls.getrequests[key] = append(getrequests, now) } return false } // Get an element func (ls *Libstore) iGet(key string) (string, error) { // If key is in cache, return corresponding value ls.syncopchan <- &syncop{CACHEGET, key, nil} cachevalue := <-ls.cachereplychan if cachevalue.found { return cachevalue.value.(string), nil } // Check whether should request a lease ls.syncopchan <- &syncop{WANTLEASE, key, nil} wantlease := <-ls.successreplychan // Request value from the storage server args := &storageproto.GetArgs{key, wantlease, ls.myhostport} var reply storageproto.GetReply cli, err := ls.getServer(key) if err != nil { fmt.Fprintf(os.Stderr, "error in get server\n") return "", err } err = cli.Call("StorageRPC.Get", args, &reply) if err != nil { fmt.Fprintf(os.Stderr, "RPC failed: %s\n", err) return "", err } if reply.Status != storageproto.OK { return "", lsplog.MakeErr("Get failed: Storage error") } // If lease granted, set expiration timer and insert value into cache if reply.Lease.Granted { go ls.expireLease(key, time.Duration(reply.Lease.ValidSeconds)*time.Second) ls.syncopchan <- &syncop{CACHEPUT, key, reply.Value} <-ls.successreplychan } return reply.Value, nil } // Put an element func (ls *Libstore) iPut(key, value string) error { args := &storageproto.PutArgs{key, value} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.Put", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("Put failed: Storage error") } return nil } // Get a list func (ls *Libstore) iGetList(key string) ([]string, error) { // If key is in cache, return corresponding value ls.syncopchan <- &syncop{CACHEGET, key, nil} cachevalue := <-ls.cachereplychan if cachevalue.found { return cachevalue.value.([]string), nil } // Check whether should request a lease ls.syncopchan <- &syncop{WANTLEASE, key, nil} wantlease := <-ls.successreplychan // Request value from the storage server args := &storageproto.GetArgs{key, wantlease, ls.myhostport} var reply storageproto.GetListReply cli, err := ls.getServer(key) if err != nil { return nil, err } err = cli.Call("StorageRPC.GetList", args, &reply) if err != nil { return nil, err } if reply.Status == storageproto.EKEYNOTFOUND { return make([]string, 0), nil } else if reply.Status != storageproto.OK { return nil, lsplog.MakeErr("GetList failed: Storage error") } // If lease granted, set expiration timer and insert value into cache if reply.Lease.Granted { go ls.expireLease(key, time.Duration(reply.Lease.ValidSeconds)*time.Second) ls.syncopchan <- &syncop{CACHEPUT, key, reply.Value} <-ls.successreplychan } return reply.Value, nil } // Remove an element from a list func (ls *Libstore) iRemoveFromList(key, removeitem string) error { args := &storageproto.PutArgs{key, removeitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.RemoveFromList", args, &reply) if err != nil
if reply.Status != storageproto.OK { return lsplog.MakeErr("RemoveFromList failed: Storage error") } return nil } // Append an element to a list func (ls *Libstore) iAppendToList(key, newitem string) error { args := &storageproto.PutArgs{key, newitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.AppendToList", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("AppendToList failed: Storage error") } return nil } // Revokes the lease when the time duration expires func (ls *Libstore) expireLease(key string, duration time.Duration) { <-time.After(duration) ls.syncopchan <- &syncop{CACHEDEL, key, nil} <-ls.successreplychan } // Revokes the lease corresponding to the key in the arguments when activated as a callback func (ls *Libstore) RevokeLease(args *storageproto.RevokeLeaseArgs, reply *storageproto.RevokeLeaseReply) error { ls.syncopchan <- &syncop{CACHEDEL, args.Key, nil} <-ls.successreplychan reply.Status = storageproto.OK return nil } // Implement sorting interface for storageproto.Node type NodeList []storageproto.Node func (nodes NodeList) Len() int { return len(nodes) } func (nodes NodeList) Swap(i, j int) { nodes[i], nodes[j] = nodes[j], nodes[i] } func (nodes NodeList) Less(i, j int) bool { return nodes[i].NodeID < nodes[j].NodeID }
{ return err }
conditional_block
router.rs
use anyhow::{bail, Result}; use indexmap::indexmap; use serde::Deserialize; use serde_json::json; use turbo_tasks::{ primitives::{JsonValueVc, StringsVc}, CompletionVc, CompletionsVc, Value, }; use turbo_tasks_fs::{ json::parse_json_rope_with_source_context, to_sys_path, File, FileSystemPathVc, }; use turbopack::{evaluate_context::node_evaluate_asset_context, transition::TransitionsByNameVc}; use turbopack_core::{ asset::AssetVc, changed::any_content_changed, chunk::ChunkingContext, context::{AssetContext, AssetContextVc}, environment::{EnvironmentIntention::Middleware, ServerAddrVc}, ident::AssetIdentVc, issue::IssueVc, reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType}, resolve::{find_context_file, FindContextFileResult}, source_asset::SourceAssetVc, virtual_asset::VirtualAssetVc, }; use turbopack_dev::DevChunkingContextVc; use turbopack_ecmascript::{ EcmascriptInputTransform, EcmascriptInputTransformsVc, EcmascriptModuleAssetType, EcmascriptModuleAssetVc, InnerAssetsVc, OptionEcmascriptModuleAssetVc, }; use turbopack_node::{ evaluate::{evaluate, JavaScriptValue}, execution_context::{ExecutionContext, ExecutionContextVc}, StructuredError, }; use crate::{ embed_js::{next_asset, next_js_file}, next_config::NextConfigVc, next_edge::{ context::{get_edge_compile_time_info, get_edge_resolve_options_context}, transition::NextEdgeTransition, }, next_import_map::get_next_build_import_map, next_server::context::{get_server_module_options_context, ServerContextType}, util::{parse_config_from_source, NextSourceConfigVc}, }; #[turbo_tasks::function] fn next_configs() -> StringsVc { StringsVc::cell( ["next.config.mjs", "next.config.js"] .into_iter() .map(ToOwned::to_owned) .collect(), ) } #[turbo_tasks::function] async fn middleware_files(page_extensions: StringsVc) -> Result<StringsVc> { let extensions = page_extensions.await?; let files = ["middleware.", "src/middleware."] .into_iter() .flat_map(|f| { extensions .iter() .map(move |ext| String::from(f) + ext.as_str()) }) .collect(); Ok(StringsVc::cell(files)) } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct RouterRequest { pub method: String, pub pathname: String, pub raw_query: String, pub raw_headers: Vec<(String, String)>, } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct RewriteResponse { pub url: String, pub headers: Vec<(String, String)>, } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct MiddlewareHeadersResponse { pub status_code: u16, pub headers: Vec<(String, String)>, } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] pub struct MiddlewareBodyResponse(pub Vec<u8>); #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] pub struct FullMiddlewareResponse { pub headers: MiddlewareHeadersResponse, pub body: Vec<u8>, } #[derive(Deserialize)] #[serde(tag = "type", rename_all = "kebab-case")] enum RouterIncomingMessage { Rewrite { data: RewriteResponse, }, // TODO: Implement #[allow(dead_code)] MiddlewareHeaders { data: MiddlewareHeadersResponse, }, // TODO: Implement #[allow(dead_code)] MiddlewareBody { data: MiddlewareBodyResponse, }, FullMiddleware { data: FullMiddlewareResponse, }, None, Error(StructuredError), } #[derive(Debug)] #[turbo_tasks::value] pub enum RouterResult { Rewrite(RewriteResponse), FullMiddleware(FullMiddlewareResponse), None, Error, } impl From<RouterIncomingMessage> for RouterResult { fn from(value: RouterIncomingMessage) -> Self { match value { RouterIncomingMessage::Rewrite { data } => Self::Rewrite(data), RouterIncomingMessage::FullMiddleware { data } => Self::FullMiddleware(data), RouterIncomingMessage::None => Self::None, _ => Self::Error, } } } #[turbo_tasks::function] async fn get_config( context: AssetContextVc, project_path: FileSystemPathVc, configs: StringsVc, ) -> Result<OptionEcmascriptModuleAssetVc> { let find_config_result = find_context_file(project_path, configs); let config_asset = match &*find_config_result.await? { FindContextFileResult::Found(config_path, _) => Some(as_es_module_asset( SourceAssetVc::new(*config_path).as_asset(), context, )), FindContextFileResult::NotFound(_) => None, }; Ok(OptionEcmascriptModuleAssetVc::cell(config_asset)) } fn as_es_module_asset(asset: AssetVc, context: AssetContextVc) -> EcmascriptModuleAssetVc { EcmascriptModuleAssetVc::new( asset, context, Value::new(EcmascriptModuleAssetType::Typescript), EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript { use_define_for_class_fields: false, }]), context.compile_time_info(), ) } #[turbo_tasks::function] async fn next_config_changed( context: AssetContextVc, project_path: FileSystemPathVc, ) -> Result<CompletionVc> { let next_config = get_config(context, project_path, next_configs()).await?; Ok(if let Some(c) = *next_config { any_content_changed(c.into()) } else { CompletionVc::immutable() }) } #[turbo_tasks::function] async fn config_assets( context: AssetContextVc, project_path: FileSystemPathVc, page_extensions: StringsVc, ) -> Result<InnerAssetsVc> { let middleware_config = get_config(context, project_path, middleware_files(page_extensions)).await?; // The router.ts file expects a manifest of chunks for the middleware. If there // is no middleware file, then we need to generate a default empty manifest // and we cannot process it with the next-edge transition because it // requires a real file for some reason. let (manifest, config) = match &*middleware_config { Some(c) => { let manifest = context.with_transition("next-edge").process( c.as_asset(), Value::new(ReferenceType::EcmaScriptModules( EcmaScriptModulesReferenceSubType::Undefined, )), ); let config = parse_config_from_source(c.as_asset()); (manifest, config) } None => { let manifest = as_es_module_asset( VirtualAssetVc::new( project_path.join("middleware.js"), File::from("export default [];").into(), ) .as_asset(), context, ) .as_asset(); let config = NextSourceConfigVc::default(); (manifest, config) } }; let config_asset = as_es_module_asset( VirtualAssetVc::new( project_path.join("middleware_config.js"), File::from(format!( "export default {};", json!({ "matcher": &config.await?.matcher }) )) .into(), ) .as_asset(), context, ) .as_asset(); Ok(InnerAssetsVc::cell(indexmap! { "MIDDLEWARE_CHUNK_GROUP".to_string() => manifest, "MIDDLEWARE_CONFIG".to_string() => config_asset, })) } #[turbo_tasks::function] fn route_executor(context: AssetContextVc, configs: InnerAssetsVc) -> AssetVc { EcmascriptModuleAssetVc::new_with_inner_assets( next_asset("entry/router.ts"), context, Value::new(EcmascriptModuleAssetType::Typescript), EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript { use_define_for_class_fields: false, }]), context.compile_time_info(), configs, ) .into() } #[turbo_tasks::function] fn edge_transition_map( server_addr: ServerAddrVc, project_path: FileSystemPathVc, output_path: FileSystemPathVc, next_config: NextConfigVc, execution_context: ExecutionContextVc, ) -> TransitionsByNameVc { let edge_compile_time_info = get_edge_compile_time_info(server_addr, Value::new(Middleware)); let edge_chunking_context = DevChunkingContextVc::builder( project_path, output_path.join("edge"), output_path.join("edge/chunks"), output_path.join("edge/assets"), edge_compile_time_info.environment(), ) .build(); let edge_resolve_options_context = get_edge_resolve_options_context( project_path, Value::new(ServerContextType::Middleware), next_config, execution_context, ); let server_module_options_context = get_server_module_options_context( project_path, execution_context, Value::new(ServerContextType::Middleware), next_config, ); let next_edge_transition = NextEdgeTransition { edge_compile_time_info, edge_chunking_context, edge_module_options_context: Some(server_module_options_context), edge_resolve_options_context, output_path: output_path.root(), base_path: project_path, bootstrap_file: next_js_file("entry/edge-bootstrap.ts"), entry_name: "middleware".to_string(), } .cell() .into(); TransitionsByNameVc::cell( [("next-edge".to_string(), next_edge_transition)] .into_iter() .collect(), ) } #[turbo_tasks::function] pub async fn route( execution_context: ExecutionContextVc, request: RouterRequestVc, next_config: NextConfigVc, server_addr: ServerAddrVc, routes_changed: CompletionVc, ) -> Result<RouterResultVc> { let RouterRequest { ref method, ref pathname, .. } = *request.await?; IssueVc::attach_description( format!("Next.js Routing for {} {}", method, pathname), route_internal( execution_context, request, next_config, server_addr, routes_changed, ), ) .await } #[turbo_tasks::function] async fn
( execution_context: ExecutionContextVc, request: RouterRequestVc, next_config: NextConfigVc, server_addr: ServerAddrVc, routes_changed: CompletionVc, ) -> Result<RouterResultVc> { let ExecutionContext { project_path, chunking_context, env, } = *execution_context.await?; let context = node_evaluate_asset_context( project_path, Some(get_next_build_import_map()), Some(edge_transition_map( server_addr, project_path, chunking_context.output_root(), next_config, execution_context, )), ); let configs = config_assets(context, project_path, next_config.page_extensions()); let router_asset = route_executor(context, configs); // This invalidates the router when the next config changes let next_config_changed = next_config_changed(context, project_path); let request = serde_json::value::to_value(&*request.await?)?; let Some(dir) = to_sys_path(project_path).await? else { bail!("Next.js requires a disk path to check for valid routes"); }; let result = evaluate( router_asset, project_path, env, AssetIdentVc::from_path(project_path), context, chunking_context.with_layer("router"), None, vec![ JsonValueVc::cell(request), JsonValueVc::cell(dir.to_string_lossy().into()), ], CompletionsVc::all(vec![next_config_changed, routes_changed]), /* debug */ false, ) .await?; match &*result { JavaScriptValue::Value(val) => { let result: RouterIncomingMessage = parse_json_rope_with_source_context(val)?; Ok(RouterResult::from(result).cell()) } JavaScriptValue::Error => Ok(RouterResult::Error.cell()), JavaScriptValue::Stream(_) => { unimplemented!("Stream not supported now"); } } }
route_internal
identifier_name
router.rs
use anyhow::{bail, Result}; use indexmap::indexmap; use serde::Deserialize; use serde_json::json; use turbo_tasks::{ primitives::{JsonValueVc, StringsVc}, CompletionVc, CompletionsVc, Value, }; use turbo_tasks_fs::{ json::parse_json_rope_with_source_context, to_sys_path, File, FileSystemPathVc, }; use turbopack::{evaluate_context::node_evaluate_asset_context, transition::TransitionsByNameVc}; use turbopack_core::{ asset::AssetVc, changed::any_content_changed, chunk::ChunkingContext, context::{AssetContext, AssetContextVc}, environment::{EnvironmentIntention::Middleware, ServerAddrVc}, ident::AssetIdentVc, issue::IssueVc, reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType}, resolve::{find_context_file, FindContextFileResult}, source_asset::SourceAssetVc, virtual_asset::VirtualAssetVc, }; use turbopack_dev::DevChunkingContextVc; use turbopack_ecmascript::{ EcmascriptInputTransform, EcmascriptInputTransformsVc, EcmascriptModuleAssetType, EcmascriptModuleAssetVc, InnerAssetsVc, OptionEcmascriptModuleAssetVc, }; use turbopack_node::{ evaluate::{evaluate, JavaScriptValue}, execution_context::{ExecutionContext, ExecutionContextVc}, StructuredError, }; use crate::{ embed_js::{next_asset, next_js_file}, next_config::NextConfigVc, next_edge::{ context::{get_edge_compile_time_info, get_edge_resolve_options_context}, transition::NextEdgeTransition, }, next_import_map::get_next_build_import_map, next_server::context::{get_server_module_options_context, ServerContextType}, util::{parse_config_from_source, NextSourceConfigVc}, }; #[turbo_tasks::function] fn next_configs() -> StringsVc { StringsVc::cell( ["next.config.mjs", "next.config.js"] .into_iter() .map(ToOwned::to_owned) .collect(), ) } #[turbo_tasks::function] async fn middleware_files(page_extensions: StringsVc) -> Result<StringsVc> { let extensions = page_extensions.await?; let files = ["middleware.", "src/middleware."] .into_iter() .flat_map(|f| { extensions .iter() .map(move |ext| String::from(f) + ext.as_str()) }) .collect(); Ok(StringsVc::cell(files)) } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct RouterRequest { pub method: String, pub pathname: String, pub raw_query: String, pub raw_headers: Vec<(String, String)>, } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct RewriteResponse { pub url: String, pub headers: Vec<(String, String)>, } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct MiddlewareHeadersResponse { pub status_code: u16, pub headers: Vec<(String, String)>, } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] pub struct MiddlewareBodyResponse(pub Vec<u8>); #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] pub struct FullMiddlewareResponse { pub headers: MiddlewareHeadersResponse, pub body: Vec<u8>, } #[derive(Deserialize)] #[serde(tag = "type", rename_all = "kebab-case")] enum RouterIncomingMessage { Rewrite { data: RewriteResponse, }, // TODO: Implement #[allow(dead_code)] MiddlewareHeaders { data: MiddlewareHeadersResponse, }, // TODO: Implement #[allow(dead_code)] MiddlewareBody { data: MiddlewareBodyResponse, }, FullMiddleware { data: FullMiddlewareResponse, }, None, Error(StructuredError), } #[derive(Debug)] #[turbo_tasks::value] pub enum RouterResult { Rewrite(RewriteResponse), FullMiddleware(FullMiddlewareResponse), None, Error, } impl From<RouterIncomingMessage> for RouterResult { fn from(value: RouterIncomingMessage) -> Self { match value { RouterIncomingMessage::Rewrite { data } => Self::Rewrite(data), RouterIncomingMessage::FullMiddleware { data } => Self::FullMiddleware(data), RouterIncomingMessage::None => Self::None, _ => Self::Error, } } } #[turbo_tasks::function] async fn get_config( context: AssetContextVc, project_path: FileSystemPathVc, configs: StringsVc, ) -> Result<OptionEcmascriptModuleAssetVc> { let find_config_result = find_context_file(project_path, configs); let config_asset = match &*find_config_result.await? { FindContextFileResult::Found(config_path, _) => Some(as_es_module_asset( SourceAssetVc::new(*config_path).as_asset(), context, )), FindContextFileResult::NotFound(_) => None, }; Ok(OptionEcmascriptModuleAssetVc::cell(config_asset)) } fn as_es_module_asset(asset: AssetVc, context: AssetContextVc) -> EcmascriptModuleAssetVc { EcmascriptModuleAssetVc::new( asset, context, Value::new(EcmascriptModuleAssetType::Typescript), EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript { use_define_for_class_fields: false, }]), context.compile_time_info(), ) } #[turbo_tasks::function] async fn next_config_changed( context: AssetContextVc, project_path: FileSystemPathVc, ) -> Result<CompletionVc> { let next_config = get_config(context, project_path, next_configs()).await?; Ok(if let Some(c) = *next_config { any_content_changed(c.into()) } else { CompletionVc::immutable() }) } #[turbo_tasks::function] async fn config_assets( context: AssetContextVc, project_path: FileSystemPathVc, page_extensions: StringsVc, ) -> Result<InnerAssetsVc> { let middleware_config = get_config(context, project_path, middleware_files(page_extensions)).await?; // The router.ts file expects a manifest of chunks for the middleware. If there // is no middleware file, then we need to generate a default empty manifest // and we cannot process it with the next-edge transition because it // requires a real file for some reason. let (manifest, config) = match &*middleware_config { Some(c) => { let manifest = context.with_transition("next-edge").process( c.as_asset(), Value::new(ReferenceType::EcmaScriptModules( EcmaScriptModulesReferenceSubType::Undefined, )), ); let config = parse_config_from_source(c.as_asset()); (manifest, config) } None => { let manifest = as_es_module_asset( VirtualAssetVc::new( project_path.join("middleware.js"), File::from("export default [];").into(), ) .as_asset(), context, ) .as_asset(); let config = NextSourceConfigVc::default(); (manifest, config) } }; let config_asset = as_es_module_asset( VirtualAssetVc::new( project_path.join("middleware_config.js"), File::from(format!( "export default {};", json!({ "matcher": &config.await?.matcher }) )) .into(), ) .as_asset(), context, ) .as_asset(); Ok(InnerAssetsVc::cell(indexmap! { "MIDDLEWARE_CHUNK_GROUP".to_string() => manifest, "MIDDLEWARE_CONFIG".to_string() => config_asset, })) } #[turbo_tasks::function] fn route_executor(context: AssetContextVc, configs: InnerAssetsVc) -> AssetVc { EcmascriptModuleAssetVc::new_with_inner_assets( next_asset("entry/router.ts"), context, Value::new(EcmascriptModuleAssetType::Typescript), EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript { use_define_for_class_fields: false, }]), context.compile_time_info(), configs, ) .into() } #[turbo_tasks::function] fn edge_transition_map( server_addr: ServerAddrVc, project_path: FileSystemPathVc, output_path: FileSystemPathVc, next_config: NextConfigVc, execution_context: ExecutionContextVc, ) -> TransitionsByNameVc { let edge_compile_time_info = get_edge_compile_time_info(server_addr, Value::new(Middleware)); let edge_chunking_context = DevChunkingContextVc::builder( project_path, output_path.join("edge"), output_path.join("edge/chunks"), output_path.join("edge/assets"), edge_compile_time_info.environment(), ) .build(); let edge_resolve_options_context = get_edge_resolve_options_context( project_path, Value::new(ServerContextType::Middleware), next_config, execution_context, ); let server_module_options_context = get_server_module_options_context( project_path, execution_context, Value::new(ServerContextType::Middleware), next_config, ); let next_edge_transition = NextEdgeTransition { edge_compile_time_info, edge_chunking_context, edge_module_options_context: Some(server_module_options_context), edge_resolve_options_context, output_path: output_path.root(), base_path: project_path, bootstrap_file: next_js_file("entry/edge-bootstrap.ts"), entry_name: "middleware".to_string(), } .cell() .into(); TransitionsByNameVc::cell( [("next-edge".to_string(), next_edge_transition)] .into_iter() .collect(), ) } #[turbo_tasks::function] pub async fn route( execution_context: ExecutionContextVc, request: RouterRequestVc, next_config: NextConfigVc, server_addr: ServerAddrVc, routes_changed: CompletionVc, ) -> Result<RouterResultVc> { let RouterRequest { ref method, ref pathname, .. } = *request.await?; IssueVc::attach_description( format!("Next.js Routing for {} {}", method, pathname), route_internal( execution_context, request, next_config, server_addr, routes_changed, ), ) .await } #[turbo_tasks::function] async fn route_internal( execution_context: ExecutionContextVc, request: RouterRequestVc, next_config: NextConfigVc, server_addr: ServerAddrVc, routes_changed: CompletionVc, ) -> Result<RouterResultVc> { let ExecutionContext { project_path, chunking_context, env, } = *execution_context.await?; let context = node_evaluate_asset_context( project_path, Some(get_next_build_import_map()), Some(edge_transition_map( server_addr, project_path, chunking_context.output_root(), next_config, execution_context, )), ); let configs = config_assets(context, project_path, next_config.page_extensions()); let router_asset = route_executor(context, configs); // This invalidates the router when the next config changes let next_config_changed = next_config_changed(context, project_path); let request = serde_json::value::to_value(&*request.await?)?; let Some(dir) = to_sys_path(project_path).await? else { bail!("Next.js requires a disk path to check for valid routes");
AssetIdentVc::from_path(project_path), context, chunking_context.with_layer("router"), None, vec![ JsonValueVc::cell(request), JsonValueVc::cell(dir.to_string_lossy().into()), ], CompletionsVc::all(vec![next_config_changed, routes_changed]), /* debug */ false, ) .await?; match &*result { JavaScriptValue::Value(val) => { let result: RouterIncomingMessage = parse_json_rope_with_source_context(val)?; Ok(RouterResult::from(result).cell()) } JavaScriptValue::Error => Ok(RouterResult::Error.cell()), JavaScriptValue::Stream(_) => { unimplemented!("Stream not supported now"); } } }
}; let result = evaluate( router_asset, project_path, env,
random_line_split
minimize.rs
use std::cmp::max; use std::cmp::Ordering; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; use std::marker::PhantomData; use anyhow::Result; use binary_heap_plus::BinaryHeap; use stable_bst::TreeMap; use crate::algorithms::encode::EncodeType; use crate::algorithms::factor_weight::factor_iterators::GallicFactorLeft; use crate::algorithms::factor_weight::{factor_weight, FactorWeightOptions, FactorWeightType}; use crate::algorithms::partition::Partition; use crate::algorithms::queues::LifoQueue; use crate::algorithms::tr_compares::ILabelCompare; use crate::algorithms::tr_mappers::QuantizeMapper; use crate::algorithms::tr_unique; use crate::algorithms::weight_converters::{FromGallicConverter, ToGallicConverter}; use crate::algorithms::Queue; use crate::algorithms::{ connect, encode::{decode, encode}, tr_map, tr_sort, weight_convert, ReweightType, }; use crate::algorithms::{push_weights_with_config, reverse, PushWeightsConfig}; use crate::fst_impls::VectorFst; use crate::fst_properties::FstProperties; use crate::fst_traits::{AllocableFst, CoreFst, ExpandedFst, Fst, MutableFst}; use crate::semirings::{ GallicWeightLeft, Semiring, SemiringProperties, WeaklyDivisibleSemiring, WeightQuantize, }; use crate::EPS_LABEL; use crate::KDELTA; use crate::NO_STATE_ID; use crate::{Label, StateId, Trs}; use crate::{Tr, KSHORTESTDELTA}; use itertools::Itertools; #[derive(Clone, Copy, PartialOrd, PartialEq)] pub struct MinimizeConfig { delta: f32, allow_nondet: bool, } impl MinimizeConfig { pub fn new(delta: f32, allow_nondet: bool) -> Self { Self { delta, allow_nondet, } } pub fn with_delta(self, delta: f32) -> Self { Self { delta, ..self } } pub fn with_allow_nondet(self, allow_nondet: bool) -> Self { Self { allow_nondet, ..self } } } impl Default for MinimizeConfig { fn default() -> Self { Self { delta: KSHORTESTDELTA, allow_nondet: false, } } } /// In place minimization of deterministic weighted automata and transducers, /// and also non-deterministic ones if they use an idempotent semiring. /// For transducers, the algorithm produces a compact factorization of the minimal transducer. pub fn minimize<W, F>(ifst: &mut F) -> Result<()> where F: MutableFst<W> + ExpandedFst<W> + AllocableFst<W>, W: WeaklyDivisibleSemiring + WeightQuantize, W::ReverseWeight: WeightQuantize, { minimize_with_config(ifst, MinimizeConfig::default()) } /// In place minimization of deterministic weighted automata and transducers,
W: WeaklyDivisibleSemiring + WeightQuantize, W::ReverseWeight: WeightQuantize, { let delta = config.delta; let allow_nondet = config.allow_nondet; let props = ifst.compute_and_update_properties( FstProperties::ACCEPTOR | FstProperties::I_DETERMINISTIC | FstProperties::WEIGHTED | FstProperties::UNWEIGHTED, )?; let allow_acyclic_minimization = if props.contains(FstProperties::I_DETERMINISTIC) { true } else { if !W::properties().contains(SemiringProperties::IDEMPOTENT) { bail!("Cannot minimize a non-deterministic FST over a non-idempotent semiring") } else if !allow_nondet { bail!("Refusing to minimize a non-deterministic FST with allow_nondet = false") } false }; if !props.contains(FstProperties::ACCEPTOR) { // Weighted transducer let mut to_gallic = ToGallicConverter {}; let mut gfst: VectorFst<GallicWeightLeft<W>> = weight_convert(ifst, &mut to_gallic)?; let push_weights_config = PushWeightsConfig::default().with_delta(delta); push_weights_with_config( &mut gfst, ReweightType::ReweightToInitial, push_weights_config, )?; let quantize_mapper = QuantizeMapper::new(delta); tr_map(&mut gfst, &quantize_mapper)?; let encode_table = encode(&mut gfst, EncodeType::EncodeWeightsAndLabels)?; acceptor_minimize(&mut gfst, allow_acyclic_minimization)?; decode(&mut gfst, encode_table)?; let factor_opts: FactorWeightOptions = FactorWeightOptions { delta: KDELTA, mode: FactorWeightType::FACTOR_FINAL_WEIGHTS | FactorWeightType::FACTOR_ARC_WEIGHTS, final_ilabel: 0, final_olabel: 0, increment_final_ilabel: false, increment_final_olabel: false, }; let fwfst: VectorFst<_> = factor_weight::<_, VectorFst<GallicWeightLeft<W>>, _, _, GallicFactorLeft<W>>( &gfst, factor_opts, )?; let mut from_gallic = FromGallicConverter { superfinal_label: EPS_LABEL, }; *ifst = weight_convert(&fwfst, &mut from_gallic)?; Ok(()) } else if props.contains(FstProperties::WEIGHTED) { // Weighted acceptor let push_weights_config = PushWeightsConfig::default().with_delta(delta); push_weights_with_config(ifst, ReweightType::ReweightToInitial, push_weights_config)?; let quantize_mapper = QuantizeMapper::new(delta); tr_map(ifst, &quantize_mapper)?; let encode_table = encode(ifst, EncodeType::EncodeWeightsAndLabels)?; acceptor_minimize(ifst, allow_acyclic_minimization)?; decode(ifst, encode_table) } else { // Unweighted acceptor acceptor_minimize(ifst, allow_acyclic_minimization) } } /// In place minimization for weighted final state acceptor. /// If `allow_acyclic_minimization` is true and the input is acyclic, then a specific /// minimization is applied. /// /// An error is returned if the input fst is not a weighted acceptor. pub fn acceptor_minimize<W: Semiring, F: MutableFst<W> + ExpandedFst<W>>( ifst: &mut F, allow_acyclic_minimization: bool, ) -> Result<()> { let props = ifst.compute_and_update_properties( FstProperties::ACCEPTOR | FstProperties::UNWEIGHTED | FstProperties::ACYCLIC, )?; if !props.contains(FstProperties::ACCEPTOR | FstProperties::UNWEIGHTED) { bail!("FST is not an unweighted acceptor"); } connect(ifst)?; if ifst.num_states() == 0 { return Ok(()); } if allow_acyclic_minimization && props.contains(FstProperties::ACYCLIC) { // Acyclic minimization tr_sort(ifst, ILabelCompare {}); let minimizer = AcyclicMinimizer::new(ifst)?; merge_states(minimizer.get_partition(), ifst)?; } else { let p = cyclic_minimize(ifst)?; merge_states(p, ifst)?; } tr_unique(ifst); Ok(()) } fn merge_states<W: Semiring, F: MutableFst<W>>(partition: Partition, fst: &mut F) -> Result<()> { let mut state_map = vec![None; partition.num_classes()]; for (i, s) in state_map .iter_mut() .enumerate() .take(partition.num_classes()) { *s = partition.iter(i).next(); } for c in 0..partition.num_classes() { for s in partition.iter(c) { if s == state_map[c].unwrap() { let mut it_tr = fst.tr_iter_mut(s as StateId)?; for idx_tr in 0..it_tr.len() { let tr = unsafe { it_tr.get_unchecked(idx_tr) }; let nextstate = state_map[partition.get_class_id(tr.nextstate as usize)].unwrap(); unsafe { it_tr.set_nextstate_unchecked(idx_tr, nextstate as StateId) }; } } else { let trs: Vec<_> = fst .get_trs(s as StateId)? .trs() .iter() .cloned() .map(|mut tr| { tr.nextstate = state_map[partition.get_class_id(tr.nextstate as usize)] .unwrap() as StateId; tr }) .collect(); for tr in trs.into_iter() { fst.add_tr(state_map[c].unwrap() as StateId, tr)?; } } } } fst.set_start( state_map[partition.get_class_id(fst.start().unwrap() as usize) as usize].unwrap() as StateId, )?; connect(fst)?; Ok(()) } // Compute the height (distance) to final state pub fn fst_depth<W: Semiring, F: Fst<W>>( fst: &F, state_id_cour: StateId, accessible_states: &mut HashSet<StateId>, fully_examined_states: &mut HashSet<StateId>, heights: &mut Vec<i32>, ) -> Result<()> { accessible_states.insert(state_id_cour); for _ in heights.len()..=(state_id_cour as usize) { heights.push(-1); } let mut height_cur_state = 0; for tr in fst.get_trs(state_id_cour)?.trs() { let nextstate = tr.nextstate; if !accessible_states.contains(&nextstate) { fst_depth( fst, nextstate, accessible_states, fully_examined_states, heights, )?; } height_cur_state = max(height_cur_state, 1 + heights[nextstate as usize]); } fully_examined_states.insert(state_id_cour); heights[state_id_cour as usize] = height_cur_state; Ok(()) } struct AcyclicMinimizer { partition: Partition, } impl AcyclicMinimizer { pub fn new<W: Semiring, F: MutableFst<W>>(fst: &mut F) -> Result<Self> { let mut c = Self { partition: Partition::empty_new(), }; c.initialize(fst)?; c.refine(fst); Ok(c) } fn initialize<W: Semiring, F: MutableFst<W>>(&mut self, fst: &mut F) -> Result<()> { let mut accessible_state = HashSet::new(); let mut fully_examined_states = HashSet::new(); let mut heights = Vec::new(); fst_depth( fst, fst.start().unwrap(), &mut accessible_state, &mut fully_examined_states, &mut heights, )?; self.partition.initialize(heights.len()); self.partition .allocate_classes((heights.iter().max().unwrap() + 1) as usize); for (s, h) in heights.iter().enumerate() { self.partition.add(s, *h as usize); } Ok(()) } fn refine<W: Semiring, F: MutableFst<W>>(&mut self, fst: &mut F) { let state_cmp = StateComparator { fst, // This clone is necessary for the moment because the partition is modified while // still needing the StateComparator. // TODO: Find a way to remove the clone. partition: self.partition.clone(), w: PhantomData, }; let height = self.partition.num_classes(); for h in 0..height { // We need here a binary search tree in order to order the states id and create a partition. // For now uses the crate `stable_bst` which is quite old but seems to do the job // TODO: Bench the performances of the implementation. Maybe re-write it. let mut equiv_classes = TreeMap::<StateId, StateId, _>::with_comparator(|a: &StateId, b: &StateId| { state_cmp.compare(*a, *b).unwrap() }); let it_partition: Vec<_> = self.partition.iter(h).collect(); equiv_classes.insert(it_partition[0] as StateId, h as StateId); let mut classes_to_add = vec![]; for e in it_partition.iter().skip(1) { // TODO: Remove double lookup if equiv_classes.contains_key(&(*e as StateId)) { equiv_classes.insert(*e as StateId, NO_STATE_ID); } else { classes_to_add.push(e); equiv_classes.insert(*e as StateId, NO_STATE_ID); } } for v in classes_to_add { equiv_classes.insert(*v as StateId, self.partition.add_class() as StateId); } for s in it_partition { let old_class = self.partition.get_class_id(s); let new_class = *equiv_classes.get(&(s as StateId)).unwrap(); if new_class == NO_STATE_ID { // The behaviour here is a bit different compared to the c++ because here // when inserting an equivalent key it modifies the key // which is not the case in c++. continue; } if old_class != (new_class as usize) { self.partition.move_element(s, new_class as usize); } } } } pub fn get_partition(self) -> Partition { self.partition } } struct StateComparator<'a, W: Semiring, F: MutableFst<W>> { fst: &'a F, partition: Partition, w: PhantomData<W>, } impl<'a, W: Semiring, F: MutableFst<W>> StateComparator<'a, W, F> { fn do_compare(&self, x: StateId, y: StateId) -> Result<bool> { let xfinal = self.fst.final_weight(x)?.unwrap_or_else(W::zero); let yfinal = self.fst.final_weight(y)?.unwrap_or_else(W::zero); if xfinal < yfinal { return Ok(true); } else if xfinal > yfinal { return Ok(false); } if self.fst.num_trs(x)? < self.fst.num_trs(y)? { return Ok(true); } if self.fst.num_trs(x)? > self.fst.num_trs(y)? { return Ok(false); } let it_x_owner = self.fst.get_trs(x)?; let it_x = it_x_owner.trs().iter(); let it_y_owner = self.fst.get_trs(y)?; let it_y = it_y_owner.trs().iter(); for (arc1, arc2) in it_x.zip(it_y) { if arc1.ilabel < arc2.ilabel { return Ok(true); } if arc1.ilabel > arc2.ilabel { return Ok(false); } let id_1 = self.partition.get_class_id(arc1.nextstate as usize); let id_2 = self.partition.get_class_id(arc2.nextstate as usize); if id_1 < id_2 { return Ok(true); } if id_1 > id_2 { return Ok(false); } } Ok(false) } pub fn compare(&self, x: StateId, y: StateId) -> Result<Ordering> { if x == y { return Ok(Ordering::Equal); } let x_y = self.do_compare(x, y).unwrap(); let y_x = self.do_compare(y, x).unwrap(); if !(x_y) && !(y_x) { return Ok(Ordering::Equal); } if x_y { Ok(Ordering::Less) } else { Ok(Ordering::Greater) } } } fn pre_partition<W: Semiring, F: MutableFst<W>>( fst: &F, partition: &mut Partition, queue: &mut LifoQueue, ) { let mut next_class: StateId = 0; let num_states = fst.num_states(); let mut state_to_initial_class: Vec<StateId> = vec![0; num_states]; { let mut hash_to_class_nonfinal = HashMap::<Vec<Label>, StateId>::new(); let mut hash_to_class_final = HashMap::<Vec<Label>, StateId>::new(); for (s, state_to_initial_class_s) in state_to_initial_class .iter_mut() .enumerate() .take(num_states) { let this_map = if unsafe { fst.is_final_unchecked(s as StateId) } { &mut hash_to_class_final } else { &mut hash_to_class_nonfinal }; let ilabels = fst .get_trs(s as StateId) .unwrap() .trs() .iter() .map(|e| e.ilabel) .dedup() .collect_vec(); match this_map.entry(ilabels) { Entry::Occupied(e) => { *state_to_initial_class_s = *e.get(); } Entry::Vacant(e) => { e.insert(next_class); *state_to_initial_class_s = next_class; next_class += 1; } }; } } partition.allocate_classes(next_class as usize); for (s, c) in state_to_initial_class.iter().enumerate().take(num_states) { partition.add(s, *c as usize); } for c in 0..next_class { queue.enqueue(c); } } fn cyclic_minimize<W: Semiring, F: MutableFst<W>>(fst: &mut F) -> Result<Partition> { // Initialize let mut tr: VectorFst<W::ReverseWeight> = reverse(fst)?; tr_sort(&mut tr, ILabelCompare {}); let mut partition = Partition::new(tr.num_states() - 1); let mut queue = LifoQueue::default(); pre_partition(fst, &mut partition, &mut queue); // Compute while let Some(c) = queue.head() { queue.dequeue(); // Split // TODO: Avoid this clone :o // Here we need to pointer to the partition that is valid even if the partition changes. let comp = TrIterCompare { partition: partition.clone(), }; let mut aiter_queue = BinaryHeap::new_by(|v1, v2| { if comp.compare(v1, v2) { Ordering::Less } else { Ordering::Greater } }); // Split for s in partition.iter(c as usize) { if tr.num_trs(s as StateId + 1)? > 0 { aiter_queue.push(TrsIterCollected { idx: 0, trs: tr.get_trs(s as StateId + 1)?, w: PhantomData, }); } } let mut prev_label = -1; while !aiter_queue.is_empty() { let mut aiter = aiter_queue.pop().unwrap(); if aiter.done() { continue; } let tr = aiter.peek().unwrap(); let from_state = tr.nextstate - 1; let from_label = tr.ilabel; if prev_label != from_label as i32 { partition.finalize_split(&mut Some(&mut queue)); } let from_class = partition.get_class_id(from_state as usize); if partition.get_class_size(from_class) > 1 { partition.split_on(from_state as usize); } prev_label = from_label as i32; aiter.next(); if !aiter.done() { aiter_queue.push(aiter); } } partition.finalize_split(&mut Some(&mut queue)); } // Get Partition Ok(partition) } struct TrsIterCollected<W: Semiring, T: Trs<W>> { idx: usize, trs: T, w: PhantomData<W>, } impl<W: Semiring, T: Trs<W>> TrsIterCollected<W, T> { fn peek(&self) -> Option<&Tr<W>> { self.trs.trs().get(self.idx) } fn done(&self) -> bool { self.idx >= self.trs.len() } fn next(&mut self) { self.idx += 1; } } #[derive(Clone)] struct TrIterCompare { partition: Partition, } impl TrIterCompare { fn compare<W: Semiring, T: Trs<W>>( &self, x: &TrsIterCollected<W, T>, y: &TrsIterCollected<W, T>, ) -> bool where W: Semiring, { let xarc = x.peek().unwrap(); let yarc = y.peek().unwrap(); xarc.ilabel > yarc.ilabel } } #[cfg(test)] mod tests { use crate::prelude::*; use algorithms::determinize::*; use proptest::prelude::*; proptest! { #![proptest_config(ProptestConfig { fork: true, timeout: 100, .. ProptestConfig::default() })] #[test] #[ignore] fn proptest_minimize_timeout(mut fst in any::<VectorFst::<TropicalWeight>>()) { let config = MinimizeConfig::default().with_allow_nondet(true); minimize_with_config(&mut fst, config).unwrap(); } } proptest! { #[test] #[ignore] // falls into the same infinite loop as the timeout test fn test_minimize_proptest(mut fst in any::<VectorFst::<TropicalWeight>>()) { let det:VectorFst<_> = determinize(&fst).unwrap(); let min_config = MinimizeConfig::default().with_allow_nondet(true); minimize_with_config(&mut fst, min_config).unwrap(); let det_config = DeterminizeConfig::default().with_det_type(DeterminizeType::DeterminizeNonFunctional); let min_det:VectorFst<_> = determinize_with_config(&fst, det_config).unwrap(); prop_assert!(isomorphic(&det, &min_det).unwrap()) } } }
/// and also non-deterministic ones if they use an idempotent semiring. /// For transducers, the algorithm produces a compact factorization of the minimal transducer. pub fn minimize_with_config<W, F>(ifst: &mut F, config: MinimizeConfig) -> Result<()> where F: MutableFst<W> + ExpandedFst<W> + AllocableFst<W>,
random_line_split
minimize.rs
use std::cmp::max; use std::cmp::Ordering; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; use std::marker::PhantomData; use anyhow::Result; use binary_heap_plus::BinaryHeap; use stable_bst::TreeMap; use crate::algorithms::encode::EncodeType; use crate::algorithms::factor_weight::factor_iterators::GallicFactorLeft; use crate::algorithms::factor_weight::{factor_weight, FactorWeightOptions, FactorWeightType}; use crate::algorithms::partition::Partition; use crate::algorithms::queues::LifoQueue; use crate::algorithms::tr_compares::ILabelCompare; use crate::algorithms::tr_mappers::QuantizeMapper; use crate::algorithms::tr_unique; use crate::algorithms::weight_converters::{FromGallicConverter, ToGallicConverter}; use crate::algorithms::Queue; use crate::algorithms::{ connect, encode::{decode, encode}, tr_map, tr_sort, weight_convert, ReweightType, }; use crate::algorithms::{push_weights_with_config, reverse, PushWeightsConfig}; use crate::fst_impls::VectorFst; use crate::fst_properties::FstProperties; use crate::fst_traits::{AllocableFst, CoreFst, ExpandedFst, Fst, MutableFst}; use crate::semirings::{ GallicWeightLeft, Semiring, SemiringProperties, WeaklyDivisibleSemiring, WeightQuantize, }; use crate::EPS_LABEL; use crate::KDELTA; use crate::NO_STATE_ID; use crate::{Label, StateId, Trs}; use crate::{Tr, KSHORTESTDELTA}; use itertools::Itertools; #[derive(Clone, Copy, PartialOrd, PartialEq)] pub struct MinimizeConfig { delta: f32, allow_nondet: bool, } impl MinimizeConfig { pub fn new(delta: f32, allow_nondet: bool) -> Self { Self { delta, allow_nondet, } } pub fn with_delta(self, delta: f32) -> Self { Self { delta, ..self } } pub fn with_allow_nondet(self, allow_nondet: bool) -> Self { Self { allow_nondet, ..self } } } impl Default for MinimizeConfig { fn default() -> Self { Self { delta: KSHORTESTDELTA, allow_nondet: false, } } } /// In place minimization of deterministic weighted automata and transducers, /// and also non-deterministic ones if they use an idempotent semiring. /// For transducers, the algorithm produces a compact factorization of the minimal transducer. pub fn minimize<W, F>(ifst: &mut F) -> Result<()> where F: MutableFst<W> + ExpandedFst<W> + AllocableFst<W>, W: WeaklyDivisibleSemiring + WeightQuantize, W::ReverseWeight: WeightQuantize, { minimize_with_config(ifst, MinimizeConfig::default()) } /// In place minimization of deterministic weighted automata and transducers, /// and also non-deterministic ones if they use an idempotent semiring. /// For transducers, the algorithm produces a compact factorization of the minimal transducer. pub fn minimize_with_config<W, F>(ifst: &mut F, config: MinimizeConfig) -> Result<()> where F: MutableFst<W> + ExpandedFst<W> + AllocableFst<W>, W: WeaklyDivisibleSemiring + WeightQuantize, W::ReverseWeight: WeightQuantize, { let delta = config.delta; let allow_nondet = config.allow_nondet; let props = ifst.compute_and_update_properties( FstProperties::ACCEPTOR | FstProperties::I_DETERMINISTIC | FstProperties::WEIGHTED | FstProperties::UNWEIGHTED, )?; let allow_acyclic_minimization = if props.contains(FstProperties::I_DETERMINISTIC) { true } else { if !W::properties().contains(SemiringProperties::IDEMPOTENT) { bail!("Cannot minimize a non-deterministic FST over a non-idempotent semiring") } else if !allow_nondet { bail!("Refusing to minimize a non-deterministic FST with allow_nondet = false") } false }; if !props.contains(FstProperties::ACCEPTOR) { // Weighted transducer let mut to_gallic = ToGallicConverter {}; let mut gfst: VectorFst<GallicWeightLeft<W>> = weight_convert(ifst, &mut to_gallic)?; let push_weights_config = PushWeightsConfig::default().with_delta(delta); push_weights_with_config( &mut gfst, ReweightType::ReweightToInitial, push_weights_config, )?; let quantize_mapper = QuantizeMapper::new(delta); tr_map(&mut gfst, &quantize_mapper)?; let encode_table = encode(&mut gfst, EncodeType::EncodeWeightsAndLabels)?; acceptor_minimize(&mut gfst, allow_acyclic_minimization)?; decode(&mut gfst, encode_table)?; let factor_opts: FactorWeightOptions = FactorWeightOptions { delta: KDELTA, mode: FactorWeightType::FACTOR_FINAL_WEIGHTS | FactorWeightType::FACTOR_ARC_WEIGHTS, final_ilabel: 0, final_olabel: 0, increment_final_ilabel: false, increment_final_olabel: false, }; let fwfst: VectorFst<_> = factor_weight::<_, VectorFst<GallicWeightLeft<W>>, _, _, GallicFactorLeft<W>>( &gfst, factor_opts, )?; let mut from_gallic = FromGallicConverter { superfinal_label: EPS_LABEL, }; *ifst = weight_convert(&fwfst, &mut from_gallic)?; Ok(()) } else if props.contains(FstProperties::WEIGHTED) { // Weighted acceptor let push_weights_config = PushWeightsConfig::default().with_delta(delta); push_weights_with_config(ifst, ReweightType::ReweightToInitial, push_weights_config)?; let quantize_mapper = QuantizeMapper::new(delta); tr_map(ifst, &quantize_mapper)?; let encode_table = encode(ifst, EncodeType::EncodeWeightsAndLabels)?; acceptor_minimize(ifst, allow_acyclic_minimization)?; decode(ifst, encode_table) } else { // Unweighted acceptor acceptor_minimize(ifst, allow_acyclic_minimization) } } /// In place minimization for weighted final state acceptor. /// If `allow_acyclic_minimization` is true and the input is acyclic, then a specific /// minimization is applied. /// /// An error is returned if the input fst is not a weighted acceptor. pub fn
<W: Semiring, F: MutableFst<W> + ExpandedFst<W>>( ifst: &mut F, allow_acyclic_minimization: bool, ) -> Result<()> { let props = ifst.compute_and_update_properties( FstProperties::ACCEPTOR | FstProperties::UNWEIGHTED | FstProperties::ACYCLIC, )?; if !props.contains(FstProperties::ACCEPTOR | FstProperties::UNWEIGHTED) { bail!("FST is not an unweighted acceptor"); } connect(ifst)?; if ifst.num_states() == 0 { return Ok(()); } if allow_acyclic_minimization && props.contains(FstProperties::ACYCLIC) { // Acyclic minimization tr_sort(ifst, ILabelCompare {}); let minimizer = AcyclicMinimizer::new(ifst)?; merge_states(minimizer.get_partition(), ifst)?; } else { let p = cyclic_minimize(ifst)?; merge_states(p, ifst)?; } tr_unique(ifst); Ok(()) } fn merge_states<W: Semiring, F: MutableFst<W>>(partition: Partition, fst: &mut F) -> Result<()> { let mut state_map = vec![None; partition.num_classes()]; for (i, s) in state_map .iter_mut() .enumerate() .take(partition.num_classes()) { *s = partition.iter(i).next(); } for c in 0..partition.num_classes() { for s in partition.iter(c) { if s == state_map[c].unwrap() { let mut it_tr = fst.tr_iter_mut(s as StateId)?; for idx_tr in 0..it_tr.len() { let tr = unsafe { it_tr.get_unchecked(idx_tr) }; let nextstate = state_map[partition.get_class_id(tr.nextstate as usize)].unwrap(); unsafe { it_tr.set_nextstate_unchecked(idx_tr, nextstate as StateId) }; } } else { let trs: Vec<_> = fst .get_trs(s as StateId)? .trs() .iter() .cloned() .map(|mut tr| { tr.nextstate = state_map[partition.get_class_id(tr.nextstate as usize)] .unwrap() as StateId; tr }) .collect(); for tr in trs.into_iter() { fst.add_tr(state_map[c].unwrap() as StateId, tr)?; } } } } fst.set_start( state_map[partition.get_class_id(fst.start().unwrap() as usize) as usize].unwrap() as StateId, )?; connect(fst)?; Ok(()) } // Compute the height (distance) to final state pub fn fst_depth<W: Semiring, F: Fst<W>>( fst: &F, state_id_cour: StateId, accessible_states: &mut HashSet<StateId>, fully_examined_states: &mut HashSet<StateId>, heights: &mut Vec<i32>, ) -> Result<()> { accessible_states.insert(state_id_cour); for _ in heights.len()..=(state_id_cour as usize) { heights.push(-1); } let mut height_cur_state = 0; for tr in fst.get_trs(state_id_cour)?.trs() { let nextstate = tr.nextstate; if !accessible_states.contains(&nextstate) { fst_depth( fst, nextstate, accessible_states, fully_examined_states, heights, )?; } height_cur_state = max(height_cur_state, 1 + heights[nextstate as usize]); } fully_examined_states.insert(state_id_cour); heights[state_id_cour as usize] = height_cur_state; Ok(()) } struct AcyclicMinimizer { partition: Partition, } impl AcyclicMinimizer { pub fn new<W: Semiring, F: MutableFst<W>>(fst: &mut F) -> Result<Self> { let mut c = Self { partition: Partition::empty_new(), }; c.initialize(fst)?; c.refine(fst); Ok(c) } fn initialize<W: Semiring, F: MutableFst<W>>(&mut self, fst: &mut F) -> Result<()> { let mut accessible_state = HashSet::new(); let mut fully_examined_states = HashSet::new(); let mut heights = Vec::new(); fst_depth( fst, fst.start().unwrap(), &mut accessible_state, &mut fully_examined_states, &mut heights, )?; self.partition.initialize(heights.len()); self.partition .allocate_classes((heights.iter().max().unwrap() + 1) as usize); for (s, h) in heights.iter().enumerate() { self.partition.add(s, *h as usize); } Ok(()) } fn refine<W: Semiring, F: MutableFst<W>>(&mut self, fst: &mut F) { let state_cmp = StateComparator { fst, // This clone is necessary for the moment because the partition is modified while // still needing the StateComparator. // TODO: Find a way to remove the clone. partition: self.partition.clone(), w: PhantomData, }; let height = self.partition.num_classes(); for h in 0..height { // We need here a binary search tree in order to order the states id and create a partition. // For now uses the crate `stable_bst` which is quite old but seems to do the job // TODO: Bench the performances of the implementation. Maybe re-write it. let mut equiv_classes = TreeMap::<StateId, StateId, _>::with_comparator(|a: &StateId, b: &StateId| { state_cmp.compare(*a, *b).unwrap() }); let it_partition: Vec<_> = self.partition.iter(h).collect(); equiv_classes.insert(it_partition[0] as StateId, h as StateId); let mut classes_to_add = vec![]; for e in it_partition.iter().skip(1) { // TODO: Remove double lookup if equiv_classes.contains_key(&(*e as StateId)) { equiv_classes.insert(*e as StateId, NO_STATE_ID); } else { classes_to_add.push(e); equiv_classes.insert(*e as StateId, NO_STATE_ID); } } for v in classes_to_add { equiv_classes.insert(*v as StateId, self.partition.add_class() as StateId); } for s in it_partition { let old_class = self.partition.get_class_id(s); let new_class = *equiv_classes.get(&(s as StateId)).unwrap(); if new_class == NO_STATE_ID { // The behaviour here is a bit different compared to the c++ because here // when inserting an equivalent key it modifies the key // which is not the case in c++. continue; } if old_class != (new_class as usize) { self.partition.move_element(s, new_class as usize); } } } } pub fn get_partition(self) -> Partition { self.partition } } struct StateComparator<'a, W: Semiring, F: MutableFst<W>> { fst: &'a F, partition: Partition, w: PhantomData<W>, } impl<'a, W: Semiring, F: MutableFst<W>> StateComparator<'a, W, F> { fn do_compare(&self, x: StateId, y: StateId) -> Result<bool> { let xfinal = self.fst.final_weight(x)?.unwrap_or_else(W::zero); let yfinal = self.fst.final_weight(y)?.unwrap_or_else(W::zero); if xfinal < yfinal { return Ok(true); } else if xfinal > yfinal { return Ok(false); } if self.fst.num_trs(x)? < self.fst.num_trs(y)? { return Ok(true); } if self.fst.num_trs(x)? > self.fst.num_trs(y)? { return Ok(false); } let it_x_owner = self.fst.get_trs(x)?; let it_x = it_x_owner.trs().iter(); let it_y_owner = self.fst.get_trs(y)?; let it_y = it_y_owner.trs().iter(); for (arc1, arc2) in it_x.zip(it_y) { if arc1.ilabel < arc2.ilabel { return Ok(true); } if arc1.ilabel > arc2.ilabel { return Ok(false); } let id_1 = self.partition.get_class_id(arc1.nextstate as usize); let id_2 = self.partition.get_class_id(arc2.nextstate as usize); if id_1 < id_2 { return Ok(true); } if id_1 > id_2 { return Ok(false); } } Ok(false) } pub fn compare(&self, x: StateId, y: StateId) -> Result<Ordering> { if x == y { return Ok(Ordering::Equal); } let x_y = self.do_compare(x, y).unwrap(); let y_x = self.do_compare(y, x).unwrap(); if !(x_y) && !(y_x) { return Ok(Ordering::Equal); } if x_y { Ok(Ordering::Less) } else { Ok(Ordering::Greater) } } } fn pre_partition<W: Semiring, F: MutableFst<W>>( fst: &F, partition: &mut Partition, queue: &mut LifoQueue, ) { let mut next_class: StateId = 0; let num_states = fst.num_states(); let mut state_to_initial_class: Vec<StateId> = vec![0; num_states]; { let mut hash_to_class_nonfinal = HashMap::<Vec<Label>, StateId>::new(); let mut hash_to_class_final = HashMap::<Vec<Label>, StateId>::new(); for (s, state_to_initial_class_s) in state_to_initial_class .iter_mut() .enumerate() .take(num_states) { let this_map = if unsafe { fst.is_final_unchecked(s as StateId) } { &mut hash_to_class_final } else { &mut hash_to_class_nonfinal }; let ilabels = fst .get_trs(s as StateId) .unwrap() .trs() .iter() .map(|e| e.ilabel) .dedup() .collect_vec(); match this_map.entry(ilabels) { Entry::Occupied(e) => { *state_to_initial_class_s = *e.get(); } Entry::Vacant(e) => { e.insert(next_class); *state_to_initial_class_s = next_class; next_class += 1; } }; } } partition.allocate_classes(next_class as usize); for (s, c) in state_to_initial_class.iter().enumerate().take(num_states) { partition.add(s, *c as usize); } for c in 0..next_class { queue.enqueue(c); } } fn cyclic_minimize<W: Semiring, F: MutableFst<W>>(fst: &mut F) -> Result<Partition> { // Initialize let mut tr: VectorFst<W::ReverseWeight> = reverse(fst)?; tr_sort(&mut tr, ILabelCompare {}); let mut partition = Partition::new(tr.num_states() - 1); let mut queue = LifoQueue::default(); pre_partition(fst, &mut partition, &mut queue); // Compute while let Some(c) = queue.head() { queue.dequeue(); // Split // TODO: Avoid this clone :o // Here we need to pointer to the partition that is valid even if the partition changes. let comp = TrIterCompare { partition: partition.clone(), }; let mut aiter_queue = BinaryHeap::new_by(|v1, v2| { if comp.compare(v1, v2) { Ordering::Less } else { Ordering::Greater } }); // Split for s in partition.iter(c as usize) { if tr.num_trs(s as StateId + 1)? > 0 { aiter_queue.push(TrsIterCollected { idx: 0, trs: tr.get_trs(s as StateId + 1)?, w: PhantomData, }); } } let mut prev_label = -1; while !aiter_queue.is_empty() { let mut aiter = aiter_queue.pop().unwrap(); if aiter.done() { continue; } let tr = aiter.peek().unwrap(); let from_state = tr.nextstate - 1; let from_label = tr.ilabel; if prev_label != from_label as i32 { partition.finalize_split(&mut Some(&mut queue)); } let from_class = partition.get_class_id(from_state as usize); if partition.get_class_size(from_class) > 1 { partition.split_on(from_state as usize); } prev_label = from_label as i32; aiter.next(); if !aiter.done() { aiter_queue.push(aiter); } } partition.finalize_split(&mut Some(&mut queue)); } // Get Partition Ok(partition) } struct TrsIterCollected<W: Semiring, T: Trs<W>> { idx: usize, trs: T, w: PhantomData<W>, } impl<W: Semiring, T: Trs<W>> TrsIterCollected<W, T> { fn peek(&self) -> Option<&Tr<W>> { self.trs.trs().get(self.idx) } fn done(&self) -> bool { self.idx >= self.trs.len() } fn next(&mut self) { self.idx += 1; } } #[derive(Clone)] struct TrIterCompare { partition: Partition, } impl TrIterCompare { fn compare<W: Semiring, T: Trs<W>>( &self, x: &TrsIterCollected<W, T>, y: &TrsIterCollected<W, T>, ) -> bool where W: Semiring, { let xarc = x.peek().unwrap(); let yarc = y.peek().unwrap(); xarc.ilabel > yarc.ilabel } } #[cfg(test)] mod tests { use crate::prelude::*; use algorithms::determinize::*; use proptest::prelude::*; proptest! { #![proptest_config(ProptestConfig { fork: true, timeout: 100, .. ProptestConfig::default() })] #[test] #[ignore] fn proptest_minimize_timeout(mut fst in any::<VectorFst::<TropicalWeight>>()) { let config = MinimizeConfig::default().with_allow_nondet(true); minimize_with_config(&mut fst, config).unwrap(); } } proptest! { #[test] #[ignore] // falls into the same infinite loop as the timeout test fn test_minimize_proptest(mut fst in any::<VectorFst::<TropicalWeight>>()) { let det:VectorFst<_> = determinize(&fst).unwrap(); let min_config = MinimizeConfig::default().with_allow_nondet(true); minimize_with_config(&mut fst, min_config).unwrap(); let det_config = DeterminizeConfig::default().with_det_type(DeterminizeType::DeterminizeNonFunctional); let min_det:VectorFst<_> = determinize_with_config(&fst, det_config).unwrap(); prop_assert!(isomorphic(&det, &min_det).unwrap()) } } }
acceptor_minimize
identifier_name
minimize.rs
use std::cmp::max; use std::cmp::Ordering; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; use std::marker::PhantomData; use anyhow::Result; use binary_heap_plus::BinaryHeap; use stable_bst::TreeMap; use crate::algorithms::encode::EncodeType; use crate::algorithms::factor_weight::factor_iterators::GallicFactorLeft; use crate::algorithms::factor_weight::{factor_weight, FactorWeightOptions, FactorWeightType}; use crate::algorithms::partition::Partition; use crate::algorithms::queues::LifoQueue; use crate::algorithms::tr_compares::ILabelCompare; use crate::algorithms::tr_mappers::QuantizeMapper; use crate::algorithms::tr_unique; use crate::algorithms::weight_converters::{FromGallicConverter, ToGallicConverter}; use crate::algorithms::Queue; use crate::algorithms::{ connect, encode::{decode, encode}, tr_map, tr_sort, weight_convert, ReweightType, }; use crate::algorithms::{push_weights_with_config, reverse, PushWeightsConfig}; use crate::fst_impls::VectorFst; use crate::fst_properties::FstProperties; use crate::fst_traits::{AllocableFst, CoreFst, ExpandedFst, Fst, MutableFst}; use crate::semirings::{ GallicWeightLeft, Semiring, SemiringProperties, WeaklyDivisibleSemiring, WeightQuantize, }; use crate::EPS_LABEL; use crate::KDELTA; use crate::NO_STATE_ID; use crate::{Label, StateId, Trs}; use crate::{Tr, KSHORTESTDELTA}; use itertools::Itertools; #[derive(Clone, Copy, PartialOrd, PartialEq)] pub struct MinimizeConfig { delta: f32, allow_nondet: bool, } impl MinimizeConfig { pub fn new(delta: f32, allow_nondet: bool) -> Self { Self { delta, allow_nondet, } } pub fn with_delta(self, delta: f32) -> Self { Self { delta, ..self } } pub fn with_allow_nondet(self, allow_nondet: bool) -> Self { Self { allow_nondet, ..self } } } impl Default for MinimizeConfig { fn default() -> Self { Self { delta: KSHORTESTDELTA, allow_nondet: false, } } } /// In place minimization of deterministic weighted automata and transducers, /// and also non-deterministic ones if they use an idempotent semiring. /// For transducers, the algorithm produces a compact factorization of the minimal transducer. pub fn minimize<W, F>(ifst: &mut F) -> Result<()> where F: MutableFst<W> + ExpandedFst<W> + AllocableFst<W>, W: WeaklyDivisibleSemiring + WeightQuantize, W::ReverseWeight: WeightQuantize, { minimize_with_config(ifst, MinimizeConfig::default()) } /// In place minimization of deterministic weighted automata and transducers, /// and also non-deterministic ones if they use an idempotent semiring. /// For transducers, the algorithm produces a compact factorization of the minimal transducer. pub fn minimize_with_config<W, F>(ifst: &mut F, config: MinimizeConfig) -> Result<()> where F: MutableFst<W> + ExpandedFst<W> + AllocableFst<W>, W: WeaklyDivisibleSemiring + WeightQuantize, W::ReverseWeight: WeightQuantize, { let delta = config.delta; let allow_nondet = config.allow_nondet; let props = ifst.compute_and_update_properties( FstProperties::ACCEPTOR | FstProperties::I_DETERMINISTIC | FstProperties::WEIGHTED | FstProperties::UNWEIGHTED, )?; let allow_acyclic_minimization = if props.contains(FstProperties::I_DETERMINISTIC)
else { if !W::properties().contains(SemiringProperties::IDEMPOTENT) { bail!("Cannot minimize a non-deterministic FST over a non-idempotent semiring") } else if !allow_nondet { bail!("Refusing to minimize a non-deterministic FST with allow_nondet = false") } false }; if !props.contains(FstProperties::ACCEPTOR) { // Weighted transducer let mut to_gallic = ToGallicConverter {}; let mut gfst: VectorFst<GallicWeightLeft<W>> = weight_convert(ifst, &mut to_gallic)?; let push_weights_config = PushWeightsConfig::default().with_delta(delta); push_weights_with_config( &mut gfst, ReweightType::ReweightToInitial, push_weights_config, )?; let quantize_mapper = QuantizeMapper::new(delta); tr_map(&mut gfst, &quantize_mapper)?; let encode_table = encode(&mut gfst, EncodeType::EncodeWeightsAndLabels)?; acceptor_minimize(&mut gfst, allow_acyclic_minimization)?; decode(&mut gfst, encode_table)?; let factor_opts: FactorWeightOptions = FactorWeightOptions { delta: KDELTA, mode: FactorWeightType::FACTOR_FINAL_WEIGHTS | FactorWeightType::FACTOR_ARC_WEIGHTS, final_ilabel: 0, final_olabel: 0, increment_final_ilabel: false, increment_final_olabel: false, }; let fwfst: VectorFst<_> = factor_weight::<_, VectorFst<GallicWeightLeft<W>>, _, _, GallicFactorLeft<W>>( &gfst, factor_opts, )?; let mut from_gallic = FromGallicConverter { superfinal_label: EPS_LABEL, }; *ifst = weight_convert(&fwfst, &mut from_gallic)?; Ok(()) } else if props.contains(FstProperties::WEIGHTED) { // Weighted acceptor let push_weights_config = PushWeightsConfig::default().with_delta(delta); push_weights_with_config(ifst, ReweightType::ReweightToInitial, push_weights_config)?; let quantize_mapper = QuantizeMapper::new(delta); tr_map(ifst, &quantize_mapper)?; let encode_table = encode(ifst, EncodeType::EncodeWeightsAndLabels)?; acceptor_minimize(ifst, allow_acyclic_minimization)?; decode(ifst, encode_table) } else { // Unweighted acceptor acceptor_minimize(ifst, allow_acyclic_minimization) } } /// In place minimization for weighted final state acceptor. /// If `allow_acyclic_minimization` is true and the input is acyclic, then a specific /// minimization is applied. /// /// An error is returned if the input fst is not a weighted acceptor. pub fn acceptor_minimize<W: Semiring, F: MutableFst<W> + ExpandedFst<W>>( ifst: &mut F, allow_acyclic_minimization: bool, ) -> Result<()> { let props = ifst.compute_and_update_properties( FstProperties::ACCEPTOR | FstProperties::UNWEIGHTED | FstProperties::ACYCLIC, )?; if !props.contains(FstProperties::ACCEPTOR | FstProperties::UNWEIGHTED) { bail!("FST is not an unweighted acceptor"); } connect(ifst)?; if ifst.num_states() == 0 { return Ok(()); } if allow_acyclic_minimization && props.contains(FstProperties::ACYCLIC) { // Acyclic minimization tr_sort(ifst, ILabelCompare {}); let minimizer = AcyclicMinimizer::new(ifst)?; merge_states(minimizer.get_partition(), ifst)?; } else { let p = cyclic_minimize(ifst)?; merge_states(p, ifst)?; } tr_unique(ifst); Ok(()) } fn merge_states<W: Semiring, F: MutableFst<W>>(partition: Partition, fst: &mut F) -> Result<()> { let mut state_map = vec![None; partition.num_classes()]; for (i, s) in state_map .iter_mut() .enumerate() .take(partition.num_classes()) { *s = partition.iter(i).next(); } for c in 0..partition.num_classes() { for s in partition.iter(c) { if s == state_map[c].unwrap() { let mut it_tr = fst.tr_iter_mut(s as StateId)?; for idx_tr in 0..it_tr.len() { let tr = unsafe { it_tr.get_unchecked(idx_tr) }; let nextstate = state_map[partition.get_class_id(tr.nextstate as usize)].unwrap(); unsafe { it_tr.set_nextstate_unchecked(idx_tr, nextstate as StateId) }; } } else { let trs: Vec<_> = fst .get_trs(s as StateId)? .trs() .iter() .cloned() .map(|mut tr| { tr.nextstate = state_map[partition.get_class_id(tr.nextstate as usize)] .unwrap() as StateId; tr }) .collect(); for tr in trs.into_iter() { fst.add_tr(state_map[c].unwrap() as StateId, tr)?; } } } } fst.set_start( state_map[partition.get_class_id(fst.start().unwrap() as usize) as usize].unwrap() as StateId, )?; connect(fst)?; Ok(()) } // Compute the height (distance) to final state pub fn fst_depth<W: Semiring, F: Fst<W>>( fst: &F, state_id_cour: StateId, accessible_states: &mut HashSet<StateId>, fully_examined_states: &mut HashSet<StateId>, heights: &mut Vec<i32>, ) -> Result<()> { accessible_states.insert(state_id_cour); for _ in heights.len()..=(state_id_cour as usize) { heights.push(-1); } let mut height_cur_state = 0; for tr in fst.get_trs(state_id_cour)?.trs() { let nextstate = tr.nextstate; if !accessible_states.contains(&nextstate) { fst_depth( fst, nextstate, accessible_states, fully_examined_states, heights, )?; } height_cur_state = max(height_cur_state, 1 + heights[nextstate as usize]); } fully_examined_states.insert(state_id_cour); heights[state_id_cour as usize] = height_cur_state; Ok(()) } struct AcyclicMinimizer { partition: Partition, } impl AcyclicMinimizer { pub fn new<W: Semiring, F: MutableFst<W>>(fst: &mut F) -> Result<Self> { let mut c = Self { partition: Partition::empty_new(), }; c.initialize(fst)?; c.refine(fst); Ok(c) } fn initialize<W: Semiring, F: MutableFst<W>>(&mut self, fst: &mut F) -> Result<()> { let mut accessible_state = HashSet::new(); let mut fully_examined_states = HashSet::new(); let mut heights = Vec::new(); fst_depth( fst, fst.start().unwrap(), &mut accessible_state, &mut fully_examined_states, &mut heights, )?; self.partition.initialize(heights.len()); self.partition .allocate_classes((heights.iter().max().unwrap() + 1) as usize); for (s, h) in heights.iter().enumerate() { self.partition.add(s, *h as usize); } Ok(()) } fn refine<W: Semiring, F: MutableFst<W>>(&mut self, fst: &mut F) { let state_cmp = StateComparator { fst, // This clone is necessary for the moment because the partition is modified while // still needing the StateComparator. // TODO: Find a way to remove the clone. partition: self.partition.clone(), w: PhantomData, }; let height = self.partition.num_classes(); for h in 0..height { // We need here a binary search tree in order to order the states id and create a partition. // For now uses the crate `stable_bst` which is quite old but seems to do the job // TODO: Bench the performances of the implementation. Maybe re-write it. let mut equiv_classes = TreeMap::<StateId, StateId, _>::with_comparator(|a: &StateId, b: &StateId| { state_cmp.compare(*a, *b).unwrap() }); let it_partition: Vec<_> = self.partition.iter(h).collect(); equiv_classes.insert(it_partition[0] as StateId, h as StateId); let mut classes_to_add = vec![]; for e in it_partition.iter().skip(1) { // TODO: Remove double lookup if equiv_classes.contains_key(&(*e as StateId)) { equiv_classes.insert(*e as StateId, NO_STATE_ID); } else { classes_to_add.push(e); equiv_classes.insert(*e as StateId, NO_STATE_ID); } } for v in classes_to_add { equiv_classes.insert(*v as StateId, self.partition.add_class() as StateId); } for s in it_partition { let old_class = self.partition.get_class_id(s); let new_class = *equiv_classes.get(&(s as StateId)).unwrap(); if new_class == NO_STATE_ID { // The behaviour here is a bit different compared to the c++ because here // when inserting an equivalent key it modifies the key // which is not the case in c++. continue; } if old_class != (new_class as usize) { self.partition.move_element(s, new_class as usize); } } } } pub fn get_partition(self) -> Partition { self.partition } } struct StateComparator<'a, W: Semiring, F: MutableFst<W>> { fst: &'a F, partition: Partition, w: PhantomData<W>, } impl<'a, W: Semiring, F: MutableFst<W>> StateComparator<'a, W, F> { fn do_compare(&self, x: StateId, y: StateId) -> Result<bool> { let xfinal = self.fst.final_weight(x)?.unwrap_or_else(W::zero); let yfinal = self.fst.final_weight(y)?.unwrap_or_else(W::zero); if xfinal < yfinal { return Ok(true); } else if xfinal > yfinal { return Ok(false); } if self.fst.num_trs(x)? < self.fst.num_trs(y)? { return Ok(true); } if self.fst.num_trs(x)? > self.fst.num_trs(y)? { return Ok(false); } let it_x_owner = self.fst.get_trs(x)?; let it_x = it_x_owner.trs().iter(); let it_y_owner = self.fst.get_trs(y)?; let it_y = it_y_owner.trs().iter(); for (arc1, arc2) in it_x.zip(it_y) { if arc1.ilabel < arc2.ilabel { return Ok(true); } if arc1.ilabel > arc2.ilabel { return Ok(false); } let id_1 = self.partition.get_class_id(arc1.nextstate as usize); let id_2 = self.partition.get_class_id(arc2.nextstate as usize); if id_1 < id_2 { return Ok(true); } if id_1 > id_2 { return Ok(false); } } Ok(false) } pub fn compare(&self, x: StateId, y: StateId) -> Result<Ordering> { if x == y { return Ok(Ordering::Equal); } let x_y = self.do_compare(x, y).unwrap(); let y_x = self.do_compare(y, x).unwrap(); if !(x_y) && !(y_x) { return Ok(Ordering::Equal); } if x_y { Ok(Ordering::Less) } else { Ok(Ordering::Greater) } } } fn pre_partition<W: Semiring, F: MutableFst<W>>( fst: &F, partition: &mut Partition, queue: &mut LifoQueue, ) { let mut next_class: StateId = 0; let num_states = fst.num_states(); let mut state_to_initial_class: Vec<StateId> = vec![0; num_states]; { let mut hash_to_class_nonfinal = HashMap::<Vec<Label>, StateId>::new(); let mut hash_to_class_final = HashMap::<Vec<Label>, StateId>::new(); for (s, state_to_initial_class_s) in state_to_initial_class .iter_mut() .enumerate() .take(num_states) { let this_map = if unsafe { fst.is_final_unchecked(s as StateId) } { &mut hash_to_class_final } else { &mut hash_to_class_nonfinal }; let ilabels = fst .get_trs(s as StateId) .unwrap() .trs() .iter() .map(|e| e.ilabel) .dedup() .collect_vec(); match this_map.entry(ilabels) { Entry::Occupied(e) => { *state_to_initial_class_s = *e.get(); } Entry::Vacant(e) => { e.insert(next_class); *state_to_initial_class_s = next_class; next_class += 1; } }; } } partition.allocate_classes(next_class as usize); for (s, c) in state_to_initial_class.iter().enumerate().take(num_states) { partition.add(s, *c as usize); } for c in 0..next_class { queue.enqueue(c); } } fn cyclic_minimize<W: Semiring, F: MutableFst<W>>(fst: &mut F) -> Result<Partition> { // Initialize let mut tr: VectorFst<W::ReverseWeight> = reverse(fst)?; tr_sort(&mut tr, ILabelCompare {}); let mut partition = Partition::new(tr.num_states() - 1); let mut queue = LifoQueue::default(); pre_partition(fst, &mut partition, &mut queue); // Compute while let Some(c) = queue.head() { queue.dequeue(); // Split // TODO: Avoid this clone :o // Here we need to pointer to the partition that is valid even if the partition changes. let comp = TrIterCompare { partition: partition.clone(), }; let mut aiter_queue = BinaryHeap::new_by(|v1, v2| { if comp.compare(v1, v2) { Ordering::Less } else { Ordering::Greater } }); // Split for s in partition.iter(c as usize) { if tr.num_trs(s as StateId + 1)? > 0 { aiter_queue.push(TrsIterCollected { idx: 0, trs: tr.get_trs(s as StateId + 1)?, w: PhantomData, }); } } let mut prev_label = -1; while !aiter_queue.is_empty() { let mut aiter = aiter_queue.pop().unwrap(); if aiter.done() { continue; } let tr = aiter.peek().unwrap(); let from_state = tr.nextstate - 1; let from_label = tr.ilabel; if prev_label != from_label as i32 { partition.finalize_split(&mut Some(&mut queue)); } let from_class = partition.get_class_id(from_state as usize); if partition.get_class_size(from_class) > 1 { partition.split_on(from_state as usize); } prev_label = from_label as i32; aiter.next(); if !aiter.done() { aiter_queue.push(aiter); } } partition.finalize_split(&mut Some(&mut queue)); } // Get Partition Ok(partition) } struct TrsIterCollected<W: Semiring, T: Trs<W>> { idx: usize, trs: T, w: PhantomData<W>, } impl<W: Semiring, T: Trs<W>> TrsIterCollected<W, T> { fn peek(&self) -> Option<&Tr<W>> { self.trs.trs().get(self.idx) } fn done(&self) -> bool { self.idx >= self.trs.len() } fn next(&mut self) { self.idx += 1; } } #[derive(Clone)] struct TrIterCompare { partition: Partition, } impl TrIterCompare { fn compare<W: Semiring, T: Trs<W>>( &self, x: &TrsIterCollected<W, T>, y: &TrsIterCollected<W, T>, ) -> bool where W: Semiring, { let xarc = x.peek().unwrap(); let yarc = y.peek().unwrap(); xarc.ilabel > yarc.ilabel } } #[cfg(test)] mod tests { use crate::prelude::*; use algorithms::determinize::*; use proptest::prelude::*; proptest! { #![proptest_config(ProptestConfig { fork: true, timeout: 100, .. ProptestConfig::default() })] #[test] #[ignore] fn proptest_minimize_timeout(mut fst in any::<VectorFst::<TropicalWeight>>()) { let config = MinimizeConfig::default().with_allow_nondet(true); minimize_with_config(&mut fst, config).unwrap(); } } proptest! { #[test] #[ignore] // falls into the same infinite loop as the timeout test fn test_minimize_proptest(mut fst in any::<VectorFst::<TropicalWeight>>()) { let det:VectorFst<_> = determinize(&fst).unwrap(); let min_config = MinimizeConfig::default().with_allow_nondet(true); minimize_with_config(&mut fst, min_config).unwrap(); let det_config = DeterminizeConfig::default().with_det_type(DeterminizeType::DeterminizeNonFunctional); let min_det:VectorFst<_> = determinize_with_config(&fst, det_config).unwrap(); prop_assert!(isomorphic(&det, &min_det).unwrap()) } } }
{ true }
conditional_block
state_machine.go
package dt import "encoding/json" // StateKey is a reserved key in the state of a plugin that tracks which state // the plugin is currently in for each user. const StateKey string = "__state" // StateKeyEntered keeps track of whether the current state has already been // "entered", which determines whether the OnEntry function should run or not. // As mentioned elsewhere, the OnEntry function is only ever run once. const stateEnteredKey string = "__state_entered" // StateMachine enables plugin developers to easily build complex state // machines given the constraints and use-cases of an A.I. bot. It primarily // holds a slice of function Handlers, which is all possible states for a given // stateMachine. The unexported variables are useful internally in keeping track // of state automatically for developers and make an easy API like // stateMachine.Next() possible. type StateMachine struct { Handlers []State state int stateEntered bool states map[string]int plugin *Plugin resetFn func(*Msg) } // State is a collection of pre-defined functions that are run when a user // reaches the appropriate state within a stateMachine. type State struct { // OnEntry preprocesses and asks the user for information. If you need // to do something when the state begins, like run a search or hit an // endpoint, do that within the OnEntry function, since it's only called // once. OnEntry func(*Msg) string // OnInput sets the category in the cache/DB. Note that if invalid, this // state's Complete function will return false, preventing the user from // continuing. User messages will continue to hit this OnInput func // until Complete returns true. // // A note on error handling: errors should be logged but are not // propogated up to the user. Due to the preferred style of thin // States, you should generally avoid logging errors directly in // the OnInput function and instead log them within any called functions // (e.g. setPreference). OnInput func(*Msg) // Complete will determine if the state machine continues. If true, // it'll move to the next state. If false, the user's next response will // hit this state's OnInput function again. Complete func(*Msg) (bool, string) // SkipIfComplete will run Complete() on entry. If Complete() == true, // then it'll skip to the next state. SkipIfComplete bool // Label enables jumping directly to a State with stateMachine.SetState. // Think of it as enabling a safe goto statement. This is especially // useful when combined with a KeywordHandler, enabling a user to jump // straight to something like a "checkout" state. The state machine // checks before jumping that it has all required information before // jumping ensuring Complete() == true at all skipped states, so the // developer can be sure, for example, that the user has selected some // products and picked a shipping address before arriving at the // checkout step. In the case where one of the jumped Complete() // functions returns false, the state machine will stop at that state, // i.e. as close to the desired state as possible. Label string } // EventRequest is sent to the state machine to request safely jumping between // states (directly to a specific Label) with guards checking that each new // state is valid. type EventRequest int // NewStateMachine initializes a stateMachine to its starting state. func NewStateMachine(p *Plugin) *StateMachine { sm := StateMachine{ state: 0, plugin: p, } sm.states = map[string]int{} sm.resetFn = func(*Msg) {} return &sm } // SetStates takes [][]State as an argument. Note that it's a slice of a slice, // which is used to enable tasks like requesting a user's shipping address, // which themselves are []Slice, to be included inline when defining the states // of a stateMachine. func (sm *StateMachine) SetStates(ssss ...[][]State) { for i, sss := range ssss { for j, ss := range sss { for k, s := range ss { sm.Handlers = append(sm.Handlers, s) if len(s.Label) > 0 { sm.states[s.Label] = i + j + k } } } } } // LoadState upserts state into the database. If there is an existing state for // a given user and plugin, the stateMachine will load it. If not, the // stateMachine will insert a starting state into the database. func (sm *StateMachine) LoadState(in *Msg) { tmp, err := json.Marshal(sm.state) if err != nil { sm.plugin.Log.Info("failed to marshal state for db.", err) return } // Using upsert to either insert and return a value or on conflict to // update and return a value doesn't work, leading to this longer form. // Could it be a Postgres bug? This can and should be optimized. if in.User.ID > 0 { q := `INSERT INTO states (key, userid, value, pluginname) VALUES ($1, $2, $3, $4)` _, err = sm.plugin.DB.Exec(q, StateKey, in.User.ID, tmp, sm.plugin.Config.Name) } else { q := `INSERT INTO states (key, flexid, flexidtype, value, pluginname) VALUES ($1, $2, $3, $4, $5)` _, err = sm.plugin.DB.Exec(q, StateKey, in.User.FlexID, in.User.FlexIDType, tmp, sm.plugin.Config.Name) } if err != nil { if err.Error() != `pq: duplicate key value violates unique constraint "states_userid_pkgname_key_key"` && err.Error() != `pq: duplicate key value violates unique constraint "states_flexid_flexidtype_pluginname_key_key"` { sm.plugin.Log.Info("could not insert value into states.", err) sm.state = 0 return } if in.User.ID > 0 { q := `SELECT value FROM states WHERE userid=$1 AND key=$2 AND pluginname=$3` err = sm.plugin.DB.Get(&tmp, q, in.User.ID, StateKey, sm.plugin.Config.Name) } else { q := `SELECT value FROM states WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4` err = sm.plugin.DB.Get(&tmp, q, in.User.FlexID, in.User.FlexIDType, StateKey, sm.plugin.Config.Name) } if err != nil { sm.plugin.Log.Info("failed to get value from state.", err) return } } var val int if err = json.Unmarshal(tmp, &val); err != nil { sm.plugin.Log.Info("failed unmarshaling state from db.", err) return } sm.state = val // Have we already entered a state? sm.stateEntered = sm.plugin.GetMemory(in, stateEnteredKey).Bool() return } // State returns the current state of a stateMachine. state is an unexported // field to protect programmers from directly editing it. While reading state // can be done through this function, changing state should happen only through // the provided stateMachine API (stateMachine.Next(), stateMachine.SetState()), // which allows for safely moving between states. func (sm *StateMachine) State() int { return sm.state } // Next moves a stateMachine from its current state to its next state. Next // handles a variety of corner cases such as reaching the end of the states, // ensuring that the current state's Complete() == true, etc. It directly // returns the next response of the stateMachine, whether that's the Complete() // failed string or the OnEntry() string. func (sm *StateMachine) Next(in *Msg) (response string) { // This check prevents a panic when no states are being used. if len(sm.Handlers) == 0 { return } sm.LoadState(in) // This check prevents a panic when a plugin has been modified to remove // one or more states. if sm.state >= len(sm.Handlers) { sm.plugin.Log.Debug("state is >= len(handlers)") sm.Reset(in) } // Ensure the state has not been entered yet h := sm.Handlers[sm.state] if !sm.stateEntered { sm.plugin.Log.Debug("state was not entered") done, _ := h.Complete(in) if h.SkipIfComplete { if done { sm.plugin.Log.Debug("state was complete. moving on") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) return sm.Next(in) } } sm.setEntered(in) sm.plugin.Log.Debug("setting state entered") // If this is the final state and complete on entry, we'll // reset the state machine. This fixes the "forever trapped" // loop of being in a plugin's finished state machine. resp := h.OnEntry(in) if sm.state+1 >= len(sm.Handlers) && done { sm.Reset(in) } return resp } // State was already entered, so process the input and check for // completion sm.plugin.Log.Debug("state was already entered") h.OnInput(in) done, str := h.Complete(in) if done { sm.plugin.Log.Debug("state is done. going to next") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) if sm.state >= len(sm.Handlers) { sm.plugin.Log.Debug("finished states. resetting") sm.Reset(in) return sm.Next(in) } sm.setEntered(in) str = sm.Handlers[sm.state].OnEntry(in) sm.plugin.Log.Debug("going to next state", sm.state) return str } sm.plugin.Log.Debug("set state to", sm.state) sm.plugin.Log.Debug("set state entered to", sm.stateEntered) return str } // setEntered is used internally to set a state as having been entered both in // memory and persisted to the database. This ensures that a stateMachine does // not run a state's OnEntry function twice. func (sm *StateMachine) setEntered(in *Msg) { sm.stateEntered = true sm.plugin.SetMemory(in, stateEnteredKey, true) } // SetOnReset sets the OnReset function for the stateMachine, which is used to // clear Abot's memory of temporary things between runs. func (sm *StateMachine) SetOnReset(reset func(in *Msg)) { sm.resetFn = reset } // Reset the stateMachine both in memory and in the database. This also runs the // programmer-defined reset function (SetOnReset) to reset memories to some // starting state for running the same plugin multiple times. func (sm *StateMachine)
(in *Msg) { sm.state = 0 sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, 0) sm.plugin.SetMemory(in, stateEnteredKey, false) sm.resetFn(in) } // SetState jumps from one state to another by its label. It will safely jump // forward but NO safety checks are performed on backward jumps. It's therefore // up to the developer to ensure that data is still OK when jumping backward. // Any forward jump will check the Complete() function of each state and get as // close as it can to the desired state as long as each Complete() == true at // each state. func (sm *StateMachine) SetState(in *Msg, label string) string { desiredState := sm.states[label] // If we're in a state beyond the desired state, go back. There are NO // checks for state when going backward, so if you're changing state // after its been completed, you'll need to do sanity checks OnEntry. if sm.state > desiredState { sm.state = desiredState sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, desiredState) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[desiredState].OnEntry(in) } // If we're in a state before the desired state, go forward only as far // as we're allowed by the Complete guards. for s := sm.state; s < desiredState; s++ { ok, _ := sm.Handlers[s].Complete(in) if !ok { sm.state = s sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, s) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[s].OnEntry(in) } } // No guards were triggered (go to state), or the state == desiredState, // so reset the state and run OnEntry again unless the plugin is now // complete. sm.state = desiredState sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, desiredState) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[desiredState].OnEntry(in) } // ReplayState returns you to the current state's OnEntry function. This is // only useful when you're iterating over results in a state machine. If you're // reading this, you should probably be using task.Iterate() instead. If you've // already considered task.Iterate(), and you've decided to use this underlying // function instead, you should only call it when Complete returns false, like // so: // // Complete: func(in *dt.Msg) (bool, string) { // if p.HasMemory(in, "memkey") { // return true, "" // } // return false, p.SM.ReplayState(in) // } // // That said, the *vast* majority of the time you should NOT be using this // function. Instead use task.Iterate(), which uses this function safely. func (sm *StateMachine) ReplayState(in *Msg) string { sm.LoadState(in) sm.plugin.Log.Debug("replaying state", sm.state) return sm.Handlers[sm.state].OnEntry(in) }
Reset
identifier_name
state_machine.go
package dt import "encoding/json" // StateKey is a reserved key in the state of a plugin that tracks which state // the plugin is currently in for each user. const StateKey string = "__state" // StateKeyEntered keeps track of whether the current state has already been // "entered", which determines whether the OnEntry function should run or not. // As mentioned elsewhere, the OnEntry function is only ever run once. const stateEnteredKey string = "__state_entered" // StateMachine enables plugin developers to easily build complex state // machines given the constraints and use-cases of an A.I. bot. It primarily // holds a slice of function Handlers, which is all possible states for a given // stateMachine. The unexported variables are useful internally in keeping track // of state automatically for developers and make an easy API like // stateMachine.Next() possible. type StateMachine struct { Handlers []State state int stateEntered bool states map[string]int plugin *Plugin resetFn func(*Msg) } // State is a collection of pre-defined functions that are run when a user // reaches the appropriate state within a stateMachine. type State struct { // OnEntry preprocesses and asks the user for information. If you need // to do something when the state begins, like run a search or hit an // endpoint, do that within the OnEntry function, since it's only called // once. OnEntry func(*Msg) string // OnInput sets the category in the cache/DB. Note that if invalid, this // state's Complete function will return false, preventing the user from // continuing. User messages will continue to hit this OnInput func // until Complete returns true. // // A note on error handling: errors should be logged but are not // propogated up to the user. Due to the preferred style of thin // States, you should generally avoid logging errors directly in // the OnInput function and instead log them within any called functions // (e.g. setPreference). OnInput func(*Msg) // Complete will determine if the state machine continues. If true, // it'll move to the next state. If false, the user's next response will // hit this state's OnInput function again. Complete func(*Msg) (bool, string) // SkipIfComplete will run Complete() on entry. If Complete() == true, // then it'll skip to the next state. SkipIfComplete bool // Label enables jumping directly to a State with stateMachine.SetState. // Think of it as enabling a safe goto statement. This is especially // useful when combined with a KeywordHandler, enabling a user to jump // straight to something like a "checkout" state. The state machine // checks before jumping that it has all required information before // jumping ensuring Complete() == true at all skipped states, so the // developer can be sure, for example, that the user has selected some // products and picked a shipping address before arriving at the // checkout step. In the case where one of the jumped Complete() // functions returns false, the state machine will stop at that state, // i.e. as close to the desired state as possible. Label string } // EventRequest is sent to the state machine to request safely jumping between // states (directly to a specific Label) with guards checking that each new // state is valid. type EventRequest int // NewStateMachine initializes a stateMachine to its starting state. func NewStateMachine(p *Plugin) *StateMachine { sm := StateMachine{ state: 0, plugin: p, } sm.states = map[string]int{} sm.resetFn = func(*Msg) {} return &sm } // SetStates takes [][]State as an argument. Note that it's a slice of a slice, // which is used to enable tasks like requesting a user's shipping address, // which themselves are []Slice, to be included inline when defining the states // of a stateMachine. func (sm *StateMachine) SetStates(ssss ...[][]State) { for i, sss := range ssss { for j, ss := range sss { for k, s := range ss { sm.Handlers = append(sm.Handlers, s) if len(s.Label) > 0 { sm.states[s.Label] = i + j + k } } } } } // LoadState upserts state into the database. If there is an existing state for // a given user and plugin, the stateMachine will load it. If not, the // stateMachine will insert a starting state into the database. func (sm *StateMachine) LoadState(in *Msg) { tmp, err := json.Marshal(sm.state) if err != nil { sm.plugin.Log.Info("failed to marshal state for db.", err) return } // Using upsert to either insert and return a value or on conflict to // update and return a value doesn't work, leading to this longer form. // Could it be a Postgres bug? This can and should be optimized. if in.User.ID > 0 { q := `INSERT INTO states (key, userid, value, pluginname) VALUES ($1, $2, $3, $4)` _, err = sm.plugin.DB.Exec(q, StateKey, in.User.ID, tmp, sm.plugin.Config.Name) } else { q := `INSERT INTO states (key, flexid, flexidtype, value, pluginname) VALUES ($1, $2, $3, $4, $5)` _, err = sm.plugin.DB.Exec(q, StateKey, in.User.FlexID, in.User.FlexIDType, tmp, sm.plugin.Config.Name) } if err != nil { if err.Error() != `pq: duplicate key value violates unique constraint "states_userid_pkgname_key_key"` && err.Error() != `pq: duplicate key value violates unique constraint "states_flexid_flexidtype_pluginname_key_key"` { sm.plugin.Log.Info("could not insert value into states.", err) sm.state = 0 return } if in.User.ID > 0 { q := `SELECT value FROM states WHERE userid=$1 AND key=$2 AND pluginname=$3` err = sm.plugin.DB.Get(&tmp, q, in.User.ID, StateKey, sm.plugin.Config.Name) } else { q := `SELECT value FROM states WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4` err = sm.plugin.DB.Get(&tmp, q, in.User.FlexID, in.User.FlexIDType, StateKey, sm.plugin.Config.Name) } if err != nil { sm.plugin.Log.Info("failed to get value from state.", err) return } } var val int if err = json.Unmarshal(tmp, &val); err != nil { sm.plugin.Log.Info("failed unmarshaling state from db.", err) return } sm.state = val // Have we already entered a state? sm.stateEntered = sm.plugin.GetMemory(in, stateEnteredKey).Bool() return } // State returns the current state of a stateMachine. state is an unexported // field to protect programmers from directly editing it. While reading state // can be done through this function, changing state should happen only through // the provided stateMachine API (stateMachine.Next(), stateMachine.SetState()), // which allows for safely moving between states. func (sm *StateMachine) State() int { return sm.state } // Next moves a stateMachine from its current state to its next state. Next // handles a variety of corner cases such as reaching the end of the states, // ensuring that the current state's Complete() == true, etc. It directly // returns the next response of the stateMachine, whether that's the Complete() // failed string or the OnEntry() string. func (sm *StateMachine) Next(in *Msg) (response string) { // This check prevents a panic when no states are being used. if len(sm.Handlers) == 0 { return } sm.LoadState(in) // This check prevents a panic when a plugin has been modified to remove // one or more states. if sm.state >= len(sm.Handlers) { sm.plugin.Log.Debug("state is >= len(handlers)") sm.Reset(in) } // Ensure the state has not been entered yet h := sm.Handlers[sm.state] if !sm.stateEntered { sm.plugin.Log.Debug("state was not entered") done, _ := h.Complete(in) if h.SkipIfComplete { if done { sm.plugin.Log.Debug("state was complete. moving on") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) return sm.Next(in) } } sm.setEntered(in) sm.plugin.Log.Debug("setting state entered") // If this is the final state and complete on entry, we'll // reset the state machine. This fixes the "forever trapped" // loop of being in a plugin's finished state machine. resp := h.OnEntry(in) if sm.state+1 >= len(sm.Handlers) && done { sm.Reset(in) } return resp } // State was already entered, so process the input and check for // completion sm.plugin.Log.Debug("state was already entered") h.OnInput(in) done, str := h.Complete(in) if done { sm.plugin.Log.Debug("state is done. going to next") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) if sm.state >= len(sm.Handlers) { sm.plugin.Log.Debug("finished states. resetting") sm.Reset(in) return sm.Next(in) } sm.setEntered(in) str = sm.Handlers[sm.state].OnEntry(in) sm.plugin.Log.Debug("going to next state", sm.state) return str } sm.plugin.Log.Debug("set state to", sm.state) sm.plugin.Log.Debug("set state entered to", sm.stateEntered) return str } // setEntered is used internally to set a state as having been entered both in // memory and persisted to the database. This ensures that a stateMachine does // not run a state's OnEntry function twice. func (sm *StateMachine) setEntered(in *Msg) { sm.stateEntered = true sm.plugin.SetMemory(in, stateEnteredKey, true) } // SetOnReset sets the OnReset function for the stateMachine, which is used to // clear Abot's memory of temporary things between runs. func (sm *StateMachine) SetOnReset(reset func(in *Msg)) { sm.resetFn = reset } // Reset the stateMachine both in memory and in the database. This also runs the // programmer-defined reset function (SetOnReset) to reset memories to some // starting state for running the same plugin multiple times. func (sm *StateMachine) Reset(in *Msg) { sm.state = 0 sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, 0) sm.plugin.SetMemory(in, stateEnteredKey, false) sm.resetFn(in) } // SetState jumps from one state to another by its label. It will safely jump // forward but NO safety checks are performed on backward jumps. It's therefore // up to the developer to ensure that data is still OK when jumping backward. // Any forward jump will check the Complete() function of each state and get as // close as it can to the desired state as long as each Complete() == true at // each state. func (sm *StateMachine) SetState(in *Msg, label string) string { desiredState := sm.states[label] // If we're in a state beyond the desired state, go back. There are NO // checks for state when going backward, so if you're changing state // after its been completed, you'll need to do sanity checks OnEntry. if sm.state > desiredState { sm.state = desiredState sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, desiredState) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[desiredState].OnEntry(in) }
// If we're in a state before the desired state, go forward only as far // as we're allowed by the Complete guards. for s := sm.state; s < desiredState; s++ { ok, _ := sm.Handlers[s].Complete(in) if !ok { sm.state = s sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, s) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[s].OnEntry(in) } } // No guards were triggered (go to state), or the state == desiredState, // so reset the state and run OnEntry again unless the plugin is now // complete. sm.state = desiredState sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, desiredState) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[desiredState].OnEntry(in) } // ReplayState returns you to the current state's OnEntry function. This is // only useful when you're iterating over results in a state machine. If you're // reading this, you should probably be using task.Iterate() instead. If you've // already considered task.Iterate(), and you've decided to use this underlying // function instead, you should only call it when Complete returns false, like // so: // // Complete: func(in *dt.Msg) (bool, string) { // if p.HasMemory(in, "memkey") { // return true, "" // } // return false, p.SM.ReplayState(in) // } // // That said, the *vast* majority of the time you should NOT be using this // function. Instead use task.Iterate(), which uses this function safely. func (sm *StateMachine) ReplayState(in *Msg) string { sm.LoadState(in) sm.plugin.Log.Debug("replaying state", sm.state) return sm.Handlers[sm.state].OnEntry(in) }
random_line_split
state_machine.go
package dt import "encoding/json" // StateKey is a reserved key in the state of a plugin that tracks which state // the plugin is currently in for each user. const StateKey string = "__state" // StateKeyEntered keeps track of whether the current state has already been // "entered", which determines whether the OnEntry function should run or not. // As mentioned elsewhere, the OnEntry function is only ever run once. const stateEnteredKey string = "__state_entered" // StateMachine enables plugin developers to easily build complex state // machines given the constraints and use-cases of an A.I. bot. It primarily // holds a slice of function Handlers, which is all possible states for a given // stateMachine. The unexported variables are useful internally in keeping track // of state automatically for developers and make an easy API like // stateMachine.Next() possible. type StateMachine struct { Handlers []State state int stateEntered bool states map[string]int plugin *Plugin resetFn func(*Msg) } // State is a collection of pre-defined functions that are run when a user // reaches the appropriate state within a stateMachine. type State struct { // OnEntry preprocesses and asks the user for information. If you need // to do something when the state begins, like run a search or hit an // endpoint, do that within the OnEntry function, since it's only called // once. OnEntry func(*Msg) string // OnInput sets the category in the cache/DB. Note that if invalid, this // state's Complete function will return false, preventing the user from // continuing. User messages will continue to hit this OnInput func // until Complete returns true. // // A note on error handling: errors should be logged but are not // propogated up to the user. Due to the preferred style of thin // States, you should generally avoid logging errors directly in // the OnInput function and instead log them within any called functions // (e.g. setPreference). OnInput func(*Msg) // Complete will determine if the state machine continues. If true, // it'll move to the next state. If false, the user's next response will // hit this state's OnInput function again. Complete func(*Msg) (bool, string) // SkipIfComplete will run Complete() on entry. If Complete() == true, // then it'll skip to the next state. SkipIfComplete bool // Label enables jumping directly to a State with stateMachine.SetState. // Think of it as enabling a safe goto statement. This is especially // useful when combined with a KeywordHandler, enabling a user to jump // straight to something like a "checkout" state. The state machine // checks before jumping that it has all required information before // jumping ensuring Complete() == true at all skipped states, so the // developer can be sure, for example, that the user has selected some // products and picked a shipping address before arriving at the // checkout step. In the case where one of the jumped Complete() // functions returns false, the state machine will stop at that state, // i.e. as close to the desired state as possible. Label string } // EventRequest is sent to the state machine to request safely jumping between // states (directly to a specific Label) with guards checking that each new // state is valid. type EventRequest int // NewStateMachine initializes a stateMachine to its starting state. func NewStateMachine(p *Plugin) *StateMachine { sm := StateMachine{ state: 0, plugin: p, } sm.states = map[string]int{} sm.resetFn = func(*Msg) {} return &sm } // SetStates takes [][]State as an argument. Note that it's a slice of a slice, // which is used to enable tasks like requesting a user's shipping address, // which themselves are []Slice, to be included inline when defining the states // of a stateMachine. func (sm *StateMachine) SetStates(ssss ...[][]State) { for i, sss := range ssss { for j, ss := range sss { for k, s := range ss { sm.Handlers = append(sm.Handlers, s) if len(s.Label) > 0 { sm.states[s.Label] = i + j + k } } } } } // LoadState upserts state into the database. If there is an existing state for // a given user and plugin, the stateMachine will load it. If not, the // stateMachine will insert a starting state into the database. func (sm *StateMachine) LoadState(in *Msg) { tmp, err := json.Marshal(sm.state) if err != nil { sm.plugin.Log.Info("failed to marshal state for db.", err) return } // Using upsert to either insert and return a value or on conflict to // update and return a value doesn't work, leading to this longer form. // Could it be a Postgres bug? This can and should be optimized. if in.User.ID > 0 { q := `INSERT INTO states (key, userid, value, pluginname) VALUES ($1, $2, $3, $4)` _, err = sm.plugin.DB.Exec(q, StateKey, in.User.ID, tmp, sm.plugin.Config.Name) } else { q := `INSERT INTO states (key, flexid, flexidtype, value, pluginname) VALUES ($1, $2, $3, $4, $5)` _, err = sm.plugin.DB.Exec(q, StateKey, in.User.FlexID, in.User.FlexIDType, tmp, sm.plugin.Config.Name) } if err != nil { if err.Error() != `pq: duplicate key value violates unique constraint "states_userid_pkgname_key_key"` && err.Error() != `pq: duplicate key value violates unique constraint "states_flexid_flexidtype_pluginname_key_key"` { sm.plugin.Log.Info("could not insert value into states.", err) sm.state = 0 return } if in.User.ID > 0 { q := `SELECT value FROM states WHERE userid=$1 AND key=$2 AND pluginname=$3` err = sm.plugin.DB.Get(&tmp, q, in.User.ID, StateKey, sm.plugin.Config.Name) } else { q := `SELECT value FROM states WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4` err = sm.plugin.DB.Get(&tmp, q, in.User.FlexID, in.User.FlexIDType, StateKey, sm.plugin.Config.Name) } if err != nil { sm.plugin.Log.Info("failed to get value from state.", err) return } } var val int if err = json.Unmarshal(tmp, &val); err != nil { sm.plugin.Log.Info("failed unmarshaling state from db.", err) return } sm.state = val // Have we already entered a state? sm.stateEntered = sm.plugin.GetMemory(in, stateEnteredKey).Bool() return } // State returns the current state of a stateMachine. state is an unexported // field to protect programmers from directly editing it. While reading state // can be done through this function, changing state should happen only through // the provided stateMachine API (stateMachine.Next(), stateMachine.SetState()), // which allows for safely moving between states. func (sm *StateMachine) State() int { return sm.state } // Next moves a stateMachine from its current state to its next state. Next // handles a variety of corner cases such as reaching the end of the states, // ensuring that the current state's Complete() == true, etc. It directly // returns the next response of the stateMachine, whether that's the Complete() // failed string or the OnEntry() string. func (sm *StateMachine) Next(in *Msg) (response string)
// setEntered is used internally to set a state as having been entered both in // memory and persisted to the database. This ensures that a stateMachine does // not run a state's OnEntry function twice. func (sm *StateMachine) setEntered(in *Msg) { sm.stateEntered = true sm.plugin.SetMemory(in, stateEnteredKey, true) } // SetOnReset sets the OnReset function for the stateMachine, which is used to // clear Abot's memory of temporary things between runs. func (sm *StateMachine) SetOnReset(reset func(in *Msg)) { sm.resetFn = reset } // Reset the stateMachine both in memory and in the database. This also runs the // programmer-defined reset function (SetOnReset) to reset memories to some // starting state for running the same plugin multiple times. func (sm *StateMachine) Reset(in *Msg) { sm.state = 0 sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, 0) sm.plugin.SetMemory(in, stateEnteredKey, false) sm.resetFn(in) } // SetState jumps from one state to another by its label. It will safely jump // forward but NO safety checks are performed on backward jumps. It's therefore // up to the developer to ensure that data is still OK when jumping backward. // Any forward jump will check the Complete() function of each state and get as // close as it can to the desired state as long as each Complete() == true at // each state. func (sm *StateMachine) SetState(in *Msg, label string) string { desiredState := sm.states[label] // If we're in a state beyond the desired state, go back. There are NO // checks for state when going backward, so if you're changing state // after its been completed, you'll need to do sanity checks OnEntry. if sm.state > desiredState { sm.state = desiredState sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, desiredState) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[desiredState].OnEntry(in) } // If we're in a state before the desired state, go forward only as far // as we're allowed by the Complete guards. for s := sm.state; s < desiredState; s++ { ok, _ := sm.Handlers[s].Complete(in) if !ok { sm.state = s sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, s) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[s].OnEntry(in) } } // No guards were triggered (go to state), or the state == desiredState, // so reset the state and run OnEntry again unless the plugin is now // complete. sm.state = desiredState sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, desiredState) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[desiredState].OnEntry(in) } // ReplayState returns you to the current state's OnEntry function. This is // only useful when you're iterating over results in a state machine. If you're // reading this, you should probably be using task.Iterate() instead. If you've // already considered task.Iterate(), and you've decided to use this underlying // function instead, you should only call it when Complete returns false, like // so: // // Complete: func(in *dt.Msg) (bool, string) { // if p.HasMemory(in, "memkey") { // return true, "" // } // return false, p.SM.ReplayState(in) // } // // That said, the *vast* majority of the time you should NOT be using this // function. Instead use task.Iterate(), which uses this function safely. func (sm *StateMachine) ReplayState(in *Msg) string { sm.LoadState(in) sm.plugin.Log.Debug("replaying state", sm.state) return sm.Handlers[sm.state].OnEntry(in) }
{ // This check prevents a panic when no states are being used. if len(sm.Handlers) == 0 { return } sm.LoadState(in) // This check prevents a panic when a plugin has been modified to remove // one or more states. if sm.state >= len(sm.Handlers) { sm.plugin.Log.Debug("state is >= len(handlers)") sm.Reset(in) } // Ensure the state has not been entered yet h := sm.Handlers[sm.state] if !sm.stateEntered { sm.plugin.Log.Debug("state was not entered") done, _ := h.Complete(in) if h.SkipIfComplete { if done { sm.plugin.Log.Debug("state was complete. moving on") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) return sm.Next(in) } } sm.setEntered(in) sm.plugin.Log.Debug("setting state entered") // If this is the final state and complete on entry, we'll // reset the state machine. This fixes the "forever trapped" // loop of being in a plugin's finished state machine. resp := h.OnEntry(in) if sm.state+1 >= len(sm.Handlers) && done { sm.Reset(in) } return resp } // State was already entered, so process the input and check for // completion sm.plugin.Log.Debug("state was already entered") h.OnInput(in) done, str := h.Complete(in) if done { sm.plugin.Log.Debug("state is done. going to next") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) if sm.state >= len(sm.Handlers) { sm.plugin.Log.Debug("finished states. resetting") sm.Reset(in) return sm.Next(in) } sm.setEntered(in) str = sm.Handlers[sm.state].OnEntry(in) sm.plugin.Log.Debug("going to next state", sm.state) return str } sm.plugin.Log.Debug("set state to", sm.state) sm.plugin.Log.Debug("set state entered to", sm.stateEntered) return str }
identifier_body
state_machine.go
package dt import "encoding/json" // StateKey is a reserved key in the state of a plugin that tracks which state // the plugin is currently in for each user. const StateKey string = "__state" // StateKeyEntered keeps track of whether the current state has already been // "entered", which determines whether the OnEntry function should run or not. // As mentioned elsewhere, the OnEntry function is only ever run once. const stateEnteredKey string = "__state_entered" // StateMachine enables plugin developers to easily build complex state // machines given the constraints and use-cases of an A.I. bot. It primarily // holds a slice of function Handlers, which is all possible states for a given // stateMachine. The unexported variables are useful internally in keeping track // of state automatically for developers and make an easy API like // stateMachine.Next() possible. type StateMachine struct { Handlers []State state int stateEntered bool states map[string]int plugin *Plugin resetFn func(*Msg) } // State is a collection of pre-defined functions that are run when a user // reaches the appropriate state within a stateMachine. type State struct { // OnEntry preprocesses and asks the user for information. If you need // to do something when the state begins, like run a search or hit an // endpoint, do that within the OnEntry function, since it's only called // once. OnEntry func(*Msg) string // OnInput sets the category in the cache/DB. Note that if invalid, this // state's Complete function will return false, preventing the user from // continuing. User messages will continue to hit this OnInput func // until Complete returns true. // // A note on error handling: errors should be logged but are not // propogated up to the user. Due to the preferred style of thin // States, you should generally avoid logging errors directly in // the OnInput function and instead log them within any called functions // (e.g. setPreference). OnInput func(*Msg) // Complete will determine if the state machine continues. If true, // it'll move to the next state. If false, the user's next response will // hit this state's OnInput function again. Complete func(*Msg) (bool, string) // SkipIfComplete will run Complete() on entry. If Complete() == true, // then it'll skip to the next state. SkipIfComplete bool // Label enables jumping directly to a State with stateMachine.SetState. // Think of it as enabling a safe goto statement. This is especially // useful when combined with a KeywordHandler, enabling a user to jump // straight to something like a "checkout" state. The state machine // checks before jumping that it has all required information before // jumping ensuring Complete() == true at all skipped states, so the // developer can be sure, for example, that the user has selected some // products and picked a shipping address before arriving at the // checkout step. In the case where one of the jumped Complete() // functions returns false, the state machine will stop at that state, // i.e. as close to the desired state as possible. Label string } // EventRequest is sent to the state machine to request safely jumping between // states (directly to a specific Label) with guards checking that each new // state is valid. type EventRequest int // NewStateMachine initializes a stateMachine to its starting state. func NewStateMachine(p *Plugin) *StateMachine { sm := StateMachine{ state: 0, plugin: p, } sm.states = map[string]int{} sm.resetFn = func(*Msg) {} return &sm } // SetStates takes [][]State as an argument. Note that it's a slice of a slice, // which is used to enable tasks like requesting a user's shipping address, // which themselves are []Slice, to be included inline when defining the states // of a stateMachine. func (sm *StateMachine) SetStates(ssss ...[][]State) { for i, sss := range ssss { for j, ss := range sss { for k, s := range ss { sm.Handlers = append(sm.Handlers, s) if len(s.Label) > 0 { sm.states[s.Label] = i + j + k } } } } } // LoadState upserts state into the database. If there is an existing state for // a given user and plugin, the stateMachine will load it. If not, the // stateMachine will insert a starting state into the database. func (sm *StateMachine) LoadState(in *Msg) { tmp, err := json.Marshal(sm.state) if err != nil { sm.plugin.Log.Info("failed to marshal state for db.", err) return } // Using upsert to either insert and return a value or on conflict to // update and return a value doesn't work, leading to this longer form. // Could it be a Postgres bug? This can and should be optimized. if in.User.ID > 0 { q := `INSERT INTO states (key, userid, value, pluginname) VALUES ($1, $2, $3, $4)` _, err = sm.plugin.DB.Exec(q, StateKey, in.User.ID, tmp, sm.plugin.Config.Name) } else { q := `INSERT INTO states (key, flexid, flexidtype, value, pluginname) VALUES ($1, $2, $3, $4, $5)` _, err = sm.plugin.DB.Exec(q, StateKey, in.User.FlexID, in.User.FlexIDType, tmp, sm.plugin.Config.Name) } if err != nil { if err.Error() != `pq: duplicate key value violates unique constraint "states_userid_pkgname_key_key"` && err.Error() != `pq: duplicate key value violates unique constraint "states_flexid_flexidtype_pluginname_key_key"` { sm.plugin.Log.Info("could not insert value into states.", err) sm.state = 0 return } if in.User.ID > 0 { q := `SELECT value FROM states WHERE userid=$1 AND key=$2 AND pluginname=$3` err = sm.plugin.DB.Get(&tmp, q, in.User.ID, StateKey, sm.plugin.Config.Name) } else { q := `SELECT value FROM states WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4` err = sm.plugin.DB.Get(&tmp, q, in.User.FlexID, in.User.FlexIDType, StateKey, sm.plugin.Config.Name) } if err != nil { sm.plugin.Log.Info("failed to get value from state.", err) return } } var val int if err = json.Unmarshal(tmp, &val); err != nil { sm.plugin.Log.Info("failed unmarshaling state from db.", err) return } sm.state = val // Have we already entered a state? sm.stateEntered = sm.plugin.GetMemory(in, stateEnteredKey).Bool() return } // State returns the current state of a stateMachine. state is an unexported // field to protect programmers from directly editing it. While reading state // can be done through this function, changing state should happen only through // the provided stateMachine API (stateMachine.Next(), stateMachine.SetState()), // which allows for safely moving between states. func (sm *StateMachine) State() int { return sm.state } // Next moves a stateMachine from its current state to its next state. Next // handles a variety of corner cases such as reaching the end of the states, // ensuring that the current state's Complete() == true, etc. It directly // returns the next response of the stateMachine, whether that's the Complete() // failed string or the OnEntry() string. func (sm *StateMachine) Next(in *Msg) (response string) { // This check prevents a panic when no states are being used. if len(sm.Handlers) == 0 { return } sm.LoadState(in) // This check prevents a panic when a plugin has been modified to remove // one or more states. if sm.state >= len(sm.Handlers) { sm.plugin.Log.Debug("state is >= len(handlers)") sm.Reset(in) } // Ensure the state has not been entered yet h := sm.Handlers[sm.state] if !sm.stateEntered { sm.plugin.Log.Debug("state was not entered") done, _ := h.Complete(in) if h.SkipIfComplete { if done { sm.plugin.Log.Debug("state was complete. moving on") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) return sm.Next(in) } } sm.setEntered(in) sm.plugin.Log.Debug("setting state entered") // If this is the final state and complete on entry, we'll // reset the state machine. This fixes the "forever trapped" // loop of being in a plugin's finished state machine. resp := h.OnEntry(in) if sm.state+1 >= len(sm.Handlers) && done { sm.Reset(in) } return resp } // State was already entered, so process the input and check for // completion sm.plugin.Log.Debug("state was already entered") h.OnInput(in) done, str := h.Complete(in) if done { sm.plugin.Log.Debug("state is done. going to next") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) if sm.state >= len(sm.Handlers)
sm.setEntered(in) str = sm.Handlers[sm.state].OnEntry(in) sm.plugin.Log.Debug("going to next state", sm.state) return str } sm.plugin.Log.Debug("set state to", sm.state) sm.plugin.Log.Debug("set state entered to", sm.stateEntered) return str } // setEntered is used internally to set a state as having been entered both in // memory and persisted to the database. This ensures that a stateMachine does // not run a state's OnEntry function twice. func (sm *StateMachine) setEntered(in *Msg) { sm.stateEntered = true sm.plugin.SetMemory(in, stateEnteredKey, true) } // SetOnReset sets the OnReset function for the stateMachine, which is used to // clear Abot's memory of temporary things between runs. func (sm *StateMachine) SetOnReset(reset func(in *Msg)) { sm.resetFn = reset } // Reset the stateMachine both in memory and in the database. This also runs the // programmer-defined reset function (SetOnReset) to reset memories to some // starting state for running the same plugin multiple times. func (sm *StateMachine) Reset(in *Msg) { sm.state = 0 sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, 0) sm.plugin.SetMemory(in, stateEnteredKey, false) sm.resetFn(in) } // SetState jumps from one state to another by its label. It will safely jump // forward but NO safety checks are performed on backward jumps. It's therefore // up to the developer to ensure that data is still OK when jumping backward. // Any forward jump will check the Complete() function of each state and get as // close as it can to the desired state as long as each Complete() == true at // each state. func (sm *StateMachine) SetState(in *Msg, label string) string { desiredState := sm.states[label] // If we're in a state beyond the desired state, go back. There are NO // checks for state when going backward, so if you're changing state // after its been completed, you'll need to do sanity checks OnEntry. if sm.state > desiredState { sm.state = desiredState sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, desiredState) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[desiredState].OnEntry(in) } // If we're in a state before the desired state, go forward only as far // as we're allowed by the Complete guards. for s := sm.state; s < desiredState; s++ { ok, _ := sm.Handlers[s].Complete(in) if !ok { sm.state = s sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, s) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[s].OnEntry(in) } } // No guards were triggered (go to state), or the state == desiredState, // so reset the state and run OnEntry again unless the plugin is now // complete. sm.state = desiredState sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, desiredState) sm.plugin.SetMemory(in, stateEnteredKey, false) return sm.Handlers[desiredState].OnEntry(in) } // ReplayState returns you to the current state's OnEntry function. This is // only useful when you're iterating over results in a state machine. If you're // reading this, you should probably be using task.Iterate() instead. If you've // already considered task.Iterate(), and you've decided to use this underlying // function instead, you should only call it when Complete returns false, like // so: // // Complete: func(in *dt.Msg) (bool, string) { // if p.HasMemory(in, "memkey") { // return true, "" // } // return false, p.SM.ReplayState(in) // } // // That said, the *vast* majority of the time you should NOT be using this // function. Instead use task.Iterate(), which uses this function safely. func (sm *StateMachine) ReplayState(in *Msg) string { sm.LoadState(in) sm.plugin.Log.Debug("replaying state", sm.state) return sm.Handlers[sm.state].OnEntry(in) }
{ sm.plugin.Log.Debug("finished states. resetting") sm.Reset(in) return sm.Next(in) }
conditional_block
gfx2.go
// Autor: (c) St. Schmidt (Kontakt: St.Schmidt@online.de) // Datum: 04.02.2019-07.02.2019; letzte Änderung: 06.11.2020 // --> Damit entspricht der Stand von gfx2 dem von gfx vom 06.11.2020 // Zweck: TCP/IP-Server, der ein gfx-Grafikfenster verwaltet // - Grafik- und Soundausgabe und Eingabe per Tastatur und Maus // mit Go unter Windows package gfx2 /* Letzte Änderungen: - 06.11.2020 Bug bei 'Clipboard_einfuegen' bzgl. der Transparenz entfernt - 18.10.2020: alle "docstrings" in die Impl. kopiert, so dass nun 'go doc gfx.<FktName>' die Spezifikation liefert, Bug in 'FensterAus' entfernt, neue Funktion 'Fenstertitel', mit der in der Titelzeile des Fensters ein eigener Fenstertitel festgelegt werden kann, neue Funktionen 'LadeBildMitColorKey' und 'Clipboard_einfuegenMitColorKey', bei der Pixel einer bestimmten Farbe transparent dargestellt werden (gut für "Sprites"!), neue Funktion 'Transparenz', damit man sich überdeckende Grafik- objekte erkennen kann - 01.10.2020 'Bug' entfernt: Mit 'defer' angemeldete Funktionsaufrufe wurden nach dem Schließen des Fensters mit Klick auf das x links oben nicht mehr ausgeführt. - 01.09.2019: -Bugfix - Nun gelingen auch nebenläufige Mausabfagen und gleichzeitige Änderungen des Fensterinhalts; -Einbau der neuen Funktionen zum Abspielen von Noten (in gfx: Mai 2019) -Spezifikationsfehler korrigiert - 07.02.2019: Umbau: Mit den unten spezifizierten Funktionen wird ein Server angesprochen, der genau ein Grafikfenster verwaltet. Vorteil: deutlich einfachere Handhabung und Installation unter Windows, da nun dort kein C-Quelltext mehr kompiliert werden muss. Der Server liegt als exe-Datei vor. - 03.03.2018: Die Funktion 'SetzeFont' liefert nun einen Rückgabewert, der den Erfolg/Misserfolg angibt. - 07.10.2017: neue Funktion 'Tastaturzeichen' - 07.10.2017: 'Bug' in Funktion 'Cls()' entfernt - KEIN FLACKERN MEHR bei 'double-buffering' mit UpdateAus() und UpdateAn() /* * * SOWOHL UNTER X (LINUX) ALS AUCH UNTER MS WINDOWS - getestet :-) * AM GO-QUELLTEXT MÜSSEN KEINE ÄNDERUNGEN VORGENOMMEN WERDEN! * * ACHTUNG: Die Darstellung von Grafikobjekte im Grafikfenster ist nur dann * sichergestellt, wenn sie vollständig im sichtbaren Bereich liegen. * * Die Zeichen-Anweisungen aus gfx2 dürfen nebenläufig aufgerufen werden! * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * --> Sollen bei Nebenläufigkeit mehrere Anweisungen "am Block" * ausgeführt werden, ist so vorzugehen: * Sperren () * <Anweisungen aus gfx2> * Entsperren () */ // Vor.: Das Grafikfenster ist nicht offen. Es gilt: breite <=1920; hoehe <=1200. // Unter Linux bzw. Windows befindet sich das ausführbare Programm 'gfx2server' // bzw. 'gfx2server.exe' im Pfad. Der Port 'GfxPortnummer()' (Standard: 55555) // ist für den Server noch frei. Ist der Port nicht frei, so muss mit // 'SetzeGfxPortnummer' (s.u.) ein freier Port zugewiesen worden sein. // Eff.: Das Serverprogramm 'gfx2server' bzw. 'gfx2server.exe' ist gestartet und // das gfx-Fenster mit einer 'Zeichenfläche' von breite x hoehe Pixeln wurde // geöffnet. Die Zeichenfarbe ist Schwarz. Der Ursprung (0,0) ist // oben links im Fenster. Die x-Koordinate wächst horizontal nach // rechts, die y-Koordinate vertikal nach unten. // Fenster (breite, hoehe uint16) // Vor.: - // Erg.: die Portnummer, die dem Serverprogramm 'gfx2server' bzw. 'gfx2server.exe' // zugewiesen wurde bzw. die es beim Start verwenden soll // GfxPortnummer () uint16 // Vor.: Das Grafikfenster ist nicht offen, das Serverprogramm 'gfx2server' // läuft nicht. p ist eine freie Portnummer auf dem Rechner. // Eff.: Die Portnummer für das Serverprogramm ist auf p geändert. // SetzeGfxPortnummer(p uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Wenn w true ist, so erfolgen ab jetzt in der Konsole Ausgaben // zur Kommunikation zwischen Programm und dem Server für eine // mögliche Fehlersuche. Ist w false, so werden diese Ausgaben // unterdrückt (Standardfall). // SetzeServerprotokoll (w bool) // Vor.: - // Erg.: True ist geliefert, gdw. das Grafikfenster offen ist. // FensterOffen () bool // Vor.: Das Grafikfenster ist offen. // Eff.: Das Grafikfenster ist geschlossen. Das Serverprogramm 'gfx2server' // ist beendet. // FensterAus () // Vor.: Das Grafikfenster ist offen. // Erg.: Die Anzahl der Grafikfensterzeilen (Pixelzeilen) des gfx2-Fensters // ist geliefert. // Grafikzeilen () uint16 // Vor.: Das Grafikfenster ist offen. // Erg.: Die Anzahl der Grafikfensterspalten (Pixelspalten) des gfx2-Fensters // ist geliefert. // Grafikspalten () uint16 // Vor.: Das Grafikfenster ist offen. // Eff.: Das gfx-Fenster hat sichtbar den neuen Fenstertitel s. // In der Regel verwendet man hier den Programmnamen. // Fenstertitel (s string) // Vor.: Das Grafikfenster ist offen. // Eff.: Alle Pixel des Grafikfenster haben nun die aktuelle Stiftfarbe, // d.h., der Inhalt des Fensters ist gelöscht. // Cls () // Vor.: Das Grafikfenster ist offen. // Eff.: Die Zeichenfarbe ist gemäß dem RGB-Farbmodell neu gesetzt. // Beispiel: Stiftfarbe (0xFF, 0, 0) ist Rot. // Die Transparenz der Stiftfarbe kann mit der Funktion Transparenz // eingestellt werden. // Stiftfarbe (r,g,b uint8) // Vor.: Das Grafikfenster ist offen. // Eff.: Die Transparenz der Stiftfarbe bzw. die von "Zeichenoperationen" ist neu gesetzt. // 0 bedeutet keine Transparenz (Standard), 255 komplett durchsichtig. // Wenn also etwas nach dem Aufruf gezeichnet wird, so scheint vorher // Gezeichnetes ggf. durch. // Transparenz (t uint8) // Vor.: Das Grafikfenster ist offen. // Eff.: An der Position (x,y) ist ein Punkt in der aktuellen Stiftfarbe // gesetzt. // Punkt (x,y uint16) // Vor.: Das Grafikfenster ist offen. // Erg.: Der Rot-, Grün- und Blauanteil des Punktes mit den Koordinaten // (x,y) im Grafikfenster ist geliefert. // GibPunktfarbe (x,y uint16) (r,g,b uint8) // Vor.: Das Grafikfenster ist offen. // Eff.: Von der Position (x1,y1) bis (x2,y2) eine Strecke mit der // Strichbreite 1 Pixel in der aktuellen Stiftfarbe gezeichnet. // Linie (x1,y1,x2,y2 uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Um den Mittelpunkt M (x,y) ist ein Kreis mit dem Radius r mit der // Strichbreite 1 Pixel in der aktuellen Stiftfarbe gezeichnet. // Kreis (x,y,r uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Um den Mittelpunkt M (x,y) ist ein ausgefüllter Kreis mit dem // Radius r in der aktuellen Stiftfarbe gezeichnet. // Vollkreis (x,y,r uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Um den Mittelpunkt M (x,y) ist mit der horizontalen Halbachse rx // und der vertikalen Halbachse ry mit der Strichbreite 1 Pixel in // der aktuellen Stiftfarbe eine Ellipse gezeichnet. // Ellipse (x,y,rx,ry uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Um den Mittelpunkt M (x,y) ist mit der horizontalen Halbachse rx // und der vertikalen Halbachse ry in der aktuellen Stiftfarbe eine // ausgefüllte Ellipse gezeichnet. // Vollellipse (x,y,rx,ry uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Um den Mittelpunkt M (x,y) ist mit dem Radius r in der aktuellen // Stiftfarbe ein Kreisektor(Tortenstück:-)) gezeichnet. w1 ist // dabei der Startwinkel in Grad, w2 der Endwinkel in Grad. Ein
// Winkelmaß von 0 Grad bedeutet in Richtung Osten geht es los, dann // entgegengesetzt zum Uhrzeigersinn. // Kreissektor (x,y,r,w1,w2 uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Um den Mittelpunkt M (x,y) ist mit dem Radius r in der aktuellen // Stiftfarbe ein gefüllter Kreissegment gezeichnet. w1 ist dabei // der Startwinkel in Grad, w2 der Endwinkel in Grad. Ein Winkelmaß // von 0 Grad bedeutet in Richtung Osten geht es los, dann entgegen- // gesetzt zum Uhrzeigersinn. // Vollkreissektor (x,y,r,w1,w2 uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: In der aktuellen Stiftfarbe ist ein Rechteck gezeichnet. Die // Position (x1,y1) gibt die linke obere Ecke des Rechtecks an, b // die Breite in x-Richtung, h die Höhe in y-Richtung. Die Seiten // des Rechtecks verlaufen parallel zu den Achsen. // Rechteck (x1,y1,b,h uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: In der aktuellen Stiftfarbe ist ein gefülltes Rechteck gezeichnet. // Die Position (x1,y1) gibt die linke obere Ecke des Rechtecks an, // b die Breite in x-Richtung, h die Höhe in y-Richtung. Die Seiten // des Rechtecks verlaufen parallel zu den Achsen. // Vollrechteck (x1,y1,b,h uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: In der aktuellen Stiftfarbe ist ein Dreieck mit den Eckpunkt- // koordinaten (x1,y1), (x2,y2) und (x3,y3) gezeichnet. // Dreieck (x1,y1,x2,y2,x3,y3 uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: In der aktuellen Stiftfarbe ein gefülltes Dreieck mit den // Eckpunktkoordinaten (x1,y1), (x2,y2) und (x3,y3) gezeichnet. // Volldreieck (x1,y1,x2,y2,x3,y3 uint16) // Vor.: Das Grafikfenster ist offen. s beinhaltet maximal 255 Bytes und // ist ein ASCII-Code-String. // Eff.: In der aktuellen Stiftfarbe ist der Text s hingeschrieben ohne // den Hintergrund zu verändern. Die Position (x,y) ist die linke // obere Ecke des Bereichs des ersten Buchstaben von S. // Schreibe (x, y uint16, s string) // Vor.: s gibt die ttf-Datei des Fonts mit vollständigem Pfad an. // groesse gibt die gewünschte Punkthöhe der Buchstaben an. // Eff.: Wenn es die ttf-Datei gibt, so ist der angegebene Font nun der // aktuelle Font, der bei Aufruf von SchreibeFont () verwendet wird. // Erg.: -true- ist geliefert, gdw. die ttf-Datei an der Stelle lag und // der Font als aktueller Font gesetzt werden konnte. // SetzeFont (s string, groesse int) bool // Vor.: keine // Erg.: Der mit SetzeFont () hinterlegte Pfad inklusive Dateiname // des aktuell gewünschten Fonts ist geliefert. // GibFont () string // Vor.: Das Grafikfenster ist offen. s beinhaltet maximal 255 Bytes. // Eff.: In der aktuellen Stiftfarbe ist der Text s mit dem zuletzt mit // SetzeFont() gesetzten Font hingeschrieben ohne // den Hintergrund zu verändern. Die Position (x,y) ist die linke // obere Ecke des Bereichs des ersten Buchstaben von S. // SchreibeFont (x,y uint16, s string) // Vor.: Das Grafikfenster ist offen. s beinhaltet maximal 255 Bytes und // stellt den Dateinamen eines Bildes im bmp-Format dar. // Eff.: Ab der Position (x,y) ist das angegebene rechteckige Bild gemäß // der aktuell eingestellten Transparenz eingefügt. Die Position ist // die linke obere Ecke des Bildes. Die Bildkanten verlaufen parallel // zu den Achsen. // LadeBild (x, y uint16, s string) // Vor.: Das Grafikfenster ist offen. s beinhaltet maximal 255 Bytes und // stellt den Dateinamen eines Bildes im bmp-Format dar. // r,g und b geben eine Pixelfarbe an (ColorKey). // Eff.: Ab der Position (x,y) ist das angegebene rechteckige Bild gemäß // der eingestellten Transparenz eingefügt. Die Position ist die // linke obere Ecke des Bildes. // Die Bildkanten verlaufen parallel zu den Achsen. Alle Pixel des // Bildes mit den Farbwerten r,g und b werden jedoch vollkommen // transparent dargestellt! Ursprüngliche Pixel im Grafikfenster // werden hier nicht überzeichnet! // LadeBildMitColorKey (x,y uint16, s string, r,g,b uint8) // Vor.: Das Grafikfenster ist offen. s beinhaltet maximal 255 Bytes und // stellt den Dateinamen eines Bildes im bmp-Format dar. // Eff.: Das angegebene Bild ist in einen Zwischenspeicher (das Clipboard) // geladen. Vorher im Clipboard enthaltene Daten wurden damit überschrieben. // LadeBildInsClipboard (s string) // Vor.: Das Grafikfenster ist offen. // Eff.: Der gesamter Inhalt des Fensters ist in einen (versteckten) // Zwischenspeicher kopiert. Daten, die vorher in diesem Zwischen- // speicher waren, wurden überschrieben. // Archivieren () // Vor.: Das Grafikfenster ist offen. Archivieren wurde vorher mindestens // einmal aufgerufen und seit dem das Fenster nicht geschlossen. // Eff.: Der angegebene rechteckige Bereich des versteckten Zwischenspeichers // (s. Archivieren) ist an seine ursprüngliche Stelle ins Grafikfenster // zurückkopiert. Die gesetzte Transparenz hat keinen Einfluss auf die Funktion. // Restaurieren (x,y,b,h uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Der angegebene rechteckige Grafikfensterbereich ist in einem // Zwischenspeicher (das Clipboard) kopiert. Daten, die vorher in // diesem Zwischenspeicher waren, wurden überschrieben. // Clipboard_kopieren (x,y,b,h uint16) // Vor.: Das Grafikfenster ist offen, Clipboard_kopieren wurde vorher // mindestens einmal aufgerufen und seitdem wurde das Fenster // nicht geschlossen. // Eff.: Der Inhalt des Zwischenspeichers (Clipboard) ist an die angege- // bene Position (x,y) ins Grafikfenster kopiert. Dort vorher // vorhandene Daten wurden überschrieben, wobei die gesetzte Transparenz // entsprechenden Einfluss hatte. // Clipboard_einfuegen (x, y uint16) // Vor.: Das Grafikfenster ist offen, Clipboard_kopieren wurde vorher // mindestens einmal aufgerufen und seitdem wurde das Fenster // nicht geschlossen. r,g und b geben eine Pixelfarbe an. // Eff.: Der Inhalt des Zwischenspeichers (Clipboard) ist an die angege- // bene Position (x,y) ins Grafikfenster unter Beachtung der gesetzten // Transparenz kopiert. Alle Pixel des Clipboards mit dem durch r,g und b // festgelegten Farbwertes sind jedoch vollkommen transparent und änder // so das ursprüngliche Pixel im Grafikfenster an dieser Stelle nicht. // Clipboard_einfuegenMitColorKey (x,y uint16, r,g,b uint8) // Vor.: Das Grafikfenster ist offen. Sperren wurde noch nicht aufgerufen // bzw. der Aufruf wurde mit einem Aufruf von Entsperren 'neutralisiert'. // Eff.: Das Grafikfenster ist nun nur noch vom aufrufenden Prozess // 'beschreibbar', wenn alle anderen Prozesse vor einem Schreibzugriff // auf das Grafikfenster ebenfalls Sperren aufrufen. Gegebenenfalls // war der aufrufende Prozess solange blockiert, bis er den Zugriff // erhielt. Andere Prozesse, die nun Sperren ausführen, sind blockiert. // Sperren () // Vor.: Das Grafikfenster ist offen. Sperren wurde aufgerufen und seit // dem das Grafikfenster nicht geschlossen. // Eff.: Das Grafikfenster ist für andere Prozesse wieder zum 'Beschreiben' // freigegeben. // Entsperren () // Vor.: Das Grafikfenster ist offen. // Eff.: Die abgesetzten Grafikbefehle werden nicht sofort im Fenster, // sondern lediglich im 'Double-Buffer-Bereich' verdeckt durchgeführt. // UpdateAus () // Vor.: Das Grafikfenster ist offen und wurde nach einem 'UpdateAus()' // nicht geschlossen. // Eff.: Alle nach 'UpdateAus ()' durchgeführten Änderungen durch abgesetzte // Grafikbefehle sind nun sichtbar geworden. Folgende Befehle werden // wieder direkt umgesetzt. // UpdateAn () // Vor.: Das Grafikfenster ist offen. // Erg.: Der aufrufende Prozess war solange blockiert, bis eine Taste // auf der Tastatur gedrückt oder losgelassen wurde. Geliefert // ist mit 'taste' die Tastennummer. 'gedrückt' ist 1 (0),falls die // Taste gedrückt (losgelassen) wurde. 'tiefe' liefert die Kombination // der gedrückten Steuerungstasten. //TastaturLesen1 () (taste uint16, gedrueckt uint8, tiefe uint16) // Vor.: Das Grafikfenster ist offen. Die Tastaturbelegung ist deutsch. // Erg.: Wenn -tiefe- nur SHIFT oder STANDARD (also kein SHIFT) in Kombination // mit NUMLOCK und/oder ALT GR ist und eine Tastaturzeichen-Taste // mit -taste- übergeben wurde (also keine Steuertastenkombination), // so ist das entsprechende Tastaturzeichen als Rune geliefert. // Andernfalls ist rune(0) geliefert. // -tiefe- und -taste- erhält man i.d.R. durch Tastaturlesen1(). // Tastaturzeichen (taste, tiefe uint16) rune // Vor.: Das Grafikfenster ist offen. // Eff.: Ab jetzt werden bis zu 255 Tastaturereignisse in einem // versteckten Tastaturpuffer zwischengespeichert. Darüber hinaus- // gehende eingehende Tastaturevents gehen verloren. //TastaturpufferAn () // Vor.: Das Grafikfenster ist offen. // Eff.: Der Tastaturpuffer ist aus. Enthaltene Events sind verloren. //TastaturpufferAus () // Vor.: Das Grafikfenster ist offen. // Erg.: Das vorderste Element (gespeicherte Event) des Tastaturpuffers // ist ausgelesen, aus dem Puffer entfernt und zurueckgegeben: Geliefert // ist mit 'taste' die Tastennummer. 'gedrückt' ist 1 (0),falls die // Taste gedrückt (losgelassen) wurde. 'tiefe' liefert die Kombination // der gedrückten Steuerungstasten. // War der Puffer leer, so war der aufrufende Prozess solange // blockiert, bis etwas gelesen werden konnte. //TastaturpufferLesen1 () (taste uint16, gedrueckt uint8, tiefe uint16) // Vor.: Das Grafikfenster ist offen. // Erg.: Der aufrufende Prozess war solange blockiert, bis Daten von der // Maus gelesen werden konnten. Mit 'taste' erhält man die Nummer // der betreffenden Maustaste. Mit 'status' (1/0/-1), ob sie gedrückt // bzw. unverändert ist oder losgelassen wurde. 'mausX' und 'mausY' // sind die Koordinaten der Mauszeigerspitze. //MausLesen1 () (taste uint8, status int8, mausX, mausY uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Ab jetzt werden bis zu 255 Mausereignisse (Events) zwischen- // gespeichert.Darüber hinaus eingehende Maus-Events gehen verloren. //MauspufferAn () // Vor.: Das Grafikfenster ist offen. // Eff.: Der Mauspuffer ist deaktiviert. Enthaltene Ereignisse sind // verloren. //MauspufferAus () // Vor.: Das Grafikfenster ist offen. // Erg.: Das vorderste Mausereignis ist aus dem Puffer gelesen, dort // entfernt und zurückgegeben: Mit 'taste' erhält man die Nummer // der betreffenden Maustaste. Mit 'status' (1/0/-1), ob sie gedrückt // bzw. unverändert ist oder losgelassen wurde. 'mausX' und 'mausY' // sind die Koordinaten der Mauszeigerspitze. // War der Puffer leer, so war der aufrufende Prozess solange // blockiert, bis er etwas lesen konnte. //MauspufferLesen1 () (taste uint8,status int8, mausX, mausY uint16) // Vor.: Das Grafikfenster ist offen. // s ist der Dateiname der wav-Datei inklusive Pfad. Zum Zeipunkt // des Aufrufs werden gerade höchstens 9 .wav-Dateien abgespielt. // Eff.: Die angegebene wav-Datei wird ab jetzt auch abgespielt. // Das Programm läuft ohne Verzögerung weiter. // SpieleSound (s string) // Vor.: Das Grafikfenster ist offen. // Erg.: Das aktuelle Noten-Tempo ist geliefert, d.h. die Anzahl der vollen Noten pro Minute. // GibNotenTempo () uint8 // Vor.: 30 <= tempo <= 240 ; Das Grafikfenster ist offen. // Eff.: Das Noten-Tempo ist auf den Wert t gesetzt, es gibt also t volle Noten pro Minute. // SetzeNotenTempo (t uint8) // Vor.: Das Grafikfenster ist offen. // Ergebnis: Anschlagzeit, Abschwellzeit, Haltepegel und Ausklingzeit sind // in ms geliefert. // GibHuellkurve () (float64,float64,float64,float64) // Vor.: Das Grafikfenster ist offen. // a ist die Anschlagzeit in ms mit 0 <= a <= 1, // d ist die Abschwellzeit in ms mit 0<= d <= 5, // s ist der Haltepegel in Prozent vom Maximum mit 0<= s <= 1.0, // r ist die Ausklingzeit in ms mit 0< =r <= 5. // Eff.: Für die Hüllkurve zukünftig zu spielender Töne bzw. Noten sind // die Parameter gesetzt. // SetzeHuellkurve (a,d,s,r float64) // Vor.: Das Grafikfenster ist offen. // Erg.: Geliefert sind: // Abtastrate der WAV-Daten in Hz, z.B. 44100, // Auflösung der Klänge (1: 8 Bit; 2: 16 Bit), // die Anzahl der Kanäle (1: mono, 2:stereo), // die Signalform (0: Sinus, 1: Rechteck, 2:Dreieck, 3: Sägezahn) und // die Pulsweite HIGH bei Rechteckform als Prozentsatz zw. 0 und 1. // GibKlangparameter () (uint32,uint8,uint8,uint8,float64) // Vor.: Das Grafikfenster ist offen. // rate ist die Abtastrate, z.B. 11025, 22050 oder 44100. // auflösung ist 1 für 8 Bit oder 2 für 16 Bit. // kanaele ist 1 für mono oder 2 für stereo. // signal gibt die Signalform an: 0: Sinus, 1: Rechteck, 2:Dreieck, 3: Sägezahn // p ist die Pulsweite für Rechtecksignale und gibt den Prozentsatz (0<=p<=1) für den HIGH-Teil an. // Eff.: Die klangparameter sind auf die angegebenen Werte gesetzt. // SetzeKlangparameter(rate uint32, aufloesung,kanaele,signal uint8, p float64) // Vor.: Das gfx-Fenster ist offen. // Das erste Zeichen von tonname ist eine Ziffer von 0 bis 9 und gibt die Oktave an. // Erlaubte weitere Zeichen für den Notennamen sind "C","D","E","F","G","A","H","C#","D#","F#","G#","A#". // 0 < laenge <= 1; laenge 1: volle Note; 1.0/2: halbe Note, ..., 1.0/16: sechzehntel Note // 0.0<=wartedauer; Die Wartedauer gibt die Dauer in Notenlänge an, nach der nach dem Anspielen der // Note im Programmablauf fortgefahren wird. 0: keine Wartedauer; 1.0/2: Dauer einer halben Note, ... // Es werden gerade höchstens 9 Noten oder WAV-Dateien abgespielt. // Eff.: Der Ton wird gerade gespielt bzw. ist gespielt. Je nach Wartedauer wurde die Fortsetzung des Programms // verzögert. // Der voreingestellte Standard ist aus 'GibHuellkurve ()' und 'GibKlangParameter()' ersichtlich. // Die Einstellungen mit 'SetzeHuellkurve' und 'SetzeKlangparameter' haben Einfluss auf den "Ton". // SpieleNote (tonname string, laenge float64, wartedauer float64)
random_line_split
diag.rs
// Diagnostics engine use super::{Span, SrcMgr}; use std::cell::RefCell; use std::cmp; use std::fmt; use std::rc::Rc; use colored::{Color, Colorize}; /// Severity of the diagnostic message. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } impl Severity { /// Get the color corresponding to this severity. fn color(&self) -> Color { match self { Severity::Remark => Color::Blue, Severity::Info => Color::Black, Severity::Warning => Color::Magenta, Severity::Error | Severity::Fatal => Color::Red, } } } impl fmt::Display for Severity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let str = match self { Severity::Remark => "remark", Severity::Info => "info", Severity::Warning => "warning", Severity::Error => "error", Severity::Fatal => "fatal error", }; write!(f, "{}", str) } } /// A note for detailed message or suggesting how to fix it. pub struct Note { pub span: Span, pub fix: Option<String>, pub message: Option<String>, } /// A diagnostic message. pub struct Diagnostic { pub severity: Severity, pub message: String, /// This is the primary span that causes the issue. This will not be displayed. /// `new` function will automatically add the span to notes for it to be displayed. pub span: Option<Span>, pub notes: Vec<Note>, } /// Helpers for building diagnostic message. Intended to be called in chains. impl Diagnostic { pub fn new(severity: Severity, msg: impl Into<String>, span: Span) -> Self { Diagnostic { severity, message: msg.into(), span: Some(span), notes: vec![Note { span, fix: None, message: None, }], } } pub fn fix_primary(mut self, fix: impl Into<String>) -> Self { self.notes[0].fix = Some(fix.into()); self } pub fn fix(mut self, span: Span, fix: impl Into<String>) -> Self { self.notes.push(Note { span, fix: Some(fix.into()), message: None, }); self } } // Helper class for printing column number in a file with tabs and non-ASCII characters. struct VisualString { str: String, columns: Vec<usize>, } impl VisualString { fn new(str: &str, tab: usize) -> VisualString { let mut columns = Vec::with_capacity(str.len() + 1); columns.push(0); // Current visual string and visual length let mut vstr = String::new(); let mut vlen = 0; for ch in str.chars() { match ch { '\r' | '\n' => (), '\t' => { let newlen = (vlen + tab) / tab * tab; for _ in vlen..newlen { vstr.push(' '); } vlen = newlen } _ => { vstr.push(ch); vlen += 1 } } for _ in 0..ch.len_utf8() { columns.push(vlen); } } // Reserve a column for end-of-line character columns.push(vlen + 1); VisualString { str: vstr, columns: columns, } } fn visual_column(&self, pos: usize) -> usize { self.columns[pos] } fn visual_length(&self) -> usize { self.columns[self.columns.len() - 1] } fn visual_text(&self) -> &str { &self.str } } impl Diagnostic { pub fn print(&self, mgr: &SrcMgr, color: bool, tab: usize) { // Stringify and color severity let mut severity = format!("{}: ", self.severity); if color { severity = severity.color(self.severity.color()).to_string(); } // Convert spans to fat spans let primary_span = match self.notes.first().and_then(|x| mgr.find_span(x.span)) { None => { // If the message has no associated file, just print it if color { eprintln!("{}{}", severity.bold(), self.message.bold()); } else { eprintln!("{}{}", severity, self.message); } return; } Some(v) => v, }; // Obtain line map let src = &primary_span.source; let linemap = src.linemap(); // Get line number (starting from 0) let line = linemap.line_number(primary_span.start); // Get position within the line let line_start = linemap.line_start_pos(line); // Get source code line for handling let line_text = linemap.line(src, line); let vstr = VisualString::new(line_text, tab); // Get colored severity string // Generate the error message line let mut msg = format!( "{}:{}: {}{}", src.filename(), line + 1, severity, self.message ); if color { msg = msg.bold().to_string(); } // Allocate char vectors to hold indicators and hints // Make this 1 longer for possibility to point to the line break character. let mut indicators = vec![' '; vstr.visual_length() + 1]; let mut fixes = vec![' '; vstr.visual_length()]; let mut character = '^'; let mut has_fix = false; // Fill in ^ and ~ characters for all spans for note in &self.notes { let span = match mgr.find_span(note.span) { // The span is non-existent, continue instead None => continue, Some(v) => v, }; // Unlikely event, we cannot display this if !Rc::ptr_eq(&span.source, &primary_span.source) { continue; } // Get start and end position, clamped within the line. let start = span.start as isize - line_start as isize; let start_clamp = cmp::min(cmp::max(start, 0) as usize, line_text.len()); let end = span.end as isize - line_start as isize; let end_clamp = cmp::min(cmp::max(end, 0) as usize, line_text.len() + 1); for i in vstr.visual_column(start_clamp)..vstr.visual_column(end_clamp) { indicators[i] = character; } // We can only display it if it partially covers this line if note.fix.is_some() && end >= 0 && start <= line_text.len() as isize { let mut vptr = cmp::min(cmp::max(start, 0) as usize, line_text.len()); // Now replace the part in vector with the replacement suggestion for ch in note.fix.as_ref().unwrap().chars() { if vptr >= fixes.len() { fixes.push(ch); } else { fixes[vptr] = ch; } vptr += 1; } has_fix = true; } // For non-primary notes, the character is different. character = '~'; } let mut indicator_line: String = indicators.into_iter().collect(); if color { indicator_line = indicator_line.green().bold().to_string(); } if has_fix { let mut line: String = fixes.into_iter().collect(); if color { line = line.green().to_string(); } eprintln!( "{}\n{}\n{}\n{}", msg, vstr.visual_text(), indicator_line, line ); } else { eprintln!("{}\n{}\n{}", msg, vstr.visual_text(), indicator_line); } } } /// Diagnostic manager struct DiagMgrMut { src: Rc<SrcMgr>, diagnostics: Vec<Diagnostic>, } pub struct DiagMgr { mutable: RefCell<DiagMgrMut>, } impl DiagMgr { /// Create a new diagnostics manager pub fn new(mgr: Rc<SrcMgr>) -> Self { Self { mutable: RefCell::new(DiagMgrMut { src: mgr, diagnostics: Vec::new(), }), } } /// Add a new diagnostic. pub fn report(&self, diag: Diagnostic) { let mut m = self.mutable.borrow_mut(); diag.print(&m.src, true, 4); m.diagnostics.push(diag); } /// Create a errpr diagnostic from message and span and report it. pub fn report_span<M: Into<String>>(&self, severity: Severity, msg: M, span: Span) { self.report(Diagnostic::new(severity, msg.into(), span)); } /// Create a errpr diagnostic from message and span and report it. pub fn report_error<M: Into<String>>(&self, msg: M, span: Span) { self.report(Diagnostic::new(Severity::Error, msg.into(), span)); } /// Create a fatal diagnostic from message and span and report it. In addition, abort /// execution with a panic. pub fn report_fatal<M: Into<String>>(&self, msg: M, span: Span) -> !
/// Clear exsting diagnostics pub fn clear(&self) { let mut m = self.mutable.borrow_mut(); m.diagnostics.clear(); } /// Check if there is any fatal error. pub fn has_fatal(&self) -> bool { let m = self.mutable.borrow(); m.diagnostics .iter() .any(|diag| diag.severity == Severity::Fatal) } /// Check if there is any error. pub fn has_error(&self) -> bool { let m = self.mutable.borrow(); m.diagnostics .iter() .any(|diag| diag.severity == Severity::Error || diag.severity == Severity::Fatal) } }
{ self.report(Diagnostic::new(Severity::Fatal, msg.into(), span)); std::panic::panic_any(Severity::Fatal); }
identifier_body
diag.rs
// Diagnostics engine use super::{Span, SrcMgr}; use std::cell::RefCell; use std::cmp; use std::fmt; use std::rc::Rc; use colored::{Color, Colorize}; /// Severity of the diagnostic message. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } impl Severity { /// Get the color corresponding to this severity. fn color(&self) -> Color { match self { Severity::Remark => Color::Blue, Severity::Info => Color::Black, Severity::Warning => Color::Magenta, Severity::Error | Severity::Fatal => Color::Red, } } } impl fmt::Display for Severity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let str = match self { Severity::Remark => "remark", Severity::Info => "info", Severity::Warning => "warning", Severity::Error => "error", Severity::Fatal => "fatal error", }; write!(f, "{}", str) } } /// A note for detailed message or suggesting how to fix it. pub struct Note { pub span: Span, pub fix: Option<String>, pub message: Option<String>, } /// A diagnostic message. pub struct Diagnostic { pub severity: Severity, pub message: String, /// This is the primary span that causes the issue. This will not be displayed. /// `new` function will automatically add the span to notes for it to be displayed. pub span: Option<Span>, pub notes: Vec<Note>, } /// Helpers for building diagnostic message. Intended to be called in chains. impl Diagnostic { pub fn new(severity: Severity, msg: impl Into<String>, span: Span) -> Self { Diagnostic { severity, message: msg.into(), span: Some(span), notes: vec![Note { span, fix: None, message: None, }], } } pub fn fix_primary(mut self, fix: impl Into<String>) -> Self { self.notes[0].fix = Some(fix.into()); self } pub fn fix(mut self, span: Span, fix: impl Into<String>) -> Self { self.notes.push(Note { span, fix: Some(fix.into()), message: None, }); self } } // Helper class for printing column number in a file with tabs and non-ASCII characters. struct VisualString { str: String, columns: Vec<usize>, } impl VisualString { fn new(str: &str, tab: usize) -> VisualString { let mut columns = Vec::with_capacity(str.len() + 1); columns.push(0); // Current visual string and visual length let mut vstr = String::new(); let mut vlen = 0; for ch in str.chars() { match ch { '\r' | '\n' => (), '\t' => { let newlen = (vlen + tab) / tab * tab; for _ in vlen..newlen { vstr.push(' '); } vlen = newlen } _ => { vstr.push(ch); vlen += 1 }
} } // Reserve a column for end-of-line character columns.push(vlen + 1); VisualString { str: vstr, columns: columns, } } fn visual_column(&self, pos: usize) -> usize { self.columns[pos] } fn visual_length(&self) -> usize { self.columns[self.columns.len() - 1] } fn visual_text(&self) -> &str { &self.str } } impl Diagnostic { pub fn print(&self, mgr: &SrcMgr, color: bool, tab: usize) { // Stringify and color severity let mut severity = format!("{}: ", self.severity); if color { severity = severity.color(self.severity.color()).to_string(); } // Convert spans to fat spans let primary_span = match self.notes.first().and_then(|x| mgr.find_span(x.span)) { None => { // If the message has no associated file, just print it if color { eprintln!("{}{}", severity.bold(), self.message.bold()); } else { eprintln!("{}{}", severity, self.message); } return; } Some(v) => v, }; // Obtain line map let src = &primary_span.source; let linemap = src.linemap(); // Get line number (starting from 0) let line = linemap.line_number(primary_span.start); // Get position within the line let line_start = linemap.line_start_pos(line); // Get source code line for handling let line_text = linemap.line(src, line); let vstr = VisualString::new(line_text, tab); // Get colored severity string // Generate the error message line let mut msg = format!( "{}:{}: {}{}", src.filename(), line + 1, severity, self.message ); if color { msg = msg.bold().to_string(); } // Allocate char vectors to hold indicators and hints // Make this 1 longer for possibility to point to the line break character. let mut indicators = vec![' '; vstr.visual_length() + 1]; let mut fixes = vec![' '; vstr.visual_length()]; let mut character = '^'; let mut has_fix = false; // Fill in ^ and ~ characters for all spans for note in &self.notes { let span = match mgr.find_span(note.span) { // The span is non-existent, continue instead None => continue, Some(v) => v, }; // Unlikely event, we cannot display this if !Rc::ptr_eq(&span.source, &primary_span.source) { continue; } // Get start and end position, clamped within the line. let start = span.start as isize - line_start as isize; let start_clamp = cmp::min(cmp::max(start, 0) as usize, line_text.len()); let end = span.end as isize - line_start as isize; let end_clamp = cmp::min(cmp::max(end, 0) as usize, line_text.len() + 1); for i in vstr.visual_column(start_clamp)..vstr.visual_column(end_clamp) { indicators[i] = character; } // We can only display it if it partially covers this line if note.fix.is_some() && end >= 0 && start <= line_text.len() as isize { let mut vptr = cmp::min(cmp::max(start, 0) as usize, line_text.len()); // Now replace the part in vector with the replacement suggestion for ch in note.fix.as_ref().unwrap().chars() { if vptr >= fixes.len() { fixes.push(ch); } else { fixes[vptr] = ch; } vptr += 1; } has_fix = true; } // For non-primary notes, the character is different. character = '~'; } let mut indicator_line: String = indicators.into_iter().collect(); if color { indicator_line = indicator_line.green().bold().to_string(); } if has_fix { let mut line: String = fixes.into_iter().collect(); if color { line = line.green().to_string(); } eprintln!( "{}\n{}\n{}\n{}", msg, vstr.visual_text(), indicator_line, line ); } else { eprintln!("{}\n{}\n{}", msg, vstr.visual_text(), indicator_line); } } } /// Diagnostic manager struct DiagMgrMut { src: Rc<SrcMgr>, diagnostics: Vec<Diagnostic>, } pub struct DiagMgr { mutable: RefCell<DiagMgrMut>, } impl DiagMgr { /// Create a new diagnostics manager pub fn new(mgr: Rc<SrcMgr>) -> Self { Self { mutable: RefCell::new(DiagMgrMut { src: mgr, diagnostics: Vec::new(), }), } } /// Add a new diagnostic. pub fn report(&self, diag: Diagnostic) { let mut m = self.mutable.borrow_mut(); diag.print(&m.src, true, 4); m.diagnostics.push(diag); } /// Create a errpr diagnostic from message and span and report it. pub fn report_span<M: Into<String>>(&self, severity: Severity, msg: M, span: Span) { self.report(Diagnostic::new(severity, msg.into(), span)); } /// Create a errpr diagnostic from message and span and report it. pub fn report_error<M: Into<String>>(&self, msg: M, span: Span) { self.report(Diagnostic::new(Severity::Error, msg.into(), span)); } /// Create a fatal diagnostic from message and span and report it. In addition, abort /// execution with a panic. pub fn report_fatal<M: Into<String>>(&self, msg: M, span: Span) -> ! { self.report(Diagnostic::new(Severity::Fatal, msg.into(), span)); std::panic::panic_any(Severity::Fatal); } /// Clear exsting diagnostics pub fn clear(&self) { let mut m = self.mutable.borrow_mut(); m.diagnostics.clear(); } /// Check if there is any fatal error. pub fn has_fatal(&self) -> bool { let m = self.mutable.borrow(); m.diagnostics .iter() .any(|diag| diag.severity == Severity::Fatal) } /// Check if there is any error. pub fn has_error(&self) -> bool { let m = self.mutable.borrow(); m.diagnostics .iter() .any(|diag| diag.severity == Severity::Error || diag.severity == Severity::Fatal) } }
} for _ in 0..ch.len_utf8() { columns.push(vlen);
random_line_split
diag.rs
// Diagnostics engine use super::{Span, SrcMgr}; use std::cell::RefCell; use std::cmp; use std::fmt; use std::rc::Rc; use colored::{Color, Colorize}; /// Severity of the diagnostic message. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } impl Severity { /// Get the color corresponding to this severity. fn color(&self) -> Color { match self { Severity::Remark => Color::Blue, Severity::Info => Color::Black, Severity::Warning => Color::Magenta, Severity::Error | Severity::Fatal => Color::Red, } } } impl fmt::Display for Severity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let str = match self { Severity::Remark => "remark", Severity::Info => "info", Severity::Warning => "warning", Severity::Error => "error", Severity::Fatal => "fatal error", }; write!(f, "{}", str) } } /// A note for detailed message or suggesting how to fix it. pub struct Note { pub span: Span, pub fix: Option<String>, pub message: Option<String>, } /// A diagnostic message. pub struct Diagnostic { pub severity: Severity, pub message: String, /// This is the primary span that causes the issue. This will not be displayed. /// `new` function will automatically add the span to notes for it to be displayed. pub span: Option<Span>, pub notes: Vec<Note>, } /// Helpers for building diagnostic message. Intended to be called in chains. impl Diagnostic { pub fn new(severity: Severity, msg: impl Into<String>, span: Span) -> Self { Diagnostic { severity, message: msg.into(), span: Some(span), notes: vec![Note { span, fix: None, message: None, }], } } pub fn fix_primary(mut self, fix: impl Into<String>) -> Self { self.notes[0].fix = Some(fix.into()); self } pub fn fix(mut self, span: Span, fix: impl Into<String>) -> Self { self.notes.push(Note { span, fix: Some(fix.into()), message: None, }); self } } // Helper class for printing column number in a file with tabs and non-ASCII characters. struct VisualString { str: String, columns: Vec<usize>, } impl VisualString { fn new(str: &str, tab: usize) -> VisualString { let mut columns = Vec::with_capacity(str.len() + 1); columns.push(0); // Current visual string and visual length let mut vstr = String::new(); let mut vlen = 0; for ch in str.chars() { match ch { '\r' | '\n' => (), '\t' => { let newlen = (vlen + tab) / tab * tab; for _ in vlen..newlen { vstr.push(' '); } vlen = newlen } _ => { vstr.push(ch); vlen += 1 } } for _ in 0..ch.len_utf8() { columns.push(vlen); } } // Reserve a column for end-of-line character columns.push(vlen + 1); VisualString { str: vstr, columns: columns, } } fn visual_column(&self, pos: usize) -> usize { self.columns[pos] } fn visual_length(&self) -> usize { self.columns[self.columns.len() - 1] } fn visual_text(&self) -> &str { &self.str } } impl Diagnostic { pub fn print(&self, mgr: &SrcMgr, color: bool, tab: usize) { // Stringify and color severity let mut severity = format!("{}: ", self.severity); if color { severity = severity.color(self.severity.color()).to_string(); } // Convert spans to fat spans let primary_span = match self.notes.first().and_then(|x| mgr.find_span(x.span)) { None => { // If the message has no associated file, just print it if color { eprintln!("{}{}", severity.bold(), self.message.bold()); } else { eprintln!("{}{}", severity, self.message); } return; } Some(v) => v, }; // Obtain line map let src = &primary_span.source; let linemap = src.linemap(); // Get line number (starting from 0) let line = linemap.line_number(primary_span.start); // Get position within the line let line_start = linemap.line_start_pos(line); // Get source code line for handling let line_text = linemap.line(src, line); let vstr = VisualString::new(line_text, tab); // Get colored severity string // Generate the error message line let mut msg = format!( "{}:{}: {}{}", src.filename(), line + 1, severity, self.message ); if color { msg = msg.bold().to_string(); } // Allocate char vectors to hold indicators and hints // Make this 1 longer for possibility to point to the line break character. let mut indicators = vec![' '; vstr.visual_length() + 1]; let mut fixes = vec![' '; vstr.visual_length()]; let mut character = '^'; let mut has_fix = false; // Fill in ^ and ~ characters for all spans for note in &self.notes { let span = match mgr.find_span(note.span) { // The span is non-existent, continue instead None => continue, Some(v) => v, }; // Unlikely event, we cannot display this if !Rc::ptr_eq(&span.source, &primary_span.source) { continue; } // Get start and end position, clamped within the line. let start = span.start as isize - line_start as isize; let start_clamp = cmp::min(cmp::max(start, 0) as usize, line_text.len()); let end = span.end as isize - line_start as isize; let end_clamp = cmp::min(cmp::max(end, 0) as usize, line_text.len() + 1); for i in vstr.visual_column(start_clamp)..vstr.visual_column(end_clamp) { indicators[i] = character; } // We can only display it if it partially covers this line if note.fix.is_some() && end >= 0 && start <= line_text.len() as isize { let mut vptr = cmp::min(cmp::max(start, 0) as usize, line_text.len()); // Now replace the part in vector with the replacement suggestion for ch in note.fix.as_ref().unwrap().chars() { if vptr >= fixes.len() { fixes.push(ch); } else { fixes[vptr] = ch; } vptr += 1; } has_fix = true; } // For non-primary notes, the character is different. character = '~'; } let mut indicator_line: String = indicators.into_iter().collect(); if color { indicator_line = indicator_line.green().bold().to_string(); } if has_fix { let mut line: String = fixes.into_iter().collect(); if color { line = line.green().to_string(); } eprintln!( "{}\n{}\n{}\n{}", msg, vstr.visual_text(), indicator_line, line ); } else { eprintln!("{}\n{}\n{}", msg, vstr.visual_text(), indicator_line); } } } /// Diagnostic manager struct DiagMgrMut { src: Rc<SrcMgr>, diagnostics: Vec<Diagnostic>, } pub struct DiagMgr { mutable: RefCell<DiagMgrMut>, } impl DiagMgr { /// Create a new diagnostics manager pub fn new(mgr: Rc<SrcMgr>) -> Self { Self { mutable: RefCell::new(DiagMgrMut { src: mgr, diagnostics: Vec::new(), }), } } /// Add a new diagnostic. pub fn
(&self, diag: Diagnostic) { let mut m = self.mutable.borrow_mut(); diag.print(&m.src, true, 4); m.diagnostics.push(diag); } /// Create a errpr diagnostic from message and span and report it. pub fn report_span<M: Into<String>>(&self, severity: Severity, msg: M, span: Span) { self.report(Diagnostic::new(severity, msg.into(), span)); } /// Create a errpr diagnostic from message and span and report it. pub fn report_error<M: Into<String>>(&self, msg: M, span: Span) { self.report(Diagnostic::new(Severity::Error, msg.into(), span)); } /// Create a fatal diagnostic from message and span and report it. In addition, abort /// execution with a panic. pub fn report_fatal<M: Into<String>>(&self, msg: M, span: Span) -> ! { self.report(Diagnostic::new(Severity::Fatal, msg.into(), span)); std::panic::panic_any(Severity::Fatal); } /// Clear exsting diagnostics pub fn clear(&self) { let mut m = self.mutable.borrow_mut(); m.diagnostics.clear(); } /// Check if there is any fatal error. pub fn has_fatal(&self) -> bool { let m = self.mutable.borrow(); m.diagnostics .iter() .any(|diag| diag.severity == Severity::Fatal) } /// Check if there is any error. pub fn has_error(&self) -> bool { let m = self.mutable.borrow(); m.diagnostics .iter() .any(|diag| diag.severity == Severity::Error || diag.severity == Severity::Fatal) } }
report
identifier_name
lib.rs
// Copyright 2016 The android_logger Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! A logger which writes to android output. //! //! ## Example //! //! ``` //! #[macro_use] extern crate log; //! extern crate android_logger; //! //! use log::Level; //! use android_logger::Filter; //! //! /// Android code may not have obvious "main", this is just an example. //! fn main() { //! android_logger::init_once( //! Filter::default() //! .with_min_level(Level::Trace) //! ); //! //! debug!("this is a debug {}", "message"); //! error!("this is printed by default"); //! } //! ``` //! //! ## Example with module path filter //! //! It is possible to limit log messages to output from a specific crate: //! //! ``` //! #[macro_use] extern crate log; //! extern crate android_logger; //! //! use log::Level; //! use android_logger::Filter; //! //! fn main() { //! android_logger::init_once( //! Filter::default() //! .with_min_level(Level::Trace) //! .with_allowed_module_path("hello::crate") //! ); //! //! // .. //! } //! ``` #[cfg(target_os = "android")] extern crate android_log_sys as log_ffi; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::sync::RwLock; #[cfg(target_os = "android")] use log_ffi::LogPriority; use log::{Level, Log, Metadata, Record}; use std::ffi::CStr; use std::mem; use std::fmt; use std::ptr; /// Output log to android system. #[cfg(target_os = "android")] fn android_log(prio: log_ffi::LogPriority, tag: &CStr, msg: &CStr) { unsafe { log_ffi::__android_log_write( prio as log_ffi::c_int, tag.as_ptr() as *const log_ffi::c_char, msg.as_ptr() as *const log_ffi::c_char, ) }; } /// Dummy output placeholder for tests. #[cfg(not(target_os = "android"))] fn android_log(_priority: Level, _tag: &CStr, _msg: &CStr) {} /// Underlying android logger backend pub struct AndroidLogger { filter: RwLock<Filter>, } lazy_static! { static ref ANDROID_LOGGER: AndroidLogger = AndroidLogger::default(); } const LOGGING_TAG_MAX_LEN: usize = 23; const LOGGING_MSG_MAX_LEN: usize = 4000; impl Default for AndroidLogger { /// Create a new logger with default filter fn default() -> AndroidLogger { AndroidLogger { filter: RwLock::new(Filter::default()), } } } impl Log for AndroidLogger { fn enabled(&self, _: &Metadata) -> bool { true } fn log(&self, record: &Record) { if let Some(module_path) = record.module_path() { let filter = self.filter .read() .expect("failed to acquire android_log filter lock for read"); if !filter.is_module_path_allowed(module_path) { return; } } // tag must not exceed LOGGING_TAG_MAX_LEN let mut tag_bytes: [u8; LOGGING_TAG_MAX_LEN + 1] = unsafe { mem::uninitialized() }; // truncate the tag here to fit into LOGGING_TAG_MAX_LEN self.fill_tag_bytes(&mut tag_bytes, record); // use stack array as C string let tag: &CStr = unsafe { CStr::from_ptr(mem::transmute(tag_bytes.as_ptr())) }; // message must not exceed LOGGING_MSG_MAX_LEN // therefore split log message into multiple log calls let mut writer = PlatformLogWriter::new(record.level(), tag); // use PlatformLogWriter to output chunks if they exceed max size let _ = fmt::write(&mut writer, *record.args()); // output the remaining message (this would usually be the most common case) writer.flush(); } fn flush(&self) {} } impl AndroidLogger { fn fill_tag_bytes(&self, array: &mut [u8], record: &Record) { let tag_bytes_iter = record.module_path().unwrap_or_default().bytes(); if tag_bytes_iter.len() > LOGGING_TAG_MAX_LEN { for (input, output) in tag_bytes_iter .take(LOGGING_TAG_MAX_LEN - 2) .chain(b"..\0".iter().cloned()) .zip(array.iter_mut()) { *output = input; } } else { for (input, output) in tag_bytes_iter .chain(b"\0".iter().cloned()) .zip(array.iter_mut()) { *output = input; } } } } /// Filter for android logger. pub struct Filter { log_level: Option<Level>, allow_module_paths: Vec<String>, } impl Default for Filter { fn default() -> Self { Filter { log_level: None, allow_module_paths: Vec::new(), } } } impl Filter { /// Change the minimum log level. /// /// All values above the set level are logged. For example, if /// `Warn` is set, the `Error` is logged too, but `Info` isn't. pub fn with_min_level(mut self, level: Level) -> Self { self.log_level = Some(level); self } /// Set allowed module path. /// /// Allow log entry only if module path matches specified path exactly. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default().with_allowed_module_path("crate"); /// /// assert!(filter.is_module_path_allowed("crate")); /// assert!(!filter.is_module_path_allowed("other_crate")); /// assert!(!filter.is_module_path_allowed("crate::subcrate")); /// ``` /// /// ## Multiple rules example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_path("A") /// .with_allowed_module_path("B"); /// /// assert!(filter.is_module_path_allowed("A")); /// assert!(filter.is_module_path_allowed("B")); /// assert!(!filter.is_module_path_allowed("C")); /// assert!(!filter.is_module_path_allowed("A::B")); /// ``` pub fn with_allowed_module_path<S: Into<String>>(mut self, path: S) -> Self
/// Set multiple allowed module paths. /// /// Same as `with_allowed_module_path`, but accepts list of paths. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_paths(["A", "B"].iter().map(|i| i.to_string())); /// /// assert!(filter.is_module_path_allowed("A")); /// assert!(filter.is_module_path_allowed("B")); /// assert!(!filter.is_module_path_allowed("C")); /// assert!(!filter.is_module_path_allowed("A::B")); /// ``` pub fn with_allowed_module_paths<I: IntoIterator<Item = String>>(mut self, paths: I) -> Self { self.allow_module_paths.extend(paths.into_iter()); self } /// Check if module path is allowed by filter rules. pub fn is_module_path_allowed(&self, path: &str) -> bool { if self.allow_module_paths.is_empty() { return true; } self.allow_module_paths .iter() .any(|allowed_path| allowed_path == path) } } #[cfg(test)] mod tests { use super::Filter; #[test] fn with_allowed_module_path() { assert!(Filter::default().is_module_path_allowed("random")); } } struct PlatformLogWriter<'a> { #[cfg(target_os = "android")] priority: LogPriority, #[cfg(not(target_os = "android"))] priority: Level, len: usize, last_newline_index: usize, tag: &'a CStr, buffer: [u8; LOGGING_MSG_MAX_LEN + 1], } impl<'a> PlatformLogWriter<'a> { #[cfg(target_os = "android")] pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter { PlatformLogWriter { priority: match level { Level::Warn => LogPriority::WARN, Level::Info => LogPriority::INFO, Level::Debug => LogPriority::DEBUG, Level::Error => LogPriority::ERROR, Level::Trace => LogPriority::VERBOSE, }, len: 0, last_newline_index: 0, tag: tag, buffer: unsafe { mem::uninitialized() }, } } #[cfg(not(target_os = "android"))] pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter { PlatformLogWriter { priority: level, len: 0, last_newline_index: 0, tag: tag, buffer: unsafe { mem::uninitialized() }, } } /// Flush some bytes to android logger. /// /// If there is a newline, flush up to it. /// If ther was no newline, flush all. /// /// Not guaranteed to flush everything. fn temporal_flush(&mut self) { let total_len = self.len; if total_len == 0 { return; } if self.last_newline_index > 0 { let copy_from_index = self.last_newline_index; let remaining_chunk_len = total_len - copy_from_index; self.output_specified_len(copy_from_index); self.copy_bytes_to_start(copy_from_index, remaining_chunk_len); self.len = remaining_chunk_len; } else { self.output_specified_len(total_len); self.len = 0; } self.last_newline_index = 0; } /// Flush everything remaining to android logger. fn flush(&mut self) { let total_len = self.len; if total_len == 0 { return; } self.output_specified_len(total_len); self.len = 0; self.last_newline_index = 0; } /// Output buffer up until the \0 which will be placed at `len` position. fn output_specified_len(&mut self, len: usize) { let mut last_byte: u8 = b'\0'; mem::swap(&mut last_byte, unsafe { self.buffer.get_unchecked_mut(len) }); let msg: &CStr = unsafe { CStr::from_ptr(mem::transmute(self.buffer.as_ptr())) }; android_log(self.priority, self.tag, msg); *unsafe { self.buffer.get_unchecked_mut(len) } = last_byte; } /// Copy `len` bytes from `index` position to starting position. fn copy_bytes_to_start(&mut self, index: usize, len: usize) { let src = unsafe { self.buffer.as_ptr().offset(index as isize) }; let dst = self.buffer.as_mut_ptr(); unsafe { ptr::copy(src, dst, len) }; } } impl<'a> fmt::Write for PlatformLogWriter<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { let mut incomming_bytes = s.as_bytes(); while !incomming_bytes.is_empty() { let len = self.len; // write everything possible to buffer and mark last \n let new_len = len + incomming_bytes.len(); let last_newline = self.buffer[len..LOGGING_MSG_MAX_LEN] .iter_mut() .zip(incomming_bytes) .enumerate() .fold(None, |acc, (i, (output, input))| { *output = *input; if *input == b'\n' { Some(i) } else { acc } }); // update last \n index if let Some(newline) = last_newline { self.last_newline_index = len + newline; } // calculate how many bytes were written let written_len = if new_len <= LOGGING_MSG_MAX_LEN { // if the len was not exceeded self.len = new_len; new_len - len // written len } else { // if new length was exceeded self.len = LOGGING_MSG_MAX_LEN; self.temporal_flush(); LOGGING_MSG_MAX_LEN - len // written len }; incomming_bytes = &incomming_bytes[written_len..]; } Ok(()) } } /// Send a log record to Android logging backend. /// /// This action does not require initialization. However, without initialization it /// will use the default filter, which allows all logs. pub fn log(record: &Record) { ANDROID_LOGGER.log(record) } /// Initializes the global logger with an android logger. /// /// This can be called many times, but will only initialize logging once, /// and will not replace any other previously initialized logger. /// /// It is ok to call this at the activity creation, and it will be /// repeatedly called on every lifecycle restart (i.e. screen rotation). pub fn init_once(filter: Filter) { if let Err(err) = log::set_logger(&*ANDROID_LOGGER) { debug!("android_logger: log::set_logger failed: {}", err); } else { if let Some(level) = filter.log_level { log::set_max_level(level.to_level_filter()); } *ANDROID_LOGGER .filter .write() .expect("failed to acquire android_log filter lock for write") = filter; } }
{ self.allow_module_paths.push(path.into()); self }
identifier_body
lib.rs
// Copyright 2016 The android_logger Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! A logger which writes to android output. //! //! ## Example //! //! ``` //! #[macro_use] extern crate log; //! extern crate android_logger; //! //! use log::Level; //! use android_logger::Filter; //! //! /// Android code may not have obvious "main", this is just an example. //! fn main() { //! android_logger::init_once( //! Filter::default() //! .with_min_level(Level::Trace) //! ); //! //! debug!("this is a debug {}", "message"); //! error!("this is printed by default"); //! } //! ``` //! //! ## Example with module path filter //! //! It is possible to limit log messages to output from a specific crate: //! //! ``` //! #[macro_use] extern crate log; //! extern crate android_logger; //! //! use log::Level; //! use android_logger::Filter; //! //! fn main() { //! android_logger::init_once( //! Filter::default() //! .with_min_level(Level::Trace) //! .with_allowed_module_path("hello::crate") //! ); //! //! // .. //! } //! ``` #[cfg(target_os = "android")] extern crate android_log_sys as log_ffi; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::sync::RwLock; #[cfg(target_os = "android")] use log_ffi::LogPriority; use log::{Level, Log, Metadata, Record}; use std::ffi::CStr; use std::mem; use std::fmt; use std::ptr; /// Output log to android system. #[cfg(target_os = "android")] fn android_log(prio: log_ffi::LogPriority, tag: &CStr, msg: &CStr) { unsafe { log_ffi::__android_log_write( prio as log_ffi::c_int, tag.as_ptr() as *const log_ffi::c_char, msg.as_ptr() as *const log_ffi::c_char, ) }; } /// Dummy output placeholder for tests. #[cfg(not(target_os = "android"))] fn
(_priority: Level, _tag: &CStr, _msg: &CStr) {} /// Underlying android logger backend pub struct AndroidLogger { filter: RwLock<Filter>, } lazy_static! { static ref ANDROID_LOGGER: AndroidLogger = AndroidLogger::default(); } const LOGGING_TAG_MAX_LEN: usize = 23; const LOGGING_MSG_MAX_LEN: usize = 4000; impl Default for AndroidLogger { /// Create a new logger with default filter fn default() -> AndroidLogger { AndroidLogger { filter: RwLock::new(Filter::default()), } } } impl Log for AndroidLogger { fn enabled(&self, _: &Metadata) -> bool { true } fn log(&self, record: &Record) { if let Some(module_path) = record.module_path() { let filter = self.filter .read() .expect("failed to acquire android_log filter lock for read"); if !filter.is_module_path_allowed(module_path) { return; } } // tag must not exceed LOGGING_TAG_MAX_LEN let mut tag_bytes: [u8; LOGGING_TAG_MAX_LEN + 1] = unsafe { mem::uninitialized() }; // truncate the tag here to fit into LOGGING_TAG_MAX_LEN self.fill_tag_bytes(&mut tag_bytes, record); // use stack array as C string let tag: &CStr = unsafe { CStr::from_ptr(mem::transmute(tag_bytes.as_ptr())) }; // message must not exceed LOGGING_MSG_MAX_LEN // therefore split log message into multiple log calls let mut writer = PlatformLogWriter::new(record.level(), tag); // use PlatformLogWriter to output chunks if they exceed max size let _ = fmt::write(&mut writer, *record.args()); // output the remaining message (this would usually be the most common case) writer.flush(); } fn flush(&self) {} } impl AndroidLogger { fn fill_tag_bytes(&self, array: &mut [u8], record: &Record) { let tag_bytes_iter = record.module_path().unwrap_or_default().bytes(); if tag_bytes_iter.len() > LOGGING_TAG_MAX_LEN { for (input, output) in tag_bytes_iter .take(LOGGING_TAG_MAX_LEN - 2) .chain(b"..\0".iter().cloned()) .zip(array.iter_mut()) { *output = input; } } else { for (input, output) in tag_bytes_iter .chain(b"\0".iter().cloned()) .zip(array.iter_mut()) { *output = input; } } } } /// Filter for android logger. pub struct Filter { log_level: Option<Level>, allow_module_paths: Vec<String>, } impl Default for Filter { fn default() -> Self { Filter { log_level: None, allow_module_paths: Vec::new(), } } } impl Filter { /// Change the minimum log level. /// /// All values above the set level are logged. For example, if /// `Warn` is set, the `Error` is logged too, but `Info` isn't. pub fn with_min_level(mut self, level: Level) -> Self { self.log_level = Some(level); self } /// Set allowed module path. /// /// Allow log entry only if module path matches specified path exactly. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default().with_allowed_module_path("crate"); /// /// assert!(filter.is_module_path_allowed("crate")); /// assert!(!filter.is_module_path_allowed("other_crate")); /// assert!(!filter.is_module_path_allowed("crate::subcrate")); /// ``` /// /// ## Multiple rules example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_path("A") /// .with_allowed_module_path("B"); /// /// assert!(filter.is_module_path_allowed("A")); /// assert!(filter.is_module_path_allowed("B")); /// assert!(!filter.is_module_path_allowed("C")); /// assert!(!filter.is_module_path_allowed("A::B")); /// ``` pub fn with_allowed_module_path<S: Into<String>>(mut self, path: S) -> Self { self.allow_module_paths.push(path.into()); self } /// Set multiple allowed module paths. /// /// Same as `with_allowed_module_path`, but accepts list of paths. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_paths(["A", "B"].iter().map(|i| i.to_string())); /// /// assert!(filter.is_module_path_allowed("A")); /// assert!(filter.is_module_path_allowed("B")); /// assert!(!filter.is_module_path_allowed("C")); /// assert!(!filter.is_module_path_allowed("A::B")); /// ``` pub fn with_allowed_module_paths<I: IntoIterator<Item = String>>(mut self, paths: I) -> Self { self.allow_module_paths.extend(paths.into_iter()); self } /// Check if module path is allowed by filter rules. pub fn is_module_path_allowed(&self, path: &str) -> bool { if self.allow_module_paths.is_empty() { return true; } self.allow_module_paths .iter() .any(|allowed_path| allowed_path == path) } } #[cfg(test)] mod tests { use super::Filter; #[test] fn with_allowed_module_path() { assert!(Filter::default().is_module_path_allowed("random")); } } struct PlatformLogWriter<'a> { #[cfg(target_os = "android")] priority: LogPriority, #[cfg(not(target_os = "android"))] priority: Level, len: usize, last_newline_index: usize, tag: &'a CStr, buffer: [u8; LOGGING_MSG_MAX_LEN + 1], } impl<'a> PlatformLogWriter<'a> { #[cfg(target_os = "android")] pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter { PlatformLogWriter { priority: match level { Level::Warn => LogPriority::WARN, Level::Info => LogPriority::INFO, Level::Debug => LogPriority::DEBUG, Level::Error => LogPriority::ERROR, Level::Trace => LogPriority::VERBOSE, }, len: 0, last_newline_index: 0, tag: tag, buffer: unsafe { mem::uninitialized() }, } } #[cfg(not(target_os = "android"))] pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter { PlatformLogWriter { priority: level, len: 0, last_newline_index: 0, tag: tag, buffer: unsafe { mem::uninitialized() }, } } /// Flush some bytes to android logger. /// /// If there is a newline, flush up to it. /// If ther was no newline, flush all. /// /// Not guaranteed to flush everything. fn temporal_flush(&mut self) { let total_len = self.len; if total_len == 0 { return; } if self.last_newline_index > 0 { let copy_from_index = self.last_newline_index; let remaining_chunk_len = total_len - copy_from_index; self.output_specified_len(copy_from_index); self.copy_bytes_to_start(copy_from_index, remaining_chunk_len); self.len = remaining_chunk_len; } else { self.output_specified_len(total_len); self.len = 0; } self.last_newline_index = 0; } /// Flush everything remaining to android logger. fn flush(&mut self) { let total_len = self.len; if total_len == 0 { return; } self.output_specified_len(total_len); self.len = 0; self.last_newline_index = 0; } /// Output buffer up until the \0 which will be placed at `len` position. fn output_specified_len(&mut self, len: usize) { let mut last_byte: u8 = b'\0'; mem::swap(&mut last_byte, unsafe { self.buffer.get_unchecked_mut(len) }); let msg: &CStr = unsafe { CStr::from_ptr(mem::transmute(self.buffer.as_ptr())) }; android_log(self.priority, self.tag, msg); *unsafe { self.buffer.get_unchecked_mut(len) } = last_byte; } /// Copy `len` bytes from `index` position to starting position. fn copy_bytes_to_start(&mut self, index: usize, len: usize) { let src = unsafe { self.buffer.as_ptr().offset(index as isize) }; let dst = self.buffer.as_mut_ptr(); unsafe { ptr::copy(src, dst, len) }; } } impl<'a> fmt::Write for PlatformLogWriter<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { let mut incomming_bytes = s.as_bytes(); while !incomming_bytes.is_empty() { let len = self.len; // write everything possible to buffer and mark last \n let new_len = len + incomming_bytes.len(); let last_newline = self.buffer[len..LOGGING_MSG_MAX_LEN] .iter_mut() .zip(incomming_bytes) .enumerate() .fold(None, |acc, (i, (output, input))| { *output = *input; if *input == b'\n' { Some(i) } else { acc } }); // update last \n index if let Some(newline) = last_newline { self.last_newline_index = len + newline; } // calculate how many bytes were written let written_len = if new_len <= LOGGING_MSG_MAX_LEN { // if the len was not exceeded self.len = new_len; new_len - len // written len } else { // if new length was exceeded self.len = LOGGING_MSG_MAX_LEN; self.temporal_flush(); LOGGING_MSG_MAX_LEN - len // written len }; incomming_bytes = &incomming_bytes[written_len..]; } Ok(()) } } /// Send a log record to Android logging backend. /// /// This action does not require initialization. However, without initialization it /// will use the default filter, which allows all logs. pub fn log(record: &Record) { ANDROID_LOGGER.log(record) } /// Initializes the global logger with an android logger. /// /// This can be called many times, but will only initialize logging once, /// and will not replace any other previously initialized logger. /// /// It is ok to call this at the activity creation, and it will be /// repeatedly called on every lifecycle restart (i.e. screen rotation). pub fn init_once(filter: Filter) { if let Err(err) = log::set_logger(&*ANDROID_LOGGER) { debug!("android_logger: log::set_logger failed: {}", err); } else { if let Some(level) = filter.log_level { log::set_max_level(level.to_level_filter()); } *ANDROID_LOGGER .filter .write() .expect("failed to acquire android_log filter lock for write") = filter; } }
android_log
identifier_name
lib.rs
// Copyright 2016 The android_logger Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! A logger which writes to android output. //! //! ## Example //! //! ``` //! #[macro_use] extern crate log; //! extern crate android_logger; //! //! use log::Level; //! use android_logger::Filter; //! //! /// Android code may not have obvious "main", this is just an example. //! fn main() { //! android_logger::init_once( //! Filter::default() //! .with_min_level(Level::Trace) //! ); //! //! debug!("this is a debug {}", "message"); //! error!("this is printed by default"); //! } //! ``` //! //! ## Example with module path filter //! //! It is possible to limit log messages to output from a specific crate: //! //! ``` //! #[macro_use] extern crate log; //! extern crate android_logger; //! //! use log::Level; //! use android_logger::Filter; //! //! fn main() { //! android_logger::init_once( //! Filter::default() //! .with_min_level(Level::Trace) //! .with_allowed_module_path("hello::crate") //! ); //! //! // .. //! } //! ``` #[cfg(target_os = "android")] extern crate android_log_sys as log_ffi; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::sync::RwLock; #[cfg(target_os = "android")] use log_ffi::LogPriority; use log::{Level, Log, Metadata, Record}; use std::ffi::CStr; use std::mem; use std::fmt; use std::ptr; /// Output log to android system. #[cfg(target_os = "android")] fn android_log(prio: log_ffi::LogPriority, tag: &CStr, msg: &CStr) { unsafe { log_ffi::__android_log_write( prio as log_ffi::c_int, tag.as_ptr() as *const log_ffi::c_char, msg.as_ptr() as *const log_ffi::c_char, ) }; } /// Dummy output placeholder for tests. #[cfg(not(target_os = "android"))] fn android_log(_priority: Level, _tag: &CStr, _msg: &CStr) {} /// Underlying android logger backend pub struct AndroidLogger { filter: RwLock<Filter>, } lazy_static! { static ref ANDROID_LOGGER: AndroidLogger = AndroidLogger::default(); } const LOGGING_TAG_MAX_LEN: usize = 23; const LOGGING_MSG_MAX_LEN: usize = 4000; impl Default for AndroidLogger { /// Create a new logger with default filter fn default() -> AndroidLogger { AndroidLogger { filter: RwLock::new(Filter::default()), } } } impl Log for AndroidLogger { fn enabled(&self, _: &Metadata) -> bool { true } fn log(&self, record: &Record) { if let Some(module_path) = record.module_path() { let filter = self.filter .read() .expect("failed to acquire android_log filter lock for read"); if !filter.is_module_path_allowed(module_path) { return; } } // tag must not exceed LOGGING_TAG_MAX_LEN let mut tag_bytes: [u8; LOGGING_TAG_MAX_LEN + 1] = unsafe { mem::uninitialized() }; // truncate the tag here to fit into LOGGING_TAG_MAX_LEN self.fill_tag_bytes(&mut tag_bytes, record); // use stack array as C string let tag: &CStr = unsafe { CStr::from_ptr(mem::transmute(tag_bytes.as_ptr())) }; // message must not exceed LOGGING_MSG_MAX_LEN // therefore split log message into multiple log calls let mut writer = PlatformLogWriter::new(record.level(), tag); // use PlatformLogWriter to output chunks if they exceed max size let _ = fmt::write(&mut writer, *record.args()); // output the remaining message (this would usually be the most common case) writer.flush(); } fn flush(&self) {} } impl AndroidLogger { fn fill_tag_bytes(&self, array: &mut [u8], record: &Record) { let tag_bytes_iter = record.module_path().unwrap_or_default().bytes(); if tag_bytes_iter.len() > LOGGING_TAG_MAX_LEN { for (input, output) in tag_bytes_iter .take(LOGGING_TAG_MAX_LEN - 2) .chain(b"..\0".iter().cloned()) .zip(array.iter_mut()) { *output = input; } } else { for (input, output) in tag_bytes_iter .chain(b"\0".iter().cloned()) .zip(array.iter_mut()) { *output = input; } } } } /// Filter for android logger. pub struct Filter { log_level: Option<Level>, allow_module_paths: Vec<String>, } impl Default for Filter { fn default() -> Self { Filter { log_level: None, allow_module_paths: Vec::new(), } } } impl Filter { /// Change the minimum log level. /// /// All values above the set level are logged. For example, if /// `Warn` is set, the `Error` is logged too, but `Info` isn't. pub fn with_min_level(mut self, level: Level) -> Self { self.log_level = Some(level); self } /// Set allowed module path. /// /// Allow log entry only if module path matches specified path exactly. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default().with_allowed_module_path("crate"); /// /// assert!(filter.is_module_path_allowed("crate")); /// assert!(!filter.is_module_path_allowed("other_crate")); /// assert!(!filter.is_module_path_allowed("crate::subcrate")); /// ``` /// /// ## Multiple rules example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_path("A") /// .with_allowed_module_path("B"); /// /// assert!(filter.is_module_path_allowed("A")); /// assert!(filter.is_module_path_allowed("B")); /// assert!(!filter.is_module_path_allowed("C")); /// assert!(!filter.is_module_path_allowed("A::B")); /// ``` pub fn with_allowed_module_path<S: Into<String>>(mut self, path: S) -> Self { self.allow_module_paths.push(path.into()); self } /// Set multiple allowed module paths. /// /// Same as `with_allowed_module_path`, but accepts list of paths. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_paths(["A", "B"].iter().map(|i| i.to_string())); /// /// assert!(filter.is_module_path_allowed("A")); /// assert!(filter.is_module_path_allowed("B")); /// assert!(!filter.is_module_path_allowed("C")); /// assert!(!filter.is_module_path_allowed("A::B")); /// ``` pub fn with_allowed_module_paths<I: IntoIterator<Item = String>>(mut self, paths: I) -> Self { self.allow_module_paths.extend(paths.into_iter()); self } /// Check if module path is allowed by filter rules. pub fn is_module_path_allowed(&self, path: &str) -> bool { if self.allow_module_paths.is_empty() { return true; } self.allow_module_paths .iter() .any(|allowed_path| allowed_path == path) } } #[cfg(test)] mod tests { use super::Filter; #[test] fn with_allowed_module_path() { assert!(Filter::default().is_module_path_allowed("random")); } } struct PlatformLogWriter<'a> { #[cfg(target_os = "android")] priority: LogPriority, #[cfg(not(target_os = "android"))] priority: Level, len: usize, last_newline_index: usize, tag: &'a CStr, buffer: [u8; LOGGING_MSG_MAX_LEN + 1], } impl<'a> PlatformLogWriter<'a> { #[cfg(target_os = "android")] pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter { PlatformLogWriter { priority: match level { Level::Warn => LogPriority::WARN, Level::Info => LogPriority::INFO, Level::Debug => LogPriority::DEBUG, Level::Error => LogPriority::ERROR, Level::Trace => LogPriority::VERBOSE, }, len: 0, last_newline_index: 0, tag: tag, buffer: unsafe { mem::uninitialized() }, } } #[cfg(not(target_os = "android"))] pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter { PlatformLogWriter { priority: level, len: 0, last_newline_index: 0, tag: tag, buffer: unsafe { mem::uninitialized() }, } } /// Flush some bytes to android logger. /// /// If there is a newline, flush up to it. /// If ther was no newline, flush all. /// /// Not guaranteed to flush everything. fn temporal_flush(&mut self) { let total_len = self.len; if total_len == 0 { return; } if self.last_newline_index > 0 { let copy_from_index = self.last_newline_index; let remaining_chunk_len = total_len - copy_from_index; self.output_specified_len(copy_from_index); self.copy_bytes_to_start(copy_from_index, remaining_chunk_len); self.len = remaining_chunk_len; } else { self.output_specified_len(total_len); self.len = 0; } self.last_newline_index = 0; } /// Flush everything remaining to android logger. fn flush(&mut self) { let total_len = self.len; if total_len == 0 { return; } self.output_specified_len(total_len); self.len = 0; self.last_newline_index = 0; } /// Output buffer up until the \0 which will be placed at `len` position. fn output_specified_len(&mut self, len: usize) { let mut last_byte: u8 = b'\0'; mem::swap(&mut last_byte, unsafe { self.buffer.get_unchecked_mut(len) }); let msg: &CStr = unsafe { CStr::from_ptr(mem::transmute(self.buffer.as_ptr())) }; android_log(self.priority, self.tag, msg);
} /// Copy `len` bytes from `index` position to starting position. fn copy_bytes_to_start(&mut self, index: usize, len: usize) { let src = unsafe { self.buffer.as_ptr().offset(index as isize) }; let dst = self.buffer.as_mut_ptr(); unsafe { ptr::copy(src, dst, len) }; } } impl<'a> fmt::Write for PlatformLogWriter<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { let mut incomming_bytes = s.as_bytes(); while !incomming_bytes.is_empty() { let len = self.len; // write everything possible to buffer and mark last \n let new_len = len + incomming_bytes.len(); let last_newline = self.buffer[len..LOGGING_MSG_MAX_LEN] .iter_mut() .zip(incomming_bytes) .enumerate() .fold(None, |acc, (i, (output, input))| { *output = *input; if *input == b'\n' { Some(i) } else { acc } }); // update last \n index if let Some(newline) = last_newline { self.last_newline_index = len + newline; } // calculate how many bytes were written let written_len = if new_len <= LOGGING_MSG_MAX_LEN { // if the len was not exceeded self.len = new_len; new_len - len // written len } else { // if new length was exceeded self.len = LOGGING_MSG_MAX_LEN; self.temporal_flush(); LOGGING_MSG_MAX_LEN - len // written len }; incomming_bytes = &incomming_bytes[written_len..]; } Ok(()) } } /// Send a log record to Android logging backend. /// /// This action does not require initialization. However, without initialization it /// will use the default filter, which allows all logs. pub fn log(record: &Record) { ANDROID_LOGGER.log(record) } /// Initializes the global logger with an android logger. /// /// This can be called many times, but will only initialize logging once, /// and will not replace any other previously initialized logger. /// /// It is ok to call this at the activity creation, and it will be /// repeatedly called on every lifecycle restart (i.e. screen rotation). pub fn init_once(filter: Filter) { if let Err(err) = log::set_logger(&*ANDROID_LOGGER) { debug!("android_logger: log::set_logger failed: {}", err); } else { if let Some(level) = filter.log_level { log::set_max_level(level.to_level_filter()); } *ANDROID_LOGGER .filter .write() .expect("failed to acquire android_log filter lock for write") = filter; } }
*unsafe { self.buffer.get_unchecked_mut(len) } = last_byte;
random_line_split
lib.rs
// Copyright 2016 The android_logger Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! A logger which writes to android output. //! //! ## Example //! //! ``` //! #[macro_use] extern crate log; //! extern crate android_logger; //! //! use log::Level; //! use android_logger::Filter; //! //! /// Android code may not have obvious "main", this is just an example. //! fn main() { //! android_logger::init_once( //! Filter::default() //! .with_min_level(Level::Trace) //! ); //! //! debug!("this is a debug {}", "message"); //! error!("this is printed by default"); //! } //! ``` //! //! ## Example with module path filter //! //! It is possible to limit log messages to output from a specific crate: //! //! ``` //! #[macro_use] extern crate log; //! extern crate android_logger; //! //! use log::Level; //! use android_logger::Filter; //! //! fn main() { //! android_logger::init_once( //! Filter::default() //! .with_min_level(Level::Trace) //! .with_allowed_module_path("hello::crate") //! ); //! //! // .. //! } //! ``` #[cfg(target_os = "android")] extern crate android_log_sys as log_ffi; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::sync::RwLock; #[cfg(target_os = "android")] use log_ffi::LogPriority; use log::{Level, Log, Metadata, Record}; use std::ffi::CStr; use std::mem; use std::fmt; use std::ptr; /// Output log to android system. #[cfg(target_os = "android")] fn android_log(prio: log_ffi::LogPriority, tag: &CStr, msg: &CStr) { unsafe { log_ffi::__android_log_write( prio as log_ffi::c_int, tag.as_ptr() as *const log_ffi::c_char, msg.as_ptr() as *const log_ffi::c_char, ) }; } /// Dummy output placeholder for tests. #[cfg(not(target_os = "android"))] fn android_log(_priority: Level, _tag: &CStr, _msg: &CStr) {} /// Underlying android logger backend pub struct AndroidLogger { filter: RwLock<Filter>, } lazy_static! { static ref ANDROID_LOGGER: AndroidLogger = AndroidLogger::default(); } const LOGGING_TAG_MAX_LEN: usize = 23; const LOGGING_MSG_MAX_LEN: usize = 4000; impl Default for AndroidLogger { /// Create a new logger with default filter fn default() -> AndroidLogger { AndroidLogger { filter: RwLock::new(Filter::default()), } } } impl Log for AndroidLogger { fn enabled(&self, _: &Metadata) -> bool { true } fn log(&self, record: &Record) { if let Some(module_path) = record.module_path() { let filter = self.filter .read() .expect("failed to acquire android_log filter lock for read"); if !filter.is_module_path_allowed(module_path) { return; } } // tag must not exceed LOGGING_TAG_MAX_LEN let mut tag_bytes: [u8; LOGGING_TAG_MAX_LEN + 1] = unsafe { mem::uninitialized() }; // truncate the tag here to fit into LOGGING_TAG_MAX_LEN self.fill_tag_bytes(&mut tag_bytes, record); // use stack array as C string let tag: &CStr = unsafe { CStr::from_ptr(mem::transmute(tag_bytes.as_ptr())) }; // message must not exceed LOGGING_MSG_MAX_LEN // therefore split log message into multiple log calls let mut writer = PlatformLogWriter::new(record.level(), tag); // use PlatformLogWriter to output chunks if they exceed max size let _ = fmt::write(&mut writer, *record.args()); // output the remaining message (this would usually be the most common case) writer.flush(); } fn flush(&self) {} } impl AndroidLogger { fn fill_tag_bytes(&self, array: &mut [u8], record: &Record) { let tag_bytes_iter = record.module_path().unwrap_or_default().bytes(); if tag_bytes_iter.len() > LOGGING_TAG_MAX_LEN { for (input, output) in tag_bytes_iter .take(LOGGING_TAG_MAX_LEN - 2) .chain(b"..\0".iter().cloned()) .zip(array.iter_mut()) { *output = input; } } else { for (input, output) in tag_bytes_iter .chain(b"\0".iter().cloned()) .zip(array.iter_mut()) { *output = input; } } } } /// Filter for android logger. pub struct Filter { log_level: Option<Level>, allow_module_paths: Vec<String>, } impl Default for Filter { fn default() -> Self { Filter { log_level: None, allow_module_paths: Vec::new(), } } } impl Filter { /// Change the minimum log level. /// /// All values above the set level are logged. For example, if /// `Warn` is set, the `Error` is logged too, but `Info` isn't. pub fn with_min_level(mut self, level: Level) -> Self { self.log_level = Some(level); self } /// Set allowed module path. /// /// Allow log entry only if module path matches specified path exactly. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default().with_allowed_module_path("crate"); /// /// assert!(filter.is_module_path_allowed("crate")); /// assert!(!filter.is_module_path_allowed("other_crate")); /// assert!(!filter.is_module_path_allowed("crate::subcrate")); /// ``` /// /// ## Multiple rules example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_path("A") /// .with_allowed_module_path("B"); /// /// assert!(filter.is_module_path_allowed("A")); /// assert!(filter.is_module_path_allowed("B")); /// assert!(!filter.is_module_path_allowed("C")); /// assert!(!filter.is_module_path_allowed("A::B")); /// ``` pub fn with_allowed_module_path<S: Into<String>>(mut self, path: S) -> Self { self.allow_module_paths.push(path.into()); self } /// Set multiple allowed module paths. /// /// Same as `with_allowed_module_path`, but accepts list of paths. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_paths(["A", "B"].iter().map(|i| i.to_string())); /// /// assert!(filter.is_module_path_allowed("A")); /// assert!(filter.is_module_path_allowed("B")); /// assert!(!filter.is_module_path_allowed("C")); /// assert!(!filter.is_module_path_allowed("A::B")); /// ``` pub fn with_allowed_module_paths<I: IntoIterator<Item = String>>(mut self, paths: I) -> Self { self.allow_module_paths.extend(paths.into_iter()); self } /// Check if module path is allowed by filter rules. pub fn is_module_path_allowed(&self, path: &str) -> bool { if self.allow_module_paths.is_empty() { return true; } self.allow_module_paths .iter() .any(|allowed_path| allowed_path == path) } } #[cfg(test)] mod tests { use super::Filter; #[test] fn with_allowed_module_path() { assert!(Filter::default().is_module_path_allowed("random")); } } struct PlatformLogWriter<'a> { #[cfg(target_os = "android")] priority: LogPriority, #[cfg(not(target_os = "android"))] priority: Level, len: usize, last_newline_index: usize, tag: &'a CStr, buffer: [u8; LOGGING_MSG_MAX_LEN + 1], } impl<'a> PlatformLogWriter<'a> { #[cfg(target_os = "android")] pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter { PlatformLogWriter { priority: match level { Level::Warn => LogPriority::WARN, Level::Info => LogPriority::INFO, Level::Debug => LogPriority::DEBUG, Level::Error => LogPriority::ERROR, Level::Trace => LogPriority::VERBOSE, }, len: 0, last_newline_index: 0, tag: tag, buffer: unsafe { mem::uninitialized() }, } } #[cfg(not(target_os = "android"))] pub fn new(level: Level, tag: &CStr) -> PlatformLogWriter { PlatformLogWriter { priority: level, len: 0, last_newline_index: 0, tag: tag, buffer: unsafe { mem::uninitialized() }, } } /// Flush some bytes to android logger. /// /// If there is a newline, flush up to it. /// If ther was no newline, flush all. /// /// Not guaranteed to flush everything. fn temporal_flush(&mut self) { let total_len = self.len; if total_len == 0 { return; } if self.last_newline_index > 0 { let copy_from_index = self.last_newline_index; let remaining_chunk_len = total_len - copy_from_index; self.output_specified_len(copy_from_index); self.copy_bytes_to_start(copy_from_index, remaining_chunk_len); self.len = remaining_chunk_len; } else { self.output_specified_len(total_len); self.len = 0; } self.last_newline_index = 0; } /// Flush everything remaining to android logger. fn flush(&mut self) { let total_len = self.len; if total_len == 0 { return; } self.output_specified_len(total_len); self.len = 0; self.last_newline_index = 0; } /// Output buffer up until the \0 which will be placed at `len` position. fn output_specified_len(&mut self, len: usize) { let mut last_byte: u8 = b'\0'; mem::swap(&mut last_byte, unsafe { self.buffer.get_unchecked_mut(len) }); let msg: &CStr = unsafe { CStr::from_ptr(mem::transmute(self.buffer.as_ptr())) }; android_log(self.priority, self.tag, msg); *unsafe { self.buffer.get_unchecked_mut(len) } = last_byte; } /// Copy `len` bytes from `index` position to starting position. fn copy_bytes_to_start(&mut self, index: usize, len: usize) { let src = unsafe { self.buffer.as_ptr().offset(index as isize) }; let dst = self.buffer.as_mut_ptr(); unsafe { ptr::copy(src, dst, len) }; } } impl<'a> fmt::Write for PlatformLogWriter<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { let mut incomming_bytes = s.as_bytes(); while !incomming_bytes.is_empty() { let len = self.len; // write everything possible to buffer and mark last \n let new_len = len + incomming_bytes.len(); let last_newline = self.buffer[len..LOGGING_MSG_MAX_LEN] .iter_mut() .zip(incomming_bytes) .enumerate() .fold(None, |acc, (i, (output, input))| { *output = *input; if *input == b'\n' { Some(i) } else
}); // update last \n index if let Some(newline) = last_newline { self.last_newline_index = len + newline; } // calculate how many bytes were written let written_len = if new_len <= LOGGING_MSG_MAX_LEN { // if the len was not exceeded self.len = new_len; new_len - len // written len } else { // if new length was exceeded self.len = LOGGING_MSG_MAX_LEN; self.temporal_flush(); LOGGING_MSG_MAX_LEN - len // written len }; incomming_bytes = &incomming_bytes[written_len..]; } Ok(()) } } /// Send a log record to Android logging backend. /// /// This action does not require initialization. However, without initialization it /// will use the default filter, which allows all logs. pub fn log(record: &Record) { ANDROID_LOGGER.log(record) } /// Initializes the global logger with an android logger. /// /// This can be called many times, but will only initialize logging once, /// and will not replace any other previously initialized logger. /// /// It is ok to call this at the activity creation, and it will be /// repeatedly called on every lifecycle restart (i.e. screen rotation). pub fn init_once(filter: Filter) { if let Err(err) = log::set_logger(&*ANDROID_LOGGER) { debug!("android_logger: log::set_logger failed: {}", err); } else { if let Some(level) = filter.log_level { log::set_max_level(level.to_level_filter()); } *ANDROID_LOGGER .filter .write() .expect("failed to acquire android_log filter lock for write") = filter; } }
{ acc }
conditional_block
dss.go
/* Package dss implements variants of a DAG-structured stack (DSS). It is used for GLR-parsing and for substring parsing. A DSS is suitable for parsing with ambiguous grammars, so the parser can execute a breadth-first (quasi-)parallel shift and/or reduce operation in inadequate (ambiguous) parse states. Each parser (logical or real) sees it's own linear stack, but all stacks together form a DAG. Stacks share common fragments, making a DSS more space-efficient than a separeted forest of stacks. All stacks are anchored at the root of the DSS. root := NewRoot("G", -1) // represents the DSS stack1 := NewStack(root) // a linear stack within the DSS stack2 := NewStack(root) Please note that a DSS (this one, at least) is not well suited for general purpose stack operations. The non-deterministic concept of GLR-parsing will always lurk in the detail of this implementation. There are other stack implementations around which are much better suited, especially if performance matters. API The main API of this DSS consists of root = NewRoot("...", impossible) stack = NewStack(root) state, symbol = stack.Peek() // peek at top state and symbol of stack newstack = stack.Fork() // duplicate stack stacks = stack.Reduce(handle) // reduce with RHS of a production stack = stack.Push(state, symbol) // transition to new parse state, i.e. a shift stack.Die() // end of life for this stack Additionally, there are some low-level methods, which may help debugging or implementing your own add-on functionality. nodes = stack.FindHandlePath(handle, 0) // find a string of symbols down the stack DSS2Dot(root, path, writer) // output to Graphviz DOT format WalkDAG(root, worker, arg) // execute a function on each DSS node Other methods of the API are rarely used in parsing and exist more or less to complete a conventional stack API. Note that a method for determining the size of a stack is missing. stacks = stack.Pop() GLR Parsing A GLR parser forks a stack whenever an ambiguous state on top of the parse stack is processed. In a GLR-parser, shift/reduce- and reduce/reduce-conflicts are not uncommon, as potentially ambiguous grammars are used. Assume that a shift/reduce-conflict is signalled by the TOS. Then the parser will duplicate the stack (stack.Fork()) and carry out both operations: for one stack a symbol will be shifted, the other will be used for the reduce-operations. Further Information For further information see for example https://people.eecs.berkeley.edu/~necula/Papers/elkhound_cc04.pdf Status This is experimental software, currently not intended for production use. BSD License Copyright (c) 2017-20, Norbert Pillmayer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of this software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package dss import ( "errors" "fmt" "io" "strconv" ssl "github.com/emirpasic/gods/lists/singlylinkedlist" "github.com/npillmayer/gotype/core/config/gtrace" "github.com/npillmayer/gotype/core/config/tracing" "github.com/npillmayer/gotype/syntax/lr" ) // T traces to the SyntaxTracer. func T() tracing.Trace { return gtrace.SyntaxTracer } // --- Stack Nodes ----------------------------------------------------------- // DSSNode is a type for a node in a DSS stack. type DSSNode struct { State int // identifier of a parse state Sym lr.Symbol // symbol on the stack (between states) preds []*DSSNode // predecessors of this node (inverse join) succs []*DSSNode // successors of this node (inverse fork) pathcnt int // count of paths through this node } // create an empty stack node func newDSSNode(state int, sym lr.Symbol) *DSSNode { n := &DSSNode{} n.State = state n.Sym = sym return n } // Simple Stringer for a stack node. func (n *DSSNode) String() string { return fmt.Sprintf("<-(%v)-[%d]", n.Sym, n.State) } // Make an identical copy of a node func (n *DSSNode) clone() *DSSNode { nn := newDSSNode(n.State, n.Sym) for _, p := range n.preds { nn.prepend(p) } for _, s := range n.succs { nn.append(s) } return nn } // Append a node, i.e., insert it into the list of successors func (n *DSSNode) append(succ *DSSNode) { if n.succs == nil { n.succs = make([]*DSSNode, 0, 3) } n.succs = append(n.succs, succ) } // Prepend a node, i.e., insert it into the list of predecessors func (n *DSSNode) prepend(pred *DSSNode) { if n.preds == nil { n.preds = make([]*DSSNode, 0, 3) } n.preds = append(n.preds, pred) } // Unlink a node func (n *DSSNode) isolate() { T().Debugf("isolating %v", n) for _, p := range n.preds { p.succs, _ = remove(p.succs, n) } for _, s := range n.succs { s.preds, _ = remove(s.preds, n) } } func (n *DSSNode) is(state int, sym lr.Symbol) bool { return n.State == state && n.Sym == sym } func (n *DSSNode) isInverseJoin() bool { return n.preds != nil && len(n.preds) > 1 } func (n *DSSNode) isInverseFork() bool { return n.succs != nil && len(n.succs) > 1 } func (n *DSSNode) successorCount() int { if n.succs != nil { return len(n.succs) } return 0 } func (n *DSSNode) predecessorCount() int { if n.preds != nil { return len(n.preds) } return 0 } func (n *DSSNode) findUplink(sym lr.Symbol) *DSSNode { s := contains(n.succs, sym) return s } func (n *DSSNode) findDownlink(state int) *DSSNode { s := hasState(n.preds, state) return s } // NodePath is a run within a stack. We often will have to deal with fragments of a stack type NodePath []*DSSNode // === DSS Data Structure ==================================================== // DSSRoot is the root of a DSS-stack. All stacks of a DSS stack structure share a common // root. Clients have to create a root before stacks can be created. type DSSRoot struct { Name string // identifier for the DSS bottom *DSSNode // stopper stacks []*Stack // housekeeping reservoir *ssl.List // list of nodes to be re-used } // NewRoot creates a named root for a DSS-stack, given a name. // The second parameter is an implementation detail: clients have to supply // a state the root will use as a stopper. It should be an "impossible" state // for normal execution, to avoid confusion. func NewRoot(name string, invalidState int) *DSSRoot { root := &DSSRoot{Name: name} root.bottom = newDSSNode(invalidState, &pseudo{"bottom"}) root.bottom.pathcnt = 1 root.stacks = make([]*Stack, 0, 10) root.reservoir = ssl.New() return root } // ActiveStacks gets the stack-heads currently active in the DSS. // No order is guaranteed. func (root *DSSRoot) ActiveStacks() []*Stack { dup := make([]*Stack, len(root.stacks)) copy(dup, root.stacks) return dup } // Remove a stack from the list of stacks func (root *DSSRoot) removeStack(stack *Stack) { for i, s := range root.stacks { if s == stack { root.stacks[i] = root.stacks[len(root.stacks)-1] root.stacks[len(root.stacks)-1] = nil root.stacks = root.stacks[:len(root.stacks)-1] } } } // As a slight optimization, we do not throw away popped nodes, but rather // append them to a free-list for re-use. // TODO: create an initial pool of nodes. // TODO: migrate this to stdlib's sync/pool. func (root *DSSRoot) recycleNode(node *DSSNode) { T().Debugf("recycling node %v", node) node.State = 0 node.Sym = nil node.preds = node.preds[0:0] node.succs = node.succs[0:0] root.reservoir.Append(node) // list of nodes free for grab } // Create a new stack node or fetch a recycled one. func (root *DSSRoot) newNode(state int, sym lr.Symbol) *DSSNode { var node *DSSNode n, ok := root.reservoir.Get(0) if ok { root.reservoir.Remove(0) node = n.(*DSSNode) node.State = state node.Sym = sym } else { node = newDSSNode(state, sym) } return node } // Wrap nodes of a stack as heads of new stacks. func (root *DSSRoot) makeStackHeadsFrom(nodes []*DSSNode) (ret []*Stack) { for _, n := range nodes { s := NewStack(root) s.tos = n ret = append(ret, s) } return } // Find a TOS of any stack in the DSS which carries state and sym. // This is needed for suffix merging. Returns nil if no TOS meets the criteria. func (root *DSSRoot) findTOSofAnyStack(state int, sym lr.Symbol) *DSSNode { for _, stack := range root.stacks { if stack.tos.is(state, sym) { return stack.tos } } return nil } // IsAlone checks if a stack may safely delete nodes for a reduce operation. There are // exactly two cases when deletion is not permitted: (1) One or more other stacks // are sitting on the same node as this one (2) There are nodes present further // up the stack (presumably operated on by other stacks). func (root *DSSRoot) IsAlone(stack *Stack) bool { if stack.tos.successorCount() > 0 { return false } for _, other := range root.stacks { if other.tos == stack.tos { return false } } return true } // Stack is a data structure for a linear stack within a DSS (DAG structured stack = DSS). // All stacks together form a DSS, i.e. they // may share portions of stacks. Each client carries its own stack, without // noticing the other stacks. The data structure hides the fact that stack- // fragments may be shared. type Stack struct { root *DSSRoot // common root for a set of sub-stacks tos *DSSNode // top of stack } // NewStack creates a new linear stack within a DSS. func NewStack(root *DSSRoot) *Stack { s := &Stack{root: root, tos: root.bottom} s.root.stacks = append(s.root.stacks, s) return s } func (stack *Stack) String() string { return fmt.Sprintf("stack{tos=%v}", stack.tos) } // Calculate the height of a stack /* func (stack *Stack) calculateHeight() { stack.height = stack.tos.height(stack.root.bottom) // recurse until hits bottom } func (node *DSSNode) height(stopper *DSSNode) int { if node == stopper { return 0 } max := 0 for _, p := range node.preds { h := p.height(stopper) if h > max { max = h } } return max + 1 } */ // IsAlone checks if a stack may safely delete nodes for a reduce operation. There are // exactly two cases when deletion is not permitted: (1) One or more other stacks // are sitting on the same node as this one (2) There are nodes present further // up the stack (presumably operated on by other stacks). func (stack *Stack) IsAlone() bool { return stack.root.IsAlone(stack) } // Fork duplicates the head of a stack, resulting in a new stack. // The new stack is implicitely registered with the (common) root. func (stack *Stack) Fork() *Stack { s := NewStack(stack.root) //s.height = stack.height s.tos = stack.tos s.tos.pathcnt++ return s } // Peek returns TOS.Symbol and TOS.State without popping it. func (stack *Stack) Peek() (int, lr.Symbol) { return stack.tos.State, stack.tos.Sym } /* Push a state and a symbol on the stack. Interpretation is as follows: a transition has been found consuming symbol sym, leading to state state. The method looks for a TOS in the DSS representing the combination of (state, sym) and -- if present -- uses (reverse joins) the TOSs. Otherwise it creates a new DAG node. */ func (stack *Stack) Push(state int, sym lr.Symbol) *Stack { if sym == nil { return stack } // create or find a node // - create: new and let node.prev be tos // - find: return existing one // update references / pathcnt if succ := stack.tos.findUplink(sym); succ != nil { T().Debugf("state already present: %v", succ) stack.tos = succ // pushed state is already there, upchain } else { succ := stack.root.findTOSofAnyStack(state, sym) if succ == nil { // not found in DSS succ = stack.root.newNode(state, sym) T().Debugf("creating state: %v", succ) succ.pathcnt = stack.tos.pathcnt } else { T().Debugf("found state on other stack: %v", succ) succ.pathcnt++ } succ.prepend(stack.tos) stack.tos.append(succ) stack.tos = succ } return stack } // FindHandlePath finds a run within a stack corresponding to a handle, i.e., // a list of parse symbols. // // For reduce operations on a stack it is necessary to identify the // nodes which correspond to the symbols of the RHS of the production // to reduce. The nodes (some or all) may overlap with other stacks of // the DSS. // // For a RHS there may be more than one path downwards the stack marked // with the symbols of RHS. It is not deterministic which one this method // will find and return. // Clients may call this method multiple times. If a clients wants to find // all simultaneously existing paths, it should increment the parameter skip // every time. This determines the number of branches have been found // previously and should be skipped now. // // Will return nil if no (more) path is found. func (stack *Stack) FindHandlePath(handle []lr.Symbol, skip int) NodePath { path, ok := collectHandleBranch(stack.tos, handle, len(handle), &skip) if ok { T().Debugf("found a handle %v", path) } return path } // Recursive function to collect nodes corresponding to a list of symbols. // The bottom-most node, i.e. the one terminating the recursion, will allocate // the result array. This array will then be handed upwards the call stack, // being filled with node links on the way. func collectHandleBranch(n *DSSNode, handleRest []lr.Symbol, handleLen int, skip *int) (NodePath, bool) { l := len(handleRest) if l > 0 { if n.Sym == handleRest[l-1] { T().Debugf("handle symbol match at %d = %v", l-1, n.Sym) for _, pred := range n.preds { branch, found := collectHandleBranch(pred, handleRest[:l-1], handleLen, skip) if found { if *skip == 0 { T().Debugf("partial branch: %v", branch) if branch != nil { // a-ha, deepest node has created collector branch[l-1] = n // collect n in branch } return branch, true // return with partially filled branch } else { *skip = max(0, *skip-1) } } } } } else { branchCreated := make([]*DSSNode, handleLen) // create the handle-path collector return branchCreated, true // search/recursion terminates } return nil, false // abort search, handle-path not found } // This is probably never used for a real parser func (stack *Stack) splitOff(path NodePath) *Stack { l := len(path) // pre-condition: there are at least l nodes on the stack-path var node, mynode, upperNode *DSSNode = nil, nil, nil mystack := NewStack(stack.root) //mystack.height = stack.height for i := l - 1; i >= 0; i-- { // walk path from back to font, i.e. top-down node = path[i] mynode = stack.root.newNode(node.State, node.Sym) //mynode = stack.root.newNode(node.State+100, node.Sym) T().Debugf("split off node %v", mynode) if upperNode != nil { // we are not the top-node of the stack mynode.append(upperNode) upperNode.prepend(mynode) upperNode.pathcnt++ } else { // is the newly created top node mystack.tos = mynode // make it TOS of new stack } upperNode = mynode } if mynode != nil && node.preds != nil { for _, p := range node.preds { mynode.prepend(p) mynode.pathcnt++ } } return mystack } /* Pop nodes corresponding to a handle from a stack. The handle path nodes must exist in the DSS (to be checked beforhand by client). The decision wether to delete the nodes on the way down is not trivial. If the destructive-flag is unset, we do not delete anything. If it is set to true, we take this as a general permission to not have to regard other stacks. But we must be careful not to burn our own bridges. We may need a node for other (amybiguity-)paths we'll reduce within the same operation. The logic is as follows: (1) If we have already deleted the single predecessor of this node and this is a regular node (no join, no fork), then we may delete this one as well. (2) If this is a reverse join, we are decrementing the linkcnt and have permission to delete it, if it is the last run through this node. (3) If this is still a reverse fork (although we possbily have deleted one successor), we do not delete. */ func (stack *Stack) reduce(path NodePath, destructive bool) (ret []*Stack) { maydelete := true haveDeleted := false for i := len(path) - 1; i >= 0; i-- { // iterate over handle symbols back to front node := path[i]
if node.isInverseJoin() { T().Debugf("is join: %v", node) maydelete = true node.pathcnt-- } else if haveDeleted && node.successorCount() > 0 { T().Debugf("is or has been fork: %v", node) maydelete = false } else { maydelete = true node.pathcnt-- } if i == 0 { // when popped every node: every predecessor is a stack head now ret = stack.root.makeStackHeadsFrom(node.preds) } if destructive && maydelete && node.pathcnt == 0 { node.isolate() stack.root.recycleNode(node) haveDeleted = true } else { haveDeleted = false } } return } // Reduce performs a reduce operation, given a handle, i.e. a right hand side of a // grammar rule. Strictly speaking, it performs not a complete reduce operation, // but just the first part: popping the RHS symbols off the stack. // Clients will have to push the LHS symbol separately. // // With a DSS, reduce may result in a multitude of new stack configurations. // Whenever there is a reduce/reduce conflict or a shift/reduce-conflict, a GLR // parser will perform both reduce-operations. To this end each possible operation // (i.e, parser) will (conceptually) use its own stack. // Thus multiple return values of a reduce operation correspond to (temporary // or real) ambiguity of a grammar. // // Example: X ::= A + A (grammar rule) // // Stack 1: ... a A + A // Stack 2: ... A + A + A // // as a DSS: -[a]------ // [A] [+]-[A] // now reduce this: A + A to X // -[A]-[+]-- // // This will result in 2 new stack heads: // // as a DSS: -[a] // return stack #1 of Reduce() // -[A]-[+] // return stack #2 of Reduce() // // After pushing X onto the stack, the 2 stacks may be merged (on 'X'), thus // resulting in a single stack head again. // // as a DSS: -[a]----- // [X] // -[A]-[+]- // // The stack triggering the reduce will be the first stack within the returning // array of stacks, i.e. the Reduce() return the stack itself plus possibly // other stacks created during the reduce operation. // func (stack *Stack) Reduce(handle []lr.Symbol) (ret []*Stack) { if len(handle) == 0 { return } var paths []NodePath // first collect all possible handle paths skip := 0 // how many paths already found? path := stack.FindHandlePath(handle, skip) for path != nil { paths = append(paths, path) skip++ path = stack.FindHandlePath(handle, skip) } destructive := stack.IsAlone() // give general permission to delete reduced nodes? for _, path = range paths { // now reduce along every path stacks := stack.reduce(path, destructive) ret = append(ret, stacks...) // collect returned stack heads } if len(ret) > 0 { // if avail, replace 1st stack with this stack.tos = ret[0].tos // make us a lookalike of the 1st returned one ret[0].Die() // the 1st returned one has to die ret[0] = stack // and we replace it } return } func (stack *Stack) reduceHandle(handle []lr.Symbol, destructive bool) (ret []*Stack) { haveReduced := true skipCnt := 0 for haveReduced { // as long as a reduction has been done haveReduced = false handleNodes := stack.FindHandlePath(handle, skipCnt) if handleNodes != nil { haveReduced = true if !destructive { skipCnt++ } s := stack.reduce(handleNodes, destructive) ret = append(ret, s...) } } return } // Pop the TOS of a stack. This is straigtforward for (non-empty) linear stacks // without shared nodes. For stacks with common suffixes, i.e. with inverse joins, // it is more tricky. The popping may result in multiple new stacks, one for // each predecessor. // // For parsers Pop may not be very useful. It is included here for // conformance with the general contract of a stack. With parsing, popping of // states happens during reductions, and the API offers more convenient // functions for this. func (stack *Stack) Pop() (ret []*Stack) { if stack.tos != stack.root.bottom { // ensure stack not empty // If tos is part of another chain: return node and go down one node // If shared by another stack: return node and go down one node // If not shared: remove node // Increase pathcnt at new TOS var oldTOS = stack.tos //var r []*Stack for i, n := range stack.tos.preds { // at least 1 predecessor if i == 0 { // 1st one: keep this stack stack.tos = n //stack.calculateHeight() } else { // further predecessors: create stack for each one s := NewStack(stack.root) s.tos = n //s.calculateHeight() //T().Debugf("creating new stack for %v (of height=%d)", n, s.height) ret = append(ret, s) } } if oldTOS.succs == nil || len(oldTOS.succs) == 0 { oldTOS.isolate() stack.root.recycleNode(oldTOS) } return ret } return nil } func (stack *Stack) pop(toNode *DSSNode, deleteNode bool, collectStacks bool) ([]*Stack, error) { var r []*Stack // return value var err error // return value if stack.tos != stack.root.bottom { // ensure stack not empty var oldTOS = stack.tos var found bool stack.tos.preds, found = remove(stack.tos.preds, toNode) if !found { err = errors.New("unable to pop TOS: 2OS not appropriate") } else { stack.tos.pathcnt-- toNode.pathcnt++ stack.tos = toNode //stack.calculateHeight() if deleteNode && oldTOS.pathcnt == 0 && (oldTOS.succs == nil || len(oldTOS.succs) == 0) { oldTOS.isolate() stack.root.recycleNode(oldTOS) } } } else { T().Errorf("unable to pop TOS: stack empty") err = errors.New("unable to pop TOS: stack empty") } return r, err } // --- Debugging ------------------------------------------------------------- // DSS2Dot outputs a DSS in Graphviz DOT format (for debugging purposes). // // If parameter path is given, it will be highlighted in the output. func DSS2Dot(root *DSSRoot, path []*DSSNode, w io.Writer) { istos := map[*DSSNode]bool{} for _, stack := range root.stacks { istos[stack.tos] = true } ids := map[*DSSNode]int{} idcounter := 1 io.WriteString(w, "digraph {\n") WalkDAG(root, func(node *DSSNode, arg interface{}) { ids[node] = idcounter idcounter++ styles := nodeDotStyles(node, pathContains(path, node)) if istos[node] { styles += ",shape=box" } io.WriteString(w, fmt.Sprintf("\"%d[%d]\" [label=%d %s];\n", node.State, ids[node], node.State, styles)) }, nil) WalkDAG(root, func(node *DSSNode, arg interface{}) { ww := w.(io.Writer) for _, p := range node.preds { io.WriteString(ww, fmt.Sprintf("\"%d[%d]\" -> \"%d[%d]\" [label=\"%v\"];\n", node.State, ids[node], p.State, ids[p], node.Sym)) } }, w) io.WriteString(w, "}\n") } func nodeDotStyles(node *DSSNode, highlight bool) string { s := ",style=filled" if highlight { s = s + fmt.Sprintf(",fillcolor=\"%s\"", hexhlcolors[node.pathcnt]) } else { s = s + fmt.Sprintf(",fillcolor=\"%s\"", hexcolors[node.pathcnt]) } return s } var hexhlcolors = [...]string{"#FFEEDD", "#FFDDCC", "#FFCCAA", "#FFBB88", "#FFAA66", "#FF9944", "#FF8822", "#FF7700", "#ff6600"} var hexcolors = [...]string{"white", "#CCDDFF", "#AACCFF", "#88BBFF", "#66AAFF", "#4499FF", "#2288FF", "#0077FF", "#0066FF"} // PrintDSS is for debugging. func PrintDSS(root *DSSRoot) { WalkDAG(root, func(node *DSSNode, arg interface{}) { predList := " " for _, p := range node.preds { predList = predList + strconv.Itoa(p.State) + " " } fmt.Printf("edge [%s]%v\n", predList, node) }, nil) } // WalkDAG walks all nodes of a DSS and execute a worker function on each. // parameter arg is presented as a second argument to each worker execution. func WalkDAG(root *DSSRoot, worker func(*DSSNode, interface{}), arg interface{}) { visited := map[*DSSNode]bool{} var walk func(*DSSNode, func(*DSSNode, interface{}), interface{}) walk = func(node *DSSNode, worker func(*DSSNode, interface{}), arg interface{}) { if visited[node] { return } visited[node] = true for _, p := range node.preds { walk(p, worker, arg) } worker(node, arg) } for _, stack := range root.stacks { walk(stack.tos, worker, arg) } } // Die signals end of lfe for this stack. // The stack will be detached from the DSS root and will let go of its TOS. func (stack *Stack) Die() { stack.root.removeStack(stack) stack.tos = nil } // --- Helpers --------------------------------------------------------------- func pathContains(s []*DSSNode, node *DSSNode) bool { if s != nil { for _, n := range s { if n == node { return true } } } return false } func contains(s []*DSSNode, sym lr.Symbol) *DSSNode { if s != nil { for _, n := range s { if n.Sym == sym { return n } } } return nil } // Helper : remove an item from a node slice // without preserving order (i.e, replace by last in slice) func remove(nodes []*DSSNode, node *DSSNode) ([]*DSSNode, bool) { for i, n := range nodes { if n == node { nodes[i] = nodes[len(nodes)-1] nodes[len(nodes)-1] = nil nodes = nodes[:len(nodes)-1] return nodes, true } } return nodes, false } func hasState(s []*DSSNode, state int) *DSSNode { for _, n := range s { if n.State == state { return n } } return nil } type pseudo struct { name string } func pseudosym(name string) lr.Symbol { return &pseudo{name: name} } func (sy *pseudo) String() string { return sy.name } func (sy *pseudo) IsTerminal() bool { return true } func (sy *pseudo) Token() int { return 0 } func (sy *pseudo) GetID() int { return 0 } var _ lr.Symbol = &pseudo{} func max(a, b int) int { if a > b { return a } return b }
T().Debugf("reducing node %v (now cnt=%d)", node, node.pathcnt) T().Debugf(" node %v has %d succs", node, len(node.succs))
random_line_split
dss.go
/* Package dss implements variants of a DAG-structured stack (DSS). It is used for GLR-parsing and for substring parsing. A DSS is suitable for parsing with ambiguous grammars, so the parser can execute a breadth-first (quasi-)parallel shift and/or reduce operation in inadequate (ambiguous) parse states. Each parser (logical or real) sees it's own linear stack, but all stacks together form a DAG. Stacks share common fragments, making a DSS more space-efficient than a separeted forest of stacks. All stacks are anchored at the root of the DSS. root := NewRoot("G", -1) // represents the DSS stack1 := NewStack(root) // a linear stack within the DSS stack2 := NewStack(root) Please note that a DSS (this one, at least) is not well suited for general purpose stack operations. The non-deterministic concept of GLR-parsing will always lurk in the detail of this implementation. There are other stack implementations around which are much better suited, especially if performance matters. API The main API of this DSS consists of root = NewRoot("...", impossible) stack = NewStack(root) state, symbol = stack.Peek() // peek at top state and symbol of stack newstack = stack.Fork() // duplicate stack stacks = stack.Reduce(handle) // reduce with RHS of a production stack = stack.Push(state, symbol) // transition to new parse state, i.e. a shift stack.Die() // end of life for this stack Additionally, there are some low-level methods, which may help debugging or implementing your own add-on functionality. nodes = stack.FindHandlePath(handle, 0) // find a string of symbols down the stack DSS2Dot(root, path, writer) // output to Graphviz DOT format WalkDAG(root, worker, arg) // execute a function on each DSS node Other methods of the API are rarely used in parsing and exist more or less to complete a conventional stack API. Note that a method for determining the size of a stack is missing. stacks = stack.Pop() GLR Parsing A GLR parser forks a stack whenever an ambiguous state on top of the parse stack is processed. In a GLR-parser, shift/reduce- and reduce/reduce-conflicts are not uncommon, as potentially ambiguous grammars are used. Assume that a shift/reduce-conflict is signalled by the TOS. Then the parser will duplicate the stack (stack.Fork()) and carry out both operations: for one stack a symbol will be shifted, the other will be used for the reduce-operations. Further Information For further information see for example https://people.eecs.berkeley.edu/~necula/Papers/elkhound_cc04.pdf Status This is experimental software, currently not intended for production use. BSD License Copyright (c) 2017-20, Norbert Pillmayer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of this software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package dss import ( "errors" "fmt" "io" "strconv" ssl "github.com/emirpasic/gods/lists/singlylinkedlist" "github.com/npillmayer/gotype/core/config/gtrace" "github.com/npillmayer/gotype/core/config/tracing" "github.com/npillmayer/gotype/syntax/lr" ) // T traces to the SyntaxTracer. func T() tracing.Trace { return gtrace.SyntaxTracer } // --- Stack Nodes ----------------------------------------------------------- // DSSNode is a type for a node in a DSS stack. type DSSNode struct { State int // identifier of a parse state Sym lr.Symbol // symbol on the stack (between states) preds []*DSSNode // predecessors of this node (inverse join) succs []*DSSNode // successors of this node (inverse fork) pathcnt int // count of paths through this node } // create an empty stack node func newDSSNode(state int, sym lr.Symbol) *DSSNode { n := &DSSNode{} n.State = state n.Sym = sym return n } // Simple Stringer for a stack node. func (n *DSSNode) String() string { return fmt.Sprintf("<-(%v)-[%d]", n.Sym, n.State) } // Make an identical copy of a node func (n *DSSNode) clone() *DSSNode { nn := newDSSNode(n.State, n.Sym) for _, p := range n.preds { nn.prepend(p) } for _, s := range n.succs { nn.append(s) } return nn } // Append a node, i.e., insert it into the list of successors func (n *DSSNode) append(succ *DSSNode) { if n.succs == nil { n.succs = make([]*DSSNode, 0, 3) } n.succs = append(n.succs, succ) } // Prepend a node, i.e., insert it into the list of predecessors func (n *DSSNode) prepend(pred *DSSNode) { if n.preds == nil { n.preds = make([]*DSSNode, 0, 3) } n.preds = append(n.preds, pred) } // Unlink a node func (n *DSSNode) isolate() { T().Debugf("isolating %v", n) for _, p := range n.preds { p.succs, _ = remove(p.succs, n) } for _, s := range n.succs { s.preds, _ = remove(s.preds, n) } } func (n *DSSNode) is(state int, sym lr.Symbol) bool { return n.State == state && n.Sym == sym } func (n *DSSNode) isInverseJoin() bool { return n.preds != nil && len(n.preds) > 1 } func (n *DSSNode) isInverseFork() bool
func (n *DSSNode) successorCount() int { if n.succs != nil { return len(n.succs) } return 0 } func (n *DSSNode) predecessorCount() int { if n.preds != nil { return len(n.preds) } return 0 } func (n *DSSNode) findUplink(sym lr.Symbol) *DSSNode { s := contains(n.succs, sym) return s } func (n *DSSNode) findDownlink(state int) *DSSNode { s := hasState(n.preds, state) return s } // NodePath is a run within a stack. We often will have to deal with fragments of a stack type NodePath []*DSSNode // === DSS Data Structure ==================================================== // DSSRoot is the root of a DSS-stack. All stacks of a DSS stack structure share a common // root. Clients have to create a root before stacks can be created. type DSSRoot struct { Name string // identifier for the DSS bottom *DSSNode // stopper stacks []*Stack // housekeeping reservoir *ssl.List // list of nodes to be re-used } // NewRoot creates a named root for a DSS-stack, given a name. // The second parameter is an implementation detail: clients have to supply // a state the root will use as a stopper. It should be an "impossible" state // for normal execution, to avoid confusion. func NewRoot(name string, invalidState int) *DSSRoot { root := &DSSRoot{Name: name} root.bottom = newDSSNode(invalidState, &pseudo{"bottom"}) root.bottom.pathcnt = 1 root.stacks = make([]*Stack, 0, 10) root.reservoir = ssl.New() return root } // ActiveStacks gets the stack-heads currently active in the DSS. // No order is guaranteed. func (root *DSSRoot) ActiveStacks() []*Stack { dup := make([]*Stack, len(root.stacks)) copy(dup, root.stacks) return dup } // Remove a stack from the list of stacks func (root *DSSRoot) removeStack(stack *Stack) { for i, s := range root.stacks { if s == stack { root.stacks[i] = root.stacks[len(root.stacks)-1] root.stacks[len(root.stacks)-1] = nil root.stacks = root.stacks[:len(root.stacks)-1] } } } // As a slight optimization, we do not throw away popped nodes, but rather // append them to a free-list for re-use. // TODO: create an initial pool of nodes. // TODO: migrate this to stdlib's sync/pool. func (root *DSSRoot) recycleNode(node *DSSNode) { T().Debugf("recycling node %v", node) node.State = 0 node.Sym = nil node.preds = node.preds[0:0] node.succs = node.succs[0:0] root.reservoir.Append(node) // list of nodes free for grab } // Create a new stack node or fetch a recycled one. func (root *DSSRoot) newNode(state int, sym lr.Symbol) *DSSNode { var node *DSSNode n, ok := root.reservoir.Get(0) if ok { root.reservoir.Remove(0) node = n.(*DSSNode) node.State = state node.Sym = sym } else { node = newDSSNode(state, sym) } return node } // Wrap nodes of a stack as heads of new stacks. func (root *DSSRoot) makeStackHeadsFrom(nodes []*DSSNode) (ret []*Stack) { for _, n := range nodes { s := NewStack(root) s.tos = n ret = append(ret, s) } return } // Find a TOS of any stack in the DSS which carries state and sym. // This is needed for suffix merging. Returns nil if no TOS meets the criteria. func (root *DSSRoot) findTOSofAnyStack(state int, sym lr.Symbol) *DSSNode { for _, stack := range root.stacks { if stack.tos.is(state, sym) { return stack.tos } } return nil } // IsAlone checks if a stack may safely delete nodes for a reduce operation. There are // exactly two cases when deletion is not permitted: (1) One or more other stacks // are sitting on the same node as this one (2) There are nodes present further // up the stack (presumably operated on by other stacks). func (root *DSSRoot) IsAlone(stack *Stack) bool { if stack.tos.successorCount() > 0 { return false } for _, other := range root.stacks { if other.tos == stack.tos { return false } } return true } // Stack is a data structure for a linear stack within a DSS (DAG structured stack = DSS). // All stacks together form a DSS, i.e. they // may share portions of stacks. Each client carries its own stack, without // noticing the other stacks. The data structure hides the fact that stack- // fragments may be shared. type Stack struct { root *DSSRoot // common root for a set of sub-stacks tos *DSSNode // top of stack } // NewStack creates a new linear stack within a DSS. func NewStack(root *DSSRoot) *Stack { s := &Stack{root: root, tos: root.bottom} s.root.stacks = append(s.root.stacks, s) return s } func (stack *Stack) String() string { return fmt.Sprintf("stack{tos=%v}", stack.tos) } // Calculate the height of a stack /* func (stack *Stack) calculateHeight() { stack.height = stack.tos.height(stack.root.bottom) // recurse until hits bottom } func (node *DSSNode) height(stopper *DSSNode) int { if node == stopper { return 0 } max := 0 for _, p := range node.preds { h := p.height(stopper) if h > max { max = h } } return max + 1 } */ // IsAlone checks if a stack may safely delete nodes for a reduce operation. There are // exactly two cases when deletion is not permitted: (1) One or more other stacks // are sitting on the same node as this one (2) There are nodes present further // up the stack (presumably operated on by other stacks). func (stack *Stack) IsAlone() bool { return stack.root.IsAlone(stack) } // Fork duplicates the head of a stack, resulting in a new stack. // The new stack is implicitely registered with the (common) root. func (stack *Stack) Fork() *Stack { s := NewStack(stack.root) //s.height = stack.height s.tos = stack.tos s.tos.pathcnt++ return s } // Peek returns TOS.Symbol and TOS.State without popping it. func (stack *Stack) Peek() (int, lr.Symbol) { return stack.tos.State, stack.tos.Sym } /* Push a state and a symbol on the stack. Interpretation is as follows: a transition has been found consuming symbol sym, leading to state state. The method looks for a TOS in the DSS representing the combination of (state, sym) and -- if present -- uses (reverse joins) the TOSs. Otherwise it creates a new DAG node. */ func (stack *Stack) Push(state int, sym lr.Symbol) *Stack { if sym == nil { return stack } // create or find a node // - create: new and let node.prev be tos // - find: return existing one // update references / pathcnt if succ := stack.tos.findUplink(sym); succ != nil { T().Debugf("state already present: %v", succ) stack.tos = succ // pushed state is already there, upchain } else { succ := stack.root.findTOSofAnyStack(state, sym) if succ == nil { // not found in DSS succ = stack.root.newNode(state, sym) T().Debugf("creating state: %v", succ) succ.pathcnt = stack.tos.pathcnt } else { T().Debugf("found state on other stack: %v", succ) succ.pathcnt++ } succ.prepend(stack.tos) stack.tos.append(succ) stack.tos = succ } return stack } // FindHandlePath finds a run within a stack corresponding to a handle, i.e., // a list of parse symbols. // // For reduce operations on a stack it is necessary to identify the // nodes which correspond to the symbols of the RHS of the production // to reduce. The nodes (some or all) may overlap with other stacks of // the DSS. // // For a RHS there may be more than one path downwards the stack marked // with the symbols of RHS. It is not deterministic which one this method // will find and return. // Clients may call this method multiple times. If a clients wants to find // all simultaneously existing paths, it should increment the parameter skip // every time. This determines the number of branches have been found // previously and should be skipped now. // // Will return nil if no (more) path is found. func (stack *Stack) FindHandlePath(handle []lr.Symbol, skip int) NodePath { path, ok := collectHandleBranch(stack.tos, handle, len(handle), &skip) if ok { T().Debugf("found a handle %v", path) } return path } // Recursive function to collect nodes corresponding to a list of symbols. // The bottom-most node, i.e. the one terminating the recursion, will allocate // the result array. This array will then be handed upwards the call stack, // being filled with node links on the way. func collectHandleBranch(n *DSSNode, handleRest []lr.Symbol, handleLen int, skip *int) (NodePath, bool) { l := len(handleRest) if l > 0 { if n.Sym == handleRest[l-1] { T().Debugf("handle symbol match at %d = %v", l-1, n.Sym) for _, pred := range n.preds { branch, found := collectHandleBranch(pred, handleRest[:l-1], handleLen, skip) if found { if *skip == 0 { T().Debugf("partial branch: %v", branch) if branch != nil { // a-ha, deepest node has created collector branch[l-1] = n // collect n in branch } return branch, true // return with partially filled branch } else { *skip = max(0, *skip-1) } } } } } else { branchCreated := make([]*DSSNode, handleLen) // create the handle-path collector return branchCreated, true // search/recursion terminates } return nil, false // abort search, handle-path not found } // This is probably never used for a real parser func (stack *Stack) splitOff(path NodePath) *Stack { l := len(path) // pre-condition: there are at least l nodes on the stack-path var node, mynode, upperNode *DSSNode = nil, nil, nil mystack := NewStack(stack.root) //mystack.height = stack.height for i := l - 1; i >= 0; i-- { // walk path from back to font, i.e. top-down node = path[i] mynode = stack.root.newNode(node.State, node.Sym) //mynode = stack.root.newNode(node.State+100, node.Sym) T().Debugf("split off node %v", mynode) if upperNode != nil { // we are not the top-node of the stack mynode.append(upperNode) upperNode.prepend(mynode) upperNode.pathcnt++ } else { // is the newly created top node mystack.tos = mynode // make it TOS of new stack } upperNode = mynode } if mynode != nil && node.preds != nil { for _, p := range node.preds { mynode.prepend(p) mynode.pathcnt++ } } return mystack } /* Pop nodes corresponding to a handle from a stack. The handle path nodes must exist in the DSS (to be checked beforhand by client). The decision wether to delete the nodes on the way down is not trivial. If the destructive-flag is unset, we do not delete anything. If it is set to true, we take this as a general permission to not have to regard other stacks. But we must be careful not to burn our own bridges. We may need a node for other (amybiguity-)paths we'll reduce within the same operation. The logic is as follows: (1) If we have already deleted the single predecessor of this node and this is a regular node (no join, no fork), then we may delete this one as well. (2) If this is a reverse join, we are decrementing the linkcnt and have permission to delete it, if it is the last run through this node. (3) If this is still a reverse fork (although we possbily have deleted one successor), we do not delete. */ func (stack *Stack) reduce(path NodePath, destructive bool) (ret []*Stack) { maydelete := true haveDeleted := false for i := len(path) - 1; i >= 0; i-- { // iterate over handle symbols back to front node := path[i] T().Debugf("reducing node %v (now cnt=%d)", node, node.pathcnt) T().Debugf(" node %v has %d succs", node, len(node.succs)) if node.isInverseJoin() { T().Debugf("is join: %v", node) maydelete = true node.pathcnt-- } else if haveDeleted && node.successorCount() > 0 { T().Debugf("is or has been fork: %v", node) maydelete = false } else { maydelete = true node.pathcnt-- } if i == 0 { // when popped every node: every predecessor is a stack head now ret = stack.root.makeStackHeadsFrom(node.preds) } if destructive && maydelete && node.pathcnt == 0 { node.isolate() stack.root.recycleNode(node) haveDeleted = true } else { haveDeleted = false } } return } // Reduce performs a reduce operation, given a handle, i.e. a right hand side of a // grammar rule. Strictly speaking, it performs not a complete reduce operation, // but just the first part: popping the RHS symbols off the stack. // Clients will have to push the LHS symbol separately. // // With a DSS, reduce may result in a multitude of new stack configurations. // Whenever there is a reduce/reduce conflict or a shift/reduce-conflict, a GLR // parser will perform both reduce-operations. To this end each possible operation // (i.e, parser) will (conceptually) use its own stack. // Thus multiple return values of a reduce operation correspond to (temporary // or real) ambiguity of a grammar. // // Example: X ::= A + A (grammar rule) // // Stack 1: ... a A + A // Stack 2: ... A + A + A // // as a DSS: -[a]------ // [A] [+]-[A] // now reduce this: A + A to X // -[A]-[+]-- // // This will result in 2 new stack heads: // // as a DSS: -[a] // return stack #1 of Reduce() // -[A]-[+] // return stack #2 of Reduce() // // After pushing X onto the stack, the 2 stacks may be merged (on 'X'), thus // resulting in a single stack head again. // // as a DSS: -[a]----- // [X] // -[A]-[+]- // // The stack triggering the reduce will be the first stack within the returning // array of stacks, i.e. the Reduce() return the stack itself plus possibly // other stacks created during the reduce operation. // func (stack *Stack) Reduce(handle []lr.Symbol) (ret []*Stack) { if len(handle) == 0 { return } var paths []NodePath // first collect all possible handle paths skip := 0 // how many paths already found? path := stack.FindHandlePath(handle, skip) for path != nil { paths = append(paths, path) skip++ path = stack.FindHandlePath(handle, skip) } destructive := stack.IsAlone() // give general permission to delete reduced nodes? for _, path = range paths { // now reduce along every path stacks := stack.reduce(path, destructive) ret = append(ret, stacks...) // collect returned stack heads } if len(ret) > 0 { // if avail, replace 1st stack with this stack.tos = ret[0].tos // make us a lookalike of the 1st returned one ret[0].Die() // the 1st returned one has to die ret[0] = stack // and we replace it } return } func (stack *Stack) reduceHandle(handle []lr.Symbol, destructive bool) (ret []*Stack) { haveReduced := true skipCnt := 0 for haveReduced { // as long as a reduction has been done haveReduced = false handleNodes := stack.FindHandlePath(handle, skipCnt) if handleNodes != nil { haveReduced = true if !destructive { skipCnt++ } s := stack.reduce(handleNodes, destructive) ret = append(ret, s...) } } return } // Pop the TOS of a stack. This is straigtforward for (non-empty) linear stacks // without shared nodes. For stacks with common suffixes, i.e. with inverse joins, // it is more tricky. The popping may result in multiple new stacks, one for // each predecessor. // // For parsers Pop may not be very useful. It is included here for // conformance with the general contract of a stack. With parsing, popping of // states happens during reductions, and the API offers more convenient // functions for this. func (stack *Stack) Pop() (ret []*Stack) { if stack.tos != stack.root.bottom { // ensure stack not empty // If tos is part of another chain: return node and go down one node // If shared by another stack: return node and go down one node // If not shared: remove node // Increase pathcnt at new TOS var oldTOS = stack.tos //var r []*Stack for i, n := range stack.tos.preds { // at least 1 predecessor if i == 0 { // 1st one: keep this stack stack.tos = n //stack.calculateHeight() } else { // further predecessors: create stack for each one s := NewStack(stack.root) s.tos = n //s.calculateHeight() //T().Debugf("creating new stack for %v (of height=%d)", n, s.height) ret = append(ret, s) } } if oldTOS.succs == nil || len(oldTOS.succs) == 0 { oldTOS.isolate() stack.root.recycleNode(oldTOS) } return ret } return nil } func (stack *Stack) pop(toNode *DSSNode, deleteNode bool, collectStacks bool) ([]*Stack, error) { var r []*Stack // return value var err error // return value if stack.tos != stack.root.bottom { // ensure stack not empty var oldTOS = stack.tos var found bool stack.tos.preds, found = remove(stack.tos.preds, toNode) if !found { err = errors.New("unable to pop TOS: 2OS not appropriate") } else { stack.tos.pathcnt-- toNode.pathcnt++ stack.tos = toNode //stack.calculateHeight() if deleteNode && oldTOS.pathcnt == 0 && (oldTOS.succs == nil || len(oldTOS.succs) == 0) { oldTOS.isolate() stack.root.recycleNode(oldTOS) } } } else { T().Errorf("unable to pop TOS: stack empty") err = errors.New("unable to pop TOS: stack empty") } return r, err } // --- Debugging ------------------------------------------------------------- // DSS2Dot outputs a DSS in Graphviz DOT format (for debugging purposes). // // If parameter path is given, it will be highlighted in the output. func DSS2Dot(root *DSSRoot, path []*DSSNode, w io.Writer) { istos := map[*DSSNode]bool{} for _, stack := range root.stacks { istos[stack.tos] = true } ids := map[*DSSNode]int{} idcounter := 1 io.WriteString(w, "digraph {\n") WalkDAG(root, func(node *DSSNode, arg interface{}) { ids[node] = idcounter idcounter++ styles := nodeDotStyles(node, pathContains(path, node)) if istos[node] { styles += ",shape=box" } io.WriteString(w, fmt.Sprintf("\"%d[%d]\" [label=%d %s];\n", node.State, ids[node], node.State, styles)) }, nil) WalkDAG(root, func(node *DSSNode, arg interface{}) { ww := w.(io.Writer) for _, p := range node.preds { io.WriteString(ww, fmt.Sprintf("\"%d[%d]\" -> \"%d[%d]\" [label=\"%v\"];\n", node.State, ids[node], p.State, ids[p], node.Sym)) } }, w) io.WriteString(w, "}\n") } func nodeDotStyles(node *DSSNode, highlight bool) string { s := ",style=filled" if highlight { s = s + fmt.Sprintf(",fillcolor=\"%s\"", hexhlcolors[node.pathcnt]) } else { s = s + fmt.Sprintf(",fillcolor=\"%s\"", hexcolors[node.pathcnt]) } return s } var hexhlcolors = [...]string{"#FFEEDD", "#FFDDCC", "#FFCCAA", "#FFBB88", "#FFAA66", "#FF9944", "#FF8822", "#FF7700", "#ff6600"} var hexcolors = [...]string{"white", "#CCDDFF", "#AACCFF", "#88BBFF", "#66AAFF", "#4499FF", "#2288FF", "#0077FF", "#0066FF"} // PrintDSS is for debugging. func PrintDSS(root *DSSRoot) { WalkDAG(root, func(node *DSSNode, arg interface{}) { predList := " " for _, p := range node.preds { predList = predList + strconv.Itoa(p.State) + " " } fmt.Printf("edge [%s]%v\n", predList, node) }, nil) } // WalkDAG walks all nodes of a DSS and execute a worker function on each. // parameter arg is presented as a second argument to each worker execution. func WalkDAG(root *DSSRoot, worker func(*DSSNode, interface{}), arg interface{}) { visited := map[*DSSNode]bool{} var walk func(*DSSNode, func(*DSSNode, interface{}), interface{}) walk = func(node *DSSNode, worker func(*DSSNode, interface{}), arg interface{}) { if visited[node] { return } visited[node] = true for _, p := range node.preds { walk(p, worker, arg) } worker(node, arg) } for _, stack := range root.stacks { walk(stack.tos, worker, arg) } } // Die signals end of lfe for this stack. // The stack will be detached from the DSS root and will let go of its TOS. func (stack *Stack) Die() { stack.root.removeStack(stack) stack.tos = nil } // --- Helpers --------------------------------------------------------------- func pathContains(s []*DSSNode, node *DSSNode) bool { if s != nil { for _, n := range s { if n == node { return true } } } return false } func contains(s []*DSSNode, sym lr.Symbol) *DSSNode { if s != nil { for _, n := range s { if n.Sym == sym { return n } } } return nil } // Helper : remove an item from a node slice // without preserving order (i.e, replace by last in slice) func remove(nodes []*DSSNode, node *DSSNode) ([]*DSSNode, bool) { for i, n := range nodes { if n == node { nodes[i] = nodes[len(nodes)-1] nodes[len(nodes)-1] = nil nodes = nodes[:len(nodes)-1] return nodes, true } } return nodes, false } func hasState(s []*DSSNode, state int) *DSSNode { for _, n := range s { if n.State == state { return n } } return nil } type pseudo struct { name string } func pseudosym(name string) lr.Symbol { return &pseudo{name: name} } func (sy *pseudo) String() string { return sy.name } func (sy *pseudo) IsTerminal() bool { return true } func (sy *pseudo) Token() int { return 0 } func (sy *pseudo) GetID() int { return 0 } var _ lr.Symbol = &pseudo{} func max(a, b int) int { if a > b { return a } return b }
{ return n.succs != nil && len(n.succs) > 1 }
identifier_body
dss.go
/* Package dss implements variants of a DAG-structured stack (DSS). It is used for GLR-parsing and for substring parsing. A DSS is suitable for parsing with ambiguous grammars, so the parser can execute a breadth-first (quasi-)parallel shift and/or reduce operation in inadequate (ambiguous) parse states. Each parser (logical or real) sees it's own linear stack, but all stacks together form a DAG. Stacks share common fragments, making a DSS more space-efficient than a separeted forest of stacks. All stacks are anchored at the root of the DSS. root := NewRoot("G", -1) // represents the DSS stack1 := NewStack(root) // a linear stack within the DSS stack2 := NewStack(root) Please note that a DSS (this one, at least) is not well suited for general purpose stack operations. The non-deterministic concept of GLR-parsing will always lurk in the detail of this implementation. There are other stack implementations around which are much better suited, especially if performance matters. API The main API of this DSS consists of root = NewRoot("...", impossible) stack = NewStack(root) state, symbol = stack.Peek() // peek at top state and symbol of stack newstack = stack.Fork() // duplicate stack stacks = stack.Reduce(handle) // reduce with RHS of a production stack = stack.Push(state, symbol) // transition to new parse state, i.e. a shift stack.Die() // end of life for this stack Additionally, there are some low-level methods, which may help debugging or implementing your own add-on functionality. nodes = stack.FindHandlePath(handle, 0) // find a string of symbols down the stack DSS2Dot(root, path, writer) // output to Graphviz DOT format WalkDAG(root, worker, arg) // execute a function on each DSS node Other methods of the API are rarely used in parsing and exist more or less to complete a conventional stack API. Note that a method for determining the size of a stack is missing. stacks = stack.Pop() GLR Parsing A GLR parser forks a stack whenever an ambiguous state on top of the parse stack is processed. In a GLR-parser, shift/reduce- and reduce/reduce-conflicts are not uncommon, as potentially ambiguous grammars are used. Assume that a shift/reduce-conflict is signalled by the TOS. Then the parser will duplicate the stack (stack.Fork()) and carry out both operations: for one stack a symbol will be shifted, the other will be used for the reduce-operations. Further Information For further information see for example https://people.eecs.berkeley.edu/~necula/Papers/elkhound_cc04.pdf Status This is experimental software, currently not intended for production use. BSD License Copyright (c) 2017-20, Norbert Pillmayer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of this software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package dss import ( "errors" "fmt" "io" "strconv" ssl "github.com/emirpasic/gods/lists/singlylinkedlist" "github.com/npillmayer/gotype/core/config/gtrace" "github.com/npillmayer/gotype/core/config/tracing" "github.com/npillmayer/gotype/syntax/lr" ) // T traces to the SyntaxTracer. func T() tracing.Trace { return gtrace.SyntaxTracer } // --- Stack Nodes ----------------------------------------------------------- // DSSNode is a type for a node in a DSS stack. type DSSNode struct { State int // identifier of a parse state Sym lr.Symbol // symbol on the stack (between states) preds []*DSSNode // predecessors of this node (inverse join) succs []*DSSNode // successors of this node (inverse fork) pathcnt int // count of paths through this node } // create an empty stack node func newDSSNode(state int, sym lr.Symbol) *DSSNode { n := &DSSNode{} n.State = state n.Sym = sym return n } // Simple Stringer for a stack node. func (n *DSSNode) String() string { return fmt.Sprintf("<-(%v)-[%d]", n.Sym, n.State) } // Make an identical copy of a node func (n *DSSNode) clone() *DSSNode { nn := newDSSNode(n.State, n.Sym) for _, p := range n.preds { nn.prepend(p) } for _, s := range n.succs { nn.append(s) } return nn } // Append a node, i.e., insert it into the list of successors func (n *DSSNode) append(succ *DSSNode) { if n.succs == nil { n.succs = make([]*DSSNode, 0, 3) } n.succs = append(n.succs, succ) } // Prepend a node, i.e., insert it into the list of predecessors func (n *DSSNode) prepend(pred *DSSNode) { if n.preds == nil { n.preds = make([]*DSSNode, 0, 3) } n.preds = append(n.preds, pred) } // Unlink a node func (n *DSSNode) isolate() { T().Debugf("isolating %v", n) for _, p := range n.preds { p.succs, _ = remove(p.succs, n) } for _, s := range n.succs { s.preds, _ = remove(s.preds, n) } } func (n *DSSNode) is(state int, sym lr.Symbol) bool { return n.State == state && n.Sym == sym } func (n *DSSNode) isInverseJoin() bool { return n.preds != nil && len(n.preds) > 1 } func (n *DSSNode) isInverseFork() bool { return n.succs != nil && len(n.succs) > 1 } func (n *DSSNode) successorCount() int { if n.succs != nil { return len(n.succs) } return 0 } func (n *DSSNode) predecessorCount() int { if n.preds != nil { return len(n.preds) } return 0 } func (n *DSSNode) findUplink(sym lr.Symbol) *DSSNode { s := contains(n.succs, sym) return s } func (n *DSSNode) findDownlink(state int) *DSSNode { s := hasState(n.preds, state) return s } // NodePath is a run within a stack. We often will have to deal with fragments of a stack type NodePath []*DSSNode // === DSS Data Structure ==================================================== // DSSRoot is the root of a DSS-stack. All stacks of a DSS stack structure share a common // root. Clients have to create a root before stacks can be created. type DSSRoot struct { Name string // identifier for the DSS bottom *DSSNode // stopper stacks []*Stack // housekeeping reservoir *ssl.List // list of nodes to be re-used } // NewRoot creates a named root for a DSS-stack, given a name. // The second parameter is an implementation detail: clients have to supply // a state the root will use as a stopper. It should be an "impossible" state // for normal execution, to avoid confusion. func NewRoot(name string, invalidState int) *DSSRoot { root := &DSSRoot{Name: name} root.bottom = newDSSNode(invalidState, &pseudo{"bottom"}) root.bottom.pathcnt = 1 root.stacks = make([]*Stack, 0, 10) root.reservoir = ssl.New() return root } // ActiveStacks gets the stack-heads currently active in the DSS. // No order is guaranteed. func (root *DSSRoot) ActiveStacks() []*Stack { dup := make([]*Stack, len(root.stacks)) copy(dup, root.stacks) return dup } // Remove a stack from the list of stacks func (root *DSSRoot) removeStack(stack *Stack) { for i, s := range root.stacks { if s == stack { root.stacks[i] = root.stacks[len(root.stacks)-1] root.stacks[len(root.stacks)-1] = nil root.stacks = root.stacks[:len(root.stacks)-1] } } } // As a slight optimization, we do not throw away popped nodes, but rather // append them to a free-list for re-use. // TODO: create an initial pool of nodes. // TODO: migrate this to stdlib's sync/pool. func (root *DSSRoot) recycleNode(node *DSSNode) { T().Debugf("recycling node %v", node) node.State = 0 node.Sym = nil node.preds = node.preds[0:0] node.succs = node.succs[0:0] root.reservoir.Append(node) // list of nodes free for grab } // Create a new stack node or fetch a recycled one. func (root *DSSRoot) newNode(state int, sym lr.Symbol) *DSSNode { var node *DSSNode n, ok := root.reservoir.Get(0) if ok { root.reservoir.Remove(0) node = n.(*DSSNode) node.State = state node.Sym = sym } else { node = newDSSNode(state, sym) } return node } // Wrap nodes of a stack as heads of new stacks. func (root *DSSRoot) makeStackHeadsFrom(nodes []*DSSNode) (ret []*Stack) { for _, n := range nodes { s := NewStack(root) s.tos = n ret = append(ret, s) } return } // Find a TOS of any stack in the DSS which carries state and sym. // This is needed for suffix merging. Returns nil if no TOS meets the criteria. func (root *DSSRoot) findTOSofAnyStack(state int, sym lr.Symbol) *DSSNode { for _, stack := range root.stacks { if stack.tos.is(state, sym) { return stack.tos } } return nil } // IsAlone checks if a stack may safely delete nodes for a reduce operation. There are // exactly two cases when deletion is not permitted: (1) One or more other stacks // are sitting on the same node as this one (2) There are nodes present further // up the stack (presumably operated on by other stacks). func (root *DSSRoot) IsAlone(stack *Stack) bool { if stack.tos.successorCount() > 0 { return false } for _, other := range root.stacks { if other.tos == stack.tos { return false } } return true } // Stack is a data structure for a linear stack within a DSS (DAG structured stack = DSS). // All stacks together form a DSS, i.e. they // may share portions of stacks. Each client carries its own stack, without // noticing the other stacks. The data structure hides the fact that stack- // fragments may be shared. type Stack struct { root *DSSRoot // common root for a set of sub-stacks tos *DSSNode // top of stack } // NewStack creates a new linear stack within a DSS. func NewStack(root *DSSRoot) *Stack { s := &Stack{root: root, tos: root.bottom} s.root.stacks = append(s.root.stacks, s) return s } func (stack *Stack) String() string { return fmt.Sprintf("stack{tos=%v}", stack.tos) } // Calculate the height of a stack /* func (stack *Stack) calculateHeight() { stack.height = stack.tos.height(stack.root.bottom) // recurse until hits bottom } func (node *DSSNode) height(stopper *DSSNode) int { if node == stopper { return 0 } max := 0 for _, p := range node.preds { h := p.height(stopper) if h > max { max = h } } return max + 1 } */ // IsAlone checks if a stack may safely delete nodes for a reduce operation. There are // exactly two cases when deletion is not permitted: (1) One or more other stacks // are sitting on the same node as this one (2) There are nodes present further // up the stack (presumably operated on by other stacks). func (stack *Stack) IsAlone() bool { return stack.root.IsAlone(stack) } // Fork duplicates the head of a stack, resulting in a new stack. // The new stack is implicitely registered with the (common) root. func (stack *Stack) Fork() *Stack { s := NewStack(stack.root) //s.height = stack.height s.tos = stack.tos s.tos.pathcnt++ return s } // Peek returns TOS.Symbol and TOS.State without popping it. func (stack *Stack) Peek() (int, lr.Symbol) { return stack.tos.State, stack.tos.Sym } /* Push a state and a symbol on the stack. Interpretation is as follows: a transition has been found consuming symbol sym, leading to state state. The method looks for a TOS in the DSS representing the combination of (state, sym) and -- if present -- uses (reverse joins) the TOSs. Otherwise it creates a new DAG node. */ func (stack *Stack) Push(state int, sym lr.Symbol) *Stack { if sym == nil { return stack } // create or find a node // - create: new and let node.prev be tos // - find: return existing one // update references / pathcnt if succ := stack.tos.findUplink(sym); succ != nil { T().Debugf("state already present: %v", succ) stack.tos = succ // pushed state is already there, upchain } else { succ := stack.root.findTOSofAnyStack(state, sym) if succ == nil { // not found in DSS succ = stack.root.newNode(state, sym) T().Debugf("creating state: %v", succ) succ.pathcnt = stack.tos.pathcnt } else { T().Debugf("found state on other stack: %v", succ) succ.pathcnt++ } succ.prepend(stack.tos) stack.tos.append(succ) stack.tos = succ } return stack } // FindHandlePath finds a run within a stack corresponding to a handle, i.e., // a list of parse symbols. // // For reduce operations on a stack it is necessary to identify the // nodes which correspond to the symbols of the RHS of the production // to reduce. The nodes (some or all) may overlap with other stacks of // the DSS. // // For a RHS there may be more than one path downwards the stack marked // with the symbols of RHS. It is not deterministic which one this method // will find and return. // Clients may call this method multiple times. If a clients wants to find // all simultaneously existing paths, it should increment the parameter skip // every time. This determines the number of branches have been found // previously and should be skipped now. // // Will return nil if no (more) path is found. func (stack *Stack) FindHandlePath(handle []lr.Symbol, skip int) NodePath { path, ok := collectHandleBranch(stack.tos, handle, len(handle), &skip) if ok { T().Debugf("found a handle %v", path) } return path } // Recursive function to collect nodes corresponding to a list of symbols. // The bottom-most node, i.e. the one terminating the recursion, will allocate // the result array. This array will then be handed upwards the call stack, // being filled with node links on the way. func collectHandleBranch(n *DSSNode, handleRest []lr.Symbol, handleLen int, skip *int) (NodePath, bool) { l := len(handleRest) if l > 0 { if n.Sym == handleRest[l-1] { T().Debugf("handle symbol match at %d = %v", l-1, n.Sym) for _, pred := range n.preds { branch, found := collectHandleBranch(pred, handleRest[:l-1], handleLen, skip) if found { if *skip == 0 { T().Debugf("partial branch: %v", branch) if branch != nil { // a-ha, deepest node has created collector branch[l-1] = n // collect n in branch } return branch, true // return with partially filled branch } else { *skip = max(0, *skip-1) } } } } } else { branchCreated := make([]*DSSNode, handleLen) // create the handle-path collector return branchCreated, true // search/recursion terminates } return nil, false // abort search, handle-path not found } // This is probably never used for a real parser func (stack *Stack) splitOff(path NodePath) *Stack { l := len(path) // pre-condition: there are at least l nodes on the stack-path var node, mynode, upperNode *DSSNode = nil, nil, nil mystack := NewStack(stack.root) //mystack.height = stack.height for i := l - 1; i >= 0; i-- { // walk path from back to font, i.e. top-down node = path[i] mynode = stack.root.newNode(node.State, node.Sym) //mynode = stack.root.newNode(node.State+100, node.Sym) T().Debugf("split off node %v", mynode) if upperNode != nil { // we are not the top-node of the stack mynode.append(upperNode) upperNode.prepend(mynode) upperNode.pathcnt++ } else { // is the newly created top node mystack.tos = mynode // make it TOS of new stack } upperNode = mynode } if mynode != nil && node.preds != nil { for _, p := range node.preds { mynode.prepend(p) mynode.pathcnt++ } } return mystack } /* Pop nodes corresponding to a handle from a stack. The handle path nodes must exist in the DSS (to be checked beforhand by client). The decision wether to delete the nodes on the way down is not trivial. If the destructive-flag is unset, we do not delete anything. If it is set to true, we take this as a general permission to not have to regard other stacks. But we must be careful not to burn our own bridges. We may need a node for other (amybiguity-)paths we'll reduce within the same operation. The logic is as follows: (1) If we have already deleted the single predecessor of this node and this is a regular node (no join, no fork), then we may delete this one as well. (2) If this is a reverse join, we are decrementing the linkcnt and have permission to delete it, if it is the last run through this node. (3) If this is still a reverse fork (although we possbily have deleted one successor), we do not delete. */ func (stack *Stack) reduce(path NodePath, destructive bool) (ret []*Stack) { maydelete := true haveDeleted := false for i := len(path) - 1; i >= 0; i-- { // iterate over handle symbols back to front node := path[i] T().Debugf("reducing node %v (now cnt=%d)", node, node.pathcnt) T().Debugf(" node %v has %d succs", node, len(node.succs)) if node.isInverseJoin() { T().Debugf("is join: %v", node) maydelete = true node.pathcnt-- } else if haveDeleted && node.successorCount() > 0 { T().Debugf("is or has been fork: %v", node) maydelete = false } else { maydelete = true node.pathcnt-- } if i == 0 { // when popped every node: every predecessor is a stack head now ret = stack.root.makeStackHeadsFrom(node.preds) } if destructive && maydelete && node.pathcnt == 0 { node.isolate() stack.root.recycleNode(node) haveDeleted = true } else { haveDeleted = false } } return } // Reduce performs a reduce operation, given a handle, i.e. a right hand side of a // grammar rule. Strictly speaking, it performs not a complete reduce operation, // but just the first part: popping the RHS symbols off the stack. // Clients will have to push the LHS symbol separately. // // With a DSS, reduce may result in a multitude of new stack configurations. // Whenever there is a reduce/reduce conflict or a shift/reduce-conflict, a GLR // parser will perform both reduce-operations. To this end each possible operation // (i.e, parser) will (conceptually) use its own stack. // Thus multiple return values of a reduce operation correspond to (temporary // or real) ambiguity of a grammar. // // Example: X ::= A + A (grammar rule) // // Stack 1: ... a A + A // Stack 2: ... A + A + A // // as a DSS: -[a]------ // [A] [+]-[A] // now reduce this: A + A to X // -[A]-[+]-- // // This will result in 2 new stack heads: // // as a DSS: -[a] // return stack #1 of Reduce() // -[A]-[+] // return stack #2 of Reduce() // // After pushing X onto the stack, the 2 stacks may be merged (on 'X'), thus // resulting in a single stack head again. // // as a DSS: -[a]----- // [X] // -[A]-[+]- // // The stack triggering the reduce will be the first stack within the returning // array of stacks, i.e. the Reduce() return the stack itself plus possibly // other stacks created during the reduce operation. // func (stack *Stack) Reduce(handle []lr.Symbol) (ret []*Stack) { if len(handle) == 0 { return } var paths []NodePath // first collect all possible handle paths skip := 0 // how many paths already found? path := stack.FindHandlePath(handle, skip) for path != nil { paths = append(paths, path) skip++ path = stack.FindHandlePath(handle, skip) } destructive := stack.IsAlone() // give general permission to delete reduced nodes? for _, path = range paths { // now reduce along every path stacks := stack.reduce(path, destructive) ret = append(ret, stacks...) // collect returned stack heads } if len(ret) > 0 { // if avail, replace 1st stack with this stack.tos = ret[0].tos // make us a lookalike of the 1st returned one ret[0].Die() // the 1st returned one has to die ret[0] = stack // and we replace it } return } func (stack *Stack) reduceHandle(handle []lr.Symbol, destructive bool) (ret []*Stack) { haveReduced := true skipCnt := 0 for haveReduced { // as long as a reduction has been done haveReduced = false handleNodes := stack.FindHandlePath(handle, skipCnt) if handleNodes != nil { haveReduced = true if !destructive { skipCnt++ } s := stack.reduce(handleNodes, destructive) ret = append(ret, s...) } } return } // Pop the TOS of a stack. This is straigtforward for (non-empty) linear stacks // without shared nodes. For stacks with common suffixes, i.e. with inverse joins, // it is more tricky. The popping may result in multiple new stacks, one for // each predecessor. // // For parsers Pop may not be very useful. It is included here for // conformance with the general contract of a stack. With parsing, popping of // states happens during reductions, and the API offers more convenient // functions for this. func (stack *Stack) Pop() (ret []*Stack) { if stack.tos != stack.root.bottom { // ensure stack not empty // If tos is part of another chain: return node and go down one node // If shared by another stack: return node and go down one node // If not shared: remove node // Increase pathcnt at new TOS var oldTOS = stack.tos //var r []*Stack for i, n := range stack.tos.preds { // at least 1 predecessor if i == 0 { // 1st one: keep this stack stack.tos = n //stack.calculateHeight() } else { // further predecessors: create stack for each one s := NewStack(stack.root) s.tos = n //s.calculateHeight() //T().Debugf("creating new stack for %v (of height=%d)", n, s.height) ret = append(ret, s) } } if oldTOS.succs == nil || len(oldTOS.succs) == 0 { oldTOS.isolate() stack.root.recycleNode(oldTOS) } return ret } return nil } func (stack *Stack) pop(toNode *DSSNode, deleteNode bool, collectStacks bool) ([]*Stack, error) { var r []*Stack // return value var err error // return value if stack.tos != stack.root.bottom { // ensure stack not empty var oldTOS = stack.tos var found bool stack.tos.preds, found = remove(stack.tos.preds, toNode) if !found { err = errors.New("unable to pop TOS: 2OS not appropriate") } else { stack.tos.pathcnt-- toNode.pathcnt++ stack.tos = toNode //stack.calculateHeight() if deleteNode && oldTOS.pathcnt == 0 && (oldTOS.succs == nil || len(oldTOS.succs) == 0) { oldTOS.isolate() stack.root.recycleNode(oldTOS) } } } else { T().Errorf("unable to pop TOS: stack empty") err = errors.New("unable to pop TOS: stack empty") } return r, err } // --- Debugging ------------------------------------------------------------- // DSS2Dot outputs a DSS in Graphviz DOT format (for debugging purposes). // // If parameter path is given, it will be highlighted in the output. func DSS2Dot(root *DSSRoot, path []*DSSNode, w io.Writer) { istos := map[*DSSNode]bool{} for _, stack := range root.stacks { istos[stack.tos] = true } ids := map[*DSSNode]int{} idcounter := 1 io.WriteString(w, "digraph {\n") WalkDAG(root, func(node *DSSNode, arg interface{}) { ids[node] = idcounter idcounter++ styles := nodeDotStyles(node, pathContains(path, node)) if istos[node] { styles += ",shape=box" } io.WriteString(w, fmt.Sprintf("\"%d[%d]\" [label=%d %s];\n", node.State, ids[node], node.State, styles)) }, nil) WalkDAG(root, func(node *DSSNode, arg interface{}) { ww := w.(io.Writer) for _, p := range node.preds { io.WriteString(ww, fmt.Sprintf("\"%d[%d]\" -> \"%d[%d]\" [label=\"%v\"];\n", node.State, ids[node], p.State, ids[p], node.Sym)) } }, w) io.WriteString(w, "}\n") } func nodeDotStyles(node *DSSNode, highlight bool) string { s := ",style=filled" if highlight { s = s + fmt.Sprintf(",fillcolor=\"%s\"", hexhlcolors[node.pathcnt]) } else { s = s + fmt.Sprintf(",fillcolor=\"%s\"", hexcolors[node.pathcnt]) } return s } var hexhlcolors = [...]string{"#FFEEDD", "#FFDDCC", "#FFCCAA", "#FFBB88", "#FFAA66", "#FF9944", "#FF8822", "#FF7700", "#ff6600"} var hexcolors = [...]string{"white", "#CCDDFF", "#AACCFF", "#88BBFF", "#66AAFF", "#4499FF", "#2288FF", "#0077FF", "#0066FF"} // PrintDSS is for debugging. func PrintDSS(root *DSSRoot) { WalkDAG(root, func(node *DSSNode, arg interface{}) { predList := " " for _, p := range node.preds { predList = predList + strconv.Itoa(p.State) + " " } fmt.Printf("edge [%s]%v\n", predList, node) }, nil) } // WalkDAG walks all nodes of a DSS and execute a worker function on each. // parameter arg is presented as a second argument to each worker execution. func WalkDAG(root *DSSRoot, worker func(*DSSNode, interface{}), arg interface{}) { visited := map[*DSSNode]bool{} var walk func(*DSSNode, func(*DSSNode, interface{}), interface{}) walk = func(node *DSSNode, worker func(*DSSNode, interface{}), arg interface{}) { if visited[node] { return } visited[node] = true for _, p := range node.preds { walk(p, worker, arg) } worker(node, arg) } for _, stack := range root.stacks { walk(stack.tos, worker, arg) } } // Die signals end of lfe for this stack. // The stack will be detached from the DSS root and will let go of its TOS. func (stack *Stack) Die() { stack.root.removeStack(stack) stack.tos = nil } // --- Helpers --------------------------------------------------------------- func pathContains(s []*DSSNode, node *DSSNode) bool { if s != nil { for _, n := range s { if n == node { return true } } } return false } func contains(s []*DSSNode, sym lr.Symbol) *DSSNode { if s != nil { for _, n := range s { if n.Sym == sym { return n } } } return nil } // Helper : remove an item from a node slice // without preserving order (i.e, replace by last in slice) func remove(nodes []*DSSNode, node *DSSNode) ([]*DSSNode, bool) { for i, n := range nodes { if n == node { nodes[i] = nodes[len(nodes)-1] nodes[len(nodes)-1] = nil nodes = nodes[:len(nodes)-1] return nodes, true } } return nodes, false } func hasState(s []*DSSNode, state int) *DSSNode { for _, n := range s { if n.State == state
} return nil } type pseudo struct { name string } func pseudosym(name string) lr.Symbol { return &pseudo{name: name} } func (sy *pseudo) String() string { return sy.name } func (sy *pseudo) IsTerminal() bool { return true } func (sy *pseudo) Token() int { return 0 } func (sy *pseudo) GetID() int { return 0 } var _ lr.Symbol = &pseudo{} func max(a, b int) int { if a > b { return a } return b }
{ return n }
conditional_block
dss.go
/* Package dss implements variants of a DAG-structured stack (DSS). It is used for GLR-parsing and for substring parsing. A DSS is suitable for parsing with ambiguous grammars, so the parser can execute a breadth-first (quasi-)parallel shift and/or reduce operation in inadequate (ambiguous) parse states. Each parser (logical or real) sees it's own linear stack, but all stacks together form a DAG. Stacks share common fragments, making a DSS more space-efficient than a separeted forest of stacks. All stacks are anchored at the root of the DSS. root := NewRoot("G", -1) // represents the DSS stack1 := NewStack(root) // a linear stack within the DSS stack2 := NewStack(root) Please note that a DSS (this one, at least) is not well suited for general purpose stack operations. The non-deterministic concept of GLR-parsing will always lurk in the detail of this implementation. There are other stack implementations around which are much better suited, especially if performance matters. API The main API of this DSS consists of root = NewRoot("...", impossible) stack = NewStack(root) state, symbol = stack.Peek() // peek at top state and symbol of stack newstack = stack.Fork() // duplicate stack stacks = stack.Reduce(handle) // reduce with RHS of a production stack = stack.Push(state, symbol) // transition to new parse state, i.e. a shift stack.Die() // end of life for this stack Additionally, there are some low-level methods, which may help debugging or implementing your own add-on functionality. nodes = stack.FindHandlePath(handle, 0) // find a string of symbols down the stack DSS2Dot(root, path, writer) // output to Graphviz DOT format WalkDAG(root, worker, arg) // execute a function on each DSS node Other methods of the API are rarely used in parsing and exist more or less to complete a conventional stack API. Note that a method for determining the size of a stack is missing. stacks = stack.Pop() GLR Parsing A GLR parser forks a stack whenever an ambiguous state on top of the parse stack is processed. In a GLR-parser, shift/reduce- and reduce/reduce-conflicts are not uncommon, as potentially ambiguous grammars are used. Assume that a shift/reduce-conflict is signalled by the TOS. Then the parser will duplicate the stack (stack.Fork()) and carry out both operations: for one stack a symbol will be shifted, the other will be used for the reduce-operations. Further Information For further information see for example https://people.eecs.berkeley.edu/~necula/Papers/elkhound_cc04.pdf Status This is experimental software, currently not intended for production use. BSD License Copyright (c) 2017-20, Norbert Pillmayer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of this software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package dss import ( "errors" "fmt" "io" "strconv" ssl "github.com/emirpasic/gods/lists/singlylinkedlist" "github.com/npillmayer/gotype/core/config/gtrace" "github.com/npillmayer/gotype/core/config/tracing" "github.com/npillmayer/gotype/syntax/lr" ) // T traces to the SyntaxTracer. func T() tracing.Trace { return gtrace.SyntaxTracer } // --- Stack Nodes ----------------------------------------------------------- // DSSNode is a type for a node in a DSS stack. type DSSNode struct { State int // identifier of a parse state Sym lr.Symbol // symbol on the stack (between states) preds []*DSSNode // predecessors of this node (inverse join) succs []*DSSNode // successors of this node (inverse fork) pathcnt int // count of paths through this node } // create an empty stack node func newDSSNode(state int, sym lr.Symbol) *DSSNode { n := &DSSNode{} n.State = state n.Sym = sym return n } // Simple Stringer for a stack node. func (n *DSSNode) String() string { return fmt.Sprintf("<-(%v)-[%d]", n.Sym, n.State) } // Make an identical copy of a node func (n *DSSNode) clone() *DSSNode { nn := newDSSNode(n.State, n.Sym) for _, p := range n.preds { nn.prepend(p) } for _, s := range n.succs { nn.append(s) } return nn } // Append a node, i.e., insert it into the list of successors func (n *DSSNode) append(succ *DSSNode) { if n.succs == nil { n.succs = make([]*DSSNode, 0, 3) } n.succs = append(n.succs, succ) } // Prepend a node, i.e., insert it into the list of predecessors func (n *DSSNode) prepend(pred *DSSNode) { if n.preds == nil { n.preds = make([]*DSSNode, 0, 3) } n.preds = append(n.preds, pred) } // Unlink a node func (n *DSSNode) isolate() { T().Debugf("isolating %v", n) for _, p := range n.preds { p.succs, _ = remove(p.succs, n) } for _, s := range n.succs { s.preds, _ = remove(s.preds, n) } } func (n *DSSNode) is(state int, sym lr.Symbol) bool { return n.State == state && n.Sym == sym } func (n *DSSNode) isInverseJoin() bool { return n.preds != nil && len(n.preds) > 1 } func (n *DSSNode) isInverseFork() bool { return n.succs != nil && len(n.succs) > 1 } func (n *DSSNode) successorCount() int { if n.succs != nil { return len(n.succs) } return 0 } func (n *DSSNode) predecessorCount() int { if n.preds != nil { return len(n.preds) } return 0 } func (n *DSSNode) findUplink(sym lr.Symbol) *DSSNode { s := contains(n.succs, sym) return s } func (n *DSSNode) findDownlink(state int) *DSSNode { s := hasState(n.preds, state) return s } // NodePath is a run within a stack. We often will have to deal with fragments of a stack type NodePath []*DSSNode // === DSS Data Structure ==================================================== // DSSRoot is the root of a DSS-stack. All stacks of a DSS stack structure share a common // root. Clients have to create a root before stacks can be created. type DSSRoot struct { Name string // identifier for the DSS bottom *DSSNode // stopper stacks []*Stack // housekeeping reservoir *ssl.List // list of nodes to be re-used } // NewRoot creates a named root for a DSS-stack, given a name. // The second parameter is an implementation detail: clients have to supply // a state the root will use as a stopper. It should be an "impossible" state // for normal execution, to avoid confusion. func NewRoot(name string, invalidState int) *DSSRoot { root := &DSSRoot{Name: name} root.bottom = newDSSNode(invalidState, &pseudo{"bottom"}) root.bottom.pathcnt = 1 root.stacks = make([]*Stack, 0, 10) root.reservoir = ssl.New() return root } // ActiveStacks gets the stack-heads currently active in the DSS. // No order is guaranteed. func (root *DSSRoot) ActiveStacks() []*Stack { dup := make([]*Stack, len(root.stacks)) copy(dup, root.stacks) return dup } // Remove a stack from the list of stacks func (root *DSSRoot) removeStack(stack *Stack) { for i, s := range root.stacks { if s == stack { root.stacks[i] = root.stacks[len(root.stacks)-1] root.stacks[len(root.stacks)-1] = nil root.stacks = root.stacks[:len(root.stacks)-1] } } } // As a slight optimization, we do not throw away popped nodes, but rather // append them to a free-list for re-use. // TODO: create an initial pool of nodes. // TODO: migrate this to stdlib's sync/pool. func (root *DSSRoot) recycleNode(node *DSSNode) { T().Debugf("recycling node %v", node) node.State = 0 node.Sym = nil node.preds = node.preds[0:0] node.succs = node.succs[0:0] root.reservoir.Append(node) // list of nodes free for grab } // Create a new stack node or fetch a recycled one. func (root *DSSRoot) newNode(state int, sym lr.Symbol) *DSSNode { var node *DSSNode n, ok := root.reservoir.Get(0) if ok { root.reservoir.Remove(0) node = n.(*DSSNode) node.State = state node.Sym = sym } else { node = newDSSNode(state, sym) } return node } // Wrap nodes of a stack as heads of new stacks. func (root *DSSRoot) makeStackHeadsFrom(nodes []*DSSNode) (ret []*Stack) { for _, n := range nodes { s := NewStack(root) s.tos = n ret = append(ret, s) } return } // Find a TOS of any stack in the DSS which carries state and sym. // This is needed for suffix merging. Returns nil if no TOS meets the criteria. func (root *DSSRoot) findTOSofAnyStack(state int, sym lr.Symbol) *DSSNode { for _, stack := range root.stacks { if stack.tos.is(state, sym) { return stack.tos } } return nil } // IsAlone checks if a stack may safely delete nodes for a reduce operation. There are // exactly two cases when deletion is not permitted: (1) One or more other stacks // are sitting on the same node as this one (2) There are nodes present further // up the stack (presumably operated on by other stacks). func (root *DSSRoot) IsAlone(stack *Stack) bool { if stack.tos.successorCount() > 0 { return false } for _, other := range root.stacks { if other.tos == stack.tos { return false } } return true } // Stack is a data structure for a linear stack within a DSS (DAG structured stack = DSS). // All stacks together form a DSS, i.e. they // may share portions of stacks. Each client carries its own stack, without // noticing the other stacks. The data structure hides the fact that stack- // fragments may be shared. type Stack struct { root *DSSRoot // common root for a set of sub-stacks tos *DSSNode // top of stack } // NewStack creates a new linear stack within a DSS. func NewStack(root *DSSRoot) *Stack { s := &Stack{root: root, tos: root.bottom} s.root.stacks = append(s.root.stacks, s) return s } func (stack *Stack)
() string { return fmt.Sprintf("stack{tos=%v}", stack.tos) } // Calculate the height of a stack /* func (stack *Stack) calculateHeight() { stack.height = stack.tos.height(stack.root.bottom) // recurse until hits bottom } func (node *DSSNode) height(stopper *DSSNode) int { if node == stopper { return 0 } max := 0 for _, p := range node.preds { h := p.height(stopper) if h > max { max = h } } return max + 1 } */ // IsAlone checks if a stack may safely delete nodes for a reduce operation. There are // exactly two cases when deletion is not permitted: (1) One or more other stacks // are sitting on the same node as this one (2) There are nodes present further // up the stack (presumably operated on by other stacks). func (stack *Stack) IsAlone() bool { return stack.root.IsAlone(stack) } // Fork duplicates the head of a stack, resulting in a new stack. // The new stack is implicitely registered with the (common) root. func (stack *Stack) Fork() *Stack { s := NewStack(stack.root) //s.height = stack.height s.tos = stack.tos s.tos.pathcnt++ return s } // Peek returns TOS.Symbol and TOS.State without popping it. func (stack *Stack) Peek() (int, lr.Symbol) { return stack.tos.State, stack.tos.Sym } /* Push a state and a symbol on the stack. Interpretation is as follows: a transition has been found consuming symbol sym, leading to state state. The method looks for a TOS in the DSS representing the combination of (state, sym) and -- if present -- uses (reverse joins) the TOSs. Otherwise it creates a new DAG node. */ func (stack *Stack) Push(state int, sym lr.Symbol) *Stack { if sym == nil { return stack } // create or find a node // - create: new and let node.prev be tos // - find: return existing one // update references / pathcnt if succ := stack.tos.findUplink(sym); succ != nil { T().Debugf("state already present: %v", succ) stack.tos = succ // pushed state is already there, upchain } else { succ := stack.root.findTOSofAnyStack(state, sym) if succ == nil { // not found in DSS succ = stack.root.newNode(state, sym) T().Debugf("creating state: %v", succ) succ.pathcnt = stack.tos.pathcnt } else { T().Debugf("found state on other stack: %v", succ) succ.pathcnt++ } succ.prepend(stack.tos) stack.tos.append(succ) stack.tos = succ } return stack } // FindHandlePath finds a run within a stack corresponding to a handle, i.e., // a list of parse symbols. // // For reduce operations on a stack it is necessary to identify the // nodes which correspond to the symbols of the RHS of the production // to reduce. The nodes (some or all) may overlap with other stacks of // the DSS. // // For a RHS there may be more than one path downwards the stack marked // with the symbols of RHS. It is not deterministic which one this method // will find and return. // Clients may call this method multiple times. If a clients wants to find // all simultaneously existing paths, it should increment the parameter skip // every time. This determines the number of branches have been found // previously and should be skipped now. // // Will return nil if no (more) path is found. func (stack *Stack) FindHandlePath(handle []lr.Symbol, skip int) NodePath { path, ok := collectHandleBranch(stack.tos, handle, len(handle), &skip) if ok { T().Debugf("found a handle %v", path) } return path } // Recursive function to collect nodes corresponding to a list of symbols. // The bottom-most node, i.e. the one terminating the recursion, will allocate // the result array. This array will then be handed upwards the call stack, // being filled with node links on the way. func collectHandleBranch(n *DSSNode, handleRest []lr.Symbol, handleLen int, skip *int) (NodePath, bool) { l := len(handleRest) if l > 0 { if n.Sym == handleRest[l-1] { T().Debugf("handle symbol match at %d = %v", l-1, n.Sym) for _, pred := range n.preds { branch, found := collectHandleBranch(pred, handleRest[:l-1], handleLen, skip) if found { if *skip == 0 { T().Debugf("partial branch: %v", branch) if branch != nil { // a-ha, deepest node has created collector branch[l-1] = n // collect n in branch } return branch, true // return with partially filled branch } else { *skip = max(0, *skip-1) } } } } } else { branchCreated := make([]*DSSNode, handleLen) // create the handle-path collector return branchCreated, true // search/recursion terminates } return nil, false // abort search, handle-path not found } // This is probably never used for a real parser func (stack *Stack) splitOff(path NodePath) *Stack { l := len(path) // pre-condition: there are at least l nodes on the stack-path var node, mynode, upperNode *DSSNode = nil, nil, nil mystack := NewStack(stack.root) //mystack.height = stack.height for i := l - 1; i >= 0; i-- { // walk path from back to font, i.e. top-down node = path[i] mynode = stack.root.newNode(node.State, node.Sym) //mynode = stack.root.newNode(node.State+100, node.Sym) T().Debugf("split off node %v", mynode) if upperNode != nil { // we are not the top-node of the stack mynode.append(upperNode) upperNode.prepend(mynode) upperNode.pathcnt++ } else { // is the newly created top node mystack.tos = mynode // make it TOS of new stack } upperNode = mynode } if mynode != nil && node.preds != nil { for _, p := range node.preds { mynode.prepend(p) mynode.pathcnt++ } } return mystack } /* Pop nodes corresponding to a handle from a stack. The handle path nodes must exist in the DSS (to be checked beforhand by client). The decision wether to delete the nodes on the way down is not trivial. If the destructive-flag is unset, we do not delete anything. If it is set to true, we take this as a general permission to not have to regard other stacks. But we must be careful not to burn our own bridges. We may need a node for other (amybiguity-)paths we'll reduce within the same operation. The logic is as follows: (1) If we have already deleted the single predecessor of this node and this is a regular node (no join, no fork), then we may delete this one as well. (2) If this is a reverse join, we are decrementing the linkcnt and have permission to delete it, if it is the last run through this node. (3) If this is still a reverse fork (although we possbily have deleted one successor), we do not delete. */ func (stack *Stack) reduce(path NodePath, destructive bool) (ret []*Stack) { maydelete := true haveDeleted := false for i := len(path) - 1; i >= 0; i-- { // iterate over handle symbols back to front node := path[i] T().Debugf("reducing node %v (now cnt=%d)", node, node.pathcnt) T().Debugf(" node %v has %d succs", node, len(node.succs)) if node.isInverseJoin() { T().Debugf("is join: %v", node) maydelete = true node.pathcnt-- } else if haveDeleted && node.successorCount() > 0 { T().Debugf("is or has been fork: %v", node) maydelete = false } else { maydelete = true node.pathcnt-- } if i == 0 { // when popped every node: every predecessor is a stack head now ret = stack.root.makeStackHeadsFrom(node.preds) } if destructive && maydelete && node.pathcnt == 0 { node.isolate() stack.root.recycleNode(node) haveDeleted = true } else { haveDeleted = false } } return } // Reduce performs a reduce operation, given a handle, i.e. a right hand side of a // grammar rule. Strictly speaking, it performs not a complete reduce operation, // but just the first part: popping the RHS symbols off the stack. // Clients will have to push the LHS symbol separately. // // With a DSS, reduce may result in a multitude of new stack configurations. // Whenever there is a reduce/reduce conflict or a shift/reduce-conflict, a GLR // parser will perform both reduce-operations. To this end each possible operation // (i.e, parser) will (conceptually) use its own stack. // Thus multiple return values of a reduce operation correspond to (temporary // or real) ambiguity of a grammar. // // Example: X ::= A + A (grammar rule) // // Stack 1: ... a A + A // Stack 2: ... A + A + A // // as a DSS: -[a]------ // [A] [+]-[A] // now reduce this: A + A to X // -[A]-[+]-- // // This will result in 2 new stack heads: // // as a DSS: -[a] // return stack #1 of Reduce() // -[A]-[+] // return stack #2 of Reduce() // // After pushing X onto the stack, the 2 stacks may be merged (on 'X'), thus // resulting in a single stack head again. // // as a DSS: -[a]----- // [X] // -[A]-[+]- // // The stack triggering the reduce will be the first stack within the returning // array of stacks, i.e. the Reduce() return the stack itself plus possibly // other stacks created during the reduce operation. // func (stack *Stack) Reduce(handle []lr.Symbol) (ret []*Stack) { if len(handle) == 0 { return } var paths []NodePath // first collect all possible handle paths skip := 0 // how many paths already found? path := stack.FindHandlePath(handle, skip) for path != nil { paths = append(paths, path) skip++ path = stack.FindHandlePath(handle, skip) } destructive := stack.IsAlone() // give general permission to delete reduced nodes? for _, path = range paths { // now reduce along every path stacks := stack.reduce(path, destructive) ret = append(ret, stacks...) // collect returned stack heads } if len(ret) > 0 { // if avail, replace 1st stack with this stack.tos = ret[0].tos // make us a lookalike of the 1st returned one ret[0].Die() // the 1st returned one has to die ret[0] = stack // and we replace it } return } func (stack *Stack) reduceHandle(handle []lr.Symbol, destructive bool) (ret []*Stack) { haveReduced := true skipCnt := 0 for haveReduced { // as long as a reduction has been done haveReduced = false handleNodes := stack.FindHandlePath(handle, skipCnt) if handleNodes != nil { haveReduced = true if !destructive { skipCnt++ } s := stack.reduce(handleNodes, destructive) ret = append(ret, s...) } } return } // Pop the TOS of a stack. This is straigtforward for (non-empty) linear stacks // without shared nodes. For stacks with common suffixes, i.e. with inverse joins, // it is more tricky. The popping may result in multiple new stacks, one for // each predecessor. // // For parsers Pop may not be very useful. It is included here for // conformance with the general contract of a stack. With parsing, popping of // states happens during reductions, and the API offers more convenient // functions for this. func (stack *Stack) Pop() (ret []*Stack) { if stack.tos != stack.root.bottom { // ensure stack not empty // If tos is part of another chain: return node and go down one node // If shared by another stack: return node and go down one node // If not shared: remove node // Increase pathcnt at new TOS var oldTOS = stack.tos //var r []*Stack for i, n := range stack.tos.preds { // at least 1 predecessor if i == 0 { // 1st one: keep this stack stack.tos = n //stack.calculateHeight() } else { // further predecessors: create stack for each one s := NewStack(stack.root) s.tos = n //s.calculateHeight() //T().Debugf("creating new stack for %v (of height=%d)", n, s.height) ret = append(ret, s) } } if oldTOS.succs == nil || len(oldTOS.succs) == 0 { oldTOS.isolate() stack.root.recycleNode(oldTOS) } return ret } return nil } func (stack *Stack) pop(toNode *DSSNode, deleteNode bool, collectStacks bool) ([]*Stack, error) { var r []*Stack // return value var err error // return value if stack.tos != stack.root.bottom { // ensure stack not empty var oldTOS = stack.tos var found bool stack.tos.preds, found = remove(stack.tos.preds, toNode) if !found { err = errors.New("unable to pop TOS: 2OS not appropriate") } else { stack.tos.pathcnt-- toNode.pathcnt++ stack.tos = toNode //stack.calculateHeight() if deleteNode && oldTOS.pathcnt == 0 && (oldTOS.succs == nil || len(oldTOS.succs) == 0) { oldTOS.isolate() stack.root.recycleNode(oldTOS) } } } else { T().Errorf("unable to pop TOS: stack empty") err = errors.New("unable to pop TOS: stack empty") } return r, err } // --- Debugging ------------------------------------------------------------- // DSS2Dot outputs a DSS in Graphviz DOT format (for debugging purposes). // // If parameter path is given, it will be highlighted in the output. func DSS2Dot(root *DSSRoot, path []*DSSNode, w io.Writer) { istos := map[*DSSNode]bool{} for _, stack := range root.stacks { istos[stack.tos] = true } ids := map[*DSSNode]int{} idcounter := 1 io.WriteString(w, "digraph {\n") WalkDAG(root, func(node *DSSNode, arg interface{}) { ids[node] = idcounter idcounter++ styles := nodeDotStyles(node, pathContains(path, node)) if istos[node] { styles += ",shape=box" } io.WriteString(w, fmt.Sprintf("\"%d[%d]\" [label=%d %s];\n", node.State, ids[node], node.State, styles)) }, nil) WalkDAG(root, func(node *DSSNode, arg interface{}) { ww := w.(io.Writer) for _, p := range node.preds { io.WriteString(ww, fmt.Sprintf("\"%d[%d]\" -> \"%d[%d]\" [label=\"%v\"];\n", node.State, ids[node], p.State, ids[p], node.Sym)) } }, w) io.WriteString(w, "}\n") } func nodeDotStyles(node *DSSNode, highlight bool) string { s := ",style=filled" if highlight { s = s + fmt.Sprintf(",fillcolor=\"%s\"", hexhlcolors[node.pathcnt]) } else { s = s + fmt.Sprintf(",fillcolor=\"%s\"", hexcolors[node.pathcnt]) } return s } var hexhlcolors = [...]string{"#FFEEDD", "#FFDDCC", "#FFCCAA", "#FFBB88", "#FFAA66", "#FF9944", "#FF8822", "#FF7700", "#ff6600"} var hexcolors = [...]string{"white", "#CCDDFF", "#AACCFF", "#88BBFF", "#66AAFF", "#4499FF", "#2288FF", "#0077FF", "#0066FF"} // PrintDSS is for debugging. func PrintDSS(root *DSSRoot) { WalkDAG(root, func(node *DSSNode, arg interface{}) { predList := " " for _, p := range node.preds { predList = predList + strconv.Itoa(p.State) + " " } fmt.Printf("edge [%s]%v\n", predList, node) }, nil) } // WalkDAG walks all nodes of a DSS and execute a worker function on each. // parameter arg is presented as a second argument to each worker execution. func WalkDAG(root *DSSRoot, worker func(*DSSNode, interface{}), arg interface{}) { visited := map[*DSSNode]bool{} var walk func(*DSSNode, func(*DSSNode, interface{}), interface{}) walk = func(node *DSSNode, worker func(*DSSNode, interface{}), arg interface{}) { if visited[node] { return } visited[node] = true for _, p := range node.preds { walk(p, worker, arg) } worker(node, arg) } for _, stack := range root.stacks { walk(stack.tos, worker, arg) } } // Die signals end of lfe for this stack. // The stack will be detached from the DSS root and will let go of its TOS. func (stack *Stack) Die() { stack.root.removeStack(stack) stack.tos = nil } // --- Helpers --------------------------------------------------------------- func pathContains(s []*DSSNode, node *DSSNode) bool { if s != nil { for _, n := range s { if n == node { return true } } } return false } func contains(s []*DSSNode, sym lr.Symbol) *DSSNode { if s != nil { for _, n := range s { if n.Sym == sym { return n } } } return nil } // Helper : remove an item from a node slice // without preserving order (i.e, replace by last in slice) func remove(nodes []*DSSNode, node *DSSNode) ([]*DSSNode, bool) { for i, n := range nodes { if n == node { nodes[i] = nodes[len(nodes)-1] nodes[len(nodes)-1] = nil nodes = nodes[:len(nodes)-1] return nodes, true } } return nodes, false } func hasState(s []*DSSNode, state int) *DSSNode { for _, n := range s { if n.State == state { return n } } return nil } type pseudo struct { name string } func pseudosym(name string) lr.Symbol { return &pseudo{name: name} } func (sy *pseudo) String() string { return sy.name } func (sy *pseudo) IsTerminal() bool { return true } func (sy *pseudo) Token() int { return 0 } func (sy *pseudo) GetID() int { return 0 } var _ lr.Symbol = &pseudo{} func max(a, b int) int { if a > b { return a } return b }
String
identifier_name