Skip to main content

record/
record.rs

1//! Record a trace against a live calculator (or emulator) over TCP.
2//!
3//! Usage: `record ADDR COMMAND [ARGS]`, e.g. `record localhost:4848 host "6 7 *"`.
4//! Commands: `info`, `host TEXT`, `dir`, `get NAME`, `send NAME FILE`, `finish`,
5//! `logout`. `host` TEXT takes the trace escapes (`\x8d` for a byte outside
6//! ASCII). The trace goes to stdout, events to stderr.
7
8use std::io::{ErrorKind, Read, Write};
9use std::net::TcpStream;
10use std::time::{Duration, Instant};
11
12use kermit_proto::trace::{escape, unescape};
13use kermit_proto::{Client, Command, Config, Event, OutgoingFile};
14
15const USAGE: &str = "usage: record ADDR info|host TEXT|dir|get NAME|send NAME FILE|finish|logout";
16
17fn parse_command(args: &[String]) -> Result<Command, Box<dyn std::error::Error>> {
18    let rest = args.get(1..).unwrap_or_default();
19    let cmd = match (args.first().map(String::as_str), rest) {
20        (Some("info"), []) => Command::Info,
21        (Some("host"), [_, ..]) => Command::Host(unescape(&rest.join(" "))?),
22        (Some("dir"), []) => Command::Directory,
23        (Some("get"), [name]) => Command::Get(name.as_bytes().to_vec()),
24        (Some("send"), [name, file]) => Command::Send(vec![OutgoingFile {
25            name: name.as_bytes().to_vec(),
26            data: std::fs::read(file)?,
27        }]),
28        (Some("finish"), []) => Command::Finish,
29        (Some("logout"), []) => Command::Logout,
30        _ => return Err(USAGE.into()),
31    };
32    Ok(cmd)
33}
34
35fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let args: Vec<String> = std::env::args().skip(1).collect();
37    let (addr, cmd_args) = match args.split_first() {
38        Some((addr, rest)) if !rest.is_empty() => (addr, rest),
39        _ => return Err(USAGE.into()),
40    };
41    let command = parse_command(cmd_args)?;
42    println!("# record {}", cmd_args.join(" "));
43
44    let mut stream = TcpStream::connect(addr)?;
45    let mut buf = [0u8; 1024];
46
47    // Drain stale input (the idle server's periodic NAKs) for 500 ms.
48    let drain_end = Instant::now() + Duration::from_millis(500);
49    loop {
50        let left = drain_end.saturating_duration_since(Instant::now());
51        if left.is_zero() {
52            break;
53        }
54        stream.set_read_timeout(Some(left.max(Duration::from_millis(1))))?;
55        match stream.read(&mut buf) {
56            Ok(0) => return Err("connection closed".into()),
57            Ok(n) => println!("# stale: {}", escape(&buf[..n])),
58            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => break,
59            Err(e) => return Err(e.into()),
60        }
61    }
62
63    let mut client = Client::new(Config::default());
64    client.start(Instant::now(), command)?;
65    let mut outcome: Option<bool> = None;
66    loop {
67        let now = Instant::now();
68        while let Some(bytes) = client.poll_output(now) {
69            stream.write_all(&bytes)?;
70            println!("> {}", escape(&bytes));
71        }
72        while let Some(event) = client.poll_event() {
73            eprintln!("{event:?}");
74            match event {
75                Event::Done => outcome = Some(true),
76                Event::Error(_) => outcome = Some(false),
77                _ => {}
78            }
79        }
80        let wait = match (client.next_timeout(), outcome) {
81            (None, Some(_)) => break,
82            (Some(t), _) => t.saturating_duration_since(now),
83            (None, None) => Duration::from_millis(100),
84        };
85        stream.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
86        match stream.read(&mut buf) {
87            Ok(0) => return Err("connection closed".into()),
88            Ok(n) => {
89                println!("< {}", escape(&buf[..n]));
90                client.handle_input(Instant::now(), &buf[..n]);
91            }
92            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
93                client.handle_timeout(Instant::now());
94            }
95            Err(e) => return Err(e.into()),
96        }
97    }
98    std::io::stdout().flush()?;
99    if outcome == Some(true) {
100        Ok(())
101    } else {
102        std::process::exit(1);
103    }
104}