use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::Serialize;
use serde_json::Value;
use crate::mxc_common::exec_stream::wrap_read_checked;
use crate::mxc_common::id::parse_sandbox_id_prefix;
use crate::mxc_common::models::ContainmentBackend;
use crate::mxc_common::mxc_error::{MxcError, ResponseEnvelope};
use crate::mxc_common::sandbox_process::{PtySize, SandboxProcess};
use crate::mxc_common::state_aware_backend::{
DeprovisionResult, ExecHandle, ExecOutcome, ExecStdio, ProvisionResult, ProvisionSessionResult,
StartResult, StatefulSandboxBackend, StopResult,
};
use crate::mxc_common::state_aware_binding::{BoundStateAwareOperation, BoundStateAwareRequest};
use crate::mxc_common::state_aware_request::ParsedStateAwareRequest;
use crate::mxc_common::validator::validate_exec_common;
#[derive(Debug)]
pub enum DispatchOutcome {
Envelope(Value),
ExecCompleted { exit_code: i32 },
}
#[derive(Debug)]
pub enum TypedDispatchOutcome<ProvisionMetadata, StartMetadata, StopMetadata, DeprovisionMetadata> {
DryRun,
ProvisionSession(ProvisionSessionResult),
Provision(ProvisionResult<ProvisionMetadata>),
Start(StartResult<StartMetadata>),
ExecCompleted { exit_code: i32 },
Stop(StopResult<StopMetadata>),
Deprovision(DeprovisionResult<DeprovisionMetadata>),
DeprovisionSession,
}
pub type TypedBackendDispatchOutcome<B> = TypedDispatchOutcome<
<B as StatefulSandboxBackend>::ProvisionMetadata,
<B as StatefulSandboxBackend>::StartMetadata,
<B as StatefulSandboxBackend>::StopMetadata,
<B as StatefulSandboxBackend>::DeprovisionMetadata,
>;
pub fn run_state_aware(
parsed: ParsedStateAwareRequest,
dry_run: bool,
) -> Result<DispatchOutcome, MxcError> {
let _ = dry_run;
let backend = resolve_backend(&parsed)?;
Err(MxcError::unsupported_phase(format!(
"backend {:?} does not implement state-aware lifecycle",
backend
)))
}
pub fn dispatch_state_aware_exec<B: StatefulSandboxBackend>(
backend: &mut B,
bound: BoundStateAwareRequest<B>,
) -> Result<ExecHandle, MxcError> {
let phase = bound.phase();
let (request, operation) = bound.into_parts();
let BoundStateAwareOperation::Exec { sandbox_id, config } = operation else {
return Err(MxcError::malformed_request(format!(
"streaming exec requires the exec phase, got {phase}"
)));
};
validate_exec_common(&request)?;
backend.validate_exec(&sandbox_id, &request, config.as_ref())?;
backend.exec(&sandbox_id, &request, config, ExecStdio::Piped)
}
pub fn dispatch_state_aware_exec_pty<B: StatefulSandboxBackend>(
backend: &mut B,
bound: BoundStateAwareRequest<B>,
size: PtySize,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
let phase = bound.phase();
let (request, operation) = bound.into_parts();
let BoundStateAwareOperation::Exec { sandbox_id, config } = operation else {
return Err(MxcError::malformed_request(format!(
"spawning a process with a PTY in an existing container requires the exec phase, got {phase}"
)));
};
validate_exec_common(&request)?;
backend.validate_exec(&sandbox_id, &request, config.as_ref())?;
backend.exec_pty(&sandbox_id, &request, config, size)
}
pub fn dispatch_state_aware<B: StatefulSandboxBackend>(
backend: &mut B,
bound: BoundStateAwareRequest<B>,
dry_run: bool,
) -> Result<DispatchOutcome, MxcError> {
match dispatch_state_aware_typed(backend, bound, dry_run)? {
TypedDispatchOutcome::DryRun => Ok(DispatchOutcome::Envelope(empty_result_envelope())),
TypedDispatchOutcome::ProvisionSession(result) => Ok(DispatchOutcome::Envelope(
provision_session_envelope(result)?,
)),
TypedDispatchOutcome::Provision(result) => {
Ok(DispatchOutcome::Envelope(provision_envelope(result)?))
}
TypedDispatchOutcome::Start(result) => {
Ok(DispatchOutcome::Envelope(metadata_envelope(result)?))
}
TypedDispatchOutcome::ExecCompleted { exit_code } => {
Ok(DispatchOutcome::ExecCompleted { exit_code })
}
TypedDispatchOutcome::Stop(result) => {
Ok(DispatchOutcome::Envelope(metadata_envelope(result)?))
}
TypedDispatchOutcome::Deprovision(result) => {
Ok(DispatchOutcome::Envelope(metadata_envelope(result)?))
}
TypedDispatchOutcome::DeprovisionSession => {
Ok(DispatchOutcome::Envelope(empty_result_envelope()))
}
}
}
pub fn dispatch_state_aware_typed<B: StatefulSandboxBackend>(
backend: &mut B,
bound: BoundStateAwareRequest<B>,
dry_run: bool,
) -> Result<TypedBackendDispatchOutcome<B>, MxcError> {
let (request, operation) = bound.into_parts();
match operation {
BoundStateAwareOperation::ProvisionSession(config) => {
backend.validate_provision_session(&request, config.as_ref())?;
if dry_run {
return Ok(TypedDispatchOutcome::DryRun);
}
let result = backend.provision_session(&request, config)?;
Ok(TypedDispatchOutcome::ProvisionSession(result))
}
BoundStateAwareOperation::Provision(config) => {
backend.validate_provision(&request, config.as_ref())?;
if dry_run {
return Ok(TypedDispatchOutcome::DryRun);
}
let result = backend.provision(&request, config)?;
Ok(TypedDispatchOutcome::Provision(result))
}
BoundStateAwareOperation::Start { sandbox_id, config } => {
backend.validate_start(&sandbox_id, &request, config.as_ref())?;
if dry_run {
return Ok(TypedDispatchOutcome::DryRun);
}
let result = backend.start(&sandbox_id, &request, config)?;
Ok(TypedDispatchOutcome::Start(result))
}
BoundStateAwareOperation::Exec { sandbox_id, config } => {
validate_exec_common(&request)?;
backend.validate_exec(&sandbox_id, &request, config.as_ref())?;
if dry_run {
return Ok(TypedDispatchOutcome::DryRun);
}
let handle = backend.exec(&sandbox_id, &request, config, ExecStdio::Relayed)?;
let exit_code = relay_exec_to_stdio(handle)?;
Ok(TypedDispatchOutcome::ExecCompleted { exit_code })
}
BoundStateAwareOperation::Stop { sandbox_id, config } => {
backend.validate_stop(&sandbox_id, &request, config.as_ref())?;
if dry_run {
return Ok(TypedDispatchOutcome::DryRun);
}
let result = backend.stop(&sandbox_id, &request, config)?;
Ok(TypedDispatchOutcome::Stop(result))
}
BoundStateAwareOperation::Deprovision { sandbox_id, config } => {
backend.validate_deprovision(&sandbox_id, &request, config.as_ref())?;
if dry_run {
return Ok(TypedDispatchOutcome::DryRun);
}
let result = backend.deprovision(&sandbox_id, &request, config)?;
Ok(TypedDispatchOutcome::Deprovision(result))
}
BoundStateAwareOperation::DeprovisionSession { session_id } => {
backend.validate_deprovision_session(&session_id, &request)?;
if dry_run {
return Ok(TypedDispatchOutcome::DryRun);
}
backend.deprovision_session(&session_id, &request)?;
Ok(TypedDispatchOutcome::DeprovisionSession)
}
}
}
pub fn resolve_backend(parsed: &ParsedStateAwareRequest) -> Result<ContainmentBackend, MxcError> {
let phase = parsed.phase();
if phase.routes_by_containment() {
return parsed.containment().ok_or_else(|| {
MxcError::malformed_request(format!("{phase} phase requires a containment field"))
});
}
let sandbox_id = parsed.sandbox_id_required()?;
let prefix = parse_sandbox_id_prefix(sandbox_id)?;
backend_from_prefix(prefix)
}
pub(crate) fn backend_from_prefix(prefix: &str) -> Result<ContainmentBackend, MxcError> {
match prefix {
"iso" => Ok(ContainmentBackend::IsolationSession),
"microvm" => Ok(ContainmentBackend::MicroVm),
"wsb" => Ok(ContainmentBackend::WindowsSandbox),
"wslc" => Ok(ContainmentBackend::Wslc),
"w365" => Ok(ContainmentBackend::W365Agents),
other => Err(MxcError::unsupported_containment(format!(
"no state-aware backend registered for prefix {:?}",
other
))),
}
}
fn relay_exec_to_stdio(handle: ExecHandle) -> Result<i32, MxcError> {
let ExecHandle {
stdout,
stderr,
stdin: _,
waiter,
terminator,
stdin_closer: _,
} = handle;
let streams = wrap_read_checked(stdout, "stdout").and_then(|out| {
let err = wrap_read_checked(stderr, "stderr")?;
Ok(RelayStreams {
stdout: out,
stderr: err,
})
});
relay_prepared_streams(streams, waiter, terminator)
}
struct RelayStreams {
stdout: Option<Box<dyn std::io::Read + Send>>,
stderr: Option<Box<dyn std::io::Read + Send>>,
}
fn relay_prepared_streams(
streams: Result<RelayStreams, MxcError>,
waiter: Box<dyn FnOnce() -> Result<ExecOutcome, MxcError> + Send>,
terminator: Box<dyn FnOnce() -> Result<(), MxcError> + Send>,
) -> Result<i32, MxcError> {
let streams = match streams {
Ok(streams) => streams,
Err(error) => return abort_relay(waiter, terminator, Vec::new(), error),
};
let mut pumps: Vec<Pump> = Vec::new();
if let Some(src) = streams.stdout {
match spawn_pump("mxc-relay-stdout", src, std::io::stdout()) {
Ok(pump) => pumps.push(pump),
Err(error) => return abort_relay(waiter, terminator, pumps, error),
}
}
if let Some(src) = streams.stderr {
match spawn_pump("mxc-relay-stderr", src, std::io::stderr()) {
Ok(pump) => pumps.push(pump),
Err(error) => return abort_relay(waiter, terminator, pumps, error),
}
}
let outcome = waiter();
if outcome.is_err() {
let _ = terminator();
}
drain_pumps(pumps);
match outcome {
Ok(ExecOutcome::Exited(code)) => Ok(code),
Ok(ExecOutcome::TimedOut) => Err(MxcError::backend_error(
"backend reported a timeout to the relay, which has no way \
to represent one; a backend serving ExecStdio::Relayed must \
report ExecOutcome::Exited",
)),
Err(error) => Err(error),
}
}
fn drain_pumps(pumps: Vec<Pump>) {
drain_pumps_within(pumps, POST_EXIT_DRAIN_GRACE);
}
fn drain_pumps_within(pumps: Vec<Pump>, grace: Duration) {
let deadline = Instant::now() + grace;
for pump in pumps {
let remaining = deadline.saturating_duration_since(Instant::now());
if pump.finished.recv_timeout(remaining).is_ok() {
let _ = pump.thread.join();
} else {
pump.mute();
}
}
}
const POST_EXIT_DRAIN_GRACE: Duration = Duration::from_secs(5);
struct Pump {
thread: std::thread::JoinHandle<()>,
finished: std::sync::mpsc::Receiver<()>,
muted: Arc<AtomicBool>,
}
impl Pump {
fn mute(&self) {
self.muted.store(true, Ordering::Relaxed);
}
}
fn abort_relay(
waiter: Box<dyn FnOnce() -> Result<ExecOutcome, MxcError> + Send>,
terminator: Box<dyn FnOnce() -> Result<(), MxcError> + Send>,
pumps: Vec<Pump>,
error: MxcError,
) -> Result<i32, MxcError> {
let _ = terminator();
drain_pumps(pumps);
let _ = waiter();
Err(error)
}
fn spawn_pump<R, W>(name: &str, src: R, dst: W) -> Result<Pump, MxcError>
where
R: std::io::Read + Send + 'static,
W: std::io::Write + Send + 'static,
{
let muted = Arc::new(AtomicBool::new(false));
let thread_muted = Arc::clone(&muted);
let (finished_tx, finished) = std::sync::mpsc::channel();
std::thread::Builder::new()
.name(name.to_string())
.spawn(move || {
pump_stream(src, dst, &thread_muted);
let _ = finished_tx.send(());
})
.map(|thread| Pump {
thread,
finished,
muted,
})
.map_err(|error| MxcError::backend_error(format!("failed to start {name}: {error}")))
}
fn pump_stream<R: std::io::Read, W: std::io::Write>(mut src: R, mut dst: W, muted: &AtomicBool) {
let mut buf = [0u8; 8192];
let mut discarding = false;
loop {
match src.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
if !discarding && !muted.load(Ordering::Relaxed) {
let wrote = dst.write_all(&buf[..n]).and_then(|()| dst.flush());
if wrote.is_err() {
discarding = true;
}
}
}
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
}
#[derive(Serialize)]
struct ProvisionWireBody<M: Serialize> {
#[serde(rename = "sandboxId")]
sandbox_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<M>,
}
#[derive(Serialize)]
struct MetadataWireBody<M: Serialize> {
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<M>,
}
#[derive(Serialize)]
struct ProvisionSessionWireBody {
#[serde(rename = "sessionId")]
session_id: String,
}
fn provision_envelope<M: Serialize>(r: ProvisionResult<M>) -> Result<Value, MxcError> {
let body = ProvisionWireBody {
sandbox_id: r.sandbox_id,
metadata: r.metadata,
};
let envelope = ResponseEnvelope::Result(body);
serde_json::to_value(&envelope).map_err(|e| {
MxcError::backend_error(format!("provision envelope serialisation failed: {}", e))
})
}
fn metadata_envelope<R: HasMetadata>(r: R) -> Result<Value, MxcError> {
let body = MetadataWireBody {
metadata: r.into_metadata(),
};
let envelope = ResponseEnvelope::Result(body);
serde_json::to_value(&envelope).map_err(|e| {
MxcError::backend_error(format!("metadata envelope serialisation failed: {}", e))
})
}
fn provision_session_envelope(r: ProvisionSessionResult) -> Result<Value, MxcError> {
let body = ProvisionSessionWireBody {
session_id: r.session_id,
};
let envelope = ResponseEnvelope::Result(body);
serde_json::to_value(&envelope).map_err(|e| {
MxcError::backend_error(format!(
"session provision envelope serialisation failed: {}",
e
))
})
}
fn empty_result_envelope() -> Value {
serde_json::json!({"result": {}})
}
trait HasMetadata {
type Metadata: Serialize;
fn into_metadata(self) -> Option<Self::Metadata>;
}
impl<M: Serialize> HasMetadata for StartResult<M> {
type Metadata = M;
fn into_metadata(self) -> Option<M> {
self.metadata
}
}
impl<M: Serialize> HasMetadata for StopResult<M> {
type Metadata = M;
fn into_metadata(self) -> Option<M> {
self.metadata
}
}
impl<M: Serialize> HasMetadata for DeprovisionResult<M> {
type Metadata = M;
fn into_metadata(self) -> Option<M> {
self.metadata
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mxc_common::models::ExecutionRequest;
use crate::mxc_common::models::WslcProvisionSessionConfig;
use crate::mxc_common::mxc_error::MxcErrorCode;
use crate::mxc_common::state_aware_operation::{StateAwareOperation, StateAwareProvision};
use crate::mxc_common::state_aware_request::Phase;
use serde_json::json;
use std::cell::Cell;
use std::cell::RefCell;
use std::time::Duration;
const SESSION_ID: &str = "wslcsess:0123456789abcdef0123456789abcdef";
struct StubBackend {
provision_calls: Cell<u32>,
start_calls: Cell<u32>,
exec_calls: Cell<u32>,
stop_calls: Cell<u32>,
deprovision_calls: Cell<u32>,
validate_provision_calls: Cell<u32>,
validate_start_calls: Cell<u32>,
validate_exec_calls: Cell<u32>,
validate_stop_calls: Cell<u32>,
validate_deprovision_calls: Cell<u32>,
last_exec_stdio: Cell<Option<ExecStdio>>,
provision_error: Option<MxcError>,
validate_provision_error: Option<MxcError>,
}
impl StubBackend {
fn new() -> Self {
Self {
provision_calls: Cell::new(0),
start_calls: Cell::new(0),
exec_calls: Cell::new(0),
stop_calls: Cell::new(0),
deprovision_calls: Cell::new(0),
validate_provision_calls: Cell::new(0),
validate_start_calls: Cell::new(0),
validate_exec_calls: Cell::new(0),
validate_stop_calls: Cell::new(0),
validate_deprovision_calls: Cell::new(0),
last_exec_stdio: Cell::new(None),
provision_error: None,
validate_provision_error: None,
}
}
}
impl StatefulSandboxBackend for StubBackend {
const ID_PREFIX: &'static str = "stubd";
const BACKEND_KEY: &'static str = "stub_dispatch";
type ProvisionConfig = ();
type StartConfig = ();
type ExecConfig = ();
type StopConfig = ();
type DeprovisionConfig = ();
type ProvisionMetadata = ();
type StartMetadata = ();
type StopMetadata = ();
type DeprovisionMetadata = ();
fn provision(
&mut self,
_request: &ExecutionRequest,
_config: Option<()>,
) -> Result<ProvisionResult<()>, MxcError> {
self.provision_calls.set(self.provision_calls.get() + 1);
if let Some(e) = self.provision_error.clone() {
return Err(e);
}
Ok(ProvisionResult {
sandbox_id: format!("{}:fixed-token", Self::ID_PREFIX),
metadata: None,
})
}
fn start(
&mut self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<()>,
) -> Result<StartResult<()>, MxcError> {
self.start_calls.set(self.start_calls.get() + 1);
Ok(StartResult { metadata: None })
}
fn exec(
&mut self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<()>,
stdio: ExecStdio,
) -> Result<ExecHandle, MxcError> {
self.exec_calls.set(self.exec_calls.get() + 1);
self.last_exec_stdio.set(Some(stdio));
Err(MxcError::backend_error("stub exec not wired"))
}
fn stop(
&mut self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<()>,
) -> Result<StopResult<()>, MxcError> {
self.stop_calls.set(self.stop_calls.get() + 1);
Ok(StopResult { metadata: None })
}
fn deprovision(
&mut self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<()>,
) -> Result<DeprovisionResult<()>, MxcError> {
self.deprovision_calls.set(self.deprovision_calls.get() + 1);
Ok(DeprovisionResult { metadata: None })
}
fn validate_provision(
&self,
_request: &ExecutionRequest,
_config: Option<&()>,
) -> Result<(), MxcError> {
self.validate_provision_calls
.set(self.validate_provision_calls.get() + 1);
if let Some(e) = self.validate_provision_error.clone() {
return Err(e);
}
Ok(())
}
fn validate_start(
&self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<&()>,
) -> Result<(), MxcError> {
self.validate_start_calls
.set(self.validate_start_calls.get() + 1);
Ok(())
}
fn validate_exec(
&self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<&()>,
) -> Result<(), MxcError> {
self.validate_exec_calls
.set(self.validate_exec_calls.get() + 1);
Ok(())
}
fn validate_stop(
&self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<&()>,
) -> Result<(), MxcError> {
self.validate_stop_calls
.set(self.validate_stop_calls.get() + 1);
Ok(())
}
fn validate_deprovision(
&self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<&()>,
) -> Result<(), MxcError> {
self.validate_deprovision_calls
.set(self.validate_deprovision_calls.get() + 1);
Ok(())
}
}
#[derive(Debug, PartialEq, Eq, Default)]
struct TypedStartConfig {
configuration_id: String,
}
struct TypedConfigStubBackend {
captured_start_config: Cell<Option<TypedStartConfig>>,
}
impl TypedConfigStubBackend {
fn new() -> Self {
Self {
captured_start_config: Cell::new(None),
}
}
}
impl StatefulSandboxBackend for TypedConfigStubBackend {
const ID_PREFIX: &'static str = "typed";
const BACKEND_KEY: &'static str = "typed_stub";
type ProvisionConfig = ();
type StartConfig = TypedStartConfig;
type ExecConfig = ();
type StopConfig = ();
type DeprovisionConfig = ();
type ProvisionMetadata = ();
type StartMetadata = ();
type StopMetadata = ();
type DeprovisionMetadata = ();
fn exec(
&mut self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<()>,
_stdio: ExecStdio,
) -> Result<ExecHandle, MxcError> {
Err(MxcError::backend_error("typed stub exec not wired"))
}
fn start(
&mut self,
_sandbox_id: &str,
_request: &ExecutionRequest,
config: Option<TypedStartConfig>,
) -> Result<StartResult<()>, MxcError> {
self.captured_start_config.set(config);
Ok(StartResult { metadata: None })
}
}
struct SessionStubBackend {
provision_session_calls: Cell<u32>,
deprovision_session_calls: Cell<u32>,
validate_provision_session_calls: Cell<u32>,
validate_deprovision_session_calls: Cell<u32>,
released: RefCell<Vec<String>>,
validated_sizing: Cell<Option<WslcProvisionSessionConfig>>,
provisioned_sizing: Cell<Option<WslcProvisionSessionConfig>>,
}
impl SessionStubBackend {
fn new() -> Self {
Self {
provision_session_calls: Cell::new(0),
deprovision_session_calls: Cell::new(0),
validate_provision_session_calls: Cell::new(0),
validate_deprovision_session_calls: Cell::new(0),
released: RefCell::new(Vec::new()),
validated_sizing: Cell::new(None),
provisioned_sizing: Cell::new(None),
}
}
}
impl StatefulSandboxBackend for SessionStubBackend {
const ID_PREFIX: &'static str = "sess";
const BACKEND_KEY: &'static str = "session_stub";
type ProvisionConfig = ();
type StartConfig = ();
type ExecConfig = ();
type StopConfig = ();
type DeprovisionConfig = ();
type ProvisionMetadata = ();
type StartMetadata = ();
type StopMetadata = ();
type DeprovisionMetadata = ();
fn exec(
&mut self,
_sandbox_id: &str,
_request: &ExecutionRequest,
_config: Option<()>,
_stdio: ExecStdio,
) -> Result<ExecHandle, MxcError> {
Err(MxcError::backend_error("session stub exec not wired"))
}
fn provision_session(
&mut self,
_request: &ExecutionRequest,
config: Option<WslcProvisionSessionConfig>,
) -> Result<ProvisionSessionResult, MxcError> {
self.provision_session_calls
.set(self.provision_session_calls.get() + 1);
self.provisioned_sizing.set(config);
Ok(ProvisionSessionResult {
session_id: "wslcsess:fixed-token".to_string(),
})
}
fn deprovision_session(
&mut self,
session_id: &str,
_request: &ExecutionRequest,
) -> Result<(), MxcError> {
self.deprovision_session_calls
.set(self.deprovision_session_calls.get() + 1);
self.released.borrow_mut().push(session_id.to_string());
Ok(())
}
fn validate_provision_session(
&self,
_request: &ExecutionRequest,
config: Option<&WslcProvisionSessionConfig>,
) -> Result<(), MxcError> {
self.validate_provision_session_calls
.set(self.validate_provision_session_calls.get() + 1);
self.validated_sizing.set(config.copied());
Ok(())
}
fn validate_deprovision_session(
&self,
_session_id: &str,
_request: &ExecutionRequest,
) -> Result<(), MxcError> {
self.validate_deprovision_session_calls
.set(self.validate_deprovision_session_calls.get() + 1);
Ok(())
}
}
fn session_bound(
phase: Phase,
session_id: Option<&str>,
) -> BoundStateAwareRequest<SessionStubBackend> {
let operation = match phase {
Phase::ProvisionSession => BoundStateAwareOperation::ProvisionSession(None),
Phase::DeprovisionSession => BoundStateAwareOperation::DeprovisionSession {
session_id: session_id.unwrap().into(),
},
other => panic!("session_bound does not cover {other}"),
};
BoundStateAwareRequest::for_test(ExecutionRequest::default(), operation)
}
fn bound(phase: Phase, sandbox_id: Option<&str>) -> BoundStateAwareRequest<StubBackend> {
let operation = match phase {
Phase::ProvisionSession => BoundStateAwareOperation::ProvisionSession(None),
Phase::Provision => BoundStateAwareOperation::Provision(None),
Phase::Start => BoundStateAwareOperation::Start {
sandbox_id: sandbox_id.unwrap().into(),
config: None,
},
Phase::Exec => BoundStateAwareOperation::Exec {
sandbox_id: sandbox_id.unwrap().into(),
config: None,
},
Phase::Stop => BoundStateAwareOperation::Stop {
sandbox_id: sandbox_id.unwrap().into(),
config: None,
},
Phase::Deprovision => BoundStateAwareOperation::Deprovision {
sandbox_id: sandbox_id.unwrap().into(),
config: None,
},
Phase::DeprovisionSession => BoundStateAwareOperation::DeprovisionSession {
session_id: sandbox_id.unwrap().into(),
},
};
BoundStateAwareRequest::for_test(ExecutionRequest::default(), operation)
}
fn bound_runnable_exec(sandbox_id: &str) -> BoundStateAwareRequest<StubBackend> {
let (mut request, operation) = bound(Phase::Exec, Some(sandbox_id)).into_parts();
request.script_code = "echo hi".to_string();
BoundStateAwareRequest::for_test(request, operation)
}
fn assert_envelope(outcome: DispatchOutcome) -> Value {
match outcome {
DispatchOutcome::Envelope(v) => v,
DispatchOutcome::ExecCompleted { .. } => panic!("expected envelope"),
}
}
#[test]
fn dispatch_provision_calls_validate_then_provision() {
let mut b = StubBackend::new();
let env = assert_envelope(
dispatch_state_aware(&mut b, bound(Phase::Provision, None), false).unwrap(),
);
assert_eq!(b.validate_provision_calls.get(), 1);
assert_eq!(b.provision_calls.get(), 1);
assert_eq!(env, json!({"result": {"sandboxId": "stubd:fixed-token"}}));
}
#[test]
fn dispatch_provision_session_returns_the_minted_session_id() {
let mut b = SessionStubBackend::new();
let env = assert_envelope(
dispatch_state_aware(&mut b, session_bound(Phase::ProvisionSession, None), false)
.unwrap(),
);
assert_eq!(b.validate_provision_session_calls.get(), 1);
assert_eq!(b.provision_session_calls.get(), 1);
assert_eq!(
env,
json!({"result": {"sessionId": "wslcsess:fixed-token"}})
);
}
#[test]
fn dispatch_deprovision_session_releases_the_named_session() {
let mut b = SessionStubBackend::new();
let env = assert_envelope(
dispatch_state_aware(
&mut b,
session_bound(Phase::DeprovisionSession, Some(SESSION_ID)),
false,
)
.unwrap(),
);
assert_eq!(b.validate_deprovision_session_calls.get(), 1);
assert_eq!(b.deprovision_session_calls.get(), 1);
assert_eq!(*b.released.borrow(), vec![SESSION_ID.to_string()]);
assert_eq!(env, json!({"result": {}}));
}
#[test]
fn dispatch_carries_session_sizing_to_both_the_hook_and_the_phase_method() {
let sizing = WslcProvisionSessionConfig {
cpu_count: Some(4),
memory_mb: Some(8192),
gpu: Some(true),
};
let bound = BoundStateAwareRequest::<SessionStubBackend>::for_test(
ExecutionRequest::default(),
BoundStateAwareOperation::ProvisionSession(Some(sizing)),
);
let mut b = SessionStubBackend::new();
dispatch_state_aware(&mut b, bound, false).unwrap();
assert_eq!(b.validated_sizing.get(), Some(sizing));
assert_eq!(b.provisioned_sizing.get(), Some(sizing));
}
#[test]
fn a_session_dry_run_still_shows_the_hook_its_sizing() {
let sizing = WslcProvisionSessionConfig {
cpu_count: Some(2),
..Default::default()
};
let bound = BoundStateAwareRequest::<SessionStubBackend>::for_test(
ExecutionRequest::default(),
BoundStateAwareOperation::ProvisionSession(Some(sizing)),
);
let mut b = SessionStubBackend::new();
dispatch_state_aware(&mut b, bound, true).unwrap();
assert_eq!(b.validated_sizing.get(), Some(sizing));
assert_eq!(b.provisioned_sizing.get(), None);
assert_eq!(b.provision_session_calls.get(), 0);
}
#[test]
fn dispatch_session_dry_run_validates_without_minting_or_releasing() {
let mut b = SessionStubBackend::new();
for bound in [
session_bound(Phase::ProvisionSession, None),
session_bound(Phase::DeprovisionSession, Some(SESSION_ID)),
] {
assert_eq!(
assert_envelope(dispatch_state_aware(&mut b, bound, true).unwrap()),
json!({"result": {}})
);
}
assert_eq!(b.validate_provision_session_calls.get(), 1);
assert_eq!(b.validate_deprovision_session_calls.get(), 1);
assert_eq!(b.provision_session_calls.get(), 0);
assert_eq!(b.deprovision_session_calls.get(), 0);
assert!(b.released.borrow().is_empty());
}
#[test]
fn dispatch_session_phases_refuse_on_a_backend_without_sessions_even_in_dry_run() {
for dry_run in [false, true] {
let mut b = StubBackend::new();
for bound in [
bound(Phase::ProvisionSession, None),
bound(Phase::DeprovisionSession, Some(SESSION_ID)),
] {
let error = dispatch_state_aware(&mut b, bound, dry_run).unwrap_err();
assert_eq!(error.code, MxcErrorCode::UnsupportedPhase, "{dry_run}");
assert!(error.message.contains("stub_dispatch"), "{error:?}");
}
}
}
#[test]
fn a_session_phase_cannot_be_streamed_as_an_exec() {
let mut b = SessionStubBackend::new();
for phase in [Phase::ProvisionSession, Phase::DeprovisionSession] {
let bound = session_bound(phase, Some(SESSION_ID));
let error = dispatch_state_aware_exec(&mut b, bound).unwrap_err();
assert_eq!(error.code, MxcErrorCode::MalformedRequest);
assert_eq!(
error.message,
format!("streaming exec requires the exec phase, got {phase}")
);
}
assert_eq!(b.provision_session_calls.get(), 0);
assert_eq!(b.deprovision_session_calls.get(), 0);
}
#[test]
fn dispatch_provision_dry_run_skips_provision_call_but_runs_validate() {
let mut b = StubBackend::new();
let env = assert_envelope(
dispatch_state_aware(&mut b, bound(Phase::Provision, None), true).unwrap(),
);
assert_eq!(b.validate_provision_calls.get(), 1);
assert_eq!(b.provision_calls.get(), 0);
assert_eq!(env, json!({"result": {}}));
}
#[test]
fn dispatch_provision_returns_validate_error_without_calling_provision() {
let mut b = StubBackend::new();
b.validate_provision_error = Some(MxcError::policy_validation("nope"));
let err = dispatch_state_aware(&mut b, bound(Phase::Provision, None), false).unwrap_err();
assert_eq!(err.code, MxcErrorCode::PolicyValidation);
assert_eq!(b.validate_provision_calls.get(), 1);
assert_eq!(b.provision_calls.get(), 0);
}
#[test]
fn dispatch_provision_propagates_provision_error() {
let mut b = StubBackend::new();
b.provision_error = Some(MxcError::backend_error("boom"));
let err = dispatch_state_aware(&mut b, bound(Phase::Provision, None), false).unwrap_err();
assert_eq!(err.code, MxcErrorCode::BackendError);
assert_eq!(b.provision_calls.get(), 1);
}
#[test]
fn start_without_sandbox_id_cannot_reach_binding() {
let error = crate::mxc_common::config_parser::load_mxc_request_from_json(
r#"{"version":"0.9.0-alpha","phase":"start"}"#,
&mut crate::mxc_common::logger::Logger::new(crate::mxc_common::logger::Mode::Buffer),
)
.unwrap_err();
let crate::mxc_common::config_parser::ParseError::StateAware(error) = error else {
panic!("expected state-aware structural rejection");
};
assert_eq!(error.code, MxcErrorCode::MalformedRequest);
assert!(error.message.contains("sandboxId"));
}
#[test]
fn dispatch_start_calls_validate_then_start() {
let mut b = StubBackend::new();
let env = assert_envelope(
dispatch_state_aware(&mut b, bound(Phase::Start, Some("stubd:abc")), false).unwrap(),
);
assert_eq!(b.validate_start_calls.get(), 1);
assert_eq!(b.start_calls.get(), 1);
assert_eq!(env, json!({"result": {}}));
}
#[test]
fn dispatch_exec_validate_common_rejects_empty_command_line() {
let mut b = StubBackend::new();
let err =
dispatch_state_aware(&mut b, bound(Phase::Exec, Some("stubd:abc")), false).unwrap_err();
assert_eq!(err.code, MxcErrorCode::MalformedRequest);
assert_eq!(b.validate_exec_calls.get(), 0);
assert_eq!(b.exec_calls.get(), 0);
}
#[test]
fn dispatch_exec_dry_run_skips_exec_call() {
let mut b = StubBackend::new();
let p = bound_runnable_exec("stubd:abc");
let env = assert_envelope(dispatch_state_aware(&mut b, p, true).unwrap());
assert_eq!(b.validate_exec_calls.get(), 1);
assert_eq!(b.exec_calls.get(), 0);
assert_eq!(env, json!({"result": {}}));
}
#[test]
fn dispatch_start_dry_run_skips_start_call_but_runs_validate() {
let mut b = StubBackend::new();
let env = assert_envelope(
dispatch_state_aware(&mut b, bound(Phase::Start, Some("stubd:abc")), true).unwrap(),
);
assert_eq!(b.validate_start_calls.get(), 1);
assert_eq!(b.start_calls.get(), 0, "dry-run must not start the sandbox");
assert_eq!(env, json!({"result": {}}));
}
#[test]
fn dispatch_stop_dry_run_skips_stop_call_but_runs_validate() {
let mut b = StubBackend::new();
let env = assert_envelope(
dispatch_state_aware(&mut b, bound(Phase::Stop, Some("stubd:abc")), true).unwrap(),
);
assert_eq!(b.validate_stop_calls.get(), 1);
assert_eq!(b.stop_calls.get(), 0, "dry-run must not stop the sandbox");
assert_eq!(env, json!({"result": {}}));
}
#[test]
fn dispatch_deprovision_dry_run_skips_deprovision_call_but_runs_validate() {
let mut b = StubBackend::new();
let env = assert_envelope(
dispatch_state_aware(&mut b, bound(Phase::Deprovision, Some("stubd:abc")), true)
.unwrap(),
);
assert_eq!(b.validate_deprovision_calls.get(), 1);
assert_eq!(
b.deprovision_calls.get(),
0,
"dry-run must not deprovision the sandbox"
);
assert_eq!(env, json!({"result": {}}));
}
#[test]
fn dispatch_stop_routes_correctly() {
let mut b = StubBackend::new();
assert_envelope(
dispatch_state_aware(&mut b, bound(Phase::Stop, Some("stubd:abc")), false).unwrap(),
);
assert_eq!(b.validate_stop_calls.get(), 1);
assert_eq!(b.stop_calls.get(), 1);
}
#[test]
fn dispatch_deprovision_routes_correctly() {
let mut b = StubBackend::new();
assert_envelope(
dispatch_state_aware(&mut b, bound(Phase::Deprovision, Some("stubd:abc")), false)
.unwrap(),
);
assert_eq!(b.validate_deprovision_calls.get(), 1);
assert_eq!(b.deprovision_calls.get(), 1);
}
#[test]
fn typed_config_stub_receives_typed_start_config() {
let mut b = TypedConfigStubBackend::new();
let p = BoundStateAwareRequest::for_test(
ExecutionRequest::default(),
BoundStateAwareOperation::Start {
sandbox_id: "typed:abc".into(),
config: Some(TypedStartConfig {
configuration_id: "small".into(),
}),
},
);
assert_envelope(dispatch_state_aware(&mut b, p, false).unwrap());
let captured = b.captured_start_config.into_inner();
assert_eq!(
captured,
Some(TypedStartConfig {
configuration_id: "small".into()
})
);
}
#[test]
fn typed_config_stub_receives_absent_configuration() {
let mut b = TypedConfigStubBackend::new();
let p = BoundStateAwareRequest::for_test(
ExecutionRequest::default(),
BoundStateAwareOperation::Start {
sandbox_id: "typed:abc".into(),
config: None,
},
);
assert_envelope(dispatch_state_aware(&mut b, p, false).unwrap());
assert_eq!(b.captured_start_config.into_inner(), None);
}
#[test]
fn misplaced_phase_configuration_is_rejected_before_dispatch() {
let err = crate::mxc_common::config_parser::load_mxc_request_from_json(
r#"{"version":"0.9.0-alpha","phase":"start","sandboxId":"iso:abc",
"isolationSession":{"provision":{"appId":"small"}}}"#,
&mut crate::mxc_common::logger::Logger::new(crate::mxc_common::logger::Mode::Buffer),
)
.unwrap_err();
let crate::mxc_common::config_parser::ParseError::StateAware(err) = err else {
panic!("expected state-aware structural rejection");
};
assert_eq!(err.code, MxcErrorCode::MalformedRequest);
assert!(
err.message.contains("isolationSession"),
"expected envelope-ready error path, got: {}",
err.message
);
}
#[test]
fn run_state_aware_provision_for_recognized_backend_returns_unsupported_phase() {
let p = ParsedStateAwareRequest::new(
ExecutionRequest::default(),
StateAwareOperation::Provision(StateAwareProvision::Wslc(None)),
);
let err = run_state_aware(p, false).unwrap_err();
assert_eq!(err.code, MxcErrorCode::UnsupportedPhase);
}
#[test]
fn provision_without_containment_cannot_reach_binding() {
let err = crate::mxc_common::config_parser::load_mxc_request_from_json(
r#"{"version":"0.9.0-alpha","phase":"provision"}"#,
&mut crate::mxc_common::logger::Logger::new(crate::mxc_common::logger::Mode::Buffer),
)
.unwrap_err();
let crate::mxc_common::config_parser::ParseError::StateAware(err) = err else {
panic!("expected state-aware structural rejection");
};
assert_eq!(err.code, MxcErrorCode::MalformedRequest);
}
#[test]
fn resolve_backend_for_iso_prefix_returns_isolation_session() {
let p = parsed_start("iso:wxc-abcd1234");
assert_eq!(
resolve_backend(&p).unwrap(),
ContainmentBackend::IsolationSession
);
}
#[test]
fn resolve_backend_for_wsb_prefix_returns_windows_sandbox() {
let p = parsed_start("wsb:deadbeef");
assert_eq!(
resolve_backend(&p).unwrap(),
ContainmentBackend::WindowsSandbox
);
}
#[test]
fn resolve_backend_for_wslc_prefix_returns_wslc() {
let p = parsed_start("wslc:deadbeef");
assert_eq!(resolve_backend(&p).unwrap(), ContainmentBackend::Wslc);
}
#[test]
fn resolve_backend_for_unknown_prefix_returns_unsupported_containment() {
let p = parsed_start("unknownxyz:abc");
let err = resolve_backend(&p).unwrap_err();
assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
}
#[test]
fn resolve_backend_for_malformed_id_surfaces_malformed_id() {
let p = parsed_start("no-colon");
let err = resolve_backend(&p).unwrap_err();
assert_eq!(err.code, MxcErrorCode::MalformedId);
}
#[test]
fn resolve_backend_for_session_phases_uses_containment_not_the_id_prefix() {
for operation in [
StateAwareOperation::ProvisionSession(None),
StateAwareOperation::DeprovisionSession {
session_id: SESSION_ID.into(),
},
] {
let parsed = ParsedStateAwareRequest::new(ExecutionRequest::default(), operation);
assert_eq!(resolve_backend(&parsed).unwrap(), ContainmentBackend::Wslc);
}
assert_eq!(
backend_from_prefix("wslcsess").unwrap_err().code,
MxcErrorCode::UnsupportedContainment
);
}
fn parsed_start(id: &str) -> ParsedStateAwareRequest {
ParsedStateAwareRequest::new(
ExecutionRequest::default(),
StateAwareOperation::Start {
sandbox_id: id.into(),
},
)
}
#[test]
fn dispatch_state_aware_asks_for_relayed_stdio() {
let mut b = StubBackend::new();
let _ = dispatch_state_aware(&mut b, bound_runnable_exec("stubd:abc"), false);
assert_eq!(b.exec_calls.get(), 1, "exec should have been reached");
assert_eq!(
b.last_exec_stdio.get(),
Some(ExecStdio::Relayed),
"the relayed path must not ask a backend for caller-owned pipes"
);
}
#[test]
fn dispatch_state_aware_exec_asks_for_piped_stdio() {
let mut b = StubBackend::new();
let _ = dispatch_state_aware_exec(&mut b, bound_runnable_exec("stubd:abc"));
assert_eq!(b.exec_calls.get(), 1, "exec should have been reached");
assert_eq!(
b.last_exec_stdio.get(),
Some(ExecStdio::Piped),
"the streaming path must never let a backend touch the caller's console"
);
}
use crate::mxc_common::state_aware_backend::null_pipe_handle;
use std::io::{Read, Write};
#[cfg(target_os = "windows")]
fn reader_handle(
r: &std::io::PipeReader,
) -> crate::mxc_common::state_aware_backend::PipeHandle {
use std::os::windows::io::AsRawHandle;
windows::Win32::Foundation::HANDLE(r.as_raw_handle() as _)
}
#[cfg(not(target_os = "windows"))]
fn reader_handle(
r: &std::io::PipeReader,
) -> crate::mxc_common::state_aware_backend::PipeHandle {
use std::os::fd::AsRawFd;
r.as_raw_fd()
}
#[test]
fn relay_with_null_handles_returns_waiter_exit_code() {
let handle = ExecHandle {
stdin_closer: None,
stdout: null_pipe_handle(),
stderr: null_pipe_handle(),
stdin: null_pipe_handle(),
waiter: Box::new(|| Ok(ExecOutcome::Exited(42))),
terminator: Box::new(|| Ok(())),
};
assert_eq!(relay_exec_to_stdio(handle).unwrap(), 42);
}
#[test]
fn relay_refuses_a_timeout_rather_than_inventing_an_exit_code() {
let handle = ExecHandle {
stdin_closer: None,
stdout: null_pipe_handle(),
stderr: null_pipe_handle(),
stdin: null_pipe_handle(),
waiter: Box::new(|| Ok(ExecOutcome::TimedOut)),
terminator: Box::new(|| Ok(())),
};
let err = relay_exec_to_stdio(handle).expect_err("the relay cannot represent a timeout");
assert!(
err.message.contains("ExecStdio::Relayed"),
"the refusal should name the contract it is enforcing: {}",
err.message
);
}
#[test]
fn relay_with_null_handles_propagates_waiter_error() {
let handle = ExecHandle {
stdin_closer: None,
stdout: null_pipe_handle(),
stderr: null_pipe_handle(),
stdin: null_pipe_handle(),
waiter: Box::new(|| Err(MxcError::backend_error("waiter blew up"))),
terminator: Box::new(|| Ok(())),
};
let err = relay_exec_to_stdio(handle).unwrap_err();
assert_eq!(err.code, MxcErrorCode::BackendError);
}
#[test]
fn relay_drains_a_real_stdout_pipe_and_returns_exit_code() {
let (mut reader, mut writer) = std::io::pipe().expect("pipe");
writer.write_all(b"relayed-stdout\n").unwrap();
drop(writer);
let handle = ExecHandle {
stdin_closer: None,
stdout: reader_handle(&reader),
stderr: null_pipe_handle(),
stdin: null_pipe_handle(),
waiter: Box::new(|| Ok(ExecOutcome::Exited(3))),
terminator: Box::new(|| Ok(())),
};
assert_eq!(relay_exec_to_stdio(handle).unwrap(), 3);
let mut leftover = Vec::new();
reader.read_to_end(&mut leftover).unwrap();
assert!(
leftover.is_empty(),
"the relay must have consumed the pipe; found {:?}",
String::from_utf8_lossy(&leftover)
);
}
#[test]
fn relay_with_failed_stream_setup_terminates_and_reaps() {
let (tx, rx) = std::sync::mpsc::channel();
let waiter_tx = tx.clone();
let result = relay_prepared_streams(
Err(MxcError::backend_error(
"failed to duplicate the exec stdout pipe handle",
)),
Box::new(move || {
let _ = waiter_tx.send("waiter");
Ok(ExecOutcome::Exited(0))
}),
Box::new(move || {
let _ = tx.send("terminator");
Ok(())
}),
);
let err = result.unwrap_err();
assert_eq!(err.code, MxcErrorCode::BackendError);
assert!(
err.message.contains("stdout"),
"the setup error must survive teardown: {}",
err.message
);
let order: Vec<&str> = rx.try_iter().collect();
assert_eq!(
order,
vec!["terminator", "waiter"],
"the exec must be terminated and then waited for"
);
}
#[test]
fn relay_does_not_invoke_terminator_on_normal_completion() {
let (tx, rx) = std::sync::mpsc::channel();
let handle = ExecHandle {
stdin_closer: None,
stdout: null_pipe_handle(),
stderr: null_pipe_handle(),
stdin: null_pipe_handle(),
waiter: Box::new(|| Ok(ExecOutcome::Exited(0))),
terminator: Box::new(move || {
let _ = tx.send(());
Ok(())
}),
};
assert_eq!(relay_exec_to_stdio(handle).unwrap(), 0);
assert!(
rx.try_recv().is_err(),
"terminator must not fire when the process exited on its own"
);
}
#[test]
fn pump_stream_copies_all_bytes() {
let (src_r, mut src_w) = std::io::pipe().expect("pipe");
let (mut dst_r, dst_w) = std::io::pipe().expect("pipe");
let payload: Vec<u8> = (0..40_000u32).map(|i| (i % 251) as u8).collect();
let expected = payload.clone();
let writer = std::thread::spawn(move || {
src_w.write_all(&payload).unwrap();
drop(src_w);
});
let unmuted = Arc::new(AtomicBool::new(false));
let pump = std::thread::spawn(move || pump_stream(src_r, dst_w, &unmuted));
let mut got = Vec::new();
dst_r.read_to_end(&mut got).unwrap();
writer.join().unwrap();
pump.join().unwrap();
assert_eq!(got.len(), expected.len(), "byte count must match");
assert_eq!(got, expected, "payload must survive the pump intact");
}
#[test]
fn pump_stream_keeps_draining_after_the_destination_fails() {
struct FailsAfterFirstWrite {
writes: usize,
}
impl std::io::Write for FailsAfterFirstWrite {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.writes += 1;
if self.writes > 1 {
return Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"destination gone",
));
}
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
if self.writes > 1 {
return Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"destination gone",
));
}
Ok(())
}
}
let (src_r, mut src_w) = std::io::pipe().expect("pipe");
let unmuted = Arc::new(AtomicBool::new(false));
let pump = std::thread::spawn(move || {
pump_stream(src_r, FailsAfterFirstWrite { writes: 0 }, &unmuted);
});
let chunk = vec![b'x'; 8192];
for _ in 0..16 {
src_w
.write_all(&chunk)
.expect("the pump must keep draining");
}
drop(src_w);
pump.join().expect("pump thread should finish");
}
#[test]
fn relay_starts_pumps_before_waiting() {
struct SignalsOnFirstRead(Option<std::sync::mpsc::Sender<()>>);
impl std::io::Read for SignalsOnFirstRead {
fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
if let Some(tx) = self.0.take() {
let _ = tx.send(());
}
Ok(0) }
}
let (started_tx, started_rx) = std::sync::mpsc::channel();
let streams = RelayStreams {
stdout: Some(Box::new(SignalsOnFirstRead(Some(started_tx.clone())))),
stderr: Some(Box::new(SignalsOnFirstRead(Some(started_tx)))),
};
let waiter = Box::new(move || {
let mut started = 0;
while started < 2 {
if started_rx.recv_timeout(Duration::from_secs(10)).is_err() {
return Err(MxcError::backend_error(format!(
"only {started} of the 2 pumps had started when the waiter began waiting"
)));
}
started += 1;
}
Ok(ExecOutcome::Exited(0))
});
let result = relay_prepared_streams(Ok(streams), waiter, Box::new(|| Ok(())));
assert_eq!(
result.expect("the pumps must be draining while the waiter waits"),
0
);
}
#[test]
fn relay_terminates_before_draining_when_the_waiter_errors() {
let (src_r, src_w) = std::io::pipe().expect("pipe");
let writer = Arc::new(std::sync::Mutex::new(Some(src_w)));
let closer = Arc::clone(&writer);
let terminated = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&terminated);
let started = Instant::now();
let result = relay_prepared_streams(
Ok(RelayStreams {
stdout: Some(Box::new(src_r)),
stderr: None,
}),
Box::new(|| Err(MxcError::backend_error("could not determine the exit"))),
Box::new(move || {
flag.store(true, Ordering::Relaxed);
closer.lock().expect("writer lock").take();
Ok(())
}),
);
let elapsed = started.elapsed();
assert!(
terminated.load(Ordering::Relaxed),
"a waiter error leaves the child possibly alive, so it must be terminated"
);
assert!(
elapsed < POST_EXIT_DRAIN_GRACE / 2,
"the terminator must run before the drain, not after it; took {elapsed:?}"
);
let err = result.unwrap_err();
assert_eq!(err.code, MxcErrorCode::BackendError);
assert!(
err.message.contains("could not determine the exit"),
"the waiter's error must survive teardown: {}",
err.message
);
}
#[test]
fn pump_stream_flushes_before_eof() {
let (src_r, mut src_w) = std::io::pipe().expect("pipe");
let (mut dst_r, dst_w) = std::io::pipe().expect("pipe");
let dst = std::io::BufWriter::with_capacity(64 * 1024, dst_w);
let unmuted = Arc::new(AtomicBool::new(false));
let pump = std::thread::spawn(move || pump_stream(src_r, dst, &unmuted));
src_w.write_all(b"no-newline-yet").unwrap();
src_w.flush().unwrap();
let mut got = [0u8; 14];
dst_r
.read_exact(&mut got)
.expect("partial line must arrive before EOF");
assert_eq!(&got, b"no-newline-yet");
drop(src_w);
pump.join().unwrap();
}
#[test]
fn a_muted_pump_stops_writing_but_keeps_draining() {
let (src_r, mut src_w) = std::io::pipe().expect("pipe");
let (mut dst_r, dst_w) = std::io::pipe().expect("pipe");
let muted = Arc::new(AtomicBool::new(false));
let thread_muted = Arc::clone(&muted);
let pump = std::thread::spawn(move || pump_stream(src_r, dst_w, &thread_muted));
src_w.write_all(b"before").unwrap();
src_w.flush().unwrap();
let mut got = [0u8; 6];
dst_r.read_exact(&mut got).expect("pre-mute output");
assert_eq!(&got, b"before");
muted.store(true, Ordering::Relaxed);
let chunk = vec![b'x'; 8192];
for _ in 0..16 {
src_w
.write_all(&chunk)
.expect("a muted pump must still drain its source");
}
drop(src_w);
pump.join().unwrap();
let mut leftover = Vec::new();
dst_r.read_to_end(&mut leftover).unwrap();
assert!(
leftover.is_empty(),
"a muted pump wrote {} bytes it should have discarded",
leftover.len()
);
}
#[test]
fn abort_relay_terminates_before_draining() {
let (src_r, src_w) = std::io::pipe().expect("pipe");
let (dst_r, dst_w) = std::io::pipe().expect("pipe");
let writer = Arc::new(std::sync::Mutex::new(Some(src_w)));
let closer = Arc::clone(&writer);
let pump = spawn_pump("test-abort-pump", src_r, dst_w).expect("spawn");
let started = Instant::now();
let result = abort_relay(
Box::new(|| Ok(ExecOutcome::Exited(0))),
Box::new(move || {
closer.lock().expect("writer lock").take();
Ok(())
}),
vec![pump],
MxcError::backend_error("stream setup failed"),
);
let elapsed = started.elapsed();
assert!(
elapsed < POST_EXIT_DRAIN_GRACE / 2,
"the terminator must run before the drain, not after it; took {elapsed:?}"
);
let err = result.expect_err("abort_relay must surface the setup error");
assert!(
err.message.contains("stream setup failed"),
"the setup error must survive teardown: {}",
err.message
);
drop(dst_r);
}
#[test]
fn drain_pumps_bounds_the_wait_and_mutes_what_it_abandons() {
let (src_r, src_w) = std::io::pipe().expect("pipe");
let (dst_r, dst_w) = std::io::pipe().expect("pipe");
let pump = spawn_pump("test-endless-pump", src_r, dst_w).expect("spawn");
let muted = Arc::clone(&pump.muted);
let started = Instant::now();
drain_pumps_within(vec![pump], Duration::from_millis(50));
let elapsed = started.elapsed();
assert!(
elapsed < Duration::from_secs(2),
"the drain must give up on an endless pump, took {elapsed:?}"
);
assert!(
muted.load(Ordering::Relaxed),
"an abandoned pump must be muted so it cannot write after the relay returns"
);
drop(src_w);
drop(dst_r);
}
}