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
|
use serde::{Deserialize, Serialize};
use smol::channel::Sender;
use crate::msg_id::MessageID;
#[derive(Debug, Serialize, Deserialize)]
pub struct Message<B> {
#[serde(flatten)]
pub header: MessageHeader,
pub body: B,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageHeader {
pub src: String,
#[serde(rename = "dest")]
pub dst: String,
}
impl MessageHeader {
pub fn flip(self) -> Self {
Self {
src: self.dst,
dst: self.src,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum MaelstromBody {
#[serde(rename = "init")]
Init {
node_id: String,
node_ids: Vec<String>,
msg_id: MessageID,
},
#[serde(rename = "init_ok")]
InitOk {
msg_id: MessageID,
in_reply_to: MessageID,
},
}
pub struct Output<B> {
node_id: String,
channel: Sender<Message<B>>,
}
impl<B: Serialize + Clone> Output<B> {
pub fn new(node_id: String, channel: Sender<Message<B>>) -> Self {
Self { node_id, channel }
}
pub async fn send(&self, dst: &str, body: &B) {
self.send_raw(Message {
header: MessageHeader {
src: self.node_id.clone(),
dst: dst.to_string(),
},
body: body.clone(),
})
.await;
}
pub async fn send_raw(&self, msg: Message<B>) {
self.channel.send(msg).await.unwrap();
}
}
|