mt_sea 0.16.1

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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
pub mod claim;
pub mod client;
pub mod coordinator;
pub mod net;
pub mod network;
pub mod presence;
pub mod ship;

pub use net::{Durability, Qos, Reliability};

// ---------------------------------------------------------------------------
// Timing constants. These values are interdependent.
// When changing one, check all others marked with the same group tag.
// ---------------------------------------------------------------------------

/// [heartbeat] How often nodes send heartbeat messages to keep their connection alive.
pub const HEARTBEAT_INTERVAL_MS: u64 = 400;

/// [heartbeat] Heartbeat is skipped if data was sent within this window.
/// Must be ≤ HEARTBEAT_INTERVAL_MS so a heartbeat is always sent before
/// DISCONNECT_TIMEOUT_MS elapses after the last real data.
pub const HEARTBEAT_SUPPRESS_MS: u64 = HEARTBEAT_INTERVAL_MS / 2;

/// [heartbeat] Coordinator drops a client after this long with no message.
/// Must be > HEARTBEAT_INTERVAL_MS + HEARTBEAT_SUPPRESS_MS to avoid false disconnects.
pub const DISCONNECT_TIMEOUT_MS: u64 = HEARTBEAT_INTERVAL_MS * 2; // 800 ms

/// [registration] How long to wait for a coordinator before giving up on registration.
pub const REGISTRATION_TIMEOUT_MS: u64 = 2000;

/// [peer-heartbeat] Consecutive ping failures before declaring a peer dead.
pub const PEER_DEAD_THRESHOLD: u32 = 3;

/// Policy shared by every node.
///
/// Carried as one value so adding a knob later does not churn every call site.
/// `Default` is LAN timing with reconnect decided by the node's QoS.
#[derive(Debug, Clone, Copy, Default)]
pub struct NodeOptions {
    /// How patient this node and its coordinator are with each other.
    pub timing: Timing,
    /// What to do when the coordinator link drops. `None` derives it from the
    /// node's QoS via [`ReconnectPolicy::for_qos`], which is almost always what
    /// you want. Override only to force a `Reliable` node to give up sooner,
    /// or to pin a resilient node to `Never` for a deterministic test.
    pub reconnect: Option<ReconnectPolicy>,
    /// Always ask the coordinator for a route, never answer from the cache.
    ///
    /// Asking has a side effect: the coordinator also hands the comparison node
    /// its Catch route for that variable, and nothing else delivers it. Only
    /// nodes carrying variables minot compares need this. For everyone else it
    /// costs a coordinator round trip per publish, which dominates a streaming
    /// path and floods the shared broadcast the answers come back on.
    pub bypass_route_cache: bool,
}

impl NodeOptions {
    /// Options for a link that is expected to wobble: WAN timing plus
    /// reconnection.
    pub fn wan() -> Self {
        Self {
            timing: Timing::wan(),
            reconnect: Some(ReconnectPolicy::always()),
            bypass_route_cache: false,
        }
    }

    /// Keep asking the coordinator for every route. See
    /// [`NodeOptions::bypass_route_cache`]; set by nodes whose variables the
    /// comparison node reads.
    pub fn with_route_cache_bypassed(mut self) -> Self {
        self.bypass_route_cache = true;
        self
    }

    pub fn with_timing(mut self, timing: Timing) -> Self {
        self.timing = timing;
        self
    }

    pub fn with_reconnect(mut self, reconnect: ReconnectPolicy) -> Self {
        self.reconnect = Some(reconnect);
        self
    }

    /// Resolve the reconnect policy for a node running at `qos`.
    pub fn reconnect_policy(&self, qos: Qos) -> ReconnectPolicy {
        self.reconnect
            .unwrap_or_else(|| ReconnectPolicy::for_qos(qos))
    }
}

/// Live state of a node's link to the coordinator.
///
/// A node's connection can come back. A reconnect rebuilds the [`ShipKind`]
/// registration, the channels to the coordinator and the coordinator's handler
/// for this client, while the *node* and every publisher and subscriber the
/// caller holds stay alive across it.
///
/// Each successful registration is a **generation**. When it changes, the
/// channels a long-lived task captured are stale and its registration with the
/// coordinator has to be redone.
#[derive(Debug)]
pub struct ConnectionState {
    generation: std::sync::atomic::AtomicU64,
    connected: std::sync::atomic::AtomicBool,
    link_proven: std::sync::atomic::AtomicBool,
    heartbeating: std::sync::atomic::AtomicBool,
    /// Where the coordinator of the live registration runs.
    coordinator: std::sync::Mutex<presence::Relation>,
    /// Carries the new generation number to everything that needs to re-register.
    announce: tokio::sync::broadcast::Sender<u64>,
}

impl Default for ConnectionState {
    fn default() -> Self {
        Self::new()
    }
}

impl ConnectionState {
    pub fn new() -> Self {
        let (announce, _) = tokio::sync::broadcast::channel(16);
        Self {
            generation: std::sync::atomic::AtomicU64::new(0),
            connected: std::sync::atomic::AtomicBool::new(true),
            link_proven: std::sync::atomic::AtomicBool::new(false),
            heartbeating: std::sync::atomic::AtomicBool::new(false),
            coordinator: std::sync::Mutex::new(presence::Relation::Remote),
            announce,
        }
    }

    /// Connection state for a coordinator-free session. Generation stays at
    /// zero; the session is ready until its lifetime token is cancelled.
    pub fn for_session(shutdown: tokio_util::sync::CancellationToken) -> std::sync::Arc<Self> {
        let state = std::sync::Arc::new(Self::new());
        state.mark_link_proven();
        let watcher = std::sync::Arc::clone(&state);
        tokio::spawn(async move {
            shutdown.cancelled().await;
            watcher.mark_disconnected();
        });
        state
    }

    /// Which registration is currently live. Starts at 0 and increments once
    /// per successful re-registration. Peer sessions keep generation zero.
    pub fn generation(&self) -> u64 {
        self.generation.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Whether the link is up right now.
    pub fn is_connected(&self) -> bool {
        self.connected.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Subscribe to reconnection announcements. Each message is the generation
    /// that just became live.
    pub fn subscribe(&self) -> tokio::sync::broadcast::Receiver<u64> {
        self.announce.subscribe()
    }

    /// Whether the coordinator has been observed answering this node.
    ///
    /// In coordinator-free sessions this instead means the local session is open.
    /// Registration only proves the coordinator was reachable at that instant.
    /// This becomes true once it echoes a heartbeat, which is also when the
    /// node's disconnect detector arms; before that, a coordinator that dies
    /// cannot be noticed. Wait on this when the link must be ready for traffic.
    pub fn is_link_proven(&self) -> bool {
        self.link_proven.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Whether this node sends heartbeats.
    ///
    /// Only a heartbeating node expects the coordinator to answer, so only a
    /// heartbeating node may treat silence as a disconnect. A ship that speaks
    /// solely when it has something to say would be torn down for being quiet.
    pub fn is_heartbeating(&self) -> bool {
        self.heartbeating.load(std::sync::atomic::Ordering::Acquire)
    }

    pub(crate) fn mark_heartbeating(&self) {
        self.heartbeating
            .store(true, std::sync::atomic::Ordering::Release);
    }

    pub(crate) fn mark_link_proven(&self) {
        self.link_proven
            .store(true, std::sync::atomic::Ordering::Release);
    }

    pub(crate) fn mark_link_unproven(&self) {
        self.link_proven
            .store(false, std::sync::atomic::Ordering::Release);
    }

    pub(crate) fn mark_disconnected(&self) {
        self.mark_link_unproven();
        self.connected
            .store(false, std::sync::atomic::Ordering::Release);
    }

    /// How the coordinator of the live registration is placed relative to
    /// this node. Remote until it welcomed this node.
    pub fn coordinator_relation(&self) -> presence::Relation {
        *self.coordinator.lock().unwrap()
    }

    pub(crate) fn set_coordinator(&self, relation: presence::Relation) {
        *self.coordinator.lock().unwrap() = relation;
    }

    /// Publish a completed re-registration. Returns the new generation.
    pub(crate) fn mark_reconnected(&self) -> u64 {
        let generation = self
            .generation
            .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
            + 1;
        self.connected
            .store(true, std::sync::atomic::Ordering::Release);
        // Having no receivers is normal.
        let _ = self.announce.send(generation);
        generation
    }
}

/// What a node should do when it loses the coordinator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReconnectPolicy {
    /// Give up. The node's shutdown token is cancelled and it is finished.
    ///
    /// The only correct policy for [`Qos::Reliable`], whose contract is that its
    /// death is fatal to the run.
    #[default]
    Never,
    /// Keep re-registering, with backoff, until the link comes back or the node
    /// is shut down explicitly. Publishers and subscribers survive.
    Always {
        /// First retry delay.
        initial_backoff_ms: u64,
        /// Ceiling for the exponential backoff.
        max_backoff_ms: u64,
    },
}

impl ReconnectPolicy {
    /// The sensible default for a node that is allowed to come back.
    pub fn always() -> Self {
        Self::Always {
            initial_backoff_ms: 250,
            max_backoff_ms: 10_000,
        }
    }

    pub fn is_enabled(self) -> bool {
        matches!(self, Self::Always { .. })
    }

    /// The default policy for a node with this QoS.
    ///
    /// `Reliable` never reconnects: peers monitor it and its loss torpedoes the
    /// run, so a silent recovery would contradict that guarantee. Nothing
    /// depends on the liveness of the other modes, so they reconnect.
    pub fn for_qos(qos: Qos) -> Self {
        if qos.fires_torpedo() {
            Self::Never
        } else {
            Self::always()
        }
    }
}

/// Per-node timing policy.
///
/// The constants above are the defaults, chosen for a LAN-attached replay rig
/// where a node quiet for 800 ms really has died. A wobbling link — an SSH
/// tunnel to a robot on cellular, a laptop roaming between access points — has
/// one-second hiccups that must not be read as a death.
///
/// A node carries its own `Timing` and tells the coordinator about it when it
/// joins, so the two sides agree on how patient to be with each other.
///
/// The fields are interdependent. [`Timing::validate`] checks the relationships
/// that the rest of the system relies on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timing {
    /// How often this node sends a heartbeat to keep its connection alive.
    pub heartbeat_interval_ms: u64,
    /// A heartbeat is skipped if real data was sent within this window.
    pub heartbeat_suppress_ms: u64,
    /// How long the coordinator waits with no message before declaring this
    /// node gone, and how long this node waits for heartbeat echoes before
    /// declaring the coordinator gone.
    pub disconnect_timeout_ms: u64,
    /// How long to wait for a coordinator before giving up on registration.
    pub registration_timeout_ms: u64,
    /// Consecutive peer ping failures before declaring that peer dead.
    pub peer_dead_threshold: u32,
}

impl Default for Timing {
    fn default() -> Self {
        Self {
            heartbeat_interval_ms: HEARTBEAT_INTERVAL_MS,
            heartbeat_suppress_ms: HEARTBEAT_SUPPRESS_MS,
            disconnect_timeout_ms: DISCONNECT_TIMEOUT_MS,
            registration_timeout_ms: REGISTRATION_TIMEOUT_MS,
            peer_dead_threshold: PEER_DEAD_THRESHOLD,
        }
    }
}

impl Timing {
    /// Timing for a link that is expected to wobble: off-LAN, tunnelled,
    /// wireless, or otherwise not under your control.
    ///
    /// Roughly 5× more patient than the default. Dead-node detection takes about
    /// 10 seconds.
    pub fn wan() -> Self {
        Self {
            heartbeat_interval_ms: 2_000,
            heartbeat_suppress_ms: 1_000,
            disconnect_timeout_ms: 10_000,
            registration_timeout_ms: 15_000,
            peer_dead_threshold: 3,
        }
    }

    /// Check the relationships the rest of the system relies on.
    ///
    /// Called when a node is built, so a bad custom `Timing` fails loudly at
    /// startup with a concrete configuration error.
    pub fn validate(&self) -> anyhow::Result<()> {
        if self.heartbeat_interval_ms == 0 {
            anyhow::bail!("Timing::heartbeat_interval_ms must be greater than zero");
        }
        if self.heartbeat_suppress_ms > self.heartbeat_interval_ms {
            anyhow::bail!(
                "Timing::heartbeat_suppress_ms ({}) must be <= heartbeat_interval_ms ({}), \
                 otherwise a heartbeat can be suppressed past the disconnect timeout",
                self.heartbeat_suppress_ms,
                self.heartbeat_interval_ms
            );
        }
        if self.disconnect_timeout_ms <= self.heartbeat_interval_ms + self.heartbeat_suppress_ms {
            anyhow::bail!(
                "Timing::disconnect_timeout_ms ({}) must be > heartbeat_interval_ms + \
                 heartbeat_suppress_ms ({}), otherwise healthy nodes are declared dead",
                self.disconnect_timeout_ms,
                self.heartbeat_interval_ms + self.heartbeat_suppress_ms
            );
        }
        if self.peer_dead_threshold == 0 {
            anyhow::bail!("Timing::peer_dead_threshold must be greater than zero");
        }
        Ok(())
    }

    pub fn heartbeat_interval(&self) -> std::time::Duration {
        std::time::Duration::from_millis(self.heartbeat_interval_ms)
    }

    pub fn heartbeat_suppress(&self) -> std::time::Duration {
        std::time::Duration::from_millis(self.heartbeat_suppress_ms)
    }

    pub fn disconnect_timeout(&self) -> std::time::Duration {
        std::time::Duration::from_millis(self.disconnect_timeout_ms)
    }

    pub fn registration_timeout(&self) -> std::time::Duration {
        std::time::Duration::from_millis(self.registration_timeout_ms)
    }
}

/// [try-reliable] Total budget for one `Qos::TryReliable` delivery.
/// Generous enough to ride out a WiFi roam, bounded so a send can never wedge
/// the caller's loop the way `Qos::Reliable` can.
pub const TRY_RELIABLE_SEND_BUDGET_MS: u64 = 3000;

/// [coordinator] Last-resort timeout for coordinator-side per-client handler.
/// This fires for
/// truly isolated or zombie clients that sent no packet for this long.
pub const COORD_CLIENT_IDLE_TIMEOUT_MS: u64 = 30_000;

use mt_net::{ActionPlan, BagMsg, Rules, VariableHuman};

/// An immutable, validated rkyv message that owns its backing byte buffer.
///
/// [`archived`](Self::archived) borrows directly from the stored buffer without
/// deserializing an owned `T`. Keeping the owner and view in one type prevents
/// the archived reference from outliving its bytes.
pub struct ArchivedMessage<T: Archive> {
    bytes: AlignedVec,
    _type: std::marker::PhantomData<fn() -> T>,
}

impl<T> std::fmt::Debug for ArchivedMessage<T>
where
    T: Archive,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ArchivedMessage")
            .field("len", &self.bytes.len())
            .finish_non_exhaustive()
    }
}

impl<T> ArchivedMessage<T>
where
    T: Archive,
    T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>,
{
    /// Validate an aligned wire buffer before exposing an archived view.
    pub fn from_aligned_bytes(bytes: AlignedVec) -> anyhow::Result<Self> {
        rkyv::access::<T::Archived, rkyv::rancor::Error>(&bytes)
            .map_err(|error| anyhow::anyhow!("Could not validate archived message: {error}"))?;
        Ok(Self {
            bytes,
            _type: std::marker::PhantomData,
        })
    }

    /// Access the archived representation without allocating or deserializing `T`.
    pub fn archived(&self) -> &T::Archived {
        // SAFETY: construction validates the buffer as T::Archived, and `bytes` is
        // private and never exposed mutably, so that validation remains valid.
        unsafe { rkyv::access_unchecked::<T::Archived>(&self.bytes) }
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    pub fn len(&self) -> usize {
        self.bytes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }
}

impl<T> ArchivedMessage<T>
where
    T: Archive,
    T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
        + Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>,
{
    /// Deserialize an owned value when an existing API still requires `T`.
    pub fn deserialize(&self) -> anyhow::Result<T> {
        let mut pool = Pool::new();
        self.archived()
            .deserialize(Strategy::wrap(&mut pool))
            .map_err(|error| anyhow::anyhow!("Could not deserialize archived message: {error}"))
    }
}

/// Initialize logging in the house format, with the transport crates capped
/// however loud `RUST_LOG` asks everything else to be.
pub fn init_logging() {
    mt_log::init_filtered("Minot", "RUST_LOG", "info", mt_log::QUIET_ZENOH);
}

use rkyv::{
    Archive, Deserialize, Serialize,
    api::high::{HighSerializer, HighValidator},
    bytecheck::CheckBytes,
    de::Pool,
    rancor::Strategy,
    ser::allocator::ArenaHandle,
    util::AlignedVec,
};

#[derive(Debug, Clone, PartialEq, Archive, Serialize, Deserialize, Hash, Eq, PartialOrd, Ord)]
pub enum ShipKind {
    Rat(String),
    Wind(String),
}

pub type ShipName = i128;

#[derive(Debug, Clone, Serialize, Deserialize, Archive, PartialEq, Eq)]
pub struct NetworkShipAddress {
    ip: [u8; 4],
    pub port: u16,
    ship: ShipName,
    pub kind: ShipKind,
    pub node_mode: net::Qos,
}

#[derive(Debug, Archive, Clone, Default, Serialize, Deserialize)]
pub enum Action {
    #[default]
    Sail,
    Shoot {
        target: Vec<NetworkShipAddress>,
        id: u32,
    },
    Catch {
        source: NetworkShipAddress,
        id: u32,
    },
}

#[derive(Clone, Debug)]
pub struct Variable {
    pub ship: ShipName,
    pub strategy: Option<Action>,
}

pub fn get_strategies(
    haystack: &Rules,
    rat_ship: &str,
    variable: String,
    indirect_parent_rat: Option<&str>,
) -> Vec<ActionPlan> {
    match haystack.raw().get(&variable) {
        None => vec![ActionPlan::default()],
        Some(plans) => {
            // directly because rule was set
            let directly = plans
                .iter()
                .filter(|plan| plan.ship == rat_ship)
                .filter_map(|el| el.strategy.clone())
                .collect::<Vec<_>>();

            // as other part of a rule
            let mut indirect = plans
                .iter()
                .filter(|plan| indirect_parent_rat.is_none_or(|parent_rat| plan.ship == parent_rat))
                .filter_map(|plan| match plan.strategy.as_ref()? {
                    ActionPlan::Sail => None,
                    ActionPlan::Shoot { target, id } => target
                        .iter()
                        .find(|shoot_target| *shoot_target == rat_ship)
                        .map(|_| ActionPlan::Catch {
                            source: plan.ship.clone(),
                            id: *id,
                        }),
                    ActionPlan::Catch { source, id } => {
                        if source == rat_ship {
                            Some(ActionPlan::Shoot {
                                target: vec![source.clone()],
                                id: *id,
                            })
                        } else {
                            None
                        }
                    }
                })
                .collect::<Vec<_>>();

            indirect.extend(directly);
            indirect
        }
    }
}

#[async_trait::async_trait]
pub trait Ship: Send + Sync + 'static {
    /// Indicate a trigger point and ask the link pilot what to do with the variable.
    async fn ask_for_action(&self, variable_name: &str) -> anyhow::Result<(Action, bool)>;

    // async fn wait_for_action(&self) -> anyhow::Result<crate::Action>;

    async fn wait_for_wind(&self) -> anyhow::Result<Vec<WindData>>;

    fn get_cannon(&self) -> &impl Cannon;
}

#[derive(Archive, Serialize, Deserialize, Debug, Clone, Copy, Default)]
pub enum VariableType {
    #[default]
    StaticOnly, // statically supported but no dynamic conversion implemented
    U8,
    I32,
    F32,
    F64,
}

impl From<u8> for VariableType {
    fn from(value: u8) -> Self {
        match value {
            1 => Self::U8,
            2 => Self::I32,
            3 => Self::F32,
            4 => Self::F64,
            _ => Self::default(),
        }
    }
}

impl From<VariableType> for u8 {
    fn from(value: VariableType) -> Self {
        match value {
            VariableType::StaticOnly => 0,
            VariableType::U8 => 1,
            VariableType::I32 => 2,
            VariableType::F32 => 3,
            VariableType::F64 => 4,
        }
    }
}

use rkyv::rancor::Error as RkyvError;

/// Types that can be serialized and sent.
pub trait Sendable: Sized + Send + Sync + 'static
where
    Self: for<'b> Serialize<HighSerializer<AlignedVec, ArenaHandle<'b>, RkyvError>>,
    Self: Archive<
        Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
                      + Deserialize<Self, Strategy<Pool, rkyv::rancor::Error>>,
    >,
{
}
impl<T> Sendable for T
where
    T: Sized + Send + Sync + 'static,
    T: for<'b> Serialize<HighSerializer<AlignedVec, ArenaHandle<'b>, RkyvError>>,
    T: Archive<
        Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
                      + Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>,
    >,
{
}

#[async_trait::async_trait]
pub trait Cannon: Send + Sync + 'static {
    // Initialize a 1:1 connection to the target. Ports are shared using the sea network internally.

    /// Dump the data to the target.
    async fn shoot<'b, T: Sendable>(
        &self,
        targets: &'b [crate::NetworkShipAddress],
        id: u32,
        data: &T,
        variable_type: VariableType,
        variable_name: &str,
    ) -> anyhow::Result<()>;

    /// Keep the latest value of a transient-local topic.
    async fn retain<T: Sendable>(
        &self,
        data: &T,
        variable_type: VariableType,
        variable_name: &str,
    ) -> anyhow::Result<()> {
        let _ = (data, variable_type, variable_name);
        Ok(())
    }

    /// Catch the dumped data from the source.
    /// The returning Vec can contain previously missed entities of T from existing sync connections.
    /// The first item of T is the newest, followed by incremental older ones.
    async fn catch<T: Sendable>(&self, id: u32) -> anyhow::Result<Vec<T>>;

    /// Catch validated archived messages without deserializing owned values.
    async fn catch_archived<T: Sendable>(&self, id: u32)
    -> anyhow::Result<Vec<ArchivedMessage<T>>>;

    /// Catch this variable's messages, tolerating a route id that has gone
    /// stale.
    ///
    /// `id` is a *route* id: [`Rules::new_id`] mints one per publisher /
    /// subscriber pairing and every publish on that route carries it. A
    /// coordinator restart re-derives the route under a fresh id from a counter
    /// that starts at zero again, so until the publisher takes the new route it
    /// shoots under the old one while the subscriber waits on the new. The
    /// id-keyed [`Self::catch_archived`] waits out that skew forever, leaving a
    /// viewer that reconnects and never updates again.
    ///
    /// The id is therefore a preference: this variable's entries under `id`
    /// when there are any, otherwise its entries under whatever id is buffered.
    ///
    /// `drop_stale` also keeps only the newest arrival. It is for modes
    /// permitted to drop samples, where nothing else bounds the buffer. A mode
    /// that promises delivery ([`Qos::expects_reliable_delivery`]) must pass
    /// `false` and receive the backlog in arrival order.
    async fn catch_for_variable<T: Sendable>(
        &self,
        id: u32,
        variable_name: &str,
        drop_stale: bool,
    ) -> anyhow::Result<Vec<ArchivedMessage<T>>>;

    async fn catch_dyn(&self, id: u32) -> anyhow::Result<Vec<(String, VariableType, String)>>;
}

#[derive(Clone, Debug, Default, Copy, Archive, Serialize, Deserialize, PartialEq)]
pub struct TimeMsg {
    pub sec: i32,
    pub nanosec: u32,
}

#[derive(Clone, Debug, Default, PartialEq, Archive, Serialize, Deserialize)]
pub struct Header {
    pub seq: u32,
    pub stamp: TimeMsg,
    pub frame_id: String,
}

pub type WindData = BagMsg;

#[async_trait::async_trait]
pub trait Coordinator: Send + Sync + 'static {
    async fn rat_action_request_queue(
        &self,
        ship: String,
    ) -> anyhow::Result<tokio::sync::broadcast::Receiver<String>>;

    async fn blow_wind(&self, ship: String, data: Vec<WindData>) -> anyhow::Result<()>;

    async fn rat_action_send(
        &self,
        ship: String,
        variable: String,
        action: ActionPlan,
        lock_until_ack: bool,
        best_effort: bool,
    ) -> anyhow::Result<()>;

    /// Push routes from [`plan_routes_for_var`] or [`changed_routes`].
    async fn push_planned_routes(
        &self,
        variable: &str,
        plans: Vec<(String, Vec<ActionPlan>)>,
    ) -> anyhow::Result<()>;
}

pub fn plan_routes_for_var(rules: &Rules, variable: &str) -> Vec<(String, Vec<ActionPlan>)> {
    rules
        .all_ships_for_var(variable)
        .into_iter()
        .map(|ship| {
            let actions = get_strategies(rules, &ship, variable.to_string(), None);
            (ship, actions)
        })
        .collect()
}

/// Ships in `after` whose actions differ from `before`, plus `always`.
pub fn changed_routes(
    before: &[(String, Vec<ActionPlan>)],
    after: Vec<(String, Vec<ActionPlan>)>,
    always: Option<&str>,
) -> Vec<(String, Vec<ActionPlan>)> {
    after
        .into_iter()
        .filter(|(ship, actions)| {
            Some(ship.as_str()) == always
                || before
                    .iter()
                    .find(|(b, _)| b == ship)
                    .is_none_or(|(_, prev)| prev != actions)
        })
        .collect()
}

#[cfg(test)]
mod route_push_tests {
    use super::{changed_routes, plan_routes_for_var};
    use mt_net::{RatPubRegisterKind::*, Rules};

    fn ships(plans: &[(String, Vec<mt_net::ActionPlan>)]) -> Vec<&str> {
        let mut v: Vec<&str> = plans.iter().map(|(s, _)| s.as_str()).collect();
        v.sort();
        v
    }

    fn reg(rules: &mut Rules, ship: &str, kind: mt_net::RatPubRegisterKind) -> Vec<String> {
        let before = plan_routes_for_var(rules, "/t");
        rules.register("/t".into(), ship.into(), kind);
        let after = plan_routes_for_var(rules, "/t");
        ships(&changed_routes(&before, after, Some(ship)))
            .into_iter()
            .map(String::from)
            .collect()
    }

    fn unreg(rules: &mut Rules, ship: &str, kind: mt_net::RatPubRegisterKind) -> Vec<String> {
        let before = plan_routes_for_var(rules, "/t");
        rules.unregister("/t", ship, kind);
        let after = plan_routes_for_var(rules, "/t");
        ships(&changed_routes(&before, after, None))
            .into_iter()
            .map(String::from)
            .collect()
    }

    #[test]
    fn targeted_pushes_reach_exactly_the_changed_ships() {
        let mut r = Rules::new();
        assert_eq!(reg(&mut r, "pub", Publish), ["pub"]);
        assert_eq!(reg(&mut r, "a", Subscribe), ["a", "pub"]);
        assert_eq!(reg(&mut r, "b", Subscribe), ["b", "pub"]);
        assert_eq!(reg(&mut r, "c", Subscribe), ["c", "pub"]);
        assert_eq!(unreg(&mut r, "b", Subscribe), ["pub"]);
        assert_eq!(reg(&mut r, "a", Subscribe), ["a"]);
    }
}