File size: 4,388 Bytes
b98ffbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use crate::{
    tcp_utils::{tcp_receive, tcp_send},
    DaemonCoordinatorEvent,
};
use dora_core::{
    coordinator_messages::{CoordinatorRequest, RegisterResult},
    daemon_messages::{DaemonCoordinatorReply, Timestamped},
    message::uhlc::HLC,
};
use eyre::{eyre, Context};
use std::{io::ErrorKind, net::SocketAddr};
use tokio::{
    net::TcpStream,
    sync::{mpsc, oneshot},
};
use tokio_stream::{wrappers::ReceiverStream, Stream};

#[derive(Debug)]
pub struct CoordinatorEvent {
    pub event: DaemonCoordinatorEvent,
    pub reply_tx: oneshot::Sender<Option<DaemonCoordinatorReply>>,
}

pub async fn register(
    addr: SocketAddr,
    machine_id: String,
    listen_port: u16,
    clock: &HLC,
) -> eyre::Result<impl Stream<Item = Timestamped<CoordinatorEvent>>> {
    let mut stream = TcpStream::connect(addr)
        .await
        .wrap_err("failed to connect to dora-coordinator")?;
    stream
        .set_nodelay(true)
        .wrap_err("failed to set TCP_NODELAY")?;
    let register = serde_json::to_vec(&Timestamped {
        inner: CoordinatorRequest::Register {
            dora_version: env!("CARGO_PKG_VERSION").to_owned(),
            machine_id,
            listen_port,
        },
        timestamp: clock.new_timestamp(),
    })?;
    tcp_send(&mut stream, &register)
        .await
        .wrap_err("failed to send register request to dora-coordinator")?;
    let reply_raw = tcp_receive(&mut stream)
        .await
        .wrap_err("failed to register reply from dora-coordinator")?;
    let result: Timestamped<RegisterResult> = serde_json::from_slice(&reply_raw)
        .wrap_err("failed to deserialize dora-coordinator reply")?;
    result.inner.to_result()?;
    if let Err(err) = clock.update_with_timestamp(&result.timestamp) {
        tracing::warn!("failed to update timestamp after register: {err}");
    }

    tracing::info!("Connected to dora-coordinator at {:?}", addr);

    let (tx, rx) = mpsc::channel(1);
    tokio::spawn(async move {
        loop {
            let event = match tcp_receive(&mut stream).await {
                Ok(raw) => match serde_json::from_slice(&raw) {
                    Ok(event) => event,
                    Err(err) => {
                        let err =
                            eyre!(err).wrap_err("failed to deserialize incoming coordinator event");
                        tracing::warn!("{err:?}");
                        continue;
                    }
                },
                Err(err) if err.kind() == ErrorKind::UnexpectedEof => break,
                Err(err) => {
                    let err = eyre!(err).wrap_err("failed to receive incoming event");
                    tracing::warn!("{err:?}");
                    continue;
                }
            };
            let Timestamped {
                inner: event,
                timestamp,
            } = event;
            let (reply_tx, reply_rx) = oneshot::channel();
            match tx
                .send(Timestamped {
                    inner: CoordinatorEvent { event, reply_tx },
                    timestamp,
                })
                .await
            {
                Ok(()) => {}
                Err(_) => {
                    // receiving end of channel was closed
                    break;
                }
            }

            let Ok(reply) = reply_rx.await else {
                tracing::warn!("daemon sent no reply");
                continue;
            };
            if let Some(reply) = reply {
                let serialized = match serde_json::to_vec(&reply)
                    .wrap_err("failed to serialize DaemonCoordinatorReply")
                {
                    Ok(r) => r,
                    Err(err) => {
                        tracing::error!("{err:?}");
                        continue;
                    }
                };
                if let Err(err) = tcp_send(&mut stream, &serialized).await {
                    tracing::warn!("failed to send reply to coordinator: {err}");
                    continue;
                };
                if let DaemonCoordinatorReply::DestroyResult { notify, .. } = reply {
                    if let Some(notify) = notify {
                        let _ = notify.send(());
                    }
                    break;
                }
            }
        }
    });

    Ok(ReceiverStream::new(rx))
}