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