serialplugin-core 0.2.5

Serial port core of tauri-plugin-serialplugin without Tauri: RX hub, watch streams with native parsers, AT exchange, CMUX, TCP and BLE transports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! In `src/`: it forces interleavings no public call can (a chunk that reaches `push_idle`
//! after a consumer was installed, reads and drains that end while the hub ticks) and sees
//! who holds each byte.
//!
//! Model test of the hub's RX routing: random sequences of chunks and consumer changes,
//! checked after every step against a reference model of who gets each byte (drain >
//! exchange waiter > read slot > watches > idle buffer). `tests/it/model_exchange.rs` and
//! `model_manager.rs` cover the same routing end to end.

use super::*;
use crate::error::ErrorKind;
use crate::events::{ExchangeCompletionMode, ExchangeOptions};
use proptest::collection::vec;
use proptest::prelude::*;
use proptest::test_runner::{Config, TestRunner};
use std::collections::BTreeMap;
use std::sync::mpsc::Receiver;
use std::thread::JoinHandle;

/// Read timeout of a started read: never reached, reads end by bytes, `ExpireRead`,
/// cancel or failure.
const READ_MS: u64 = 30_000;
const PATH: &str = "model";

#[derive(Clone, Debug)]
pub(super) enum Step {
    /// A chunk the hub read off the port.
    Feed(Vec<u8>),
    /// A chunk that reaches `push_idle` after `feed_bytes` saw no consumer: the race in
    /// which a drain, waiter or read slot is installed between the two.
    RaceFeed(Vec<u8>),
    SetWaiter,
    ClearWaiter,
    /// `cancel_exchange`: the waiter fails but stays installed until cleared.
    CancelExchange,
    /// `take_idle_bytes` (the drain prepare throws them away).
    TakeIdle,
    StartRead {
        max: usize,
        fill: bool,
    },
    /// The read's deadline passes and the hub ticks.
    ExpireRead,
    CancelRead,
    StartDrain,
    /// The drain's deadline passes, or its line falls idle, and the hub ticks.
    EndDrain {
        idle: bool,
    },
    /// The drain's cancel flag is set and the hub ticks.
    CancelDrain,
    AttachWatch,
    DetachWatch,
    AttachCore,
    DetachCore(usize),
    Purge,
    FailAll,
}

#[derive(Clone, Debug)]
pub(super) struct PendingRead {
    max: usize,
    fill: bool,
    buf: Vec<u8>,
}

#[derive(Clone, Debug, Default)]
pub(super) struct Model {
    idle: Vec<u8>,
    drain: Option<Vec<u8>>,
    /// Bytes of the installed waiter and the failure it got, if any.
    waiter: Option<(Vec<u8>, Option<String>)>,
    read: Option<PendingRead>,
    /// Index of the current old watch in `watch_got`.
    watch: Option<usize>,
    cores: Vec<u64>,
    next_core: u64,
    watch_got: Vec<Vec<u8>>,
    core_got: BTreeMap<u64, Vec<u8>>,
    /// Bytes of each cleared waiter and its `wait` error.
    waiters_done: Vec<(Vec<u8>, String)>,
    taken: Vec<Vec<u8>>,
    reads_done: Vec<Result<Vec<u8>, String>>,
    drains_done: Vec<Result<Vec<u8>, String>>,
}

impl Model {
    fn has_watches(&self) -> bool {
        self.watch.is_some() || !self.cores.is_empty()
    }

    fn give_watches(&mut self, chunk: &[u8]) {
        if let Some(w) = self.watch {
            self.watch_got[w].extend_from_slice(chunk);
        }
        for id in &self.cores {
            self.core_got.get_mut(id).unwrap().extend_from_slice(chunk);
        }
    }

    /// The read slot takes what fits; a completed slot leaves the rest of the chunk.
    fn give_read<'a>(&mut self, chunk: &'a [u8]) -> &'a [u8] {
        let Some(r) = self.read.as_mut() else {
            return chunk;
        };
        let take = chunk.len().min(r.max - r.buf.len());
        r.buf.extend_from_slice(&chunk[..take]);
        if !r.fill || r.buf.len() >= r.max {
            let r = self.read.take().unwrap();
            self.reads_done.push(Ok(r.buf));
        }
        &chunk[take..]
    }

    fn give_idle(&mut self, chunk: &[u8]) {
        self.idle.extend_from_slice(chunk);
        let excess = self.idle.len().saturating_sub(IDLE_BUFFER_CAP);
        self.idle.drain(..excess);
    }

    fn feed(&mut self, chunk: &[u8]) {
        if chunk.is_empty() {
            return;
        }
        if let Some(d) = self.drain.as_mut() {
            d.extend_from_slice(chunk);
            return;
        }
        if let Some((w, _)) = self.waiter.as_mut() {
            w.extend_from_slice(chunk);
            return;
        }
        let had_read = self.read.is_some();
        let rest = self.give_read(chunk);
        if had_read && rest.is_empty() {
            return;
        }
        if self.has_watches() {
            self.give_watches(rest);
        } else {
            self.give_idle(rest);
        }
    }

    fn race_feed(&mut self, chunk: &[u8]) {
        // A drain installed in the gap takes the chunk: left in idle it would reach the
        // next exchange as a stale reply.
        if let Some(d) = self.drain.as_mut() {
            d.extend_from_slice(chunk);
            return;
        }
        if let Some((w, _)) = self.waiter.as_mut() {
            w.extend_from_slice(chunk);
            return;
        }
        let rest = self.give_read(chunk);
        self.give_idle(rest);
    }

    fn start_read(&mut self, max: usize, fill: bool) {
        if self.has_watches() {
            self.reads_done.push(Err(
                "Cannot read while watch is active; use watch or exchange".into(),
            ));
            return;
        }
        if self.read.is_some() {
            self.reads_done.push(Err("read already in progress".into()));
            return;
        }
        let n = max.min(self.idle.len());
        let buf: Vec<u8> = self.idle.drain(..n).collect();
        if (!fill && !buf.is_empty()) || buf.len() >= max {
            self.reads_done.push(Ok(buf));
        } else {
            self.read = Some(PendingRead { max, fill, buf });
        }
    }

    fn fail_all(&mut self, reason: &str) {
        if let Some((w, failed)) = self.waiter.take() {
            self.waiters_done
                .push((w, failed.unwrap_or_else(|| reason.into())));
        }
        if self.drain.take().is_some() {
            self.drains_done.push(Err(reason.into()));
        }
        if self.read.take().is_some() {
            self.reads_done.push(Err(reason.into()));
        }
    }
}

fn chunk(len: std::ops::Range<usize>) -> impl Strategy<Value = Vec<u8>> {
    // No newline, CR or '+': no line ever completes, so no URC is split off and the
    // test waiter (completes on "\n") never finishes on its own.
    proptest::collection::vec(b'a'..=b'h', len)
}

fn step_strategy() -> impl Strategy<Value = Step> {
    prop_oneof![
            6 => chunk(0..9).prop_map(Step::Feed),
            2 => chunk(1..9).prop_map(Step::RaceFeed),
            1 => Just(Step::SetWaiter),
            1 => Just(Step::ClearWaiter),
            1 => Just(Step::CancelExchange),
            1 => Just(Step::TakeIdle),
            2 => (1usize..8, any::<bool>()).prop_map(|(max, fill)| Step::StartRead { max, fill }),
            1 => Just(Step::ExpireRead),
            1 => Just(Step::CancelRead),
            1 => Just(Step::StartDrain),
            1 => any::<bool>().prop_map(|idle| Step::EndDrain { idle }),
            1 => Just(Step::CancelDrain),
            1 => Just(Step::AttachWatch),
            1 => Just(Step::DetachWatch),
            1 => Just(Step::AttachCore),
            1 => (0usize..4).prop_map(Step::DetachCore),
            1 => Just(Step::Purge),
            1 => Just(Step::FailAll),
    ]
}

impl Model {
    /// Whether `step` can happen in this state (else the runner skips it).
    fn observable(&self, step: &Step) -> bool {
        let m = self;
        match step {
            Step::RaceFeed(_) => !m.has_watches(),
            Step::SetWaiter => m.waiter.is_none(),
            Step::ClearWaiter => m.waiter.is_some(),
            Step::ExpireRead => m.read.is_some(),
            Step::EndDrain { .. } | Step::CancelDrain => m.drain.is_some(),
            Step::AttachWatch => m.watch.is_none(),
            Step::DetachWatch => m.watch.is_some(),
            Step::DetachCore(_) => !m.cores.is_empty(),
            _ => true,
        }
    }

    fn apply(&mut self, step: &Step) {
        let m = self;
        match step {
            Step::Feed(c) => m.feed(c),
            Step::RaceFeed(c) => m.race_feed(c),
            Step::SetWaiter => m.waiter = Some((std::mem::take(&mut m.idle), None)),
            Step::ClearWaiter => {
                let (w, failed) = m.waiter.take().unwrap();
                let error = failed.unwrap_or_else(|| "exchange timed out after 0 ms".into());
                m.waiters_done.push((w, error));
            }
            Step::CancelExchange => {
                if let Some((_, failed)) = m.waiter.as_mut() {
                    failed.get_or_insert_with(|| "exchange cancelled".into());
                }
            }
            Step::TakeIdle => {
                let idle = std::mem::take(&mut m.idle);
                m.taken.push(idle);
            }
            Step::StartRead { max, fill } => m.start_read(*max, *fill),
            Step::ExpireRead => {
                let r = m.read.take().unwrap();
                m.reads_done.push(if r.buf.is_empty() {
                    Err(format!("no data received within {READ_MS} ms"))
                } else {
                    Ok(r.buf)
                });
            }
            Step::CancelRead => {
                if m.read.take().is_some() {
                    m.reads_done.push(Err("read cancelled".into()));
                }
            }
            Step::StartDrain if m.drain.is_some() => {
                m.drains_done.push(Err("drain already in progress".into()))
            }
            Step::StartDrain => {
                // Idle bytes are stale to a drain: dropped as its slot goes in.
                m.idle.clear();
                m.drain = Some(Vec::new());
            }
            Step::EndDrain { .. } => {
                let d = m.drain.take().unwrap();
                m.drains_done.push(Ok(d));
            }
            Step::CancelDrain => {
                m.drain = None;
                m.drains_done.push(Err("exchange cancelled".into()));
            }
            Step::AttachWatch => {
                m.idle.clear();
                m.watch = Some(m.watch_got.len());
                m.watch_got.push(Vec::new());
            }
            Step::DetachWatch => m.watch = None,
            Step::AttachCore => {
                m.idle.clear();
                m.next_core += 1;
                m.cores.push(m.next_core);
                m.core_got.insert(m.next_core, Vec::new());
            }
            Step::DetachCore(i) => {
                let i = i % m.cores.len();
                m.cores.remove(i);
            }
            Step::Purge => {
                m.idle.clear();
                if let Some(r) = m.read.as_mut() {
                    r.buf.clear();
                }
            }
            Step::FailAll => m.fail_all("gone"),
        }
    }
}

type Bytes = Arc<Mutex<Vec<u8>>>;
type Results = Receiver<Result<Vec<u8>, String>>;

pub(super) struct Sut {
    shared: Arc<RxHubShared>,
    routing: HubRoutingState,
    watches: Vec<Bytes>,
    cores: BTreeMap<u64, Bytes>,
    /// Attached core watch ids, in the model's order.
    attached: Vec<u64>,
    waiter: Option<Arc<ExchangeWaiter>>,
    waiters_done: Vec<(Vec<u8>, String)>,
    taken: Vec<Vec<u8>>,
    reads: (SyncSender<Result<Vec<u8>, String>>, Results),
    reads_done: Vec<Result<Vec<u8>, String>>,
    drains: (SyncSender<Result<Vec<u8>, String>>, Results),
    drains_done: Vec<Result<Vec<u8>, String>>,
    threads: Vec<JoinHandle<()>>,
}

/// A sink that records `Data` bytes; any other event fails the test.
fn recorder() -> (EventSink, Bytes) {
    let got: Bytes = Arc::default();
    let sink_got = got.clone();
    let sink: EventSink = Arc::new(move |ev| {
        match ev {
            SerialEvent::Data { data, .. } => sink_got.lock().unwrap().extend(data),
            other => panic!("unexpected event {other:?}"),
        }
        true
    });
    (sink, got)
}

fn wait_for(what: &str, f: impl Fn() -> bool) {
    let deadline = Instant::now() + Duration::from_secs(10);
    while !f() {
        assert!(Instant::now() < deadline, "timed out waiting for {what}");
        std::thread::park_timeout(Duration::from_millis(1));
    }
}

/// Results with errors as their kind (the hub's errors are text).
fn kinds(r: &[Result<Vec<u8>, String>]) -> Vec<Result<Vec<u8>, ErrorKind>> {
    r.iter()
        .map(|r| r.clone().map_err(|e| ErrorKind::from_message(&e)))
        .collect()
}

fn kinds_w(w: &[(Vec<u8>, String)]) -> Vec<(Vec<u8>, ErrorKind)> {
    w.iter()
        .map(|(b, e)| (b.clone(), ErrorKind::from_message(e)))
        .collect()
}

/// A cleared waiter's bytes and its `wait` error (it never completes: no "\n").
fn finished(w: &Arc<ExchangeWaiter>) -> (Vec<u8>, String) {
    let bytes = w.buffer.lock().unwrap().0.clone();
    (bytes, w.wait(0).expect_err("waiter completed"))
}

fn past() -> Instant {
    Instant::now()
        .checked_sub(Duration::from_millis(1))
        .unwrap_or_else(Instant::now)
}

impl Sut {
    /// Route the hub's queued events and run its timers (batch 0: every tick flushes).
    fn settle(&mut self) {
        self.shared
            .dispatch_queued_events(std::mem::take(&mut self.routing.pending_events));
        self.shared.tick(PATH, &mut self.routing);
        self.shared
            .dispatch_queued_events(std::mem::take(&mut self.routing.pending_events));
    }

    fn collect(rx: &Results, done: &mut Vec<Result<Vec<u8>, String>>, want: usize) {
        while done.len() < want {
            done.push(
                rx.recv_timeout(Duration::from_secs(10))
                    .expect("a result the model expects"),
            );
        }
        if let Ok(extra) = rx.try_recv() {
            panic!("unexpected result {extra:?}");
        }
    }
}

impl Sut {
    fn new() -> Sut {
        Sut {
            shared: Arc::new(RxHubShared::for_path(PATH.into())),
            routing: HubRoutingState::new(PATH.into()),
            watches: Vec::new(),
            cores: BTreeMap::new(),
            attached: Vec::new(),
            waiter: None,
            waiters_done: Vec::new(),
            taken: Vec::new(),
            reads: mpsc::sync_channel(64),
            reads_done: Vec::new(),
            drains: mpsc::sync_channel(64),
            drains_done: Vec::new(),
            threads: Vec::new(),
        }
    }

    fn apply(&mut self, m: &Model, step: Step) {
        let sut = self;
        let shared = sut.shared.clone();
        match step {
            Step::Feed(c) => shared.feed_bytes(&c, &mut sut.routing),
            Step::RaceFeed(c) => push_idle(&shared, &c),
            Step::SetWaiter => {
                let options = ExchangeOptions {
                    completion_mode: Some(ExchangeCompletionMode::Substring),
                    terminators: Some(vec!["\n".into()]),
                    ..Default::default()
                }
                .resolve();
                let w = ExchangeWaiter::new(options, Arc::new(AtomicBool::new(false)));
                shared.set_exchange_waiter(w.clone());
                sut.waiter = Some(w);
            }
            Step::ClearWaiter => {
                shared.clear_exchange_waiter();
                let w = sut.waiter.take().unwrap();
                sut.waiters_done.push(finished(&w));
            }
            Step::CancelExchange => shared.cancel_active_exchange(),
            Step::TakeIdle => sut.taken.push(shared.take_idle_bytes()),
            Step::StartRead { max, fill } => {
                let tx = sut.reads.0.clone();
                sut.threads.push(std::thread::spawn(move || {
                    let _ = tx.send(shared.read_request(max, READ_MS, fill));
                }));
                if m.read.is_some() {
                    // The model installed a slot (a busy read leaves the old one).
                    let s = sut.shared.clone();
                    wait_for("read slot", || s.read_slot.lock().unwrap().is_some());
                }
            }
            Step::ExpireRead => {
                if let Some(slot) = shared.read_slot.lock().unwrap().as_mut() {
                    slot.deadline = past();
                }
            }
            Step::CancelRead => shared.cancel_pending_read(),
            Step::StartDrain => {
                let tx = sut.drains.0.clone();
                let s = shared.clone();
                sut.threads.push(std::thread::spawn(move || {
                    let cancel = Arc::new(AtomicBool::new(false));
                    let _ = tx.send(s.drain(60_000, 60_000, cancel, Vec::new()));
                }));
                wait_for("drain slot", || shared.drain.lock().unwrap().is_some());
            }
            Step::EndDrain { idle } => {
                if let Some(d) = shared.drain.lock().unwrap().as_mut() {
                    if idle {
                        // Since the last byte, or since the start when there was none.
                        d.idle_ms = 0;
                        d.last_byte_at = d.last_byte_at.map(|_| past());
                        d.started_at = past();
                    } else {
                        d.deadline = past();
                    }
                }
            }
            Step::CancelDrain => {
                if let Some(d) = shared.drain.lock().unwrap().as_ref() {
                    d.cancel.store(true, Ordering::SeqCst);
                }
            }
            Step::AttachWatch => {
                let (sink, got) = recorder();
                shared.attach_watch_with(sink, 0, 1024, false, None);
                sut.watches.push(got);
            }
            Step::DetachWatch => shared.detach_watch(),
            Step::AttachCore => {
                let (sink, got) = recorder();
                let id = m.next_core;
                let target = Target::Core {
                    sink,
                    alive: Arc::new(AtomicBool::new(true)),
                };
                shared.attach_core_watch(CoreWatchSlot::new(id, target, 0, 1024, false, None));
                sut.cores.insert(id, got);
                sut.attached.push(id);
            }
            Step::DetachCore(i) => {
                let i = i % sut.attached.len();
                assert!(shared.detach_core_watch(sut.attached.remove(i)));
            }
            Step::Purge => shared.purge_buffers(),
            Step::FailAll => {
                shared.fail_all_waiters("gone");
                if let Some(w) = sut.waiter.take() {
                    sut.waiters_done.push(finished(&w));
                }
            }
        }
        sut.settle();
        Sut::collect(&sut.reads.1, &mut sut.reads_done, m.reads_done.len());
        Sut::collect(&sut.drains.1, &mut sut.drains_done, m.drains_done.len());
    }

    fn check(&self, m: &Model) {
        let sut = self;
        let shared = &sut.shared;
        for (i, got) in sut.watches.iter().enumerate() {
            assert_eq!(*got.lock().unwrap(), m.watch_got[i], "old watch #{i}");
        }
        for (id, got) in &sut.cores {
            assert_eq!(*got.lock().unwrap(), m.core_got[id], "core watch {id}");
        }
        assert_eq!(
            kinds_w(&sut.waiters_done),
            kinds_w(&m.waiters_done),
            "finished waiters"
        );
        let waiter = sut
            .waiter
            .as_ref()
            .map(|w| w.buffer.lock().unwrap().0.clone());
        let want = m.waiter.as_ref().map(|(w, _)| w.clone());
        assert_eq!(waiter, want, "current waiter");
        assert_eq!(sut.taken, m.taken, "taken idle bytes");
        assert_eq!(kinds(&sut.reads_done), kinds(&m.reads_done), "read results");
        assert_eq!(
            kinds(&sut.drains_done),
            kinds(&m.drains_done),
            "drain results"
        );
        assert_eq!(*shared.idle.lock().unwrap(), m.idle, "idle buffer");
        let slot = shared
            .read_slot
            .lock()
            .unwrap()
            .as_ref()
            .map(|s| s.buffer.clone());
        assert_eq!(slot, m.read.as_ref().map(|r| r.buf.clone()), "read slot");
        assert_eq!(
            shared.buffered_len(),
            m.idle.len() + m.read.as_ref().map_or(0, |r| r.buf.len())
        );
        assert_eq!(shared.drain.lock().unwrap().is_some(), m.drain.is_some());
        let drained = shared
            .drain
            .lock()
            .unwrap()
            .as_ref()
            .map(|d| d.buffer.clone());
        assert_eq!(drained, m.drain, "drain buffer");
    }

    fn teardown(mut self) {
        let sut = &mut self;
        sut.shared.fail_all_waiters("teardown");
        for t in sut.threads.drain(..) {
            t.join().unwrap();
        }
    }
}

/// Random routing steps against the model.
#[test]
fn hub_routing_matches_the_model() {
    let mut runner = TestRunner::new(Config {
        cases: 64,
        failure_persistence: None,
        ..Config::default()
    });
    let result = runner.run(&vec(step_strategy(), 1..40), |steps| {
        let mut model = Model::default();
        let mut sut = Sut::new();
        for step in steps {
            if !model.observable(&step) {
                continue;
            }
            model.apply(&step);
            sut.apply(&model, step);
            sut.check(&model);
        }
        sut.teardown();
        Ok(())
    });
    if let Err(e) = result {
        panic!("{e}");
    }
}

/// Given a read (or a drain) whose slot the hub has taken while its caller gives up,
/// when another caller's slot is in by then,
/// then the caller that gave up leaves it alone.
#[test]
fn a_caller_that_gives_up_takes_only_its_own_slot() {
    /// Run `call`, and once it has its slot in `place`, put `theirs` there instead.
    fn swap<S: 'static>(
        call: impl FnOnce() -> Result<Vec<u8>, String> + Send + 'static,
        place: impl Fn() -> std::sync::MutexGuard<'static, Option<S>>,
        theirs: S,
    ) -> Result<Vec<u8>, String> {
        let caller = std::thread::spawn(call);
        let mut theirs = Some(theirs);
        let mut own = None;
        let deadline = Instant::now() + Duration::from_secs(10);
        while own.is_none() {
            assert!(Instant::now() < deadline, "no slot");
            std::thread::park_timeout(Duration::from_millis(1));
            let mut slot = place();
            if slot.is_some() {
                own = slot.take();
                *slot = theirs.take();
            }
        }
        // The hub has its slot (and answers it late).
        let result = caller.join().unwrap();
        drop(own);
        result
    }
    let shared: &'static RxHubShared = Box::leak(Box::new(RxHubShared::new()));
    let (tx, rx) = mpsc::sync_channel(1);
    let read = swap(
        || shared.read_request(4, 100, false),
        || shared.read_slot.lock().unwrap(),
        ReadSlot {
            id: u64::MAX,
            max_bytes: 4,
            fill: false,
            timeout_ms: READ_MS,
            buffer: Vec::new(),
            deadline: Instant::now() + Duration::from_secs(60),
            tx,
        },
    );
    assert_eq!(read.unwrap_err(), "no data received within 100 ms");
    shared.feed_bytes(b"mine", &mut HubRoutingState::new(PATH.into()));
    assert_eq!(rx.try_recv().unwrap(), Ok(b"mine".to_vec()));

    let (tx, rx) = mpsc::sync_channel(1);
    let drain = swap(
        || shared.drain(60_000, 0, Arc::default(), Vec::new()),
        || shared.drain.lock().unwrap(),
        DrainSlot {
            id: u64::MAX,
            idle_ms: 60_000,
            cancel: Arc::default(),
            buffer: b"mine".to_vec(),
            last_byte_at: None,
            started_at: Instant::now(),
            deadline: Instant::now() + Duration::from_secs(60),
            solicited_prefixes: Vec::new(),
            tx,
        },
    );
    assert_eq!(drain.unwrap_err(), "drain timed out waiting for hub");
    shared.fail_all_waiters("ended");
    assert_eq!(rx.try_recv().unwrap(), Err("ended".into()));
}

/// Given a hub whose port is being closed,
/// when a caller that had the hub in hand starts a read, a drain or an exchange,
/// then it fails at once: no hub thread will.
#[test]
fn nothing_waits_on_a_port_that_is_being_closed() {
    let shared = RxHubShared::new();
    shared.begin_close();
    let read = shared.read_request(4, READ_MS, true);
    assert_eq!(read.unwrap_err(), PORT_CLOSED);
    let drain = shared.drain(READ_MS, READ_MS, Arc::default(), Vec::new());
    assert_eq!(drain.unwrap_err(), PORT_CLOSED);
    let waiter = ExchangeWaiter::new(ExchangeOptions::default().resolve(), Arc::default());
    shared.set_exchange_waiter(waiter.clone());
    assert_eq!(waiter.wait(READ_MS).unwrap_err(), PORT_CLOSED);
}