mt_scope 0.9.0

Node crash monitoring for Minot — detects disconnected nodes and fires a Torpedo shutdown.
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use anyhow::{Result, anyhow};
use core::net::SocketAddr;
use log::{debug, info};
use mt_sea::ShipKind;
use mt_sea::{net::Packet, ship::NetworkShipImpl, *};
use once_cell::sync::OnceCell;
use std::collections::HashSet;
use std::sync::Arc;
use std::thread;
use std::time;

use tokio::signal::ctrl_c;
use tokio::sync::Mutex;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Qos {
    #[default]
    Reliable,
    /// Reliable wire delivery and ordering, without the fatal failure policy.
    /// See `mt_sea::Qos` for the full split.
    TryReliable,
    BestEffort,
}

#[derive(Debug, Clone)]
pub struct ScopeConfig {
    pub name: String,
    pub mode: Qos,
}

// Singleton Objects to make sure this exists only once in the system
static SCOPE: OnceCell<Arc<Mutex<Scope>>> = OnceCell::new();
static COORDCOMMUNICATION: OnceCell<Arc<Mutex<CoordCommunication>>> = OnceCell::new();
static PACKET_ID: OnceCell<Arc<Mutex<i32>>> = OnceCell::new();
static CLIENTS: OnceCell<Arc<Mutex<HashSet<String>>>> = OnceCell::new();
static BEST_EFFORT_CLIENTS: OnceCell<Arc<Mutex<HashSet<String>>>> = OnceCell::new();

#[derive(Debug, Clone)]
pub struct Scope {
    name: String,
    ship: Arc<NetworkShipImpl>,
}

// Save communication channel to the coordinator
struct CoordCommunication {
    coord: (
        tokio::sync::mpsc::Sender<Packet>,
        tokio::sync::broadcast::Receiver<(Packet, Option<SocketAddr>)>,
    ),
}

impl Scope {
    /// Start the Scope. Only once per process due to static OnceCell.
    pub async fn create(config: ScopeConfig) -> anyhow::Result<()> {
        let sea_node_mode = match config.mode {
            Qos::Reliable => mt_sea::Qos::Reliable,
            Qos::TryReliable => mt_sea::Qos::TryReliable,
            Qos::BestEffort => mt_sea::Qos::BestEffort,
        };
        let rm_rules_on_disconnect = sea_node_mode.removes_rules_on_exit();
        let ship = mt_sea::ship::NetworkShipImpl::init(
            ShipKind::Rat(config.name.clone()),
            rm_rules_on_disconnect,
            sea_node_mode,
        )
        .await?;
        debug!("Ship created");

        let ship = Arc::new(ship);
        // A Scope can stay quiet for a long time between samples; without this
        // the coordinator drops it and stops answering its requests.
        ship.spawn_heartbeat();

        let scope = Scope {
            name: config.name,
            ship,
        };

        SCOPE
            .set(Arc::new(Mutex::new(scope)))
            .map_err(|_| anyhow!("This scope already exists"))?;

        PACKET_ID
            .set(Arc::new(Mutex::new(0)))
            .map_err(|_| anyhow!("Packet ID already initialized"))?;

        CLIENTS
            .set(Arc::new(Mutex::new(HashSet::new())))
            .map_err(|_| anyhow!("Clients already initialized"))?;

        BEST_EFFORT_CLIENTS
            .set(Arc::new(Mutex::new(HashSet::new())))
            .map_err(|_| anyhow!("Best-effort clients already initialized"))?;

        Scope::init_connection().await?;
        debug!("Coordinator connection established");

        Scope::connect_to_coord().await?;
        debug!("Registered with coordinator");

        Scope::start_scoping().await?;
        debug!("Scoping complete");

        Ok(())
    }

    async fn init_connection() -> anyhow::Result<()> {
        let scope = Scope::get_scope().await?;
        let scope = scope.lock().await;
        let ship = &scope.ship;

        let (coord_tx, coord_rx) = {
            let client = ship.client.lock().await;
            let client_send_lock = client.coordinator_send.read().unwrap();
            let coord_tx = client_send_lock
                .as_ref()
                .expect("Sender does not exist after creation.")
                .clone();

            let client_recv_lock = client.coordinator_receive.read().unwrap();
            let coord_rx = client_recv_lock
                .as_ref()
                .expect("Receiver does not exist after creation")
                .subscribe();
            (coord_tx, coord_rx)
        };

        let coords = CoordCommunication {
            coord: (coord_tx, coord_rx),
        };

        COORDCOMMUNICATION
            .set(Arc::new(Mutex::new(coords)))
            .map_err(|_| anyhow::anyhow!("COORDCOMMUNICATION already initialized"))?;

        Ok(())
    }

    async fn connect_to_coord() -> anyhow::Result<()> {
        let channels = Scope::get_coord_communication().await?;
        let channels = channels.lock().await;

        let (coord_tx, mut coord_rx) = (channels.coord.0.clone(), channels.coord.1.resubscribe());

        let (result_tx, result_rx) = tokio::sync::oneshot::channel();
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();

        tokio::spawn(async move {
            let _ = ready_tx.send(());

            loop {
                match coord_rx.recv().await {
                    Ok((packet, _)) => {
                        if matches!(packet.data, net::PacketKind::Acknowledge) {
                            let _ = result_tx.send(());
                            return;
                        }
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(_) => return,
                }
            }
        });

        ready_rx
            .await
            .map_err(|_| anyhow!("Receiver task failed to start"))?;

        coord_tx
            .send(Packet {
                header: mt_sea::net::Header::default(),
                data: net::PacketKind::RegisterShipAtVar {
                    ship: Scope::get_scope_name().await.unwrap(),
                    var: Scope::get_scope_name().await.unwrap(),
                    kind: net::RatPubRegisterKind::Scope,
                    node_mode: net::Qos::Reliable,
                },
            })
            .await?;

        result_rx.await?;

        Ok(())
    }

    async fn start_scoping() -> anyhow::Result<()> {
        loop {
            tokio::select! {
                _ = ctrl_c() => {
                    debug!("Ctrl-C received. Stopping scoping.");
                    return Ok(())
                }
                res = Scope::threesixty_scoping() => {
                    res?
                }
            }
            let interval = time::Duration::from_millis(1000);
            thread::sleep(interval);
        }
    }

    async fn threesixty_scoping() -> anyhow::Result<()> {
        let channels = Scope::get_coord_communication().await?;
        let channels = channels.lock().await;

        let (coord_tx, mut coord_rx) = (channels.coord.0.clone(), channels.coord.1.resubscribe());
        let (result_tx, result_rx) = tokio::sync::oneshot::channel();
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();

        let clients_current = Arc::new(Mutex::new(HashSet::new()));
        let clients_clone = clients_current.clone();

        tokio::spawn(async move {
            let _ = ready_tx.send(());

            loop {
                match coord_rx.recv().await {
                    Ok((packet, _)) => match packet.data {
                        net::PacketKind::Acknowledge => {
                            let _ = result_tx.send(());
                            return;
                        }
                        net::PacketKind::ClientsHash {
                            mut reliable,
                            best_effort,
                        } => {
                            // Exclude the scope itself from the set it monitors
                            if let Ok(name) = Scope::get_scope_name().await {
                                reliable.remove(&name);
                            }
                            debug!(
                                "[SCOPE] Sonar response — reliable: {:?}, best_effort: {:?}",
                                reliable, best_effort
                            );
                            // Accumulate best-effort names — never remove, so a dying
                            // best-effort node is still recognisable as best-effort even
                            // after the coordinator has already removed it from its own set.
                            if let Some(be_set) = BEST_EFFORT_CLIENTS.get() {
                                let mut be = be_set.lock().await;
                                be.extend(best_effort);
                            }
                            *clients_clone.lock().await = reliable;
                            let _ = result_tx.send(());
                            return;
                        }
                        _ => (),
                    },
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(_) => return,
                }
            }
        });

        ready_rx
            .await
            .map_err(|_| anyhow!("Receiver task failed to start"))?;

        coord_tx
            .send(Packet {
                header: mt_sea::net::Header::default(),
                data: net::PacketKind::Sonar,
            })
            .await
            .map_err(|_e| anyhow!("Failed to send Sonar packet"))?;

        result_rx
            .await
            .map_err(|_e| anyhow!("Failed to receive Sonar response"))?;

        drop(channels);

        Scope::handle_packet(clients_current.lock().await.clone()).await
    }

    async fn handle_packet(clients_current: HashSet<String>) -> anyhow::Result<()> {
        debug!(
            "[SCOPE] Handling packet #{:?}",
            Scope::get_counter_value().await
        );
        let clients = Scope::get_clients().await?;
        let mut clients = clients.lock().await;

        if clients.is_subset(&clients_current) {
            let new_clients: Vec<_> = clients_current.difference(&clients).cloned().collect();
            if new_clients.is_empty() {
                return Ok(());
            }
            info!("[SCOPE] New clients: {:?}", new_clients);
            for client in new_clients {
                clients.insert(client);
            }
        } else {
            let all_lost: Vec<_> = clients.difference(&clients_current).cloned().collect();

            // Filter out best-effort nodes — losing them should not trigger Torpedo
            let best_effort = BEST_EFFORT_CLIENTS
                .get()
                .and_then(|arc| arc.try_lock().ok());
            let lost_reliable: Vec<_> = match &best_effort {
                Some(be) => all_lost
                    .iter()
                    .filter(|name| !be.contains(*name))
                    .cloned()
                    .collect(),
                None => all_lost.clone(),
            };

            for client in &all_lost {
                clients.remove(client);
            }

            if !lost_reliable.is_empty() {
                info!("[SCOPE] Lost clients, firing Torpedo: {:?}", lost_reliable);
                Scope::send_torpedo(lost_reliable).await?;
            } else {
                debug!(
                    "[SCOPE] Lost best-effort clients, skipping Torpedo: {:?}",
                    all_lost
                );
            }
        }
        Ok(())
    }

    async fn send_torpedo(dead_clients: Vec<String>) -> anyhow::Result<()> {
        debug!("[SCOPE] Sending Torpedo for: {:?}", dead_clients);
        let channels = Scope::get_coord_communication().await?;
        let channels = channels.lock().await;

        let (coord_tx, mut coord_rx) = (channels.coord.0.clone(), channels.coord.1.resubscribe());
        let (result_tx, result_rx) = tokio::sync::oneshot::channel();
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();

        tokio::spawn(async move {
            let _ = ready_tx.send(());

            loop {
                match coord_rx.recv().await {
                    Ok((packet, _)) => {
                        if let net::PacketKind::Acknowledge = packet.data {
                            let _ = result_tx.send(());
                            return;
                        }
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(_) => return,
                }
            }
        });

        ready_rx
            .await
            .map_err(|_| anyhow!("Receiver task failed to start"))?;

        info!("[SCOPE] Sending Torpedo packet");
        coord_tx
            .send(Packet {
                header: mt_sea::net::Header::default(),
                data: net::PacketKind::Torpedo(dead_clients),
            })
            .await
            .map_err(|_e| anyhow!("Failed to send Torpedo packet"))?;

        result_rx
            .await
            .map_err(|_e| anyhow!("Failed to receive Torpedo acknowledgement"))?;

        drop(channels);
        Ok(())
    }

    async fn get_scope() -> Result<Arc<Mutex<Scope>>> {
        SCOPE
            .get()
            .cloned()
            .ok_or_else(|| anyhow!("No scope initialized"))
    }

    async fn get_coord_communication() -> Result<Arc<Mutex<CoordCommunication>>> {
        COORDCOMMUNICATION
            .get()
            .cloned()
            .ok_or_else(|| anyhow!("No coordinator communication channel initialized"))
    }

    async fn get_clients() -> Result<Arc<Mutex<HashSet<String>>>> {
        CLIENTS
            .get()
            .cloned()
            .ok_or_else(|| anyhow!("No clients set initialized"))
    }

    async fn get_scope_name() -> Result<String> {
        let name = Scope::get_scope().await?.lock().await.name.clone();
        Ok(name)
    }

    async fn get_packet_id() -> Result<Arc<Mutex<i32>>> {
        PACKET_ID
            .get()
            .cloned()
            .ok_or_else(|| anyhow!("Packet ID not initialized"))
    }

    async fn get_counter_value() -> Result<i32> {
        let value = Scope::get_packet_id().await?;
        let mut value = value.lock().await;
        let current = *value;
        *value += 1;
        Ok(current)
    }
}