Skip to main content

satx_core/
session.rs

1//! Drives a [`kermit_proto::Client`] over a byte link.
2//!
3//! The loop is the one from `kermit-proto`'s docs: write each queued packet
4//! with one write (the HP overruns on inter-byte gaps), handle the events,
5//! read until the client's next deadline and feed input or a timeout back.
6//! After `Done` or `Error` it keeps going until the final ACK or E packet is
7//! out, and through the client's linger after a receive (re-ACKing a
8//! repeated `B`). Input left over from the idle server (it NAKs once, a
9//! server timeout after its last packet, and then stays silent) is drained
10//! when the session is created.
11//!
12//! A no-progress watchdog is the backstop above the client's retries: a
13//! transaction in which no new packet is accepted for longer than the
14//! client could need to give up on one packet, (timeout + packet pause) x
15//! (retries + 2) + 1 s, is cancelled with [`Error::Stalled`], also when the peer keeps the line
16//! busy (a packet replayed over and over, noise at the right rate). The
17//! limit counts time without progress on the caller's clock, so a long
18//! transfer that moves on, or a host command the calculator computes for a
19//! long time and answers within the timeout, never trips it.
20//!
21//! The loop is written once, as async code on the crate's link (see
22//! [`machine`](crate::machine)); [`Session`] runs it over a [`Transport`]
23//! with the system clock, [`Machine`](crate::Machine) with the caller's.
24
25use kermit_proto::{Client, Command, Config, Event, StartError};
26
27use crate::charset;
28#[cfg(not(target_arch = "wasm32"))]
29use crate::link;
30use crate::link::{Link, Progress};
31use crate::time::{Duration, Instant};
32#[cfg(not(target_arch = "wasm32"))]
33use crate::transport::{self, Transport};
34use crate::watchdog::Watchdog;
35use crate::{Error, Result};
36
37/// Read wait while a transaction runs but the client has no deadline.
38const IDLE_WAIT: Duration = Duration::from_millis(100);
39/// Shortest read wait.
40const MIN_WAIT: Duration = Duration::from_millis(10);
41/// Read wait while discarding input that is already waiting before a host
42/// command ([`Session::transact_with`]): long enough to collect what the
43/// link has buffered, short enough to cost nothing noticeable.
44const PENDING_WAIT: Duration = Duration::from_millis(1);
45/// Most time spent discarding waiting input before a host command (a link
46/// that never goes quiet must not stall the command).
47const PENDING_MAX: Duration = Duration::from_millis(50);
48
49/// How long a Kermit transaction may go without a new packet accepted
50/// before the watchdog cancels it: one more try than the most the client
51/// makes for one packet (its retries, or the first packet's with the one
52/// resend an immediate NAK grants), each a receive timeout plus the packet
53/// pause, one more for slack, and [`STALL_SLACK`] for a late clock.
54pub(crate) fn stall_limit(config: &Config) -> Duration {
55    let first = config
56        .first_packet_retries
57        .map_or(config.retries, |r| r.saturating_add(1));
58    let tries = config.retries.max(first).saturating_add(2);
59    config
60        .timeout
61        .saturating_add(config.packet_pause)
62        .saturating_mul(tries)
63        .saturating_add(STALL_SLACK)
64}
65
66/// Fixed slack on the stall limit, so the client's own timeout always
67/// comes first even when every read returns late: with short timeouts one
68/// extra try was not enough on a loaded CI runner (100 ms timeouts, six
69/// reads late by more than 100 ms in all, `Stalled` instead of `Timeout`).
70const STALL_SLACK: Duration = Duration::from_secs(1);
71
72/// Tunables for a [`Session`].
73#[derive(Clone, Debug)]
74pub struct Options {
75    /// Kermit client configuration. The default lingers after a receive
76    /// ([`Config::linger`]) as long as the turnaround, which the linger
77    /// counts toward: no extra delay between transactions.
78    pub kermit: Config,
79    /// How long to discard input after opening (stale NAKs).
80    pub drain: Duration,
81    /// Pause between the end of one transaction and the start of the next.
82    /// The HP drops a command packet that arrives right after the final ACK
83    /// of the previous transaction, and only answers after its own timeout
84    /// (about 6 s) NAKs it; 100 ms was enough on the emulator. Counted
85    /// from the `Done` or `Error`, so the client's linger runs inside it.
86    pub turnaround: Duration,
87}
88
89impl Default for Options {
90    fn default() -> Self {
91        let turnaround = Duration::from_millis(200);
92        let mut kermit = Config::default();
93        kermit.linger = turnaround;
94        Options {
95            kermit,
96            drain: Duration::from_millis(500),
97            turnaround,
98        }
99    }
100}
101
102/// A file received with a GET.
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct ReceivedFile {
105    /// Name from the F packet, decoded from the HP character set.
106    pub name: String,
107    /// File contents.
108    pub data: Vec<u8>,
109}
110
111/// What a transaction produced.
112#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct Transcript {
114    /// Received files (GET); discarded files are left out.
115    pub files: Vec<ReceivedFile>,
116    /// Names the calculator stored sent files under (SEND), decoded.
117    pub stored_names: Vec<String>,
118    /// All server text (host command and directory replies), raw HP bytes.
119    pub text: Vec<u8>,
120}
121
122/// The Kermit side of a link, without the I/O: the client, its
123/// configuration and the pacing between transactions.
124#[derive(Debug)]
125pub(crate) struct KermitCore {
126    pub(crate) link: Link,
127    client: Client,
128    config: Config,
129    turnaround: Duration,
130    /// When the last transaction ended.
131    last_end: Option<Instant>,
132    /// See [`Session::answered`].
133    answered: bool,
134    /// The watchdog's limit instead of [`stall_limit`] of the config (tests
135    /// shorten it below what the client's own retries take).
136    pub(crate) stall_limit: Option<Duration>,
137}
138
139impl KermitCore {
140    pub(crate) fn new(link: Link, options: &Options) -> Self {
141        KermitCore {
142            link,
143            client: Client::new(options.kermit.clone()),
144            config: options.kermit.clone(),
145            turnaround: options.turnaround,
146            last_end: None,
147            answered: false,
148            stall_limit: None,
149        }
150    }
151
152    pub(crate) fn config(&self) -> &Config {
153        &self.config
154    }
155
156    pub(crate) fn set_config(&mut self, config: Config) {
157        self.client = Client::new(config.clone());
158        self.config = config;
159    }
160
161    pub(crate) fn answered(&self) -> bool {
162        self.answered
163    }
164
165    /// Count a transaction as ended at `now` (an aborted one): the next
166    /// waits for the turnaround.
167    pub(crate) fn ended_at(&mut self, now: Instant) {
168        self.last_end = Some(now);
169    }
170
171    /// Run one transaction to completion; every event goes to the link.
172    pub(crate) async fn transact(&mut self, command: Command) -> Result<Transcript> {
173        if let Some(end) = self.last_end {
174            self.link.sleep_until(end + self.turnaround).await;
175        }
176        if matches!(command, Command::Host(_)) {
177            self.discard_pending().await?;
178        }
179        let result = self.run(command).await;
180        self.answered = self.client.peer_params().is_some();
181        if result.is_err() {
182            self.client = Client::new(self.config.clone());
183            self.last_end = Some(self.link.now());
184        }
185        result
186    }
187
188    /// Discard input that arrived between transactions, before a host
189    /// command goes out: a stale NAK of the idle server (it NAKs once, a
190    /// server timeout after its last packet, and then stays silent; measured
191    /// on Saturnus and saturnng, real hardware unverified) that would
192    /// otherwise be read right after the `C`, inside the immediate-NAK
193    /// window of host commands. Nothing of the coming transaction can be in
194    /// it yet.
195    async fn discard_pending(&mut self) -> Result<()> {
196        let end = self.link.now() + PENDING_MAX;
197        loop {
198            let deadline = self.link.now() + PENDING_WAIT;
199            let got = self.link.read(Some(deadline)).await?;
200            if got.is_empty() || self.link.now() >= end {
201                return Ok(());
202            }
203        }
204    }
205
206    async fn run(&mut self, command: Command) -> Result<Transcript> {
207        let sending = matches!(command, Command::Send(_));
208        let command_text = match &command {
209            Command::Host(bytes) | Command::Get(bytes) => charset::decode(bytes),
210            _ => String::new(),
211        };
212        self.client
213            .start(self.link.now(), command)
214            .map_err(|e| match e {
215                StartError::TooLong { len, max } => Error::CommandTooLong {
216                    command: command_text,
217                    len,
218                    max,
219                },
220                StartError::Busy => Error::Reply("kermit client busy".into()),
221                other => Error::Reply(format!("kermit client: {other}")),
222            })?;
223
224        let limit = self
225            .stall_limit
226            .unwrap_or_else(|| stall_limit(&self.config));
227        let mut watchdog = Watchdog::new(self.link.now(), limit, limit);
228        let mut accepted = self.client.accepted();
229        let mut stalled = false;
230
231        let mut transcript = Transcript::default();
232        let mut current: Option<ReceivedFile> = None;
233        let mut outcome: Option<Result<()>> = None;
234        'run: loop {
235            let now = self.link.now();
236            while let Some(packet) = self.client.poll_output(now) {
237                match self.link.write(packet) {
238                    Ok(()) => {}
239                    // A re-ACK during the linger: the transaction is
240                    // complete, a failing link does not undo it.
241                    Err(_) if matches!(outcome, Some(Ok(()))) => break 'run,
242                    Err(e) => return Err(e.into()),
243                }
244            }
245            // Written before the events count: a failed write of the final
246            // ACK fails the transaction, a re-ACK's only ends the linger.
247            match self.link.flush().await {
248                Ok(()) => {}
249                Err(_) if matches!(outcome, Some(Ok(()))) => break 'run,
250                Err(e) => return Err(e.into()),
251            }
252            while let Some(event) = self.client.poll_event() {
253                self.link.emit(Progress::Kermit(event.clone()));
254                match event {
255                    Event::FileStart { name } if sending => {
256                        transcript.stored_names.push(charset::decode(&name));
257                    }
258                    Event::FileStart { name } => {
259                        current = Some(ReceivedFile {
260                            name: charset::decode(&name),
261                            data: Vec::new(),
262                        });
263                    }
264                    Event::Data(data) => {
265                        if let Some(file) = current.as_mut() {
266                            file.data.extend_from_slice(&data);
267                        }
268                    }
269                    Event::FileEnd { discarded } => {
270                        if let Some(file) = current.take()
271                            && !discarded
272                        {
273                            transcript.files.push(file);
274                        }
275                    }
276                    Event::ServerText(text) => transcript.text.extend_from_slice(&text),
277                    Event::Progress { .. } => {}
278                    Event::Done => {
279                        outcome = Some(Ok(()));
280                        // The final ACK is out (it is queued with Done):
281                        // the turnaround starts, the linger runs inside it.
282                        self.last_end = Some(now);
283                    }
284                    Event::Error(kermit_proto::Error::Remote(text)) => {
285                        outcome = Some(Err(Error::Remote(charset::decode(&text))));
286                    }
287                    Event::Error(kermit_proto::Error::Cancelled) if stalled => {
288                        outcome = Some(Err(Error::Stalled(limit)));
289                    }
290                    Event::Error(e) => outcome = Some(Err(Error::Kermit(e))),
291                    _ => {}
292                }
293            }
294            if outcome.is_none() && watchdog.expired(now) {
295                // The E packet goes out and Error(Cancelled) comes next.
296                stalled = true;
297                self.client.cancel(now);
298                continue;
299            }
300            let deadline = match (self.client.next_timeout(), &outcome) {
301                (None, Some(_)) => break,
302                (Some(t), _) => t,
303                (None, None) => now + IDLE_WAIT,
304            };
305            let deadline = match watchdog.deadline() {
306                Some(w) if outcome.is_none() => deadline.min(w),
307                _ => deadline,
308            };
309            let input = match self.link.read(Some(deadline.max(now + MIN_WAIT))).await {
310                Ok(input) => input,
311                // Lingering after Done: the transcript is complete, a
312                // failing link only ends the linger.
313                Err(_) if matches!(outcome, Some(Ok(()))) => break,
314                Err(e) => return Err(e.into()),
315            };
316            let now = self.link.now();
317            if !input.is_empty() {
318                self.client.handle_input(now, &input);
319            }
320            // Also after input: handle_input does not check the deadline, so
321            // a peer that keeps sending garbage (noise, wrong speed) would
322            // otherwise stall the transaction forever. A no-op until the
323            // deadline has passed.
324            self.client.handle_timeout(now);
325            if self.client.accepted() != accepted {
326                accepted = self.client.accepted();
327                watchdog.progress(now);
328            }
329        }
330        match outcome {
331            Some(Err(e)) => Err(e),
332            _ => Ok(transcript),
333        }
334    }
335}
336
337/// A Kermit connection to a calculator in server mode, over a blocking
338/// [`Transport`] with the system clock. For a link driven from outside (a
339/// browser), see [`machine::Machine`](crate::machine::Machine).
340#[cfg(not(target_arch = "wasm32"))]
341pub struct Session {
342    pub(crate) transport: Box<dyn Transport>,
343    pub(crate) core: KermitCore,
344}
345
346// The transport is a trait object without `Debug`.
347#[cfg(not(target_arch = "wasm32"))]
348impl std::fmt::Debug for Session {
349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350        f.debug_struct("Session")
351            .field("core", &self.core)
352            .finish_non_exhaustive()
353    }
354}
355
356#[cfg(not(target_arch = "wasm32"))]
357impl Session {
358    /// Wrap `transport`, discarding input for `options.drain` first.
359    pub fn new(mut transport: Box<dyn Transport>, options: Options) -> Result<Self> {
360        let link = Link::new(Instant::now());
361        link::drive(
362            transport.as_mut(),
363            &link,
364            link.drain(options.drain),
365            &mut |_| {},
366        )?;
367        Ok(Session {
368            transport,
369            core: KermitCore::new(link, &options),
370        })
371    }
372
373    /// Open `addr` (see [`transport::open`]) with default [`Options`].
374    pub fn open(addr: &str) -> Result<Self> {
375        Session::new(transport::open(addr)?, Options::default())
376    }
377
378    /// Give the link back, e.g. for an XModem transfer after
379    /// [`Calculator::prepare_for_xmodem`](crate::Calculator::prepare_for_xmodem)
380    /// ended server mode.
381    pub fn into_transport(self) -> Box<dyn Transport> {
382        self.transport
383    }
384
385    /// The Kermit configuration in use.
386    pub fn config(&self) -> &Config {
387        self.core.config()
388    }
389
390    /// Use `config` from the next transaction on.
391    pub fn set_config(&mut self, config: Config) {
392        self.core.set_config(config);
393    }
394
395    /// Whether the server sent its parameters (its `S`, or the ACK to an
396    /// `I` or `S`) in the last transaction, also when it failed later: for
397    /// a host command, whether the `C` was received and answered.
398    pub fn answered(&self) -> bool {
399        self.core.answered()
400    }
401
402    /// Run one transaction to completion.
403    pub fn transact(&mut self, command: Command) -> Result<Transcript> {
404        self.transact_with(command, &mut |_| {})
405    }
406
407    /// Run one transaction, passing every event to `progress`.
408    pub fn transact_with(
409        &mut self,
410        command: Command,
411        progress: &mut dyn FnMut(&Event),
412    ) -> Result<Transcript> {
413        let link = self.core.link.clone();
414        link::drive(
415            self.transport.as_mut(),
416            &link,
417            self.core.transact(command),
418            &mut |p| {
419                if let Progress::Kermit(event) = p {
420                    progress(event);
421                }
422            },
423        )
424    }
425}
426
427#[cfg(test)]
428#[allow(clippy::unwrap_used, clippy::expect_used)]
429mod tests {
430    use super::*;
431    use crate::transport::MemoryTransport;
432    use kermit_proto::OutgoingFile;
433    use kermit_proto::codec::{BlockCheck, Deframer, Framing, Packet, parse_frame};
434    use std::sync::{Arc, Mutex};
435
436    const SX_HOST: &str = include_str!("../../kermit-proto/traces/48sx-host.trace");
437    const SX_GET: &str = include_str!("../../kermit-proto/traces/48sx-get.trace");
438    const SX_GET_MISSING: &str = include_str!("../../kermit-proto/traces/48sx-get-missing.trace");
439    const SX_SEND: &str = include_str!("../../kermit-proto/traces/48sx-send.trace");
440    const GX_GET_BINARY: &str = include_str!("../../kermit-proto/traces/48gx-get-binary.trace");
441
442    /// No pauses: zero drain and turnaround, and no linger after a receive
443    /// (the in-memory peers never repeat a B).
444    fn options() -> Options {
445        let mut kermit = Options::default().kermit;
446        kermit.linger = Duration::ZERO;
447        Options {
448            kermit,
449            drain: Duration::ZERO,
450            turnaround: Duration::ZERO,
451        }
452    }
453
454    fn session(trace: &str, options: Options) -> Session {
455        Session::new(
456            Box::new(MemoryTransport::from_trace(trace).unwrap()),
457            options,
458        )
459        .unwrap()
460    }
461
462    fn host_reply() -> Vec<u8> {
463        let mut text = b"1:".to_vec();
464        text.extend_from_slice(&[b' '; 20]);
465        text.extend_from_slice(b"42\r\n");
466        text
467    }
468
469    #[test]
470    fn host_command() {
471        let mut s = session(SX_HOST, options());
472        let mut events = 0;
473        let t = s
474            .transact_with(Command::Host(b"6 7 *".to_vec()), &mut |_| events += 1)
475            .unwrap();
476        assert_eq!(t.text, host_reply());
477        assert!(t.files.is_empty() && t.stored_names.is_empty());
478        assert_eq!(events, 2);
479    }
480
481    #[test]
482    fn get_missing_is_remote_error() {
483        let mut s = session(SX_GET_MISSING, options());
484        let err = s.transact(Command::Get(b"NOSUCH".to_vec())).unwrap_err();
485        assert!(
486            matches!(&err, Error::Remote(m) if m == "Undefined Name"),
487            "{err:?}"
488        );
489    }
490
491    #[test]
492    fn get_ascii() {
493        let mut s = session(SX_GET, options());
494        let t = s.transact(Command::Get(b"ALLB".to_vec())).unwrap();
495        assert_eq!(t.files.len(), 1);
496        assert_eq!(t.files[0].name, "ALLB");
497        assert!(t.files[0].data.starts_with(b"%%HP: T(1)A(D)F(.);\r\n"));
498    }
499
500    #[test]
501    fn get_binary() {
502        let mut s = session(GX_GET_BINARY, options());
503        let t = s.transact(Command::Get(b"ALLB".to_vec())).unwrap();
504        assert_eq!(t.files.len(), 1);
505        assert!(t.files[0].data.starts_with(b"HPHP48-R"));
506    }
507
508    #[test]
509    fn send_reports_stored_name() {
510        let mut s = session(SX_SEND, options());
511        let file = OutgoingFile {
512            name: b"ALLB".to_vec(),
513            data: (0..=255).collect(),
514        };
515        let t = s.transact(Command::Send(vec![file])).unwrap();
516        assert_eq!(t.stored_names, vec!["ALLB".to_string()]);
517        assert!(t.files.is_empty());
518    }
519
520    #[test]
521    fn turnaround_pause_between_transactions() {
522        let trace = format!("{SX_HOST}\n{SX_HOST}");
523        let options = Options {
524            turnaround: Duration::from_millis(50),
525            ..options()
526        };
527        let mut s = session(&trace, options);
528        s.transact(Command::Host(b"6 7 *".to_vec())).unwrap();
529        let start = Instant::now();
530        s.transact(Command::Host(b"6 7 *".to_vec())).unwrap();
531        assert!(start.elapsed() >= Duration::from_millis(50));
532    }
533
534    #[test]
535    fn stale_nak_drained() {
536        let trace = format!("< \\x01# N3\\r\n{SX_HOST}");
537        let mut s = session(
538            &trace,
539            Options {
540                drain: Duration::from_millis(50),
541                turnaround: Duration::ZERO,
542                ..options()
543            },
544        );
545        let t = s.transact(Command::Host(b"6 7 *".to_vec())).unwrap();
546        assert_eq!(t.text, host_reply());
547    }
548
549    /// PR #26 review, #1: input that arrived between transactions (here a
550    /// stray packet after the first reply; on the link, the idle server's
551    /// NAKs) is discarded before a host command goes out, so it is not read
552    /// as the first answer to the `C`.
553    #[test]
554    fn input_between_host_commands_is_discarded() {
555        use kermit_proto::codec::{Framing, Packet};
556        let line = |dir: &str, kind: u8, data: &[u8]| {
557            let p = Packet::new(0, kind, data.to_vec())
558                .encode(kermit_proto::BlockCheck::Type1, &Framing::default())
559                .unwrap();
560            format!("{dir} {}\n", kermit_proto::trace::escape(&p))
561        };
562        let trace = line(">", b'C', b"A")
563            + &line("<", b'Y', b"a")
564            + &line("<", b'Y', b"stale")
565            + &line(">", b'C', b"B")
566            + &line("<", b'Y', b"b");
567        let mut s = session(&trace, options());
568        assert_eq!(s.transact(Command::Host(b"A".to_vec())).unwrap().text, b"a");
569        assert_eq!(s.transact(Command::Host(b"B".to_vec())).unwrap().text, b"b");
570    }
571
572    #[test]
573    fn error_resets_client() {
574        let mut s = session(SX_HOST, options());
575        let err = s.transact(Command::Host(b"6 7 +".to_vec())).unwrap_err();
576        assert!(matches!(err, Error::Io(_)), "{err:?}");
577        // The mismatching write was not consumed, so a clean client can
578        // replay the trace from the start.
579        let t = s.transact(Command::Host(b"6 7 *".to_vec())).unwrap();
580        assert_eq!(t.text, host_reply());
581    }
582
583    #[test]
584    fn command_too_long() {
585        let mut s = session("", options());
586        let err = s.transact(Command::Host(vec![b'1'; 200])).unwrap_err();
587        assert!(
588            matches!(&err, Error::CommandTooLong { command, len, .. } if command.len() == 200 && *len == 200),
589            "{err:?}"
590        );
591    }
592
593    /// A Kermit server that sends file `X` (two D packets) in reply to R and
594    /// drops the first transmission of D seq 2.
595    fn lossy_server(naks: Arc<Mutex<Vec<u8>>>) -> impl FnMut(&[u8]) -> Vec<Vec<u8>> + Send {
596        let check = BlockCheck::Type1;
597        let mut deframer = Deframer::new();
598        let mut dropped = false;
599        move |bytes| {
600            let wire = |seq: u8, kind: u8, data: &[u8]| {
601                Packet::new(seq, kind, data.to_vec())
602                    .encode(check, &Framing::default())
603                    .unwrap()
604            };
605            deframer.push(bytes);
606            let mut replies = Vec::new();
607            while let Some(frame) = deframer.next_frame() {
608                let p = parse_frame(&frame, check).unwrap();
609                match (p.kind, p.seq) {
610                    (b'R', _) => replies.push(wire(0, b'S', b"~* @-#Y1 ")),
611                    (b'Y', 0) => replies.push(wire(1, b'F', b"X")),
612                    (b'Y', 1) if !dropped => dropped = true,
613                    (b'Y', 1) => {}
614                    (b'N', 2) => {
615                        naks.lock().unwrap().push(2);
616                        replies.push(wire(2, b'D', b"hello "));
617                    }
618                    (b'Y', 2) => replies.push(wire(3, b'D', b"world")),
619                    (b'Y', 3) => replies.push(wire(4, b'Z', b"")),
620                    (b'Y', 4) => replies.push(wire(5, b'B', b"")),
621                    (b'Y', 5) => {}
622                    (kind, seq) => panic!("unexpected packet {} seq {seq}", char::from(kind)),
623                }
624            }
625            replies
626        }
627    }
628
629    /// A server that sends file `X` ("hi") in reply to R, and a link that
630    /// fails every read once our ACK to its B is out.
631    struct LostAfterFinalAck {
632        inner: MemoryTransport,
633        acked: Arc<Mutex<bool>>,
634    }
635
636    impl Transport for LostAfterFinalAck {
637        fn write_packet(&mut self, packet: &[u8]) -> std::io::Result<()> {
638            self.inner.write_packet(packet)
639        }
640
641        fn read(&mut self, buf: &mut [u8], timeout: Duration) -> std::io::Result<usize> {
642            if *self.acked.lock().unwrap() {
643                return Err(std::io::Error::other("link lost"));
644            }
645            self.inner.read(buf, timeout)
646        }
647    }
648
649    #[test]
650    fn link_lost_while_lingering_keeps_the_transcript() {
651        let acked = Arc::new(Mutex::new(false));
652        let flag = Arc::clone(&acked);
653        let check = BlockCheck::Type1;
654        let mut deframer = Deframer::new();
655        let server = move |bytes: &[u8]| {
656            let wire = |seq: u8, kind: u8, data: &[u8]| {
657                Packet::new(seq, kind, data.to_vec())
658                    .encode(check, &Framing::default())
659                    .unwrap()
660            };
661            deframer.push(bytes);
662            let mut replies = Vec::new();
663            while let Some(frame) = deframer.next_frame() {
664                let p = parse_frame(&frame, check).unwrap();
665                match (p.kind, p.seq) {
666                    (b'R', _) => replies.push(wire(0, b'S', b"~* @-#Y1 ")),
667                    (b'Y', 0) => replies.push(wire(1, b'F', b"X")),
668                    (b'Y', 1) => replies.push(wire(2, b'D', b"hi")),
669                    (b'Y', 2) => replies.push(wire(3, b'Z', b"")),
670                    (b'Y', 3) => replies.push(wire(4, b'B', b"")),
671                    (b'Y', 4) => *flag.lock().unwrap() = true,
672                    (kind, seq) => panic!("unexpected packet {} seq {seq}", char::from(kind)),
673                }
674            }
675            replies
676        };
677        let mut kermit = Options::default().kermit;
678        kermit.linger = Duration::from_secs(5);
679        let options = Options {
680            kermit,
681            ..options()
682        };
683        let transport = LostAfterFinalAck {
684            inner: MemoryTransport::new(server),
685            acked: Arc::clone(&acked),
686        };
687        let mut s = Session::new(Box::new(transport), options).unwrap();
688        let start = Instant::now();
689        let t = s.transact(Command::Get(b"X".to_vec())).unwrap();
690        assert!(*acked.lock().unwrap());
691        assert!(
692            start.elapsed() < Duration::from_secs(5),
693            "linger ended early"
694        );
695        assert_eq!(
696            t.files,
697            vec![ReceivedFile {
698                name: "X".into(),
699                data: b"hi".to_vec()
700            }]
701        );
702    }
703
704    /// A link that fails every write once the server's B is out: the ACK
705    /// to the B, which comes with Done.
706    struct FinalAckLost {
707        inner: MemoryTransport,
708        b_sent: Arc<Mutex<bool>>,
709    }
710
711    impl Transport for FinalAckLost {
712        fn write_packet(&mut self, packet: &[u8]) -> std::io::Result<()> {
713            if *self.b_sent.lock().unwrap() {
714                return Err(std::io::Error::other("link lost"));
715            }
716            self.inner.write_packet(packet)
717        }
718
719        fn read(&mut self, buf: &mut [u8], timeout: Duration) -> std::io::Result<usize> {
720            self.inner.read(buf, timeout)
721        }
722    }
723
724    /// The final ACK's write fails the transaction: it is written before
725    /// Done counts, as when the loop wrote to the transport directly.
726    #[test]
727    fn final_ack_lost_fails_the_transaction() {
728        let b_sent = Arc::new(Mutex::new(false));
729        let flag = Arc::clone(&b_sent);
730        let check = BlockCheck::Type1;
731        let mut deframer = Deframer::new();
732        let server = move |bytes: &[u8]| {
733            let wire = |seq: u8, kind: u8, data: &[u8]| {
734                Packet::new(seq, kind, data.to_vec())
735                    .encode(check, &Framing::default())
736                    .unwrap()
737            };
738            deframer.push(bytes);
739            let mut replies = Vec::new();
740            while let Some(frame) = deframer.next_frame() {
741                let p = parse_frame(&frame, check).unwrap();
742                match (p.kind, p.seq) {
743                    (b'R', _) => replies.push(wire(0, b'S', b"~* @-#Y1 ")),
744                    (b'Y', 0) => replies.push(wire(1, b'F', b"X")),
745                    (b'Y', 1) => replies.push(wire(2, b'D', b"hi")),
746                    (b'Y', 2) => replies.push(wire(3, b'Z', b"")),
747                    (b'Y', 3) => {
748                        *flag.lock().unwrap() = true;
749                        replies.push(wire(4, b'B', b""));
750                    }
751                    (kind, seq) => panic!("unexpected packet {} seq {seq}", char::from(kind)),
752                }
753            }
754            replies
755        };
756        let transport = FinalAckLost {
757            inner: MemoryTransport::new(server),
758            b_sent,
759        };
760        let mut s = Session::new(Box::new(transport), options()).unwrap();
761        let err = s.transact(Command::Get(b"X".to_vec())).unwrap_err();
762        assert!(matches!(err, Error::Io(_)), "{err:?}");
763    }
764
765    /// Reads that never stop delivering noise: no SOH, so no frame ever
766    /// completes. Fails the read after `MAX_READS` so a regression cannot
767    /// hang the test.
768    struct NoisyLine {
769        reads: usize,
770    }
771
772    const MAX_READS: usize = 5_000;
773
774    impl Transport for NoisyLine {
775        fn write_packet(&mut self, _packet: &[u8]) -> std::io::Result<()> {
776            Ok(())
777        }
778
779        fn read(&mut self, buf: &mut [u8], _timeout: Duration) -> std::io::Result<usize> {
780            self.reads += 1;
781            if self.reads > MAX_READS {
782                return Err(std::io::Error::other("read cap hit: timeout never fired"));
783            }
784            std::thread::sleep(Duration::from_millis(1));
785            let noise = b"zq~";
786            buf[..noise.len()].copy_from_slice(noise);
787            Ok(noise.len())
788        }
789    }
790
791    #[test]
792    fn continuous_garbage_still_times_out() {
793        let mut kermit = Options::default().kermit;
794        kermit.timeout = Duration::from_millis(20);
795        kermit.retries = 2;
796        let options = Options {
797            kermit,
798            drain: Duration::ZERO,
799            turnaround: Duration::ZERO,
800        };
801        let mut s = Session {
802            transport: Box::new(NoisyLine { reads: 0 }),
803            core: KermitCore::new(Link::new(Instant::now()), &options),
804        };
805        let start = Instant::now();
806        let err = s.transact(Command::Host(b"6 7 *".to_vec())).unwrap_err();
807        assert!(
808            matches!(err, Error::Kermit(kermit_proto::Error::Timeout)),
809            "{err:?}"
810        );
811        assert!(
812            start.elapsed() < Duration::from_secs(2),
813            "{:?}",
814            start.elapsed()
815        );
816    }
817
818    /// A Kermit server that sends file `X` in reply to R, then answers
819    /// every ACK of its F with the F again, forever: the previous packet
820    /// replayed. Logs the E packets it gets.
821    fn replaying_server(errors: Arc<Mutex<Vec<Vec<u8>>>>) -> impl FnMut(&[u8]) -> Vec<Vec<u8>> {
822        let check = BlockCheck::Type1;
823        let mut deframer = Deframer::new();
824        move |bytes| {
825            let wire = |seq: u8, kind: u8, data: &[u8]| {
826                Packet::new(seq, kind, data.to_vec())
827                    .encode(check, &Framing::default())
828                    .unwrap()
829            };
830            deframer.push(bytes);
831            let mut replies = Vec::new();
832            while let Some(frame) = deframer.next_frame() {
833                let p = parse_frame(&frame, check).unwrap();
834                match (p.kind, p.seq) {
835                    (b'R', _) => replies.push(wire(0, b'S', b"~* @-#Y1 ")),
836                    (b'Y', 0 | 1) => replies.push(wire(1, b'F', b"X")),
837                    (b'E', _) => errors.lock().unwrap().push(p.data.clone()),
838                    (kind, seq) => panic!("unexpected packet {} seq {seq}", char::from(kind)),
839                }
840            }
841            replies
842        }
843    }
844
845    fn session_with(
846        transport: Box<dyn Transport>,
847        kermit: Config,
848        stall: Option<Duration>,
849    ) -> Session {
850        let options = Options {
851            kermit,
852            drain: Duration::ZERO,
853            turnaround: Duration::ZERO,
854        };
855        let mut core = KermitCore::new(Link::new(Instant::now()), &options);
856        core.stall_limit = stall;
857        Session { transport, core }
858    }
859
860    /// Iteration 48: a peer that replays its last packet forever, to a
861    /// client whose retries never run out, is cancelled by the watchdog
862    /// once no new packet came for the stall limit, with an E packet.
863    #[test]
864    fn a_replaying_peer_is_cancelled_by_the_watchdog() {
865        let errors = Arc::new(Mutex::new(Vec::new()));
866        let transport = MemoryTransport::new(replaying_server(Arc::clone(&errors)));
867        let mut kermit = options().kermit;
868        kermit.timeout = Duration::from_secs(2);
869        kermit.retries = u32::MAX;
870        let limit = Duration::from_millis(100);
871        let mut s = session_with(Box::new(transport), kermit, Some(limit));
872        let start = Instant::now();
873        let err = s.transact(Command::Get(b"X".to_vec())).unwrap_err();
874        let elapsed = start.elapsed();
875        assert!(matches!(err, Error::Stalled(l) if l == limit), "{err:?}");
876        assert!(err.to_string().contains("no progress for 0.1 s"), "{err}");
877        assert!(
878            elapsed >= limit && elapsed < Duration::from_secs(1),
879            "{elapsed:?}"
880        );
881        assert_eq!(*errors.lock().unwrap(), vec![b"Cancelled".to_vec()]);
882    }
883
884    /// Iteration 48: noise that never forms a packet, to a client whose
885    /// retries never run out, is cancelled by the watchdog.
886    #[test]
887    fn a_babbling_line_is_cancelled_by_the_watchdog() {
888        let mut kermit = options().kermit;
889        kermit.timeout = Duration::from_millis(20);
890        kermit.retries = u32::MAX;
891        let limit = Duration::from_millis(150);
892        let mut s = session_with(Box::new(NoisyLine { reads: 0 }), kermit, Some(limit));
893        let start = Instant::now();
894        let err = s.transact(Command::Host(b"6 7 *".to_vec())).unwrap_err();
895        let elapsed = start.elapsed();
896        assert!(matches!(err, Error::Stalled(_)), "{err:?}");
897        assert!(
898            elapsed >= limit && elapsed < Duration::from_secs(2),
899            "{elapsed:?}"
900        );
901    }
902
903    /// Iteration 48: with the limit from the configuration, a replaying peer
904    /// ends within it (the client's retries end it first: a repeated packet
905    /// counts as a retry).
906    #[test]
907    fn a_replaying_peer_ends_within_the_stall_limit() {
908        let errors = Arc::new(Mutex::new(Vec::new()));
909        let transport = MemoryTransport::new(replaying_server(Arc::clone(&errors)));
910        let mut kermit = options().kermit;
911        kermit.timeout = Duration::from_millis(50);
912        kermit.retries = 3;
913        let limit = stall_limit(&kermit);
914        assert_eq!(limit, Duration::from_millis(1250));
915        let mut s = session_with(Box::new(transport), kermit, None);
916        let start = Instant::now();
917        let err = s.transact(Command::Get(b"X".to_vec())).unwrap_err();
918        assert!(
919            matches!(
920                err,
921                Error::Kermit(kermit_proto::Error::Timeout) | Error::Stalled(_)
922            ),
923            "{err:?}"
924        );
925        assert!(start.elapsed() < limit, "{:?}", start.elapsed());
926    }
927
928    /// The limit: one try more than the client's most for one packet, each
929    /// a timeout plus the packet pause, and the fixed slack; the first
930    /// packet's retries count when they are more.
931    #[test]
932    fn the_stall_limit_covers_every_retry() {
933        let mut c = Config::default();
934        assert_eq!(stall_limit(&c), Duration::from_secs(20 * 7 + 1));
935        c.first_packet_retries = Some(0);
936        assert_eq!(stall_limit(&c), Duration::from_secs(20 * 7 + 1));
937        c.first_packet_retries = Some(9);
938        assert_eq!(stall_limit(&c), Duration::from_secs(20 * 12 + 1));
939        c.packet_pause = Duration::from_secs(1);
940        assert_eq!(stall_limit(&c), Duration::from_secs(21 * 12 + 1));
941        c.retries = u32::MAX;
942        assert_eq!(
943            stall_limit(&c),
944            Duration::from_secs(21 * u64::from(u32::MAX) + 1)
945        );
946    }
947
948    #[test]
949    fn lost_packet_is_recovered() {
950        let naks = Arc::new(Mutex::new(Vec::new()));
951        let transport = MemoryTransport::new(lossy_server(Arc::clone(&naks)));
952        let mut kermit = options().kermit;
953        kermit.timeout = Duration::from_millis(100);
954        let options = Options {
955            kermit,
956            drain: Duration::ZERO,
957            turnaround: Duration::ZERO,
958        };
959        let mut s = Session::new(Box::new(transport), options).unwrap();
960        let start = Instant::now();
961        let t = s.transact(Command::Get(b"X".to_vec())).unwrap();
962        assert!(start.elapsed() < Duration::from_millis(800));
963        assert_eq!(
964            t.files,
965            vec![ReceivedFile {
966                name: "X".into(),
967                data: b"hello world".to_vec()
968            }]
969        );
970        assert_eq!(*naks.lock().unwrap(), vec![2]);
971    }
972}