Skip to main content

dvm_api/
sandbox_input.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{ByteChunk, RunOutput};
4
5/// Appends bytes to `POST /api/sandboxes/{id}/input`.
6#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
7#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
8#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
9pub struct SandboxInput {
10    pub offset: u64,
11    pub chunk: ByteChunk,
12    /// Closes stdin after the chunk; further input is refused.
13    pub end: bool,
14}
15
16impl SandboxInput {
17    /// Maximum decoded bytes in one input request.
18    pub const MAX_CHUNK_BYTES: usize = 64 * 1024;
19}
20
21/// The input accepted into the runner connection, which may still be in flight.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
23#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
24#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
25pub struct SandboxInputState {
26    pub length: u64,
27    pub ended: bool,
28}
29
30/// Output after the stdout cursor `offset` and optional `stderr_offset`.
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
33#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
34pub struct OutputAfter {
35    #[serde(flatten)]
36    pub output: RunOutput,
37    /// Whether the run can still write output.
38    pub more: bool,
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn input_and_incremental_output_round_trip_as_bytes() {
47        let input = SandboxInput {
48            offset: u64::MAX,
49            chunk: ByteChunk::new(vec![0, 255]),
50            end: true,
51        };
52        let encoded = serde_json::to_string(&input).unwrap();
53        assert!(encoded.contains("AP8="));
54        assert_eq!(
55            serde_json::from_str::<SandboxInput>(&encoded).unwrap(),
56            input
57        );
58        let state = SandboxInputState {
59            length: 2,
60            ended: true,
61        };
62        assert_eq!(
63            serde_json::from_str::<SandboxInputState>(&serde_json::to_string(&state).unwrap())
64                .unwrap(),
65            state
66        );
67        let output = OutputAfter {
68            output: RunOutput {
69                stdout: input.chunk,
70                stderr: ByteChunk::default(),
71            },
72            more: false,
73        };
74        let encoded = serde_json::to_string(&output).unwrap();
75        assert_eq!(encoded, r#"{"stdout":"AP8=","stderr":"","more":false}"#);
76        assert_eq!(
77            serde_json::from_str::<OutputAfter>(&encoded).unwrap(),
78            output
79        );
80    }
81}