Skip to main content

serialplugin_core/hub/
shared.rs

1//! Shared RX hub state (desktop poll + Android push).
2
3use crate::at::parse::{classify_final_line, is_likely_urc, ExchangeDemux, ExchangeMatch};
4use crate::cmux::CmuxSession;
5use crate::events::{EventSink, SerialEvent};
6use crate::exchange::completion::Completion;
7use crate::exchange::options::ResolvedExchangeOptions;
8use serial_codec::framing::Framer;
9use std::collections::VecDeque;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
12use std::sync::{Arc, Condvar, Mutex};
13use std::time::{Duration, Instant};
14
15pub(crate) const IDLE_BUFFER_CAP: usize = 64 * 1024;
16
17type ExchangeDone = Arc<(
18    Mutex<Option<Result<(Vec<u8>, ExchangeMatch), String>>>,
19    Condvar,
20)>;
21type ByteResultTx = SyncSender<Result<Vec<u8>, String>>;
22
23/// Actions produced when routing incoming bytes in streaming mode.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum RxRouteAction {
26    StreamData(Vec<u8>),
27    UrcLine(String),
28}
29
30/// Session waiting for an exchange to complete.
31pub struct ExchangeWaiter {
32    pub options: ResolvedExchangeOptions,
33    buffer: Mutex<(Vec<u8>, Completion)>,
34    done: ExchangeDone,
35    pub cancel: Arc<AtomicBool>,
36    /// Set by the first `finish`; later results (a late cancel / failure) are ignored.
37    finished: AtomicBool,
38}
39
40impl ExchangeWaiter {
41    pub fn new(options: ResolvedExchangeOptions, cancel: Arc<AtomicBool>) -> Arc<Self> {
42        Arc::new(Self {
43            buffer: Mutex::new((Vec::new(), Completion::new(&options))),
44            options,
45            done: Arc::new((Mutex::new(None), Condvar::new())),
46            cancel,
47            finished: AtomicBool::new(false),
48        })
49    }
50
51    pub fn push_bytes(&self, chunk: &[u8]) {
52        let mut guard = crate::sync_util::lock_or_recover(&self.buffer);
53        let (buffer, completion) = &mut *guard;
54        buffer.extend_from_slice(chunk);
55        if self.cancel.load(Ordering::SeqCst) {
56            self.finish(Err("exchange cancelled".into()));
57            return;
58        }
59        if buffer.len() >= self.options.max_bytes {
60            self.finish(Err(format!(
61                "exchange response exceeded {} bytes",
62                self.options.max_bytes
63            )));
64            return;
65        }
66        if let Some(matched) = completion.push(buffer, chunk.len()) {
67            let raw = std::mem::take(buffer);
68            *completion = Completion::new(&self.options);
69            self.finish(Ok((raw, matched)));
70        }
71    }
72
73    pub fn wait(self: &Arc<Self>, timeout_ms: u64) -> Result<(Vec<u8>, ExchangeMatch), String> {
74        let (lock, cvar) = &*self.done;
75        let mut guard = crate::sync_util::lock_or_recover(lock);
76        let deadline = Instant::now() + Duration::from_millis(timeout_ms);
77        while guard.is_none() {
78            if self.cancel.load(Ordering::SeqCst) {
79                return Err("exchange cancelled".into());
80            }
81            let remaining = deadline.saturating_duration_since(Instant::now());
82            if remaining.is_zero() {
83                return Err(format!("exchange timed out after {} ms", timeout_ms));
84            }
85            let (g, timeout) = cvar
86                .wait_timeout(guard, remaining.min(Duration::from_millis(50)))
87                .map_err(|e| e.to_string())?;
88            guard = g;
89            if guard.is_none() && timeout.timed_out() && Instant::now() >= deadline {
90                return Err(format!("exchange timed out after {} ms", timeout_ms));
91            }
92        }
93        guard.take().unwrap()
94    }
95
96    /// The first result wins: a reply that already completed is not replaced by a
97    /// cancel or failure arriving after it.
98    fn finish(&self, result: Result<(Vec<u8>, ExchangeMatch), String>) {
99        let (lock, cvar) = &*self.done;
100        let mut guard = crate::sync_util::lock_or_recover(lock);
101        if !self.finished.swap(true, Ordering::SeqCst) {
102            *guard = Some(result);
103        }
104        cvar.notify_all();
105    }
106
107    /// Fail an in-flight exchange immediately (e.g. USB error teardown).
108    pub fn fail_with_reason(&self, reason: String) {
109        self.finish(Err(reason));
110    }
111}
112
113/// Line-oriented router for streaming when no exchange is active (`route_urc`).
114///
115/// Data lines go out byte-for-byte, terminator included; only URC lines are pulled out.
116/// An unfinished line is held until the next chunk (or the batch flush), so a URC split
117/// across two reads is still recognised and UTF-8 characters are never cut in half.
118#[derive(Debug, Default)]
119pub struct LineRouter {
120    partial: Vec<u8>,
121}
122
123impl LineRouter {
124    // ponytail: splits on LF only, so outside an exchange the quoted multi-line `+CUSD`
125    // join and the glued `OK+CUSD:` peel of `serial_codec::at::split_lines` do not apply
126    // here. Reusing them needs an incremental, byte-preserving splitter exported from
127    // `at.rs` (the one in `ExchangeDemux::process_chunk` is private and returns trimmed
128    // text, while this router must forward data lines byte-for-byte).
129    pub fn route_streaming(
130        &mut self,
131        chunk: &[u8],
132        solicited_prefixes: &[String],
133    ) -> Vec<RxRouteAction> {
134        self.partial.extend_from_slice(chunk);
135        let mut actions = Vec::new();
136        while let Some(pos) = self.partial.iter().position(|&b| b == b'\n') {
137            let raw: Vec<u8> = self.partial.drain(..=pos).collect();
138            let line = String::from_utf8_lossy(&raw).trim().to_string();
139            if !line.is_empty()
140                && is_likely_urc(&line, solicited_prefixes)
141                && classify_final_line(&line).is_none()
142            {
143                actions.push(RxRouteAction::UrcLine(line));
144            } else {
145                actions.push(RxRouteAction::StreamData(raw));
146            }
147        }
148        actions
149    }
150
151    /// Unfinished line bytes (handed to the data stream on batch flush).
152    pub fn take_partial(&mut self) -> Vec<u8> {
153        std::mem::take(&mut self.partial)
154    }
155}
156
157/// An event and the sink it was produced for (captured when it was produced, so an
158/// `unwatch` racing the hub cannot drop frames that were already decoded).
159pub type QueuedEvent = (EventSink, SerialEvent);
160
161/// Ordered event delivery for one hub (or one CMUX session).
162///
163/// Sinks run with no hub or manager lock held, so a sink may call back into the
164/// manager. Events reach sinks in queue order whichever thread queued them: while the
165/// hub thread is between routing and dispatch (`begin_batch` .. `end_batch`), events
166/// queued by other threads (watch remainder on `unwatch`, `Disconnect` from a JNI
167/// callback) wait behind the hub's batch. One thread delivers at a time; a thread
168/// that finds delivery in progress leaves its events to it (also when a sink re-enters).
169#[derive(Default)]
170pub struct Outbox(Mutex<OutboxState>);
171
172#[derive(Default)]
173struct OutboxState {
174    queue: VecDeque<QueuedEvent>,
175    held: Vec<QueuedEvent>,
176    batch_open: bool,
177    delivering: bool,
178}
179
180impl Outbox {
181    /// The hub thread starts routing into its local `pending_events`.
182    fn begin_batch(&self) {
183        crate::sync_util::lock_or_recover(&self.0).batch_open = true;
184    }
185
186    /// The hub thread's batch, then what other threads queued while it was open.
187    fn end_batch(&self, batch: Vec<QueuedEvent>) {
188        let mut s = crate::sync_util::lock_or_recover(&self.0);
189        s.queue.extend(batch);
190        let held = std::mem::take(&mut s.held);
191        s.queue.extend(held);
192        s.batch_open = false;
193    }
194
195    pub(crate) fn push(&self, events: impl IntoIterator<Item = QueuedEvent>) {
196        let mut s = crate::sync_util::lock_or_recover(&self.0);
197        if s.batch_open {
198            s.held.extend(events);
199        } else {
200            s.queue.extend(events);
201        }
202    }
203
204    /// Deliver queued events. Call with no lock held.
205    // ponytail: whoever finds the queue idle delivers everything, including events
206    // the hub queues meanwhile; with a sink slower than the stream an `unwatch` caller
207    // keeps delivering for the new watch. Hand back to the hub thread if that matters.
208    pub(crate) fn deliver(&self) {
209        let mut s = crate::sync_util::lock_or_recover(&self.0);
210        if s.delivering {
211            return;
212        }
213        s.delivering = true;
214        while let Some((sink, ev)) = s.queue.pop_front() {
215            drop(s);
216            crate::port::watch_registry::send_event_to(&sink, ev);
217            s = crate::sync_util::lock_or_recover(&self.0);
218        }
219        s.delivering = false;
220    }
221}
222
223/// 4.0.0 API (feature `tauri`): [`emit_urc_to`] for a Tauri channel.
224#[cfg(feature = "tauri")]
225pub fn emit_urc(channel: &tauri::ipc::Channel<SerialEvent>, path: &str, line: &str) {
226    let _ = channel.send(SerialEvent::Urc {
227        path: path.to_string(),
228        line: line.to_string(),
229    });
230}
231
232pub fn emit_urc_to(channel: &crate::events::EventSink, path: &str, line: &str) {
233    let _ = (channel)(SerialEvent::Urc {
234        path: path.to_string(),
235        line: line.to_string(),
236    });
237}
238
239/// Per-port routing state shared between desktop poll loop and Android push feed.
240pub struct HubRoutingState {
241    pub path: String,
242    pub line_router: LineRouter,
243    /// URC demux for the exchange it was built for; rebuilt when the waiter changes.
244    pub exchange_demux: Option<(Arc<ExchangeWaiter>, ExchangeDemux)>,
245    pub combined_buffer: Vec<u8>,
246    pub flush_at: Instant,
247    /// Watch/URC events (with their sink) queued under the routing locks; delivered by
248    /// [`RxHubShared::dispatch_queued_events`] once the locks are released.
249    pub pending_events: Vec<QueuedEvent>,
250}
251
252impl HubRoutingState {
253    pub fn new(path: String) -> Self {
254        Self {
255            path,
256            line_router: LineRouter::default(),
257            exchange_demux: None,
258            combined_buffer: Vec::with_capacity(1024),
259            flush_at: Instant::now(),
260            pending_events: Vec::new(),
261        }
262    }
263}
264
265pub(crate) struct WatchSlot {
266    pub(crate) channel: crate::events::EventSink,
267    pub(crate) batch_timeout_ms: u64,
268    /// Poll read chunk size for the hub thread.
269    pub(crate) read_size: usize,
270    /// When true, idle watch RX goes through [`LineRouter`] (AT URC split).
271    pub(crate) route_urc: bool,
272    /// Native parser: each frame is its own `Data` event, no batching.
273    ///
274    /// With `route_urc` the URC split runs first and the parser sees only the data
275    /// lines. That is the least surprising order: `onUrc` keeps its meaning whatever
276    /// the parser, and a parser never has to know AT syntax. The line router's
277    /// unterminated tail reaches the parser on the batch timer, as it reaches `data`
278    /// without a parser.
279    pub(crate) framer: Option<Box<dyn Framer>>,
280}
281
282impl WatchSlot {
283    /// Feed watch bytes: into the parser (one event per frame) or the batch buffer.
284    fn sink(&mut self, path: &str, bytes: &[u8], state: &mut HubRoutingState) {
285        match self.framer.as_mut() {
286            Some(f) => {
287                let mut frames = Vec::new();
288                f.push(bytes, Instant::now(), &mut frames);
289                push_frames(path, &self.channel, frames, &mut state.pending_events);
290            }
291            None => state.combined_buffer.extend_from_slice(bytes),
292        }
293    }
294
295    /// End of stream: the parser's buffered partial frame as a final `Data` event.
296    fn take_remainder(&mut self, path: &str) -> Option<SerialEvent> {
297        let data = self.framer.as_mut()?.flush()?;
298        Some(data_event(path, data))
299    }
300}
301
302/// One [`SerialManager::watch_core`](crate::SerialManager::watch_core) stream: its own
303/// line router, batch buffer and parser over the hub's byte stream, so one subscriber's
304/// parser state never affects another's.
305pub(crate) struct CoreWatchSlot {
306    pub(crate) id: u64,
307    pub(crate) sink: EventSink,
308    pub(crate) alive: Arc<AtomicBool>,
309    pub(crate) batch_timeout_ms: u64,
310    pub(crate) read_size: usize,
311    pub(crate) route_urc: bool,
312    pub(crate) framer: Option<Box<dyn Framer>>,
313    pub(crate) line_router: LineRouter,
314    pub(crate) buffer: Vec<u8>,
315    pub(crate) flush_at: Instant,
316}
317
318impl CoreWatchSlot {
319    pub(crate) fn new(
320        id: u64,
321        sink: EventSink,
322        alive: Arc<AtomicBool>,
323        batch_timeout_ms: u64,
324        read_size: usize,
325        route_urc: bool,
326        framer: Option<Box<dyn Framer>>,
327    ) -> Self {
328        Self {
329            id,
330            sink,
331            alive,
332            batch_timeout_ms,
333            read_size,
334            route_urc,
335            framer,
336            line_router: LineRouter::default(),
337            buffer: Vec::new(),
338            flush_at: Instant::now(),
339        }
340    }
341
342    fn alive(&self) -> bool {
343        self.alive.load(Ordering::SeqCst)
344    }
345
346    fn push(&self, out: &mut Vec<QueuedEvent>, event: SerialEvent) {
347        out.push((self.sink.clone(), event));
348    }
349
350    /// Bytes past the URC split: into the parser (one event per frame) or the batch.
351    fn sink_bytes(&mut self, path: &str, bytes: &[u8], out: &mut Vec<QueuedEvent>) {
352        match self.framer.as_mut() {
353            Some(f) => {
354                let mut frames = Vec::new();
355                f.push(bytes, Instant::now(), &mut frames);
356                push_frames(path, &self.sink, frames, out);
357            }
358            None => self.buffer.extend_from_slice(bytes),
359        }
360    }
361
362    fn feed(&mut self, path: &str, chunk: &[u8], out: &mut Vec<QueuedEvent>) {
363        if !self.route_urc {
364            self.sink_bytes(path, chunk, out);
365            return;
366        }
367        for action in self.line_router.route_streaming(chunk, &[]) {
368            match action {
369                RxRouteAction::UrcLine(line) => self.push(
370                    out,
371                    SerialEvent::Urc {
372                        path: path.to_string(),
373                        line,
374                    },
375                ),
376                RxRouteAction::StreamData(bytes) => self.sink_bytes(path, &bytes, out),
377            }
378        }
379    }
380
381    fn tick(&mut self, path: &str, out: &mut Vec<QueuedEvent>) {
382        let timer = self.flush_at.elapsed() >= Duration::from_millis(self.batch_timeout_ms);
383        if self.framer.is_some() {
384            if timer {
385                self.flush_at = Instant::now();
386                let partial = self.line_router.take_partial();
387                if !partial.is_empty() {
388                    self.sink_bytes(path, &partial, out);
389                }
390            }
391            let mut frames = Vec::new();
392            if let Some(f) = self.framer.as_mut() {
393                f.poll(Instant::now(), &mut frames);
394            }
395            push_frames(path, &self.sink, frames, out);
396            return;
397        }
398        if timer || self.buffer.len() >= self.read_size.max(1) {
399            self.flush_at = Instant::now();
400            self.flush_buffers(path, out);
401        }
402    }
403
404    /// Line-router tail and batch out now (parser state kept).
405    fn flush_buffers(&mut self, path: &str, out: &mut Vec<QueuedEvent>) {
406        let partial = self.line_router.take_partial();
407        if !partial.is_empty() {
408            self.sink_bytes(path, &partial, out);
409        }
410        let data = std::mem::take(&mut self.buffer);
411        if !data.is_empty() {
412            self.push(out, data_event(path, data));
413        }
414    }
415
416    /// End of stream: batch, then the parser's remainder.
417    fn finish(&mut self, path: &str, out: &mut Vec<QueuedEvent>) {
418        self.flush_buffers(path, out);
419        if let Some(rest) = self.framer.as_mut().and_then(|f| f.flush()) {
420            self.push(out, data_event(path, rest));
421        }
422    }
423}
424
425fn data_event(path: &str, data: Vec<u8>) -> SerialEvent {
426    SerialEvent::Data {
427        path: path.to_string(),
428        size: data.len(),
429        data,
430    }
431}
432
433fn push_frames(
434    path: &str,
435    channel: &EventSink,
436    frames: Vec<Vec<u8>>,
437    pending: &mut Vec<QueuedEvent>,
438) {
439    pending.extend(
440        frames
441            .into_iter()
442            .map(|f| (channel.clone(), data_event(path, f))),
443    );
444}
445
446pub(crate) struct DrainSlot {
447    pub(crate) idle_ms: u64,
448    pub(crate) cancel: Arc<AtomicBool>,
449    pub(crate) buffer: Vec<u8>,
450    pub(crate) last_byte_at: Option<Instant>,
451    pub(crate) started_at: Instant,
452    pub(crate) deadline: Instant,
453    pub(crate) solicited_prefixes: Vec<String>,
454    pub(crate) tx: ByteResultTx,
455}
456
457pub(crate) struct ReadSlot {
458    pub(crate) max_bytes: usize,
459    pub(crate) fill: bool,
460    pub(crate) timeout_ms: u64,
461    pub(crate) buffer: Vec<u8>,
462    pub(crate) deadline: Instant,
463    pub(crate) tx: ByteResultTx,
464}
465
466/// Shared hub state between the RX thread and API handlers.
467pub struct RxHubShared {
468    pub(crate) exchange_waiter: Mutex<Option<Arc<ExchangeWaiter>>>,
469    pub(crate) watch: Mutex<Option<WatchSlot>>,
470    pub(crate) drain: Mutex<Option<DrainSlot>>,
471    pub(crate) read_slot: Mutex<Option<ReadSlot>>,
472    pub(crate) idle: Mutex<Vec<u8>>,
473    pub(crate) cmux: Mutex<Option<Arc<CmuxSession>>>,
474    /// `watch_core` streams (any number, beside the one old watch).
475    pub(crate) core_watches: Mutex<Vec<CoreWatchSlot>>,
476    /// Set by an intentional close: a read error from now on is not a `Disconnect`.
477    closing: AtomicBool,
478    /// `Disconnect` went out (it is sent once, even when two paths report the loss).
479    disconnected: AtomicBool,
480    outbox: Outbox,
481    /// Port path, for events sent outside the hub thread (watch remainder on detach).
482    path: String,
483}
484
485impl Default for RxHubShared {
486    fn default() -> Self {
487        Self::new()
488    }
489}
490
491impl RxHubShared {
492    pub fn new() -> Self {
493        Self::for_path(String::new())
494    }
495
496    pub fn for_path(path: String) -> Self {
497        Self {
498            path,
499            exchange_waiter: Mutex::new(None),
500            watch: Mutex::new(None),
501            drain: Mutex::new(None),
502            read_slot: Mutex::new(None),
503            idle: Mutex::new(Vec::new()),
504            cmux: Mutex::new(None),
505            core_watches: Mutex::new(Vec::new()),
506            closing: AtomicBool::new(false),
507            disconnected: AtomicBool::new(false),
508            outbox: Outbox::default(),
509        }
510    }
511
512    /// 4.0.0 API (feature `tauri`): [`Self::attach_watch_with`] for a Tauri channel, no parser.
513    #[cfg(feature = "tauri")]
514    pub fn attach_watch(
515        &self,
516        channel: tauri::ipc::Channel<SerialEvent>,
517        batch_timeout_ms: u64,
518        read_size: usize,
519        route_urc: bool,
520    ) {
521        let sink = crate::events::channel_sink(channel);
522        self.attach_watch_with(sink, batch_timeout_ms, read_size, route_urc, None);
523    }
524
525    pub fn attach_watch_with(
526        &self,
527        channel: crate::events::EventSink,
528        batch_timeout_ms: u64,
529        read_size: usize,
530        route_urc: bool,
531        framer: Option<Box<dyn Framer>>,
532    ) {
533        crate::sync_util::lock_or_recover(&self.idle).clear();
534        *crate::sync_util::lock_or_recover(&self.watch) = Some(WatchSlot {
535            channel,
536            batch_timeout_ms,
537            read_size,
538            route_urc,
539            framer,
540        });
541    }
542
543    /// Stop the watch; a parser's buffered remainder goes out as a last `Data` event,
544    /// after every frame the hub already decoded. Call with no lock held (the sink runs
545    /// here); under locks use [`Self::detach_watch_queued`] + [`Self::deliver_queued`].
546    pub fn detach_watch(&self) {
547        self.detach_watch_queued();
548        self.deliver_queued();
549    }
550
551    /// [`Self::detach_watch`] without running the sink: the remainder is queued.
552    pub fn detach_watch_queued(&self) {
553        let slot = crate::sync_util::lock_or_recover(&self.watch).take();
554        if let Some(mut slot) = slot {
555            if let Some(ev) = slot.take_remainder(&self.path) {
556                self.outbox.push([(slot.channel, ev)]);
557            }
558        }
559    }
560
561    /// Add a `watch_core` stream (bytes from now on; idle bytes are dropped, as on attach).
562    pub(crate) fn attach_core_watch(&self, slot: CoreWatchSlot) {
563        crate::sync_util::lock_or_recover(&self.idle).clear();
564        crate::sync_util::lock_or_recover(&self.core_watches).push(slot);
565    }
566
567    /// Remove a `watch_core` stream; its batch and parser remainder go out last.
568    /// `false` when no such stream. Call with no lock held.
569    pub(crate) fn detach_core_watch(&self, id: u64) -> bool {
570        let slot = {
571            let mut cores = crate::sync_util::lock_or_recover(&self.core_watches);
572            cores
573                .iter()
574                .position(|c| c.id == id)
575                .map(|i| cores.remove(i))
576        };
577        let Some(mut slot) = slot else {
578            return false;
579        };
580        let mut events = Vec::new();
581        slot.finish(&self.path, &mut events);
582        self.outbox.push(events);
583        self.outbox.deliver();
584        true
585    }
586
587    pub fn has_core_watches(&self) -> bool {
588        !crate::sync_util::lock_or_recover(&self.core_watches).is_empty()
589    }
590
591    /// Mark an intentional close: no `Disconnect` from here on.
592    pub(crate) fn mark_closing(&self) {
593        self.closing.store(true, Ordering::SeqCst);
594    }
595
596    pub(crate) fn is_closing(&self) -> bool {
597        self.closing.load(Ordering::SeqCst)
598    }
599
600    /// Run `f` over the live `watch_core` streams (dead ones are dropped first).
601    fn with_core_watches(&self, f: impl FnMut(&mut CoreWatchSlot)) {
602        let mut cores = crate::sync_util::lock_or_recover(&self.core_watches);
603        cores.retain(CoreWatchSlot::alive);
604        cores.iter_mut().for_each(f);
605    }
606
607    /// Copies of `event` for the old watch and every `watch_core` stream (`urc_only`:
608    /// only those with `route_urc`).
609    fn fan_out(&self, event: &SerialEvent, urc_only: bool, out: &mut Vec<QueuedEvent>) {
610        if let Some(channel) = self.watch_channel() {
611            out.push((channel, event.clone()));
612        }
613        self.with_core_watches(|c| {
614            if !urc_only || c.route_urc {
615                out.push((c.sink.clone(), event.clone()));
616            }
617        });
618    }
619
620    /// Earliest parser timer of all watches (the hub wakes for it).
621    pub(crate) fn next_framer_deadline(&self) -> Option<Instant> {
622        let old = crate::sync_util::lock_or_recover(&self.watch)
623            .as_ref()
624            .and_then(|w| w.framer.as_ref()?.deadline());
625        let core = crate::sync_util::lock_or_recover(&self.core_watches)
626            .iter()
627            .filter_map(|c| c.framer.as_ref()?.deadline())
628            .min();
629        match (old, core) {
630            (Some(a), Some(b)) => Some(a.min(b)),
631            (a, b) => a.or(b),
632        }
633    }
634
635    /// Read chunk size: the old watch's, else the largest `watch_core` one.
636    pub(crate) fn read_size(&self) -> Option<usize> {
637        if let Some(w) = crate::sync_util::lock_or_recover(&self.watch).as_ref() {
638            return Some(w.read_size);
639        }
640        crate::sync_util::lock_or_recover(&self.core_watches)
641            .iter()
642            .map(|c| c.read_size)
643            .max()
644    }
645
646    /// Deliver events queued by `*_queued` calls. Call with no lock held.
647    pub fn deliver_queued(&self) {
648        self.outbox.deliver();
649    }
650
651    /// Queue `event` for the current watch (if any) and deliver.
652    pub fn emit(&self, event: SerialEvent) {
653        let mut events = Vec::new();
654        self.fan_out(&event, false, &mut events);
655        if !events.is_empty() {
656            self.outbox.push(events);
657            self.outbox.deliver();
658        }
659    }
660
661    fn watch_channel(&self) -> Option<EventSink> {
662        crate::sync_util::lock_or_recover(&self.watch)
663            .as_ref()
664            .map(|w| w.channel.clone())
665    }
666
667    pub fn attach_cmux(&self, session: Arc<CmuxSession>) {
668        *crate::sync_util::lock_or_recover(&self.cmux) = Some(session);
669    }
670
671    pub fn detach_cmux(&self) {
672        *crate::sync_util::lock_or_recover(&self.cmux) = None;
673    }
674
675    /// Install the waiter. Bytes that arrived with no consumer (`idle`) are handed to it
676    /// first, under the idle lock, so they keep their order ahead of the reply.
677    pub fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
678        let mut idle = crate::sync_util::lock_or_recover(&self.idle);
679        if !idle.is_empty() {
680            waiter.push_bytes(&std::mem::take(&mut *idle));
681        }
682        *crate::sync_util::lock_or_recover(&self.exchange_waiter) = Some(waiter);
683    }
684
685    pub fn clear_exchange_waiter(&self) {
686        *crate::sync_util::lock_or_recover(&self.exchange_waiter) = None;
687    }
688
689    /// Wake an in-flight exchange waiter when [`SerialManager::cancel_exchange`](crate::SerialManager::cancel_exchange) is invoked.
690    pub fn cancel_active_exchange(&self) {
691        if let Some(waiter) = crate::sync_util::lock_or_recover(&self.exchange_waiter).as_ref() {
692            waiter.fail_with_reason("exchange cancelled".into());
693        }
694    }
695
696    /// Push-model entry: route incoming bytes (Android JNI / tests).
697    pub fn feed_bytes(&self, chunk: &[u8], state: &mut HubRoutingState) {
698        if chunk.is_empty() {
699            return;
700        }
701        self.outbox.begin_batch();
702        let path = state.path.clone();
703        // Bound first: the guard must not live through the session's sink calls.
704        let session = crate::sync_util::lock_or_recover(&self.cmux).clone();
705        if let Some(session) = session {
706            session.feed_physical_rx(chunk);
707            return;
708        }
709        if route_drain_chunk(self, chunk) {
710            return;
711        }
712        if let Some(waiter) = crate::sync_util::lock_or_recover(&self.exchange_waiter).clone() {
713            route_exchange_chunk(self, &path, chunk, state, waiter);
714            return;
715        }
716        // A read takes what fits; the rest of the chunk goes on to the next consumer.
717        let chunk = match route_read_slot_chunk(self, chunk) {
718            Some(taken) if taken == chunk.len() => return,
719            Some(taken) => &chunk[taken..],
720            None => chunk,
721        };
722        let cores = self.has_core_watches();
723        if self.has_watch() || cores {
724            route_watch_chunk(self, &path, chunk, state);
725            if cores {
726                let mut out = std::mem::take(&mut state.pending_events);
727                self.with_core_watches(|c| c.feed(&path, chunk, &mut out));
728                state.pending_events = out;
729            }
730            return;
731        }
732        push_idle(self, chunk);
733    }
734
735    /// Idle timers for push model: drain completion + watch batch flush + read deadlines.
736    pub fn tick(&self, path: &str, state: &mut HubRoutingState) {
737        self.outbox.begin_batch();
738        tick_read_slot(self);
739        try_complete_drain(self);
740        let session = crate::sync_util::lock_or_recover(&self.cmux).clone();
741        if let Some(session) = session {
742            session.tick();
743        }
744        {
745            let mut out = std::mem::take(&mut state.pending_events);
746            self.with_core_watches(|c| c.tick(path, &mut out));
747            state.pending_events = out;
748        }
749
750        let (batch_timeout_ms, read_size) = {
751            let mut guard = crate::sync_util::lock_or_recover(&self.watch);
752            if let Some(w) = guard.as_mut().filter(|w| w.framer.is_some()) {
753                // Parser watch: frames already went out one by one. Release the line
754                // router tail on the batch timer, then fire time-based frames.
755                if state.flush_at.elapsed() >= Duration::from_millis(w.batch_timeout_ms) {
756                    state.flush_at = Instant::now();
757                    let partial = state.line_router.take_partial();
758                    if !partial.is_empty() {
759                        w.sink(path, &partial, state);
760                    }
761                }
762                let mut frames = Vec::new();
763                if let Some(f) = w.framer.as_mut() {
764                    f.poll(Instant::now(), &mut frames);
765                }
766                push_frames(path, &w.channel, frames, &mut state.pending_events);
767                // Bytes batched before a parser watch replaced a plain one.
768                let stale = std::mem::take(&mut state.combined_buffer);
769                if !stale.is_empty() {
770                    state
771                        .pending_events
772                        .insert(0, (w.channel.clone(), data_event(path, stale)));
773                }
774                return;
775            }
776            guard
777                .as_ref()
778                .map(|w| (w.batch_timeout_ms, w.read_size))
779                .unwrap_or((1000, usize::MAX))
780        };
781        // Flush on the batch timer, or as soon as a full `size` worth is buffered,
782        // so a fast stream does not grow one huge event per window.
783        if state.flush_at.elapsed() >= Duration::from_millis(batch_timeout_ms)
784            || state.combined_buffer.len() >= read_size.max(1)
785        {
786            state.flush_at = Instant::now();
787            let partial = state.line_router.take_partial();
788            state.combined_buffer.extend_from_slice(&partial);
789            flush_watch_data(
790                self,
791                path,
792                &mut state.combined_buffer,
793                &mut state.pending_events,
794            );
795        }
796    }
797
798    /// Immediately fail exchange waiters, active drain, and pending read (USB error teardown).
799    pub fn fail_all_waiters(&self, reason: &str) {
800        if let Some(waiter) = crate::sync_util::lock_or_recover(&self.exchange_waiter).take() {
801            waiter.fail_with_reason(reason.to_string());
802        }
803        finish_drain(self, Err(reason.to_string()));
804        finish_read_slot(self, Err(reason.to_string()));
805    }
806
807    pub fn buffered_len(&self) -> usize {
808        let idle_len = crate::sync_util::lock_or_recover(&self.idle).len();
809        let read_len = crate::sync_util::lock_or_recover(&self.read_slot)
810            .as_ref()
811            .map(|slot| slot.buffer.len())
812            .unwrap_or(0);
813        idle_len + read_len
814    }
815
816    /// Drop bytes the hub holds for no one yet (idle RX, a pending read's partial fill).
817    pub fn purge_buffers(&self) {
818        crate::sync_util::lock_or_recover(&self.idle).clear();
819        if let Some(slot) = crate::sync_util::lock_or_recover(&self.read_slot).as_mut() {
820            slot.buffer.clear();
821        }
822    }
823
824    /// Take any bytes buffered without an active consumer (e.g. early RX before exchange waiter).
825    pub fn take_idle_bytes(&self) -> Vec<u8> {
826        std::mem::take(&mut *crate::sync_util::lock_or_recover(&self.idle))
827    }
828
829    pub fn cancel_pending_read(&self) {
830        finish_read_slot(self, Err("read cancelled".into()));
831    }
832
833    /// Blocking poll-read via the hub (raw bytes, bypasses [`LineRouter`]).
834    pub fn read_request(
835        &self,
836        max_bytes: usize,
837        timeout_ms: u64,
838        fill: bool,
839    ) -> Result<Vec<u8>, String> {
840        if self.has_watch() || self.has_core_watches() {
841            return Err("Cannot read while watch is active; use watch or exchange".into());
842        }
843
844        let max_bytes = max_bytes.max(1);
845        let wait = Duration::from_millis(timeout_ms);
846        let deadline = Instant::now() + wait;
847
848        // Idle hand-off and slot install happen under one idle lock: a chunk routed in
849        // between would otherwise land in `idle` behind an installed slot (see `push_idle`).
850        let (tx, rx) = mpsc::sync_channel(1);
851        {
852            let mut idle = crate::sync_util::lock_or_recover(&self.idle);
853            let mut guard = crate::sync_util::lock_or_recover(&self.read_slot);
854            if guard.is_some() {
855                return Err("read already in progress".into());
856            }
857            let mut initial = Vec::new();
858            if !idle.is_empty() {
859                let n = max_bytes.min(idle.len());
860                if !fill {
861                    return Ok(idle.drain(..n).collect());
862                }
863                initial.extend(idle.drain(..n));
864                if initial.len() >= max_bytes {
865                    return Ok(initial);
866                }
867            }
868            *guard = Some(ReadSlot {
869                max_bytes,
870                fill,
871                timeout_ms,
872                buffer: initial,
873                deadline,
874                tx,
875            });
876        }
877
878        match rx.recv_timeout(wait) {
879            Ok(result) => result,
880            Err(RecvTimeoutError::Timeout) => {
881                if let Some(slot) = crate::sync_util::lock_or_recover(&self.read_slot).take() {
882                    if slot.buffer.is_empty() {
883                        Err(format!("no data received within {} ms", timeout_ms))
884                    } else {
885                        Ok(slot.buffer)
886                    }
887                } else {
888                    // Completer took the slot then sends — brief wait covers that gap.
889                    rx.recv_timeout(Duration::from_millis(50))
890                        .unwrap_or_else(|_| {
891                            Err(format!("no data received within {} ms", timeout_ms))
892                        })
893                }
894            }
895            Err(RecvTimeoutError::Disconnected) => {
896                Err(format!("no data received within {} ms", timeout_ms))
897            }
898        }
899    }
900
901    pub fn pending_watch_bytes(&self, state: &HubRoutingState) -> usize {
902        state.combined_buffer.len()
903    }
904
905    pub fn flush_watch_now(&self, state: &mut HubRoutingState) {
906        self.outbox.begin_batch();
907        let partial = state.line_router.take_partial();
908        self.sink_watch(&partial, state);
909        flush_watch_data(
910            self,
911            &state.path,
912            &mut state.combined_buffer,
913            &mut state.pending_events,
914        );
915        let mut out = std::mem::take(&mut state.pending_events);
916        let path = state.path.clone();
917        self.with_core_watches(|c| c.flush_buffers(&path, &mut out));
918        state.pending_events = out;
919    }
920
921    /// Send `Disconnect` on the watch, after the parser's remainder as a last `Data`.
922    /// CMUX channel watches get the same (remainder, then `Disconnect` on their path).
923    /// Once per hub: a second call (Android reports a USB failure from the hub loop
924    /// and from `fail_port`) does nothing.
925    pub fn emit_disconnect(&self, path: &str, reason: &str) {
926        if self.disconnected.swap(true, Ordering::SeqCst) {
927            return;
928        }
929        let mut events = Vec::new();
930        if let Some(watch) = crate::sync_util::lock_or_recover(&self.watch).as_mut() {
931            if let Some(ev) = watch.take_remainder(path) {
932                events.push((watch.channel.clone(), ev));
933            }
934            events.push((
935                watch.channel.clone(),
936                SerialEvent::Disconnect {
937                    path: path.to_string(),
938                    reason: reason.to_string(),
939                },
940            ));
941        }
942        self.with_core_watches(|c| {
943            c.finish(path, &mut events);
944            c.push(
945                &mut events,
946                SerialEvent::Disconnect {
947                    path: path.to_string(),
948                    reason: reason.to_string(),
949                },
950            );
951        });
952        self.outbox.push(events);
953        self.outbox.deliver();
954        let session = crate::sync_util::lock_or_recover(&self.cmux).clone();
955        if let Some(session) = session {
956            session.emit_disconnect(reason);
957        }
958    }
959
960    /// Port going away: flush the batch and the parser remainder into `pending_events`.
961    pub fn finish_watch_stream(&self, state: &mut HubRoutingState) {
962        self.flush_watch_now(state);
963        if let Some(watch) = crate::sync_util::lock_or_recover(&self.watch).as_mut() {
964            if let Some(ev) = watch.take_remainder(&state.path) {
965                state.pending_events.push((watch.channel.clone(), ev));
966            }
967        }
968        let mut out = std::mem::take(&mut state.pending_events);
969        let path = state.path.clone();
970        self.with_core_watches(|c| c.finish(&path, &mut out));
971        state.pending_events = out;
972    }
973
974    /// Bytes for the watch with no URC routing (line router tail): parser or batch.
975    fn sink_watch(&self, bytes: &[u8], state: &mut HubRoutingState) {
976        if bytes.is_empty() {
977            return;
978        }
979        match crate::sync_util::lock_or_recover(&self.watch).as_mut() {
980            Some(watch) => watch.sink(&state.path.clone(), bytes, state),
981            None => state.combined_buffer.extend_from_slice(bytes),
982        }
983    }
984
985    pub fn has_watch(&self) -> bool {
986        crate::sync_util::lock_or_recover(&self.watch).is_some()
987    }
988
989    /// Deliver the hub thread's batch (`pending_events`), then events other threads
990    /// queued meanwhile. Each event goes to the sink it was produced for, even if the
991    /// watch was detached since. Call with no lock held, after every routing call.
992    /// 4.0.0 API (feature `tauri`): deliver `events` to the current watch.
993    #[cfg(feature = "tauri")]
994    pub fn dispatch_pending_events(&self, events: Vec<SerialEvent>) {
995        if events.is_empty() {
996            return;
997        }
998        if let Some(sink) = self.watch_channel() {
999            self.dispatch_queued_events(events.into_iter().map(|e| (sink.clone(), e)).collect());
1000        }
1001    }
1002
1003    pub fn dispatch_queued_events(&self, events: Vec<QueuedEvent>) {
1004        self.outbox.end_batch(events);
1005        self.outbox.deliver();
1006    }
1007
1008    /// Soft-drain via the hub thread (single reader); URC lines are emitted on the watch channel.
1009    /// Bytes already in the idle buffer are dropped with the drained ones (a late reply to
1010    /// a timed-out exchange is exactly what a drain throws away).
1011    pub fn drain(
1012        &self,
1013        idle_ms: u64,
1014        max_ms: u64,
1015        cancel: Arc<AtomicBool>,
1016        solicited_prefixes: Vec<String>,
1017    ) -> Result<Vec<u8>, String> {
1018        let wait = Duration::from_millis(max_ms.saturating_add(500));
1019        let (tx, rx) = mpsc::sync_channel(1);
1020        {
1021            // Under the idle lock (order: idle, then drain): a chunk `feed_bytes` routes
1022            // to idle while the slot goes in lands either before (cleared here) or after
1023            // (`push_idle` hands it to the slot), never in idle behind the drain.
1024            let mut idle = crate::sync_util::lock_or_recover(&self.idle);
1025            let mut guard = crate::sync_util::lock_or_recover(&self.drain);
1026            if guard.is_some() {
1027                return Err("drain already in progress".into());
1028            }
1029            idle.clear();
1030            *guard = Some(DrainSlot {
1031                idle_ms,
1032                cancel,
1033                buffer: Vec::new(),
1034                last_byte_at: None,
1035                started_at: Instant::now(),
1036                deadline: Instant::now() + Duration::from_millis(max_ms),
1037                solicited_prefixes,
1038                tx,
1039            });
1040        }
1041
1042        match rx.recv_timeout(wait) {
1043            Ok(result) => result,
1044            Err(RecvTimeoutError::Timeout) => {
1045                let slot = crate::sync_util::lock_or_recover(&self.drain).take();
1046                if let Some(slot) = slot {
1047                    emit_drain_urcs(self, &slot);
1048                    if slot.buffer.is_empty() {
1049                        Err("drain timed out waiting for hub".into())
1050                    } else {
1051                        Ok(slot.buffer)
1052                    }
1053                } else {
1054                    // Completer took the slot then sends — brief wait covers that gap.
1055                    rx.recv_timeout(Duration::from_millis(50))
1056                        .unwrap_or_else(|_| Err("drain timed out waiting for hub".into()))
1057                }
1058            }
1059            Err(RecvTimeoutError::Disconnected) => Err("drain timed out waiting for hub".into()),
1060        }
1061    }
1062}
1063
1064/// Append RX into the active drain slot. Returns `false` if there is no slot
1065/// (caller must route elsewhere — never silently drop the chunk).
1066/// URCs in the drained bytes go out when the drain completes, judged over the whole
1067/// buffer: a two-line URC (`+CMT:` + PDU) or a multi-line `+CUSD` split across reads
1068/// stays together. That delays them by at most the drain window (default 200 ms).
1069pub(crate) fn route_drain_chunk(shared: &RxHubShared, chunk: &[u8]) -> bool {
1070    let mut guard = crate::sync_util::lock_or_recover(&shared.drain);
1071    let Some(drain) = guard.as_mut() else {
1072        return false;
1073    };
1074    drain.buffer.extend_from_slice(chunk);
1075    drain.last_byte_at = Some(Instant::now());
1076    true
1077}
1078
1079pub(crate) fn route_exchange_chunk(
1080    shared: &RxHubShared,
1081    path: &str,
1082    chunk: &[u8],
1083    state: &mut HubRoutingState,
1084    waiter: Arc<ExchangeWaiter>,
1085) {
1086    let stale = !matches!(&state.exchange_demux, Some((w, _)) if Arc::ptr_eq(w, &waiter));
1087    if stale {
1088        let cmd = waiter.options.command.clone().unwrap_or_default();
1089        let demux = ExchangeDemux::with_format(
1090            &cmd,
1091            &waiter.options.solicited_prefixes,
1092            waiter.options.result_format,
1093        );
1094        state.exchange_demux = Some((waiter.clone(), demux));
1095    }
1096    if let Some((_, demux)) = state.exchange_demux.as_mut() {
1097        for line in demux.process_chunk(chunk) {
1098            let event = SerialEvent::Urc {
1099                path: path.to_string(),
1100                line,
1101            };
1102            shared.fan_out(&event, true, &mut state.pending_events);
1103        }
1104    }
1105    waiter.push_bytes(chunk);
1106}
1107
1108pub(crate) fn route_watch_chunk(
1109    shared: &RxHubShared,
1110    path: &str,
1111    chunk: &[u8],
1112    state: &mut HubRoutingState,
1113) {
1114    state.exchange_demux = None;
1115    let mut guard = crate::sync_util::lock_or_recover(&shared.watch);
1116    let Some(watch) = guard.as_mut() else {
1117        // Watch went away since `has_watch`: the batch is dropped on flush anyway.
1118        return;
1119    };
1120    if !watch.route_urc {
1121        // Raw stream: do not UTF-8-lossify, split on 0x0A, or steal URC-looking lines.
1122        state.line_router = LineRouter::default();
1123        watch.sink(path, chunk, state);
1124        return;
1125    }
1126    for action in state.line_router.route_streaming(chunk, &[]) {
1127        match action {
1128            RxRouteAction::UrcLine(line) => {
1129                state.pending_events.push((
1130                    watch.channel.clone(),
1131                    SerialEvent::Urc {
1132                        path: path.to_string(),
1133                        line,
1134                    },
1135                ));
1136            }
1137            RxRouteAction::StreamData(bytes) => watch.sink(path, &bytes, state),
1138        }
1139    }
1140}
1141
1142/// Feed a read slot: the bytes it took, or `None` if there is no slot (fall through).
1143/// A read takes at most its size; the caller routes the rest of the chunk on (they
1144/// were once dropped).
1145pub(crate) fn route_read_slot_chunk(shared: &RxHubShared, chunk: &[u8]) -> Option<usize> {
1146    let taken;
1147    let completed = {
1148        let mut guard = crate::sync_util::lock_or_recover(&shared.read_slot);
1149        let ready = {
1150            let slot = guard.as_mut()?;
1151            let remaining = slot.max_bytes.saturating_sub(slot.buffer.len());
1152            taken = chunk.len().min(remaining);
1153            slot.buffer.extend_from_slice(&chunk[..taken]);
1154            !slot.fill || slot.buffer.len() >= slot.max_bytes
1155        };
1156        if !ready {
1157            None
1158        } else {
1159            let slot = guard.take().unwrap();
1160            Some((slot.tx, Ok(slot.buffer)))
1161        }
1162    };
1163    if let Some((tx, result)) = completed {
1164        let _ = tx.send(result);
1165    }
1166    Some(taken)
1167}
1168
1169pub(crate) fn tick_read_slot(shared: &RxHubShared) {
1170    let completed = {
1171        let mut guard = crate::sync_util::lock_or_recover(&shared.read_slot);
1172        let expired = match guard.as_ref() {
1173            Some(slot) => Instant::now() >= slot.deadline,
1174            None => return,
1175        };
1176        if !expired {
1177            return;
1178        }
1179        let slot = guard.take().unwrap();
1180        let result = if slot.buffer.is_empty() {
1181            Err(format!("no data received within {} ms", slot.timeout_ms))
1182        } else {
1183            Ok(slot.buffer)
1184        };
1185        Some((slot.tx, result))
1186    };
1187    if let Some((tx, result)) = completed {
1188        let _ = tx.send(result);
1189    }
1190}
1191
1192/// Shared idle/deadline/cancel completion for drain (desktop poll + Android tick).
1193pub(crate) fn try_complete_drain(shared: &RxHubShared) {
1194    let completed = {
1195        let mut guard = crate::sync_util::lock_or_recover(&shared.drain);
1196        let kind = match guard.as_ref() {
1197            Some(d) if d.cancel.load(Ordering::SeqCst) => Some(DrainCompleteKind::Cancel),
1198            Some(d) if Instant::now() >= d.deadline => Some(DrainCompleteKind::Buffer),
1199            Some(d)
1200                if d.last_byte_at
1201                    .is_some_and(|t| t.elapsed() >= Duration::from_millis(d.idle_ms)) =>
1202            {
1203                Some(DrainCompleteKind::Buffer)
1204            }
1205            Some(d)
1206                if d.last_byte_at.is_none()
1207                    && d.started_at.elapsed() >= Duration::from_millis(d.idle_ms) =>
1208            {
1209                Some(DrainCompleteKind::Empty)
1210            }
1211            _ => None,
1212        };
1213        kind.map(|k| (k, guard.take().unwrap()))
1214    };
1215    // The drain lock is released: the URC sink may touch the drain slot.
1216    if let Some((k, d)) = completed {
1217        emit_drain_urcs(shared, &d);
1218        let result = match k {
1219            DrainCompleteKind::Cancel => Err("exchange cancelled".into()),
1220            DrainCompleteKind::Buffer => Ok(d.buffer),
1221            DrainCompleteKind::Empty => Ok(Vec::new()),
1222        };
1223        let _ = d.tx.send(result);
1224    }
1225}
1226
1227#[derive(Clone, Copy)]
1228enum DrainCompleteKind {
1229    Cancel,
1230    Buffer,
1231    Empty,
1232}
1233
1234pub(crate) fn finish_read_slot(shared: &RxHubShared, result: Result<Vec<u8>, String>) {
1235    if let Some(slot) = crate::sync_util::lock_or_recover(&shared.read_slot).take() {
1236        let _ = slot.tx.send(result);
1237    }
1238}
1239
1240pub(crate) fn push_idle(shared: &RxHubShared, chunk: &[u8]) {
1241    let mut idle = crate::sync_util::lock_or_recover(&shared.idle);
1242    // A drain, waiter or read slot may have been installed after `feed_bytes` checked
1243    // for one (lock order: idle, then drain / exchange_waiter / read_slot). A drain
1244    // first, as in `feed_bytes`: idle bytes left behind it would reach the next exchange.
1245    if route_drain_chunk(shared, chunk) {
1246        return;
1247    }
1248    if let Some(waiter) = crate::sync_util::lock_or_recover(&shared.exchange_waiter).as_ref() {
1249        waiter.push_bytes(chunk);
1250        return;
1251    }
1252    // Same for a read slot installed after `feed_bytes` checked for one.
1253    let chunk = match route_read_slot_chunk(shared, chunk) {
1254        Some(taken) => &chunk[taken..],
1255        None => chunk,
1256    };
1257    idle.extend_from_slice(chunk);
1258    let excess = idle.len().saturating_sub(IDLE_BUFFER_CAP);
1259    idle.drain(..excess);
1260}
1261
1262/// End the drain with `result`; URCs it collected still reach the watch.
1263pub(crate) fn finish_drain(shared: &RxHubShared, result: Result<Vec<u8>, String>) {
1264    let drain = crate::sync_util::lock_or_recover(&shared.drain).take();
1265    if let Some(drain) = drain {
1266        emit_drain_urcs(shared, &drain);
1267        let _ = drain.tx.send(result);
1268    }
1269}
1270
1271/// Send the URC lines of a finished drain on the watch channel (if any).
1272/// Call with the drain lock released.
1273fn emit_drain_urcs(shared: &RxHubShared, drain: &DrainSlot) {
1274    if drain.buffer.is_empty() {
1275        return;
1276    }
1277    if !shared.has_watch() && !shared.has_core_watches() {
1278        return;
1279    }
1280    let lines = crate::at::parse::urc_lines_from_drain(&drain.buffer, &drain.solicited_prefixes);
1281    let mut events = Vec::new();
1282    for line in lines {
1283        let event = SerialEvent::Urc {
1284            path: shared.path.clone(),
1285            line,
1286        };
1287        shared.fan_out(&event, true, &mut events);
1288    }
1289    shared.outbox.push(events);
1290    shared.outbox.deliver();
1291}
1292
1293pub(crate) fn flush_watch_data(
1294    shared: &RxHubShared,
1295    path: &str,
1296    combined_buffer: &mut Vec<u8>,
1297    pending: &mut Vec<QueuedEvent>,
1298) {
1299    if combined_buffer.is_empty() {
1300        return;
1301    }
1302    if let Some(channel) = shared.watch_channel() {
1303        pending.push((channel, data_event(path, std::mem::take(combined_buffer))));
1304    } else {
1305        combined_buffer.clear();
1306    }
1307}
1308#[cfg(test)]
1309mod model;
1310
1311#[cfg(test)]
1312mod tests {
1313    use super::*;
1314    use crate::at::parse::ExchangeMatch;
1315    use crate::events::{AtResultFormat, ExchangeCompletionMode, RxPrepareMode};
1316    use std::path::PathBuf;
1317    use std::thread;
1318
1319    #[test]
1320    fn exchange_waiter_completes_on_final_ok_line() {
1321        let cancel = Arc::new(AtomicBool::new(false));
1322        let options = ResolvedExchangeOptions {
1323            timeout_ms: 5000,
1324            max_bytes: 4096,
1325            terminators: vec![],
1326            idle_ms: None,
1327            rx_prepare: RxPrepareMode::Drain,
1328            drain_idle_ms: 50,
1329            drain_max_ms: 200,
1330            completion_mode: ExchangeCompletionMode::AtFinalLine,
1331            result_format: AtResultFormat::Verbose,
1332            command: Some("AT".into()),
1333            solicited_prefixes: vec![],
1334        };
1335        let waiter = ExchangeWaiter::new(options, cancel);
1336        waiter.push_bytes(b"AT\r\r\nOK\r\n");
1337        let result = waiter.wait(1000).expect("complete");
1338        assert!(matches!(result.1, ExchangeMatch::Ok));
1339    }
1340
1341    fn waiter_options(
1342        mode: ExchangeCompletionMode,
1343        format: AtResultFormat,
1344    ) -> ResolvedExchangeOptions {
1345        ResolvedExchangeOptions {
1346            timeout_ms: 5000,
1347            max_bytes: 64 << 20,
1348            terminators: crate::exchange::options::default_terminators(),
1349            idle_ms: None,
1350            rx_prepare: RxPrepareMode::Drain,
1351            drain_idle_ms: 50,
1352            drain_max_ms: 200,
1353            completion_mode: mode,
1354            result_format: format,
1355            command: Some("AT+CSQ".into()),
1356            solicited_prefixes: vec![],
1357        }
1358    }
1359
1360    /// A long reply in small reads completes in every mode. (Completion used to re-run
1361    /// over the whole buffer on every chunk; `exchange::completion` tests pin the
1362    /// window each chunk looks at, which keeps it linear.)
1363    #[test]
1364    fn exchange_completion_is_linear_in_the_reply() {
1365        let line = b"+CPBR: 1,\"+10000000001\",145,\"Name\"\r\n".repeat(2);
1366        for mode in [
1367            ExchangeCompletionMode::AtFinalLine,
1368            ExchangeCompletionMode::AtIntermediate,
1369            ExchangeCompletionMode::Substring,
1370        ] {
1371            let waiter = ExchangeWaiter::new(
1372                waiter_options(mode.clone(), AtResultFormat::Verbose),
1373                Arc::new(AtomicBool::new(false)),
1374            );
1375            waiter.push_bytes(b"AT+CPBR=1,9999\r\r\n");
1376            for _ in 0..(1 << 8) {
1377                for part in line.chunks(64) {
1378                    waiter.push_bytes(part);
1379                }
1380            }
1381            for part in b"\r\nOK\r\n".chunks(3) {
1382                waiter.push_bytes(part);
1383            }
1384            let (raw, m) = waiter.wait(1000).expect("complete");
1385            assert!(
1386                matches!(m, ExchangeMatch::Ok | ExchangeMatch::Substring { .. }),
1387                "{mode:?}: {m:?}"
1388            );
1389            assert!(raw.ends_with(b"OK\r\n"));
1390        }
1391    }
1392
1393    /// The live URC demux judges result codes like the completion check: with `ATV0`
1394    /// a lone `4` after a `+CMT` header is the ERROR result, not the URC's data line.
1395    #[test]
1396    fn exchange_demux_follows_the_result_format() {
1397        for (format, want) in [
1398            (AtResultFormat::Verbose, vec!["+CMT: ,5", "4"]),
1399            (AtResultFormat::Numeric, vec!["+CMT: ,5"]),
1400        ] {
1401            let shared = RxHubShared::new();
1402            let sink: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1403            shared.attach_watch_with(sink, 100, 1024, true, None);
1404            let mut routing = HubRoutingState::new("p".into());
1405            let waiter = ExchangeWaiter::new(
1406                waiter_options(ExchangeCompletionMode::AtFinalLine, format),
1407                Arc::new(AtomicBool::new(false)),
1408            );
1409            route_exchange_chunk(&shared, "p", b"+CMT: ,5\r\n4\r\n", &mut routing, waiter);
1410            let urcs: Vec<String> = routing
1411                .pending_events
1412                .iter()
1413                .filter_map(|(_, e)| match e {
1414                    SerialEvent::Urc { line, .. } => Some(line.clone()),
1415                    _ => None,
1416                })
1417                .collect();
1418            assert_eq!(urcs, want, "{format:?}");
1419        }
1420    }
1421
1422    #[test]
1423    fn line_router_emits_vendor_urc() {
1424        let mut router = LineRouter::default();
1425        let actions = router.route_streaming(b"^CARDLOCK: 1\r\n", &[]);
1426        assert!(actions
1427            .iter()
1428            .any(|a| matches!(a, RxRouteAction::UrcLine(s) if s.starts_with("^CARDLOCK"))));
1429    }
1430
1431    #[test]
1432    fn watch_without_route_urc_preserves_mavlink_bytes() {
1433        let shared = RxHubShared::new();
1434        let channel = {
1435            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1436            c
1437        };
1438        shared.attach_watch_with(channel, 100, 1024, false, None);
1439        // MAVLink v2 HEARTBEAT: start 0xFD, payload contains 0x0A, CRC contains 0xFD.
1440        let frame: Vec<u8> = vec![
1441            0xFD, 0x09, 0x00, 0x00, 0x2A, 0x01, 0x01, 0x00, 0x00, 0x00, 0x0A, 0x2B, 0x00, 0x00,
1442            0x01, 0x03, 0x51, 0x04, 0x03, 0xFD, 0x72,
1443        ];
1444        let mut routing = HubRoutingState::new("p".into());
1445        shared.feed_bytes(&frame, &mut routing);
1446        assert_eq!(routing.combined_buffer, frame);
1447        assert!(
1448            routing
1449                .pending_events
1450                .iter()
1451                .map(|(_, e)| e)
1452                .all(|e| !matches!(e, SerialEvent::Urc { .. })),
1453            "binary stream must not emit URC events"
1454        );
1455    }
1456
1457    #[test]
1458    fn watch_without_route_urc_keeps_nmea_in_data_stream() {
1459        let shared = RxHubShared::new();
1460        let channel = {
1461            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1462            c
1463        };
1464        shared.attach_watch_with(channel, 100, 1024, false, None);
1465        let nmea = b"$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\r\n";
1466        let mut routing = HubRoutingState::new("p".into());
1467        shared.feed_bytes(nmea, &mut routing);
1468        assert_eq!(routing.combined_buffer.as_slice(), nmea.as_slice());
1469        assert!(
1470            routing
1471                .pending_events
1472                .iter()
1473                .map(|(_, e)| e)
1474                .all(|e| !matches!(e, SerialEvent::Urc { .. })),
1475            "NMEA `$` lines must stay in onData when route_urc is off"
1476        );
1477    }
1478
1479    #[test]
1480    fn watch_with_route_urc_classifies_idle_urc_lines() {
1481        let shared = RxHubShared::new();
1482        let channel = {
1483            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1484            c
1485        };
1486        shared.attach_watch_with(channel, 100, 1024, true, None);
1487        let mut routing = HubRoutingState::new("p".into());
1488        shared.feed_bytes(b"^CARDLOCK: 1\r\nOK\r\n", &mut routing);
1489        assert!(
1490            routing.pending_events.iter().map(|(_, e)| e).any(
1491                |e| matches!(e, SerialEvent::Urc { line, .. } if line.starts_with("^CARDLOCK"))
1492            ),
1493            "expected URC, got {:?}",
1494            evs(&routing.pending_events)
1495        );
1496        assert!(
1497            routing.combined_buffer.windows(2).any(|w| w == b"OK"),
1498            "non-URC line should remain in data stream, got {:?}",
1499            routing.combined_buffer
1500        );
1501    }
1502
1503    /// Regression: data lines lost their `\r\n`, and a URC split across reads went
1504    /// out as data.
1505    #[test]
1506    fn line_router_keeps_terminators_and_joins_split_lines() {
1507        let mut router = LineRouter::default();
1508        let mut data = Vec::new();
1509        let mut urc = Vec::new();
1510        for chunk in [&b"A\r\nB\r\n+CRE"[..], b"G: 0,1\r\n\xD0", b"\x9F\r\n"] {
1511            for action in router.route_streaming(chunk, &[]) {
1512                match action {
1513                    RxRouteAction::StreamData(b) => data.extend(b),
1514                    RxRouteAction::UrcLine(l) => urc.push(l),
1515                }
1516            }
1517        }
1518        assert_eq!(data, "A\r\nB\r\nП\r\n".as_bytes());
1519        assert_eq!(urc, vec!["+CREG: 0,1".to_string()]);
1520        assert!(router.take_partial().is_empty());
1521    }
1522
1523    #[test]
1524    fn feed_bytes_exchange_with_watch_emits_live_urc_pending() {
1525        let shared = RxHubShared::new();
1526        let channel = {
1527            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1528            c
1529        };
1530        shared.attach_watch_with(channel, 100, 1024, false, None);
1531
1532        let cancel = Arc::new(AtomicBool::new(false));
1533        let options = ResolvedExchangeOptions {
1534            timeout_ms: 5000,
1535            max_bytes: 4096,
1536            terminators: vec![],
1537            idle_ms: None,
1538            rx_prepare: RxPrepareMode::None,
1539            drain_idle_ms: 50,
1540            drain_max_ms: 200,
1541            completion_mode: ExchangeCompletionMode::AtFinalLine,
1542            result_format: AtResultFormat::Verbose,
1543            command: Some("AT+CSQ".into()),
1544            solicited_prefixes: vec![],
1545        };
1546        let waiter = ExchangeWaiter::new(options, cancel);
1547        shared.set_exchange_waiter(waiter.clone());
1548
1549        let mut routing = HubRoutingState::new("p".into());
1550        shared.feed_bytes(
1551            b"\r\n+CREG: 0,1\r\n\r\nAT+CSQ\r\n\r\n+CSQ: 10,99\r\n\r\nOK\r\n",
1552            &mut routing,
1553        );
1554
1555        let urcs: Vec<_> = routing
1556            .pending_events
1557            .iter()
1558            .map(|(_, e)| e)
1559            .filter_map(|e| match e {
1560                SerialEvent::Urc { line, .. } => Some(line.as_str()),
1561                _ => None,
1562            })
1563            .collect();
1564        assert!(
1565            urcs.iter().any(|l| l.contains("+CREG:")),
1566            "expected +CREG in pending URC, got {:?}",
1567            urcs
1568        );
1569        assert!(waiter.wait(100).is_ok());
1570    }
1571
1572    // Kept: the 64 KiB cap, which the model's small chunks never reach.
1573    #[test]
1574    fn idle_buffer_drops_oldest_beyond_cap() {
1575        let shared = Arc::new(RxHubShared::new());
1576        let huge = vec![0u8; IDLE_BUFFER_CAP + 1024];
1577        shared.feed_bytes(&huge, &mut HubRoutingState::new("p".into()));
1578        assert!(crate::sync_util::lock_or_recover(&shared.idle).len() <= IDLE_BUFFER_CAP);
1579    }
1580
1581    // Kept beside the model (`model.rs`): the real `recv_timeout` path; the model ends reads by deadline + tick.
1582    #[test]
1583    fn read_request_times_out_without_bytes() {
1584        let shared = Arc::new(RxHubShared::new());
1585        let shared_bg = shared.clone();
1586        let reader = thread::spawn(move || shared_bg.read_request(64, 50, false));
1587        let result = reader.join().unwrap();
1588        assert!(result.is_err());
1589        let err = result.unwrap_err();
1590        assert!(
1591            err.contains("no data") || err.contains("timed out") || err.contains("timeout"),
1592            "unexpected: {err}"
1593        );
1594    }
1595
1596    // Kept: drain ends by idle time, which the model (deadline only) does not drive.
1597    #[test]
1598    fn try_complete_drain_takes_whole_slot() {
1599        let shared = RxHubShared::new();
1600        let (tx, rx) = mpsc::sync_channel(1);
1601        *crate::sync_util::lock_or_recover(&shared.drain) = Some(DrainSlot {
1602            idle_ms: 1,
1603            cancel: Arc::new(AtomicBool::new(false)),
1604            buffer: b"buf".to_vec(),
1605            last_byte_at: Some(Instant::now() - Duration::from_millis(50)),
1606            started_at: Instant::now() - Duration::from_millis(100),
1607            deadline: Instant::now() + Duration::from_secs(5),
1608            solicited_prefixes: vec![],
1609            tx,
1610        });
1611        try_complete_drain(&shared);
1612        assert!(crate::sync_util::lock_or_recover(&shared.drain).is_none());
1613        assert_eq!(rx.recv().unwrap().unwrap(), b"buf");
1614    }
1615
1616    #[test]
1617    fn try_complete_drain_empty_waits_idle_from_started_at() {
1618        let shared = RxHubShared::new();
1619        let (tx, rx) = mpsc::sync_channel(1);
1620        *crate::sync_util::lock_or_recover(&shared.drain) = Some(DrainSlot {
1621            idle_ms: 30,
1622            cancel: Arc::new(AtomicBool::new(false)),
1623            buffer: Vec::new(),
1624            last_byte_at: None,
1625            started_at: Instant::now(),
1626            deadline: Instant::now() + Duration::from_secs(5),
1627            solicited_prefixes: vec![],
1628            tx,
1629        });
1630        try_complete_drain(&shared);
1631        assert!(crate::sync_util::lock_or_recover(&shared.drain).is_some());
1632        thread::sleep(Duration::from_millis(40));
1633        try_complete_drain(&shared);
1634        assert!(crate::sync_util::lock_or_recover(&shared.drain).is_none());
1635        assert_eq!(rx.recv().unwrap().unwrap(), b"");
1636    }
1637
1638    fn wait_until_drain_slot(shared: &RxHubShared) {
1639        let start = Instant::now();
1640        while crate::sync_util::lock_or_recover(&shared.drain).is_none() {
1641            assert!(
1642                start.elapsed() < Duration::from_secs(2),
1643                "drain worker never installed slot"
1644            );
1645            thread::sleep(Duration::from_millis(1));
1646        }
1647    }
1648
1649    fn wait_until_read_slot(shared: &RxHubShared) {
1650        let start = Instant::now();
1651        while crate::sync_util::lock_or_recover(&shared.read_slot).is_none() {
1652            assert!(
1653                start.elapsed() < Duration::from_secs(2),
1654                "read worker never installed slot"
1655            );
1656            thread::sleep(Duration::from_millis(1));
1657        }
1658    }
1659
1660    // Kept: the timeout reclaim races of drain / read are not model steps.
1661    #[test]
1662    fn drain_timeout_recovers_result_already_posted() {
1663        let shared = Arc::new(RxHubShared::new());
1664        let cancel = Arc::new(AtomicBool::new(false));
1665        let shared_bg = shared.clone();
1666        let handle = thread::spawn(move || shared_bg.drain(10_000, 0, cancel, vec![]));
1667        wait_until_drain_slot(&shared);
1668        finish_drain(&shared, Ok(b"drained".to_vec()));
1669        assert_eq!(handle.join().unwrap().expect("recovered"), b"drained");
1670    }
1671
1672    #[test]
1673    fn drain_timeout_reclaim_returns_buffer_left_in_slot() {
1674        let shared = Arc::new(RxHubShared::new());
1675        let cancel = Arc::new(AtomicBool::new(false));
1676        let shared_bg = shared.clone();
1677        let handle = thread::spawn(move || shared_bg.drain(10_000, 0, cancel, vec![]));
1678        wait_until_drain_slot(&shared);
1679        {
1680            let mut guard = crate::sync_util::lock_or_recover(&shared.drain);
1681            let slot = guard.as_mut().expect("drain slot still live");
1682            slot.buffer.extend_from_slice(b"kept");
1683            slot.last_byte_at = Some(Instant::now());
1684        }
1685        assert_eq!(handle.join().unwrap().expect("slot buffer"), b"kept");
1686    }
1687
1688    #[test]
1689    fn drain_timeout_reclaim_empty_slot_is_timeout_error() {
1690        let shared = Arc::new(RxHubShared::new());
1691        let cancel = Arc::new(AtomicBool::new(false));
1692        let err = shared
1693            .drain(10_000, 0, cancel, vec![])
1694            .expect_err("empty reclaim");
1695        assert!(err.contains("drain timed out"), "unexpected: {err}");
1696    }
1697
1698    #[test]
1699    fn drain_timeout_preserves_finish_drain_error() {
1700        let shared = Arc::new(RxHubShared::new());
1701        let cancel = Arc::new(AtomicBool::new(false));
1702        let shared_bg = shared.clone();
1703        let handle = thread::spawn(move || shared_bg.drain(10_000, 0, cancel, vec![]));
1704        wait_until_drain_slot(&shared);
1705        finish_drain(&shared, Err("drain read failed: boom".into()));
1706        let err = handle.join().unwrap().expect_err("posted Err");
1707        assert!(
1708            err.contains("drain read failed"),
1709            "must not rewrite to generic timeout, got: {err}"
1710        );
1711    }
1712
1713    #[test]
1714    fn read_request_timeout_recovers_result_already_posted() {
1715        let shared = Arc::new(RxHubShared::new());
1716        let shared_bg = shared.clone();
1717        let handle = thread::spawn(move || shared_bg.read_request(64, 500, false));
1718        wait_until_read_slot(&shared);
1719        finish_read_slot(&shared, Ok(b"late".to_vec()));
1720        assert_eq!(handle.join().unwrap().expect("recovered"), b"late");
1721    }
1722
1723    fn at_csq_options() -> ResolvedExchangeOptions {
1724        ResolvedExchangeOptions {
1725            timeout_ms: 5000,
1726            max_bytes: 4096,
1727            terminators: vec![],
1728            idle_ms: None,
1729            rx_prepare: RxPrepareMode::None,
1730            drain_idle_ms: 50,
1731            drain_max_ms: 200,
1732            completion_mode: ExchangeCompletionMode::AtFinalLine,
1733            result_format: AtResultFormat::Verbose,
1734            command: Some("AT+CSQ".into()),
1735            solicited_prefixes: vec![],
1736        }
1737    }
1738
1739    fn decode_hex(s: &str) -> Vec<u8> {
1740        (0..s.len())
1741            .step_by(2)
1742            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex"))
1743            .collect()
1744    }
1745
1746    #[test]
1747    fn hub_script_creg_csq_ok_fixture_feeds_urc_and_completes() {
1748        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1749            .join("tests/fixtures/hub_scripts/creg_csq_ok.json");
1750        let text = std::fs::read_to_string(&path).expect("fixture");
1751        let fixture: serde_json::Value = serde_json::from_str(&text).expect("json");
1752        let command = fixture["command"].as_str().unwrap();
1753        let chunks: Vec<Vec<u8>> = fixture["chunks_hex"]
1754            .as_array()
1755            .unwrap()
1756            .iter()
1757            .map(|v| decode_hex(v.as_str().unwrap()))
1758            .collect();
1759        let expected_urc = fixture["expected_urc_contains"].as_str().unwrap();
1760        let expected_match = fixture["expected_match"].as_str().unwrap();
1761
1762        let shared = RxHubShared::new();
1763        let channel = {
1764            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1765            c
1766        };
1767        shared.attach_watch_with(channel, 100, 1024, false, None);
1768        let mut options = at_csq_options();
1769        options.command = Some(command.to_string());
1770        let waiter = ExchangeWaiter::new(options, Arc::new(AtomicBool::new(false)));
1771        shared.set_exchange_waiter(waiter.clone());
1772
1773        let mut routing = HubRoutingState::new("p".into());
1774        for chunk in &chunks {
1775            shared.feed_bytes(chunk, &mut routing);
1776        }
1777
1778        let urcs: Vec<_> = routing
1779            .pending_events
1780            .iter()
1781            .map(|(_, e)| e)
1782            .filter_map(|e| match e {
1783                SerialEvent::Urc { line, .. } => Some(line.clone()),
1784                _ => None,
1785            })
1786            .collect();
1787        assert!(
1788            urcs.iter().any(|l| l.contains(expected_urc)),
1789            "expected {expected_urc} in {:?}",
1790            urcs
1791        );
1792        let (_, matched) = waiter.wait(100).expect("complete");
1793        match expected_match {
1794            "ok" => assert!(
1795                matches!(matched, ExchangeMatch::Ok),
1796                "expected Ok, got {matched:?}"
1797            ),
1798            "error" => assert!(
1799                matches!(matched, ExchangeMatch::Error),
1800                "expected Error, got {matched:?}"
1801            ),
1802            other => panic!("unsupported expected_match `{other}` in fixture"),
1803        }
1804    }
1805
1806    #[test]
1807    fn feed_bytes_chunked_vs_oneshot_same_exchange_match() {
1808        let transcript = b"\r\n+CREG: 0,1\r\n\r\nAT+CSQ\r\n\r\n+CSQ: 10,99\r\n\r\nOK\r\n";
1809
1810        let run = |chunks: Vec<&[u8]>| {
1811            let shared = RxHubShared::new();
1812            let waiter = ExchangeWaiter::new(at_csq_options(), Arc::new(AtomicBool::new(false)));
1813            shared.set_exchange_waiter(waiter.clone());
1814            let mut routing = HubRoutingState::new("p".into());
1815            for chunk in chunks {
1816                shared.feed_bytes(chunk, &mut routing);
1817            }
1818            waiter.wait(100).expect("complete").1
1819        };
1820
1821        let oneshot = run(vec![&transcript[..]]);
1822        let bytewise = run(transcript.chunks(1).collect());
1823        assert_eq!(oneshot, bytewise);
1824        assert!(matches!(oneshot, ExchangeMatch::Ok));
1825    }
1826
1827    // --- Native parser on the watch ---
1828
1829    fn parser(json: serde_json::Value) -> Option<Box<dyn Framer>> {
1830        let cfg: serial_codec::framing::FramerConfig = serde_json::from_value(json).unwrap();
1831        Some(cfg.build().unwrap())
1832    }
1833
1834    /// Channel that records every event, in order.
1835    fn recording_channel() -> (crate::events::EventSink, Arc<Mutex<Vec<SerialEvent>>>) {
1836        let events = Arc::new(Mutex::new(Vec::new()));
1837        let sink = events.clone();
1838        let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
1839            sink.lock().unwrap().push(event);
1840            true
1841        });
1842        (channel, events)
1843    }
1844
1845    fn evs(queued: &[QueuedEvent]) -> Vec<SerialEvent> {
1846        queued.iter().map(|(_, e)| e.clone()).collect()
1847    }
1848
1849    fn data_frames(events: &[SerialEvent]) -> Vec<Vec<u8>> {
1850        events
1851            .iter()
1852            .filter_map(|e| match e {
1853                SerialEvent::Data { data, size, .. } => {
1854                    assert_eq!(*size, data.len());
1855                    Some(data.clone())
1856                }
1857                _ => None,
1858            })
1859            .collect()
1860    }
1861
1862    #[test]
1863    fn parser_readline_frames_across_split_chunks_without_batching() {
1864        let shared = RxHubShared::new();
1865        let channel = {
1866            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1867            c
1868        };
1869        shared.attach_watch_with(
1870            channel,
1871            10_000,
1872            1024,
1873            false,
1874            parser(serde_json::json!({"type": "readline", "delimiter": "\r\n"})),
1875        );
1876        let mut routing = HubRoutingState::new("p".into());
1877        for chunk in [&b"$GPGGA,1"[..], b"23\r", b"\n$GPRMC\r\nPART"] {
1878            shared.feed_bytes(chunk, &mut routing);
1879        }
1880        // Frames are ready at once: no batch timer, nothing left in the batch buffer.
1881        assert!(routing.combined_buffer.is_empty());
1882        assert_eq!(
1883            data_frames(&evs(&routing.pending_events)),
1884            vec![b"$GPGGA,123".to_vec(), b"$GPRMC".to_vec()]
1885        );
1886    }
1887
1888    #[test]
1889    fn parser_inter_byte_timeout_fires_from_tick_without_more_data() {
1890        let shared = RxHubShared::new();
1891        let channel = {
1892            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1893            c
1894        };
1895        shared.attach_watch_with(
1896            channel,
1897            10_000,
1898            1024,
1899            false,
1900            parser(serde_json::json!({"type": "interByteTimeout", "interval": 20})),
1901        );
1902        let mut routing = HubRoutingState::new("p".into());
1903        shared.feed_bytes(b"\x01\x02", &mut routing);
1904        shared.feed_bytes(b"\x03", &mut routing);
1905        shared.tick("p", &mut routing);
1906        assert!(routing.pending_events.is_empty(), "silence not over yet");
1907        let deadline = crate::sync_util::lock_or_recover(&shared.watch)
1908            .as_ref()
1909            .and_then(|w| w.framer.as_ref()?.deadline())
1910            .expect("deadline armed");
1911        thread::sleep(
1912            deadline.saturating_duration_since(Instant::now()) + Duration::from_millis(2),
1913        );
1914        shared.tick("p", &mut routing);
1915        assert_eq!(
1916            data_frames(&evs(&routing.pending_events)),
1917            vec![vec![1, 2, 3]]
1918        );
1919    }
1920
1921    #[test]
1922    fn parser_remainder_flushed_on_detach_and_before_disconnect() {
1923        let shared = RxHubShared::for_path("p".into());
1924        let (channel, events) = recording_channel();
1925        let cfg = serde_json::json!({"type": "readline"});
1926        shared.attach_watch_with(channel.clone(), 20, 1024, false, parser(cfg.clone()));
1927        let mut routing = HubRoutingState::new("p".into());
1928        shared.feed_bytes(b"done\ntail", &mut routing);
1929        shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
1930        shared.detach_watch();
1931        assert_eq!(
1932            data_frames(&events.lock().unwrap()),
1933            vec![b"done".to_vec(), b"tail".to_vec()]
1934        );
1935
1936        events.lock().unwrap().clear();
1937        shared.attach_watch_with(channel, 20, 1024, false, parser(cfg));
1938        shared.feed_bytes(b"half", &mut routing);
1939        shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
1940        shared.emit_disconnect("p", "gone");
1941        let got = events.lock().unwrap().clone();
1942        assert_eq!(got.len(), 2, "{got:?}");
1943        assert!(matches!(&got[0], SerialEvent::Data { data, .. } if data == b"half"));
1944        assert!(matches!(&got[1], SerialEvent::Disconnect { .. }));
1945    }
1946
1947    /// Android: the hub loop and `fail_port` both report one disconnect; every stream
1948    /// still gets exactly one `Disconnect`.
1949    #[test]
1950    fn disconnect_is_sent_once_per_stream() {
1951        let shared = RxHubShared::for_path("p".into());
1952        let (old, old_events) = recording_channel();
1953        let (core, core_events) = recording_channel();
1954        shared.attach_watch_with(old, 20, 1024, false, None);
1955        shared.attach_core_watch(CoreWatchSlot::new(
1956            1,
1957            core,
1958            Arc::new(std::sync::atomic::AtomicBool::new(true)),
1959            20,
1960            1024,
1961            false,
1962            None,
1963        ));
1964        shared.emit_disconnect("p", "gone");
1965        shared.emit_disconnect("p", "gone again");
1966        for events in [old_events, core_events] {
1967            let n = events
1968                .lock()
1969                .unwrap()
1970                .iter()
1971                .filter(|e| matches!(e, SerialEvent::Disconnect { .. }))
1972                .count();
1973            assert_eq!(n, 1);
1974        }
1975    }
1976
1977    #[test]
1978    fn parser_with_route_urc_splits_urc_first() {
1979        let shared = RxHubShared::new();
1980        let channel = {
1981            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
1982            c
1983        };
1984        shared.attach_watch_with(
1985            channel,
1986            10_000,
1987            1024,
1988            true,
1989            parser(serde_json::json!({"type": "readline", "delimiter": "\r\n"})),
1990        );
1991        let mut routing = HubRoutingState::new("p".into());
1992        shared.feed_bytes(b"+CREG: 0,1\r\nhello\r\nwor", &mut routing);
1993        shared.feed_bytes(b"ld\r\n", &mut routing);
1994        let urcs: Vec<_> = routing
1995            .pending_events
1996            .iter()
1997            .map(|(_, e)| e)
1998            .filter_map(|e| match e {
1999                SerialEvent::Urc { line, .. } => Some(line.as_str()),
2000                _ => None,
2001            })
2002            .collect();
2003        assert_eq!(urcs, vec!["+CREG: 0,1"]);
2004        assert_eq!(
2005            data_frames(&evs(&routing.pending_events)),
2006            vec![b"hello".to_vec(), b"world".to_vec()]
2007        );
2008    }
2009
2010    /// Regression: drain URCs were judged per read chunk, so a `+CMT:` header went out
2011    /// without the PDU line that arrived in the next chunk.
2012    #[test]
2013    fn drain_emits_two_line_urc_together_across_chunks() {
2014        let shared = Arc::new(RxHubShared::for_path("p".into()));
2015        let (channel, events) = recording_channel();
2016        shared.attach_watch_with(channel, 20, 1024, false, None);
2017        let bg = shared.clone();
2018        let handle =
2019            thread::spawn(move || bg.drain(20, 2_000, Arc::new(AtomicBool::new(false)), vec![]));
2020        wait_until_drain_slot(&shared);
2021        let mut routing = HubRoutingState::new("p".into());
2022        shared.feed_bytes(b"\r\n+CMT: ,23\r\n", &mut routing);
2023        shared.feed_bytes(b"0791447758100650\r\nOK\r\n", &mut routing);
2024        thread::sleep(Duration::from_millis(30));
2025        shared.tick("p", &mut routing);
2026        shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
2027        handle.join().unwrap().expect("drain");
2028        let urcs: Vec<String> = events
2029            .lock()
2030            .unwrap()
2031            .iter()
2032            .filter_map(|e| match e {
2033                SerialEvent::Urc { line, path } => {
2034                    assert_eq!(path, "p");
2035                    Some(line.clone())
2036                }
2037                _ => None,
2038            })
2039            .collect();
2040        assert_eq!(urcs, vec!["+CMT: ,23", "0791447758100650"]);
2041    }
2042
2043    #[test]
2044    fn no_parser_watch_still_batches_until_tick() {
2045        let shared = RxHubShared::new();
2046        let channel = {
2047            let c: crate::events::EventSink = Arc::new(|_: SerialEvent| true);
2048            c
2049        };
2050        shared.attach_watch_with(channel, 0, 1024, false, None);
2051        let mut routing = HubRoutingState::new("p".into());
2052        shared.feed_bytes(b"a\nb", &mut routing);
2053        shared.feed_bytes(b"\nc", &mut routing);
2054        assert!(routing.pending_events.is_empty());
2055        assert_eq!(routing.combined_buffer, b"a\nb\nc");
2056        shared.tick("p", &mut routing);
2057        assert_eq!(
2058            data_frames(&evs(&routing.pending_events)),
2059            vec![b"a\nb\nc".to_vec()]
2060        );
2061    }
2062
2063    #[test]
2064    fn cancel_during_active_drain_completes_with_error() {
2065        let shared = Arc::new(RxHubShared::new());
2066        let cancel = Arc::new(AtomicBool::new(false));
2067        let shared_bg = shared.clone();
2068        let cancel_bg = cancel.clone();
2069        let handle = thread::spawn(move || shared_bg.drain(10_000, 5_000, cancel_bg, vec![]));
2070        wait_until_drain_slot(&shared);
2071        cancel.store(true, Ordering::SeqCst);
2072        shared.tick("p", &mut HubRoutingState::new("p".into()));
2073        let err = handle.join().unwrap().expect_err("drain must cancel");
2074        assert!(err.contains("cancel"), "unexpected: {err}");
2075    }
2076
2077    /// Audit p1: `unwatch` ran between the hub's `feed_bytes` (frame `a` decoded) and
2078    /// its `dispatch_queued_events`. Frame `a` was dropped and remainder `b` delivered.
2079    #[test]
2080    fn detach_between_feed_and_dispatch_keeps_frames_before_remainder() {
2081        let shared = RxHubShared::for_path("p".into());
2082        let (channel, events) = recording_channel();
2083        let cfg = serde_json::json!({"type": "delimiter", "delimiter": [10]});
2084        shared.attach_watch_with(channel, 20, 1024, false, parser(cfg));
2085        let mut routing = HubRoutingState::new("p".into());
2086        shared.feed_bytes(b"a\nb", &mut routing); // hub thread
2087        shared.detach_watch(); // API thread, inside the window
2088        shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events)); // hub
2089        assert_eq!(
2090            data_frames(&events.lock().unwrap()),
2091            vec![b"a".to_vec(), b"b".to_vec()]
2092        );
2093    }
2094
2095    /// Audit p3: drain-completion URCs went to the sink with the `drain` mutex held, so
2096    /// a sink touching the drain slot hung the hub thread.
2097    #[test]
2098    fn drain_urc_sink_may_start_a_drain() {
2099        let shared = Arc::new(RxHubShared::for_path("p".into()));
2100        let weak = Arc::downgrade(&shared);
2101        let (tx, rx) = mpsc::channel();
2102        let tx = Mutex::new(tx);
2103        let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
2104            if let SerialEvent::Urc { line, .. } = event {
2105                if let Some(shared) = weak.upgrade() {
2106                    let _ = shared.drain(1, 1, Arc::new(AtomicBool::new(false)), vec![]);
2107                }
2108                let _ = tx.lock().unwrap().send(line);
2109            }
2110            true
2111        });
2112        shared.attach_watch_with(channel, 20, 1024, true, None);
2113        let bg = shared.clone();
2114        let drainer =
2115            thread::spawn(move || bg.drain(10, 2_000, Arc::new(AtomicBool::new(false)), vec![]));
2116        wait_until_drain_slot(&shared);
2117        let hub = shared.clone();
2118        thread::spawn(move || {
2119            let mut routing = HubRoutingState::new("p".into());
2120            hub.feed_bytes(b"\r\n+CREG: 1\r\n", &mut routing);
2121            hub.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
2122            thread::sleep(Duration::from_millis(30));
2123            hub.tick("p", &mut routing);
2124            hub.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
2125        });
2126        let line = rx
2127            .recv_timeout(Duration::from_secs(3))
2128            .expect("hub thread hung: URC sink ran under the drain lock");
2129        assert_eq!(line, "+CREG: 1");
2130        drainer.join().unwrap().expect("drain");
2131    }
2132
2133    /// URCs collected by a drain that then ends with an error still reach the watch.
2134    #[test]
2135    fn drain_urcs_survive_a_failed_drain() {
2136        let shared = Arc::new(RxHubShared::for_path("p".into()));
2137        let (channel, events) = recording_channel();
2138        shared.attach_watch_with(channel, 20, 1024, true, None);
2139        let bg = shared.clone();
2140        let drainer = thread::spawn(move || {
2141            bg.drain(10_000, 5_000, Arc::new(AtomicBool::new(false)), vec![])
2142        });
2143        wait_until_drain_slot(&shared);
2144        let mut routing = HubRoutingState::new("p".into());
2145        shared.feed_bytes(b"\r\n+CMTI: \"SM\",3\r\n", &mut routing);
2146        shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
2147        shared.fail_all_waiters("usb error");
2148        assert!(drainer.join().unwrap().is_err());
2149        let got = events.lock().unwrap().clone();
2150        assert!(
2151            got.iter()
2152                .any(|e| matches!(e, SerialEvent::Urc { line, .. } if line.starts_with("+CMTI"))),
2153            "{got:?}"
2154        );
2155    }
2156
2157    /// A physical disconnect flushes CMUX channel watches too: remainder, then
2158    /// `Disconnect` on the virtual path.
2159    #[test]
2160    fn physical_disconnect_flushes_cmux_channel_watches() {
2161        struct NoopIo;
2162        impl crate::cmux::CmuxPhysicalIo for NoopIo {
2163            fn write_all(&self, _data: &[u8]) -> Result<(), String> {
2164                Ok(())
2165            }
2166        }
2167        let shared = RxHubShared::for_path("phys".into());
2168        let session = CmuxSession::with_n1("phys".into(), Arc::new(NoopIo), 31);
2169        session.register_dlci(2, "phys#dlci=2".into());
2170        let (channel, events) = recording_channel();
2171        session.set_watch_with(
2172            2,
2173            channel,
2174            10_000,
2175            parser(serde_json::json!({"type": "readline"})),
2176        );
2177        shared.attach_cmux(session);
2178        let mut routing = HubRoutingState::new("phys".into());
2179        shared.feed_bytes(&crate::cmux::encode_uih(2, b"one\ntail"), &mut routing);
2180        shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
2181        shared.emit_disconnect("phys", "gone");
2182        let got = events.lock().unwrap().clone();
2183        assert_eq!(data_frames(&got), vec![b"one".to_vec(), b"tail".to_vec()]);
2184        assert!(
2185            matches!(got.last(), Some(SerialEvent::Disconnect { path, .. }) if path == "phys#dlci=2"),
2186            "{got:?}"
2187        );
2188    }
2189
2190    // ------------------------------------------------ mutation-test coverage
2191
2192    type Recorded = Arc<Mutex<Vec<SerialEvent>>>;
2193
2194    fn core_slot(
2195        batch_ms: u64,
2196        read_size: usize,
2197        route_urc: bool,
2198        framer: Option<Box<dyn Framer>>,
2199    ) -> (CoreWatchSlot, Recorded) {
2200        let (sink, events) = recording_channel();
2201        let slot = CoreWatchSlot::new(
2202            1,
2203            sink,
2204            Arc::new(AtomicBool::new(true)),
2205            batch_ms,
2206            read_size,
2207            route_urc,
2208            framer,
2209        );
2210        (slot, events)
2211    }
2212
2213    fn data_of(routing: &HubRoutingState) -> Vec<Vec<u8>> {
2214        data_frames(&evs(&routing.pending_events))
2215    }
2216
2217    #[test]
2218    fn idle_buffer_holds_64_kib() {
2219        let shared = RxHubShared::new();
2220        shared.feed_bytes(&[7u8; 10_000], &mut HubRoutingState::new("p".into()));
2221        assert_eq!(shared.buffered_len(), 10_000);
2222        assert_eq!(IDLE_BUFFER_CAP, 64 * 1024);
2223    }
2224
2225    #[test]
2226    fn plain_watch_flushes_on_its_timer_with_the_line_tail() {
2227        let shared = RxHubShared::new();
2228        let (sink, _) = recording_channel();
2229        shared.attach_watch_with(sink, 0, 1024, true, None);
2230        let mut routing = HubRoutingState::new("p".into());
2231        shared.feed_bytes(b"abc", &mut routing);
2232        assert_eq!(
2233            shared.pending_watch_bytes(&routing),
2234            0,
2235            "held by the line router"
2236        );
2237        shared.tick("p", &mut routing);
2238        assert_eq!(data_of(&routing), vec![b"abc".to_vec()]);
2239
2240        let shared = RxHubShared::new();
2241        let (sink, _) = recording_channel();
2242        shared.attach_watch_with(sink, 10_000, 1024, false, None);
2243        let mut routing = HubRoutingState::new("p".into());
2244        shared.feed_bytes(b"abcde", &mut routing);
2245        assert_eq!(shared.pending_watch_bytes(&routing), 5);
2246        shared.tick("p", &mut routing);
2247        assert!(
2248            routing.pending_events.is_empty(),
2249            "flushed before the window"
2250        );
2251    }
2252
2253    #[test]
2254    fn flush_now_sends_the_line_tail() {
2255        let shared = RxHubShared::new();
2256        let (sink, _) = recording_channel();
2257        shared.attach_watch_with(sink, 10_000, 1024, true, None);
2258        let mut routing = HubRoutingState::new("p".into());
2259        shared.feed_bytes(b"abc", &mut routing);
2260        shared.flush_watch_now(&mut routing);
2261        assert_eq!(data_of(&routing), vec![b"abc".to_vec()]);
2262    }
2263
2264    #[test]
2265    fn parser_watch_gets_the_line_tail_on_its_timer() {
2266        let shared = RxHubShared::new();
2267        let (sink, _) = recording_channel();
2268        let three = || parser(serde_json::json!({"type": "byteLength", "length": 3}));
2269        shared.attach_watch_with(sink, 0, 1024, true, three());
2270        let mut routing = HubRoutingState::new("p".into());
2271        shared.feed_bytes(b"abc", &mut routing);
2272        assert!(routing.pending_events.is_empty(), "held by the line router");
2273        shared.tick("p", &mut routing);
2274        assert_eq!(data_of(&routing), vec![b"abc".to_vec()]);
2275
2276        // The same for a `watch_core` stream.
2277        let shared = RxHubShared::new();
2278        let (slot, _) = core_slot(0, 1024, true, three());
2279        shared.attach_core_watch(slot);
2280        let mut routing = HubRoutingState::new("p".into());
2281        shared.feed_bytes(b"abc", &mut routing);
2282        assert!(routing.pending_events.is_empty());
2283        shared.tick("p", &mut routing);
2284        assert_eq!(data_of(&routing), vec![b"abc".to_vec()]);
2285    }
2286
2287    #[test]
2288    fn core_watch_batches_by_timer_and_size() {
2289        let tick_once = |slot: CoreWatchSlot, bytes: &[u8]| {
2290            let shared = RxHubShared::new();
2291            shared.attach_core_watch(slot);
2292            let mut routing = HubRoutingState::new("p".into());
2293            shared.feed_bytes(bytes, &mut routing);
2294            shared.tick("p", &mut routing);
2295            data_of(&routing)
2296        };
2297        assert!(tick_once(core_slot(10_000, 1024, false, None).0, b"abc").is_empty());
2298        assert_eq!(
2299            tick_once(core_slot(0, 1024, false, None).0, b"abc"),
2300            vec![b"abc".to_vec()]
2301        );
2302        assert_eq!(
2303            tick_once(core_slot(10_000, 4, false, None).0, b"abcdef"),
2304            vec![b"abcdef".to_vec()],
2305            "a full read size goes out before the window"
2306        );
2307        assert_eq!(
2308            tick_once(core_slot(0, 1024, true, None).0, b"abc"),
2309            vec![b"abc".to_vec()],
2310            "line tail on the timer"
2311        );
2312    }
2313
2314    #[test]
2315    fn emit_urc_to_sends_one_urc() {
2316        let (sink, events) = recording_channel();
2317        emit_urc_to(&sink, "p", "+CREG: 1");
2318        assert!(matches!(
2319            events.lock().unwrap().as_slice(),
2320            [SerialEvent::Urc { path, line }] if path == "p" && line == "+CREG: 1"
2321        ));
2322    }
2323
2324    #[test]
2325    fn closing_flag_and_emit() {
2326        let shared = RxHubShared::new();
2327        assert!(!shared.is_closing());
2328        shared.mark_closing();
2329        assert!(shared.is_closing());
2330        let (sink, events) = recording_channel();
2331        shared.attach_watch_with(sink, 10, 64, false, None);
2332        shared.emit(SerialEvent::Error {
2333            path: "p".into(),
2334            message: "m".into(),
2335        });
2336        assert_eq!(events.lock().unwrap().len(), 1);
2337    }
2338
2339    #[test]
2340    fn framer_deadline_and_read_size_cover_every_watch() {
2341        let shared = RxHubShared::new();
2342        assert_eq!(shared.next_framer_deadline(), None);
2343        assert_eq!(shared.read_size(), None);
2344        let ibt = || parser(serde_json::json!({"type": "interByteTimeout", "interval": 500}));
2345        shared.attach_core_watch(core_slot(10, 16, false, None).0);
2346        shared.attach_core_watch(core_slot(10, 64, false, ibt()).0);
2347        assert_eq!(shared.read_size(), Some(64));
2348        shared.feed_bytes(b"x", &mut HubRoutingState::new("p".into()));
2349        assert!(shared.next_framer_deadline().is_some(), "core parser armed");
2350        let (sink, _) = recording_channel();
2351        shared.attach_watch_with(sink, 10, 8, false, ibt());
2352        assert_eq!(shared.read_size(), Some(8), "the old watch's size wins");
2353    }
2354
2355    fn drain_slot(tx: ByteResultTx, idle_ms: u64, deadline: Instant, buffer: &[u8]) -> DrainSlot {
2356        DrainSlot {
2357            idle_ms,
2358            cancel: Arc::new(AtomicBool::new(false)),
2359            buffer: buffer.to_vec(),
2360            last_byte_at: None,
2361            started_at: Instant::now(),
2362            deadline,
2363            solicited_prefixes: vec![],
2364            tx,
2365        }
2366    }
2367
2368    #[test]
2369    fn drain_urcs_reach_core_watches_without_an_old_watch() {
2370        let shared = RxHubShared::for_path("p".into());
2371        let (slot, events) = core_slot(10, 64, true, None);
2372        shared.attach_core_watch(slot);
2373        let (tx, _rx) = mpsc::sync_channel(1);
2374        *crate::sync_util::lock_or_recover(&shared.drain) = Some(drain_slot(
2375            tx,
2376            10_000,
2377            Instant::now() + Duration::from_secs(10),
2378            b"\r\n+CREG: 1\r\n",
2379        ));
2380        finish_drain(&shared, Ok(Vec::new()));
2381        assert!(
2382            events
2383                .lock()
2384                .unwrap()
2385                .iter()
2386                .any(|e| matches!(e, SerialEvent::Urc { line, .. } if line == "+CREG: 1")),
2387            "{:?}",
2388            events.lock().unwrap()
2389        );
2390    }
2391}