1use 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
37const IDLE_WAIT: Duration = Duration::from_millis(100);
39const MIN_WAIT: Duration = Duration::from_millis(10);
41const PENDING_WAIT: Duration = Duration::from_millis(1);
45const PENDING_MAX: Duration = Duration::from_millis(50);
48
49pub(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
66const STALL_SLACK: Duration = Duration::from_secs(1);
71
72#[derive(Clone, Debug)]
74pub struct Options {
75 pub kermit: Config,
79 pub drain: Duration,
81 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#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct ReceivedFile {
105 pub name: String,
107 pub data: Vec<u8>,
109}
110
111#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct Transcript {
114 pub files: Vec<ReceivedFile>,
116 pub stored_names: Vec<String>,
118 pub text: Vec<u8>,
120}
121
122#[derive(Debug)]
125pub(crate) struct KermitCore {
126 pub(crate) link: Link,
127 client: Client,
128 config: Config,
129 turnaround: Duration,
130 last_end: Option<Instant>,
132 answered: bool,
134 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 pub(crate) fn ended_at(&mut self, now: Instant) {
168 self.last_end = Some(now);
169 }
170
171 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 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 Err(_) if matches!(outcome, Some(Ok(()))) => break 'run,
242 Err(e) => return Err(e.into()),
243 }
244 }
245 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 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 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 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 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#[cfg(not(target_arch = "wasm32"))]
341pub struct Session {
342 pub(crate) transport: Box<dyn Transport>,
343 pub(crate) core: KermitCore,
344}
345
346#[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 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 pub fn open(addr: &str) -> Result<Self> {
375 Session::new(transport::open(addr)?, Options::default())
376 }
377
378 pub fn into_transport(self) -> Box<dyn Transport> {
382 self.transport
383 }
384
385 pub fn config(&self) -> &Config {
387 self.core.config()
388 }
389
390 pub fn set_config(&mut self, config: Config) {
392 self.core.set_config(config);
393 }
394
395 pub fn answered(&self) -> bool {
399 self.core.answered()
400 }
401
402 pub fn transact(&mut self, command: Command) -> Result<Transcript> {
404 self.transact_with(command, &mut |_| {})
405 }
406
407 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 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 #[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 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 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 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 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 #[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 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 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 #[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 #[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 #[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 #[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}