1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use crate::message::Message;
use crate::node::Node;
use crate::Context;
use ockam_core::{Address, Result, Worker};
use std::collections::HashMap;
use std::future::Future;
use tokio::runtime::Runtime;
use tokio::sync::mpsc::{channel, Receiver, Sender};
pub struct Executor {
sender: Sender<Message>,
receiver: Receiver<Message>,
registry: HashMap<Address, (Context, Box<dyn Worker<Context = Context>>)>,
}
impl Default for Executor {
fn default() -> Self {
let (sender, receiver) = channel(32);
let registry = HashMap::new();
Self {
sender,
receiver,
registry,
}
}
}
impl Executor {
pub fn new() -> Self {
Executor::default()
}
pub async fn receive(&mut self) -> Option<Message> {
self.receiver.recv().await
}
pub fn new_context<S: ToString>(&self, address: S) -> Context {
let node = Node::new(self.sender.clone());
Context::new(node, address.to_string())
}
pub fn execute<F>(&mut self, future: F) -> Result<()>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let runtime = Runtime::new().unwrap();
let _join = runtime.spawn(future);
runtime.block_on(Message::handle(self));
Ok(())
}
pub fn register<S: ToString>(
&mut self,
address: S,
worker: Box<dyn Worker<Context = Context>>,
) -> Result<()> {
let address = address.to_string();
let context = self.new_context(address.clone());
self.registry.insert(address.clone(), (context, worker));
let (context, w) = self.registry.get_mut(&address).unwrap();
w.initialize(&mut context.clone()).unwrap();
Ok(())
}
}