use serde::{Deserialize, Serialize}; use smol::channel::Sender; use crate::msg_id::MessageID; #[derive(Debug, Serialize, Deserialize)] pub struct Message { #[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, msg_id: MessageID, }, #[serde(rename = "init_ok")] InitOk { msg_id: MessageID, in_reply_to: MessageID, }, } pub struct Output { node_id: String, channel: Sender>, } impl Output { pub fn new(node_id: String, channel: Sender>) -> 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) { self.channel.send(msg).await.unwrap(); } }