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: apps must drive routing telemetry through
502 /// [`crate::OfflineProtocol::install_telemetry_sink`] rather than wiring
503 /// the callback directly. This keeps [`crate::telemetry::TelemetryConfig`]
504 /// the single source of truth for sink configuration.
505 pub(crate) fn set_routing_decision_callback(
506 &mut self,
507 callback: Option<Arc<dyn Fn(RoutingDecision) + Send + Sync>>,
508 ) {
509 self.routing_decision_callback = callback;
510 }
511
512 /// Enables or disables the routing-diagnostic detail level.
513 ///
514 /// When `true`, [`RoutingDecision::scores`] is populated with the full
515 /// seven-factor [`TransportScore`] for every ranked transport on every
516 /// emission. When `false` (default), the vector is empty and the hot
517 /// path avoids the per-emission allocation. Mirrors
518 /// `TelemetryConfig::routing_diagnostic`.
519 ///
520 /// Crate-private: see [`Self::set_routing_decision_callback`].
521 pub(crate) fn set_routing_diagnostic(&mut self, enabled: bool) {
522 self.routing_diagnostic = enabled;
523 }
524
525 fn emit_dors_event(&self, event: Event) {
526 if let Some(ref cb) = self.dors_event_callback {
527 cb(event);
528 }
529 }
530
531 /// Lazy-emit a [`RoutingDecision`]. The `build` closure only runs when a
532 /// callback is actually installed, so the no-sink path pays only an
533 /// `Option::is_some` check — not a `Utc::now()` call and struct build.
534 fn emit_routing_decision<F: FnOnce() -> RoutingDecision>(&self, build: F) {
535 if let Some(ref cb) = self.routing_decision_callback {
536 cb(build());
537 }
538 }
539
540 fn escalation_trigger_reason_to_code(r: EscalationTriggerReason) -> DorsEscalationReasonCode {
541 match r {
542 EscalationTriggerReason::RetryThreshold => DorsEscalationReasonCode::RetryThreshold,
543 EscalationTriggerReason::PoorSignal => DorsEscalationReasonCode::PoorSignal,
544 EscalationTriggerReason::Congestion => DorsEscalationReasonCode::Congestion,
545 EscalationTriggerReason::LowTtl => DorsEscalationReasonCode::LowTtl,
546 EscalationTriggerReason::LowSuccessRate => DorsEscalationReasonCode::LowSuccessRate,
547 }
548 }
549
550 fn dors_reason_code_to_routing(code: DorsReasonCode) -> RoutingReasonCode {
551 match code {
552 DorsReasonCode::InitialSelection => RoutingReasonCode::InitialSelection,
553 DorsReasonCode::PrimarySelected => RoutingReasonCode::PrimarySelected,
554 DorsReasonCode::PrimarySuccess => RoutingReasonCode::PrimarySuccess,
555 DorsReasonCode::FallbackSuccess => RoutingReasonCode::FallbackSuccess,
556 DorsReasonCode::EscalationApplied => RoutingReasonCode::EscalationApplied,
557 DorsReasonCode::CurrentUnavailable => RoutingReasonCode::CurrentUnavailable,
558 }
559 }
560
561 fn escalation_reason_code_to_routing(code: DorsEscalationReasonCode) -> RoutingReasonCode {
562 match code {
563 DorsEscalationReasonCode::FallbackSuccess => RoutingReasonCode::FallbackSuccess,
564 DorsEscalationReasonCode::RetryThreshold => RoutingReasonCode::RetryThreshold,
565 DorsEscalationReasonCode::PoorSignal => RoutingReasonCode::PoorSignal,
566 DorsEscalationReasonCode::Congestion => RoutingReasonCode::Congestion,
567 DorsEscalationReasonCode::LowTtl => RoutingReasonCode::LowTtl,
568 DorsEscalationReasonCode::LowSuccessRate => RoutingReasonCode::LowSuccessRate,
569 }
570 }
571
572 /// Builds a [`RoutingDecision`]. The `detailed_scores` slice is cloned
573 /// into `scores` when `routing_diagnostic` is enabled on the manager;
574 /// otherwise the vector stays empty (allocation-free).
575 ///
576 /// Takes `now_ms` by argument rather than calling `Utc::now()` per
577 /// build so every decision emitted from a single `send()` cycle shares
578 /// one timestamp — easier to correlate downstream and saves three to
579 /// four syscalls on the send hot path.
580 #[allow(clippy::too_many_arguments)]
581 fn build_routing_decision(
582 &self,
583 now_ms: i64,
584 phase: RoutingPhase,
585 from: Option<TransportType>,
586 to: Option<TransportType>,
587 winning_score: Option<f32>,
588 reason_code: Option<RoutingReasonCode>,
589 detailed_scores: Option<&[(TransportType, TransportScore)]>,
590 ) -> RoutingDecision {
591 // Sanitize the internal fallback-demotion sentinel out of every score
592 // that leaves the engine. DORS keeps Internet's `total` negative to rank
593 // it last; telemetry/UniFFI consumers must see the real 0–125 quality
594 // score instead. This is the single chokepoint for all RoutingDecision
595 // emitters, so `winning_score` is also sanitized here defensively
596 // (idempotent for an already-positive value).
597 let scores = match (self.routing_diagnostic, detailed_scores) {
598 (true, Some(detailed)) => detailed
599 .iter()
600 .map(|(t, s)| {
601 let mut s = s.clone();
602 s.total = display_routing_score(s.total);
603 (*t, s)
604 })
605 .collect(),
606 _ => Vec::new(),
607 };
608 RoutingDecision {
609 timestamp_ms: now_ms,
610 phase,
611 from,
612 to,
613 winning_score: winning_score.map(display_routing_score),
614 reason_code,
615 scores,
616 }
617 }
618
619 /// Emit dors_escalation_triggered at trigger boundary (typed reason), deduped by reason + time window.
620 fn emit_escalation_trigger_if_deduped(
621 &mut self,
622 now_ms: i64,
623 reason_code: DorsEscalationReasonCode,
624 from: TransportType,
625 to: TransportType,
626 reason_detail: Option<String>,
627 detailed_scores: Option<&[(TransportType, TransportScore)]>,
628 ) {
629 let now = std::time::Instant::now();
630 let emit = match &self.last_escalation_trigger_emitted {
631 Some((last_code, last_at)) => {
632 *last_code != reason_code
633 || last_at.elapsed().as_secs() >= ESCALATION_TRIGGER_DEDUPE_SECS
634 }
635 None => true,
636 };
637 if emit {
638 self.last_escalation_trigger_emitted = Some((reason_code, now));
639 self.emit_dors_event(Event::dors_escalation_triggered(
640 DorsEscalationPhase::Triggered,
641 from.to_string(),
642 to.to_string(),
643 reason_code,
644 reason_detail,
645 ));
646 self.emit_routing_decision(|| {
647 self.build_routing_decision(
648 now_ms,
649 RoutingPhase::Escalated,
650 Some(from),
651 Some(to),
652 None,
653 Some(Self::escalation_reason_code_to_routing(reason_code)),
654 detailed_scores,
655 )
656 });
657 }
658 }
659
660 /// Adds a transport to the manager.
661 ///
662 /// # Arguments
663 ///
664 /// * `transport_type` - Type of transport to add
665 /// * `transport` - The transport implementation
666 pub fn add_transport(&mut self, transport_type: TransportType, transport: Box<dyn Transport>) {
667 self.transports.insert(transport_type, Arc::from(transport));
668 }
669
670 /// Sends a message through the best available transport, with fallback.
671 ///
672 /// DORS selects a primary transport (applying hysteresis, cooldown, and
673 /// stability checks). If the primary's `send()` fails synchronously, the
674 /// remaining transports are tried in descending score order before
675 /// returning an error. Each synchronous failure is recorded via
676 /// `record_retry_failure` so DORS can adjust future scoring.
677 ///
678 /// # Internet transport — fallback does NOT apply
679 ///
680 /// Internet `send()` enqueues the message and returns `Ok(())`
681 /// immediately. The actual wire-level outcome is reported asynchronously
682 /// via the `confirm_sent` / `report_send_failure` confirmation loop on
683 /// `InternetTransport`. Because `send()` never fails synchronously, the
684 /// fallback loop below will **not** trigger for Internet. If the
685 /// WebSocket is silently broken (status still `Available` but sends
686 /// fail), messages will be enqueued, detected as failures by the
687 /// confirmation-loop timeout, and counted in DORS metrics — but they
688 /// are **not** retried on an alternative transport by this method.
689 /// Retry/re-routing for those messages is handled by the higher-level
690 /// outbox retry mechanism.
691 pub fn send(&mut self, message: &Message) -> Result<()> {
692 // Stamp the negotiated wire codec for this recipient. The clone happens
693 // only on the binary path (peers known to support it); JSON and unknown
694 // peers reuse the borrowed message. The internet transport ignores the
695 // stamp (its relay bridge is JSON-only), and mesh transports only ever
696 // emit to a recipient that is a directly connected peer, so `recipient`
697 // is the physical peer whose capability was recorded — keying by it
698 // matches the same peer-string the MTU path already keys by.
699 //
700 // The codec travels on the message, and both `Transport::send` and this
701 // method take `&Message` as public API, so carrying the stamp across
702 // that boundary needs an owned message — hence this clone. Note it is a
703 // full-message clone: it copies `binary_content` (up to the max message
704 // size), not just the envelope, so for media-sized payloads sent to a
705 // binary-capable peer it is a real payload memcpy on the hot path. It is
706 // a deliberate tradeoff: threading the codec as a separate argument would
707 // shave the clone but is a breaking change to the public `Transport`
708 // trait every downstream implementor relies on. The transport's own
709 // queue-clone is unaffected either way. If profiling ever flags this,
710 // stamp via a lightweight wrapper rather than cloning the payload.
711 let stamped = self.stamp_negotiated_wire_codec(message);
712 let message = stamped.as_ref().unwrap_or(message);
713
714 let available = self.get_available_transports();
715 if available.is_empty() {
716 return Err(Error::Transport(TransportError::TransportNotAvailable(
717 "No available transport".to_string(),
718 )));
719 }
720
721 // Single timestamp shared by every RoutingDecision emitted from this
722 // send cycle — cheaper than per-emit `Utc::now()` and lets downstream
723 // consumers group decisions by timestamp.
724 let now_ms = Utc::now().timestamp_millis();
725
726 let previous = self.current_transport;
727
728 // DORS selects the primary transport (applies hysteresis/cooldown/stability).
729 let primary = self
730 .selector
731 .select_transport(message, &available)
732 .ok_or_else(|| {
733 Error::Transport(TransportError::TransportNotAvailable(
734 "No suitable transport selected from available transports".to_string(),
735 ))
736 })?;
737
738 // Emit DORS observability: scores and selection (before send attempt).
739 // At the default (non-diagnostic) tier we project the detailed
740 // breakdown down to `(transport, total)` — a single scoring pass
741 // feeds both the legacy event and the routing record.
742 let detailed_scores: Option<Vec<(TransportType, TransportScore)>> =
743 if self.routing_diagnostic && self.routing_decision_callback.is_some() {
744 Some(self.selector.score_and_rank_detailed(message, &available))
745 } else {
746 None
747 };
748 let detailed_slice = detailed_scores.as_deref();
749 let scored: Vec<(TransportType, f32)> = match detailed_slice {
750 Some(d) => d.iter().map(|(t, s)| (*t, s.total)).collect(),
751 None => self.selector.score_and_rank(message, &available),
752 };
753 // Sanitize the fallback-demotion sentinel out of the emitted scores (the
754 // `scored` vec itself keeps the raw totals — the fallback loop below
755 // relies on Internet ranking last).
756 let scores: Vec<(String, f32)> = scored
757 .iter()
758 .map(|(t, s)| (t.to_string(), display_routing_score(*s)))
759 .collect();
760 self.emit_dors_event(Event::dors_score_updated(scores));
761
762 self.emit_routing_decision(|| {
763 self.build_routing_decision(
764 now_ms,
765 RoutingPhase::ScoreUpdated,
766 previous,
767 None,
768 None,
769 None,
770 detailed_slice,
771 )
772 });
773 // Telemetry-only; sanitize the fallback-demotion sentinel so the emitted
774 // selection score is the real 0–125 quality value, not the negative rank.
775 let primary_score = scored
776 .iter()
777 .find(|(t, _)| *t == primary)
778 .map(|(_, s)| display_routing_score(*s))
779 .unwrap_or(0.0);
780 let selection_reason = if previous.is_none() {
781 DorsReasonCode::InitialSelection
782 } else {
783 DorsReasonCode::PrimarySelected
784 };
785 self.emit_dors_event(Event::dors_transport_selected(
786 previous.map(|t| t.to_string()),
787 primary.to_string(),
788 selection_reason,
789 primary_score,
790 ));
791 self.emit_routing_decision(|| {
792 self.build_routing_decision(
793 now_ms,
794 RoutingPhase::Selected,
795 previous,
796 Some(primary),
797 Some(primary_score),
798 Some(Self::dors_reason_code_to_routing(selection_reason)),
799 detailed_slice,
800 )
801 });
802
803 // Try the primary transport first.
804 let primary_result = {
805 let transport = self
806 .transports
807 .get(&primary)
808 .ok_or_else(|| Error::Other(format!("Transport {:?} not found", primary)))?;
809 transport.send(message)
810 };
811
812 match primary_result {
813 Ok(()) => {
814 self.current_transport = Some(primary);
815 if previous != Some(primary) {
816 let reason_code = if previous.is_some_and(|p| !available.contains_key(&p)) {
817 DorsReasonCode::CurrentUnavailable
818 } else {
819 DorsReasonCode::PrimarySuccess
820 };
821 self.emit_dors_event(Event::dors_transport_switched(
822 previous.map(|t| t.to_string()),
823 primary.to_string(),
824 reason_code,
825 None,
826 ));
827 self.emit_routing_decision(|| {
828 self.build_routing_decision(
829 now_ms,
830 RoutingPhase::Switched,
831 previous,
832 Some(primary),
833 Some(primary_score),
834 Some(Self::dors_reason_code_to_routing(reason_code)),
835 detailed_slice,
836 )
837 });
838 }
839 return Ok(());
840 }
841 Err(e) => {
842 let is_peer_routing = matches!(e, TransportError::PeerNotReachable(_));
843 if is_peer_routing {
844 debug!(
845 transport = ?primary,
846 error = %e,
847 "Peer not reachable via primary transport, trying fallback"
848 );
849 } else {
850 warn!(
851 transport = ?primary,
852 error = %e,
853 "Primary transport send failed, trying fallback"
854 );
855 self.selector.record_retry_failure(primary);
856 }
857 }
858 }
859
860 // Primary failed — try remaining transports in score order.
861 // Reuse the scored ranking computed above; record_retry_failure only
862 // mutates retry_counts which score_and_rank does not read.
863 let mut last_error = None;
864 let mut attempted: Vec<TransportType> = vec![primary];
865
866 for (transport_type, _score) in &scored {
867 if *transport_type == primary {
868 continue;
869 }
870
871 // Emit escalation trigger at DORS boundary (typed reason), deduped.
872 if primary == TransportType::BLE && *transport_type == TransportType::WiFiDirect {
873 if let Some(trigger_reason) = self.selector.escalation_trigger_reason() {
874 let reason_code = Self::escalation_trigger_reason_to_code(trigger_reason);
875 self.emit_escalation_trigger_if_deduped(
876 now_ms,
877 reason_code,
878 primary,
879 *transport_type,
880 None,
881 detailed_slice,
882 );
883 }
884 }
885
886 let transport = match self.transports.get(transport_type) {
887 Some(t) => t,
888 None => continue,
889 };
890
891 attempted.push(*transport_type);
892
893 match transport.send(message) {
894 Ok(()) => {
895 self.current_transport = Some(*transport_type);
896 self.selector.set_current_transport(*transport_type);
897 // Emit switch only when active transport actually changed (fallback success).
898 if previous != Some(*transport_type) {
899 let reason_code = if primary == TransportType::BLE
900 && *transport_type == TransportType::WiFiDirect
901 {
902 DorsReasonCode::EscalationApplied
903 } else {
904 DorsReasonCode::FallbackSuccess
905 };
906 self.emit_dors_event(Event::dors_transport_switched(
907 previous.map(|t| t.to_string()),
908 transport_type.to_string(),
909 reason_code,
910 Some("primary send failed, fallback succeeded".to_string()),
911 ));
912 let fallback = *transport_type;
913 self.emit_routing_decision(|| {
914 self.build_routing_decision(
915 now_ms,
916 RoutingPhase::Switched,
917 previous,
918 Some(fallback),
919 None,
920 Some(Self::dors_reason_code_to_routing(reason_code)),
921 detailed_slice,
922 )
923 });
924 }
925 // Escalation applied only when BLE→WiFi fallback actually succeeded.
926 if primary == TransportType::BLE && *transport_type == TransportType::WiFiDirect
927 {
928 self.emit_dors_event(Event::dors_escalation_triggered(
929 DorsEscalationPhase::Applied,
930 primary.to_string(),
931 transport_type.to_string(),
932 DorsEscalationReasonCode::FallbackSuccess,
933 Some("primary BLE send failed, fallback to WiFi succeeded".to_string()),
934 ));
935 let escalated = *transport_type;
936 self.emit_routing_decision(|| {
937 self.build_routing_decision(
938 now_ms,
939 RoutingPhase::Escalated,
940 Some(primary),
941 Some(escalated),
942 None,
943 Some(Self::escalation_reason_code_to_routing(
944 DorsEscalationReasonCode::FallbackSuccess,
945 )),
946 detailed_slice,
947 )
948 });
949 }
950 return Ok(());
951 }
952 Err(e) => {
953 if !matches!(e, TransportError::PeerNotReachable(_)) {
954 warn!(
955 transport = ?transport_type,
956 error = %e,
957 "Fallback transport send failed, trying next"
958 );
959 self.selector.record_retry_failure(*transport_type);
960 }
961 last_error = Some(e);
962 }
963 }
964 }
965
966 let terminal_error = last_error.unwrap_or_else(|| {
967 TransportError::SendFailed(format!("All transports failed (tried {:?})", attempted))
968 });
969 Err(Error::Transport(terminal_error))
970 }
971
972 /// Sends a message via a specific transport, bypassing DORS selection.
973 ///
974 /// # Arguments
975 ///
976 /// * `message` - The message to send
977 /// * `transport_type` - The transport to use
978 ///
979 /// # Returns
980 ///
981 /// Returns Ok(()) if sent successfully, Err otherwise.
982 pub fn send_via_transport(
983 &mut self,
984 message: &Message,
985 transport_type: TransportType,
986 ) -> Result<()> {
987 let transport = self
988 .transports
989 .get(&transport_type)
990 .ok_or_else(|| Error::Other(format!("Transport {:?} not found", transport_type)))?;
991
992 if transport.status() != TransportStatus::Available {
993 return Err(Error::Other(format!(
994 "Transport {:?} is not available",
995 transport_type
996 )));
997 }
998
999 // Preserved as `Error::Transport`, not flattened into `Error::Other`.
1000 // Flattening discarded the variant every classifier keys on —
1001 // `SessionStateError::classify` and `Protocol::is_no_carrier_error`
1002 // both answer on `Error::Transport(_)`, so on this path they saw
1003 // `Unknown`/`false` and the rendered string was the only surviving
1004 // signal. That is exactly the string that must stop being read.
1005 // Stamped exactly as `send` does. This path carries ordinary DMs
1006 // whenever a recipient is a live mesh neighbour, so skipping the stamp
1007 // would downgrade binary-capable peers to JSON on the mesh while the
1008 // DORS path kept them on binary.
1009 let stamped = self.stamp_negotiated_wire_codec(message);
1010 let message = stamped.as_ref().unwrap_or(message);
1011 transport.send(message).map_err(Error::Transport)?;
1012
1013 // Only update current transport after successful send
1014 self.current_transport = Some(transport_type);
1015
1016 Ok(())
1017 }
1018
1019 /// Lists every peer reachable over a direct mesh link, with the transport
1020 /// that link runs on.
1021 ///
1022 /// Only the peer-to-peer carriers are consulted: a mesh neighbor is one we
1023 /// can hand a frame to over our own radio, which is what makes it a
1024 /// candidate next hop. Infrastructure carriers (Internet, Nostr, Reticulum)
1025 /// reach peers through something else, so they report no links and appear
1026 /// here as nothing — a message routed through them is not taking a mesh
1027 /// hop, it is leaving the mesh.
1028 ///
1029 /// A peer visible on more than one carrier is reported once, on the first
1030 /// carrier that claims it; [`Self::send_to_neighbor`] resolves the same way,
1031 /// so the pair stay consistent.
1032 pub fn mesh_neighbors(&self) -> Vec<MeshNeighbor> {
1033 let mut neighbors: Vec<MeshNeighbor> = Vec::new();
1034
1035 for transport_type in MESH_TRANSPORTS {
1036 let Some(transport) = self.transports.get(transport_type) else {
1037 continue;
1038 };
1039 for link in transport.connected_peers() {
1040 if neighbors.iter().any(|n| n.peer_id == link.peer_id) {
1041 continue;
1042 }
1043 neighbors.push(MeshNeighbor {
1044 peer_id: link.peer_id,
1045 rssi: link.rssi,
1046 transport: *transport_type,
1047 });
1048 }
1049 }
1050
1051 neighbors
1052 }
1053
1054 /// Returns an owned copy stamped with the negotiated binary codec, when
1055 /// this recipient has one and the message is not already stamped.
1056 ///
1057 /// `None` means the borrowed message is already correct, which is the
1058 /// common case (JSON peers, unknown peers, already-stamped messages) and
1059 /// costs no allocation.
1060 ///
1061 /// Shared by every send path rather than living inline in [`Self::send`].
1062 /// The codec is negotiated per recipient, so a path that skips the stamp
1063 /// silently downgrades a binary-capable peer to JSON — a regression with no
1064 /// error and no event, visible only as larger frames on the wire.
1065 fn stamp_negotiated_wire_codec(&self, message: &Message) -> Option<Message> {
1066 if message.wire_codec() == WireCodec::BinaryV1
1067 || !self.peer_binary_wire.contains(message.recipient.as_str())
1068 {
1069 return None;
1070 }
1071 let mut stamped = message.clone();
1072 stamped.set_wire_codec(WireCodec::BinaryV1);
1073 Some(stamped)
1074 }
1075
1076 /// The mesh carrier holding a live link straight to `peer_id`, if any.
1077 ///
1078 /// Ordered by mesh-carrier preference, so a peer reachable over both answers
1079 /// with the higher-bandwidth carrier. This is ground truth rather than a
1080 /// claim: it is read from the transport's live link view at the moment it
1081 /// is asked, never remembered.
1082 pub fn mesh_transport_for(&self, peer_id: &str) -> Option<TransportType> {
1083 MESH_TRANSPORTS.iter().copied().find(|transport_type| {
1084 self.transports
1085 .get(transport_type)
1086 .filter(|transport| transport.status() == TransportStatus::Available)
1087 .is_some_and(|transport| {
1088 transport
1089 .connected_peers()
1090 .iter()
1091 .any(|link| link.peer_id == peer_id)
1092 })
1093 })
1094 }
1095
1096 /// Every available carrier that does its own routing.
1097 ///
1098 /// The enumerated form of [`Self::has_infrastructure_carrier`], for callers
1099 /// that hold a per-recipient fact and must ask each carrier separately
1100 /// rather than accepting "one of them is up" for every recipient.
1101 pub fn available_infrastructure_carriers(&self) -> Vec<TransportType> {
1102 self.transports
1103 .iter()
1104 .filter(|(transport_type, transport)| {
1105 !MESH_TRANSPORTS.contains(transport_type)
1106 && transport.status() == TransportStatus::Available
1107 })
1108 .map(|(transport_type, _)| *transport_type)
1109 .collect()
1110 }
1111
1112 /// Whether a frame for `peer_id` can plausibly arrive without being carried
1113 /// by other devices.
1114 ///
1115 /// This exists because **a send returning `Ok` is not evidence of
1116 /// reachability**. Only BLE refuses a recipient it holds no link to; Wi-Fi
1117 /// Direct and Reticulum enqueue for any recipient and report success, so a
1118 /// frame handed to them for someone out of range is queued for a link that
1119 /// will never drain — reported as sent, silently swallowed. Anything that
1120 /// decides "the mesh has to carry this" from a send failure therefore never
1121 /// fires on a device where one of those carriers is up. Asking this instead
1122 /// keeps that decision on facts we can check.
1123 ///
1124 /// Two ways the answer is yes:
1125 ///
1126 /// - An **infrastructure** carrier is available. Internet, Nostr and
1127 /// Reticulum do their own routing and reach peers we hold no radio link
1128 /// to, so a direct send is a real delivery attempt. (Reticulum counts
1129 /// here because it is a routing network in its own right — its `Ok` means
1130 /// "accepted for routing", which is as much as any relay-style carrier
1131 /// promises.)
1132 /// - The peer is one of our own **mesh neighbors**, so a mesh carrier can
1133 /// hand the frame straight over.
1134 ///
1135 /// Checked in that order so the common online case costs a status scan and
1136 /// never enumerates links.
1137 ///
1138 /// **This answer is deliberately peer-blind on its first arm**, and that is
1139 /// a real limit rather than an oversight: an infrastructure carrier being up
1140 /// says nothing about whether *this* recipient is on it. Callers that hold a
1141 /// peer-specific fact must not settle for this answer — the relay's own
1142 /// `recipient_unreachable` verdict is exactly such a fact, and the park it
1143 /// drives offers the frame to the mesh regardless of what this returns (see
1144 /// `park_unreachable_dm`).
1145 pub fn can_reach_without_carrying(&self, peer_id: &str) -> bool {
1146 self.has_infrastructure_carrier() || self.mesh_can_address(peer_id)
1147 }
1148
1149 /// Whether any carrier that does its own routing is available.
1150 ///
1151 /// Peer-blind by nature: these carriers reach peers we hold no radio link
1152 /// to, so there is no per-peer link to consult. Note the status is
1153 /// bridge-reported and means "the platform says this carrier is up", not
1154 /// "the relay connection is authenticated" — a distinction that matters
1155 /// wherever this stands in for reachability.
1156 pub fn has_infrastructure_carrier(&self) -> bool {
1157 self.transports.iter().any(|(transport_type, transport)| {
1158 !MESH_TRANSPORTS.contains(transport_type)
1159 && transport.status() == TransportStatus::Available
1160 })
1161 }
1162
1163 /// Whether a mesh carrier holds a live link straight to `peer_id`.
1164 ///
1165 /// The peer-specific half of [`Self::can_reach_without_carrying`], split out
1166 /// because callers that already know infrastructure is up still need to ask
1167 /// whether the mesh can hand a frame over without anyone carrying it.
1168 pub fn mesh_can_address(&self, peer_id: &str) -> bool {
1169 self.mesh_transport_for(peer_id).is_some()
1170 }
1171
1172 /// Whether `transport_type` is a short-range carrier that can only address
1173 /// peers it holds a live link to — as opposed to an infrastructure carrier
1174 /// that does its own routing.
1175 ///
1176 /// A frame that arrived over one of these travelled either from a neighbor
1177 /// or through them, which is what makes it evidence about the route back.
1178 pub fn is_mesh_transport(transport_type: TransportType) -> bool {
1179 MESH_TRANSPORTS.contains(&transport_type)
1180 }
1181
1182 /// Whether `transport_type` can actually put a frame in front of `peer_id`.
1183 ///
1184 /// The narrower question [`Self::can_reach_without_carrying`] answers across
1185 /// every carrier, asked of one. It exists for the same reason: a transport
1186 /// returning `Ok` is not evidence the frame can arrive. A **mesh** carrier
1187 /// can only address a peer it holds a live link to, and Wi-Fi Direct
1188 /// enqueues for any recipient regardless — so a frame handed to it for
1189 /// someone several hops away is queued for a link that never drains.
1190 /// **Infrastructure** carriers do their own routing, so for them the answer
1191 /// is yes whenever they are available.
1192 ///
1193 /// Callers that would otherwise trust a preferred transport — replying on
1194 /// the link a message arrived over, above all — must ask this first, or the
1195 /// reply dies on exactly the multi-hop path that made forwarding necessary.
1196 pub fn can_address_via(&self, transport_type: TransportType, peer_id: &str) -> bool {
1197 let Some(transport) = self.transports.get(&transport_type) else {
1198 return false;
1199 };
1200 if transport.status() != TransportStatus::Available {
1201 return false;
1202 }
1203 if !MESH_TRANSPORTS.contains(&transport_type) {
1204 return true;
1205 }
1206 transport
1207 .connected_peers()
1208 .iter()
1209 .any(|link| link.peer_id == peer_id)
1210 }
1211
1212 /// Hands `message` to a specific mesh neighbor, whatever the message's own
1213 /// recipient is.
1214 ///
1215 /// This is the forwarding primitive: the frame crosses one link, to the
1216 /// peer named by `peer_id`. Because that peer is the physical target, the
1217 /// binary wire codec is negotiated against **its** capabilities rather than
1218 /// the recipient's — stamping a forwarded frame binary because the distant
1219 /// recipient supports it could put bytes a neighbor cannot decode onto that
1220 /// neighbor's link.
1221 ///
1222 /// Returns the transport the frame went out on.
1223 pub fn send_to_neighbor(&self, peer_id: &str, message: &Message) -> Result<TransportType> {
1224 let stamped;
1225 let message = if message.wire_codec() != WireCodec::BinaryV1
1226 && self.peer_binary_wire.contains(peer_id)
1227 {
1228 let mut m = message.clone();
1229 m.set_wire_codec(WireCodec::BinaryV1);
1230 stamped = m;
1231 &stamped
1232 } else if message.wire_codec() == WireCodec::BinaryV1
1233 && !self.peer_binary_wire.contains(peer_id)
1234 {
1235 // The frame arrived stamped binary (or was stamped for a different
1236 // peer) but this hop cannot decode it. Fall back to the JSON floor
1237 // rather than writing bytes the neighbor will drop.
1238 let mut m = message.clone();
1239 m.set_wire_codec(WireCodec::Json);
1240 stamped = m;
1241 &stamped
1242 } else {
1243 message
1244 };
1245
1246 let mut last_error: Option<String> = None;
1247
1248 for transport_type in MESH_TRANSPORTS {
1249 let Some(transport) = self.transports.get(transport_type) else {
1250 continue;
1251 };
1252 if transport.status() != TransportStatus::Available {
1253 continue;
1254 }
1255 match transport.send_to_peer(peer_id, message) {
1256 Ok(()) => return Ok(*transport_type),
1257 Err(e) => last_error = Some(e.to_string()),
1258 }
1259 }
1260
1261 Err(Error::Transport(TransportError::PeerNotReachable(format!(
1262 "no mesh transport holds a link to {}{}",
1263 peer_id,
1264 last_error.map(|e| format!(" ({})", e)).unwrap_or_default()
1265 ))))
1266 }
1267
1268 /// Attempts to receive a message from any transport.
1269 ///
1270 /// # Returns
1271 ///
1272 /// Returns Ok(Some((TransportType, Message))) if a message was received, Ok(None) if no message available.
1273 pub fn receive(&self) -> Result<Option<(TransportType, Message)>> {
1274 // Check all transports for messages
1275 for (transport_type, transport) in &self.transports {
1276 match transport.receive() {
1277 Ok(Some(message)) => {
1278 debug!(
1279 transport = ?transport_type,
1280 sender = %message.sender,
1281 recipient = %message.recipient,
1282 "TransportManager found message"
1283 );
1284 return Ok(Some((*transport_type, message)));
1285 }
1286 Ok(None) => {
1287 // No message from this transport, continue checking others
1288 }
1289 Err(e) => {
1290 warn!(
1291 transport = ?transport_type,
1292 error = %e,
1293 "Transport receive error"
1294 );
1295 }
1296 }
1297 }
1298 Ok(None)
1299 }
1300
1301 /// Gets metrics for all available transports.
1302 ///
1303 /// # Returns
1304 ///
1305 /// Returns a map of transport type to metrics.
1306 pub fn get_available_transports(&self) -> HashMap<TransportType, TransportMetrics> {
1307 let mut available = HashMap::new();
1308
1309 for (transport_type, transport) in &self.transports {
1310 let maybe_metrics = {
1311 let status = transport.status();
1312 if status == TransportStatus::Available {
1313 Some(transport.metrics())
1314 } else {
1315 debug!(
1316 transport = ?transport_type,
1317 status = ?status,
1318 "Transport excluded from available set"
1319 );
1320 None
1321 }
1322 };
1323
1324 if let Some(mut metrics) = maybe_metrics {
1325 if let Some(stats) = self.observations.get(transport_type) {
1326 stats.apply_to_metrics(&mut metrics);
1327 }
1328 self.apply_device_battery(&mut metrics);
1329 available.insert(*transport_type, metrics);
1330 }
1331 }
1332
1333 available
1334 }
1335
1336 /// Gets the current active transport type.
1337 pub fn current_transport(&self) -> Option<TransportType> {
1338 self.current_transport
1339 }
1340
1341 /// Returns the current status of every registered transport, including
1342 /// those not currently [`TransportStatus::Available`].
1343 ///
1344 /// Used by the telemetry aggregator to detect state transitions; unlike
1345 /// [`TransportManager::get_available_transports`], this only reads each
1346 /// transport's status with no metrics work.
1347 pub fn get_all_transport_statuses(&self) -> HashMap<TransportType, TransportStatus> {
1348 let mut out = HashMap::with_capacity(self.transports.len());
1349 for (transport_type, transport) in &self.transports {
1350 out.insert(*transport_type, transport.status());
1351 }
1352 out
1353 }
1354
1355 /// Returns the per-transport status map AND the available-only metrics
1356 /// map in a single pass.
1357 ///
1358 /// Equivalent to calling [`Self::get_all_transport_statuses`] and
1359 /// [`Self::get_available_transports`] back-to-back, but reads each
1360 /// transport's status once instead of twice. Used by the per-tick
1361 /// telemetry aggregator.
1362 pub fn snapshot_status_and_available(
1363 &self,
1364 ) -> (
1365 HashMap<TransportType, TransportStatus>,
1366 HashMap<TransportType, TransportMetrics>,
1367 ) {
1368 let mut statuses = HashMap::with_capacity(self.transports.len());
1369 let mut available = HashMap::new();
1370
1371 for (transport_type, transport) in &self.transports {
1372 let status = transport.status();
1373 let metrics = if status == TransportStatus::Available {
1374 Some(transport.metrics())
1375 } else {
1376 None
1377 };
1378 statuses.insert(*transport_type, status);
1379 if let Some(mut metrics) = metrics {
1380 if let Some(stats) = self.observations.get(transport_type) {
1381 stats.apply_to_metrics(&mut metrics);
1382 }
1383 self.apply_device_battery(&mut metrics);
1384 available.insert(*transport_type, metrics);
1385 }
1386 }
1387
1388 (statuses, available)
1389 }
1390
1391 /// Starts all transports.
1392 pub fn start(&mut self) -> Result<()> {
1393 for (transport_type, transport) in &self.transports {
1394 transport.start().map_err(|e| {
1395 Error::Other(format!(
1396 "Failed to start transport {:?}: {}",
1397 transport_type, e
1398 ))
1399 })?;
1400 }
1401 Ok(())
1402 }
1403
1404 /// Stops all transports.
1405 pub fn stop(&mut self) -> Result<()> {
1406 for (transport_type, transport) in &self.transports {
1407 transport.stop().map_err(|e| {
1408 Error::Other(format!(
1409 "Failed to stop transport {:?}: {}",
1410 transport_type, e
1411 ))
1412 })?;
1413 }
1414 Ok(())
1415 }
1416
1417 /// Gets a shared handle to a specific transport.
1418 pub fn get_transport(&self, transport_type: TransportType) -> Option<Arc<dyn Transport>> {
1419 self.transports.get(&transport_type).cloned()
1420 }
1421
1422 /// Removes a transport from the manager.
1423 ///
1424 /// # Arguments
1425 ///
1426 /// * `transport_type` - Type of transport to remove
1427 pub fn remove_transport(&mut self, transport_type: TransportType) {
1428 self.transports.remove(&transport_type);
1429
1430 // Clear current transport if it was the one removed
1431 if self.current_transport == Some(transport_type) {
1432 self.current_transport = None;
1433 }
1434
1435 self.observations.remove(&transport_type);
1436 }
1437
1438 /// Gets a list of all active transport types.
1439 ///
1440 /// # Returns
1441 ///
1442 /// Returns a vector of transport types that are currently added to the manager.
1443 pub fn get_active_transports(&self) -> Vec<TransportType> {
1444 self.transports.keys().copied().collect()
1445 }
1446
1447 /// Checks if DORS suggests escalating from BLE to WiFi Direct.
1448 pub fn should_escalate_to_wifi(&self) -> bool {
1449 self.selector.should_escalate_to_wifi()
1450 }
1451
1452 /// Records a retry failure for the given transport.
1453 pub fn record_retry_failure(&mut self, transport_type: TransportType) {
1454 self.selector.record_retry_failure(transport_type);
1455 }
1456
1457 /// Resets retry count for the given transport after successful delivery.
1458 pub fn reset_retry_count(&mut self, transport_type: TransportType) {
1459 self.selector.reset_retry_count(transport_type);
1460 }
1461
1462 /// Records a successful end-to-end delivery for the given transport.
1463 pub fn record_delivery_success(
1464 &mut self,
1465 transport_type: TransportType,
1466 latency_ms: u32,
1467 hop_count: u8,
1468 ) {
1469 let stats = self.observations.entry(transport_type).or_default();
1470 stats.record_success(latency_ms, hop_count);
1471 }
1472
1473 /// Records a delivery failure (after exhausting retries) for the given transport.
1474 pub fn record_delivery_failure(&mut self, transport_type: TransportType) {
1475 let stats = self.observations.entry(transport_type).or_default();
1476 stats.record_failure();
1477 }
1478
1479 /// Updates the DORS selector configuration at runtime, preserving
1480 /// accumulated state (transport history, retry counts, signal tracking).
1481 pub fn update_selector_config(&mut self, config: DorsConfig) {
1482 self.selector.update_config(config);
1483 }
1484
1485 /// Returns the DORS configuration transport scoring runs against.
1486 pub fn selector_config(&self) -> &DorsConfig {
1487 self.selector.config()
1488 }
1489}
1490
1491#[cfg(test)]
1492mod tests {
1493 use super::*;
1494 use offline_protocol_core::{AppId, UserId};
1495 use offline_protocol_router::DorsConfig;
1496 use offline_protocol_transport::{mock::MockTransport, TransportType};
1497 use std::sync::Mutex;
1498
1499 fn create_test_message() -> Message {
1500 Message::new(
1501 UserId::new("alice").unwrap(),
1502 UserId::new("bob").unwrap(),
1503 AppId::new("test").unwrap(),
1504 "Test message",
1505 )
1506 }
1507
1508 #[test]
1509 fn test_transport_manager_creation() {
1510 let selector = TransportSelector::with_config(DorsConfig::default());
1511 let manager = TransportManager::new(selector);
1512 assert_eq!(manager.transports.len(), 0);
1513 assert!(manager.current_transport().is_none());
1514 }
1515
1516 #[test]
1517 fn test_add_transport() {
1518 let selector = TransportSelector::with_config(DorsConfig::default());
1519 let mut manager = TransportManager::new(selector);
1520
1521 let transport = Box::new(MockTransport::new(TransportType::BLE));
1522 manager.add_transport(TransportType::BLE, transport);
1523
1524 assert_eq!(manager.transports.len(), 1);
1525 }
1526
1527 #[test]
1528 fn test_start_stop_through_shared_transport_handle() {
1529 let selector = TransportSelector::with_config(DorsConfig::default());
1530 let mut manager = TransportManager::new(selector);
1531 manager.add_transport(
1532 TransportType::BLE,
1533 Box::new(MockTransport::new(TransportType::BLE)),
1534 );
1535
1536 // The handle shares the same transport the manager drives: start()
1537 // and stop() go through &self, no per-transport mutex involved.
1538 let handle = manager
1539 .get_transport(TransportType::BLE)
1540 .expect("transport registered");
1541 assert_eq!(handle.status(), TransportStatus::Unavailable);
1542
1543 manager.start().unwrap();
1544 assert_eq!(handle.status(), TransportStatus::Available);
1545
1546 manager.stop().unwrap();
1547 assert_eq!(handle.status(), TransportStatus::Disconnected);
1548 }
1549
1550 #[test]
1551 fn test_send_message() {
1552 let selector = TransportSelector::with_config(DorsConfig::default());
1553 let mut manager = TransportManager::new(selector);
1554
1555 let transport = MockTransport::new(TransportType::BLE);
1556 transport.start().unwrap();
1557 manager.add_transport(TransportType::BLE, Box::new(transport));
1558
1559 let message = create_test_message();
1560 let result = manager.send(&message);
1561 assert!(result.is_ok());
1562 }
1563
1564 #[test]
1565 fn send_stamps_binary_only_for_capable_peer() {
1566 let selector = TransportSelector::with_config(DorsConfig::default());
1567 let mut manager = TransportManager::new(selector);
1568 let transport = MockTransport::new(TransportType::BLE);
1569 transport.start().unwrap();
1570 manager.add_transport(TransportType::BLE, Box::new(transport));
1571
1572 // Unknown peer -> JSON (the default).
1573 manager.send(&create_test_message()).unwrap();
1574 // Peer recorded as binary-capable -> the send is stamped binary.
1575 manager.mark_peer_binary_wire("bob", true);
1576 manager.send(&create_test_message()).unwrap();
1577
1578 let mock = manager
1579 .transports
1580 .get(&TransportType::BLE)
1581 .unwrap()
1582 .as_any()
1583 .downcast_ref::<MockTransport>()
1584 .unwrap();
1585 let sent = mock.sent_messages();
1586 assert_eq!(sent.len(), 2);
1587 assert_eq!(sent[0].wire_codec(), WireCodec::Json);
1588 assert_eq!(sent[1].wire_codec(), WireCodec::BinaryV1);
1589 }
1590
1591 #[test]
1592 fn send_reverts_to_json_after_peer_downgrades() {
1593 let selector = TransportSelector::with_config(DorsConfig::default());
1594 let mut manager = TransportManager::new(selector);
1595 let transport = MockTransport::new(TransportType::BLE);
1596 transport.start().unwrap();
1597 manager.add_transport(TransportType::BLE, Box::new(transport));
1598
1599 // Learn the peer is binary-capable -> the next send is stamped binary.
1600 manager.mark_peer_binary_wire("bob", true);
1601 assert!(manager.peer_supports_binary_wire("bob"));
1602 manager.send(&create_test_message()).unwrap();
1603
1604 // A later key package that no longer advertises support downgrades the
1605 // peer (e.g. after a session reset, or the codec being turned off on
1606 // their side); subsequent sends must fall back to JSON, not keep
1607 // emitting binary a legacy build could not decode.
1608 manager.mark_peer_binary_wire("bob", false);
1609 assert!(!manager.peer_supports_binary_wire("bob"));
1610 manager.send(&create_test_message()).unwrap();
1611
1612 let mock = manager
1613 .transports
1614 .get(&TransportType::BLE)
1615 .unwrap()
1616 .as_any()
1617 .downcast_ref::<MockTransport>()
1618 .unwrap();
1619 let sent = mock.sent_messages();
1620 assert_eq!(sent.len(), 2);
1621 assert_eq!(sent[0].wire_codec(), WireCodec::BinaryV1);
1622 assert_eq!(sent[1].wire_codec(), WireCodec::Json);
1623 }
1624
1625 #[test]
1626 fn test_dors_events_emitted_when_callback_set() {
1627 let selector = TransportSelector::with_config(DorsConfig::default());
1628 let mut manager = TransportManager::new(selector);
1629
1630 let transport = MockTransport::new(TransportType::BLE);
1631 transport.start().unwrap();
1632 manager.add_transport(TransportType::BLE, Box::new(transport));
1633
1634 let events: std::sync::Arc<Mutex<Vec<Event>>> = std::sync::Arc::new(Mutex::new(Vec::new()));
1635 let events_clone = events.clone();
1636 manager.set_dors_event_callback(Some(Arc::new(move |e| {
1637 events_clone.lock().unwrap().push(e);
1638 })));
1639
1640 let message = create_test_message();
1641 let _ = manager.send(&message);
1642
1643 let captured = events.lock().unwrap();
1644 assert!(
1645 captured
1646 .iter()
1647 .any(|e| matches!(e, crate::events::Event::DorsScoreUpdated { .. })),
1648 "expected dors_score_updated"
1649 );
1650 assert!(
1651 captured
1652 .iter()
1653 .any(|e| { matches!(e, crate::events::Event::DorsTransportSelected { .. }) }),
1654 "expected dors_transport_selected"
1655 );
1656 }
1657
1658 #[test]
1659 fn test_receive_message() {
1660 let selector = TransportSelector::with_config(DorsConfig::default());
1661 let mut manager = TransportManager::new(selector);
1662
1663 let transport = MockTransport::new(TransportType::BLE);
1664 transport.start().unwrap();
1665 let message = create_test_message();
1666 transport.queue_message(message.clone());
1667
1668 manager.add_transport(TransportType::BLE, Box::new(transport));
1669
1670 let received = manager.receive().unwrap();
1671 assert!(matches!(received, Some((TransportType::BLE, _))));
1672 }
1673
1674 #[test]
1675 fn test_record_delivery_success_enriches_metrics() {
1676 let selector = TransportSelector::with_config(DorsConfig::default());
1677 let mut manager = TransportManager::new(selector);
1678
1679 let transport = MockTransport::new(TransportType::BLE);
1680 transport.start().unwrap();
1681 manager.add_transport(TransportType::BLE, Box::new(transport));
1682
1683 manager.record_delivery_success(TransportType::BLE, 150, 2);
1684
1685 let metrics = manager.get_available_transports();
1686 let ble_metrics = metrics.get(&TransportType::BLE).expect("metrics");
1687
1688 assert_eq!(ble_metrics.success_count, 1);
1689 assert_eq!(ble_metrics.failure_count, 0);
1690 assert!(ble_metrics.delivery_ratio.expect("delivery ratio") > 0.99);
1691 assert_eq!(ble_metrics.average_hop_count, Some(2.0));
1692 assert_eq!(ble_metrics.latency_ms, Some(150));
1693 }
1694
1695 #[test]
1696 fn test_record_delivery_failure_enriches_metrics() {
1697 let selector = TransportSelector::with_config(DorsConfig::default());
1698 let mut manager = TransportManager::new(selector);
1699
1700 let transport = MockTransport::new(TransportType::BLE);
1701 transport.start().unwrap();
1702 manager.add_transport(TransportType::BLE, Box::new(transport));
1703
1704 manager.record_delivery_failure(TransportType::BLE);
1705 let metrics = manager.get_available_transports();
1706 let ble_metrics = metrics.get(&TransportType::BLE).expect("metrics");
1707
1708 assert_eq!(ble_metrics.success_count, 0);
1709 assert_eq!(ble_metrics.failure_count, 1);
1710 assert!(ble_metrics.drop_rate.expect("drop ratio") > 0.99);
1711 }
1712
1713 /// Two transports, neither reporting a battery level of its own — the
1714 /// ordinary case, since no platform transport publishes one. Both must
1715 /// come back carrying the host reading, because every downstream consumer
1716 /// (DORS energy scoring, the relay role, the forwarding floor) resolves
1717 /// battery through this map and would otherwise take its unknown branch.
1718 #[test]
1719 fn test_device_battery_fills_transports_that_report_none() {
1720 let selector = TransportSelector::with_config(DorsConfig::default());
1721 let mut manager = TransportManager::new(selector);
1722
1723 for transport_type in [TransportType::BLE, TransportType::WiFiDirect] {
1724 let transport = MockTransport::new(transport_type);
1725 transport.start().unwrap();
1726 manager.add_transport(transport_type, Box::new(transport));
1727 }
1728
1729 assert_eq!(manager.device_battery(), (None, false));
1730 manager.set_device_battery(42, true);
1731 assert_eq!(manager.device_battery(), (Some(42), true));
1732
1733 let metrics = manager.get_available_transports();
1734 for transport_type in [TransportType::BLE, TransportType::WiFiDirect] {
1735 let m = metrics.get(&transport_type).expect("metrics");
1736 assert_eq!(m.battery_level, Some(42));
1737 assert!(m.is_charging);
1738 }
1739
1740 // The one-pass snapshot builds the same map and must agree with it —
1741 // the telemetry aggregator and the relay-role evaluation read this one.
1742 let (_statuses, available) = manager.snapshot_status_and_available();
1743 let m = available.get(&TransportType::BLE).expect("metrics");
1744 assert_eq!(m.battery_level, Some(42));
1745 assert!(m.is_charging);
1746 }
1747
1748 /// A transport that publishes its own battery reading keeps it, and keeps
1749 /// its own charging state with it: mixing a level from one source with a
1750 /// charging flag from another is what produces the spurious
1751 /// charging-state flips `device_battery_from_available` documents.
1752 #[test]
1753 fn test_transport_reported_battery_wins_over_device_feed() {
1754 let selector = TransportSelector::with_config(DorsConfig::default());
1755 let mut manager = TransportManager::new(selector);
1756
1757 let transport = MockTransport::new(TransportType::BLE);
1758 transport.start().unwrap();
1759 transport.set_metrics(TransportMetrics {
1760 battery_level: Some(7),
1761 is_charging: false,
1762 ..Default::default()
1763 });
1764 manager.add_transport(TransportType::BLE, Box::new(transport));
1765
1766 manager.set_device_battery(90, true);
1767
1768 let metrics = manager.get_available_transports();
1769 let m = metrics.get(&TransportType::BLE).expect("metrics");
1770 assert_eq!(m.battery_level, Some(7));
1771 assert!(!m.is_charging);
1772 }
1773
1774 #[test]
1775 fn test_device_battery_is_clamped() {
1776 let selector = TransportSelector::with_config(DorsConfig::default());
1777 let mut manager = TransportManager::new(selector);
1778 manager.set_device_battery(240, false);
1779 assert_eq!(manager.device_battery(), (Some(100), false));
1780 }
1781}