Skip to main content

satx_core/
machine.rs

1//! The sans-I/O face of satx-core: a [`Machine`] is fed bytes, time and
2//! link errors, and hands out bytes to write, progress events and the
3//! result of each operation. It never reads a clock, sleeps, blocks or
4//! touches a port, so it runs where the bytes arrive by callback: a browser
5//! with Web Serial (WebAssembly), an event loop, a GUI thread.
6//!
7//! The calling convention is the one of [`kermit_proto::Client`], one level
8//! up: a whole calculator operation ([`Op`]) instead of one Kermit
9//! transaction. The operations are the ones of
10//! [`Calculator`](crate::Calculator) and
11//! [`XmodemSession`](crate::XmodemSession), which run the same code over a
12//! blocking [`Transport`](crate::transport::Transport).
13//!
14//! # The seam
15//!
16//! - [`Machine::new`] takes the caller's clock, the [`Options`] and a seed
17//!   for the sync markers (from a random source such as
18//!   `crypto.getRandomValues`).
19//! - [`Machine::start`] begins an operation; its first bytes are queued at
20//!   once. One operation runs at a time.
21//! - [`Machine::handle_input`] feeds bytes read from the link, in any
22//!   chunking, with the time they arrived.
23//! - [`Machine::handle_timeout`] tells the machine the time; call it when
24//!   [`Machine::next_timeout`] is reached (early calls do nothing).
25//! - [`Machine::handle_link_error`] reports a failed or closed link.
26//! - [`Machine::poll_transmit`] hands out the next chunk to write. Write
27//!   each one as one unit, without inter-byte gaps: the HP's receiver
28//!   overruns on gaps.
29//! - [`Machine::poll_event`] yields [`Progress`] events (Kermit or XModem):
30//!   take them, or turn them off with [`Machine::set_events`], since data
31//!   events carry the file contents.
32//! - [`Machine::poll_result`] yields the [`Reply`] once the operation is
33//!   over.
34//!
35//! After every `start` and `handle_*` call, write everything
36//! `poll_transmit` hands out, then arm a timer for `next_timeout`.
37//!
38//! # Time
39//!
40//! Every call that can make progress takes `now`, a
41//! [`time::Instant`](crate::time::Instant) of the caller's monotonic clock:
42//! `std::time::Instant` on native targets, `web_time::Instant` on wasm32
43//! (`Instant::now()` is `performance.now()` there). The machine keeps the
44//! latest `now` it was given and never lets it run backwards.
45//!
46//! # A host loop
47//!
48//! ```
49//! use satx_core::machine::{Machine, Op, Reply};
50//! use satx_core::time::{Duration, Instant};
51//! use satx_core::Options;
52//!
53//! // Stand-ins for the host's serial port and clock.
54//! fn write_to_port(_bytes: &[u8]) {}
55//! fn wait_for_bytes_until(_deadline: Option<Instant>) -> Option<Vec<u8>> { None }
56//!
57//! let mut options = Options::default();
58//! options.kermit.timeout = Duration::from_millis(50);
59//! options.drain = Duration::ZERO;
60//! let mut m = Machine::new(Instant::now(), options, 0x5eed);
61//! m.start(Instant::now(), Op::List).unwrap();
62//! let result = loop {
63//!     while let Some(bytes) = m.poll_transmit() {
64//!         write_to_port(&bytes);
65//!     }
66//!     while let Some(_event) = m.poll_event() {}
67//!     if let Some(result) = m.poll_result() {
68//!         break result;
69//!     }
70//!     match wait_for_bytes_until(m.next_timeout()) {
71//!         Some(bytes) => m.handle_input(Instant::now(), &bytes),
72//!         None => m.handle_timeout(Instant::now()),
73//!     }
74//! };
75//! // Nobody answered.
76//! assert!(result.is_err());
77//! ```
78//!
79//! In a browser the loop is inverted: the Web Serial reader's callback calls
80//! `handle_input`, a `setTimeout` for `next_timeout` calls
81//! `handle_timeout`, and each of them is followed by the drain of
82//! `poll_transmit`, `poll_event` and `poll_result`.
83
84use std::fmt;
85use std::future::Future;
86use std::io;
87use std::pin::Pin;
88use std::task::Poll;
89
90use kermit_proto::Command;
91
92#[cfg(test)]
93use crate::Error;
94use crate::Result;
95use crate::calc::{CalcOps, CalcState, Model, TransferMode};
96use crate::grob::Grob;
97use crate::link::Link;
98pub use crate::link::Progress;
99use crate::reply::{Iopar, Listing, StackReply};
100use crate::session::{KermitCore, Options, Transcript};
101use crate::time::Duration;
102use crate::time::Instant;
103use crate::xmodem::{
104    self, XmodemDirection, XmodemOptions, XmodemPlan, XmodemReceived, XmodemReport,
105};
106use crate::xserv::{self, DirRecord, XservCommand, XservOptions, XservState};
107
108/// One operation of a [`Machine`]; each is the
109/// [`Calculator`](crate::Calculator) or
110/// [`XmodemSession`](crate::XmodemSession) method of the same name, and
111/// its result is the [`Reply`] variant named.
112#[derive(Clone, Debug)]
113#[non_exhaustive]
114pub enum Op {
115    /// Discard input for [`Options::drain`] (stale NAKs of the idle
116    /// server), then [`Op::Sync`]: the start of every connection.
117    /// [`Reply::Done`].
118    Connect,
119    /// [`Calculator::sync`](crate::Calculator::sync). [`Reply::Done`].
120    Sync,
121    /// One raw Kermit transaction. [`Reply::Transcript`].
122    Transact(Command),
123    /// A host command. [`Reply::Stack`].
124    Run(String),
125    /// [`Reply::Listing`].
126    List,
127    /// [`Reply::Path`].
128    Path,
129    /// Change to an absolute directory path. [`Reply::Done`].
130    Cd(Vec<String>),
131    /// [`Reply::Done`].
132    Updir,
133    /// [`Reply::Done`].
134    Mkdir(String),
135    /// [`Reply::Done`].
136    Remove(String),
137    /// [`Reply::Done`].
138    Rename {
139        /// The existing name.
140        from: String,
141        /// The new name, which must not exist.
142        to: String,
143    },
144    /// Free memory. [`Reply::Real`].
145    Mem,
146    /// [`Reply::Version`].
147    Version,
148    /// [`Reply::Model`].
149    Model,
150    /// [`Reply::Iopar`].
151    Iopar,
152    /// [`Reply::Done`].
153    SetIopar(Iopar),
154    /// [`Reply::TransferMode`].
155    TransferMode,
156    /// [`Reply::Done`].
157    SetTransferMode(TransferMode),
158    /// GET a variable. [`Reply::Data`].
159    Get {
160        /// The variable name.
161        name: String,
162        /// The transfer mode.
163        mode: TransferMode,
164    },
165    /// SEND a variable. [`Reply::Stored`].
166    Put {
167        /// The variable name.
168        name: String,
169        /// The file contents.
170        data: Vec<u8>,
171        /// The transfer mode.
172        mode: TransferMode,
173    },
174    /// [`Reply::Pict`].
175    Pict,
176    /// PICT as the binary transfer file the calculator sent (a GROB).
177    /// [`Reply::Data`].
178    PictFile,
179    /// [`Reply::Data`].
180    Backup,
181    /// [`Reply::Done`].
182    Restore(Vec<u8>),
183    /// [`Op::Restore`] with flag -35 set to `mode` just before `RESTORE`
184    /// (the calculator keeps its flags through it). [`Reply::Done`].
185    RestoreLeaving {
186        /// The backup.
187        data: Vec<u8>,
188        /// The transfer mode the calculator is left in.
189        mode: TransferMode,
190    },
191    /// [`Reply::Done`].
192    PurgeRestoreLeftover,
193    /// End server mode (`G F`). [`Reply::Done`].
194    Finish,
195    /// [`Reply::XmodemPlan`].
196    PrepareXmodem {
197        /// Which way the transfer goes.
198        direction: XmodemDirection,
199        /// The variable name.
200        name: String,
201    },
202    /// Send a file to a calculator running `XRECV`. [`Reply::XmodemSent`].
203    XmodemSend {
204        /// The file.
205        data: Vec<u8>,
206        /// The XModem options (see [`XmodemOptions::for_model`]).
207        options: XmodemOptions,
208    },
209    /// Receive a file from a calculator running `XSEND`.
210    /// [`Reply::XmodemReceived`].
211    XmodemReceive {
212        /// The XModem options (see [`XmodemOptions::for_model`]).
213        options: XmodemOptions,
214    },
215    /// XSERV: send `M` once and wait this long for the answer (see
216    /// [`xserv::memory_reply`]). [`Reply::XservProbe`].
217    XservProbe(Duration),
218    /// XSERV `L`. [`Reply::XservListing`].
219    XservList,
220    /// XSERV `M`. [`Reply::Real`].
221    XservMemory,
222    /// XSERV `E`: run RPL text; nothing comes back. [`Reply::Done`].
223    XservExecute(String),
224    /// XSERV `G`, then XModem. [`Reply::XmodemReceived`].
225    XservGet {
226        /// The variable, in the current directory.
227        name: String,
228        /// The XModem options (see [`xserv::transfer_options`]).
229        options: XmodemOptions,
230    },
231    /// XSERV `P`, then XModem. [`Reply::XmodemSent`].
232    XservPut {
233        /// The variable name.
234        name: String,
235        /// The file.
236        data: Vec<u8>,
237        /// The XModem options (see [`xserv::transfer_options`]).
238        options: XmodemOptions,
239    },
240    /// XSERV `Q`, then `M` once. [`Reply::XservQuit`].
241    XservQuit,
242}
243
244/// The result of an [`Op`].
245#[derive(Clone, Debug, PartialEq)]
246#[non_exhaustive]
247pub enum Reply {
248    /// The operation has no value.
249    Done,
250    /// What a raw transaction produced.
251    Transcript(Transcript),
252    /// The stack after a host command.
253    Stack(StackReply),
254    /// A directory listing.
255    Listing(Listing),
256    /// The current directory, e.g. `["HOME", "D1"]`.
257    Path(Vec<String>),
258    /// A number (free memory).
259    Real(f64),
260    /// The ROM version text; `None` on the 48SX.
261    Version(Option<String>),
262    /// The model.
263    Model(Model),
264    /// The serial settings.
265    Iopar(Iopar),
266    /// The transfer mode.
267    TransferMode(TransferMode),
268    /// File contents (GET, backup).
269    Data(Vec<u8>),
270    /// The name the calculator stored a sent file under.
271    Stored(String),
272    /// The PICT graphic.
273    Pict(Grob),
274    /// What the user must type for an XModem transfer.
275    XmodemPlan(XmodemPlan),
276    /// An XModem send finished.
277    XmodemSent(XmodemReport),
278    /// An XModem receive finished.
279    XmodemReceived(XmodemReceived),
280    /// XSERV's answer to the probe: the free memory, `None` for no XSERV.
281    XservProbe(Option<f64>),
282    /// An XSERV directory listing.
283    XservListing(Vec<DirRecord>),
284    /// Whether XSERV ended at `Q` (`false`: it still answers).
285    XservQuit(bool),
286}
287
288/// [`Machine::start`] while an operation runs.
289#[derive(Clone, Copy, Debug, PartialEq, Eq)]
290pub struct Busy;
291
292impl fmt::Display for Busy {
293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294        f.write_str("an operation is already running")
295    }
296}
297
298impl std::error::Error for Busy {}
299
300/// The protocol state that outlives an operation.
301#[derive(Debug)]
302struct Core {
303    kermit: KermitCore,
304    calc: CalcState,
305    xserv: XservState,
306}
307
308type Task = Pin<Box<dyn Future<Output = (Box<Core>, Result<Reply>)> + Send>>;
309
310/// A calculator link without I/O. See the [module documentation](self).
311pub struct Machine {
312    options: Options,
313    link: Link,
314    /// The protocol state while no operation runs (the task owns it
315    /// meanwhile).
316    core: Option<Box<Core>>,
317    task: Option<Task>,
318    result: Option<Result<Reply>>,
319    /// Seed of the next [`CalcState`] (after an abort).
320    seed: u64,
321    /// The XSERV client's timing (kept for the state after an abort).
322    xserv_options: XservOptions,
323}
324
325impl fmt::Debug for Machine {
326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327        f.debug_struct("Machine")
328            .field("busy", &self.is_busy())
329            .field("next_timeout", &self.next_timeout())
330            .finish_non_exhaustive()
331    }
332}
333
334impl Machine {
335    /// A machine for a newly opened link at `now`. `seed` should be random
336    /// (it picks the sync markers that tell this connection's replies from
337    /// a late one of an earlier client).
338    pub fn new(now: Instant, options: Options, seed: u64) -> Self {
339        let link = Link::new(now);
340        let core = Core {
341            kermit: KermitCore::new(link.clone(), &options),
342            calc: CalcState::new(seed),
343            xserv: XservState::new(XservOptions::default()),
344        };
345        Machine {
346            options,
347            link,
348            core: Some(Box::new(core)),
349            task: None,
350            result: None,
351            seed: seed.rotate_left(17) ^ 0xA5A5_A5A5_A5A5_A5A5,
352            xserv_options: XservOptions::default(),
353        }
354    }
355
356    /// The XSERV operations' timing (default [`XservOptions::default`]).
357    /// Takes effect at once while idle, else after the running operation.
358    pub fn set_xserv_options(&mut self, options: XservOptions) {
359        if let Some(core) = self.core.as_mut() {
360            core.xserv.options = options.clone();
361        }
362        self.xserv_options = options;
363    }
364
365    /// Begin `op`; its first bytes are ready for [`Machine::poll_transmit`]
366    /// at once. A result not yet taken with [`Machine::poll_result`] is
367    /// dropped.
368    pub fn start(&mut self, now: Instant, op: Op) -> std::result::Result<(), Busy> {
369        let Some(mut core) = self.core.take() else {
370            return Err(Busy);
371        };
372        self.link.set_now(now);
373        self.link.clear_error();
374        self.result = None;
375        let drain = self.options.drain;
376        let link = self.link.clone();
377        self.task = Some(Box::pin(async move {
378            let result = perform(&mut core, &link, drain, op).await;
379            (core, result)
380        }));
381        self.step();
382        Ok(())
383    }
384
385    /// Feed bytes read from the link at `now`.
386    pub fn handle_input(&mut self, now: Instant, bytes: &[u8]) {
387        self.link.set_now(now);
388        self.link.push_input(bytes);
389        self.step();
390        if self.task.is_none() {
391            // Nothing reads it until the next operation.
392            self.link.cap_idle_input();
393        }
394    }
395
396    /// Tell the machine the time is `now`.
397    pub fn handle_timeout(&mut self, now: Instant) {
398        self.link.set_now(now);
399        self.step();
400    }
401
402    /// The link failed or closed (a closed port is
403    /// [`io::ErrorKind::UnexpectedEof`]): the running operation fails with
404    /// [`Error::Io`](crate::Error::Io), except that a Kermit or XModem
405    /// transfer already complete keeps its result. The next
406    /// [`Machine::start`] clears the error.
407    pub fn handle_link_error(&mut self, now: Instant, error: &io::Error) {
408        self.link.set_now(now);
409        self.link.fail(error);
410        self.step();
411    }
412
413    /// The next chunk to write, one write each.
414    pub fn poll_transmit(&mut self) -> Option<Vec<u8>> {
415        self.link.take_output()
416    }
417
418    /// The next progress event.
419    pub fn poll_event(&mut self) -> Option<Progress> {
420        self.link.take_event()
421    }
422
423    /// Whether progress events are kept for [`Machine::poll_event`]
424    /// (default `true`). Off, they are dropped as they happen.
425    pub fn set_events(&mut self, keep: bool) {
426        self.link.set_keep_events(keep);
427    }
428
429    /// The result of the last operation, once it is over.
430    pub fn poll_result(&mut self) -> Option<Result<Reply>> {
431        self.result.take()
432    }
433
434    /// When to call [`Machine::handle_timeout`] at the latest; `None` while
435    /// no operation runs.
436    pub fn next_timeout(&self) -> Option<Instant> {
437        self.task.as_ref().and(self.link.wake())
438    }
439
440    /// Whether an operation runs.
441    pub fn is_busy(&self) -> bool {
442        self.task.is_some()
443    }
444
445    /// Drop the running operation at once, without telling the calculator.
446    /// Queued bytes are forgotten; the calculator may still be in the
447    /// middle of a transaction and answers the next command late, which the
448    /// next [`Op::Connect`] or [`Op::Sync`] sorts out. The cached transfer
449    /// mode is forgotten; the session keeps its options. No-op when idle.
450    pub fn abort(&mut self, now: Instant) {
451        if self.task.take().is_none() {
452            return;
453        }
454        self.link.set_now(now);
455        self.link.reset();
456        let mut kermit = KermitCore::new(self.link.clone(), &self.options);
457        kermit.ended_at(now);
458        let seed = self.seed;
459        self.seed = seed.rotate_left(17) ^ 0xA5A5_A5A5_A5A5_A5A5;
460        self.core = Some(Box::new(Core {
461            kermit,
462            calc: CalcState::new(seed),
463            xserv: XservState::new(self.xserv_options.clone()),
464        }));
465    }
466
467    fn step(&mut self) {
468        let Some(task) = self.task.as_mut() else {
469            return;
470        };
471        if let Poll::Ready((core, result)) = self.link.poll(task.as_mut()) {
472            self.core = Some(core);
473            self.task = None;
474            self.result = Some(result);
475        }
476    }
477}
478
479async fn perform(
480    core: &mut Core,
481    link: &Link,
482    drain: crate::time::Duration,
483    op: Op,
484) -> Result<Reply> {
485    let xs = &mut core.xserv;
486    if !op.is_xserv() {
487        // A Kermit operation (a nested server) or an XModem transfer: XSERV
488        // may need a moment before it answers again.
489        xs.settle = true;
490    }
491    let mut c = CalcOps {
492        k: &mut core.kermit,
493        st: &mut core.calc,
494    };
495    Ok(match op {
496        Op::Connect => {
497            link.drain(drain).await?;
498            c.sync().await?;
499            Reply::Done
500        }
501        Op::Sync => c.sync().await.map(|()| Reply::Done)?,
502        Op::Transact(command) => Reply::Transcript(c.k.transact(command).await?),
503        Op::Run(command) => Reply::Stack(c.run(&command).await?),
504        Op::List => Reply::Listing(c.list().await?),
505        Op::Path => Reply::Path(c.path().await?),
506        Op::Cd(path) => {
507            let path: Vec<&str> = path.iter().map(String::as_str).collect();
508            c.cd(&path).await?;
509            Reply::Done
510        }
511        Op::Updir => c.updir().await.map(|()| Reply::Done)?,
512        Op::Mkdir(name) => c.mkdir(&name).await.map(|()| Reply::Done)?,
513        Op::Remove(name) => c.remove(&name).await.map(|()| Reply::Done)?,
514        Op::Rename { from, to } => c.rename(&from, &to).await.map(|()| Reply::Done)?,
515        Op::Mem => Reply::Real(c.mem().await?),
516        Op::Version => Reply::Version(c.version().await?),
517        Op::Model => Reply::Model(c.model().await?),
518        Op::Iopar => Reply::Iopar(c.iopar().await?),
519        Op::SetIopar(iopar) => c.set_iopar(&iopar).await.map(|()| Reply::Done)?,
520        Op::TransferMode => Reply::TransferMode(c.transfer_mode().await?),
521        Op::SetTransferMode(mode) => c.set_transfer_mode(mode).await.map(|()| Reply::Done)?,
522        Op::Get { name, mode } => Reply::Data(c.get(&name, mode).await?),
523        Op::Put { name, data, mode } => Reply::Stored(c.put(&name, &data, mode).await?),
524        Op::Pict => Reply::Pict(c.pict().await?),
525        Op::PictFile => Reply::Data(c.pict_file().await?),
526        Op::Backup => Reply::Data(c.backup().await?),
527        Op::Restore(data) => c.restore(&data).await.map(|()| Reply::Done)?,
528        Op::RestoreLeaving { data, mode } => c
529            .restore_leaving(&data, Some(mode))
530            .await
531            .map(|()| Reply::Done)?,
532        Op::PurgeRestoreLeftover => c.purge_restore_leftover().await.map(|()| Reply::Done)?,
533        Op::Finish => c.finish().await.map(|()| Reply::Done)?,
534        Op::PrepareXmodem { direction, name } => {
535            Reply::XmodemPlan(c.prepare_for_xmodem(direction, &name).await?)
536        }
537        Op::XmodemSend { data, options } => {
538            Reply::XmodemSent(xmodem::send(link, &options, &data).await?)
539        }
540        Op::XmodemReceive { options } => {
541            Reply::XmodemReceived(xmodem::receive(link, &options).await?)
542        }
543        Op::XservProbe(wait) => Reply::XservProbe(xserv::probe(link, xs, wait).await?),
544        Op::XservList => Reply::XservListing(xserv::list(link, xs).await?),
545        Op::XservMemory => Reply::Real(xserv::memory(link, xs).await?),
546        Op::XservExecute(text) => {
547            xserv::command(link, xs, &XservCommand::Execute(text)).await?;
548            Reply::Done
549        }
550        Op::XservGet { name, options } => {
551            Reply::XmodemReceived(xserv::get(link, xs, &name, &options).await?)
552        }
553        Op::XservPut {
554            name,
555            data,
556            options,
557        } => Reply::XmodemSent(xserv::put(link, xs, &name, &data, &options).await?),
558        Op::XservQuit => Reply::XservQuit(xserv::quit(link, xs).await?),
559    })
560}
561
562impl Op {
563    /// Whether the operation talks to XSERV.
564    fn is_xserv(&self) -> bool {
565        matches!(
566            self,
567            Op::XservProbe(_)
568                | Op::XservList
569                | Op::XservMemory
570                | Op::XservExecute(_)
571                | Op::XservGet { .. }
572                | Op::XservPut { .. }
573                | Op::XservQuit
574        )
575    }
576}
577
578#[cfg(test)]
579#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
580mod tests {
581    use super::*;
582    use crate::time::Duration;
583    use kermit_proto::codec::{BlockCheck, Deframer, Framing, Packet, parse_frame};
584    use std::sync::{Arc, Mutex};
585    use xmodem_proto::codec::{ACK, EOT, NAK, decode_block, encode_block};
586    use xmodem_proto::{BlockSize, Check};
587
588    /// 10 bits per byte at 9600 baud, rounded up to whole microseconds.
589    fn wire(bytes: usize) -> Duration {
590        Duration::from_micros(1042 * bytes as u64)
591    }
592
593    /// Drive `m` against `peer` on a fake clock: every chunk written goes to
594    /// the peer, whose answer arrives after both wire times; with nothing
595    /// to write and no result, the clock jumps to the machine's deadline. No
596    /// threads, no sleeps.
597    fn run(
598        m: &mut Machine,
599        clock: &mut Instant,
600        peer: &mut dyn FnMut(&[u8]) -> Vec<Vec<u8>>,
601    ) -> Result<Reply> {
602        for _ in 0..100_000 {
603            while let Some(chunk) = m.poll_transmit() {
604                *clock += wire(chunk.len());
605                for answer in peer(&chunk) {
606                    *clock += wire(answer.len());
607                    m.handle_input(*clock, &answer);
608                }
609            }
610            if let Some(result) = m.poll_result() {
611                return result;
612            }
613            let deadline = m.next_timeout().expect("waits without a deadline");
614            *clock = (*clock).max(deadline);
615            m.handle_timeout(*clock);
616        }
617        panic!("no result");
618    }
619
620    fn options(timeout: Duration) -> Options {
621        let mut options = Options::default();
622        options.kermit.timeout = timeout;
623        options.kermit.linger = Duration::ZERO;
624        options.drain = Duration::ZERO;
625        options.turnaround = Duration::ZERO;
626        options
627    }
628
629    /// A Kermit server that sends file `X` (two D packets) in reply to R
630    /// and drops the first transmission of D seq 2, so only the client's
631    /// timeout and NAK recover it.
632    fn lossy_server(naks: Arc<Mutex<u32>>) -> impl FnMut(&[u8]) -> Vec<Vec<u8>> {
633        let check = BlockCheck::Type1;
634        let mut deframer = Deframer::new();
635        let mut dropped = false;
636        move |bytes| {
637            let wire = |seq: u8, kind: u8, data: &[u8]| {
638                Packet::new(seq, kind, data.to_vec())
639                    .encode(check, &Framing::default())
640                    .unwrap()
641            };
642            deframer.push(bytes);
643            let mut replies = Vec::new();
644            while let Some(frame) = deframer.next_frame() {
645                let p = parse_frame(&frame, check).unwrap();
646                match (p.kind, p.seq) {
647                    (b'R', _) => replies.push(wire(0, b'S', b"~* @-#Y1 ")),
648                    (b'Y', 0) => replies.push(wire(1, b'F', b"X")),
649                    (b'Y', 1) if !dropped => dropped = true,
650                    (b'Y', 1) => {}
651                    (b'N', 2) => {
652                        *naks.lock().unwrap() += 1;
653                        replies.push(wire(2, b'D', b"hello "));
654                    }
655                    (b'Y', 2) => replies.push(wire(3, b'D', b"world")),
656                    (b'Y', 3) => replies.push(wire(4, b'Z', b"")),
657                    (b'Y', 4) => replies.push(wire(5, b'B', b"")),
658                    (b'Y', 5) => {}
659                    (kind, seq) => panic!("unexpected packet {} seq {seq}", char::from(kind)),
660                }
661            }
662            replies
663        }
664    }
665
666    /// A Kermit GET through the machine: the dropped packet costs one
667    /// 20-second timeout of the fake clock and no real time.
668    #[test]
669    fn kermit_get_recovers_a_lost_packet_on_a_fake_clock() {
670        let t0 = Instant::now();
671        let mut clock = t0;
672        let timeout = Duration::from_secs(20);
673        let mut m = Machine::new(clock, options(timeout), 1);
674        let naks = Arc::new(Mutex::new(0));
675        let mut peer = lossy_server(Arc::clone(&naks));
676        m.start(clock, Op::Transact(Command::Get(b"X".to_vec())))
677            .unwrap();
678        assert!(m.is_busy());
679        let reply = run(&mut m, &mut clock, &mut peer).unwrap();
680        let Reply::Transcript(t) = reply else {
681            panic!("{reply:?}");
682        };
683        assert_eq!(t.files.len(), 1);
684        assert_eq!(t.files[0].name, "X");
685        assert_eq!(t.files[0].data, b"hello world");
686        assert_eq!(*naks.lock().unwrap(), 1);
687        assert!(clock - t0 >= timeout, "{:?}", clock - t0);
688        assert!(t0.elapsed() < Duration::from_secs(2));
689        assert!(!m.is_busy());
690        assert_eq!(m.next_timeout(), None);
691        let mut files = 0;
692        while let Some(event) = m.poll_event() {
693            if matches!(
694                event,
695                Progress::Kermit(kermit_proto::Event::FileStart { .. })
696            ) {
697                files += 1;
698            }
699        }
700        assert_eq!(files, 1);
701    }
702
703    /// Calculator operations through the machine: connect (sync with the
704    /// seeded marker), then a listing.
705    #[test]
706    fn connect_and_list_through_the_machine() {
707        let log = Arc::default();
708        let mut peer = crate::calc::tests::fake_server(Arc::clone(&log), |cmd: &str| {
709            if cmd.starts_with("\"SATX-") {
710                format!("1:      {cmd}\r\n")
711            } else if cmd == "DROP" {
712                "Empty Stack\r\n".into()
713            } else if cmd == "G D" {
714                "{ HOME D1 } 127847\r\nX 10.5 Real Number 1234\r\n".into()
715            } else {
716                panic!("unexpected {cmd}")
717            }
718        });
719        let mut clock = Instant::now();
720        let mut m = Machine::new(clock, options(Duration::from_secs(5)), 7);
721        m.set_events(false);
722        m.start(clock, Op::Connect).unwrap();
723        assert_eq!(m.start(clock, Op::List), Err(Busy));
724        assert_eq!(run(&mut m, &mut clock, &mut peer).unwrap(), Reply::Done);
725        m.start(clock, Op::List).unwrap();
726        let Reply::Listing(listing) = run(&mut m, &mut clock, &mut peer).unwrap() else {
727            panic!("not a listing");
728        };
729        assert_eq!(listing.path, Some(vec!["HOME".into(), "D1".into()]));
730        assert_eq!(listing.entries.len(), 1);
731        assert_eq!(m.poll_event(), None);
732        let sent = log.lock().unwrap().clone();
733        assert_eq!(sent.len(), 3, "{sent:?}");
734        assert!(sent[0].starts_with("\"SATX-"));
735        assert_eq!(sent[1..], ["DROP", "G D"]);
736    }
737
738    /// A `C` the calculator never took is sent once: `NoReply`.
739    #[test]
740    fn a_lost_host_command_is_not_resent() {
741        let log = Arc::default();
742        let mut server = crate::calc::tests::fake_server(Arc::clone(&log), |cmd: &str| {
743            assert_eq!(cmd, "1");
744            "1:      1\r\n".into()
745        });
746        let mut lost = false;
747        let mut peer = |bytes: &[u8]| {
748            let is_c = bytes
749                .iter()
750                .position(|&b| b == 0x01)
751                .and_then(|i| bytes.get(i + 3))
752                == Some(&b'C');
753            if is_c && !lost {
754                lost = true;
755                return Vec::new();
756            }
757            server(bytes)
758        };
759        let mut clock = Instant::now();
760        let mut m = Machine::new(clock, options(Duration::from_secs(1)), 7);
761        m.start(clock, Op::Run("1".into())).unwrap();
762        let result = run(&mut m, &mut clock, &mut peer);
763        assert!(matches!(result, Err(Error::NoReply { .. })), "{result:?}");
764    }
765
766    /// A Windows device name is refused before anything is sent.
767    #[test]
768    fn device_names_are_refused() {
769        let mut clock = Instant::now();
770        let mut m = Machine::new(clock, options(Duration::from_millis(50)), 7);
771        m.set_events(false);
772        let op = Op::Get {
773            name: "AUX".into(),
774            mode: TransferMode::Binary,
775        };
776        m.start(clock, op).unwrap();
777        let result = run(&mut m, &mut clock, &mut |_: &[u8]| Vec::new());
778        assert!(matches!(result, Err(Error::Name(_))), "{result:?}");
779    }
780
781    /// A 48GX-like XModem sender (checksum, 128-byte blocks) answering the
782    /// machine's start NAKs.
783    fn xsend_peer(file: Vec<u8>) -> impl FnMut(&[u8]) -> Vec<Vec<u8>> {
784        let blocks: Vec<Vec<u8>> = file
785            .chunks(128)
786            .enumerate()
787            .map(|(i, chunk)| {
788                encode_block((i + 1) as u8, BlockSize::B128, chunk, 0, Check::Checksum).unwrap()
789            })
790            .collect();
791        let mut next = 0;
792        move |bytes| match bytes.last() {
793            Some(&NAK) if next == 0 => {
794                next = 1;
795                vec![blocks[0].clone()]
796            }
797            Some(&ACK) if next < blocks.len() => {
798                next += 1;
799                vec![blocks[next - 1].clone()]
800            }
801            Some(&ACK) if next == blocks.len() => {
802                next += 1;
803                vec![vec![EOT]]
804            }
805            _ => Vec::new(),
806        }
807    }
808
809    fn fast_xmodem() -> XmodemOptions {
810        let mut options = XmodemOptions::for_model(Model::Hp48Gx).unwrap();
811        options.xmodem.linger = Duration::ZERO;
812        options
813    }
814
815    /// An HP String object file with `n` characters.
816    fn hp_string(n: usize) -> Vec<u8> {
817        let len = 5 + 2 * n;
818        let mut nibbles = vec![0xC, 0x2, 0xA, 0x2, 0x0];
819        nibbles.extend((0..5).map(|i| ((len >> (4 * i)) & 0xF) as u8));
820        let mut out = b"HPHP48-R".to_vec();
821        out.extend(crate::object::pack(&nibbles));
822        out.extend((0..n).map(|i| (i % 251) as u8));
823        out
824    }
825
826    /// An XModem receive through the machine on the fake clock: the
827    /// sender answers the first start NAK, the padding is cut.
828    #[test]
829    fn xmodem_receive_through_the_machine() {
830        let file = hp_string(300);
831        let mut peer = xsend_peer(file.clone());
832        let t0 = Instant::now();
833        let mut clock = t0;
834        let mut m = Machine::new(clock, options(Duration::from_secs(5)), 3);
835        m.start(
836            clock,
837            Op::XmodemReceive {
838                options: fast_xmodem(),
839            },
840        )
841        .unwrap();
842        let Reply::XmodemReceived(got) = run(&mut m, &mut clock, &mut peer).unwrap() else {
843            panic!("not received");
844        };
845        assert_eq!(got.data, file);
846        assert_eq!(got.check, Check::Checksum);
847        assert_eq!(got.received, 384);
848        assert_eq!(got.stripped, Some(384 - file.len()));
849        assert!(t0.elapsed() < Duration::from_secs(2));
850    }
851
852    /// An XModem send through the machine: the receiver waits two of its
853    /// 3-second periods before the first start NAK (the user typing
854    /// `XRECV`), which only the fake clock sees.
855    #[test]
856    fn xmodem_send_through_the_machine() {
857        let file = hp_string(200);
858        let received = Arc::new(Mutex::new(Vec::new()));
859        let got = Arc::clone(&received);
860        let mut blocks = 0u8;
861        let mut peer = move |bytes: &[u8]| -> Vec<Vec<u8>> {
862            if bytes == [EOT] {
863                return vec![vec![ACK]];
864            }
865            let block = decode_block(bytes, Check::Checksum).unwrap();
866            blocks += 1;
867            assert_eq!(block.num, blocks);
868            got.lock().unwrap().extend_from_slice(&block.data);
869            vec![vec![ACK]]
870        };
871        let t0 = Instant::now();
872        let mut clock = t0;
873        let mut m = Machine::new(clock, options(Duration::from_secs(5)), 4);
874        m.start(
875            clock,
876            Op::XmodemSend {
877                data: file.clone(),
878                options: fast_xmodem(),
879            },
880        )
881        .unwrap();
882        // Nothing to send before the receiver asks.
883        assert_eq!(m.poll_transmit(), None);
884        clock += Duration::from_secs(6);
885        m.handle_timeout(clock);
886        m.handle_input(clock, &[NAK]);
887        let Reply::XmodemSent(report) = run(&mut m, &mut clock, &mut peer).unwrap() else {
888            panic!("not sent");
889        };
890        assert_eq!(report.check, Check::Checksum);
891        assert_eq!(report.bytes, file.len() as u64);
892        let data = received.lock().unwrap().clone();
893        // Two 128-byte blocks, the second padded.
894        assert_eq!(data.len(), 256);
895        assert_eq!(&data[..file.len()], &file[..]);
896        assert!(t0.elapsed() < Duration::from_secs(2));
897    }
898
899    /// A Kermit server that sends file `X` ("hi") in reply to R, counting
900    /// the R packets it gets.
901    fn file_server(requests: Arc<Mutex<u32>>) -> impl FnMut(&[u8]) -> Vec<Vec<u8>> {
902        let check = BlockCheck::Type1;
903        let mut deframer = Deframer::new();
904        move |bytes| {
905            let wire = |seq: u8, kind: u8, data: &[u8]| {
906                Packet::new(seq, kind, data.to_vec())
907                    .encode(check, &Framing::default())
908                    .unwrap()
909            };
910            deframer.push(bytes);
911            let mut replies = Vec::new();
912            while let Some(frame) = deframer.next_frame() {
913                let p = parse_frame(&frame, check).unwrap();
914                match (p.kind, p.seq) {
915                    (b'R', _) => {
916                        *requests.lock().unwrap() += 1;
917                        replies.push(wire(0, b'S', b"~* @-#Y1 "));
918                    }
919                    (b'Y', 0) => replies.push(wire(1, b'F', b"X")),
920                    (b'Y', 1) => replies.push(wire(2, b'D', b"hi")),
921                    (b'Y', 2) => replies.push(wire(3, b'Z', b"")),
922                    (b'Y', 3) => replies.push(wire(4, b'B', b"")),
923                    (b'Y', 4) => {}
924                    (kind, seq) => panic!("unexpected packet {} seq {seq}", char::from(kind)),
925                }
926            }
927            replies
928        }
929    }
930
931    /// PR 108 review: one feed larger than the idle-input cap during an
932    /// operation keeps every byte. Here the server's S comes first, then
933    /// more than 64 KiB of line noise; cut from the front, the S would be
934    /// lost and the GET would ask again after a timeout.
935    #[test]
936    fn a_big_feed_during_an_operation_keeps_every_byte() {
937        let requests = Arc::new(Mutex::new(0));
938        let mut peer = file_server(Arc::clone(&requests));
939        let mut clock = Instant::now();
940        let mut m = Machine::new(clock, options(Duration::from_secs(5)), 8);
941        m.set_events(false);
942        m.start(clock, Op::Transact(Command::Get(b"X".to_vec())))
943            .unwrap();
944        let request = m.poll_transmit().unwrap();
945        let mut feed = peer(&request).concat();
946        feed.extend(std::iter::repeat_n(b'z', 70 * 1024));
947        clock += Duration::from_millis(50);
948        m.handle_input(clock, &feed);
949        let Reply::Transcript(t) = run(&mut m, &mut clock, &mut peer).unwrap() else {
950            panic!("not a transcript");
951        };
952        assert_eq!(t.files.len(), 1);
953        assert_eq!(t.files[0].data, b"hi");
954        assert_eq!(*requests.lock().unwrap(), 1);
955
956        // Idle, the input nobody reads is capped.
957        m.handle_input(clock, &vec![b'z'; 70 * 1024]);
958        assert_eq!(m.link.unread_input(), 64 * 1024);
959    }
960
961    /// PR 108 review: an abort drops the aborted operation's events and
962    /// unread input, so the next operation sees none of them.
963    #[test]
964    fn abort_drops_events_and_input_of_the_aborted_operation() {
965        let mut get_peer = file_server(Arc::default());
966        let mut clock = Instant::now();
967        let mut m = Machine::new(clock, options(Duration::from_secs(5)), 9);
968        m.start(clock, Op::Transact(Command::Get(b"X".to_vec())))
969            .unwrap();
970        // R out, S in; the ACK out, F in: FileStart is queued.
971        for _ in 0..2 {
972            let chunk = m.poll_transmit().unwrap();
973            clock += Duration::from_millis(10);
974            m.handle_input(clock, &get_peer(&chunk).concat());
975        }
976        // Half a packet the operation has not read yet.
977        m.link.push_input(b"\x01+\"");
978        m.abort(clock);
979        assert_eq!(m.poll_event(), None);
980        assert_eq!(m.link.unread_input(), 0);
981
982        let mut peer = crate::calc::tests::fake_server(Arc::default(), |cmd: &str| {
983            assert_eq!(cmd, "G D");
984            "{ HOME } 1000\r\n".into()
985        });
986        m.start(clock, Op::List).unwrap();
987        let Reply::Listing(listing) = run(&mut m, &mut clock, &mut peer).unwrap() else {
988            panic!("not a listing");
989        };
990        assert_eq!(listing.path, Some(vec!["HOME".into()]));
991        while let Some(event) = m.poll_event() {
992            assert!(
993                !matches!(
994                    event,
995                    Progress::Kermit(kermit_proto::Event::FileStart { .. })
996                ),
997                "a stale event of the aborted GET: {event:?}"
998            );
999        }
1000    }
1001
1002    /// Answers of a peer, each with the delay before it is sent.
1003    type Timed = Vec<(Duration, Vec<u8>)>;
1004
1005    /// Like [`run`], with each answer of `peer` arriving after its delay
1006    /// (plus wire time) and, with `noise_every`, a burst of noise (no
1007    /// packet start) that often. The clock jumps to the next arrival, noise
1008    /// or deadline.
1009    fn run_timed(
1010        m: &mut Machine,
1011        clock: &mut Instant,
1012        peer: &mut dyn FnMut(&[u8]) -> Timed,
1013        noise_every: Option<Duration>,
1014    ) -> Result<Reply> {
1015        let mut pending: Vec<(Instant, Vec<u8>)> = Vec::new();
1016        let mut next_noise = noise_every.map(|every| *clock + every);
1017        for _ in 0..1_000_000 {
1018            while let Some(chunk) = m.poll_transmit() {
1019                *clock += wire(chunk.len());
1020                for (delay, answer) in peer(&chunk) {
1021                    pending.push((*clock + delay + wire(answer.len()), answer));
1022                }
1023            }
1024            if let Some(result) = m.poll_result() {
1025                return result;
1026            }
1027            let next_input = pending.iter().map(|(t, _)| *t).min();
1028            let next = [next_input, next_noise, m.next_timeout()]
1029                .into_iter()
1030                .flatten()
1031                .min()
1032                .expect("nothing to wait for");
1033            *clock = (*clock).max(next);
1034            let due = pending
1035                .iter()
1036                .enumerate()
1037                .filter(|(_, (t, _))| *t <= *clock)
1038                .min_by_key(|(_, (t, _))| *t)
1039                .map(|(i, _)| i);
1040            if let Some(i) = due {
1041                let (_, bytes) = pending.remove(i);
1042                m.handle_input(*clock, &bytes);
1043            } else if next_noise.is_some_and(|t| t <= *clock) {
1044                m.handle_input(*clock, b"zq~");
1045                next_noise = noise_every.map(|every| *clock + every);
1046            } else {
1047                m.handle_timeout(*clock);
1048            }
1049        }
1050        panic!("no result");
1051    }
1052
1053    fn kermit_wire(seq: u8, kind: u8, data: &[u8]) -> Vec<u8> {
1054        Packet::new(seq, kind, data.to_vec())
1055            .encode(BlockCheck::Type1, &Framing::default())
1056            .unwrap()
1057    }
1058
1059    /// A server that answers the first packet with `script[0]` (its S) and
1060    /// the ACK of packet `n` with `script[n + 1]`, each after `delay`; an
1061    /// ACK of an earlier packet gets that packet's successor again.
1062    fn scripted_server(script: Vec<(u8, Vec<u8>)>, delay: Duration) -> impl FnMut(&[u8]) -> Timed {
1063        let mut deframer = Deframer::new();
1064        move |bytes| {
1065            deframer.push(bytes);
1066            let mut replies = Vec::new();
1067            while let Some(frame) = deframer.next_frame() {
1068                let p = parse_frame(&frame, BlockCheck::Type1).unwrap();
1069                let next = match p.kind {
1070                    b'R' | b'C' => Some(0),
1071                    b'Y' => Some(usize::from(p.seq) + 1),
1072                    _ => None,
1073                };
1074                if let Some(i) = next
1075                    && let Some((kind, data)) = script.get(i)
1076                {
1077                    replies.push((delay, kermit_wire(u8::try_from(i).unwrap(), *kind, data)));
1078                }
1079            }
1080            replies
1081        }
1082    }
1083
1084    /// A server that sends file `X` in reply to R, then answers every ACK
1085    /// of its F with the F again after `delay`: the previous packet
1086    /// replayed, forever.
1087    fn replaying_server(delay: Duration) -> impl FnMut(&[u8]) -> Timed {
1088        let mut deframer = Deframer::new();
1089        move |bytes| {
1090            deframer.push(bytes);
1091            let mut replies = Vec::new();
1092            while let Some(frame) = deframer.next_frame() {
1093                let p = parse_frame(&frame, BlockCheck::Type1).unwrap();
1094                match (p.kind, p.seq) {
1095                    (b'R', _) => replies.push((delay, kermit_wire(0, b'S', b"~* @-#Y1 "))),
1096                    (b'Y', 0 | 1) => replies.push((delay, kermit_wire(1, b'F', b"X"))),
1097                    _ => {}
1098                }
1099            }
1100            replies
1101        }
1102    }
1103
1104    /// A machine whose client never runs out of retries (only the watchdog
1105    /// ends a transaction) and whose watchdog allows `stall`.
1106    fn endless_machine(clock: Instant, timeout: Duration, stall: Duration) -> Machine {
1107        let mut options = options(timeout);
1108        options.kermit.retries = u32::MAX;
1109        let mut m = Machine::new(clock, options, 7);
1110        m.core.as_mut().unwrap().kermit.stall_limit = Some(stall);
1111        m
1112    }
1113
1114    /// Iteration 48: a peer replaying its last packet is cancelled once no
1115    /// new packet came for the stall limit, on the fake clock.
1116    #[test]
1117    fn a_replaying_peer_stalls_on_a_fake_clock() {
1118        let t0 = Instant::now();
1119        let mut clock = t0;
1120        let stall = Duration::from_secs(2);
1121        let mut m = endless_machine(clock, Duration::from_secs(1), stall);
1122        m.start(clock, Op::Transact(Command::Get(b"X".to_vec())))
1123            .unwrap();
1124        let mut peer = replaying_server(Duration::from_millis(300));
1125        let err = run_timed(&mut m, &mut clock, &mut peer, None).unwrap_err();
1126        assert!(matches!(err, Error::Stalled(l) if l == stall), "{err:?}");
1127        // The F came after two 300 ms answers; the stall limit after it.
1128        let took = clock - t0;
1129        assert!(
1130            took >= stall && took < stall + Duration::from_secs(1),
1131            "{took:?}"
1132        );
1133        assert!(!m.is_busy());
1134    }
1135
1136    /// Iteration 48: noise every 10 ms (no packet ever) is cancelled by the
1137    /// watchdog, on the fake clock.
1138    #[test]
1139    fn a_babbling_line_stalls_on_a_fake_clock() {
1140        let t0 = Instant::now();
1141        let mut clock = t0;
1142        let stall = Duration::from_secs(5);
1143        let mut m = endless_machine(clock, Duration::from_secs(1), stall);
1144        m.start(clock, Op::Transact(Command::Host(b"6 7 *".to_vec())))
1145            .unwrap();
1146        let mut silent = |_: &[u8]| Vec::new();
1147        let every = Duration::from_millis(10);
1148        let err = run_timed(&mut m, &mut clock, &mut silent, Some(every)).unwrap_err();
1149        assert!(matches!(err, Error::Stalled(_)), "{err:?}");
1150        let took = clock - t0;
1151        assert!(
1152            took >= stall && took < stall + Duration::from_millis(100),
1153            "{took:?}"
1154        );
1155    }
1156
1157    /// Iteration 48: with the limit from the configuration (20 s timeout,
1158    /// 5 retries: 141 s), a replaying peer and a babbling line both end
1159    /// within it.
1160    #[test]
1161    fn replaying_and_babbling_end_within_the_default_limit() {
1162        let timeout = Duration::from_secs(20);
1163        let limit = crate::session::stall_limit(&options(timeout).kermit);
1164        assert_eq!(limit, Duration::from_secs(141));
1165
1166        let t0 = Instant::now();
1167        let mut clock = t0;
1168        let mut m = Machine::new(clock, options(timeout), 8);
1169        m.start(clock, Op::Transact(Command::Get(b"X".to_vec())))
1170            .unwrap();
1171        let mut peer = replaying_server(Duration::from_secs(1));
1172        let err = run_timed(&mut m, &mut clock, &mut peer, None).unwrap_err();
1173        assert!(
1174            matches!(err, Error::Kermit(_) | Error::Stalled(_)),
1175            "{err:?}"
1176        );
1177        assert!(clock - t0 <= limit, "{:?}", clock - t0);
1178
1179        let t0 = clock;
1180        let mut m = Machine::new(clock, options(timeout), 9);
1181        m.start(clock, Op::Transact(Command::Host(b"6 7 *".to_vec())))
1182            .unwrap();
1183        let mut silent = |_: &[u8]| Vec::new();
1184        let every = Duration::from_millis(50);
1185        let err = run_timed(&mut m, &mut clock, &mut silent, Some(every)).unwrap_err();
1186        assert!(
1187            matches!(err, Error::Kermit(_) | Error::Stalled(_)),
1188            "{err:?}"
1189        );
1190        assert!(clock - t0 <= limit, "{:?}", clock - t0);
1191    }
1192
1193    /// Iteration 48: a long transfer that moves on never trips the
1194    /// watchdog: a GET of 60 packets, each answered after 0.9 of the
1195    /// timeout, takes far longer than the stall limit (7 s) and succeeds;
1196    /// so does a host command the calculator computes for 0.95 of the
1197    /// timeout and answers as slowly.
1198    #[test]
1199    fn a_long_slow_transfer_never_stalls() {
1200        let timeout = Duration::from_secs(1);
1201        let limit = crate::session::stall_limit(&options(timeout).kermit);
1202        let init = (b'S', b"~* @-#Y1 ".to_vec());
1203
1204        let mut script = vec![init.clone(), (b'F', b"X".to_vec())];
1205        let chunks: Vec<Vec<u8>> = (0..60u8).map(|i| vec![b'a' + i % 26; 40]).collect();
1206        script.extend(chunks.iter().map(|c| (b'D', c.clone())));
1207        script.extend([(b'Z', Vec::new()), (b'B', Vec::new())]);
1208        let t0 = Instant::now();
1209        let mut clock = t0;
1210        let mut m = Machine::new(clock, options(timeout), 10);
1211        m.start(clock, Op::Transact(Command::Get(b"X".to_vec())))
1212            .unwrap();
1213        let mut peer = scripted_server(script, timeout.mul_f32(0.9));
1214        let reply = run_timed(&mut m, &mut clock, &mut peer, None).unwrap();
1215        let Reply::Transcript(t) = reply else {
1216            panic!("{reply:?}");
1217        };
1218        assert_eq!(t.files.len(), 1);
1219        assert_eq!(t.files[0].data, chunks.concat());
1220        assert!(clock - t0 > 5 * limit, "{:?}", clock - t0);
1221
1222        let mut script = vec![init, (b'X', Vec::new())];
1223        script.extend((0..20).map(|_| (b'D', b"42 ".to_vec())));
1224        script.extend([(b'Z', Vec::new()), (b'B', Vec::new())]);
1225        let t0 = clock;
1226        let mut m = Machine::new(clock, options(timeout), 11);
1227        m.start(clock, Op::Transact(Command::Host(b"SLOW".to_vec())))
1228            .unwrap();
1229        let mut slow = scripted_server(script, timeout.mul_f32(0.95));
1230        let reply = run_timed(&mut m, &mut clock, &mut slow, None).unwrap();
1231        let Reply::Transcript(t) = reply else {
1232            panic!("{reply:?}");
1233        };
1234        assert_eq!(t.text, b"42 ".repeat(20));
1235        assert!(clock - t0 > 2 * limit, "{:?}", clock - t0);
1236    }
1237
1238    /// A link error fails the running operation; an abort frees the
1239    /// machine for the next one.
1240    #[test]
1241    fn link_error_and_abort() {
1242        let mut clock = Instant::now();
1243        let mut m = Machine::new(clock, options(Duration::from_secs(5)), 5);
1244        m.start(clock, Op::List).unwrap();
1245        assert!(m.poll_transmit().is_some());
1246        clock += Duration::from_millis(5);
1247        m.handle_link_error(clock, &io::Error::from(io::ErrorKind::UnexpectedEof));
1248        assert!(
1249            matches!(m.poll_result(), Some(Err(Error::Io(e))) if e.kind() == io::ErrorKind::UnexpectedEof)
1250        );
1251        assert!(!m.is_busy());
1252
1253        let mut m = Machine::new(clock, options(Duration::from_secs(5)), 6);
1254        m.start(clock, Op::List).unwrap();
1255        assert!(m.next_timeout().is_some());
1256        m.abort(clock);
1257        assert!(!m.is_busy());
1258        assert_eq!(m.poll_transmit(), None);
1259        assert_eq!(m.next_timeout(), None);
1260        assert!(m.poll_result().is_none());
1261        m.start(clock, Op::List).unwrap();
1262        assert!(m.poll_transmit().is_some());
1263    }
1264}