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 crate::hub::stream::{call_sink, EventStream, Target, WatchOwner};
9use serial_codec::framing::Framer;
10use std::sync::atomic::{AtomicBool, AtomicU64, 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
17/// What waits on a port (or CMUX channel) fails with this when it is closed.
18pub(crate) const PORT_CLOSED: &str = "port closed";
19
20type ExchangeDone = Arc<(
21    Mutex<Option<Result<(Vec<u8>, ExchangeMatch), String>>>,
22    Condvar,
23)>;
24type ByteResultTx = SyncSender<Result<Vec<u8>, String>>;
25
26/// Actions produced when routing incoming bytes in streaming mode.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum RxRouteAction {
29    StreamData(Vec<u8>),
30    UrcLine(String),
31}
32
33/// Session waiting for an exchange to complete.
34pub struct ExchangeWaiter {
35    pub options: ResolvedExchangeOptions,
36    buffer: Mutex<(Vec<u8>, Completion)>,
37    done: ExchangeDone,
38    pub cancel: Arc<AtomicBool>,
39    /// Set by the first `finish`; later results (a late cancel / failure) are ignored.
40    finished: AtomicBool,
41}
42
43impl ExchangeWaiter {
44    pub fn new(options: ResolvedExchangeOptions, cancel: Arc<AtomicBool>) -> Arc<Self> {
45        Arc::new(Self {
46            buffer: Mutex::new((Vec::new(), Completion::new(&options))),
47            options,
48            done: Arc::new((Mutex::new(None), Condvar::new())),
49            cancel,
50            finished: AtomicBool::new(false),
51        })
52    }
53
54    pub fn push_bytes(&self, chunk: &[u8]) {
55        let mut guard = crate::sync_util::lock_or_recover(&self.buffer);
56        let (buffer, completion) = &mut *guard;
57        buffer.extend_from_slice(chunk);
58        if self.cancel.load(Ordering::SeqCst) {
59            self.finish(Err("exchange cancelled".into()));
60            return;
61        }
62        if buffer.len() >= self.options.max_bytes {
63            self.finish(Err(format!(
64                "exchange response exceeded {} bytes",
65                self.options.max_bytes
66            )));
67            return;
68        }
69        if let Some(matched) = completion.push(buffer, chunk.len()) {
70            let raw = std::mem::take(buffer);
71            *completion = Completion::new(&self.options);
72            self.finish(Ok((raw, matched)));
73        }
74    }
75
76    pub fn wait(self: &Arc<Self>, timeout_ms: u64) -> Result<(Vec<u8>, ExchangeMatch), String> {
77        let (lock, cvar) = &*self.done;
78        let mut guard = crate::sync_util::lock_or_recover(lock);
79        let deadline = Instant::now() + Duration::from_millis(timeout_ms);
80        while guard.is_none() {
81            if self.cancel.load(Ordering::SeqCst) {
82                return Err("exchange cancelled".into());
83            }
84            let remaining = deadline.saturating_duration_since(Instant::now());
85            if remaining.is_zero() {
86                return Err(format!("exchange timed out after {} ms", timeout_ms));
87            }
88            let (g, timeout) = cvar
89                .wait_timeout(guard, remaining.min(Duration::from_millis(50)))
90                .map_err(|e| e.to_string())?;
91            guard = g;
92            if guard.is_none() && timeout.timed_out() && Instant::now() >= deadline {
93                return Err(format!("exchange timed out after {} ms", timeout_ms));
94            }
95        }
96        guard.take().unwrap()
97    }
98
99    /// The first result wins: a reply that already completed is not replaced by a
100    /// cancel or failure arriving after it.
101    fn finish(&self, result: Result<(Vec<u8>, ExchangeMatch), String>) {
102        let (lock, cvar) = &*self.done;
103        let mut guard = crate::sync_util::lock_or_recover(lock);
104        if !self.finished.swap(true, Ordering::SeqCst) {
105            *guard = Some(result);
106        }
107        cvar.notify_all();
108    }
109
110    /// Fail an in-flight exchange immediately (e.g. USB error teardown).
111    pub fn fail_with_reason(&self, reason: String) {
112        self.finish(Err(reason));
113    }
114}
115
116/// Line-oriented router for streaming when no exchange is active (`route_urc`).
117///
118/// Data lines go out byte-for-byte, terminator included; only URC lines are pulled out.
119/// An unfinished line is held until the next chunk (or the batch flush), so a URC split
120/// across two reads is still recognised and UTF-8 characters are never cut in half.
121#[derive(Debug, Default)]
122pub struct LineRouter {
123    partial: Vec<u8>,
124}
125
126impl LineRouter {
127    // ponytail: splits on LF only, so outside an exchange the quoted multi-line `+CUSD`
128    // join and the glued `OK+CUSD:` peel of `serial_codec::at::split_lines` do not apply
129    // here. Reusing them needs an incremental, byte-preserving splitter exported from
130    // `at.rs` (the one in `ExchangeDemux::process_chunk` is private and returns trimmed
131    // text, while this router must forward data lines byte-for-byte).
132    pub fn route_streaming(
133        &mut self,
134        chunk: &[u8],
135        solicited_prefixes: &[String],
136    ) -> Vec<RxRouteAction> {
137        self.partial.extend_from_slice(chunk);
138        let mut actions = Vec::new();
139        while let Some(pos) = self.partial.iter().position(|&b| b == b'\n') {
140            let raw: Vec<u8> = self.partial.drain(..=pos).collect();
141            let line = String::from_utf8_lossy(&raw).trim().to_string();
142            if !line.is_empty()
143                && is_likely_urc(&line, solicited_prefixes)
144                && classify_final_line(&line).is_none()
145            {
146                actions.push(RxRouteAction::UrcLine(line));
147            } else {
148                actions.push(RxRouteAction::StreamData(raw));
149            }
150        }
151        actions
152    }
153
154    /// Unfinished line bytes (handed to the data stream on batch flush).
155    pub fn take_partial(&mut self) -> Vec<u8> {
156        std::mem::take(&mut self.partial)
157    }
158}
159
160/// An event and the sink it was produced for (captured when it was produced, so an
161/// `unwatch` racing the hub cannot drop frames that were already decoded).
162pub type QueuedEvent = (EventSink, SerialEvent);
163
164pub use crate::hub::stream::Outbox;
165
166/// 4.0.0 API (feature `tauri`): [`emit_urc_to`] for a Tauri channel.
167#[cfg(feature = "tauri")]
168pub fn emit_urc(channel: &tauri::ipc::Channel<SerialEvent>, path: &str, line: &str) {
169    let _ = channel.send(SerialEvent::Urc {
170        path: path.to_string(),
171        line: line.to_string(),
172    });
173}
174
175pub fn emit_urc_to(channel: &crate::events::EventSink, path: &str, line: &str) {
176    let event = SerialEvent::Urc {
177        path: path.to_string(),
178        line: line.to_string(),
179    };
180    let _ = call_sink(channel, event);
181}
182
183/// Per-port routing state shared between desktop poll loop and Android push feed.
184///
185/// Since 4.2 each watch owns its line router and batch, and events are queued in the hub as
186/// they are produced: [`Self::line_router`], [`Self::combined_buffer`], [`Self::flush_at`]
187/// and [`Self::pending_events`] stay for the 4.x API only. The hub neither fills nor reads
188/// them: [`RxHubShared::deliver_queued`] delivers what a routing call produced.
189pub struct HubRoutingState {
190    pub path: String,
191    /// Not used any more.
192    pub line_router: LineRouter,
193    /// URC demux for the exchange it was built for; rebuilt when the waiter changes.
194    pub exchange_demux: Option<(Arc<ExchangeWaiter>, ExchangeDemux)>,
195    /// Not used any more.
196    pub combined_buffer: Vec<u8>,
197    /// Not used any more.
198    pub flush_at: Instant,
199    /// Not filled any more; [`RxHubShared::dispatch_queued_events`] still delivers what it
200    /// is given, after the hub's own events.
201    pub pending_events: Vec<QueuedEvent>,
202}
203
204impl HubRoutingState {
205    pub fn new(path: String) -> Self {
206        Self {
207            path,
208            line_router: LineRouter::default(),
209            exchange_demux: None,
210            combined_buffer: Vec::new(),
211            flush_at: Instant::now(),
212            pending_events: Vec::new(),
213        }
214    }
215}
216
217/// One watch (the old one, or a [`SerialManager::watch_core`](crate::SerialManager::watch_core)
218/// stream): its own line router, batch buffer and parser over the hub's byte stream, so one
219/// watch's state never affects another's and all of it goes out when the watch ends.
220///
221/// With `route_urc` the URC split runs before the parser, which sees only the data lines:
222/// `onUrc` keeps its meaning whatever the parser, and a parser never has to know AT syntax.
223/// The line router's unterminated tail follows on the batch timer.
224pub(crate) struct CoreWatchSlot {
225    pub(crate) id: u64,
226    pub(crate) target: Target,
227    pub(crate) batch_timeout_ms: u64,
228    pub(crate) read_size: usize,
229    pub(crate) route_urc: bool,
230    pub(crate) framer: Option<Box<dyn Framer>>,
231    pub(crate) line_router: LineRouter,
232    pub(crate) buffer: Vec<u8>,
233    pub(crate) flush_at: Instant,
234}
235
236impl CoreWatchSlot {
237    /// `id` 0: the old watch.
238    pub(crate) fn new(
239        id: u64,
240        target: Target,
241        batch_timeout_ms: u64,
242        read_size: usize,
243        route_urc: bool,
244        framer: Option<Box<dyn Framer>>,
245    ) -> Self {
246        Self {
247            id,
248            target,
249            batch_timeout_ms,
250            read_size,
251            route_urc,
252            framer,
253            line_router: LineRouter::default(),
254            buffer: Vec::new(),
255            flush_at: Instant::now(),
256        }
257    }
258
259    /// Bytes past the URC split: into the parser (one event per frame) or the batch.
260    fn sink_bytes(&mut self, path: &str, bytes: &[u8], out: &mut Vec<SerialEvent>) {
261        match self.framer.as_mut() {
262            Some(f) => {
263                let mut frames = Vec::new();
264                f.push(bytes, Instant::now(), &mut frames);
265                push_frames(path, frames, out);
266            }
267            None => self.buffer.extend_from_slice(bytes),
268        }
269    }
270
271    fn feed(&mut self, path: &str, chunk: &[u8], out: &mut Vec<SerialEvent>) {
272        if !self.route_urc {
273            self.sink_bytes(path, chunk, out);
274            return;
275        }
276        for action in self.line_router.route_streaming(chunk, &[]) {
277            match action {
278                RxRouteAction::UrcLine(line) => out.push(SerialEvent::Urc {
279                    path: path.to_string(),
280                    line,
281                }),
282                RxRouteAction::StreamData(bytes) => self.sink_bytes(path, &bytes, out),
283            }
284        }
285    }
286
287    fn tick(&mut self, path: &str, out: &mut Vec<SerialEvent>) {
288        let timer = self.flush_at.elapsed() >= Duration::from_millis(self.batch_timeout_ms);
289        if self.framer.is_some() {
290            if timer {
291                self.flush_at = Instant::now();
292                let partial = self.line_router.take_partial();
293                if !partial.is_empty() {
294                    self.sink_bytes(path, &partial, out);
295                }
296            }
297            let mut frames = Vec::new();
298            if let Some(f) = self.framer.as_mut() {
299                f.poll(Instant::now(), &mut frames);
300            }
301            push_frames(path, frames, out);
302            return;
303        }
304        if timer || self.buffer.len() >= self.read_size.max(1) {
305            self.flush_at = Instant::now();
306            self.flush_buffers(path, out);
307        }
308    }
309
310    /// Line-router tail and batch out now (parser state kept).
311    fn flush_buffers(&mut self, path: &str, out: &mut Vec<SerialEvent>) {
312        let partial = self.line_router.take_partial();
313        if !partial.is_empty() {
314            self.sink_bytes(path, &partial, out);
315        }
316        let data = std::mem::take(&mut self.buffer);
317        if !data.is_empty() {
318            out.push(data_event(path, data));
319        }
320    }
321
322    /// End of stream: batch, then the parser's remainder.
323    fn finish(&mut self, path: &str, out: &mut Vec<SerialEvent>) {
324        self.flush_buffers(path, out);
325        if let Some(rest) = self.framer.as_mut().and_then(|f| f.flush()) {
326            out.push(data_event(path, rest));
327        }
328    }
329
330    /// [`Self::finish`], then `last`: nothing more is sent.
331    fn end(&mut self, path: &str, last: Option<&SerialEvent>) {
332        let mut out = Vec::new();
333        self.finish(path, &mut out);
334        out.extend(last.cloned());
335        self.target.end(&mut out);
336    }
337}
338
339fn data_event(path: &str, data: Vec<u8>) -> SerialEvent {
340    SerialEvent::Data {
341        path: path.to_string(),
342        size: data.len(),
343        data,
344    }
345}
346
347fn push_frames(path: &str, frames: Vec<Vec<u8>>, out: &mut Vec<SerialEvent>) {
348    out.extend(frames.into_iter().map(|f| data_event(path, f)));
349}
350
351pub(crate) struct DrainSlot {
352    /// Whose slot this is: a caller that gives up takes only its own.
353    pub(crate) id: u64,
354    pub(crate) idle_ms: u64,
355    pub(crate) cancel: Arc<AtomicBool>,
356    pub(crate) buffer: Vec<u8>,
357    pub(crate) last_byte_at: Option<Instant>,
358    pub(crate) started_at: Instant,
359    pub(crate) deadline: Instant,
360    pub(crate) solicited_prefixes: Vec<String>,
361    pub(crate) tx: ByteResultTx,
362}
363
364pub(crate) struct ReadSlot {
365    /// See [`DrainSlot::id`].
366    pub(crate) id: u64,
367    pub(crate) max_bytes: usize,
368    pub(crate) fill: bool,
369    pub(crate) timeout_ms: u64,
370    pub(crate) buffer: Vec<u8>,
371    pub(crate) deadline: Instant,
372    pub(crate) tx: ByteResultTx,
373}
374
375/// Shared hub state between the RX thread and API handlers.
376pub struct RxHubShared {
377    pub(crate) exchange_waiter: Mutex<Option<Arc<ExchangeWaiter>>>,
378    pub(crate) watch: Mutex<Option<CoreWatchSlot>>,
379    pub(crate) drain: Mutex<Option<DrainSlot>>,
380    pub(crate) read_slot: Mutex<Option<ReadSlot>>,
381    pub(crate) idle: Mutex<Vec<u8>>,
382    pub(crate) cmux: Mutex<Option<Arc<CmuxSession>>>,
383    /// `watch_core` streams (any number, beside the one old watch).
384    pub(crate) core_watches: Mutex<Vec<CoreWatchSlot>>,
385    /// Set by an intentional close: a read error from now on is not a `Disconnect`, and
386    /// waiters fail at once.
387    closing: AtomicBool,
388    /// `Disconnect` went out (it is sent once, even when two paths report the loss).
389    disconnected: AtomicBool,
390    outbox: Outbox,
391    next_slot: AtomicU64,
392    /// Port path, for events sent outside the hub thread (watch remainder on detach).
393    path: String,
394}
395
396impl Default for RxHubShared {
397    fn default() -> Self {
398        Self::new()
399    }
400}
401
402impl RxHubShared {
403    pub fn new() -> Self {
404        Self::for_path(String::new())
405    }
406
407    pub fn for_path(path: String) -> Self {
408        Self {
409            path,
410            exchange_waiter: Mutex::new(None),
411            watch: Mutex::new(None),
412            drain: Mutex::new(None),
413            read_slot: Mutex::new(None),
414            idle: Mutex::new(Vec::new()),
415            cmux: Mutex::new(None),
416            core_watches: Mutex::new(Vec::new()),
417            closing: AtomicBool::new(false),
418            disconnected: AtomicBool::new(false),
419            outbox: Outbox::default(),
420            next_slot: AtomicU64::new(0),
421        }
422    }
423
424    /// 4.0.0 API (feature `tauri`): [`Self::attach_watch_with`] for a Tauri channel, no parser.
425    #[cfg(feature = "tauri")]
426    pub fn attach_watch(
427        &self,
428        channel: tauri::ipc::Channel<SerialEvent>,
429        batch_timeout_ms: u64,
430        read_size: usize,
431        route_urc: bool,
432    ) {
433        let sink = crate::events::channel_sink(channel);
434        self.attach_watch_with(sink, batch_timeout_ms, read_size, route_urc, None);
435    }
436
437    pub fn attach_watch_with(
438        &self,
439        channel: crate::events::EventSink,
440        batch_timeout_ms: u64,
441        read_size: usize,
442        route_urc: bool,
443        framer: Option<Box<dyn Framer>>,
444    ) {
445        self.attach_stream(channel, batch_timeout_ms, read_size, route_urc, framer);
446    }
447
448    /// [`Self::attach_watch_with`]; the stream is the watch's identity. A watch it replaces
449    /// ends with its tail queued.
450    pub(crate) fn attach_stream(
451        &self,
452        channel: EventSink,
453        batch_timeout_ms: u64,
454        read_size: usize,
455        route_urc: bool,
456        framer: Option<Box<dyn Framer>>,
457    ) -> Arc<EventStream> {
458        crate::sync_util::lock_or_recover(&self.idle).clear();
459        let stream = self.outbox.stream(channel);
460        let slot = CoreWatchSlot::new(
461            0,
462            Target::Old(stream.clone()),
463            batch_timeout_ms,
464            read_size,
465            route_urc,
466            framer,
467        );
468        let mut watch = crate::sync_util::lock_or_recover(&self.watch);
469        let mut replaced = watch.replace(slot);
470        if let Some(old) = replaced.as_mut() {
471            old.end(&self.path, None);
472        }
473        // Unlocked before the replaced watch's sink is dropped.
474        drop(watch);
475        stream
476    }
477
478    /// Take the old watch (if `which` accepts it); its tail is queued.
479    fn take_watch(&self, which: impl Fn(&CoreWatchSlot) -> bool) -> Option<CoreWatchSlot> {
480        let mut watch = crate::sync_util::lock_or_recover(&self.watch);
481        if !watch.as_ref().is_some_and(which) {
482            return None;
483        }
484        let mut slot = watch.take();
485        if let Some(slot) = slot.as_mut() {
486            slot.end(&self.path, None);
487        }
488        slot
489    }
490
491    /// Stop the watch; its batch, its unfinished line and its parser's remainder go out
492    /// last, after everything already decoded, before this returns (a sink that calls it
493    /// does not wait for another thread's delivery). Call with no lock held (the sink runs
494    /// here); under locks use [`Self::detach_watch_queued`] + [`Self::deliver_queued`].
495    pub fn detach_watch(&self) {
496        if let Some(CoreWatchSlot {
497            target: Target::Old(stream),
498            ..
499        }) = self.take_watch(|_| true)
500        {
501            self.outbox.settle(&stream);
502        }
503    }
504
505    /// [`Self::detach_watch`] without running the sink: its last events are queued.
506    pub fn detach_watch_queued(&self) {
507        self.take_watch(|_| true);
508    }
509
510    /// Add a `watch_core` stream (bytes from now on; idle bytes are dropped, as on attach).
511    pub(crate) fn attach_core_watch(&self, slot: CoreWatchSlot) {
512        crate::sync_util::lock_or_recover(&self.idle).clear();
513        crate::sync_util::lock_or_recover(&self.core_watches).push(slot);
514    }
515
516    /// Remove a `watch_core` stream; its batch and parser remainder go out last.
517    /// `false` when no such stream.
518    pub(crate) fn detach_core_watch(&self, id: u64) -> bool {
519        let mut cores = crate::sync_util::lock_or_recover(&self.core_watches);
520        let Some(i) = cores.iter().position(|c| c.id == id) else {
521            return false;
522        };
523        let mut slot = cores.remove(i);
524        slot.end(&self.path, None);
525        drop(cores);
526        true
527    }
528
529    pub fn has_core_watches(&self) -> bool {
530        !crate::sync_util::lock_or_recover(&self.core_watches).is_empty()
531    }
532
533    /// An intentional close begins: no `Disconnect` from here on, and what waits (or starts
534    /// to wait) fails, so a sink in an exchange does not hold up the close.
535    pub(crate) fn begin_close(&self) {
536        self.closing.store(true, Ordering::SeqCst);
537        self.fail_waiters(PORT_CLOSED);
538    }
539
540    /// Called by whoever installed a waiter, drain or read slot.
541    fn fail_if_closing(&self) {
542        if self.is_closing() {
543            self.fail_waiters(PORT_CLOSED);
544        }
545    }
546
547    /// The port is neither being closed nor lost.
548    pub(crate) fn check_open(&self) -> Result<(), String> {
549        if self.is_closing() {
550            return Err(PORT_CLOSED.into());
551        }
552        if self.disconnected.load(Ordering::SeqCst) {
553            return Err("Serial port disconnected".into());
554        }
555        Ok(())
556    }
557
558    pub(crate) fn is_closing(&self) -> bool {
559        self.closing.load(Ordering::SeqCst)
560    }
561
562    /// Run `f` over the old watch, then the `watch_core` streams (those whose sink is gone
563    /// are dropped first); what it produces is sent under the watch's lock, so nothing of a
564    /// watch is queued once it is detached. `false`: there was no watch.
565    fn each_watch(&self, mut f: impl FnMut(&mut CoreWatchSlot, &mut Vec<SerialEvent>)) -> bool {
566        let mut events = Vec::new();
567        let mut any = false;
568        let mut visit = |slot: &mut CoreWatchSlot| {
569            any = true;
570            f(slot, &mut events);
571            slot.target.send(&mut events);
572        };
573        let gone = {
574            let mut watch = crate::sync_util::lock_or_recover(&self.watch);
575            match watch.as_mut() {
576                Some(slot) if !slot.target.gone() => {
577                    visit(slot);
578                    None
579                }
580                _ => watch.take(),
581            }
582        };
583        // Unlocked: it drops the sink.
584        drop(gone);
585        let mut cores = crate::sync_util::lock_or_recover(&self.core_watches);
586        cores.retain(|c| !c.target.gone());
587        cores.iter_mut().for_each(visit);
588        any
589    }
590
591    /// End every watch: its tail, then `last`.
592    fn end_watches(&self, path: &str, last: Option<&SerialEvent>) {
593        let old = {
594            let mut watch = crate::sync_util::lock_or_recover(&self.watch);
595            let mut old = watch.take();
596            if let Some(slot) = old.as_mut() {
597                slot.end(path, last);
598            }
599            old
600        };
601        drop(old);
602        let mut cores = crate::sync_util::lock_or_recover(&self.core_watches);
603        for mut slot in cores.drain(..) {
604            slot.end(path, last);
605        }
606    }
607
608    /// Queue copies of `event` for the old watch and every `watch_core` stream (`urc_only`:
609    /// only those with `route_urc`).
610    fn fan_out(&self, event: &SerialEvent, urc_only: bool) {
611        self.each_watch(|c, out| {
612            // Id 0: the old watch gets URCs of exchanges and drains either way (4.x).
613            if c.id == 0 || !urc_only || c.route_urc {
614                out.push(event.clone());
615            }
616        });
617    }
618
619    /// Earliest parser timer of all watches (the hub wakes for it).
620    pub(crate) fn next_framer_deadline(&self) -> Option<Instant> {
621        let old = crate::sync_util::lock_or_recover(&self.watch)
622            .as_ref()
623            .and_then(|w| w.framer.as_ref()?.deadline());
624        let core = crate::sync_util::lock_or_recover(&self.core_watches)
625            .iter()
626            .filter_map(|c| c.framer.as_ref()?.deadline())
627            .min();
628        match (old, core) {
629            (Some(a), Some(b)) => Some(a.min(b)),
630            (a, b) => a.or(b),
631        }
632    }
633
634    /// Read chunk size: the old watch's, else the largest `watch_core` one.
635    pub(crate) fn read_size(&self) -> Option<usize> {
636        if let Some(w) = crate::sync_util::lock_or_recover(&self.watch).as_ref() {
637            return Some(w.read_size);
638        }
639        crate::sync_util::lock_or_recover(&self.core_watches)
640            .iter()
641            .map(|c| c.read_size)
642            .max()
643    }
644
645    /// Deliver events queued by `*_queued` calls. Call with no lock held.
646    pub fn deliver_queued(&self) {
647        self.outbox.deliver();
648    }
649
650    /// Queue `event` for the current watch (if any) and deliver.
651    pub fn emit(&self, event: SerialEvent) {
652        self.fan_out(&event, false);
653        self.outbox.deliver();
654    }
655
656    pub fn attach_cmux(&self, session: Arc<CmuxSession>) {
657        *crate::sync_util::lock_or_recover(&self.cmux) = Some(session);
658    }
659
660    pub fn detach_cmux(&self) {
661        *crate::sync_util::lock_or_recover(&self.cmux) = None;
662    }
663
664    /// Install the waiter. Bytes that arrived with no consumer (`idle`) are handed to it
665    /// first, under the idle lock, so they keep their order ahead of the reply.
666    pub fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
667        let mut idle = crate::sync_util::lock_or_recover(&self.idle);
668        if !idle.is_empty() {
669            waiter.push_bytes(&std::mem::take(&mut *idle));
670        }
671        *crate::sync_util::lock_or_recover(&self.exchange_waiter) = Some(waiter);
672        drop(idle);
673        self.fail_if_closing();
674    }
675
676    pub fn clear_exchange_waiter(&self) {
677        *crate::sync_util::lock_or_recover(&self.exchange_waiter) = None;
678    }
679
680    /// Wake an in-flight exchange waiter when [`SerialManager::cancel_exchange`](crate::SerialManager::cancel_exchange) is invoked.
681    pub fn cancel_active_exchange(&self) {
682        if let Some(waiter) = crate::sync_util::lock_or_recover(&self.exchange_waiter).as_ref() {
683            waiter.fail_with_reason("exchange cancelled".into());
684        }
685    }
686
687    /// Push-model entry: route incoming bytes (Android JNI / tests).
688    pub fn feed_bytes(&self, chunk: &[u8], state: &mut HubRoutingState) {
689        if chunk.is_empty() {
690            return;
691        }
692        // Bound first: the guard must not live through the session's sink calls.
693        let session = crate::sync_util::lock_or_recover(&self.cmux).clone();
694        if let Some(session) = session {
695            session.feed_physical_rx(chunk);
696            return;
697        }
698        if route_drain_chunk(self, chunk) {
699            return;
700        }
701        if let Some(waiter) = crate::sync_util::lock_or_recover(&self.exchange_waiter).clone() {
702            route_exchange_chunk(self, chunk, state, waiter);
703            return;
704        }
705        // A read takes what fits; the rest of the chunk goes on to the next consumer.
706        let chunk = match route_read_slot_chunk(self, chunk) {
707            Some(taken) if taken == chunk.len() => return,
708            Some(taken) => &chunk[taken..],
709            None => chunk,
710        };
711        state.exchange_demux = None;
712        if !self.each_watch(|c, out| c.feed(&state.path, chunk, out)) {
713            push_idle(self, chunk);
714        }
715    }
716
717    /// Idle timers for push model: drain completion + watch batch flush + read deadlines.
718    pub fn tick(&self, path: &str, _state: &mut HubRoutingState) {
719        tick_read_slot(self);
720        try_complete_drain(self);
721        let session = crate::sync_util::lock_or_recover(&self.cmux).clone();
722        if let Some(session) = session {
723            session.tick();
724        }
725        self.each_watch(|c, out| c.tick(path, out));
726    }
727
728    /// Immediately fail exchange waiters, active drain, and pending read (USB error teardown).
729    pub fn fail_all_waiters(&self, reason: &str) {
730        self.fail_waiters(reason);
731        self.outbox.deliver();
732    }
733
734    /// [`Self::fail_all_waiters`] without running a sink (the URCs of a drain are queued).
735    pub(crate) fn fail_waiters(&self, reason: &str) {
736        if let Some(waiter) = crate::sync_util::lock_or_recover(&self.exchange_waiter).take() {
737            waiter.fail_with_reason(reason.to_string());
738        }
739        finish_drain(self, Err(reason.to_string()));
740        finish_read_slot(self, Err(reason.to_string()));
741    }
742
743    pub fn buffered_len(&self) -> usize {
744        let idle_len = crate::sync_util::lock_or_recover(&self.idle).len();
745        let read_len = crate::sync_util::lock_or_recover(&self.read_slot)
746            .as_ref()
747            .map(|slot| slot.buffer.len())
748            .unwrap_or(0);
749        idle_len + read_len
750    }
751
752    /// Drop bytes the hub holds for no one yet (idle RX, a pending read's partial fill).
753    pub fn purge_buffers(&self) {
754        crate::sync_util::lock_or_recover(&self.idle).clear();
755        if let Some(slot) = crate::sync_util::lock_or_recover(&self.read_slot).as_mut() {
756            slot.buffer.clear();
757        }
758    }
759
760    /// Take any bytes buffered without an active consumer (e.g. early RX before exchange waiter).
761    pub fn take_idle_bytes(&self) -> Vec<u8> {
762        std::mem::take(&mut *crate::sync_util::lock_or_recover(&self.idle))
763    }
764
765    pub fn cancel_pending_read(&self) {
766        finish_read_slot(self, Err("read cancelled".into()));
767    }
768
769    /// Blocking poll-read via the hub (raw bytes, bypasses [`LineRouter`]).
770    pub fn read_request(
771        &self,
772        max_bytes: usize,
773        timeout_ms: u64,
774        fill: bool,
775    ) -> Result<Vec<u8>, String> {
776        if self.has_watch() || self.has_core_watches() {
777            return Err("Cannot read while watch is active; use watch or exchange".into());
778        }
779
780        let max_bytes = max_bytes.max(1);
781        let wait = Duration::from_millis(timeout_ms);
782        let deadline = Instant::now() + wait;
783
784        // Idle hand-off and slot install happen under one idle lock: a chunk routed in
785        // between would otherwise land in `idle` behind an installed slot (see `push_idle`).
786        let (tx, rx) = mpsc::sync_channel(1);
787        let id = self.next_slot.fetch_add(1, Ordering::Relaxed);
788        {
789            let mut idle = crate::sync_util::lock_or_recover(&self.idle);
790            let mut guard = crate::sync_util::lock_or_recover(&self.read_slot);
791            if guard.is_some() {
792                return Err("read already in progress".into());
793            }
794            let mut initial = Vec::new();
795            if !idle.is_empty() {
796                let n = max_bytes.min(idle.len());
797                if !fill {
798                    return Ok(idle.drain(..n).collect());
799                }
800                initial.extend(idle.drain(..n));
801                if initial.len() >= max_bytes {
802                    return Ok(initial);
803                }
804            }
805            *guard = Some(ReadSlot {
806                id,
807                max_bytes,
808                fill,
809                timeout_ms,
810                buffer: initial,
811                deadline,
812                tx,
813            });
814        }
815
816        self.fail_if_closing();
817
818        match rx.recv_timeout(wait) {
819            Ok(result) => result,
820            Err(RecvTimeoutError::Timeout) => {
821                let mine = crate::sync_util::lock_or_recover(&self.read_slot)
822                    .take_if(|slot| slot.id == id);
823                if let Some(slot) = mine {
824                    if slot.buffer.is_empty() {
825                        Err(format!("no data received within {} ms", timeout_ms))
826                    } else {
827                        Ok(slot.buffer)
828                    }
829                } else {
830                    // Completer took the slot then sends — brief wait covers that gap.
831                    rx.recv_timeout(Duration::from_millis(50))
832                        .unwrap_or_else(|_| {
833                            Err(format!("no data received within {} ms", timeout_ms))
834                        })
835                }
836            }
837            Err(RecvTimeoutError::Disconnected) => {
838                Err(format!("no data received within {} ms", timeout_ms))
839            }
840        }
841    }
842
843    /// Batched bytes of the old watch.
844    pub fn pending_watch_bytes(&self, _state: &HubRoutingState) -> usize {
845        crate::sync_util::lock_or_recover(&self.watch)
846            .as_ref()
847            .map_or(0, |w| w.buffer.len())
848    }
849
850    /// Batches and unfinished lines out now (parser state kept).
851    pub fn flush_watch_now(&self, state: &mut HubRoutingState) {
852        self.each_watch(|c, out| c.flush_buffers(&state.path, out));
853    }
854
855    /// Send `Disconnect` on the watches, after their batch and parser's remainder: their
856    /// last event. CMUX channel watches get the same on their path, and what waits on a
857    /// channel fails before any sink runs.
858    /// Once per hub: a second call (Android reports a USB failure from the hub loop
859    /// and from `fail_port`) does nothing.
860    pub fn emit_disconnect(&self, path: &str, reason: &str) {
861        if self.disconnected.swap(true, Ordering::SeqCst) {
862            return;
863        }
864        let session = crate::sync_util::lock_or_recover(&self.cmux).clone();
865        if let Some(session) = &session {
866            session.disconnect_queued(reason);
867        }
868        let event = SerialEvent::Disconnect {
869            path: path.to_string(),
870            reason: reason.to_string(),
871        };
872        self.end_watches(path, Some(&event));
873        self.outbox.deliver();
874        if let Some(session) = session {
875            session.deliver_queued();
876        }
877    }
878
879    /// Port going away: the watches end, what they still hold is queued.
880    pub fn finish_watch_stream(&self, state: &mut HubRoutingState) {
881        self.end_watches(&state.path, None);
882    }
883
884    pub fn has_watch(&self) -> bool {
885        crate::sync_util::lock_or_recover(&self.watch)
886            .as_ref()
887            .is_some_and(|w| !w.target.gone())
888    }
889
890    /// 4.0.0 API (feature `tauri`): deliver `events` to the current watch.
891    #[cfg(feature = "tauri")]
892    pub fn dispatch_pending_events(&self, events: Vec<SerialEvent>) {
893        self.each_watch(|c, out| {
894            if c.id == 0 {
895                out.extend(events.iter().cloned());
896            }
897        });
898        self.outbox.deliver();
899    }
900
901    /// Deliver the events the hub queued, then `events`. Each goes to the sink it was
902    /// produced for, even if the watch was detached since. Call with no lock held, after
903    /// every routing call.
904    pub fn dispatch_queued_events(&self, events: Vec<QueuedEvent>) {
905        self.outbox.deliver();
906        for (sink, event) in events {
907            let _ = call_sink(&sink, event);
908        }
909    }
910
911    /// Everything queued so far has been delivered when this returns (in a sink: unless
912    /// another thread is delivering it). Call with no lock held.
913    pub(crate) fn settle_events(&self) {
914        self.outbox.settle_all();
915    }
916
917    /// Soft-drain via the hub thread (single reader); URC lines are emitted on the watch channel.
918    /// Bytes already in the idle buffer are dropped with the drained ones (a late reply to
919    /// a timed-out exchange is exactly what a drain throws away).
920    pub fn drain(
921        &self,
922        idle_ms: u64,
923        max_ms: u64,
924        cancel: Arc<AtomicBool>,
925        solicited_prefixes: Vec<String>,
926    ) -> Result<Vec<u8>, String> {
927        let wait = Duration::from_millis(max_ms.saturating_add(500));
928        let (tx, rx) = mpsc::sync_channel(1);
929        let id = self.next_slot.fetch_add(1, Ordering::Relaxed);
930        {
931            // Under the idle lock (order: idle, then drain): a chunk `feed_bytes` routes
932            // to idle while the slot goes in lands either before (cleared here) or after
933            // (`push_idle` hands it to the slot), never in idle behind the drain.
934            let mut idle = crate::sync_util::lock_or_recover(&self.idle);
935            let mut guard = crate::sync_util::lock_or_recover(&self.drain);
936            if guard.is_some() {
937                return Err("drain already in progress".into());
938            }
939            idle.clear();
940            *guard = Some(DrainSlot {
941                id,
942                idle_ms,
943                cancel,
944                buffer: Vec::new(),
945                last_byte_at: None,
946                started_at: Instant::now(),
947                deadline: Instant::now() + Duration::from_millis(max_ms),
948                solicited_prefixes,
949                tx,
950            });
951        }
952
953        self.fail_if_closing();
954
955        match rx.recv_timeout(wait) {
956            Ok(result) => result,
957            Err(RecvTimeoutError::Timeout) => {
958                let mine =
959                    crate::sync_util::lock_or_recover(&self.drain).take_if(|slot| slot.id == id);
960                if let Some(slot) = mine {
961                    queue_drain_urcs(self, &slot);
962                    self.outbox.deliver();
963                    if slot.buffer.is_empty() {
964                        Err("drain timed out waiting for hub".into())
965                    } else {
966                        Ok(slot.buffer)
967                    }
968                } else {
969                    // Completer took the slot then sends — brief wait covers that gap.
970                    rx.recv_timeout(Duration::from_millis(50))
971                        .unwrap_or_else(|_| Err("drain timed out waiting for hub".into()))
972                }
973            }
974            Err(RecvTimeoutError::Disconnected) => Err("drain timed out waiting for hub".into()),
975        }
976    }
977}
978
979/// Append RX into the active drain slot. Returns `false` if there is no slot
980/// (caller must route elsewhere — never silently drop the chunk).
981/// URCs in the drained bytes go out when the drain completes, judged over the whole
982/// buffer: a two-line URC (`+CMT:` + PDU) or a multi-line `+CUSD` split across reads
983/// stays together. That delays them by at most the drain window (default 200 ms).
984pub(crate) fn route_drain_chunk(shared: &RxHubShared, chunk: &[u8]) -> bool {
985    let mut guard = crate::sync_util::lock_or_recover(&shared.drain);
986    let Some(drain) = guard.as_mut() else {
987        return false;
988    };
989    drain.buffer.extend_from_slice(chunk);
990    drain.last_byte_at = Some(Instant::now());
991    true
992}
993
994pub(crate) fn route_exchange_chunk(
995    shared: &RxHubShared,
996    chunk: &[u8],
997    state: &mut HubRoutingState,
998    waiter: Arc<ExchangeWaiter>,
999) {
1000    let stale = !matches!(&state.exchange_demux, Some((w, _)) if Arc::ptr_eq(w, &waiter));
1001    if stale {
1002        let cmd = waiter.options.command.clone().unwrap_or_default();
1003        let demux = ExchangeDemux::with_format(
1004            &cmd,
1005            &waiter.options.solicited_prefixes,
1006            waiter.options.result_format,
1007        );
1008        state.exchange_demux = Some((waiter.clone(), demux));
1009    }
1010    if let Some((_, demux)) = state.exchange_demux.as_mut() {
1011        for line in demux.process_chunk(chunk) {
1012            let event = SerialEvent::Urc {
1013                path: state.path.clone(),
1014                line,
1015            };
1016            shared.fan_out(&event, true);
1017        }
1018    }
1019    waiter.push_bytes(chunk);
1020}
1021
1022/// Feed a read slot: the bytes it took, or `None` if there is no slot (fall through).
1023/// A read takes at most its size; the caller routes the rest of the chunk on (they
1024/// were once dropped).
1025pub(crate) fn route_read_slot_chunk(shared: &RxHubShared, chunk: &[u8]) -> Option<usize> {
1026    let taken;
1027    let completed = {
1028        let mut guard = crate::sync_util::lock_or_recover(&shared.read_slot);
1029        let ready = {
1030            let slot = guard.as_mut()?;
1031            let remaining = slot.max_bytes.saturating_sub(slot.buffer.len());
1032            taken = chunk.len().min(remaining);
1033            slot.buffer.extend_from_slice(&chunk[..taken]);
1034            !slot.fill || slot.buffer.len() >= slot.max_bytes
1035        };
1036        if !ready {
1037            None
1038        } else {
1039            let slot = guard.take().unwrap();
1040            Some((slot.tx, Ok(slot.buffer)))
1041        }
1042    };
1043    if let Some((tx, result)) = completed {
1044        let _ = tx.send(result);
1045    }
1046    Some(taken)
1047}
1048
1049pub(crate) fn tick_read_slot(shared: &RxHubShared) {
1050    let completed = {
1051        let mut guard = crate::sync_util::lock_or_recover(&shared.read_slot);
1052        let expired = match guard.as_ref() {
1053            Some(slot) => Instant::now() >= slot.deadline,
1054            None => return,
1055        };
1056        if !expired {
1057            return;
1058        }
1059        let slot = guard.take().unwrap();
1060        let result = if slot.buffer.is_empty() {
1061            Err(format!("no data received within {} ms", slot.timeout_ms))
1062        } else {
1063            Ok(slot.buffer)
1064        };
1065        Some((slot.tx, result))
1066    };
1067    if let Some((tx, result)) = completed {
1068        let _ = tx.send(result);
1069    }
1070}
1071
1072/// Shared idle/deadline/cancel completion for drain (desktop poll + Android tick).
1073pub(crate) fn try_complete_drain(shared: &RxHubShared) {
1074    let completed = {
1075        let mut guard = crate::sync_util::lock_or_recover(&shared.drain);
1076        let kind = match guard.as_ref() {
1077            Some(d) if d.cancel.load(Ordering::SeqCst) => Some(DrainCompleteKind::Cancel),
1078            Some(d) if Instant::now() >= d.deadline => Some(DrainCompleteKind::Buffer),
1079            Some(d)
1080                if d.last_byte_at
1081                    .is_some_and(|t| t.elapsed() >= Duration::from_millis(d.idle_ms)) =>
1082            {
1083                Some(DrainCompleteKind::Buffer)
1084            }
1085            Some(d)
1086                if d.last_byte_at.is_none()
1087                    && d.started_at.elapsed() >= Duration::from_millis(d.idle_ms) =>
1088            {
1089                Some(DrainCompleteKind::Empty)
1090            }
1091            _ => None,
1092        };
1093        kind.map(|k| (k, guard.take().unwrap()))
1094    };
1095    // The drain lock is released: the URC sink may touch the drain slot.
1096    if let Some((k, d)) = completed {
1097        queue_drain_urcs(shared, &d);
1098        shared.outbox.deliver();
1099        let result = match k {
1100            DrainCompleteKind::Cancel => Err("exchange cancelled".into()),
1101            DrainCompleteKind::Buffer => Ok(d.buffer),
1102            DrainCompleteKind::Empty => Ok(Vec::new()),
1103        };
1104        let _ = d.tx.send(result);
1105    }
1106}
1107
1108#[derive(Clone, Copy)]
1109enum DrainCompleteKind {
1110    Cancel,
1111    Buffer,
1112    Empty,
1113}
1114
1115pub(crate) fn finish_read_slot(shared: &RxHubShared, result: Result<Vec<u8>, String>) {
1116    if let Some(slot) = crate::sync_util::lock_or_recover(&shared.read_slot).take() {
1117        let _ = slot.tx.send(result);
1118    }
1119}
1120
1121pub(crate) fn push_idle(shared: &RxHubShared, chunk: &[u8]) {
1122    let mut idle = crate::sync_util::lock_or_recover(&shared.idle);
1123    // A drain, waiter or read slot may have been installed after `feed_bytes` checked
1124    // for one (lock order: idle, then drain / exchange_waiter / read_slot). A drain
1125    // first, as in `feed_bytes`: idle bytes left behind it would reach the next exchange.
1126    if route_drain_chunk(shared, chunk) {
1127        return;
1128    }
1129    if let Some(waiter) = crate::sync_util::lock_or_recover(&shared.exchange_waiter).as_ref() {
1130        waiter.push_bytes(chunk);
1131        return;
1132    }
1133    // Same for a read slot installed after `feed_bytes` checked for one.
1134    let chunk = match route_read_slot_chunk(shared, chunk) {
1135        Some(taken) => &chunk[taken..],
1136        None => chunk,
1137    };
1138    idle.extend_from_slice(chunk);
1139    let excess = idle.len().saturating_sub(IDLE_BUFFER_CAP);
1140    idle.drain(..excess);
1141}
1142
1143/// End the drain with `result`; URCs it collected are queued for the watch.
1144pub(crate) fn finish_drain(shared: &RxHubShared, result: Result<Vec<u8>, String>) {
1145    let drain = crate::sync_util::lock_or_recover(&shared.drain).take();
1146    if let Some(drain) = drain {
1147        queue_drain_urcs(shared, &drain);
1148        let _ = drain.tx.send(result);
1149    }
1150}
1151
1152/// Queue the URC lines of a finished drain for the watch channel (if any).
1153fn queue_drain_urcs(shared: &RxHubShared, drain: &DrainSlot) {
1154    if drain.buffer.is_empty() {
1155        return;
1156    }
1157    if !shared.has_watch() && !shared.has_core_watches() {
1158        return;
1159    }
1160    let lines = crate::at::parse::urc_lines_from_drain(&drain.buffer, &drain.solicited_prefixes);
1161    for line in lines {
1162        let event = SerialEvent::Urc {
1163            path: shared.path.clone(),
1164            line,
1165        };
1166        shared.fan_out(&event, true);
1167    }
1168}
1169
1170impl WatchOwner for RxHubShared {
1171    fn stop(&self, stream: &Arc<EventStream>) {
1172        // The slot (and with it the sink) is dropped with no lock held.
1173        drop(self.take_watch(|slot| slot.target.is(stream)));
1174        self.outbox.settle(stream);
1175    }
1176}
1177
1178#[cfg(test)]
1179mod model;