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#[derive(Serialize, Deserialize, Archive, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
171pub enum RatPubRegisterKind {
172 Publish,
173 Subscribe,
174 Scope,
175}
176
177#[derive(Serialize, Deserialize, Archive, Clone, Debug)]
178pub enum PacketKind {
179 Acknowledge,
180 Retry,
181 RequestVarSend(String),
182 JoinRequest {
183 kind: ShipKind,
184 remove_rules_on_disconnect: bool,
185 domain_id: u16,
186 node_mode: Qos,
187 disconnect_timeout_ms: u64,
191 presence: crate::presence::Presence,
194 },
195 Welcome {
196 addr: crate::NetworkShipAddress,
197 wait_for_ack: bool,
198 presence: crate::presence::Presence,
200 },
201 Heartbeat,
202 Disconnect,
203 RuleAppend {
204 variable: String,
205 commands: Vec<VariableHuman>,
206 },
207 RulesClear,
208 LockNext {
209 unlock_first: bool,
210 },
211 Unlock,
212 RawDataf64(NetArray<f64>),
213 RawDataf32(NetArray<f32>),
214 RawDatai32(NetArray<i32>),
215 RawDatau8(NetArray<u8>),
216 VariableTaskRequest(String),
217 RatAction {
218 variable: String,
219 action: Action,
220 lock_until_ack: bool,
221 },
222 Wind(Vec<WindAt>),
223 WindDynamic(String),
224 RegisterShipAtVar {
225 ship: String,
226 var: String,
227 kind: RatPubRegisterKind,
228 node_mode: Qos,
229 },
230 UnregisterShipAtVar {
233 ship: String,
234 var: String,
235 kind: RatPubRegisterKind,
236 },
237 RegistrationError(String),
238 Sonar,
239 Torpedo(Vec<String>),
240 ClientsHash {
241 reliable: HashSet<String>,
242 best_effort: HashSet<String>,
243 },
244 PeerDead {
245 ship: String,
246 },
247}
248
249#[derive(Archive, Serialize, Deserialize, Copy, Clone, Debug, Default)]
250pub struct Header {
251 pub source: ShipName,
252 pub target: ShipName,
253}
254
255#[derive(Archive, Serialize, Deserialize, Clone, Debug)]
256pub struct Packet {
257 pub header: Header,
258 pub data: PacketKind,
259}
260
261#[derive(Clone, Debug)]
262pub struct ShipHandle {
263 pub name: ShipKind,
264 pub addr_from_coord: crate::NetworkShipAddress,
265 pub ship: ShipName,
266 pub disconnect: tokio::sync::broadcast::Sender<bool>,
267 pub recv: tokio::sync::broadcast::Sender<(Packet, Option<std::net::SocketAddr>)>,
268 pub send: tokio::sync::mpsc::Sender<Packet>,
269 pub remove_rules_on_disconnect: bool,
270 pub node_mode: Qos,
271 pub disconnect_timeout_ms: u64,
273 pub presence: crate::presence::Presence,
275}
276
277#[derive(Debug)]
279pub struct Sea {
280 pub network_clients_chan: tokio::sync::broadcast::Sender<ShipHandle>,
281 #[allow(dead_code)]
282 session: std::sync::Arc<zenoh::Session>,
283 #[allow(dead_code)]
284 domain_id: u16,
285}
286
287impl Sea {
288 pub async fn init(
289 _external_ip: Option<[u8; 4]>,
290 clients_wait_for_ack: std::sync::Arc<std::sync::RwLock<bool>>,
291 ) -> anyhow::Result<Self> {
292 let domain_id = get_domain_id();
293 if domain_id > 0 {
294 info!("Coordinator using domain ID {}", domain_id);
295 }
296
297 let session = crate::network::open_zenoh_session(crate::network::NetworkRole::Coordinator)?;
298 let session = std::sync::Arc::new(session);
299
300 let (clients_tx, _clients_rx) = tokio::sync::broadcast::channel::<ShipHandle>(64);
301 let clients_tx_inner = clients_tx.clone();
302
303 let join_key = format!("minot/{}/coord/join", domain_id);
304
305 let session_clone = std::sync::Arc::clone(&session);
306 let clwa = std::sync::Arc::clone(&clients_wait_for_ack);
307 let rat_lock = std::sync::Arc::new(std::sync::Mutex::new(HashSet::new()));
308 let subscriber = session
309 .declare_subscriber(join_key.clone())
310 .wait()
311 .map_err(|e| anyhow::anyhow!("Failed to create coordinator join subscriber: {e}"))?;
312
313 tokio::spawn(async move {
314 info!("Sea coordinator listening on {}", join_key);
315 let mut client_transport_tasks =
316 std::collections::HashMap::<ShipKind, Vec<tokio::task::JoinHandle<()>>>::new();
317
318 loop {
319 let sample = subscriber.recv_async().await;
320 let sample = match sample {
321 Ok(s) => s,
322 Err(e) => {
323 error!("Error receiving join request: {}", e);
324 continue;
325 }
326 };
327
328 let payload = sample.payload().to_bytes();
329 let aligned = align_bytes(&payload);
330 let packet: Packet = match from_bytes::<Packet, rancor::Error>(&aligned) {
331 Ok(p) => p,
332 Err(e) => {
333 error!("Failed to deserialize join request: {}", e);
334 continue;
335 }
336 };
337
338 if let PacketKind::JoinRequest {
339 kind: ship_kind,
340 remove_rules_on_disconnect,
341 domain_id: client_domain_id,
342 node_mode,
343 disconnect_timeout_ms,
344 presence,
345 } = packet.data
346 {
347 if client_domain_id != domain_id {
348 debug!(
349 "Rejecting join request from domain {} (coordinator is domain {})",
350 client_domain_id, domain_id
351 );
352 continue;
353 }
354
355 let ship_kind = Sea::unpad_ship_kind_name(&ship_kind);
356 debug!("Received JoinRequest: {:?}", ship_kind);
357
358 {
359 let mut lock = rat_lock.lock().unwrap();
360 if lock.get(&ship_kind).is_some() {
361 info!("Client {:?} reconnecting, allowing rejoin", ship_kind);
365 lock.remove(&ship_kind);
366 }
367 lock.insert(ship_kind.clone());
368 }
369 if let Some(tasks) = client_transport_tasks.remove(&ship_kind) {
370 for task in tasks {
371 task.abort();
372 }
373 }
374
375 let generated_id = rand::random::<ShipName>().abs();
376 let (disconnect_tx, _disconnect_rx) =
377 tokio::sync::broadcast::channel::<bool>(1);
378
379 let ship_name_str = match &ship_kind {
380 ShipKind::Rat(name) => name.clone(),
381 ShipKind::Wind(name) => name.clone(),
382 };
383 let ship_name_key = sanitize_key(&ship_name_str);
384
385 let (recv_tx, _) = tokio::sync::broadcast::channel::<(
386 Packet,
387 Option<std::net::SocketAddr>,
388 )>(256);
389 let (send_tx, mut send_rx) = tokio::sync::mpsc::channel::<Packet>(256);
390
391 let client_addr = crate::NetworkShipAddress {
392 ip: [0, 0, 0, 0],
393 port: 0,
394 ship: generated_id,
395 kind: ship_kind.clone(),
396 node_mode,
397 };
398
399 let coord_to_client_key =
400 format!("minot/{}/coord/clients/{}", domain_id, ship_name_key);
401 let client_to_coord_key =
402 format!("minot/{}/clients/{}/coord", domain_id, ship_name_key);
403 let heartbeat_to_coord_key = client_heartbeat_key(domain_id, &ship_name_key);
404
405 let client_subscriber = session_clone
406 .declare_subscriber(client_to_coord_key)
407 .wait()
408 .expect("Failed to create subscriber for client");
409
410 let recv_tx_clone = recv_tx.clone();
411 let heartbeat_recv_tx = recv_tx.clone();
412 let ships_lock = std::sync::Arc::clone(&rat_lock);
413 let ship_kind_for_disconnect = ship_kind.clone();
414
415 let receive_task = tokio::spawn(async move {
416 loop {
417 match client_subscriber.recv_async().await {
418 Ok(sample) => {
419 let payload = sample.payload().to_bytes();
420 let aligned = align_bytes(&payload);
421 match from_bytes::<Packet, rancor::Error>(&aligned) {
422 Ok(packet) => {
423 if let Err(e) = recv_tx_clone.send((packet, None)) {
429 debug!(
430 "Dropping packet from {:?}: no receiver yet ({})",
431 ship_kind_for_disconnect, e
432 );
433 }
434 }
435 Err(e) => {
436 error!("Failed to deserialize client packet: {}", e);
437 }
438 }
439 }
440 Err(e) => {
441 warn!(
442 "Client {:?} disconnected: {}",
443 ship_kind_for_disconnect, e
444 );
445 let mut lock = ships_lock.lock().unwrap();
446 lock.remove(&ship_kind_for_disconnect);
447 break;
448 }
449 }
450 }
451 });
452
453 let heartbeat_subscriber = session_clone
459 .declare_subscriber(heartbeat_to_coord_key)
460 .wait()
461 .expect("Failed to create client heartbeat subscriber");
462 let heartbeat_echo_publisher = session_clone
463 .declare_publisher(coord_to_client_key.clone())
464 .priority(zenoh::qos::Priority::RealTime)
465 .congestion_control(zenoh::qos::CongestionControl::Drop)
466 .reliability(zenoh::qos::Reliability::Reliable)
467 .wait()
468 .expect("Failed to create heartbeat echo publisher");
469 let heartbeat_task = tokio::spawn(async move {
470 let heartbeat_packet = Packet {
471 header: Header::default(),
472 data: PacketKind::Heartbeat,
473 };
474 let heartbeat_bytes =
475 rkyv::api::high::to_bytes::<rancor::Error>(&heartbeat_packet)
476 .expect("Failed to serialize heartbeat");
477 while heartbeat_subscriber.recv_async().await.is_ok() {
478 let _ = heartbeat_recv_tx.send((heartbeat_packet.clone(), None));
479 if let Err(error) =
480 heartbeat_echo_publisher.put(&*heartbeat_bytes).wait()
481 {
482 debug!("Failed to echo dedicated heartbeat: {error}");
483 }
484 }
485 });
486
487 debug!("Creating coordinator publisher for {}", coord_to_client_key);
490 let coord_to_client_key_owned = coord_to_client_key.clone();
491 let publisher = session_clone
492 .declare_publisher(coord_to_client_key_owned)
493 .congestion_control(node_mode.congestion_control())
494 .reliability(node_mode.reliability())
495 .wait()
496 .expect("Failed to create publisher for client");
497
498 let current_wait_for_ack = { *clwa.read().unwrap() };
499 let welcome_packet = Packet {
500 header: Header {
501 source: CONTROLLER_CLIENT_ID,
502 target: generated_id,
503 },
504 data: PacketKind::Welcome {
505 addr: client_addr.clone(),
506 wait_for_ack: current_wait_for_ack,
507 presence: crate::presence::Presence::current(),
508 },
509 };
510
511 let bytes = rkyv::api::high::to_bytes::<rancor::Error>(&welcome_packet)
512 .expect("Failed to serialize welcome packet");
513 if let Err(e) = publisher.put(&*bytes).wait() {
514 error!("Failed to send welcome packet: {}", e);
515 receive_task.abort();
516 heartbeat_task.abort();
517 continue;
518 }
519
520 debug!("Welcome packet sent to {}", coord_to_client_key);
521
522 let send_task = tokio::spawn(async move {
523 while let Some(packet) = send_rx.recv().await {
524 let bytes = rkyv::api::high::to_bytes::<rancor::Error>(&packet)
525 .expect("Failed to serialize packet");
526 if let Err(e) = publisher.put(&*bytes).wait() {
527 error!("Failed to send to client: {}", e);
528 break;
529 }
530 }
531 });
532
533 let ship_kind_for_tasks = ship_kind.clone();
534 let ship_handle = ShipHandle {
535 ship: generated_id,
536 disconnect: disconnect_tx,
537 recv: recv_tx,
538 send: send_tx,
539 name: ship_kind,
540 addr_from_coord: client_addr,
541 remove_rules_on_disconnect,
542 node_mode,
543 disconnect_timeout_ms,
544 presence,
545 };
546
547 if let Err(e) = clients_tx_inner.send(ship_handle) {
548 error!("Failed to broadcast new client: {}", e);
549 }
550 client_transport_tasks.insert(
551 ship_kind_for_tasks,
552 vec![receive_task, heartbeat_task, send_task],
553 );
554 debug!("ShipHandle created and sent");
555 }
556 }
557 });
558
559 Ok(Self {
560 network_clients_chan: clients_tx,
561 session,
562 domain_id,
563 })
564 }
565
566 pub fn pad_string(input: &str) -> String {
567 if input.len() >= 64 {
568 return input.to_string();
569 }
570 let padding_count = 64 - input.len();
571 let padding = "#".repeat(padding_count);
572 format!("{}{}", input, padding)
573 }
574
575 pub fn reverse_padding(input: &str) -> String {
576 let trimmed: &str = input.trim_end_matches('#');
577 trimmed.to_string()
578 }
579
580 pub fn pad_ship_kind_name(kind: &ShipKind) -> ShipKind {
581 match kind {
582 ShipKind::Rat(name) => ShipKind::Rat(Self::pad_string(name)),
583 ShipKind::Wind(name) => ShipKind::Wind(Self::pad_string(name)),
584 }
585 }
586
587 pub fn unpad_ship_kind_name(kind: &ShipKind) -> ShipKind {
588 match kind {
589 ShipKind::Rat(name) => ShipKind::Rat(Self::reverse_padding(name)),
590 ShipKind::Wind(name) => ShipKind::Wind(Self::reverse_padding(name)),
591 }
592 }
593
594 pub async fn cleanup(&mut self) {
595 info!("Sea coordinator shutting down");
596 }
597}