mt_sea 0.17.0

Primitives for a Minot network.
Documentation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use std::collections::HashSet;

use log::{debug, error, info, warn};
use nalgebra::DMatrix;

use rkyv::{Archive, Deserialize, Serialize, api::high::from_bytes, rancor, util::AlignedVec};
use zenoh::Wait;

use crate::{Action, ShipKind, ShipName, VariableHuman, WindData};

pub const PROTO_IDENTIFIER: u8 = 69;
pub const CONTROLLER_CLIENT_ID: ShipName = 0;

pub(crate) fn client_heartbeat_key(domain_id: u16, sanitized_ship_name: &str) -> String {
    format!(
        "minot/{}/heartbeat/clients/{}/coord",
        domain_id, sanitized_ship_name
    )
}

/// Copy bytes into an aligned buffer for rkyv deserialization.
fn align_bytes(bytes: &[u8]) -> AlignedVec {
    let mut aligned = AlignedVec::with_capacity(bytes.len());
    aligned.extend_from_slice(bytes);
    aligned
}

/// Sanitize a ship name for use in Zenoh key expressions.
/// Zenoh forbids `#` and `?` characters in key expressions.
pub fn sanitize_key(name: &str) -> String {
    name.replace('#', "_hash_").replace('?', "_qmark_")
}

pub fn get_domain_id() -> u16 {
    let val = std::env::var("MINOT_DOMAIN_ID")
        .ok()
        .unwrap_or("0".to_owned());
    let parsed = val.parse::<u16>().ok();
    match parsed {
        Some(parsed) => parsed,
        None => {
            warn!("Invalid MINOT_DOMAIN_ID, selecting default 0");
            0
        }
    }
}

#[derive(Archive, Serialize, Deserialize, Clone, Debug)]
pub struct WindAt {
    pub data: WindData,
    pub at_var: Option<String>,
}

/// Wrapper for using the rkyv 0.8 APIs with nalgebra.
#[derive(Archive, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct NetArray<T: nalgebra::Scalar> {
    cols: usize,
    data: Vec<T>,
    rows: usize,
}

impl<T: nalgebra::Scalar> From<DMatrix<T>> for NetArray<T> {
    fn from(value: DMatrix<T>) -> Self {
        Self {
            rows: value.nrows(),
            cols: value.ncols(),
            data: value.data.into(),
        }
    }
}

impl<T: nalgebra::Scalar> From<NetArray<T>> for DMatrix<T> {
    fn from(value: NetArray<T>) -> Self {
        Self::from_data(nalgebra::VecStorage::new(
            nalgebra::Dyn(value.rows),
            nalgebra::Dyn(value.cols),
            value.data,
        ))
    }
}

/// Reliability and failure handling.
#[derive(Serialize, Deserialize, Archive, Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Reliability {
    #[default]
    Reliable,
    TryReliable,
    BestEffort,
}

/// Message durability.
#[derive(Serialize, Deserialize, Archive, Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Durability {
    #[default]
    Volatile,
    TransientLocal,
}

/// Delivery policy for a node or topic.
#[derive(Serialize, Deserialize, Archive, Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Qos {
    reliability: Reliability,
    durability: Durability,
}

#[allow(non_upper_case_globals)]
impl Qos {
    pub const Reliable: Self = Self::new(Reliability::Reliable, Durability::Volatile);
    pub const TryReliable: Self = Self::new(Reliability::TryReliable, Durability::Volatile);
    pub const BestEffort: Self = Self::new(Reliability::BestEffort, Durability::Volatile);

    pub const fn new(reliability: Reliability, durability: Durability) -> Self {
        Self {
            reliability,
            durability,
        }
    }

    pub const fn reliability_mode(self) -> Reliability {
        self.reliability
    }

    pub const fn durability(self) -> Durability {
        self.durability
    }

    pub fn reliability(self) -> zenoh::qos::Reliability {
        match self.reliability {
            Reliability::Reliable | Reliability::TryReliable => zenoh::qos::Reliability::Reliable,
            Reliability::BestEffort => zenoh::qos::Reliability::BestEffort,
        }
    }

    /// For control traffic and `BestEffort`/`Reliable` data. `TryReliable` data
    /// uses `Block`.
    pub fn congestion_control(self) -> zenoh::qos::CongestionControl {
        match self.reliability {
            Reliability::Reliable => zenoh::qos::CongestionControl::Block,
            Reliability::TryReliable => zenoh::qos::CongestionControl::BlockFirst,
            Reliability::BestEffort => zenoh::qos::CongestionControl::Drop,
        }
    }

    pub fn is_monitored(self) -> bool {
        self.reliability == Reliability::Reliable
    }

    pub fn fires_torpedo(self) -> bool {
        self.reliability == Reliability::Reliable
    }

    pub fn removes_rules_on_exit(self) -> bool {
        self.reliability == Reliability::Reliable
    }

    pub fn expects_reliable_delivery(self) -> bool {
        self.reliability != Reliability::BestEffort
    }

    pub const fn transient_local(mut self) -> Self {
        self.durability = Durability::TransientLocal;
        self
    }

    pub const fn is_transient_local(self) -> bool {
        matches!(self.durability, Durability::TransientLocal)
    }
}

#[derive(Serialize, Deserialize, Archive, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum RatPubRegisterKind {
    Publish,
    Subscribe,
    Scope,
}

#[derive(Serialize, Deserialize, Archive, Clone, Debug)]
pub enum PacketKind {
    Acknowledge,
    Retry,
    RequestVarSend(String),
    JoinRequest {
        kind: ShipKind,
        remove_rules_on_disconnect: bool,
        domain_id: u16,
        node_mode: Qos,
        /// How long this client wants the coordinator to wait before declaring
        /// it gone. Sent by the client because only it knows what kind of link
        /// it is on. See `crate::Timing`.
        disconnect_timeout_ms: u64,
        /// Where the client runs. It decides how the coordinator knows that
        /// the client is still there, see `crate::presence`.
        presence: crate::presence::Presence,
    },
    Welcome {
        addr: crate::NetworkShipAddress,
        wait_for_ack: bool,
        /// Where the coordinator runs, for the client to watch it the same way.
        presence: crate::presence::Presence,
    },
    Heartbeat,
    Disconnect,
    RuleAppend {
        variable: String,
        commands: Vec<VariableHuman>,
    },
    RulesClear,
    LockNext {
        unlock_first: bool,
    },
    Unlock,
    RawDataf64(NetArray<f64>),
    RawDataf32(NetArray<f32>),
    RawDatai32(NetArray<i32>),
    RawDatau8(NetArray<u8>),
    VariableTaskRequest(String),
    RatAction {
        variable: String,
        action: Action,
        lock_until_ack: bool,
    },
    Wind(Vec<WindAt>),
    WindDynamic(String),
    RegisterShipAtVar {
        ship: String,
        var: String,
        kind: RatPubRegisterKind,
        node_mode: Qos,
    },
    /// Stop delivering a topic to a ship. Without it a subscriber can only stop
    /// reading while the coordinator keeps pushing data at it.
    UnregisterShipAtVar {
        ship: String,
        var: String,
        kind: RatPubRegisterKind,
    },
    RegistrationError(String),
    Sonar,
    Torpedo(Vec<String>),
    ClientsHash {
        reliable: HashSet<String>,
        best_effort: HashSet<String>,
    },
    PeerDead {
        ship: String,
    },
}

#[derive(Archive, Serialize, Deserialize, Copy, Clone, Debug, Default)]
pub struct Header {
    pub source: ShipName,
    pub target: ShipName,
}

#[derive(Archive, Serialize, Deserialize, Clone, Debug)]
pub struct Packet {
    pub header: Header,
    pub data: PacketKind,
}

#[derive(Clone, Debug)]
pub struct ShipHandle {
    pub name: ShipKind,
    pub addr_from_coord: crate::NetworkShipAddress,
    pub ship: ShipName,
    pub disconnect: tokio::sync::broadcast::Sender<bool>,
    pub recv: tokio::sync::broadcast::Sender<(Packet, Option<std::net::SocketAddr>)>,
    pub send: tokio::sync::mpsc::Sender<Packet>,
    pub remove_rules_on_disconnect: bool,
    pub node_mode: Qos,
    /// How patient this client asked the coordinator to be with it.
    pub disconnect_timeout_ms: u64,
    /// Where the client runs.
    pub presence: crate::presence::Presence,
}

/// Zenoh-based Sea coordinator.
#[derive(Debug)]
pub struct Sea {
    pub network_clients_chan: tokio::sync::broadcast::Sender<ShipHandle>,
    #[allow(dead_code)]
    session: std::sync::Arc<zenoh::Session>,
    #[allow(dead_code)]
    domain_id: u16,
}

impl Sea {
    pub async fn init(
        _external_ip: Option<[u8; 4]>,
        clients_wait_for_ack: std::sync::Arc<std::sync::RwLock<bool>>,
    ) -> anyhow::Result<Self> {
        let domain_id = get_domain_id();
        if domain_id > 0 {
            info!("Coordinator using domain ID {}", domain_id);
        }

        let session = crate::network::open_zenoh_session(crate::network::NetworkRole::Coordinator)?;
        let session = std::sync::Arc::new(session);

        let (clients_tx, _clients_rx) = tokio::sync::broadcast::channel::<ShipHandle>(64);
        let clients_tx_inner = clients_tx.clone();

        let join_key = format!("minot/{}/coord/join", domain_id);

        let session_clone = std::sync::Arc::clone(&session);
        let clwa = std::sync::Arc::clone(&clients_wait_for_ack);
        let rat_lock = std::sync::Arc::new(std::sync::Mutex::new(HashSet::new()));
        let subscriber = session
            .declare_subscriber(join_key.clone())
            .wait()
            .map_err(|e| anyhow::anyhow!("Failed to create coordinator join subscriber: {e}"))?;

        tokio::spawn(async move {
            info!("Sea coordinator listening on {}", join_key);
            let mut client_transport_tasks =
                std::collections::HashMap::<ShipKind, Vec<tokio::task::JoinHandle<()>>>::new();

            loop {
                let sample = subscriber.recv_async().await;
                let sample = match sample {
                    Ok(s) => s,
                    Err(e) => {
                        error!("Error receiving join request: {}", e);
                        continue;
                    }
                };

                let payload = sample.payload().to_bytes();
                let aligned = align_bytes(&payload);
                let packet: Packet = match from_bytes::<Packet, rancor::Error>(&aligned) {
                    Ok(p) => p,
                    Err(e) => {
                        error!("Failed to deserialize join request: {}", e);
                        continue;
                    }
                };

                if let PacketKind::JoinRequest {
                    kind: ship_kind,
                    remove_rules_on_disconnect,
                    domain_id: client_domain_id,
                    node_mode,
                    disconnect_timeout_ms,
                    presence,
                } = packet.data
                {
                    if client_domain_id != domain_id {
                        debug!(
                            "Rejecting join request from domain {} (coordinator is domain {})",
                            client_domain_id, domain_id
                        );
                        continue;
                    }

                    let ship_kind = Sea::unpad_ship_kind_name(&ship_kind);
                    debug!("Received JoinRequest: {:?}", ship_kind);

                    {
                        let mut lock = rat_lock.lock().unwrap();
                        if lock.get(&ship_kind).is_some() {
                            // Client is reconnecting. Its old transport tasks
                            // are aborted below so duplicate subscribers and
                            // heartbeat echoers cannot survive a generation.
                            info!("Client {:?} reconnecting, allowing rejoin", ship_kind);
                            lock.remove(&ship_kind);
                        }
                        lock.insert(ship_kind.clone());
                    }
                    if let Some(tasks) = client_transport_tasks.remove(&ship_kind) {
                        for task in tasks {
                            task.abort();
                        }
                    }

                    let generated_id = rand::random::<ShipName>().abs();
                    let (disconnect_tx, _disconnect_rx) =
                        tokio::sync::broadcast::channel::<bool>(1);

                    let ship_name_str = match &ship_kind {
                        ShipKind::Rat(name) => name.clone(),
                        ShipKind::Wind(name) => name.clone(),
                    };
                    let ship_name_key = sanitize_key(&ship_name_str);

                    let (recv_tx, _) = tokio::sync::broadcast::channel::<(
                        Packet,
                        Option<std::net::SocketAddr>,
                    )>(256);
                    let (send_tx, mut send_rx) = tokio::sync::mpsc::channel::<Packet>(256);

                    let client_addr = crate::NetworkShipAddress {
                        ip: [0, 0, 0, 0],
                        port: 0,
                        ship: generated_id,
                        kind: ship_kind.clone(),
                        node_mode,
                    };

                    let coord_to_client_key =
                        format!("minot/{}/coord/clients/{}", domain_id, ship_name_key);
                    let client_to_coord_key =
                        format!("minot/{}/clients/{}/coord", domain_id, ship_name_key);
                    let heartbeat_to_coord_key = client_heartbeat_key(domain_id, &ship_name_key);

                    let client_subscriber = session_clone
                        .declare_subscriber(client_to_coord_key)
                        .wait()
                        .expect("Failed to create subscriber for client");

                    let recv_tx_clone = recv_tx.clone();
                    let heartbeat_recv_tx = recv_tx.clone();
                    let ships_lock = std::sync::Arc::clone(&rat_lock);
                    let ship_kind_for_disconnect = ship_kind.clone();

                    let receive_task = tokio::spawn(async move {
                        loop {
                            match client_subscriber.recv_async().await {
                                Ok(sample) => {
                                    let payload = sample.payload().to_bytes();
                                    let aligned = align_bytes(&payload);
                                    match from_bytes::<Packet, rancor::Error>(&aligned) {
                                        Ok(packet) => {
                                            // A broadcast send fails while nothing
                                            // is subscribed. That is normal here:
                                            // this task starts as soon as Join
                                            // packets can arrive, before the
                                            // ShipHandle consumer subscribes.
                                            if let Err(e) = recv_tx_clone.send((packet, None)) {
                                                debug!(
                                                    "Dropping packet from {:?}: no receiver yet ({})",
                                                    ship_kind_for_disconnect, e
                                                );
                                            }
                                        }
                                        Err(e) => {
                                            error!("Failed to deserialize client packet: {}", e);
                                        }
                                    }
                                }
                                Err(e) => {
                                    warn!(
                                        "Client {:?} disconnected: {}",
                                        ship_kind_for_disconnect, e
                                    );
                                    let mut lock = ships_lock.lock().unwrap();
                                    lock.remove(&ship_kind_for_disconnect);
                                    break;
                                }
                            }
                        }
                    });

                    // A dedicated high-priority control path keeps liveness
                    // independent of wind/data publisher queues and range
                    // query congestion. Heartbeat echoes use their own
                    // publisher but the normal coordinator-to-client key, so
                    // the client's existing connection watcher sees them.
                    let heartbeat_subscriber = session_clone
                        .declare_subscriber(heartbeat_to_coord_key)
                        .wait()
                        .expect("Failed to create client heartbeat subscriber");
                    let heartbeat_echo_publisher = session_clone
                        .declare_publisher(coord_to_client_key.clone())
                        .priority(zenoh::qos::Priority::RealTime)
                        .congestion_control(zenoh::qos::CongestionControl::Drop)
                        .reliability(zenoh::qos::Reliability::Reliable)
                        .wait()
                        .expect("Failed to create heartbeat echo publisher");
                    let heartbeat_task = tokio::spawn(async move {
                        let heartbeat_packet = Packet {
                            header: Header::default(),
                            data: PacketKind::Heartbeat,
                        };
                        let heartbeat_bytes =
                            rkyv::api::high::to_bytes::<rancor::Error>(&heartbeat_packet)
                                .expect("Failed to serialize heartbeat");
                        while heartbeat_subscriber.recv_async().await.is_ok() {
                            let _ = heartbeat_recv_tx.send((heartbeat_packet.clone(), None));
                            if let Err(error) =
                                heartbeat_echo_publisher.put(&*heartbeat_bytes).wait()
                            {
                                debug!("Failed to echo dedicated heartbeat: {error}");
                            }
                        }
                    });

                    // Declared before the send task is spawned, so it is ready
                    // for the welcome below.
                    debug!("Creating coordinator publisher for {}", coord_to_client_key);
                    let coord_to_client_key_owned = coord_to_client_key.clone();
                    let publisher = session_clone
                        .declare_publisher(coord_to_client_key_owned)
                        .congestion_control(node_mode.congestion_control())
                        .reliability(node_mode.reliability())
                        .wait()
                        .expect("Failed to create publisher for client");

                    let current_wait_for_ack = { *clwa.read().unwrap() };
                    let welcome_packet = Packet {
                        header: Header {
                            source: CONTROLLER_CLIENT_ID,
                            target: generated_id,
                        },
                        data: PacketKind::Welcome {
                            addr: client_addr.clone(),
                            wait_for_ack: current_wait_for_ack,
                            presence: crate::presence::Presence::current(),
                        },
                    };

                    let bytes = rkyv::api::high::to_bytes::<rancor::Error>(&welcome_packet)
                        .expect("Failed to serialize welcome packet");
                    if let Err(e) = publisher.put(&*bytes).wait() {
                        error!("Failed to send welcome packet: {}", e);
                        receive_task.abort();
                        heartbeat_task.abort();
                        continue;
                    }

                    debug!("Welcome packet sent to {}", coord_to_client_key);

                    let send_task = tokio::spawn(async move {
                        while let Some(packet) = send_rx.recv().await {
                            let bytes = rkyv::api::high::to_bytes::<rancor::Error>(&packet)
                                .expect("Failed to serialize packet");
                            if let Err(e) = publisher.put(&*bytes).wait() {
                                error!("Failed to send to client: {}", e);
                                break;
                            }
                        }
                    });

                    let ship_kind_for_tasks = ship_kind.clone();
                    let ship_handle = ShipHandle {
                        ship: generated_id,
                        disconnect: disconnect_tx,
                        recv: recv_tx,
                        send: send_tx,
                        name: ship_kind,
                        addr_from_coord: client_addr,
                        remove_rules_on_disconnect,
                        node_mode,
                        disconnect_timeout_ms,
                        presence,
                    };

                    if let Err(e) = clients_tx_inner.send(ship_handle) {
                        error!("Failed to broadcast new client: {}", e);
                    }
                    client_transport_tasks.insert(
                        ship_kind_for_tasks,
                        vec![receive_task, heartbeat_task, send_task],
                    );
                    debug!("ShipHandle created and sent");
                }
            }
        });

        Ok(Self {
            network_clients_chan: clients_tx,
            session,
            domain_id,
        })
    }

    pub fn pad_string(input: &str) -> String {
        if input.len() >= 64 {
            return input.to_string();
        }
        let padding_count = 64 - input.len();
        let padding = "#".repeat(padding_count);
        format!("{}{}", input, padding)
    }

    pub fn reverse_padding(input: &str) -> String {
        let trimmed: &str = input.trim_end_matches('#');
        trimmed.to_string()
    }

    pub fn pad_ship_kind_name(kind: &ShipKind) -> ShipKind {
        match kind {
            ShipKind::Rat(name) => ShipKind::Rat(Self::pad_string(name)),
            ShipKind::Wind(name) => ShipKind::Wind(Self::pad_string(name)),
        }
    }

    pub fn unpad_ship_kind_name(kind: &ShipKind) -> ShipKind {
        match kind {
            ShipKind::Rat(name) => ShipKind::Rat(Self::reverse_padding(name)),
            ShipKind::Wind(name) => ShipKind::Wind(Self::reverse_padding(name)),
        }
    }

    pub async fn cleanup(&mut self) {
        info!("Sea coordinator shutting down");
    }
}