1use std::collections::HashSet;
2
3use log::{debug, error, info, warn};
4use nalgebra::DMatrix;
5
6use rkyv::{Archive, Deserialize, Serialize, api::high::from_bytes, rancor, util::AlignedVec};
7use zenoh::Wait;
8
9use crate::{Action, ShipKind, ShipName, VariableHuman, WindData};
10
11pub const PROTO_IDENTIFIER: u8 = 69;
12pub const CONTROLLER_CLIENT_ID: ShipName = 0;
13
14pub(crate) fn client_heartbeat_key(domain_id: u16, sanitized_ship_name: &str) -> String {
15 format!(
16 "minot/{}/heartbeat/clients/{}/coord",
17 domain_id, sanitized_ship_name
18 )
19}
20
21fn align_bytes(bytes: &[u8]) -> AlignedVec {
23 let mut aligned = AlignedVec::with_capacity(bytes.len());
24 aligned.extend_from_slice(bytes);
25 aligned
26}
27
28pub fn sanitize_key(name: &str) -> String {
31 name.replace('#', "_hash_").replace('?', "_qmark_")
32}
33
34pub fn get_domain_id() -> u16 {
35 let val = std::env::var("MINOT_DOMAIN_ID")
36 .ok()
37 .unwrap_or("0".to_owned());
38 let parsed = val.parse::<u16>().ok();
39 match parsed {
40 Some(parsed) => parsed,
41 None => {
42 warn!("Invalid MINOT_DOMAIN_ID, selecting default 0");
43 0
44 }
45 }
46}
47
48#[derive(Archive, Serialize, Deserialize, Clone, Debug)]
49pub struct WindAt {
50 pub data: WindData,
51 pub at_var: Option<String>,
52}
53
54#[derive(Archive, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
56pub struct NetArray<T: nalgebra::Scalar> {
57 cols: usize,
58 data: Vec<T>,
59 rows: usize,
60}
61
62impl<T: nalgebra::Scalar> From<DMatrix<T>> for NetArray<T> {
63 fn from(value: DMatrix<T>) -> Self {
64 Self {
65 rows: value.nrows(),
66 cols: value.ncols(),
67 data: value.data.into(),
68 }
69 }
70}
71
72impl<T: nalgebra::Scalar> From<NetArray<T>> for DMatrix<T> {
73 fn from(value: NetArray<T>) -> Self {
74 Self::from_data(nalgebra::VecStorage::new(
75 nalgebra::Dyn(value.rows),
76 nalgebra::Dyn(value.cols),
77 value.data,
78 ))
79 }
80}
81
82#[derive(Serialize, Deserialize, Archive, Clone, Copy, Debug, Default, PartialEq, Eq)]
84pub enum Reliability {
85 #[default]
86 Reliable,
87 TryReliable,
88 BestEffort,
89}
90
91#[derive(Serialize, Deserialize, Archive, Clone, Copy, Debug, Default, PartialEq, Eq)]
93pub enum Durability {
94 #[default]
95 Volatile,
96 TransientLocal,
97}
98
99#[derive(Serialize, Deserialize, Archive, Clone, Copy, Debug, Default, PartialEq, Eq)]
101pub struct Qos {
102 reliability: Reliability,
103 durability: Durability,
104}
105
106#[allow(non_upper_case_globals)]
107impl Qos {
108 pub const Reliable: Self = Self::new(Reliability::Reliable, Durability::Volatile);
109 pub const TryReliable: Self = Self::new(Reliability::TryReliable, Durability::Volatile);
110 pub const BestEffort: Self = Self::new(Reliability::BestEffort, Durability::Volatile);
111
112 pub const fn new(reliability: Reliability, durability: Durability) -> Self {
113 Self {
114 reliability,
115 durability,
116 }
117 }
118
119 pub const fn reliability_mode(self) -> Reliability {
120 self.reliability
121 }
122
123 pub const fn durability(self) -> Durability {
124 self.durability
125 }
126
127 pub fn reliability(self) -> zenoh::qos::Reliability {
128 match self.reliability {
129 Reliability::Reliable | Reliability::TryReliable => zenoh::qos::Reliability::Reliable,
130 Reliability::BestEffort => zenoh::qos::Reliability::BestEffort,
131 }
132 }
133
134 pub fn congestion_control(self) -> zenoh::qos::CongestionControl {
137 match self.reliability {
138 Reliability::Reliable => zenoh::qos::CongestionControl::Block,
139 Reliability::TryReliable => zenoh::qos::CongestionControl::BlockFirst,
140 Reliability::BestEffort => zenoh::qos::CongestionControl::Drop,
141 }
142 }
143
144 pub fn is_monitored(self) -> bool {
145 self.reliability == Reliability::Reliable
146 }
147
148 pub fn fires_torpedo(self) -> bool {
149 self.reliability == Reliability::Reliable
150 }
151
152 pub fn removes_rules_on_exit(self) -> bool {
153 self.reliability == Reliability::Reliable
154 }
155
156 pub fn expects_reliable_delivery(self) -> bool {
157 self.reliability != Reliability::BestEffort
158 }
159
160 pub const fn transient_local(mut self) -> Self {
161 self.durability = Durability::TransientLocal;
162 self
163 }
164
165 pub const fn is_transient_local(self) -> bool {
166 matches!(self.durability, Durability::TransientLocal)
167 }
168}
169
170#[cfg(test)]
171mod qos_tests {
172 use super::{Durability, Qos, Reliability};
173
174 #[test]
175 fn transient_local_is_an_optional_modifier() {
176 assert_eq!(Qos::default().durability(), Durability::Volatile);
177
178 for reliability in [
179 Reliability::Reliable,
180 Reliability::TryReliable,
181 Reliability::BestEffort,
182 ] {
183 let qos = Qos::new(reliability, Durability::Volatile).transient_local();
184 assert_eq!(qos.reliability_mode(), reliability);
185 assert_eq!(qos.durability(), Durability::TransientLocal);
186 }
187 }
188}
189
190#[derive(Serialize, Deserialize, Archive, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
191pub enum RatPubRegisterKind {
192 Publish,
193 Subscribe,
194 Scope,
195}
196
197#[derive(Serialize, Deserialize, Archive, Clone, Debug)]
198pub enum PacketKind {
199 Acknowledge,
200 Retry,
201 RequestVarSend(String),
202 JoinRequest {
203 kind: ShipKind,
204 remove_rules_on_disconnect: bool,
205 domain_id: u16,
206 node_mode: Qos,
207 disconnect_timeout_ms: u64,
211 },
212 Welcome {
213 addr: crate::NetworkShipAddress,
214 wait_for_ack: bool,
215 },
216 Heartbeat,
217 Disconnect,
218 RuleAppend {
219 variable: String,
220 commands: Vec<VariableHuman>,
221 },
222 RulesClear,
223 LockNext {
224 unlock_first: bool,
225 },
226 Unlock,
227 RawDataf64(NetArray<f64>),
228 RawDataf32(NetArray<f32>),
229 RawDatai32(NetArray<i32>),
230 RawDatau8(NetArray<u8>),
231 VariableTaskRequest(String),
232 RatAction {
233 variable: String,
234 action: Action,
235 lock_until_ack: bool,
236 },
237 Wind(Vec<WindAt>),
238 WindDynamic(String),
239 RegisterShipAtVar {
240 ship: String,
241 var: String,
242 kind: RatPubRegisterKind,
243 node_mode: Qos,
244 },
245 UnregisterShipAtVar {
248 ship: String,
249 var: String,
250 kind: RatPubRegisterKind,
251 },
252 RegistrationError(String),
253 Sonar,
254 Torpedo(Vec<String>),
255 ClientsHash {
256 reliable: HashSet<String>,
257 best_effort: HashSet<String>,
258 },
259 PeerDead {
260 ship: String,
261 },
262}
263
264#[derive(Archive, Serialize, Deserialize, Copy, Clone, Debug, Default)]
265pub struct Header {
266 pub source: ShipName,
267 pub target: ShipName,
268}
269
270#[derive(Archive, Serialize, Deserialize, Clone, Debug)]
271pub struct Packet {
272 pub header: Header,
273 pub data: PacketKind,
274}
275
276#[derive(Clone, Debug)]
277pub struct ShipHandle {
278 pub name: ShipKind,
279 pub addr_from_coord: crate::NetworkShipAddress,
280 pub ship: ShipName,
281 pub disconnect: tokio::sync::broadcast::Sender<bool>,
282 pub recv: tokio::sync::broadcast::Sender<(Packet, Option<std::net::SocketAddr>)>,
283 pub send: tokio::sync::mpsc::Sender<Packet>,
284 pub remove_rules_on_disconnect: bool,
285 pub node_mode: Qos,
286 pub disconnect_timeout_ms: u64,
288}
289
290#[derive(Debug)]
292pub struct Sea {
293 pub network_clients_chan: tokio::sync::broadcast::Sender<ShipHandle>,
294 #[allow(dead_code)]
295 session: std::sync::Arc<zenoh::Session>,
296 #[allow(dead_code)]
297 domain_id: u16,
298}
299
300impl Sea {
301 pub async fn init(
302 _external_ip: Option<[u8; 4]>,
303 clients_wait_for_ack: std::sync::Arc<std::sync::RwLock<bool>>,
304 ) -> anyhow::Result<Self> {
305 let domain_id = get_domain_id();
306 if domain_id > 0 {
307 info!("Coordinator using domain ID {}", domain_id);
308 }
309
310 let session = crate::network::open_zenoh_session(crate::network::NetworkRole::Coordinator)?;
311 let session = std::sync::Arc::new(session);
312
313 let (clients_tx, _clients_rx) = tokio::sync::broadcast::channel::<ShipHandle>(64);
314 let clients_tx_inner = clients_tx.clone();
315
316 let join_key = format!("minot/{}/coord/join", domain_id);
317
318 let session_clone = std::sync::Arc::clone(&session);
319 let clwa = std::sync::Arc::clone(&clients_wait_for_ack);
320 let rat_lock = std::sync::Arc::new(std::sync::Mutex::new(HashSet::new()));
321 let subscriber = session
322 .declare_subscriber(join_key.clone())
323 .wait()
324 .map_err(|e| anyhow::anyhow!("Failed to create coordinator join subscriber: {e}"))?;
325
326 tokio::spawn(async move {
327 info!("Sea coordinator listening on {}", join_key);
328 let mut client_transport_tasks =
329 std::collections::HashMap::<ShipKind, Vec<tokio::task::JoinHandle<()>>>::new();
330
331 loop {
332 let sample = subscriber.recv_async().await;
333 let sample = match sample {
334 Ok(s) => s,
335 Err(e) => {
336 error!("Error receiving join request: {}", e);
337 continue;
338 }
339 };
340
341 let payload = sample.payload().to_bytes();
342 let aligned = align_bytes(&payload);
343 let packet: Packet = match from_bytes::<Packet, rancor::Error>(&aligned) {
344 Ok(p) => p,
345 Err(e) => {
346 error!("Failed to deserialize join request: {}", e);
347 continue;
348 }
349 };
350
351 if let PacketKind::JoinRequest {
352 kind: ship_kind,
353 remove_rules_on_disconnect,
354 domain_id: client_domain_id,
355 node_mode,
356 disconnect_timeout_ms,
357 } = packet.data
358 {
359 if client_domain_id != domain_id {
360 debug!(
361 "Rejecting join request from domain {} (coordinator is domain {})",
362 client_domain_id, domain_id
363 );
364 continue;
365 }
366
367 let ship_kind = Sea::unpad_ship_kind_name(&ship_kind);
368 debug!("Received JoinRequest: {:?}", ship_kind);
369
370 {
371 let mut lock = rat_lock.lock().unwrap();
372 if lock.get(&ship_kind).is_some() {
373 info!("Client {:?} reconnecting, allowing rejoin", ship_kind);
377 lock.remove(&ship_kind);
378 }
379 lock.insert(ship_kind.clone());
380 }
381 if let Some(tasks) = client_transport_tasks.remove(&ship_kind) {
382 for task in tasks {
383 task.abort();
384 }
385 }
386
387 let generated_id = rand::random::<ShipName>().abs();
388 let (disconnect_tx, _disconnect_rx) =
389 tokio::sync::broadcast::channel::<bool>(1);
390
391 let ship_name_str = match &ship_kind {
392 ShipKind::Rat(name) => name.clone(),
393 ShipKind::Wind(name) => name.clone(),
394 };
395 let ship_name_key = sanitize_key(&ship_name_str);
396
397 let (recv_tx, _) = tokio::sync::broadcast::channel::<(
398 Packet,
399 Option<std::net::SocketAddr>,
400 )>(256);
401 let (send_tx, mut send_rx) = tokio::sync::mpsc::channel::<Packet>(256);
402
403 let client_addr = crate::NetworkShipAddress {
404 ip: [0, 0, 0, 0],
405 port: 0,
406 ship: generated_id,
407 kind: ship_kind.clone(),
408 node_mode,
409 };
410
411 let coord_to_client_key =
412 format!("minot/{}/coord/clients/{}", domain_id, ship_name_key);
413 let client_to_coord_key =
414 format!("minot/{}/clients/{}/coord", domain_id, ship_name_key);
415 let heartbeat_to_coord_key = client_heartbeat_key(domain_id, &ship_name_key);
416
417 let client_subscriber = session_clone
418 .declare_subscriber(client_to_coord_key)
419 .wait()
420 .expect("Failed to create subscriber for client");
421
422 let recv_tx_clone = recv_tx.clone();
423 let heartbeat_recv_tx = recv_tx.clone();
424 let ships_lock = std::sync::Arc::clone(&rat_lock);
425 let ship_kind_for_disconnect = ship_kind.clone();
426
427 let receive_task = tokio::spawn(async move {
428 loop {
429 match client_subscriber.recv_async().await {
430 Ok(sample) => {
431 let payload = sample.payload().to_bytes();
432 let aligned = align_bytes(&payload);
433 match from_bytes::<Packet, rancor::Error>(&aligned) {
434 Ok(packet) => {
435 if let Err(e) = recv_tx_clone.send((packet, None)) {
441 debug!(
442 "Dropping packet from {:?}: no receiver yet ({})",
443 ship_kind_for_disconnect, e
444 );
445 }
446 }
447 Err(e) => {
448 error!("Failed to deserialize client packet: {}", e);
449 }
450 }
451 }
452 Err(e) => {
453 warn!(
454 "Client {:?} disconnected: {}",
455 ship_kind_for_disconnect, e
456 );
457 let mut lock = ships_lock.lock().unwrap();
458 lock.remove(&ship_kind_for_disconnect);
459 break;
460 }
461 }
462 }
463 });
464
465 let heartbeat_subscriber = session_clone
471 .declare_subscriber(heartbeat_to_coord_key)
472 .wait()
473 .expect("Failed to create client heartbeat subscriber");
474 let heartbeat_echo_publisher = session_clone
475 .declare_publisher(coord_to_client_key.clone())
476 .priority(zenoh::qos::Priority::RealTime)
477 .congestion_control(zenoh::qos::CongestionControl::Drop)
478 .reliability(zenoh::qos::Reliability::Reliable)
479 .wait()
480 .expect("Failed to create heartbeat echo publisher");
481 let heartbeat_task = tokio::spawn(async move {
482 let heartbeat_packet = Packet {
483 header: Header::default(),
484 data: PacketKind::Heartbeat,
485 };
486 let heartbeat_bytes =
487 rkyv::api::high::to_bytes::<rancor::Error>(&heartbeat_packet)
488 .expect("Failed to serialize heartbeat");
489 while heartbeat_subscriber.recv_async().await.is_ok() {
490 let _ = heartbeat_recv_tx.send((heartbeat_packet.clone(), None));
491 if let Err(error) =
492 heartbeat_echo_publisher.put(&*heartbeat_bytes).wait()
493 {
494 debug!("Failed to echo dedicated heartbeat: {error}");
495 }
496 }
497 });
498
499 debug!("Creating coordinator publisher for {}", coord_to_client_key);
502 let coord_to_client_key_owned = coord_to_client_key.clone();
503 let publisher = session_clone
504 .declare_publisher(coord_to_client_key_owned)
505 .congestion_control(node_mode.congestion_control())
506 .reliability(node_mode.reliability())
507 .wait()
508 .expect("Failed to create publisher for client");
509
510 let current_wait_for_ack = { *clwa.read().unwrap() };
511 let welcome_packet = Packet {
512 header: Header {
513 source: CONTROLLER_CLIENT_ID,
514 target: generated_id,
515 },
516 data: PacketKind::Welcome {
517 addr: client_addr.clone(),
518 wait_for_ack: current_wait_for_ack,
519 },
520 };
521
522 let bytes = rkyv::api::high::to_bytes::<rancor::Error>(&welcome_packet)
523 .expect("Failed to serialize welcome packet");
524 if let Err(e) = publisher.put(&*bytes).wait() {
525 error!("Failed to send welcome packet: {}", e);
526 receive_task.abort();
527 heartbeat_task.abort();
528 continue;
529 }
530
531 debug!("Welcome packet sent to {}", coord_to_client_key);
532
533 let send_task = tokio::spawn(async move {
534 while let Some(packet) = send_rx.recv().await {
535 let bytes = rkyv::api::high::to_bytes::<rancor::Error>(&packet)
536 .expect("Failed to serialize packet");
537 if let Err(e) = publisher.put(&*bytes).wait() {
538 error!("Failed to send to client: {}", e);
539 break;
540 }
541 }
542 });
543
544 let ship_kind_for_tasks = ship_kind.clone();
545 let ship_handle = ShipHandle {
546 ship: generated_id,
547 disconnect: disconnect_tx,
548 recv: recv_tx,
549 send: send_tx,
550 name: ship_kind,
551 addr_from_coord: client_addr,
552 remove_rules_on_disconnect,
553 node_mode,
554 disconnect_timeout_ms,
555 };
556
557 if let Err(e) = clients_tx_inner.send(ship_handle) {
558 error!("Failed to broadcast new client: {}", e);
559 }
560 client_transport_tasks.insert(
561 ship_kind_for_tasks,
562 vec![receive_task, heartbeat_task, send_task],
563 );
564 debug!("ShipHandle created and sent");
565 }
566 }
567 });
568
569 Ok(Self {
570 network_clients_chan: clients_tx,
571 session,
572 domain_id,
573 })
574 }
575
576 pub fn pad_string(input: &str) -> String {
577 if input.len() >= 64 {
578 return input.to_string();
579 }
580 let padding_count = 64 - input.len();
581 let padding = "#".repeat(padding_count);
582 format!("{}{}", input, padding)
583 }
584
585 pub fn reverse_padding(input: &str) -> String {
586 let trimmed: &str = input.trim_end_matches('#');
587 trimmed.to_string()
588 }
589
590 pub fn pad_ship_kind_name(kind: &ShipKind) -> ShipKind {
591 match kind {
592 ShipKind::Rat(name) => ShipKind::Rat(Self::pad_string(name)),
593 ShipKind::Wind(name) => ShipKind::Wind(Self::pad_string(name)),
594 }
595 }
596
597 pub fn unpad_ship_kind_name(kind: &ShipKind) -> ShipKind {
598 match kind {
599 ShipKind::Rat(name) => ShipKind::Rat(Self::reverse_padding(name)),
600 ShipKind::Wind(name) => ShipKind::Wind(Self::reverse_padding(name)),
601 }
602 }
603
604 pub async fn cleanup(&mut self) {
605 info!("Sea coordinator shutting down");
606 }
607}