Skip to main content

dvm_api/
sandbox_input.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{ByteChunk, FrameError, RunOutput, decode_frame, encode_frame};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
6#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
7#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
8pub struct SandboxInput {
9    pub offset: u64,
10    #[serde(default)]
11    pub end: bool,
12}
13
14impl SandboxInput {
15    pub const MAX_CHUNK_BYTES: usize = 64 * 1024;
16}
17
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
19#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
20#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
21pub struct SandboxInputState {
22    pub length: u64,
23    pub ended: bool,
24}
25
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct OutputAfter {
28    pub output: RunOutput,
29    pub more: bool,
30    pub cut: bool,
31}
32
33#[derive(Serialize, Deserialize)]
34#[serde(deny_unknown_fields)]
35struct OutputAfterHeader {
36    stdout: u64,
37    stderr: u64,
38    more: bool,
39    cut: bool,
40}
41
42impl OutputAfter {
43    pub fn to_frame(&self) -> Vec<u8> {
44        let (stdout, stderr) = (self.output.stdout.bytes(), self.output.stderr.bytes());
45        let header = OutputAfterHeader {
46            stdout: stdout.len() as u64,
47            stderr: stderr.len() as u64,
48            more: self.more,
49            cut: self.cut,
50        };
51        encode_frame(&header, &[stdout, stderr].concat())
52    }
53
54    pub fn from_frame(frame: &[u8]) -> Result<Self, FrameError> {
55        let frame = decode_frame::<OutputAfterHeader>(frame)?;
56        let header = frame.header;
57        let mut stdout = frame.payload;
58        if header.stdout.checked_add(header.stderr) != Some(stdout.len() as u64) {
59            return Err(FrameError::BadHeader(format!(
60                "{} and {} bytes of output in a frame of {}",
61                header.stdout,
62                header.stderr,
63                stdout.len()
64            )));
65        }
66        let stderr = stdout.split_off(header.stdout as usize);
67        Ok(Self {
68            output: RunOutput {
69                stdout: ByteChunk::new(stdout),
70                stderr: ByteChunk::new(stderr),
71            },
72            more: header.more,
73            cut: header.cut,
74        })
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn input_is_a_query_and_output_a_frame_of_raw_bytes() {
84        let input: SandboxInput = serde_json::from_str(r#"{"offset":7}"#).unwrap();
85        assert_eq!(
86            input,
87            SandboxInput {
88                offset: 7,
89                end: false
90            }
91        );
92        let output = OutputAfter {
93            output: RunOutput {
94                stdout: ByteChunk::new(vec![0, 255]),
95                stderr: ByteChunk::new(b"err".to_vec()),
96            },
97            more: false,
98            cut: true,
99        };
100        let frame = output.to_frame();
101        assert_eq!(
102            frame,
103            b"{\"stdout\":2,\"stderr\":3,\"more\":false,\"cut\":true,\"bytes\":5}\n\x00\xfferr"
104        );
105        assert_eq!(OutputAfter::from_frame(&frame).unwrap(), output);
106        let short = b"{\"stdout\":9,\"stderr\":0,\"more\":true,\"cut\":false,\"bytes\":2}\nhi";
107        assert!(matches!(
108            OutputAfter::from_frame(short),
109            Err(FrameError::BadHeader(_))
110        ));
111    }
112}