Skip to main content

mt_sea/
lib.rs

1pub mod client;
2pub mod coordinator;
3pub mod net;
4pub mod network;
5pub mod ship;
6
7pub use net::{Durability, Qos, Reliability};
8
9// ---------------------------------------------------------------------------
10// Timing constants. These values are interdependent.
11// When changing one, check all others marked with the same group tag.
12// ---------------------------------------------------------------------------
13
14/// [heartbeat] How often nodes send heartbeat messages to keep their connection alive.
15pub const HEARTBEAT_INTERVAL_MS: u64 = 400;
16
17/// [heartbeat] Heartbeat is skipped if data was sent within this window.
18/// Must be ≤ HEARTBEAT_INTERVAL_MS so a heartbeat is always sent before
19/// DISCONNECT_TIMEOUT_MS elapses after the last real data.
20pub const HEARTBEAT_SUPPRESS_MS: u64 = HEARTBEAT_INTERVAL_MS / 2;
21
22/// [heartbeat] Coordinator drops a client after this long with no message.
23/// Must be > HEARTBEAT_INTERVAL_MS + HEARTBEAT_SUPPRESS_MS to avoid false disconnects.
24pub const DISCONNECT_TIMEOUT_MS: u64 = HEARTBEAT_INTERVAL_MS * 2; // 800 ms
25
26/// [registration] How long to wait for a coordinator before giving up on registration.
27pub const REGISTRATION_TIMEOUT_MS: u64 = 2000;
28
29/// [peer-heartbeat] Consecutive ping failures before declaring a peer dead.
30pub const PEER_DEAD_THRESHOLD: u32 = 3;
31
32/// Policy shared by every node.
33///
34/// Carried as one value so adding a knob later does not churn every call site.
35/// `Default` is LAN timing with reconnect decided by the node's QoS.
36#[derive(Debug, Clone, Copy, Default)]
37pub struct NodeOptions {
38    /// How patient this node and its coordinator are with each other.
39    pub timing: Timing,
40    /// What to do when the coordinator link drops. `None` derives it from the
41    /// node's QoS via [`ReconnectPolicy::for_qos`], which is almost always what
42    /// you want. Override only to force a `Reliable` node to give up sooner,
43    /// or to pin a resilient node to `Never` for a deterministic test.
44    pub reconnect: Option<ReconnectPolicy>,
45    /// Always ask the coordinator for a route, never answer from the cache.
46    ///
47    /// Asking has a side effect: the coordinator also hands the comparison node
48    /// its Catch route for that variable, and nothing else delivers it. Only
49    /// nodes carrying variables minot compares need this. For everyone else it
50    /// costs a coordinator round trip per publish, which dominates a streaming
51    /// path and floods the shared broadcast the answers come back on.
52    pub bypass_route_cache: bool,
53}
54
55impl NodeOptions {
56    /// Options for a link that is expected to wobble: WAN timing plus
57    /// reconnection.
58    pub fn wan() -> Self {
59        Self {
60            timing: Timing::wan(),
61            reconnect: Some(ReconnectPolicy::always()),
62            bypass_route_cache: false,
63        }
64    }
65
66    /// Keep asking the coordinator for every route. See
67    /// [`NodeOptions::bypass_route_cache`]; set by nodes whose variables the
68    /// comparison node reads.
69    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    /// Resolve the reconnect policy for a node running at `qos`.
85    pub fn reconnect_policy(&self, qos: Qos) -> ReconnectPolicy {
86        self.reconnect
87            .unwrap_or_else(|| ReconnectPolicy::for_qos(qos))
88    }
89}
90
91/// Live state of a node's link to the coordinator.
92///
93/// A node's connection can come back. A reconnect rebuilds the [`ShipKind`]
94/// registration, the channels to the coordinator and the coordinator's handler
95/// for this client, while the *node* and every publisher and subscriber the
96/// caller holds stay alive across it.
97///
98/// Each successful registration is a **generation**. When it changes, the
99/// channels a long-lived task captured are stale and its registration with the
100/// coordinator has to be redone.
101#[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    /// Carries the new generation number to everything that needs to re-register.
108    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    /// Which registration is currently live. Starts at 0 and increments once
130    /// per successful re-registration.
131    pub fn generation(&self) -> u64 {
132        self.generation.load(std::sync::atomic::Ordering::Acquire)
133    }
134
135    /// Whether the link is up right now.
136    pub fn is_connected(&self) -> bool {
137        self.connected.load(std::sync::atomic::Ordering::Acquire)
138    }
139
140    /// Subscribe to reconnection announcements. Each message is the generation
141    /// that just became live.
142    pub fn subscribe(&self) -> tokio::sync::broadcast::Receiver<u64> {
143        self.announce.subscribe()
144    }
145
146    /// Whether the coordinator has been observed answering this node.
147    ///
148    /// Registration only proves the coordinator was reachable at that instant.
149    /// This becomes true once it echoes a heartbeat, which is also when the
150    /// node's disconnect detector arms; before that, a coordinator that dies
151    /// cannot be noticed. Wait on this when the link must be ready for traffic.
152    pub fn is_link_proven(&self) -> bool {
153        self.link_proven.load(std::sync::atomic::Ordering::Acquire)
154    }
155
156    /// Whether this node sends heartbeats.
157    ///
158    /// Only a heartbeating node expects the coordinator to answer, so only a
159    /// heartbeating node may treat silence as a disconnect. A ship that speaks
160    /// solely when it has something to say would be torn down for being quiet.
161    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    /// Publish a completed re-registration. Returns the new generation.
187    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        // Having no receivers is normal.
195        let _ = self.announce.send(generation);
196        generation
197    }
198}
199
200/// What a node should do when it loses the coordinator.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
202pub enum ReconnectPolicy {
203    /// Give up. The node's shutdown token is cancelled and it is finished.
204    ///
205    /// The only correct policy for [`Qos::Reliable`], whose contract is that its
206    /// death is fatal to the run.
207    #[default]
208    Never,
209    /// Keep re-registering, with backoff, until the link comes back or the node
210    /// is shut down explicitly. Publishers and subscribers survive.
211    Always {
212        /// First retry delay.
213        initial_backoff_ms: u64,
214        /// Ceiling for the exponential backoff.
215        max_backoff_ms: u64,
216    },
217}
218
219impl ReconnectPolicy {
220    /// The sensible default for a node that is allowed to come back.
221    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    /// The default policy for a node with this QoS.
233    ///
234    /// `Reliable` never reconnects: peers monitor it and its loss torpedoes the
235    /// run, so a silent recovery would contradict that guarantee. Nothing
236    /// depends on the liveness of the other modes, so they reconnect.
237    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/// Per-node timing policy.
247///
248/// The constants above are the defaults, chosen for a LAN-attached replay rig
249/// where a node quiet for 800 ms really has died. A wobbling link — an SSH
250/// tunnel to a robot on cellular, a laptop roaming between access points — has
251/// one-second hiccups that must not be read as a death.
252///
253/// A node carries its own `Timing` and tells the coordinator about it when it
254/// joins, so the two sides agree on how patient to be with each other.
255///
256/// The fields are interdependent. [`Timing::validate`] checks the relationships
257/// that the rest of the system relies on.
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub struct Timing {
260    /// How often this node sends a heartbeat to keep its connection alive.
261    pub heartbeat_interval_ms: u64,
262    /// A heartbeat is skipped if real data was sent within this window.
263    pub heartbeat_suppress_ms: u64,
264    /// How long the coordinator waits with no message before declaring this
265    /// node gone, and how long this node waits for heartbeat echoes before
266    /// declaring the coordinator gone.
267    pub disconnect_timeout_ms: u64,
268    /// How long to wait for a coordinator before giving up on registration.
269    pub registration_timeout_ms: u64,
270    /// Consecutive peer ping failures before declaring that peer dead.
271    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    /// Timing for a link that is expected to wobble: off-LAN, tunnelled,
288    /// wireless, or otherwise not under your control.
289    ///
290    /// Roughly 5× more patient than the default. Dead-node detection takes about
291    /// 10 seconds.
292    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    /// Check the relationships the rest of the system relies on.
303    ///
304    /// Called when a node is built, so a bad custom `Timing` fails loudly at
305    /// startup with a concrete configuration error.
306    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
349/// [try-reliable] Total budget for one `Qos::TryReliable` delivery.
350/// Generous enough to ride out a WiFi roam or a retry burst, bounded so a
351/// send can never wedge the caller's loop the way `Qos::Reliable` can.
352pub const TRY_RELIABLE_SEND_BUDGET_MS: u64 = 3000;
353
354/// [try-reliable] Per-attempt query timeout inside that budget. Must be well
355/// below TRY_RELIABLE_SEND_BUDGET_MS so a stalled attempt leaves room to retry.
356pub const TRY_RELIABLE_ATTEMPT_TIMEOUT_MS: u64 = 500;
357
358/// [try-reliable] Pause between failed attempts, so a dead target is not
359/// hammered for the whole budget.
360pub const TRY_RELIABLE_RETRY_BACKOFF_MS: u64 = 50;
361
362/// [coordinator] Last-resort timeout for coordinator-side per-client handler.
363/// This fires for
364/// truly isolated or zombie clients that sent no packet for this long.
365pub const COORD_CLIENT_IDLE_TIMEOUT_MS: u64 = 30_000;
366
367use mt_net::{ActionPlan, BagMsg, Rules, VariableHuman};
368
369/// An immutable, validated rkyv message that owns its backing byte buffer.
370///
371/// [`archived`](Self::archived) borrows directly from the stored buffer without
372/// deserializing an owned `T`. Keeping the owner and view in one type prevents
373/// the archived reference from outliving its bytes.
374pub 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    /// Access the archived representation without allocating or deserializing `T`.
405    pub fn archived(&self) -> &T::Archived {
406        // SAFETY: construction validates the buffer as T::Archived, and `bytes` is
407        // private and never exposed mutably, so that validation remains valid.
408        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    /// Deserialize an owned value when an existing API still requires `T`.
431    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
439/// Initialize logging in the house format, with the transport crates capped
440/// however loud `RUST_LOG` asks everything else to be.
441pub 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            // directly because rule was set
502            let directly = plans
503                .iter()
504                .filter(|plan| plan.ship == rat_ship)
505                .filter_map(|el| el.strategy.clone())
506                .collect::<Vec<_>>();
507
508            // as other part of a rule
509            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    /// Indicate a trigger point and ask the link pilot what to do with the variable.
543    async fn ask_for_action(&self, variable_name: &str) -> anyhow::Result<(Action, bool)>;
544
545    // async fn wait_for_action(&self) -> anyhow::Result<crate::Action>;
546
547    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, // statically supported but no dynamic conversion implemented
556    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
588/// Types that can be serialized and sent.
589pub 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    // Initialize a 1:1 connection to the target. Ports are shared using the sea network internally.
612
613    /// Dump the data to the target.
614    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    /// Keep the latest value of a transient-local topic.
624    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    /// Catch the dumped data from the source.
635    /// The returning Vec can contain previously missed entities of T from existing sync connections.
636    /// The first item of T is the newest, followed by incremental older ones.
637    async fn catch<T: Sendable>(&self, id: u32) -> anyhow::Result<Vec<T>>;
638
639    /// Catch validated archived messages without deserializing owned values.
640    async fn catch_archived<T: Sendable>(&self, id: u32)
641    -> anyhow::Result<Vec<ArchivedMessage<T>>>;
642
643    /// Catch this variable's messages, tolerating a route id that has gone
644    /// stale.
645    ///
646    /// `id` is a *route* id: [`Rules::new_id`] mints one per publisher /
647    /// subscriber pairing and every publish on that route carries it. A
648    /// coordinator restart re-derives the route under a fresh id from a counter
649    /// that starts at zero again, so until the publisher takes the new route it
650    /// shoots under the old one while the subscriber waits on the new. The
651    /// id-keyed [`Self::catch_archived`] waits out that skew forever, leaving a
652    /// viewer that reconnects and never updates again.
653    ///
654    /// The id is therefore a preference: this variable's entries under `id`
655    /// when there are any, otherwise its entries under whatever id is buffered.
656    ///
657    /// `drop_stale` also keeps only the newest arrival. It is for modes
658    /// permitted to drop samples, where nothing else bounds the buffer. A mode
659    /// that promises delivery ([`Qos::expects_reliable_delivery`]) must pass
660    /// `false` and receive the backlog in arrival order.
661    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    /// Push updated routes for `variable` to all ships currently involved in it.
705    /// Called after topology changes (register / disconnect / PeerDead).
706    async fn push_routes_for_var(&self, variable: &str, rules: &Rules) -> anyhow::Result<()>;
707}