Skip to main content

offline_protocol/
transport_manager.rs

1//! Transport management for multi-transport protocol.
2//!
3//! This module provides the TransportManager which manages multiple transports
4//! and uses DORS (Dynamic Offline Relay Switch) to select the optimal transport
5//! for each message.
6
7use crate::constants::{HOP_COUNT_EMA_ALPHA, LATENCY_EMA_ALPHA, OBSERVED_STATS_COMPACT_THRESHOLD};
8use crate::events::{DorsEscalationPhase, DorsEscalationReasonCode, DorsReasonCode, Event};
9use crate::telemetry::routing::{RoutingDecision, RoutingPhase, RoutingReasonCode};
10use crate::{Error, Result};
11use chrono::Utc;
12use offline_protocol_core::{Message, Username, WireCodec};
13use offline_protocol_router::{
14    display_routing_score, DorsConfig, EscalationTriggerReason, TransportScore, TransportSelector,
15};
16use offline_protocol_transport::{
17    nostr::ResolveRequest, Error as TransportError, Transport, TransportMetrics, TransportStatus,
18    TransportType,
19};
20use std::collections::{HashMap, HashSet};
21use std::sync::Arc;
22use std::time::Instant;
23use tracing::{debug, warn};
24
25/// Manages multiple transports and handles transport selection.
26pub struct TransportManager {
27    /// Available transports mapped by type.
28    ///
29    /// Transports are fully interior-mutable (every `Transport` method takes
30    /// `&self`), so they are shared as plain `Arc`s — no outer mutex
31    /// serializing sends against status/metrics reads.
32    transports: HashMap<TransportType, Arc<dyn Transport>>,
33
34    /// Current active transport.
35    current_transport: Option<TransportType>,
36
37    /// Transport selector (DORS).
38    selector: TransportSelector,
39
40    /// Locally observed delivery outcomes used to enrich transport metrics.
41    observations: HashMap<TransportType, ObservedStats>,
42
43    /// Optional callback for DORS lifecycle/decision events (OFF-258).
44    dors_event_callback: Option<Arc<dyn Fn(Event) + Send + Sync>>,
45
46    /// Optional callback for structured routing decisions. Fires alongside
47    /// every legacy `dors_event_callback` emission so the telemetry sink
48    /// receives the richer `RoutingDecision` shape while `EventCallback`
49    /// consumers continue to see the flattened `Event::Dors*` variants.
50    routing_decision_callback: Option<Arc<dyn Fn(RoutingDecision) + Send + Sync>>,
51
52    /// When `true`, every emitted [`RoutingDecision`] carries the full
53    /// per-transport [`TransportScore`] breakdown in its `scores` field.
54    /// Mirrors `TelemetryConfig::routing_diagnostic` and is toggled by
55    /// `OfflineProtocol::install_telemetry_sink`.
56    routing_diagnostic: bool,
57
58    /// Last escalation trigger event emitted (reason, time) for dedupe window.
59    last_escalation_trigger_emitted: Option<(DorsEscalationReasonCode, std::time::Instant)>,
60
61    /// Peers known to decode the binary wire codec (from their signed key
62    /// package). Messages addressed to a listed peer are stamped
63    /// [`WireCodec::BinaryV1`] at send; all others stay JSON.
64    peer_binary_wire: HashSet<String>,
65
66    /// Host-reported battery level for this device, if the platform publishes
67    /// one. Merged into every transport's metrics that does not report its own
68    /// — see [`TransportManager::set_device_battery`].
69    device_battery: Option<u8>,
70
71    /// Host-reported charging state, applied alongside [`Self::device_battery`].
72    device_is_charging: bool,
73}
74
75/// Carriers whose links are peer-to-peer, in the order a forwarding caller
76/// should prefer them.
77///
78/// These are the only transports that can carry a *mesh hop*: a frame handed
79/// straight to a neighbor's radio. Wi-Fi Direct leads because a link that
80/// exists at all is the higher-bandwidth one; BLE is the carrier that is
81/// almost always present. Everything else reaches peers through
82/// infrastructure, which is not a hop — it is an exit from the mesh.
83const MESH_TRANSPORTS: &[TransportType] = &[TransportType::WiFiDirect, TransportType::BLE];
84
85/// A peer reachable over a direct mesh link.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct MeshNeighbor {
88    /// User-level id of the neighbor.
89    pub peer_id: String,
90    /// Signal strength for the link, when the carrier measures one.
91    pub rssi: Option<i16>,
92    /// The carrier holding the link.
93    pub transport: TransportType,
94}
95
96impl MeshNeighbor {
97    /// How good this link is, on a 0–100 scale.
98    ///
99    /// Derived from signal strength where the carrier reports it, and a
100    /// mid-scale value where it does not — an unmeasured link should not
101    /// outrank a measured good one, nor be discarded like a measured bad one.
102    pub fn link_quality(&self) -> u8 {
103        match self.rssi {
104            Some(rssi) => offline_protocol_transport::LinkQuality::from_rssi(rssi).value(),
105            None => offline_protocol_transport::DEFAULT_LINK_QUALITY_WITHOUT_RSSI,
106        }
107    }
108}
109
110/// Dedupe window: don't re-emit same escalation trigger reason within this duration.
111const ESCALATION_TRIGGER_DEDUPE_SECS: u64 = 30;
112
113/// Cap on the per-peer binary-wire capability set. Keyed by the wire-claimed
114/// peer id, so — like `key_package_sent_to` — it is cleared at capacity to bound
115/// a forged-sender flood; the only cost of forgetting a peer is re-learning its
116/// capability from the next key package (one JSON send in the meantime).
117const MAX_PEER_BINARY_WIRE_ENTRIES: usize = 4096;
118
119#[derive(Debug, Default, Clone)]
120struct ObservedStats {
121    success_count: u32,
122    failure_count: u32,
123    latency_ema: Option<f32>,
124    hop_ema: Option<f32>,
125    last_success_at: Option<Instant>,
126}
127
128impl ObservedStats {
129    fn record_success(&mut self, latency_ms: u32, hop_count: u8) {
130        self.success_count = self.success_count.saturating_add(1);
131        self.latency_ema = Some(update_ema(
132            self.latency_ema,
133            latency_ms as f32,
134            LATENCY_EMA_ALPHA,
135        ));
136        self.hop_ema = Some(update_ema(
137            self.hop_ema,
138            hop_count as f32,
139            HOP_COUNT_EMA_ALPHA,
140        ));
141        self.last_success_at = Some(Instant::now());
142        self.compact();
143    }
144
145    fn record_failure(&mut self) {
146        self.failure_count = self.failure_count.saturating_add(1);
147        self.compact();
148    }
149
150    fn compact(&mut self) {
151        let total = self.success_count.saturating_add(self.failure_count);
152        if total > OBSERVED_STATS_COMPACT_THRESHOLD {
153            self.success_count /= 2;
154            self.failure_count /= 2;
155        }
156    }
157
158    fn delivery_ratio(&self) -> Option<f32> {
159        let total = self.success_count + self.failure_count;
160        if total == 0 {
161            None
162        } else {
163            Some(self.success_count as f32 / total as f32)
164        }
165    }
166
167    fn drop_ratio(&self) -> Option<f32> {
168        self.delivery_ratio()
169            .map(|ratio| (1.0 - ratio).clamp(0.0, 1.0))
170    }
171
172    fn apply_to_metrics(&self, metrics: &mut TransportMetrics) {
173        if self.success_count + self.failure_count > 0 {
174            // Only override delivery counts when the transport itself has not
175            // reported any.  Internet transport tracks wire-level outcomes via
176            // the confirmation loop; overwriting those would discard real data.
177            //
178            // NOTE: This check is value-based, not transport-type-based.  If
179            // BLE or WiFi Direct ever start reporting their own success/failure
180            // counts from the native layer (the way Internet does via the
181            // confirmation loop), the condition below will silently skip the
182            // local observations for those transports too.  At that point,
183            // consider switching to an explicit per-transport-type check.
184            if metrics.success_count + metrics.failure_count == 0 {
185                metrics.success_count = self.success_count;
186                metrics.failure_count = self.failure_count;
187                metrics.delivery_ratio = self.delivery_ratio();
188                metrics.drop_rate = self.drop_ratio();
189            }
190        }
191
192        if let Some(latency) = self.latency_ema {
193            metrics.latency_ms = Some(latency.round().clamp(0.0, u32::MAX as f32) as u32);
194        }
195
196        if let Some(hop) = self.hop_ema {
197            metrics.average_hop_count = Some(hop);
198        }
199    }
200}
201
202fn update_ema(current: Option<f32>, new_value: f32, alpha: f32) -> f32 {
203    let alpha = alpha.clamp(0.0, 1.0);
204    match current {
205        Some(existing) => existing * (1.0 - alpha) + new_value * alpha,
206        None => new_value,
207    }
208}
209
210impl TransportManager {
211    /// Creates a new transport manager with default configuration.
212    pub fn new(selector: TransportSelector) -> Self {
213        Self {
214            transports: HashMap::new(),
215            current_transport: None,
216            selector,
217            observations: HashMap::new(),
218            dors_event_callback: None,
219            routing_decision_callback: None,
220            routing_diagnostic: false,
221            last_escalation_trigger_emitted: None,
222            peer_binary_wire: HashSet::new(),
223            device_battery: None,
224            device_is_charging: false,
225        }
226    }
227
228    /// Records the host's battery reading for this device.
229    ///
230    /// Battery is a property of the *device*, not of any one radio, but every
231    /// consumer inside the SDK reads it from the per-transport
232    /// [`TransportMetrics`] map: DORS energy scoring, the relay
233    /// promote/demote policy, the forwarding battery floor, and the telemetry
234    /// device-capability snapshot all resolve it through
235    /// `device_battery_from_available`. This setter is therefore the single
236    /// host-facing feed, and it is merged into the two snapshot loops that
237    /// build that map.
238    ///
239    /// `level` is clamped to 0-100. A transport that reports its own battery
240    /// level keeps it: the merge fills the field, never overwrites it.
241    pub fn set_device_battery(&mut self, level: u8, is_charging: bool) {
242        self.device_battery = Some(level.min(100));
243        self.device_is_charging = is_charging;
244    }
245
246    /// Returns the host-reported `(battery_level, is_charging)` pair, if the
247    /// platform has published one.
248    pub fn device_battery(&self) -> (Option<u8>, bool) {
249        (self.device_battery, self.device_is_charging)
250    }
251
252    /// Fills the device-level battery fields on one transport's metrics.
253    ///
254    /// **Fill-if-absent, never overwrite.** A transport that publishes its own
255    /// `battery_level` is reporting something the host feed cannot know better
256    /// (a peripheral's own cell, say), so its reading wins; the host value is
257    /// the fallback for the ordinary case where no transport reports one at
258    /// all. `is_charging` is only applied alongside a battery level that came
259    /// from the host, so a transport's own (level, charging) pair is never
260    /// split across two sources — the same coherence rule
261    /// `device_battery_from_available` applies when choosing between
262    /// transports.
263    fn apply_device_battery(&self, metrics: &mut TransportMetrics) {
264        let Some(level) = self.device_battery else {
265            return;
266        };
267        if metrics.battery_level.is_none() {
268            metrics.battery_level = Some(level);
269            metrics.is_charging = self.device_is_charging;
270        }
271    }
272
273    /// Returns whether a peer is recorded as able to decode the binary wire
274    /// codec (and would therefore be sent binary frames).
275    pub fn peer_supports_binary_wire(&self, peer_id: &str) -> bool {
276        self.peer_binary_wire.contains(peer_id)
277    }
278
279    /// Records whether a peer can decode our binary wire frames, learned from
280    /// its signed key package. Messages addressed to a capable peer are stamped
281    /// [`WireCodec::BinaryV1`] at send; all others stay JSON.
282    pub fn mark_peer_binary_wire(&mut self, peer_id: &str, supported: bool) {
283        if supported {
284            // Bound the wire-keyed set: clear at capacity, then insert.
285            if !self.peer_binary_wire.contains(peer_id)
286                && self.peer_binary_wire.len() >= MAX_PEER_BINARY_WIRE_ENTRIES
287            {
288                self.peer_binary_wire.clear();
289            }
290            self.peer_binary_wire.insert(peer_id.to_string());
291        } else {
292            self.peer_binary_wire.remove(peer_id);
293        }
294    }
295
296    /// Forwards a peer's advertised Nostr public key to the Nostr transport, so
297    /// gift wraps addressed to them are sealed to a key only their install
298    /// holds instead of to the publicly computable bootstrap key.
299    ///
300    /// `None` means "this peer advertises no Nostr key", which **forgets** any
301    /// key already held rather than leaving it in place. That is what keeps the
302    /// in-memory copy consistent with the durable record, whose downgrade
303    /// semantics delete on an empty advertisement: retaining it here instead
304    /// would keep sealing to a key the peer has stopped claiming, and survive
305    /// only until the next restart — a divergence with no symptom.
306    ///
307    /// A no-op when the Nostr transport is not installed (the common case —
308    /// `nostr_enabled` defaults off). The bound on the underlying map lives in
309    /// the transport.
310    pub fn mark_peer_nostr_pubkey(&mut self, peer_id: &str, pubkey_hex: Option<&str>) {
311        let Some(transport) = self.transports.get(&TransportType::Nostr) else {
312            return;
313        };
314        if let Some(nostr) = transport
315            .as_any()
316            .downcast_ref::<offline_protocol_transport::nostr::NostrTransport>()
317        {
318            match pubkey_hex {
319                Some(pubkey_hex) => nostr.set_peer_nostr_pubkey(peer_id, pubkey_hex),
320                None => nostr.forget_peer_nostr_pubkey(peer_id),
321            }
322        }
323    }
324
325    /// Forgets a peer's Nostr public key, so frames to them revert to the
326    /// publicly computable bootstrap key.
327    ///
328    /// Used by the unblock clean slate, which declares everything learned about
329    /// a peer stale. Reverting is the right fallback rather than refusing to
330    /// send: the bootstrap key is derived from the peer's user id, so it works
331    /// whatever install they are on now.
332    pub fn clear_peer_nostr_pubkey(&mut self, peer_id: &str) {
333        if let Some(nostr) = self.transports.get(&TransportType::Nostr).and_then(|t| {
334            t.as_any()
335                .downcast_ref::<offline_protocol_transport::nostr::NostrTransport>()
336        }) {
337            nostr.forget_peer_nostr_pubkey(peer_id);
338        }
339    }
340
341    /// This install's Nostr public key, for advertising in outgoing key
342    /// packages. `None` when the Nostr transport is not installed.
343    pub fn nostr_public_key(&self) -> Option<String> {
344        self.transports
345            .get(&TransportType::Nostr)?
346            .as_any()
347            .downcast_ref::<offline_protocol_transport::nostr::NostrTransport>()
348            .map(|nostr| nostr.public_key_hex())
349    }
350
351    /// Applies the sealed-envelope kill switch to the Nostr transport.
352    pub fn set_nostr_sealing_enabled(&mut self, enabled: bool) {
353        if let Some(nostr) = self.transports.get(&TransportType::Nostr).and_then(|t| {
354            t.as_any()
355                .downcast_ref::<offline_protocol_transport::nostr::NostrTransport>()
356        }) {
357            nostr.set_sealing_enabled(enabled);
358        }
359    }
360
361    /// Applies the cold-contact kill switch to the Nostr transport.
362    pub fn set_nostr_cold_contact_enabled(&mut self, enabled: bool) {
363        if let Some(nostr) = self.nostr_transport() {
364            nostr.set_cold_contact_enabled(enabled);
365        }
366    }
367
368    /// Queues a key-package record for publication at `slot_id`.
369    ///
370    /// A no-op when the Nostr transport is not installed, which is the common
371    /// case: publication is driven from the engine's tick, and that tick runs
372    /// whether or not Nostr is enabled.
373    ///
374    /// Serializes through the transport's own chokepoint, which yields JSON for
375    /// an unstamped message — and a published record must never be anything
376    /// else. The binary codec is negotiated per peer from that peer's key
377    /// package, and the reader of this record is by definition a stranger whose
378    /// key package we have not seen. Emitting binary here would make the record
379    /// unreadable by exactly the audience it exists for.
380    pub fn publish_nostr_key_package(&mut self, slot_id: &str, message: &Message) -> Result<()> {
381        let Some(nostr) = self.nostr_transport() else {
382            return Ok(());
383        };
384        let payload = nostr.serialize_message(message)?;
385        nostr.publish_key_package(slot_id, payload);
386        Ok(())
387    }
388
389    /// Drains the slot ids whose publication never reached a relay.
390    ///
391    /// Empty when Nostr is not installed, which keeps the caller's tick free of
392    /// a transport check it would otherwise need.
393    pub fn take_failed_nostr_publications(&self) -> Vec<String> {
394        self.nostr_transport()
395            .map(|nostr| nostr.take_failed_publications())
396            .unwrap_or_default()
397    }
398
399    /// Whether the Nostr transport is installed and publishing records.
400    pub fn nostr_cold_contact_active(&self) -> bool {
401        self.nostr_transport()
402            .map(|nostr| nostr.cold_contact_enabled())
403            .unwrap_or(false)
404    }
405
406    /// Enables or disables username discovery on the Nostr transport.
407    pub fn set_nostr_username_discovery_enabled(&mut self, enabled: bool) {
408        if let Some(nostr) = self.nostr_transport() {
409            nostr.set_discovery_enabled(enabled);
410        }
411    }
412
413    /// Whether the Nostr transport is installed and username discovery is on.
414    ///
415    /// Already accounts for the cold-contact coupling: the transport reports
416    /// false when either switch is off.
417    pub fn nostr_discovery_active(&self) -> bool {
418        self.nostr_transport()
419            .map(|nostr| nostr.discovery_enabled())
420            .unwrap_or(false)
421    }
422
423    /// Queues this install's username claim for publication.
424    pub fn publish_nostr_discovery_record(&mut self, username: Username, payload: Vec<u8>) {
425        if let Some(nostr) = self.nostr_transport() {
426            nostr.publish_discovery_record(username, payload);
427        }
428    }
429
430    /// Queues a retraction of this install's username claim.
431    pub fn retract_nostr_discovery_record(&mut self, username: Username, payload: Vec<u8>) {
432        if let Some(nostr) = self.nostr_transport() {
433            nostr.retract_discovery_record(username, payload);
434        }
435    }
436
437    /// Drains the discovery tags whose publication never reached a relay.
438    pub fn take_failed_nostr_discovery_publications(&self) -> Vec<String> {
439        self.nostr_transport()
440            .map(|nostr| nostr.take_failed_discovery_publications())
441            .unwrap_or_default()
442    }
443
444    /// Drains the discovery tags whose publication a relay acknowledged.
445    pub fn take_confirmed_nostr_discovery_publications(&self) -> Vec<String> {
446        self.nostr_transport()
447            .map(|nostr| nostr.take_confirmed_discovery_publications())
448            .unwrap_or_default()
449    }
450
451    /// Whether a Nostr transport is installed at all.
452    ///
453    /// Distinct from [`Self::nostr_discovery_active`]: a retraction is owed
454    /// whether or not discovery is still switched on, so the engine has to be
455    /// able to tell "the feature is off" from "there is nothing here that could
456    /// carry a tombstone". Without the second, queueing a retraction silently
457    /// does nothing while the engine records it as done.
458    pub fn has_nostr_transport(&self) -> bool {
459        self.nostr_transport().is_some()
460    }
461
462    /// Requests resolution of the devices claiming `username`.
463    ///
464    /// A missing Nostr transport reports `Disabled`, which is what it is from
465    /// the caller's side: no query was sent and no event will follow.
466    pub fn resolve_nostr_username(&self, username: Username) -> ResolveRequest {
467        self.nostr_transport()
468            .map(|nostr| nostr.resolve_username(username))
469            .unwrap_or(ResolveRequest::Disabled)
470    }
471
472    /// Withdraws a queued username lookup that was never issued to a relay.
473    ///
474    /// Returns whether one was removed. Called when the engine gives up on a
475    /// lookup, so the name does not sit in the queue making every later request
476    /// for it return "already queued" without ever answering.
477    pub fn cancel_nostr_username_resolution(&self, username: &Username) -> bool {
478        self.nostr_transport()
479            .map(|nostr| nostr.cancel_username_resolution(username))
480            .unwrap_or(false)
481    }
482
483    fn nostr_transport(&self) -> Option<&offline_protocol_transport::nostr::NostrTransport> {
484        self.transports.get(&TransportType::Nostr).and_then(|t| {
485            t.as_any()
486                .downcast_ref::<offline_protocol_transport::nostr::NostrTransport>()
487        })
488    }
489
490    /// Sets the callback for DORS decision events (dors_score_updated, dors_transport_selected,
491    pub fn set_dors_event_callback(&mut self, callback: Option<Arc<dyn Fn(Event) + Send + Sync>>) {
492        self.dors_event_callback = callback;
493    }
494
495    /// Sets the callback that receives structured
496    /// [`crate::telemetry::RoutingDecision`] records.
497    ///
498    /// Fires at the same sites as `dors_event_callback`, carrying a richer
499    /// shape suitable for the unified telemetry sink.
500    ///
501    /// Crate-private: the callback is installed together with the telemetry
502    /// sink (`OfflineProtocol::enable_telemetry` installs the pipe's) and is
503    /// never wired directly, which keeps
504    /// [`crate::telemetry::TelemetryConfig`] the single source of truth for
505    /// its configuration.
506    pub(crate) fn set_routing_decision_callback(
507        &mut self,
508        callback: Option<Arc<dyn Fn(RoutingDecision) + Send + Sync>>,
509    ) {
510        self.routing_decision_callback = callback;
511    }
512
513    /// Enables or disables the routing-diagnostic detail level.
514    ///
515    /// When `true`, [`RoutingDecision::scores`] is populated with the full
516    /// seven-factor [`TransportScore`] for every ranked transport on every
517    /// emission. When `false` (default), the vector is empty and the hot
518    /// path avoids the per-emission allocation. Mirrors
519    /// `TelemetryConfig::routing_diagnostic`.
520    ///
521    /// Crate-private: see [`Self::set_routing_decision_callback`].
522    pub(crate) fn set_routing_diagnostic(&mut self, enabled: bool) {
523        self.routing_diagnostic = enabled;
524    }
525
526    fn emit_dors_event(&self, event: Event) {
527        if let Some(ref cb) = self.dors_event_callback {
528            cb(event);
529        }
530    }
531
532    /// Lazy-emit a [`RoutingDecision`]. The `build` closure only runs when a
533    /// callback is actually installed, so the no-sink path pays only an
534    /// `Option::is_some` check — not a `Utc::now()` call and struct build.
535    fn emit_routing_decision<F: FnOnce() -> RoutingDecision>(&self, build: F) {
536        if let Some(ref cb) = self.routing_decision_callback {
537            cb(build());
538        }
539    }
540
541    fn escalation_trigger_reason_to_code(r: EscalationTriggerReason) -> DorsEscalationReasonCode {
542        match r {
543            EscalationTriggerReason::RetryThreshold => DorsEscalationReasonCode::RetryThreshold,
544            EscalationTriggerReason::PoorSignal => DorsEscalationReasonCode::PoorSignal,
545            EscalationTriggerReason::Congestion => DorsEscalationReasonCode::Congestion,
546            EscalationTriggerReason::LowTtl => DorsEscalationReasonCode::LowTtl,
547            EscalationTriggerReason::LowSuccessRate => DorsEscalationReasonCode::LowSuccessRate,
548        }
549    }
550
551    fn dors_reason_code_to_routing(code: DorsReasonCode) -> RoutingReasonCode {
552        match code {
553            DorsReasonCode::InitialSelection => RoutingReasonCode::InitialSelection,
554            DorsReasonCode::PrimarySelected => RoutingReasonCode::PrimarySelected,
555            DorsReasonCode::PrimarySuccess => RoutingReasonCode::PrimarySuccess,
556            DorsReasonCode::FallbackSuccess => RoutingReasonCode::FallbackSuccess,
557            DorsReasonCode::EscalationApplied => RoutingReasonCode::EscalationApplied,
558            DorsReasonCode::CurrentUnavailable => RoutingReasonCode::CurrentUnavailable,
559        }
560    }
561
562    fn escalation_reason_code_to_routing(code: DorsEscalationReasonCode) -> RoutingReasonCode {
563        match code {
564            DorsEscalationReasonCode::FallbackSuccess => RoutingReasonCode::FallbackSuccess,
565            DorsEscalationReasonCode::RetryThreshold => RoutingReasonCode::RetryThreshold,
566            DorsEscalationReasonCode::PoorSignal => RoutingReasonCode::PoorSignal,
567            DorsEscalationReasonCode::Congestion => RoutingReasonCode::Congestion,
568            DorsEscalationReasonCode::LowTtl => RoutingReasonCode::LowTtl,
569            DorsEscalationReasonCode::LowSuccessRate => RoutingReasonCode::LowSuccessRate,
570        }
571    }
572
573    /// Builds a [`RoutingDecision`]. The `detailed_scores` slice is cloned
574    /// into `scores` when `routing_diagnostic` is enabled on the manager;
575    /// otherwise the vector stays empty (allocation-free).
576    ///
577    /// Takes `now_ms` by argument rather than calling `Utc::now()` per
578    /// build so every decision emitted from a single `send()` cycle shares
579    /// one timestamp — easier to correlate downstream and saves three to
580    /// four syscalls on the send hot path.
581    #[allow(clippy::too_many_arguments)]
582    fn build_routing_decision(
583        &self,
584        now_ms: i64,
585        phase: RoutingPhase,
586        from: Option<TransportType>,
587        to: Option<TransportType>,
588        winning_score: Option<f32>,
589        reason_code: Option<RoutingReasonCode>,
590        detailed_scores: Option<&[(TransportType, TransportScore)]>,
591    ) -> RoutingDecision {
592        // Sanitize the internal fallback-demotion sentinel out of every score
593        // that leaves the engine. DORS keeps Internet's `total` negative to rank
594        // it last; telemetry/UniFFI consumers must see the real 0–125 quality
595        // score instead. This is the single chokepoint for all RoutingDecision
596        // emitters, so `winning_score` is also sanitized here defensively
597        // (idempotent for an already-positive value).
598        let scores = match (self.routing_diagnostic, detailed_scores) {
599            (true, Some(detailed)) => detailed
600                .iter()
601                .map(|(t, s)| {
602                    let mut s = s.clone();
603                    s.total = display_routing_score(s.total);
604                    (*t, s)
605                })
606                .collect(),
607            _ => Vec::new(),
608        };
609        RoutingDecision {
610            timestamp_ms: now_ms,
611            phase,
612            from,
613            to,
614            winning_score: winning_score.map(display_routing_score),
615            reason_code,
616            scores,
617        }
618    }
619
620    /// Emit dors_escalation_triggered at trigger boundary (typed reason), deduped by reason + time window.
621    fn emit_escalation_trigger_if_deduped(
622        &mut self,
623        now_ms: i64,
624        reason_code: DorsEscalationReasonCode,
625        from: TransportType,
626        to: TransportType,
627        reason_detail: Option<String>,
628        detailed_scores: Option<&[(TransportType, TransportScore)]>,
629    ) {
630        let now = std::time::Instant::now();
631        let emit = match &self.last_escalation_trigger_emitted {
632            Some((last_code, last_at)) => {
633                *last_code != reason_code
634                    || last_at.elapsed().as_secs() >= ESCALATION_TRIGGER_DEDUPE_SECS
635            }
636            None => true,
637        };
638        if emit {
639            self.last_escalation_trigger_emitted = Some((reason_code, now));
640            self.emit_dors_event(Event::dors_escalation_triggered(
641                DorsEscalationPhase::Triggered,
642                from.to_string(),
643                to.to_string(),
644                reason_code,
645                reason_detail,
646            ));
647            self.emit_routing_decision(|| {
648                self.build_routing_decision(
649                    now_ms,
650                    RoutingPhase::Escalated,
651                    Some(from),
652                    Some(to),
653                    None,
654                    Some(Self::escalation_reason_code_to_routing(reason_code)),
655                    detailed_scores,
656                )
657            });
658        }
659    }
660
661    /// Adds a transport to the manager.
662    ///
663    /// # Arguments
664    ///
665    /// * `transport_type` - Type of transport to add
666    /// * `transport` - The transport implementation
667    pub fn add_transport(&mut self, transport_type: TransportType, transport: Box<dyn Transport>) {
668        self.transports.insert(transport_type, Arc::from(transport));
669    }
670
671    /// Sends a message through the best available transport, with fallback.
672    ///
673    /// DORS selects a primary transport (applying hysteresis, cooldown, and
674    /// stability checks). If the primary's `send()` fails synchronously, the
675    /// remaining transports are tried in descending score order before
676    /// returning an error. Each synchronous failure is recorded via
677    /// `record_retry_failure` so DORS can adjust future scoring.
678    ///
679    /// # Internet transport — fallback does NOT apply
680    ///
681    /// Internet `send()` enqueues the message and returns `Ok(())`
682    /// immediately. The actual wire-level outcome is reported asynchronously
683    /// via the `confirm_sent` / `report_send_failure` confirmation loop on
684    /// `InternetTransport`. Because `send()` never fails synchronously, the
685    /// fallback loop below will **not** trigger for Internet. If the
686    /// WebSocket is silently broken (status still `Available` but sends
687    /// fail), messages will be enqueued, detected as failures by the
688    /// confirmation-loop timeout, and counted in DORS metrics — but they
689    /// are **not** retried on an alternative transport by this method.
690    /// Retry/re-routing for those messages is handled by the higher-level
691    /// outbox retry mechanism.
692    pub fn send(&mut self, message: &Message) -> Result<()> {
693        // Stamp the negotiated wire codec for this recipient. The clone happens
694        // only on the binary path (peers known to support it); JSON and unknown
695        // peers reuse the borrowed message. The internet transport ignores the
696        // stamp (its relay bridge is JSON-only), and mesh transports only ever
697        // emit to a recipient that is a directly connected peer, so `recipient`
698        // is the physical peer whose capability was recorded — keying by it
699        // matches the same peer-string the MTU path already keys by.
700        //
701        // The codec travels on the message, and both `Transport::send` and this
702        // method take `&Message` as public API, so carrying the stamp across
703        // that boundary needs an owned message — hence this clone. Note it is a
704        // full-message clone: it copies `binary_content` (up to the max message
705        // size), not just the envelope, so for media-sized payloads sent to a
706        // binary-capable peer it is a real payload memcpy on the hot path. It is
707        // a deliberate tradeoff: threading the codec as a separate argument would
708        // shave the clone but is a breaking change to the public `Transport`
709        // trait every downstream implementor relies on. The transport's own
710        // queue-clone is unaffected either way. If profiling ever flags this,
711        // stamp via a lightweight wrapper rather than cloning the payload.
712        let stamped = self.stamp_negotiated_wire_codec(message);
713        let message = stamped.as_ref().unwrap_or(message);
714
715        let available = self.get_available_transports();
716        if available.is_empty() {
717            return Err(Error::Transport(TransportError::TransportNotAvailable(
718                "No available transport".to_string(),
719            )));
720        }
721
722        // Single timestamp shared by every RoutingDecision emitted from this
723        // send cycle — cheaper than per-emit `Utc::now()` and lets downstream
724        // consumers group decisions by timestamp.
725        let now_ms = Utc::now().timestamp_millis();
726
727        let previous = self.current_transport;
728
729        // DORS selects the primary transport (applies hysteresis/cooldown/stability).
730        let primary = self
731            .selector
732            .select_transport(message, &available)
733            .ok_or_else(|| {
734                Error::Transport(TransportError::TransportNotAvailable(
735                    "No suitable transport selected from available transports".to_string(),
736                ))
737            })?;
738
739        // Emit DORS observability: scores and selection (before send attempt).
740        // At the default (non-diagnostic) tier we project the detailed
741        // breakdown down to `(transport, total)` — a single scoring pass
742        // feeds both the legacy event and the routing record.
743        let detailed_scores: Option<Vec<(TransportType, TransportScore)>> =
744            if self.routing_diagnostic && self.routing_decision_callback.is_some() {
745                Some(self.selector.score_and_rank_detailed(message, &available))
746            } else {
747                None
748            };
749        let detailed_slice = detailed_scores.as_deref();
750        let scored: Vec<(TransportType, f32)> = match detailed_slice {
751            Some(d) => d.iter().map(|(t, s)| (*t, s.total)).collect(),
752            None => self.selector.score_and_rank(message, &available),
753        };
754        // Sanitize the fallback-demotion sentinel out of the emitted scores (the
755        // `scored` vec itself keeps the raw totals — the fallback loop below
756        // relies on Internet ranking last).
757        let scores: Vec<(String, f32)> = scored
758            .iter()
759            .map(|(t, s)| (t.to_string(), display_routing_score(*s)))
760            .collect();
761        self.emit_dors_event(Event::dors_score_updated(scores));
762
763        self.emit_routing_decision(|| {
764            self.build_routing_decision(
765                now_ms,
766                RoutingPhase::ScoreUpdated,
767                previous,
768                None,
769                None,
770                None,
771                detailed_slice,
772            )
773        });
774        // Telemetry-only; sanitize the fallback-demotion sentinel so the emitted
775        // selection score is the real 0–125 quality value, not the negative rank.
776        let primary_score = scored
777            .iter()
778            .find(|(t, _)| *t == primary)
779            .map(|(_, s)| display_routing_score(*s))
780            .unwrap_or(0.0);
781        let selection_reason = if previous.is_none() {
782            DorsReasonCode::InitialSelection
783        } else {
784            DorsReasonCode::PrimarySelected
785        };
786        self.emit_dors_event(Event::dors_transport_selected(
787            previous.map(|t| t.to_string()),
788            primary.to_string(),
789            selection_reason,
790            primary_score,
791        ));
792        self.emit_routing_decision(|| {
793            self.build_routing_decision(
794                now_ms,
795                RoutingPhase::Selected,
796                previous,
797                Some(primary),
798                Some(primary_score),
799                Some(Self::dors_reason_code_to_routing(selection_reason)),
800                detailed_slice,
801            )
802        });
803
804        // Try the primary transport first.
805        let primary_result = {
806            let transport = self
807                .transports
808                .get(&primary)
809                .ok_or_else(|| Error::Other(format!("Transport {:?} not found", primary)))?;
810            transport.send(message)
811        };
812
813        match primary_result {
814            Ok(()) => {
815                self.current_transport = Some(primary);
816                if previous != Some(primary) {
817                    let reason_code = if previous.is_some_and(|p| !available.contains_key(&p)) {
818                        DorsReasonCode::CurrentUnavailable
819                    } else {
820                        DorsReasonCode::PrimarySuccess
821                    };
822                    self.emit_dors_event(Event::dors_transport_switched(
823                        previous.map(|t| t.to_string()),
824                        primary.to_string(),
825                        reason_code,
826                        None,
827                    ));
828                    self.emit_routing_decision(|| {
829                        self.build_routing_decision(
830                            now_ms,
831                            RoutingPhase::Switched,
832                            previous,
833                            Some(primary),
834                            Some(primary_score),
835                            Some(Self::dors_reason_code_to_routing(reason_code)),
836                            detailed_slice,
837                        )
838                    });
839                }
840                return Ok(());
841            }
842            Err(e) => {
843                let is_peer_routing = matches!(e, TransportError::PeerNotReachable(_));
844                if is_peer_routing {
845                    debug!(
846                        transport = ?primary,
847                        error = %e,
848                        "Peer not reachable via primary transport, trying fallback"
849                    );
850                } else {
851                    warn!(
852                        transport = ?primary,
853                        error = %e,
854                        "Primary transport send failed, trying fallback"
855                    );
856                    self.selector.record_retry_failure(primary);
857                }
858            }
859        }
860
861        // Primary failed — try remaining transports in score order.
862        // Reuse the scored ranking computed above; record_retry_failure only
863        // mutates retry_counts which score_and_rank does not read.
864        let mut last_error = None;
865        let mut attempted: Vec<TransportType> = vec![primary];
866
867        for (transport_type, _score) in &scored {
868            if *transport_type == primary {
869                continue;
870            }
871
872            // Emit escalation trigger at DORS boundary (typed reason), deduped.
873            if primary == TransportType::BLE && *transport_type == TransportType::WiFiDirect {
874                if let Some(trigger_reason) = self.selector.escalation_trigger_reason() {
875                    let reason_code = Self::escalation_trigger_reason_to_code(trigger_reason);
876                    self.emit_escalation_trigger_if_deduped(
877                        now_ms,
878                        reason_code,
879                        primary,
880                        *transport_type,
881                        None,
882                        detailed_slice,
883                    );
884                }
885            }
886
887            let transport = match self.transports.get(transport_type) {
888                Some(t) => t,
889                None => continue,
890            };
891
892            attempted.push(*transport_type);
893
894            match transport.send(message) {
895                Ok(()) => {
896                    self.current_transport = Some(*transport_type);
897                    self.selector.set_current_transport(*transport_type);
898                    // Emit switch only when active transport actually changed (fallback success).
899                    if previous != Some(*transport_type) {
900                        let reason_code = if primary == TransportType::BLE
901                            && *transport_type == TransportType::WiFiDirect
902                        {
903                            DorsReasonCode::EscalationApplied
904                        } else {
905                            DorsReasonCode::FallbackSuccess
906                        };
907                        self.emit_dors_event(Event::dors_transport_switched(
908                            previous.map(|t| t.to_string()),
909                            transport_type.to_string(),
910                            reason_code,
911                            Some("primary send failed, fallback succeeded".to_string()),
912                        ));
913                        let fallback = *transport_type;
914                        self.emit_routing_decision(|| {
915                            self.build_routing_decision(
916                                now_ms,
917                                RoutingPhase::Switched,
918                                previous,
919                                Some(fallback),
920                                None,
921                                Some(Self::dors_reason_code_to_routing(reason_code)),
922                                detailed_slice,
923                            )
924                        });
925                    }
926                    // Escalation applied only when BLE→WiFi fallback actually succeeded.
927                    if primary == TransportType::BLE && *transport_type == TransportType::WiFiDirect
928                    {
929                        self.emit_dors_event(Event::dors_escalation_triggered(
930                            DorsEscalationPhase::Applied,
931                            primary.to_string(),
932                            transport_type.to_string(),
933                            DorsEscalationReasonCode::FallbackSuccess,
934                            Some("primary BLE send failed, fallback to WiFi succeeded".to_string()),
935                        ));
936                        let escalated = *transport_type;
937                        self.emit_routing_decision(|| {
938                            self.build_routing_decision(
939                                now_ms,
940                                RoutingPhase::Escalated,
941                                Some(primary),
942                                Some(escalated),
943                                None,
944                                Some(Self::escalation_reason_code_to_routing(
945                                    DorsEscalationReasonCode::FallbackSuccess,
946                                )),
947                                detailed_slice,
948                            )
949                        });
950                    }
951                    return Ok(());
952                }
953                Err(e) => {
954                    if !matches!(e, TransportError::PeerNotReachable(_)) {
955                        warn!(
956                            transport = ?transport_type,
957                            error = %e,
958                            "Fallback transport send failed, trying next"
959                        );
960                        self.selector.record_retry_failure(*transport_type);
961                    }
962                    last_error = Some(e);
963                }
964            }
965        }
966
967        let terminal_error = last_error.unwrap_or_else(|| {
968            TransportError::SendFailed(format!("All transports failed (tried {:?})", attempted))
969        });
970        Err(Error::Transport(terminal_error))
971    }
972
973    /// Sends a message via a specific transport, bypassing DORS selection.
974    ///
975    /// # Arguments
976    ///
977    /// * `message` - The message to send
978    /// * `transport_type` - The transport to use
979    ///
980    /// # Returns
981    ///
982    /// Returns Ok(()) if sent successfully, Err otherwise.
983    pub fn send_via_transport(
984        &mut self,
985        message: &Message,
986        transport_type: TransportType,
987    ) -> Result<()> {
988        let transport = self
989            .transports
990            .get(&transport_type)
991            .ok_or_else(|| Error::Other(format!("Transport {:?} not found", transport_type)))?;
992
993        if transport.status() != TransportStatus::Available {
994            return Err(Error::Other(format!(
995                "Transport {:?} is not available",
996                transport_type
997            )));
998        }
999
1000        // Preserved as `Error::Transport`, not flattened into `Error::Other`.
1001        // Flattening discarded the variant every classifier keys on —
1002        // `SessionStateError::classify` and `Protocol::is_no_carrier_error`
1003        // both answer on `Error::Transport(_)`, so on this path they saw
1004        // `Unknown`/`false` and the rendered string was the only surviving
1005        // signal. That is exactly the string that must stop being read.
1006        // Stamped exactly as `send` does. This path carries ordinary DMs
1007        // whenever a recipient is a live mesh neighbour, so skipping the stamp
1008        // would downgrade binary-capable peers to JSON on the mesh while the
1009        // DORS path kept them on binary.
1010        let stamped = self.stamp_negotiated_wire_codec(message);
1011        let message = stamped.as_ref().unwrap_or(message);
1012        transport.send(message).map_err(Error::Transport)?;
1013
1014        // Only update current transport after successful send
1015        self.current_transport = Some(transport_type);
1016
1017        Ok(())
1018    }
1019
1020    /// Lists every peer reachable over a direct mesh link, with the transport
1021    /// that link runs on.
1022    ///
1023    /// Only the peer-to-peer carriers are consulted: a mesh neighbor is one we
1024    /// can hand a frame to over our own radio, which is what makes it a
1025    /// candidate next hop. Infrastructure carriers (Internet, Nostr, Reticulum)
1026    /// reach peers through something else, so they report no links and appear
1027    /// here as nothing — a message routed through them is not taking a mesh
1028    /// hop, it is leaving the mesh.
1029    ///
1030    /// A peer visible on more than one carrier is reported once, on the first
1031    /// carrier that claims it; [`Self::send_to_neighbor`] resolves the same way,
1032    /// so the pair stay consistent.
1033    pub fn mesh_neighbors(&self) -> Vec<MeshNeighbor> {
1034        let mut neighbors: Vec<MeshNeighbor> = Vec::new();
1035
1036        for transport_type in MESH_TRANSPORTS {
1037            let Some(transport) = self.transports.get(transport_type) else {
1038                continue;
1039            };
1040            for link in transport.connected_peers() {
1041                if neighbors.iter().any(|n| n.peer_id == link.peer_id) {
1042                    continue;
1043                }
1044                neighbors.push(MeshNeighbor {
1045                    peer_id: link.peer_id,
1046                    rssi: link.rssi,
1047                    transport: *transport_type,
1048                });
1049            }
1050        }
1051
1052        neighbors
1053    }
1054
1055    /// Returns an owned copy stamped with the negotiated binary codec, when
1056    /// this recipient has one and the message is not already stamped.
1057    ///
1058    /// `None` means the borrowed message is already correct, which is the
1059    /// common case (JSON peers, unknown peers, already-stamped messages) and
1060    /// costs no allocation.
1061    ///
1062    /// Shared by every send path rather than living inline in [`Self::send`].
1063    /// The codec is negotiated per recipient, so a path that skips the stamp
1064    /// silently downgrades a binary-capable peer to JSON — a regression with no
1065    /// error and no event, visible only as larger frames on the wire.
1066    fn stamp_negotiated_wire_codec(&self, message: &Message) -> Option<Message> {
1067        if message.wire_codec() == WireCodec::BinaryV1
1068            || !self.peer_binary_wire.contains(message.recipient.as_str())
1069        {
1070            return None;
1071        }
1072        let mut stamped = message.clone();
1073        stamped.set_wire_codec(WireCodec::BinaryV1);
1074        Some(stamped)
1075    }
1076
1077    /// The mesh carrier holding a live link straight to `peer_id`, if any.
1078    ///
1079    /// Ordered by mesh-carrier preference, so a peer reachable over both answers
1080    /// with the higher-bandwidth carrier. This is ground truth rather than a
1081    /// claim: it is read from the transport's live link view at the moment it
1082    /// is asked, never remembered.
1083    pub fn mesh_transport_for(&self, peer_id: &str) -> Option<TransportType> {
1084        MESH_TRANSPORTS.iter().copied().find(|transport_type| {
1085            self.transports
1086                .get(transport_type)
1087                .filter(|transport| transport.status() == TransportStatus::Available)
1088                .is_some_and(|transport| {
1089                    transport
1090                        .connected_peers()
1091                        .iter()
1092                        .any(|link| link.peer_id == peer_id)
1093                })
1094        })
1095    }
1096
1097    /// Every available carrier that does its own routing.
1098    ///
1099    /// The enumerated form of [`Self::has_infrastructure_carrier`], for callers
1100    /// that hold a per-recipient fact and must ask each carrier separately
1101    /// rather than accepting "one of them is up" for every recipient.
1102    pub fn available_infrastructure_carriers(&self) -> Vec<TransportType> {
1103        self.transports
1104            .iter()
1105            .filter(|(transport_type, transport)| {
1106                !MESH_TRANSPORTS.contains(transport_type)
1107                    && transport.status() == TransportStatus::Available
1108            })
1109            .map(|(transport_type, _)| *transport_type)
1110            .collect()
1111    }
1112
1113    /// Whether a frame for `peer_id` can plausibly arrive without being carried
1114    /// by other devices.
1115    ///
1116    /// This exists because **a send returning `Ok` is not evidence of
1117    /// reachability**. Only BLE refuses a recipient it holds no link to; Wi-Fi
1118    /// Direct and Reticulum enqueue for any recipient and report success, so a
1119    /// frame handed to them for someone out of range is queued for a link that
1120    /// will never drain — reported as sent, silently swallowed. Anything that
1121    /// decides "the mesh has to carry this" from a send failure therefore never
1122    /// fires on a device where one of those carriers is up. Asking this instead
1123    /// keeps that decision on facts we can check.
1124    ///
1125    /// Two ways the answer is yes:
1126    ///
1127    /// - An **infrastructure** carrier is available. Internet, Nostr and
1128    ///   Reticulum do their own routing and reach peers we hold no radio link
1129    ///   to, so a direct send is a real delivery attempt. (Reticulum counts
1130    ///   here because it is a routing network in its own right — its `Ok` means
1131    ///   "accepted for routing", which is as much as any relay-style carrier
1132    ///   promises.)
1133    /// - The peer is one of our own **mesh neighbors**, so a mesh carrier can
1134    ///   hand the frame straight over.
1135    ///
1136    /// Checked in that order so the common online case costs a status scan and
1137    /// never enumerates links.
1138    ///
1139    /// **This answer is deliberately peer-blind on its first arm**, and that is
1140    /// a real limit rather than an oversight: an infrastructure carrier being up
1141    /// says nothing about whether *this* recipient is on it. Callers that hold a
1142    /// peer-specific fact must not settle for this answer — the relay's own
1143    /// `recipient_unreachable` verdict is exactly such a fact, and the park it
1144    /// drives offers the frame to the mesh regardless of what this returns (see
1145    /// `park_unreachable_dm`).
1146    pub fn can_reach_without_carrying(&self, peer_id: &str) -> bool {
1147        self.has_infrastructure_carrier() || self.mesh_can_address(peer_id)
1148    }
1149
1150    /// Whether any carrier that does its own routing is available.
1151    ///
1152    /// Peer-blind by nature: these carriers reach peers we hold no radio link
1153    /// to, so there is no per-peer link to consult. Note the status is
1154    /// bridge-reported and means "the platform says this carrier is up", not
1155    /// "the relay connection is authenticated" — a distinction that matters
1156    /// wherever this stands in for reachability.
1157    pub fn has_infrastructure_carrier(&self) -> bool {
1158        self.transports.iter().any(|(transport_type, transport)| {
1159            !MESH_TRANSPORTS.contains(transport_type)
1160                && transport.status() == TransportStatus::Available
1161        })
1162    }
1163
1164    /// Whether a mesh carrier holds a live link straight to `peer_id`.
1165    ///
1166    /// The peer-specific half of [`Self::can_reach_without_carrying`], split out
1167    /// because callers that already know infrastructure is up still need to ask
1168    /// whether the mesh can hand a frame over without anyone carrying it.
1169    pub fn mesh_can_address(&self, peer_id: &str) -> bool {
1170        self.mesh_transport_for(peer_id).is_some()
1171    }
1172
1173    /// Whether `transport_type` is a short-range carrier that can only address
1174    /// peers it holds a live link to — as opposed to an infrastructure carrier
1175    /// that does its own routing.
1176    ///
1177    /// A frame that arrived over one of these travelled either from a neighbor
1178    /// or through them, which is what makes it evidence about the route back.
1179    pub fn is_mesh_transport(transport_type: TransportType) -> bool {
1180        MESH_TRANSPORTS.contains(&transport_type)
1181    }
1182
1183    /// Whether `transport_type` can actually put a frame in front of `peer_id`.
1184    ///
1185    /// The narrower question [`Self::can_reach_without_carrying`] answers across
1186    /// every carrier, asked of one. It exists for the same reason: a transport
1187    /// returning `Ok` is not evidence the frame can arrive. A **mesh** carrier
1188    /// can only address a peer it holds a live link to, and Wi-Fi Direct
1189    /// enqueues for any recipient regardless — so a frame handed to it for
1190    /// someone several hops away is queued for a link that never drains.
1191    /// **Infrastructure** carriers do their own routing, so for them the answer
1192    /// is yes whenever they are available.
1193    ///
1194    /// Callers that would otherwise trust a preferred transport — replying on
1195    /// the link a message arrived over, above all — must ask this first, or the
1196    /// reply dies on exactly the multi-hop path that made forwarding necessary.
1197    pub fn can_address_via(&self, transport_type: TransportType, peer_id: &str) -> bool {
1198        let Some(transport) = self.transports.get(&transport_type) else {
1199            return false;
1200        };
1201        if transport.status() != TransportStatus::Available {
1202            return false;
1203        }
1204        if !MESH_TRANSPORTS.contains(&transport_type) {
1205            return true;
1206        }
1207        transport
1208            .connected_peers()
1209            .iter()
1210            .any(|link| link.peer_id == peer_id)
1211    }
1212
1213    /// Hands `message` to a specific mesh neighbor, whatever the message's own
1214    /// recipient is.
1215    ///
1216    /// This is the forwarding primitive: the frame crosses one link, to the
1217    /// peer named by `peer_id`. Because that peer is the physical target, the
1218    /// binary wire codec is negotiated against **its** capabilities rather than
1219    /// the recipient's — stamping a forwarded frame binary because the distant
1220    /// recipient supports it could put bytes a neighbor cannot decode onto that
1221    /// neighbor's link.
1222    ///
1223    /// Returns the transport the frame went out on.
1224    pub fn send_to_neighbor(&self, peer_id: &str, message: &Message) -> Result<TransportType> {
1225        let stamped;
1226        let message = if message.wire_codec() != WireCodec::BinaryV1
1227            && self.peer_binary_wire.contains(peer_id)
1228        {
1229            let mut m = message.clone();
1230            m.set_wire_codec(WireCodec::BinaryV1);
1231            stamped = m;
1232            &stamped
1233        } else if message.wire_codec() == WireCodec::BinaryV1
1234            && !self.peer_binary_wire.contains(peer_id)
1235        {
1236            // The frame arrived stamped binary (or was stamped for a different
1237            // peer) but this hop cannot decode it. Fall back to the JSON floor
1238            // rather than writing bytes the neighbor will drop.
1239            let mut m = message.clone();
1240            m.set_wire_codec(WireCodec::Json);
1241            stamped = m;
1242            &stamped
1243        } else {
1244            message
1245        };
1246
1247        let mut last_error: Option<String> = None;
1248
1249        for transport_type in MESH_TRANSPORTS {
1250            let Some(transport) = self.transports.get(transport_type) else {
1251                continue;
1252            };
1253            if transport.status() != TransportStatus::Available {
1254                continue;
1255            }
1256            match transport.send_to_peer(peer_id, message) {
1257                Ok(()) => return Ok(*transport_type),
1258                Err(e) => last_error = Some(e.to_string()),
1259            }
1260        }
1261
1262        Err(Error::Transport(TransportError::PeerNotReachable(format!(
1263            "no mesh transport holds a link to {}{}",
1264            peer_id,
1265            last_error.map(|e| format!(" ({})", e)).unwrap_or_default()
1266        ))))
1267    }
1268
1269    /// Attempts to receive a message from any transport.
1270    ///
1271    /// # Returns
1272    ///
1273    /// Returns Ok(Some((TransportType, Message))) if a message was received, Ok(None) if no message available.
1274    pub fn receive(&self) -> Result<Option<(TransportType, Message)>> {
1275        // Check all transports for messages
1276        for (transport_type, transport) in &self.transports {
1277            match transport.receive() {
1278                Ok(Some(message)) => {
1279                    debug!(
1280                        transport = ?transport_type,
1281                        sender = %message.sender,
1282                        recipient = %message.recipient,
1283                        "TransportManager found message"
1284                    );
1285                    return Ok(Some((*transport_type, message)));
1286                }
1287                Ok(None) => {
1288                    // No message from this transport, continue checking others
1289                }
1290                Err(e) => {
1291                    warn!(
1292                        transport = ?transport_type,
1293                        error = %e,
1294                        "Transport receive error"
1295                    );
1296                }
1297            }
1298        }
1299        Ok(None)
1300    }
1301
1302    /// Gets metrics for all available transports.
1303    ///
1304    /// # Returns
1305    ///
1306    /// Returns a map of transport type to metrics.
1307    pub fn get_available_transports(&self) -> HashMap<TransportType, TransportMetrics> {
1308        let mut available = HashMap::new();
1309
1310        for (transport_type, transport) in &self.transports {
1311            let maybe_metrics = {
1312                let status = transport.status();
1313                if status == TransportStatus::Available {
1314                    Some(transport.metrics())
1315                } else {
1316                    debug!(
1317                        transport = ?transport_type,
1318                        status = ?status,
1319                        "Transport excluded from available set"
1320                    );
1321                    None
1322                }
1323            };
1324
1325            if let Some(mut metrics) = maybe_metrics {
1326                if let Some(stats) = self.observations.get(transport_type) {
1327                    stats.apply_to_metrics(&mut metrics);
1328                }
1329                self.apply_device_battery(&mut metrics);
1330                available.insert(*transport_type, metrics);
1331            }
1332        }
1333
1334        available
1335    }
1336
1337    /// Gets the current active transport type.
1338    pub fn current_transport(&self) -> Option<TransportType> {
1339        self.current_transport
1340    }
1341
1342    /// Returns the current status of every registered transport, including
1343    /// those not currently [`TransportStatus::Available`].
1344    ///
1345    /// Used by the telemetry aggregator to detect state transitions; unlike
1346    /// [`TransportManager::get_available_transports`], this only reads each
1347    /// transport's status with no metrics work.
1348    pub fn get_all_transport_statuses(&self) -> HashMap<TransportType, TransportStatus> {
1349        let mut out = HashMap::with_capacity(self.transports.len());
1350        for (transport_type, transport) in &self.transports {
1351            out.insert(*transport_type, transport.status());
1352        }
1353        out
1354    }
1355
1356    /// Returns the per-transport status map AND the available-only metrics
1357    /// map in a single pass.
1358    ///
1359    /// Equivalent to calling [`Self::get_all_transport_statuses`] and
1360    /// [`Self::get_available_transports`] back-to-back, but reads each
1361    /// transport's status once instead of twice. Used by the per-tick
1362    /// telemetry aggregator.
1363    pub fn snapshot_status_and_available(
1364        &self,
1365    ) -> (
1366        HashMap<TransportType, TransportStatus>,
1367        HashMap<TransportType, TransportMetrics>,
1368    ) {
1369        let mut statuses = HashMap::with_capacity(self.transports.len());
1370        let mut available = HashMap::new();
1371
1372        for (transport_type, transport) in &self.transports {
1373            let status = transport.status();
1374            let metrics = if status == TransportStatus::Available {
1375                Some(transport.metrics())
1376            } else {
1377                None
1378            };
1379            statuses.insert(*transport_type, status);
1380            if let Some(mut metrics) = metrics {
1381                if let Some(stats) = self.observations.get(transport_type) {
1382                    stats.apply_to_metrics(&mut metrics);
1383                }
1384                self.apply_device_battery(&mut metrics);
1385                available.insert(*transport_type, metrics);
1386            }
1387        }
1388
1389        (statuses, available)
1390    }
1391
1392    /// Starts all transports.
1393    pub fn start(&mut self) -> Result<()> {
1394        for (transport_type, transport) in &self.transports {
1395            transport.start().map_err(|e| {
1396                Error::Other(format!(
1397                    "Failed to start transport {:?}: {}",
1398                    transport_type, e
1399                ))
1400            })?;
1401        }
1402        Ok(())
1403    }
1404
1405    /// Stops all transports.
1406    pub fn stop(&mut self) -> Result<()> {
1407        for (transport_type, transport) in &self.transports {
1408            transport.stop().map_err(|e| {
1409                Error::Other(format!(
1410                    "Failed to stop transport {:?}: {}",
1411                    transport_type, e
1412                ))
1413            })?;
1414        }
1415        Ok(())
1416    }
1417
1418    /// Gets a shared handle to a specific transport.
1419    pub fn get_transport(&self, transport_type: TransportType) -> Option<Arc<dyn Transport>> {
1420        self.transports.get(&transport_type).cloned()
1421    }
1422
1423    /// Removes a transport from the manager.
1424    ///
1425    /// # Arguments
1426    ///
1427    /// * `transport_type` - Type of transport to remove
1428    pub fn remove_transport(&mut self, transport_type: TransportType) {
1429        self.transports.remove(&transport_type);
1430
1431        // Clear current transport if it was the one removed
1432        if self.current_transport == Some(transport_type) {
1433            self.current_transport = None;
1434        }
1435
1436        self.observations.remove(&transport_type);
1437    }
1438
1439    /// Gets a list of all active transport types.
1440    ///
1441    /// # Returns
1442    ///
1443    /// Returns a vector of transport types that are currently added to the manager.
1444    pub fn get_active_transports(&self) -> Vec<TransportType> {
1445        self.transports.keys().copied().collect()
1446    }
1447
1448    /// Checks if DORS suggests escalating from BLE to WiFi Direct.
1449    pub fn should_escalate_to_wifi(&self) -> bool {
1450        self.selector.should_escalate_to_wifi()
1451    }
1452
1453    /// Records a retry failure for the given transport.
1454    pub fn record_retry_failure(&mut self, transport_type: TransportType) {
1455        self.selector.record_retry_failure(transport_type);
1456    }
1457
1458    /// Resets retry count for the given transport after successful delivery.
1459    pub fn reset_retry_count(&mut self, transport_type: TransportType) {
1460        self.selector.reset_retry_count(transport_type);
1461    }
1462
1463    /// Records a successful end-to-end delivery for the given transport.
1464    pub fn record_delivery_success(
1465        &mut self,
1466        transport_type: TransportType,
1467        latency_ms: u32,
1468        hop_count: u8,
1469    ) {
1470        let stats = self.observations.entry(transport_type).or_default();
1471        stats.record_success(latency_ms, hop_count);
1472    }
1473
1474    /// Records a delivery failure (after exhausting retries) for the given transport.
1475    pub fn record_delivery_failure(&mut self, transport_type: TransportType) {
1476        let stats = self.observations.entry(transport_type).or_default();
1477        stats.record_failure();
1478    }
1479
1480    /// Updates the DORS selector configuration at runtime, preserving
1481    /// accumulated state (transport history, retry counts, signal tracking).
1482    pub fn update_selector_config(&mut self, config: DorsConfig) {
1483        self.selector.update_config(config);
1484    }
1485
1486    /// Returns the DORS configuration transport scoring runs against.
1487    pub fn selector_config(&self) -> &DorsConfig {
1488        self.selector.config()
1489    }
1490}
1491
1492#[cfg(test)]
1493mod tests {
1494    use super::*;
1495    use offline_protocol_core::{AppId, UserId};
1496    use offline_protocol_router::DorsConfig;
1497    use offline_protocol_transport::{mock::MockTransport, TransportType};
1498    use std::sync::Mutex;
1499
1500    fn create_test_message() -> Message {
1501        Message::new(
1502            UserId::new("alice").unwrap(),
1503            UserId::new("bob").unwrap(),
1504            AppId::new("test").unwrap(),
1505            "Test message",
1506        )
1507    }
1508
1509    #[test]
1510    fn test_transport_manager_creation() {
1511        let selector = TransportSelector::with_config(DorsConfig::default());
1512        let manager = TransportManager::new(selector);
1513        assert_eq!(manager.transports.len(), 0);
1514        assert!(manager.current_transport().is_none());
1515    }
1516
1517    #[test]
1518    fn test_add_transport() {
1519        let selector = TransportSelector::with_config(DorsConfig::default());
1520        let mut manager = TransportManager::new(selector);
1521
1522        let transport = Box::new(MockTransport::new(TransportType::BLE));
1523        manager.add_transport(TransportType::BLE, transport);
1524
1525        assert_eq!(manager.transports.len(), 1);
1526    }
1527
1528    #[test]
1529    fn test_start_stop_through_shared_transport_handle() {
1530        let selector = TransportSelector::with_config(DorsConfig::default());
1531        let mut manager = TransportManager::new(selector);
1532        manager.add_transport(
1533            TransportType::BLE,
1534            Box::new(MockTransport::new(TransportType::BLE)),
1535        );
1536
1537        // The handle shares the same transport the manager drives: start()
1538        // and stop() go through &self, no per-transport mutex involved.
1539        let handle = manager
1540            .get_transport(TransportType::BLE)
1541            .expect("transport registered");
1542        assert_eq!(handle.status(), TransportStatus::Unavailable);
1543
1544        manager.start().unwrap();
1545        assert_eq!(handle.status(), TransportStatus::Available);
1546
1547        manager.stop().unwrap();
1548        assert_eq!(handle.status(), TransportStatus::Disconnected);
1549    }
1550
1551    #[test]
1552    fn test_send_message() {
1553        let selector = TransportSelector::with_config(DorsConfig::default());
1554        let mut manager = TransportManager::new(selector);
1555
1556        let transport = MockTransport::new(TransportType::BLE);
1557        transport.start().unwrap();
1558        manager.add_transport(TransportType::BLE, Box::new(transport));
1559
1560        let message = create_test_message();
1561        let result = manager.send(&message);
1562        assert!(result.is_ok());
1563    }
1564
1565    #[test]
1566    fn send_stamps_binary_only_for_capable_peer() {
1567        let selector = TransportSelector::with_config(DorsConfig::default());
1568        let mut manager = TransportManager::new(selector);
1569        let transport = MockTransport::new(TransportType::BLE);
1570        transport.start().unwrap();
1571        manager.add_transport(TransportType::BLE, Box::new(transport));
1572
1573        // Unknown peer -> JSON (the default).
1574        manager.send(&create_test_message()).unwrap();
1575        // Peer recorded as binary-capable -> the send is stamped binary.
1576        manager.mark_peer_binary_wire("bob", true);
1577        manager.send(&create_test_message()).unwrap();
1578
1579        let mock = manager
1580            .transports
1581            .get(&TransportType::BLE)
1582            .unwrap()
1583            .as_any()
1584            .downcast_ref::<MockTransport>()
1585            .unwrap();
1586        let sent = mock.sent_messages();
1587        assert_eq!(sent.len(), 2);
1588        assert_eq!(sent[0].wire_codec(), WireCodec::Json);
1589        assert_eq!(sent[1].wire_codec(), WireCodec::BinaryV1);
1590    }
1591
1592    #[test]
1593    fn send_reverts_to_json_after_peer_downgrades() {
1594        let selector = TransportSelector::with_config(DorsConfig::default());
1595        let mut manager = TransportManager::new(selector);
1596        let transport = MockTransport::new(TransportType::BLE);
1597        transport.start().unwrap();
1598        manager.add_transport(TransportType::BLE, Box::new(transport));
1599
1600        // Learn the peer is binary-capable -> the next send is stamped binary.
1601        manager.mark_peer_binary_wire("bob", true);
1602        assert!(manager.peer_supports_binary_wire("bob"));
1603        manager.send(&create_test_message()).unwrap();
1604
1605        // A later key package that no longer advertises support downgrades the
1606        // peer (e.g. after a session reset, or the codec being turned off on
1607        // their side); subsequent sends must fall back to JSON, not keep
1608        // emitting binary a legacy build could not decode.
1609        manager.mark_peer_binary_wire("bob", false);
1610        assert!(!manager.peer_supports_binary_wire("bob"));
1611        manager.send(&create_test_message()).unwrap();
1612
1613        let mock = manager
1614            .transports
1615            .get(&TransportType::BLE)
1616            .unwrap()
1617            .as_any()
1618            .downcast_ref::<MockTransport>()
1619            .unwrap();
1620        let sent = mock.sent_messages();
1621        assert_eq!(sent.len(), 2);
1622        assert_eq!(sent[0].wire_codec(), WireCodec::BinaryV1);
1623        assert_eq!(sent[1].wire_codec(), WireCodec::Json);
1624    }
1625
1626    #[test]
1627    fn test_dors_events_emitted_when_callback_set() {
1628        let selector = TransportSelector::with_config(DorsConfig::default());
1629        let mut manager = TransportManager::new(selector);
1630
1631        let transport = MockTransport::new(TransportType::BLE);
1632        transport.start().unwrap();
1633        manager.add_transport(TransportType::BLE, Box::new(transport));
1634
1635        let events: std::sync::Arc<Mutex<Vec<Event>>> = std::sync::Arc::new(Mutex::new(Vec::new()));
1636        let events_clone = events.clone();
1637        manager.set_dors_event_callback(Some(Arc::new(move |e| {
1638            events_clone.lock().unwrap().push(e);
1639        })));
1640
1641        let message = create_test_message();
1642        let _ = manager.send(&message);
1643
1644        let captured = events.lock().unwrap();
1645        assert!(
1646            captured
1647                .iter()
1648                .any(|e| matches!(e, crate::events::Event::DorsScoreUpdated { .. })),
1649            "expected dors_score_updated"
1650        );
1651        assert!(
1652            captured
1653                .iter()
1654                .any(|e| { matches!(e, crate::events::Event::DorsTransportSelected { .. }) }),
1655            "expected dors_transport_selected"
1656        );
1657    }
1658
1659    #[test]
1660    fn test_receive_message() {
1661        let selector = TransportSelector::with_config(DorsConfig::default());
1662        let mut manager = TransportManager::new(selector);
1663
1664        let transport = MockTransport::new(TransportType::BLE);
1665        transport.start().unwrap();
1666        let message = create_test_message();
1667        transport.queue_message(message.clone());
1668
1669        manager.add_transport(TransportType::BLE, Box::new(transport));
1670
1671        let received = manager.receive().unwrap();
1672        assert!(matches!(received, Some((TransportType::BLE, _))));
1673    }
1674
1675    #[test]
1676    fn test_record_delivery_success_enriches_metrics() {
1677        let selector = TransportSelector::with_config(DorsConfig::default());
1678        let mut manager = TransportManager::new(selector);
1679
1680        let transport = MockTransport::new(TransportType::BLE);
1681        transport.start().unwrap();
1682        manager.add_transport(TransportType::BLE, Box::new(transport));
1683
1684        manager.record_delivery_success(TransportType::BLE, 150, 2);
1685
1686        let metrics = manager.get_available_transports();
1687        let ble_metrics = metrics.get(&TransportType::BLE).expect("metrics");
1688
1689        assert_eq!(ble_metrics.success_count, 1);
1690        assert_eq!(ble_metrics.failure_count, 0);
1691        assert!(ble_metrics.delivery_ratio.expect("delivery ratio") > 0.99);
1692        assert_eq!(ble_metrics.average_hop_count, Some(2.0));
1693        assert_eq!(ble_metrics.latency_ms, Some(150));
1694    }
1695
1696    #[test]
1697    fn test_record_delivery_failure_enriches_metrics() {
1698        let selector = TransportSelector::with_config(DorsConfig::default());
1699        let mut manager = TransportManager::new(selector);
1700
1701        let transport = MockTransport::new(TransportType::BLE);
1702        transport.start().unwrap();
1703        manager.add_transport(TransportType::BLE, Box::new(transport));
1704
1705        manager.record_delivery_failure(TransportType::BLE);
1706        let metrics = manager.get_available_transports();
1707        let ble_metrics = metrics.get(&TransportType::BLE).expect("metrics");
1708
1709        assert_eq!(ble_metrics.success_count, 0);
1710        assert_eq!(ble_metrics.failure_count, 1);
1711        assert!(ble_metrics.drop_rate.expect("drop ratio") > 0.99);
1712    }
1713
1714    /// Two transports, neither reporting a battery level of its own — the
1715    /// ordinary case, since no platform transport publishes one. Both must
1716    /// come back carrying the host reading, because every downstream consumer
1717    /// (DORS energy scoring, the relay role, the forwarding floor) resolves
1718    /// battery through this map and would otherwise take its unknown branch.
1719    #[test]
1720    fn test_device_battery_fills_transports_that_report_none() {
1721        let selector = TransportSelector::with_config(DorsConfig::default());
1722        let mut manager = TransportManager::new(selector);
1723
1724        for transport_type in [TransportType::BLE, TransportType::WiFiDirect] {
1725            let transport = MockTransport::new(transport_type);
1726            transport.start().unwrap();
1727            manager.add_transport(transport_type, Box::new(transport));
1728        }
1729
1730        assert_eq!(manager.device_battery(), (None, false));
1731        manager.set_device_battery(42, true);
1732        assert_eq!(manager.device_battery(), (Some(42), true));
1733
1734        let metrics = manager.get_available_transports();
1735        for transport_type in [TransportType::BLE, TransportType::WiFiDirect] {
1736            let m = metrics.get(&transport_type).expect("metrics");
1737            assert_eq!(m.battery_level, Some(42));
1738            assert!(m.is_charging);
1739        }
1740
1741        // The one-pass snapshot builds the same map and must agree with it —
1742        // the telemetry aggregator and the relay-role evaluation read this one.
1743        let (_statuses, available) = manager.snapshot_status_and_available();
1744        let m = available.get(&TransportType::BLE).expect("metrics");
1745        assert_eq!(m.battery_level, Some(42));
1746        assert!(m.is_charging);
1747    }
1748
1749    /// A transport that publishes its own battery reading keeps it, and keeps
1750    /// its own charging state with it: mixing a level from one source with a
1751    /// charging flag from another is what produces the spurious
1752    /// charging-state flips `device_battery_from_available` documents.
1753    #[test]
1754    fn test_transport_reported_battery_wins_over_device_feed() {
1755        let selector = TransportSelector::with_config(DorsConfig::default());
1756        let mut manager = TransportManager::new(selector);
1757
1758        let transport = MockTransport::new(TransportType::BLE);
1759        transport.start().unwrap();
1760        transport.set_metrics(TransportMetrics {
1761            battery_level: Some(7),
1762            is_charging: false,
1763            ..Default::default()
1764        });
1765        manager.add_transport(TransportType::BLE, Box::new(transport));
1766
1767        manager.set_device_battery(90, true);
1768
1769        let metrics = manager.get_available_transports();
1770        let m = metrics.get(&TransportType::BLE).expect("metrics");
1771        assert_eq!(m.battery_level, Some(7));
1772        assert!(!m.is_charging);
1773    }
1774
1775    #[test]
1776    fn test_device_battery_is_clamped() {
1777        let selector = TransportSelector::with_config(DorsConfig::default());
1778        let mut manager = TransportManager::new(selector);
1779        manager.set_device_battery(240, false);
1780        assert_eq!(manager.device_battery(), (Some(100), false));
1781    }
1782}