summaryrefslogtreecommitdiffstats
path: root/src/sandbox/wire.rs
blob: ae89d6dbd67072e1125494cfeda976f2e8da9c82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use std::io::{self, BufRead, Write};

use serde::{Deserialize, Serialize};

pub(crate) const MAX_FRAME_BYTES: u32 = 2 * 1024 * 1024 * 1024;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub(crate) enum Frame {
    /// agent → hub, first frame on every connection: the outbound rendezvous.
    Hello { token: String, agent_id: String, profiles: Vec<String> },
    /// hub → agent: rendezvous accepted; `ttl_secs` arms the agent's watchdog.
    HelloAck { ttl_secs: u64 },
    /// hub → agent: run argv. `blob:<digest>` argv elements name blobs the
    /// agent must already have via `Put`; `env` is the hub's child environment.
    Run { req: u64, argv: Vec<String>, cwd: Option<String>, env: Vec<(String, String)> },
    /// agent → hub: a chunk of the running child's output, hex-encoded.
    Log { req: u64, stream: String, data: String },
    /// agent → hub: the child finished. `code` is None when it died by signal.
    Exit { req: u64, code: Option<i32> },
    /// hub → agent: stage this blob. The agent verifies `data` hashes to
    /// `digest` before writing.
    Put { req: u64, digest: String, data: String },
    /// hub → agent: pull this blob back out.
    Get { req: u64, digest: String },
    /// agent → hub: reply to `Get`.
    Blob { req: u64, data: String },
    /// agent → hub: generic success for `Put`/`Get`.
    Ok { req: u64 },
    /// agent → hub: generic failure.
    Err { req: u64, msg: String },
    /// hub → agent: keepalive; resets the agent's TTL watchdog.
    Ping {},
    /// hub → agent: tear down now. TTL is the guarantee, this is courtesy.
    Destroy {},
}

pub(crate) fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> {
    let body = serde_json::to_vec(f)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    if body.len() as u64 > MAX_FRAME_BYTES as u64 {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large"));
    }
    w.write_all(&(body.len() as u32).to_be_bytes())?;
    w.write_all(&body)?;
    w.flush()
}

pub(crate) fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> {
    let mut len = [0u8; 4];
    match r.read_exact(&mut len) {
        Ok(()) => {}
        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
        Err(e) => return Err(e),
    }
    let n = u32::from_be_bytes(len) as usize;
    if n as u32 > MAX_FRAME_BYTES {
        return Err(io::Error::new(io::ErrorKind::InvalidData, "frame too large"));
    }
    let mut body = vec![0u8; n];
    r.read_exact(&mut body)?;
    let f: Frame = serde_json::from_slice(&body)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    Ok(Some(f))
}

pub(crate) fn hex_bytes(b: &[u8]) -> String {
    hex::encode(b)
}

pub(crate) fn unhex(s: &str) -> io::Result<Vec<u8>> {
    hex::decode(s).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn frames_round_trip_through_a_byte_stream() {
        let mut buf = Vec::new();
        write_frame(&mut buf, &Frame::Hello { token: "t".into(), agent_id: "a".into(), profiles: vec!["p".into()] }).unwrap();
        write_frame(&mut buf, &Frame::Log { req: 7, stream: "stdout".into(), data: hex_bytes(b"hello") }).unwrap();
        write_frame(&mut buf, &Frame::Exit { req: 7, code: Some(0) }).unwrap();
        let mut cur = std::io::BufReader::new(std::io::Cursor::new(buf));
        match read_frame(&mut cur).unwrap().unwrap() {
            Frame::Hello { token, .. } => assert_eq!(token, "t"),
            other => panic!("{other:?}"),
        }
        match read_frame(&mut cur).unwrap().unwrap() {
            Frame::Log { req, data, .. } => {
                assert_eq!(req, 7);
                assert_eq!(unhex(&data).unwrap(), b"hello");
            }
            other => panic!("{other:?}"),
        }
        match read_frame(&mut cur).unwrap().unwrap() {
            Frame::Exit { req, code } => assert_eq!((req, code), (7, Some(0))),
            other => panic!("{other:?}"),
        }
        assert!(read_frame(&mut cur).unwrap().is_none(), "clean close reads as None");
    }

    #[test]
    fn a_truncated_frame_is_an_error_not_a_silent_none() {
        let mut buf = Vec::new();
        write_frame(&mut buf, &Frame::Ping {}).unwrap();
        buf.truncate(3);
        let mut cur = std::io::BufReader::new(std::io::Cursor::new(buf));
        assert!(read_frame(&mut cur).is_err() || read_frame(&mut cur).unwrap().is_none());
    }
}