file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
distributed_dqn_v2.py
qn_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 =
getReturn
identifier_name
distributed_dqn_v2.py
qn_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
else: #return action return self.greedy_policy(state)
random_line_split
distributed_dqn_v2.py
qn_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 =
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
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),
{ 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
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), ))
PluginInstruction
identifier_name
wasm_vm.rs
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),
{ 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
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), ))
buf_tx.send(wasi_read_string(&plugin_env.wasi_env)).unwrap();
random_line_split
state.rs
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
into_humanized
identifier_name
state.rs
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 ///
random_line_split
state.rs
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:
{ 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
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)
{ result? }
conditional_block
testingfrog.rs
(|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; //
random_line_split
testingfrog.rs
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
{ delimited( tag("status:"), delimited( space1, alt(( map(tag("published"), |_| PostStatus::Published), map(tag("draft"), |_| PostStatus::Draft), )), space0, ), newline, )(input) }
identifier_body
testingfrog.rs
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
post_status
identifier_name
sync.rs
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).
// Process response
random_line_split
sync.rs
file"; /// 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
check_response
identifier_name
sync.rs
file"; /// 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>
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
{ // 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), };
identifier_body
de.py
_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', '@')
filename = filename.replace('.csv', '')
random_line_split
de.py
Dataset() # 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
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
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
{ bgColor = jScene["bgColor"]; }
conditional_block
SceneL5.js
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.f
Scene
identifier_name
SceneL5.js
false; function Scene(canvasID, sceneURL)
// 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
{ // 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) });
identifier_body
SceneL5.js
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.far
camera.perspective = this.perspectiveCheckBox.checked; if (camera.perspective) {
random_line_split
main.go
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
//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
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
{ status.InputChannelCount.Update(int64(len(inputChannel))) status.OutputChannelCount.Update(int64(len(outputChannel))) }
conditional_block
main.go
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
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
{ 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 {
identifier_body
main.go
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
worker
identifier_name
index.py
> 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
''' 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
> 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
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
> 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
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
> 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 mangad
mangadex_import_progress
identifier_name
inter.go
+= "\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
ke([]string, 0) for _, od := range ods { for _, h := range od.header { h.transfer.collectFriendly(&friendly) } } return friendly } func CollectMis
identifier_body
inter.go
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"},
mbed(
identifier_name
inter.go
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"}},
type referenceTransfer struct { targetKey string
random_line_split
inter.go
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
values[i] = strings.TrimSpace(v) }
conditional_block
tab2.page.ts
.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); } }
identifier_body
tab2.page.ts
: 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
{ continue;}
conditional_block
tab2.page.ts
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");
random_line_split
tab2.page.ts
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
identifier_name
model.rs
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 = "
{ let rc = self.item[self.index]; self.index += 1; Some(rc) }
conditional_block
model.rs
(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
new
identifier_name
model.rs
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.
identifier_body
model.rs
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.
random_line_split
art_tree.go
} 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
{ current.RemoveChild(key[depth]) t.size -= 1 // Otherwise, recurse. t.size -= 1 }
conditional_block
art_tree.go
} 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
// 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
} 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
{ return t.EachChanResultFrom(t.searchHelper(t.root, key, 0)) }
identifier_body
art_tree.go
} 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
Remove
identifier_name
lib.rs
_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
spawn
identifier_name
lib.rs
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()) }
identifier_body
lib.rs
_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
// Routes request using the `DstAddr` extension.
random_line_split
lib.rs
.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 }
EndpointError
identifier_name
lib.rs
)] 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)) }
random_line_split
infinite-article-origin.js
$('.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; }
conditional_block
infinite-article-origin.js
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
{ h = c }
identifier_body
infinite-article-origin.js
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 () {
random_line_split
infinite-article-origin.js
() { 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
g
identifier_name
main.rs
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 =
{ data[0][500 - xstart + 2] = Tile::Spring; Map { data, xstart } }
identifier_body
main.rs
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().
tile_at
identifier_name
main.rs
::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
random_line_split
manager_test.go
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.NewMut
{ 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"))
identifier_body
manager_test.go
Entities(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) }
conditional_block
manager_test.go
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
identifier_name
manager_test.go
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) }
random_line_split
point.js
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
identifier_name
point.js
{ //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()
{ }
identifier_body
point.js
ier, {'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; }
conditional_block
point.js
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
if (a1.types['program']) this.programName = nodeName;
random_line_split
lib.rs
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
swap_invoke_context
identifier_name
lib.rs
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 }
identifier_body
lib.rs
InvokeContext 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);
}
random_line_split
utils.rs
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
fn channels(&self) -> usize {
random_line_split
utils.rs
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
xt(&
identifier_name
utils.rs
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 f6
self } }
identifier_body
utils.rs
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 {
self.seed.channels as usize } e
conditional_block
libstore-impl.go
port 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:
var err error cli, err = rpc.DialHTTP("tcp", hostport)
random_line_split
libstore-impl.go
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)
RevokeLease
identifier_name
libstore-impl.go
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 }
identifier_body
libstore-impl.go
[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 }
conditional_block
router.rs
}, 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
identifier_name
router.rs
)] #[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");
}; let result = evaluate( router_asset, project_path, env,
random_line_split
minimize.rs
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
/// 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
ISTIC) { 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
acceptor_minimize
identifier_name
minimize.rs
ISTIC)
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
{ true }
conditional_block
state_machine.go
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
identifier_name
state_machine.go
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) }
random_line_split
state_machine.go
// 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)
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
{ // 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)
identifier_body
state_machine.go
// 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
{ sm.plugin.Log.Debug("finished states. resetting") sm.Reset(in) return sm.Next(in) }
conditional_block
gfx2.go
-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) //
random_line_split
diag.rs
, 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
{ self.report(Diagnostic::new(Severity::Fatal, msg.into(), span)); std::panic::panic_any(Severity::Fatal); }
identifier_body
diag.rs
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
} for _ in 0..ch.len_utf8() { columns.push(vlen);
random_line_split
diag.rs
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
report
identifier_name
lib.rs
//! // .. //! } //! ``` #[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.
{ self.allow_module_paths.push(path.into()); self }
identifier_body
lib.rs
//! //! // .. //! } //! ``` #[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.
android_log
identifier_name
lib.rs
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;
random_line_split
lib.rs
} } 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 }
conditional_block
dss.go
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))
random_line_split
dss.go
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
{ return n.succs != nil && len(n.succs) > 1 }
identifier_body
dss.go
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 }
conditional_block
dss.go
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
String
identifier_name
tags.rs
fn add_class(&mut self, class: &str) { let attr = self.attribute("class"); let mut attr = if let Some(s) = attr { s } else { String::with_capacity(class.len()) }; attr.push(' '); attr.push_str(class); self.set_attribute("class", &attr); } fn remove_class(&mut self, class: &str) { let attr = self.attribute("class"); if attr.is_none() { self.set_attribute("class", class); return; } let attr = attr.unwrap(); let split = attr.split_whitespace(); let mut new_str = String::with_capacity(attr.len()); for val in split { if val != class { new_str.push_str(val); } } self.set_attribute("class", &new_str); } fn has_class(&self, class: &str) -> bool { let attr = self.attribute("class"); if attr.is_none() { return false; } let attr = attr.unwrap(); let split = attr.split_whitespace(); for s in split { if s == class { return true; } } false } } /// Text content can be set to some text value and read this content back. pub trait TextContent: Element { /// Get text contained by this element. fn text(&self) -> String { if let Some(s) = self.attribute("textContent") { s } else { String::new() } } fn set_text<T: AsRef<str>>(&mut self, text: T) { self.set_attribute("textContent", text.as_ref()) } } pub trait ImageContent: Element { /// Set image data to this element. fn set_image(&mut self, img: Arc<Image>); /// Get image data of this element. fn image(&self) -> Option<&Arc<Image>>; /// Remove any supplied image data. fn remove_image(&mut self) -> Option<Arc<Image>>; } macro_rules! elm_impl { ($name: ident) => { impl Element for $name { fn view(&self) -> &ViewWrap { &self.view } fn id(&self) -> &String { &self.id } fn tag_name(&self) -> TagName { TagName::$name } } } } /// Wrap that gives access to the dynamic element which is known to be of given type. #[derive(Debug)] pub struct Wrap<T: Element> { element: Box<dyn Element>, _p: PhantomData<T>, } /// Image data of canvas. #[derive(Clone)] pub struct Image { base64: String, format: ImageFormat, } #[derive(Debug)] pub struct A { view: ViewWrap, id: String, onclick: OnClick<A>, } #[derive(Debug)] pub struct Canvas { view: ViewWrap, id: String, } #[derive(Clone, Debug)] pub struct H4 { view: ViewWrap, id: String, } #[derive(Clone, Debug)] pub struct H5 { view: ViewWrap, id: String, } #[derive(Clone, Debug)] pub struct Img { view: ViewWrap, id: String, data: Option<Arc<Image>>, } #[derive(Clone, Debug)] pub struct Li { view: ViewWrap, id: String, } #[derive(Clone, Debug)] pub struct P { view: ViewWrap, id: String, } #[derive(Clone, Debug)] pub struct Span { view: ViewWrap, id: String, } elm_impl!(A); elm_impl!(Canvas); elm_impl!(H4); elm_impl!(H5); elm_impl!(Img); elm_impl!(Li); elm_impl!(P); elm_impl!(Span); #[derive(Clone, Debug)] pub struct Unknown { view: ViewWrap, id: String, name: String, } impl<T> Wrap<T> where T: Element { /// Wrap given element. /// /// # Safety /// Programmer must be sure this element has expected type. pub unsafe fn new(element: Box<dyn Element>) -> Self { Wrap { element, _p: Default::default(), } } } impl<T> Deref for Wrap<T> where T: Element { type Target = Box<T>; fn deref(&self) -> &Box<T> { let b = &self.element; let ptr = b as *const Box<dyn Element> as *const Box<T>; unsafe { &*ptr } } } impl<T> DerefMut for Wrap<T> where T: Element { fn deref_mut(&mut self) -> &mut Box<T> { let b = &mut self.element; let ptr = b as *mut Box<dyn Element> as *mut Box<T>; unsafe { &mut *ptr } } } impl Debug for Image { fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result { write!(fmt, "Image {{ base64: [char; ")?; write!(fmt, "{}", self.base64.len())?; write!(fmt, "], format: ")?; write!(fmt, "{:?}", self.format)?; write!(fmt, " }}")?; Ok(()) } } impl From<&str> for TagName { fn from(s: &str) -> Self { use self::TagName::*; match s.to_lowercase().as_str() { "a" => A, "canvas" => Canvas, "h4" => H4, "h5" => H5, "img" => Img, "li" => Li, "p" => P, "span" => Span, _ => Unknown(String::from(s)), } } } impl TagName { /// Create implementation of the tag by it's tag name. pub fn new_impl(&self, view: ViewWrap, id: String) -> Box<dyn Element> { match self { TagName::A => { let mut b = Box::new(A { view, id, onclick: unsafe { OnClick::null() }, }); let onclick = unsafe { OnClick::new(&mut *b) }; b.onclick = onclick; b }, TagName::Canvas => { Box::new(Canvas { view, id, }) }, TagName::H4 => Box::new( H4 { view, id, } ), TagName::H5 => Box::new( H4 { view, id, } ), TagName::Img => Box::new( Img { view, id, data: None, } ), TagName::Li => Box::new ( Li { view, id, } ), TagName::P => Box::new(P { view, id }), TagName::Span => Box::new(Span { view, id }), TagName::Unknown(name) => Box::new(Unknown { view, id, name: name.clone(), }), } } /// Try creating TagName from this node. pub fn try_from_node(node: &Node) -> Option<Self> { let tag_name = node.tag_name(); if let Some(tag_name) = tag_name { let tag_name = TagName::from(tag_name); Some(tag_name) } else { None } } /// Try creating implementation of the Element from this node. /// /// # Failures /// Node must contain ID of the element. It also is required to contain opening tag /// which corresponds to element tag. If either of conditions is not met this function /// will return None. pub fn try_impl_from_node(node: &Node, view: ViewWrap) -> Option<Box<dyn Element>> { let tag_name = Self::try_from_node(node); if let Some(tag_name) = tag_name { let id = node.attribute_by_name("id"); if let Some(id) = id { Some(tag_name.new_impl(view, id.values_to_string())) } else { None } } else { None } } } impl ImageFormat { pub fn to_string(&self) -> String { use ImageFormat::*; match self { Jpg => "jpg", Png => "png", }.to_string() } } impl Image { /// Encode given array of bytes in Base64 encoding. pub fn base64(bin: Vec<u8>) -> String { base64::encode(&bin) } /// Generate image struct from given array. pub fn from_binary(bin: Vec<u8>, format: ImageFormat) -> Image { Image { base64: Self::base64(bin), format, } } /// Convert this image to string that can be supplied to 'src' attribute of <img> tag. pub fn to_img_string(&self) -> String { format!("data:image/{};base64,{}", self.format.to_string(), self.base64) } } impl A { pub fn href(&self) -> String
{ if let Some(s) = self.attribute("href") { s } else { String::new() } }
identifier_body