use serde::de::DeserializeOwned;
use serde::ser::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use crate::mxc_common::mxc_error::ApiFailure;
use crate::wslc_common::process_env::EnvScope;
pub const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
pub const MAX_EXEC_ID_BYTES: usize = 128;
pub const PROTOCOL_VERSION: u32 = 13;
pub const MAX_STDIN_CHUNK_BYTES: usize = 64 * 1024;
fn deserialize_exec_id<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
if value.is_empty() {
return Err(<D::Error as serde::de::Error>::custom(
"exec identifier must not be empty",
));
}
if value.len() > MAX_EXEC_ID_BYTES {
return Err(<D::Error as serde::de::Error>::custom(format!(
"exec identifier exceeds {MAX_EXEC_ID_BYTES} bytes"
)));
}
Ok(value)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VolumeMount {
pub host: String,
pub container: String,
pub read_only: bool,
}
pub use crate::wslc_common::policy::NetworkMode;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortMapping {
pub windows_port: u16,
pub container_port: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ProvisionSessionConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu_count: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memory_mb: Option<u64>,
#[serde(default)]
pub gpu: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeprovisionSessionConfig {
#[serde(rename = "session_id")]
pub session_ref: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProvisionConfig {
pub image: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_tar_path: Option<String>,
#[serde(default)]
pub volumes: Vec<VolumeMount>,
#[serde(default)]
pub network: NetworkMode,
#[serde(default)]
pub port_mappings: Vec<PortMapping>,
#[serde(
rename = "session_id",
default,
skip_serializing_if = "Option::is_none"
)]
pub session_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub network_proxy: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StartConfig {
pub sandbox_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecConfig {
#[serde(deserialize_with = "deserialize_exec_id")]
pub exec_id: String,
#[serde(deserialize_with = "deserialize_exec_id")]
pub run_token: String,
pub sandbox_id: String,
pub script_code: String,
#[serde(default)]
pub working_directory: String,
#[serde(default)]
pub env: Vec<(String, String)>,
#[serde(default)]
pub env_scope: EnvScope,
#[serde(default)]
pub timeout_ms: u32,
#[serde(default)]
pub stdin: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub network_proxy: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StopConfig {
pub sandbox_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeprovisionConfig {
pub sandbox_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CancelExecConfig {
#[serde(deserialize_with = "deserialize_exec_id")]
pub exec_id: String,
#[serde(deserialize_with = "deserialize_exec_id")]
pub run_token: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecStdinConfig {
#[serde(deserialize_with = "deserialize_exec_id")]
pub exec_id: String,
#[serde(deserialize_with = "deserialize_exec_id")]
pub run_token: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecTerminal {
Exited(i32),
TimedOut,
Cancelled,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum DaemonRequest {
ProvisionSession(ProvisionSessionConfig),
DeprovisionSession(DeprovisionSessionConfig),
Provision(ProvisionConfig),
Start(StartConfig),
Exec(ExecConfig),
CancelExec(CancelExecConfig),
ExecStdin(ExecStdinConfig),
Stop(StopConfig),
Deprovision(DeprovisionConfig),
Ping,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum DaemonResponse {
SessionProvisioned {
#[serde(rename = "session_id")]
session_ref: String,
},
Provisioned { sandbox_id: String },
Ok,
Pong,
Err {
kind: ErrKind,
message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
api_failure: Option<DaemonApiFailure>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrKind {
NotProvisioned,
NotStarted,
Busy,
NotReady,
Protocol,
Unavailable,
Rejected,
Backend,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaemonApiFailure {
pub operation: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub native_code: Option<String>,
}
impl From<&ApiFailure> for DaemonApiFailure {
fn from(failure: &ApiFailure) -> Self {
Self {
operation: failure.operation.clone(),
native_code: failure.native_code.clone(),
}
}
}
impl From<DaemonApiFailure> for ApiFailure {
fn from(failure: DaemonApiFailure) -> Self {
Self {
operation: failure.operation,
native_code: failure.native_code,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StreamFrame {
Stdin {
#[serde(with = "base64_bytes")]
data: Vec<u8>,
},
Stdout {
#[serde(with = "base64_bytes")]
data: Vec<u8>,
},
Stderr {
#[serde(with = "base64_bytes")]
data: Vec<u8>,
},
Exit { code: i32 },
TimedOut,
Cancelled,
Truncated,
Error {
message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
api_failure: Option<DaemonApiFailure>,
},
}
mod base64_bytes {
use base64::{engine::general_purpose::STANDARD, Engine as _};
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&STANDARD.encode(bytes))
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
let encoded = String::deserialize(deserializer)?;
STANDARD.decode(&encoded).map_err(serde::de::Error::custom)
}
}
pub fn encode_frame<T: Serialize>(msg: &T) -> Result<Vec<u8>, serde_json::Error> {
let json = serde_json::to_vec(msg)?;
if json.len() > MAX_FRAME_SIZE {
return Err(serde_json::Error::custom(
"message too large for protocol framing",
));
}
let len = json.len() as u32;
let mut frame = Vec::with_capacity(4 + json.len());
frame.extend_from_slice(&len.to_le_bytes());
frame.extend_from_slice(&json);
Ok(frame)
}
#[derive(Debug, PartialEq, Eq)]
pub enum DecodeResult<T> {
Message { message: T, consumed: usize },
Incomplete,
}
pub fn decode_frame<T: DeserializeOwned>(buf: &[u8]) -> Result<DecodeResult<T>, serde_json::Error> {
if buf.len() < 4 {
return Ok(DecodeResult::Incomplete);
}
let len = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
if len > MAX_FRAME_SIZE {
return Err(serde_json::Error::custom("frame length exceeds maximum"));
}
let total = 4 + len;
if buf.len() < total {
return Ok(DecodeResult::Incomplete);
}
let message: T = serde_json::from_slice(&buf[4..total])?;
Ok(DecodeResult::Message {
message,
consumed: total,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn roundtrip<T>(msg: T)
where
T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug,
{
let frame = encode_frame(&msg).unwrap();
match decode_frame::<T>(&frame).unwrap() {
DecodeResult::Message { message, consumed } => {
assert_eq!(message, msg);
assert_eq!(consumed, frame.len());
}
DecodeResult::Incomplete => panic!("expected a complete message"),
}
}
#[test]
fn roundtrip_provision() {
roundtrip(DaemonRequest::Provision(ProvisionConfig {
image: "alpine:latest".to_string(),
image_tar_path: Some(r"C:\images\alpine.tar".to_string()),
volumes: vec![VolumeMount {
host: r"C:\work".to_string(),
container: "/work".to_string(),
read_only: true,
}],
network: NetworkMode::Bridged,
port_mappings: vec![PortMapping {
windows_port: 8080,
container_port: 80,
}],
session_ref: Some("wslcsess:abc".to_string()),
network_proxy: None,
}));
}
#[test]
fn roundtrip_each_request_variant() {
roundtrip(DaemonRequest::Start(StartConfig {
sandbox_id: "wslc:abc123".to_string(),
}));
roundtrip(DaemonRequest::Exec(ExecConfig {
exec_id: "exec-1".to_string(),
run_token: "run-1".to_string(),
sandbox_id: "wslc:abc123".to_string(),
script_code: "echo hi".to_string(),
working_directory: "/work".to_string(),
env: vec![("PATH".to_string(), "/usr/bin".to_string())],
env_scope: EnvScope::Replace,
timeout_ms: 30_000,
stdin: true,
network_proxy: None,
}));
roundtrip(DaemonRequest::CancelExec(CancelExecConfig {
exec_id: "exec-1".to_string(),
run_token: "run-1".to_string(),
}));
roundtrip(DaemonRequest::ExecStdin(ExecStdinConfig {
exec_id: "exec-1".to_string(),
run_token: "run-1".to_string(),
}));
roundtrip(DaemonRequest::Stop(StopConfig {
sandbox_id: "wslc:abc123".to_string(),
}));
roundtrip(DaemonRequest::Deprovision(DeprovisionConfig {
sandbox_id: "wslc:abc123".to_string(),
}));
roundtrip(DaemonRequest::ProvisionSession(ProvisionSessionConfig {
cpu_count: Some(4),
memory_mb: Some(8192),
gpu: true,
}));
roundtrip(DaemonRequest::DeprovisionSession(
DeprovisionSessionConfig {
session_ref: "wslcsess:abc123".to_string(),
},
));
roundtrip(DaemonRequest::Ping);
}
#[test]
fn an_exec_config_keeps_repeated_environment_names_in_order() {
let config = ExecConfig {
exec_id: "exec-1".to_string(),
run_token: "run-1".to_string(),
sandbox_id: "wslc:abc123".to_string(),
script_code: "echo hi".to_string(),
working_directory: String::new(),
env: vec![
("FOO".to_string(), "1".to_string()),
("BAR".to_string(), "keep".to_string()),
("FOO".to_string(), "2".to_string()),
],
env_scope: EnvScope::Replace,
timeout_ms: 0,
stdin: false,
network_proxy: None,
};
let frame = encode_frame(&DaemonRequest::Exec(config.clone())).unwrap();
let DecodeResult::Message { message, .. } = decode_frame::<DaemonRequest>(&frame).unwrap()
else {
panic!("expected a complete message");
};
let DaemonRequest::Exec(decoded) = message else {
panic!("expected an exec request");
};
assert_eq!(decoded.env, config.env);
}
#[test]
fn roundtrip_each_response_variant() {
roundtrip(DaemonResponse::SessionProvisioned {
session_ref: "wslcsess:abc123".to_string(),
});
roundtrip(DaemonResponse::Provisioned {
sandbox_id: "wslc:abc123".to_string(),
});
roundtrip(DaemonResponse::Ok);
roundtrip(DaemonResponse::Pong);
for kind in [
ErrKind::NotProvisioned,
ErrKind::NotStarted,
ErrKind::Busy,
ErrKind::NotReady,
ErrKind::Protocol,
ErrKind::Unavailable,
ErrKind::Rejected,
ErrKind::Backend,
ErrKind::Unknown,
] {
roundtrip(DaemonResponse::Err {
kind,
message: "detail".to_string(),
api_failure: None,
});
}
roundtrip(DaemonResponse::Err {
kind: ErrKind::Backend,
message: "start failed".to_string(),
api_failure: Some(DaemonApiFailure {
operation: "WslcStartContainer".to_string(),
native_code: Some("0x80072740".to_string()),
}),
});
}
#[test]
fn a_provision_without_a_session_joins_the_implicit_one() {
let wire = r#"{"op":"provision","image":"alpine:latest"}"#;
let decoded: DaemonRequest = serde_json::from_str(wire).expect("decode without a session");
let DaemonRequest::Provision(config) = decoded else {
panic!("expected a provision request");
};
assert_eq!(config.session_ref, None);
}
#[test]
fn an_absent_session_is_left_off_the_wire() {
let frame = serde_json::to_string(&ProvisionConfig {
image: "alpine:latest".to_string(),
image_tar_path: None,
volumes: Vec::new(),
network: NetworkMode::None,
port_mappings: Vec::new(),
session_ref: None,
network_proxy: None,
})
.expect("serialize");
assert!(
!frame.contains("session_id"),
"an absent session must not serialize as a present null: {frame}"
);
}
#[test]
fn the_session_field_keeps_its_wire_name() {
let provision: DaemonRequest = serde_json::from_str(
r#"{"op":"provision","image":"alpine:latest","session_id":"wslcsess:abc"}"#,
)
.expect("decode a provision that names a session");
let deprovision: DaemonRequest =
serde_json::from_str(r#"{"op":"deprovision_session","session_id":"wslcsess:abc"}"#)
.expect("decode a session deprovision");
let provisioned: DaemonResponse =
serde_json::from_str(r#"{"status":"session_provisioned","session_id":"wslcsess:abc"}"#)
.expect("decode a session reply");
for encoded in [
serde_json::to_value(&provision),
serde_json::to_value(&deprovision),
serde_json::to_value(&provisioned),
] {
let encoded = encoded.expect("encode");
assert_eq!(
encoded["session_id"], "wslcsess:abc",
"a session must travel under the documented `session_id` key: {encoded}"
);
}
}
#[test]
fn a_session_sizing_omitted_is_the_host_default() {
let wire = r#"{"op":"provision_session"}"#;
let decoded: DaemonRequest = serde_json::from_str(wire).expect("decode bare sizing");
assert_eq!(
decoded,
DaemonRequest::ProvisionSession(ProvisionSessionConfig {
cpu_count: None,
memory_mb: None,
gpu: false,
}),
"absent sizing is the host default, which is distinct from a zero"
);
}
#[test]
fn unrecognized_err_kind_decodes_as_unknown() {
let wire = r#"{"status":"err","kind":"some_future_kind","message":"detail"}"#;
let decoded: DaemonResponse = serde_json::from_str(wire).expect("decode unknown kind");
assert_eq!(
decoded,
DaemonResponse::Err {
kind: ErrKind::Unknown,
message: "detail".to_string(),
api_failure: None,
}
);
}
#[test]
fn oversized_exec_identifiers_are_rejected_during_decode() {
let oversized = "x".repeat(MAX_EXEC_ID_BYTES + 1);
let exec = serde_json::json!({
"op": "exec",
"exec_id": oversized,
"run_token": "run-1",
"sandbox_id": "wslc:abc123",
"script_code": "true",
"working_directory": "",
"env": [],
"timeout_ms": 0
});
assert!(serde_json::from_value::<DaemonRequest>(exec).is_err());
let cancel = serde_json::json!({
"op": "cancel_exec",
"exec_id": "exec-1",
"run_token": "x".repeat(MAX_EXEC_ID_BYTES + 1)
});
assert!(serde_json::from_value::<DaemonRequest>(cancel).is_err());
let stdin = serde_json::json!({
"op": "exec_stdin",
"exec_id": "",
"run_token": "run-1"
});
assert!(serde_json::from_value::<DaemonRequest>(stdin).is_err());
}
#[test]
fn an_exec_config_without_stdin_gives_the_process_none() {
let without = r#"{"exec_id":"e","run_token":"r","sandbox_id":"s","script_code":"run"}"#;
let parsed: ExecConfig = serde_json::from_str(without).expect("stdin is optional");
assert!(!parsed.stdin);
}
#[test]
fn roundtrip_stream_frames() {
roundtrip(StreamFrame::Stdin {
data: b"input".to_vec(),
});
roundtrip(StreamFrame::Stdout {
data: b"out".to_vec(),
});
roundtrip(StreamFrame::Stderr {
data: b"err".to_vec(),
});
roundtrip(StreamFrame::Exit { code: 42 });
roundtrip(StreamFrame::TimedOut);
roundtrip(StreamFrame::Cancelled);
roundtrip(StreamFrame::Truncated);
roundtrip(StreamFrame::Error {
message: "spawn failed".to_string(),
api_failure: Some(DaemonApiFailure {
operation: "WslcCreateContainerProcess".to_string(),
native_code: Some("0x80004005".to_string()),
}),
});
}
#[test]
fn an_api_failure_travels_under_snake_case_keys() {
let encoded = serde_json::to_value(StreamFrame::Error {
message: "spawn failed".to_string(),
api_failure: Some(DaemonApiFailure {
operation: "WslcCreateContainerProcess".to_string(),
native_code: Some("0x80004005".to_string()),
}),
})
.expect("encode");
assert_eq!(
encoded["api_failure"],
serde_json::json!({
"operation": "WslcCreateContainerProcess",
"native_code": "0x80004005"
})
);
}
#[test]
fn stream_frame_bytes_roundtrip_including_non_utf8() {
let raw: Vec<u8> = (0u16..=255).map(|b| b as u8).collect();
roundtrip(StreamFrame::Stdout { data: raw.clone() });
roundtrip(StreamFrame::Stderr { data: raw.clone() });
roundtrip(StreamFrame::Stdin { data: raw });
}
#[test]
fn stream_frame_payload_is_base64_not_integer_array() {
let json = serde_json::to_string(&StreamFrame::Stdout {
data: b"hi".to_vec(),
})
.unwrap();
assert!(
json.contains("\"data\":\"aGk=\""),
"unexpected wire: {json}"
);
assert!(
!json.contains('['),
"payload must not be an integer array: {json}"
);
}
#[test]
fn network_mode_defaults_to_none() {
assert_eq!(NetworkMode::default(), NetworkMode::None);
}
#[test]
fn decode_incomplete_header() {
let r: DecodeResult<DaemonRequest> = decode_frame(&[0u8; 3]).unwrap();
assert_eq!(r, DecodeResult::Incomplete);
}
#[test]
fn decode_incomplete_body() {
let mut buf = Vec::new();
buf.extend_from_slice(&100u32.to_le_bytes());
buf.extend_from_slice(&[0u8; 10]);
let r: DecodeResult<DaemonRequest> = decode_frame(&buf).unwrap();
assert_eq!(r, DecodeResult::Incomplete);
}
#[test]
fn decode_empty_buffer_is_incomplete() {
let r: DecodeResult<DaemonRequest> = decode_frame(&[]).unwrap();
assert_eq!(r, DecodeResult::Incomplete);
}
#[test]
fn decode_rejects_oversized_length_prefix() {
let mut buf = Vec::new();
buf.extend_from_slice(&(MAX_FRAME_SIZE as u32 + 1).to_le_bytes());
let r: Result<DecodeResult<DaemonRequest>, _> = decode_frame(&buf);
assert!(r.is_err());
}
#[test]
fn frame_length_prefix_matches_payload() {
let frame = encode_frame(&DaemonRequest::Ping).unwrap();
let declared = u32::from_le_bytes([frame[0], frame[1], frame[2], frame[3]]) as usize;
assert_eq!(declared, frame.len() - 4);
}
#[test]
fn two_frames_decode_sequentially() {
let f1 = encode_frame(&DaemonRequest::Ping).unwrap();
let f2 = encode_frame(&DaemonResponse::Pong).unwrap();
let mut buf = Vec::new();
buf.extend_from_slice(&f1);
buf.extend_from_slice(&f2);
let consumed = match decode_frame::<DaemonRequest>(&buf).unwrap() {
DecodeResult::Message { message, consumed } => {
assert_eq!(message, DaemonRequest::Ping);
consumed
}
DecodeResult::Incomplete => panic!("expected first frame"),
};
match decode_frame::<DaemonResponse>(&buf[consumed..]).unwrap() {
DecodeResult::Message {
message,
consumed: c2,
} => {
assert_eq!(message, DaemonResponse::Pong);
assert_eq!(consumed + c2, buf.len());
}
DecodeResult::Incomplete => panic!("expected second frame"),
}
}
#[test]
fn decode_rejects_malformed_json_body() {
let mut buf = Vec::new();
let body = b"{ not json";
buf.extend_from_slice(&(body.len() as u32).to_le_bytes());
buf.extend_from_slice(body);
let r: Result<DecodeResult<DaemonRequest>, _> = decode_frame(&buf);
assert!(r.is_err());
}
#[test]
fn an_exec_config_without_an_env_scope_defaults_to_merge() {
let without = r#"{"exec_id":"e","run_token":"r","sandbox_id":"s","script_code":"run"}"#;
let parsed: ExecConfig = serde_json::from_str(without).expect("env_scope is optional");
assert_eq!(parsed.env_scope, EnvScope::Merge);
}
}