1pub mod client;
2pub mod coordinator;
3pub mod net;
4pub mod network;
5pub mod ship;
6
7pub use net::{Durability, Qos, Reliability};
8
9pub const HEARTBEAT_INTERVAL_MS: u64 = 400;
16
17pub const HEARTBEAT_SUPPRESS_MS: u64 = HEARTBEAT_INTERVAL_MS / 2;
21
22pub const DISCONNECT_TIMEOUT_MS: u64 = HEARTBEAT_INTERVAL_MS * 2; pub const REGISTRATION_TIMEOUT_MS: u64 = 2000;
28
29pub const PEER_DEAD_THRESHOLD: u32 = 3;
31
32#[derive(Debug, Clone, Copy, Default)]
37pub struct NodeOptions {
38 pub timing: Timing,
40 pub reconnect: Option<ReconnectPolicy>,
45 pub bypass_route_cache: bool,
53}
54
55impl NodeOptions {
56 pub fn wan() -> Self {
59 Self {
60 timing: Timing::wan(),
61 reconnect: Some(ReconnectPolicy::always()),
62 bypass_route_cache: false,
63 }
64 }
65
66 pub fn with_route_cache_bypassed(mut self) -> Self {
70 self.bypass_route_cache = true;
71 self
72 }
73
74 pub fn with_timing(mut self, timing: Timing) -> Self {
75 self.timing = timing;
76 self
77 }
78
79 pub fn with_reconnect(mut self, reconnect: ReconnectPolicy) -> Self {
80 self.reconnect = Some(reconnect);
81 self
82 }
83
84 pub fn reconnect_policy(&self, qos: Qos) -> ReconnectPolicy {
86 self.reconnect
87 .unwrap_or_else(|| ReconnectPolicy::for_qos(qos))
88 }
89}
90
91#[derive(Debug)]
102pub struct ConnectionState {
103 generation: std::sync::atomic::AtomicU64,
104 connected: std::sync::atomic::AtomicBool,
105 link_proven: std::sync::atomic::AtomicBool,
106 heartbeating: std::sync::atomic::AtomicBool,
107 announce: tokio::sync::broadcast::Sender<u64>,
109}
110
111impl Default for ConnectionState {
112 fn default() -> Self {
113 Self::new()
114 }
115}
116
117impl ConnectionState {
118 pub fn new() -> Self {
119 let (announce, _) = tokio::sync::broadcast::channel(16);
120 Self {
121 generation: std::sync::atomic::AtomicU64::new(0),
122 connected: std::sync::atomic::AtomicBool::new(true),
123 link_proven: std::sync::atomic::AtomicBool::new(false),
124 heartbeating: std::sync::atomic::AtomicBool::new(false),
125 announce,
126 }
127 }
128
129 pub fn generation(&self) -> u64 {
132 self.generation.load(std::sync::atomic::Ordering::Acquire)
133 }
134
135 pub fn is_connected(&self) -> bool {
137 self.connected.load(std::sync::atomic::Ordering::Acquire)
138 }
139
140 pub fn subscribe(&self) -> tokio::sync::broadcast::Receiver<u64> {
143 self.announce.subscribe()
144 }
145
146 pub fn is_link_proven(&self) -> bool {
153 self.link_proven.load(std::sync::atomic::Ordering::Acquire)
154 }
155
156 pub fn is_heartbeating(&self) -> bool {
162 self.heartbeating.load(std::sync::atomic::Ordering::Acquire)
163 }
164
165 pub(crate) fn mark_heartbeating(&self) {
166 self.heartbeating
167 .store(true, std::sync::atomic::Ordering::Release);
168 }
169
170 pub(crate) fn mark_link_proven(&self) {
171 self.link_proven
172 .store(true, std::sync::atomic::Ordering::Release);
173 }
174
175 pub(crate) fn mark_link_unproven(&self) {
176 self.link_proven
177 .store(false, std::sync::atomic::Ordering::Release);
178 }
179
180 pub(crate) fn mark_disconnected(&self) {
181 self.mark_link_unproven();
182 self.connected
183 .store(false, std::sync::atomic::Ordering::Release);
184 }
185
186 pub(crate) fn mark_reconnected(&self) -> u64 {
188 let generation = self
189 .generation
190 .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
191 + 1;
192 self.connected
193 .store(true, std::sync::atomic::Ordering::Release);
194 let _ = self.announce.send(generation);
196 generation
197 }
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
202pub enum ReconnectPolicy {
203 #[default]
208 Never,
209 Always {
212 initial_backoff_ms: u64,
214 max_backoff_ms: u64,
216 },
217}
218
219impl ReconnectPolicy {
220 pub fn always() -> Self {
222 Self::Always {
223 initial_backoff_ms: 250,
224 max_backoff_ms: 10_000,
225 }
226 }
227
228 pub fn is_enabled(self) -> bool {
229 matches!(self, Self::Always { .. })
230 }
231
232 pub fn for_qos(qos: Qos) -> Self {
238 if qos.fires_torpedo() {
239 Self::Never
240 } else {
241 Self::always()
242 }
243 }
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub struct Timing {
260 pub heartbeat_interval_ms: u64,
262 pub heartbeat_suppress_ms: u64,
264 pub disconnect_timeout_ms: u64,
268 pub registration_timeout_ms: u64,
270 pub peer_dead_threshold: u32,
272}
273
274impl Default for Timing {
275 fn default() -> Self {
276 Self {
277 heartbeat_interval_ms: HEARTBEAT_INTERVAL_MS,
278 heartbeat_suppress_ms: HEARTBEAT_SUPPRESS_MS,
279 disconnect_timeout_ms: DISCONNECT_TIMEOUT_MS,
280 registration_timeout_ms: REGISTRATION_TIMEOUT_MS,
281 peer_dead_threshold: PEER_DEAD_THRESHOLD,
282 }
283 }
284}
285
286impl Timing {
287 pub fn wan() -> Self {
293 Self {
294 heartbeat_interval_ms: 2_000,
295 heartbeat_suppress_ms: 1_000,
296 disconnect_timeout_ms: 10_000,
297 registration_timeout_ms: 15_000,
298 peer_dead_threshold: 3,
299 }
300 }
301
302 pub fn validate(&self) -> anyhow::Result<()> {
307 if self.heartbeat_interval_ms == 0 {
308 anyhow::bail!("Timing::heartbeat_interval_ms must be greater than zero");
309 }
310 if self.heartbeat_suppress_ms > self.heartbeat_interval_ms {
311 anyhow::bail!(
312 "Timing::heartbeat_suppress_ms ({}) must be <= heartbeat_interval_ms ({}), \
313 otherwise a heartbeat can be suppressed past the disconnect timeout",
314 self.heartbeat_suppress_ms,
315 self.heartbeat_interval_ms
316 );
317 }
318 if self.disconnect_timeout_ms <= self.heartbeat_interval_ms + self.heartbeat_suppress_ms {
319 anyhow::bail!(
320 "Timing::disconnect_timeout_ms ({}) must be > heartbeat_interval_ms + \
321 heartbeat_suppress_ms ({}), otherwise healthy nodes are declared dead",
322 self.disconnect_timeout_ms,
323 self.heartbeat_interval_ms + self.heartbeat_suppress_ms
324 );
325 }
326 if self.peer_dead_threshold == 0 {
327 anyhow::bail!("Timing::peer_dead_threshold must be greater than zero");
328 }
329 Ok(())
330 }
331
332 pub fn heartbeat_interval(&self) -> std::time::Duration {
333 std::time::Duration::from_millis(self.heartbeat_interval_ms)
334 }
335
336 pub fn heartbeat_suppress(&self) -> std::time::Duration {
337 std::time::Duration::from_millis(self.heartbeat_suppress_ms)
338 }
339
340 pub fn disconnect_timeout(&self) -> std::time::Duration {
341 std::time::Duration::from_millis(self.disconnect_timeout_ms)
342 }
343
344 pub fn registration_timeout(&self) -> std::time::Duration {
345 std::time::Duration::from_millis(self.registration_timeout_ms)
346 }
347}
348
349pub const TRY_RELIABLE_SEND_BUDGET_MS: u64 = 3000;
353
354pub const TRY_RELIABLE_ATTEMPT_TIMEOUT_MS: u64 = 500;
357
358pub const TRY_RELIABLE_RETRY_BACKOFF_MS: u64 = 50;
361
362pub const COORD_CLIENT_IDLE_TIMEOUT_MS: u64 = 30_000;
366
367use mt_net::{ActionPlan, BagMsg, Rules, VariableHuman};
368
369pub struct ArchivedMessage<T: Archive> {
375 bytes: AlignedVec,
376 _type: std::marker::PhantomData<fn() -> T>,
377}
378
379impl<T> std::fmt::Debug for ArchivedMessage<T>
380where
381 T: Archive,
382{
383 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384 f.debug_struct("ArchivedMessage")
385 .field("len", &self.bytes.len())
386 .finish_non_exhaustive()
387 }
388}
389
390impl<T> ArchivedMessage<T>
391where
392 T: Archive,
393 T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>,
394{
395 pub(crate) fn from_aligned_bytes(bytes: AlignedVec) -> anyhow::Result<Self> {
396 rkyv::access::<T::Archived, rkyv::rancor::Error>(&bytes)
397 .map_err(|error| anyhow::anyhow!("Could not validate archived message: {error}"))?;
398 Ok(Self {
399 bytes,
400 _type: std::marker::PhantomData,
401 })
402 }
403
404 pub fn archived(&self) -> &T::Archived {
406 unsafe { rkyv::access_unchecked::<T::Archived>(&self.bytes) }
409 }
410
411 pub fn as_bytes(&self) -> &[u8] {
412 &self.bytes
413 }
414
415 pub fn len(&self) -> usize {
416 self.bytes.len()
417 }
418
419 pub fn is_empty(&self) -> bool {
420 self.bytes.is_empty()
421 }
422}
423
424impl<T> ArchivedMessage<T>
425where
426 T: Archive,
427 T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
428 + Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>,
429{
430 pub fn deserialize(&self) -> anyhow::Result<T> {
432 let mut pool = Pool::new();
433 self.archived()
434 .deserialize(Strategy::wrap(&mut pool))
435 .map_err(|error| anyhow::anyhow!("Could not deserialize archived message: {error}"))
436 }
437}
438
439pub fn init_logging() {
442 mt_log::init_filtered("Minot", "RUST_LOG", "info", mt_log::QUIET_ZENOH);
443}
444
445use rkyv::{
446 Archive, Deserialize, Serialize,
447 api::high::{HighSerializer, HighValidator},
448 bytecheck::CheckBytes,
449 de::Pool,
450 rancor::Strategy,
451 ser::allocator::ArenaHandle,
452 util::AlignedVec,
453};
454
455#[derive(Debug, Clone, PartialEq, Archive, Serialize, Deserialize, Hash, Eq, PartialOrd, Ord)]
456pub enum ShipKind {
457 Rat(String),
458 Wind(String),
459}
460
461pub type ShipName = i128;
462
463#[derive(Debug, Clone, Serialize, Deserialize, Archive, PartialEq, Eq)]
464pub struct NetworkShipAddress {
465 ip: [u8; 4],
466 pub port: u16,
467 ship: ShipName,
468 pub kind: ShipKind,
469 pub node_mode: net::Qos,
470}
471
472#[derive(Debug, Archive, Clone, Default, Serialize, Deserialize)]
473pub enum Action {
474 #[default]
475 Sail,
476 Shoot {
477 target: Vec<NetworkShipAddress>,
478 id: u32,
479 },
480 Catch {
481 source: NetworkShipAddress,
482 id: u32,
483 },
484}
485
486#[derive(Clone, Debug)]
487pub struct Variable {
488 pub ship: ShipName,
489 pub strategy: Option<Action>,
490}
491
492pub fn get_strategies(
493 haystack: &Rules,
494 rat_ship: &str,
495 variable: String,
496 indirect_parent_rat: Option<&str>,
497) -> Vec<ActionPlan> {
498 match haystack.raw().get(&variable) {
499 None => vec![ActionPlan::default()],
500 Some(plans) => {
501 let directly = plans
503 .iter()
504 .filter(|plan| plan.ship == rat_ship)
505 .filter_map(|el| el.strategy.clone())
506 .collect::<Vec<_>>();
507
508 let mut indirect = plans
510 .iter()
511 .filter(|plan| indirect_parent_rat.is_none_or(|parent_rat| plan.ship == parent_rat))
512 .filter_map(|plan| match plan.strategy.as_ref()? {
513 ActionPlan::Sail => None,
514 ActionPlan::Shoot { target, id } => target
515 .iter()
516 .find(|shoot_target| *shoot_target == rat_ship)
517 .map(|_| ActionPlan::Catch {
518 source: plan.ship.clone(),
519 id: *id,
520 }),
521 ActionPlan::Catch { source, id } => {
522 if source == rat_ship {
523 Some(ActionPlan::Shoot {
524 target: vec![source.clone()],
525 id: *id,
526 })
527 } else {
528 None
529 }
530 }
531 })
532 .collect::<Vec<_>>();
533
534 indirect.extend(directly);
535 indirect
536 }
537 }
538}
539
540#[async_trait::async_trait]
541pub trait Ship: Send + Sync + 'static {
542 async fn ask_for_action(&self, variable_name: &str) -> anyhow::Result<(Action, bool)>;
544
545 async fn wait_for_wind(&self) -> anyhow::Result<Vec<WindData>>;
548
549 fn get_cannon(&self) -> &impl Cannon;
550}
551
552#[derive(Archive, Serialize, Deserialize, Debug, Clone, Copy, Default)]
553pub enum VariableType {
554 #[default]
555 StaticOnly, U8,
557 I32,
558 F32,
559 F64,
560}
561
562impl From<u8> for VariableType {
563 fn from(value: u8) -> Self {
564 match value {
565 1 => Self::U8,
566 2 => Self::I32,
567 3 => Self::F32,
568 4 => Self::F64,
569 _ => Self::default(),
570 }
571 }
572}
573
574impl From<VariableType> for u8 {
575 fn from(value: VariableType) -> Self {
576 match value {
577 VariableType::StaticOnly => 0,
578 VariableType::U8 => 1,
579 VariableType::I32 => 2,
580 VariableType::F32 => 3,
581 VariableType::F64 => 4,
582 }
583 }
584}
585
586use rkyv::rancor::Error as RkyvError;
587
588pub trait Sendable: Sized + Send + Sync + 'static
590where
591 Self: for<'b> Serialize<HighSerializer<AlignedVec, ArenaHandle<'b>, RkyvError>>,
592 Self: Archive<
593 Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
594 + Deserialize<Self, Strategy<Pool, rkyv::rancor::Error>>,
595 >,
596{
597}
598impl<T> Sendable for T
599where
600 T: Sized + Send + Sync + 'static,
601 T: for<'b> Serialize<HighSerializer<AlignedVec, ArenaHandle<'b>, RkyvError>>,
602 T: Archive<
603 Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
604 + Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>,
605 >,
606{
607}
608
609#[async_trait::async_trait]
610pub trait Cannon: Send + Sync + 'static {
611 async fn shoot<'b, T: Sendable>(
615 &self,
616 targets: &'b [crate::NetworkShipAddress],
617 id: u32,
618 data: &T,
619 variable_type: VariableType,
620 variable_name: &str,
621 ) -> anyhow::Result<()>;
622
623 async fn retain<T: Sendable>(
625 &self,
626 data: &T,
627 variable_type: VariableType,
628 variable_name: &str,
629 ) -> anyhow::Result<()> {
630 let _ = (data, variable_type, variable_name);
631 Ok(())
632 }
633
634 async fn catch<T: Sendable>(&self, id: u32) -> anyhow::Result<Vec<T>>;
638
639 async fn catch_archived<T: Sendable>(&self, id: u32)
641 -> anyhow::Result<Vec<ArchivedMessage<T>>>;
642
643 async fn catch_for_variable<T: Sendable>(
662 &self,
663 id: u32,
664 variable_name: &str,
665 drop_stale: bool,
666 ) -> anyhow::Result<Vec<ArchivedMessage<T>>>;
667
668 async fn catch_dyn(&self, id: u32) -> anyhow::Result<Vec<(String, VariableType, String)>>;
669}
670
671#[derive(Clone, Debug, Default, Copy, Archive, Serialize, Deserialize, PartialEq)]
672pub struct TimeMsg {
673 pub sec: i32,
674 pub nanosec: u32,
675}
676
677#[derive(Clone, Debug, Default, PartialEq, Archive, Serialize, Deserialize)]
678pub struct Header {
679 pub seq: u32,
680 pub stamp: TimeMsg,
681 pub frame_id: String,
682}
683
684pub type WindData = BagMsg;
685
686#[async_trait::async_trait]
687pub trait Coordinator: Send + Sync + 'static {
688 async fn rat_action_request_queue(
689 &self,
690 ship: String,
691 ) -> anyhow::Result<tokio::sync::broadcast::Receiver<String>>;
692
693 async fn blow_wind(&self, ship: String, data: Vec<WindData>) -> anyhow::Result<()>;
694
695 async fn rat_action_send(
696 &self,
697 ship: String,
698 variable: String,
699 action: ActionPlan,
700 lock_until_ack: bool,
701 best_effort: bool,
702 ) -> anyhow::Result<()>;
703
704 async fn push_routes_for_var(&self, variable: &str, rules: &Rules) -> anyhow::Result<()>;
707}