summaryrefslogtreecommitdiff
path: root/echo/src/main.rs
blob: fed0059df19e9b303810d2c4267c39584a561905 (plain)
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
#![feature(return_position_impl_trait_in_trait)]
use std::future::Future;

use common::{
    msg::*,
    msg_id::{gen_msg_id, MessageID},
    run_server, Handler,
};
use serde::{Deserialize, Serialize};

fn main() {
    run_server::<EchoHandler>();
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum EchoBody {
    #[serde(rename = "echo")]
    Echo { msg_id: MessageID, echo: String },

    #[serde(rename = "echo_ok")]
    EchoOk {
        msg_id: MessageID,
        in_reply_to: MessageID,
        echo: String,
    },
}

pub struct EchoHandler {
    output: Output<EchoBody>,
}

impl Handler for EchoHandler {
    type Body = EchoBody;

    fn init(_node_id: String, _node_ids: Vec<String>, output: Output<Self::Body>) -> Self {
        EchoHandler { output }
    }

    fn handle(&self, header: MessageHeader, body: Self::Body) -> impl Future<Output = ()> + Send {
        async move {
            match body {
                EchoBody::Echo { msg_id, echo } => {
                    self.output
                        .send(
                            &header.src,
                            &EchoBody::EchoOk {
                                msg_id: gen_msg_id(),
                                in_reply_to: msg_id,
                                echo,
                            },
                        )
                        .await;
                }
                EchoBody::EchoOk { .. } => (),
            };
        }
    }
}