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