use std::collections::{hash_map::Entry, HashMap};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use anyhow::Result;
use tokio::sync::mpsc::error::TrySendError;
use tokio::sync::{mpsc, oneshot};
use mxc_sdk::mxc_common::logger::{Logger, Mode};
use mxc_sdk::mxc_common::models::{FailurePhase, ScriptResponse};
use mxc_sdk::wslc_common::container_steps::{self, OutStream, OutputSink, ProcessSettings};
use mxc_sdk::wslc_common::daemon_protocol::{
DeprovisionConfig, ErrKind, ExecConfig, ExecTerminal, NetworkMode, ProvisionConfig,
StartConfig, StopConfig,
};
use mxc_sdk::wslc_common::image;
use mxc_sdk::wslc_common::policy_mapping;
use mxc_sdk::wslc_common::process_env::EnvScope;
use mxc_sdk::wslc_common::wslc_bindings::{
WslcContainer, WslcContainerGuard, WslcContainerNetworkingMode, WslcSdk, WslcSessionGuard,
};
const SESSION_NAME: &str = "mxc-wslc-daemon";
const PULL_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
fn default_storage_path() -> String {
std::env::temp_dir()
.join("mxc-wslc-sessions")
.to_string_lossy()
.to_string()
}
fn sr_err(resp: ScriptResponse) -> WorkerError {
let err = anyhow::anyhow!(resp.error_message);
match resp.failure_phase {
FailurePhase::BackendUnavailable => WorkerError::Unavailable(err),
FailurePhase::Rejected => WorkerError::Rejected(err),
_ => WorkerError::Backend(err),
}
}
#[derive(Debug)]
pub enum WorkerError {
NotProvisioned(String),
NotStarted(String),
Unavailable(anyhow::Error),
Rejected(anyhow::Error),
Backend(anyhow::Error),
}
impl WorkerError {
pub fn kind(&self) -> ErrKind {
match self {
WorkerError::NotProvisioned(_) => ErrKind::NotProvisioned,
WorkerError::NotStarted(_) => ErrKind::NotStarted,
WorkerError::Unavailable(_) => ErrKind::Unavailable,
WorkerError::Rejected(_) => ErrKind::Rejected,
WorkerError::Backend(_) => ErrKind::Backend,
}
}
}
impl std::fmt::Display for WorkerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
WorkerError::NotProvisioned(id) => write!(f, "unknown sandbox {id}"),
WorkerError::NotStarted(id) => write!(f, "sandbox {id} is not started"),
WorkerError::Unavailable(e) | WorkerError::Rejected(e) | WorkerError::Backend(e) => {
write!(f, "{e:#}")
}
}
}
}
impl std::error::Error for WorkerError {}
impl From<anyhow::Error> for WorkerError {
fn from(e: anyhow::Error) -> Self {
WorkerError::Backend(e)
}
}
pub enum WorkerCommand {
Provision {
config: ProvisionConfig,
reply: oneshot::Sender<Result<String, WorkerError>>,
},
Start {
config: StartConfig,
reply: oneshot::Sender<Result<(), WorkerError>>,
},
Exec {
config: ExecConfig,
sink: OutputSink,
cancellation: Arc<AtomicBool>,
registration: Arc<ExecRegistration>,
admit: oneshot::Sender<Result<(), WorkerError>>,
done: oneshot::Sender<Result<ExecTerminal, WorkerError>>,
},
Stop {
config: StopConfig,
reply: oneshot::Sender<Result<(), WorkerError>>,
},
Deprovision {
config: DeprovisionConfig,
reply: oneshot::Sender<Result<(), WorkerError>>,
},
PullFinished {
token: u64,
outcome: Result<(), ScriptResponse>,
},
Retire {
sandbox_id: String,
reply: oneshot::Sender<()>,
},
ContainerCount { reply: oneshot::Sender<usize> },
Shutdown { reply: oneshot::Sender<()> },
}
pub type OutputChunk = (OutStream, Vec<u8>);
const LIVE_OUTPUT_CHANNEL_CAPACITY: usize = 256;
const LIVE_OUTPUT_MAX_CHUNK_BYTES: usize = 64 * 1024;
fn enqueue_output(
tx: &mpsc::Sender<OutputChunk>,
overflowed: &AtomicBool,
kind: OutStream,
bytes: &[u8],
) {
if overflowed.load(Ordering::Relaxed) {
return;
}
for chunk in bytes.chunks(LIVE_OUTPUT_MAX_CHUNK_BYTES) {
match tx.try_send((kind, chunk.to_vec())) {
Ok(()) => {}
Err(TrySendError::Full(_)) => {
overflowed.store(true, Ordering::Relaxed);
return;
}
Err(TrySendError::Closed(_)) => return,
}
}
}
#[derive(Debug)]
pub struct ExecStream {
pub done: oneshot::Receiver<Result<ExecTerminal, WorkerError>>,
pub output: mpsc::Receiver<OutputChunk>,
pub overflowed: Arc<AtomicBool>,
pub(crate) registration: Arc<ExecRegistration>,
}
pub(crate) type ActiveExecs = Arc<Mutex<HashMap<String, ActiveExec>>>;
#[derive(Debug)]
pub(crate) struct ActiveExec {
run_token: String,
cancellation: Weak<AtomicBool>,
}
#[derive(Debug)]
pub(crate) struct ExecRegistration {
exec_id: String,
run_token: String,
active_execs: ActiveExecs,
cancellation: Arc<AtomicBool>,
}
impl Drop for ExecRegistration {
fn drop(&mut self) {
let mut active_execs = self
.active_execs
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if active_execs.get(&self.exec_id).is_some_and(|current| {
current.run_token == self.run_token
&& current
.cancellation
.ptr_eq(&Arc::downgrade(&self.cancellation))
}) {
active_execs.remove(&self.exec_id);
}
}
}
pub(crate) fn register_exec(
active_execs: &ActiveExecs,
exec_id: &str,
run_token: &str,
cancellation: &Arc<AtomicBool>,
) -> Result<ExecRegistration, WorkerError> {
let active_exec = ActiveExec {
run_token: run_token.to_string(),
cancellation: Arc::downgrade(cancellation),
};
let mut active_execs_guard = active_execs
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
match active_execs_guard.entry(exec_id.to_string()) {
Entry::Occupied(mut entry) if entry.get().cancellation.upgrade().is_none() => {
entry.insert(active_exec);
}
Entry::Occupied(_) => {
return Err(WorkerError::Rejected(anyhow::anyhow!(
"exec id {exec_id:?} is already active"
)));
}
Entry::Vacant(entry) => {
entry.insert(active_exec);
}
}
drop(active_execs_guard);
Ok(ExecRegistration {
exec_id: exec_id.to_string(),
run_token: run_token.to_string(),
active_execs: Arc::clone(active_execs),
cancellation: Arc::clone(cancellation),
})
}
#[derive(Clone)]
pub struct SessionHandle {
tx: mpsc::UnboundedSender<WorkerCommand>,
active_execs: ActiveExecs,
}
impl SessionHandle {
pub async fn provision(&self, config: ProvisionConfig) -> Result<String, WorkerError> {
let (reply, rx) = oneshot::channel();
self.send(WorkerCommand::Provision { config, reply })?;
rx.await.map_err(worker_gone)?
}
pub async fn start(&self, config: StartConfig) -> Result<(), WorkerError> {
let (reply, rx) = oneshot::channel();
self.send(WorkerCommand::Start { config, reply })?;
rx.await.map_err(worker_gone)?
}
pub async fn exec(&self, config: ExecConfig) -> Result<ExecStream, WorkerError> {
let (admit, admit_rx) = oneshot::channel();
let (done, done_rx) = oneshot::channel();
let (stream_tx, output) = mpsc::channel::<OutputChunk>(LIVE_OUTPUT_CHANNEL_CAPACITY);
let overflowed = Arc::new(AtomicBool::new(false));
let sink_overflowed = Arc::clone(&overflowed);
let sink: OutputSink = Box::new(move |kind, bytes| {
enqueue_output(&stream_tx, &sink_overflowed, kind, bytes);
});
let cancellation = Arc::new(AtomicBool::new(false));
let registration = Arc::new(register_exec(
&self.active_execs,
&config.exec_id,
&config.run_token,
&cancellation,
)?);
self.send(WorkerCommand::Exec {
config,
sink,
cancellation,
registration: Arc::clone(®istration),
admit,
done,
})?;
admit_rx.await.map_err(worker_gone)??;
Ok(ExecStream {
done: done_rx,
output,
overflowed,
registration,
})
}
pub fn cancel_exec(&self, exec_id: &str, run_token: &str) {
if let Some(cancellation) = self
.active_execs
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(exec_id)
.filter(|current| current.run_token == run_token)
.and_then(|current| current.cancellation.upgrade())
{
cancellation.store(true, Ordering::Release);
}
}
pub async fn stop(&self, config: StopConfig) -> Result<(), WorkerError> {
let (reply, rx) = oneshot::channel();
self.send(WorkerCommand::Stop { config, reply })?;
rx.await.map_err(worker_gone)?
}
pub async fn deprovision(&self, config: DeprovisionConfig) -> Result<(), WorkerError> {
let (reply, rx) = oneshot::channel();
self.send(WorkerCommand::Deprovision { config, reply })?;
rx.await.map_err(worker_gone)?
}
pub async fn container_count(&self) -> Result<usize, WorkerError> {
let (reply, rx) = oneshot::channel();
self.send(WorkerCommand::ContainerCount { reply })?;
rx.await.map_err(worker_gone)
}
pub async fn retire(&self, sandbox_id: String) -> Result<(), WorkerError> {
let (reply, rx) = oneshot::channel();
self.send(WorkerCommand::Retire { sandbox_id, reply })?;
rx.await.map_err(worker_gone)
}
pub async fn shutdown(&self) -> Result<(), WorkerError> {
let (reply, rx) = oneshot::channel();
self.send(WorkerCommand::Shutdown { reply })?;
rx.await.map_err(worker_gone)
}
fn send(&self, cmd: WorkerCommand) -> Result<(), WorkerError> {
self.tx
.send(cmd)
.map_err(|_| WorkerError::Backend(anyhow::anyhow!("WSLc worker thread is gone")))
}
}
fn worker_gone(_e: oneshot::error::RecvError) -> WorkerError {
WorkerError::Backend(anyhow::anyhow!("WSLc worker dropped the reply channel"))
}
struct ContainerEntry {
started: bool,
quarantined: bool,
retired: bool,
container: WslcContainerGuard,
}
struct PendingProvision {
config: ProvisionConfig,
reply: oneshot::Sender<Result<String, WorkerError>>,
_retire_deadline: std::sync::mpsc::Sender<()>,
}
struct Worker {
logger: Logger,
containers: HashMap<String, ContainerEntry>,
pending: HashMap<u64, PendingProvision>,
next_pull_token: u64,
session: Option<WslcSessionGuard>,
sdk: Option<WslcSdk>,
}
impl Worker {
fn new() -> Self {
Self {
logger: Logger::new(Mode::Console),
sdk: None,
session: None,
containers: HashMap::new(),
pending: HashMap::new(),
next_pull_token: 0,
}
}
fn ensure_session(&mut self) -> Result<(), WorkerError> {
if self.sdk.is_none() {
let sdk =
unsafe { container_steps::load_sdk_checked(&mut self.logger) }.map_err(sr_err)?;
self.sdk = Some(sdk);
}
if self.session.is_none() {
let storage = default_storage_path();
let sdk = self.sdk.as_ref().expect("sdk loaded above");
let session = unsafe {
container_steps::create_daemon_session(
sdk,
SESSION_NAME,
&storage,
&mut self.logger,
)
}
.map_err(sr_err)?;
self.session = Some(session);
}
Ok(())
}
fn begin_provision(
&mut self,
config: ProvisionConfig,
reply: oneshot::Sender<Result<String, WorkerError>>,
worker: &mpsc::UnboundedSender<WorkerCommand>,
) {
if let Err(e) = self.ensure_session() {
let _ = reply.send(Err(e));
return;
}
let sdk = self.sdk.as_ref().expect("session ensured");
let session = self.session.as_ref().expect("session ensured").as_raw();
let step = unsafe {
image::begin_resolve(
sdk,
session,
&config.image,
config.image_tar_path.as_deref(),
None,
match config.network {
NetworkMode::None => image::RegistryAccess::Denied,
NetworkMode::Bridged => image::RegistryAccess::Allowed,
},
"[WSLC][daemon]",
&mut self.logger,
)
};
let step = match step {
Ok(step) => step,
Err(e) => {
let _ = reply.send(Err(sr_err(e)));
return;
}
};
match step {
image::ImageStep::Ready => {
let _ = reply.send(self.create_provisioned_container(&config));
}
image::ImageStep::Pull => {
let token = self.next_pull_token;
self.next_pull_token += 1;
let done = worker.clone();
let started = unsafe {
image::start_pull(
sdk,
session,
&config.image,
None,
"[WSLC][daemon]",
move |outcome| {
let _ = done.send(WorkerCommand::PullFinished { token, outcome });
},
)
};
if let Err(e) = started {
let _ = reply.send(Err(sr_err(e)));
return;
}
let budget = image::daemon_pull_budget();
let image_name = config.image.clone();
let expired = worker.clone();
let (retire_deadline, retired) = std::sync::mpsc::channel::<()>();
let armed = std::thread::Builder::new()
.name("wslc-pull-deadline".to_string())
.spawn(move || {
if retired.recv_timeout(budget)
!= Err(std::sync::mpsc::RecvTimeoutError::Timeout)
{
return;
}
let _ = expired.send(WorkerCommand::PullFinished {
token,
outcome: Err(image::pull_deadline_expired(&image_name, budget)),
});
});
if armed.is_err() {
let _ = reply.send(Err(WorkerError::Backend(anyhow::anyhow!(
"could not arm the pull deadline for image '{}'",
config.image
))));
return;
}
self.pending.insert(
token,
PendingProvision {
config,
reply,
_retire_deadline: retire_deadline,
},
);
}
}
}
fn finish_provision(&mut self, token: u64, outcome: Result<(), ScriptResponse>) {
let Some(PendingProvision {
config,
reply,
_retire_deadline: _,
}) = self.pending.remove(&token)
else {
return;
};
if let Err(e) = outcome {
let _ = reply.send(Err(sr_err(e)));
return;
}
let sdk = self.sdk.as_ref().expect("session ensured");
let session = self.session.as_ref().expect("session ensured").as_raw();
if let Err(e) = unsafe {
image::report_pulled_digest(
sdk,
session,
&config.image,
"[WSLC][daemon]",
&mut self.logger,
)
} {
let _ = reply.send(Err(sr_err(e)));
return;
}
let _ = reply.send(self.create_provisioned_container(&config));
}
fn create_provisioned_container(
&mut self,
config: &ProvisionConfig,
) -> Result<String, WorkerError> {
let sdk = self.sdk.as_ref().expect("session ensured");
let session = self.session.as_ref().expect("session ensured").as_raw();
let mounts: Vec<policy_mapping::VolumeMount> = config
.volumes
.iter()
.map(|v| policy_mapping::VolumeMount {
windows_path: v.host.clone(),
container_path: v.container.clone(),
read_only: v.read_only,
})
.collect();
let net_mode = match config.network {
NetworkMode::None => WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_NONE,
NetworkMode::Bridged => {
WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_BRIDGED
}
};
let container = unsafe {
let mut keepalive = ProcessSettings::build_detached(
sdk,
container_steps::KEEPALIVE_SCRIPT,
&[],
EnvScope::Merge,
"",
)
.map_err(sr_err)?;
container_steps::create_daemon_container(
sdk,
session,
&config.image,
&mounts,
net_mode,
&mut keepalive,
&mut self.logger,
)
.map_err(sr_err)?
};
let sandbox_id = format!("wslc:{}", uuid::Uuid::new_v4().simple());
self.containers.insert(
sandbox_id.clone(),
ContainerEntry {
started: false,
quarantined: false,
retired: false,
container,
},
);
Ok(sandbox_id)
}
fn start(&mut self, config: StartConfig) -> Result<(), WorkerError> {
if !self.containers.contains_key(&config.sandbox_id) {
return Err(WorkerError::NotProvisioned(config.sandbox_id));
}
let sdk = self
.sdk
.as_ref()
.ok_or_else(|| anyhow::anyhow!("no active WSLc session"))?;
let entry = self
.containers
.get_mut(&config.sandbox_id)
.expect("checked above");
if entry.quarantined {
return Err(WorkerError::Backend(anyhow::anyhow!(
"sandbox {} is quarantined after an exec whose termination could not be \
confirmed; deprovision it before reuse",
config.sandbox_id
)));
}
unsafe {
container_steps::start_daemon_container(sdk, entry.container.as_raw(), &mut self.logger)
}
.map_err(sr_err)?;
entry.started = true;
Ok(())
}
fn validate_exec(&self, sandbox_id: &str) -> Result<WslcContainer, WorkerError> {
match self.containers.get(sandbox_id) {
None => Err(WorkerError::NotProvisioned(sandbox_id.to_string())),
Some(entry) if entry.quarantined => Err(WorkerError::Backend(anyhow::anyhow!(
"sandbox {sandbox_id} is quarantined after an exec whose termination could not \
be confirmed; deprovision it before reuse"
))),
Some(entry) if !entry.started => Err(WorkerError::NotStarted(sandbox_id.to_string())),
Some(entry) => Ok(entry.container.as_raw()),
}
}
fn exec(
&mut self,
config: ExecConfig,
container: WslcContainer,
sink: OutputSink,
cancellation: &AtomicBool,
) -> Result<ExecTerminal, WorkerError> {
let sdk = self
.sdk
.as_ref()
.ok_or_else(|| anyhow::anyhow!("no active WSLc session"))?;
let env: Vec<String> = config
.env
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect();
let outcome = unsafe {
container_steps::exec_in_container(
sdk,
container,
&config.script_code,
&env,
config.env_scope,
&config.working_directory,
config.timeout_ms,
cancellation,
Some(sink),
&mut self.logger,
)
}
.map_err(sr_err)?;
match outcome.completion {
container_steps::ProcessCompletion::TerminationUnconfirmed => {
let detail = outcome
.post_launch_error
.map(|error| error.error_message)
.unwrap_or_else(|| "process termination could not be confirmed".to_string());
Err(self.quarantine(&config.sandbox_id, container, &detail))
}
container_steps::ProcessCompletion::Confirmed(terminal) => Ok(terminal),
}
}
fn quarantine(
&mut self,
sandbox_id: &str,
container: WslcContainer,
detail: &str,
) -> WorkerError {
let delete_result = self.sdk.as_ref().map(|sdk| {
unsafe { container_steps::delete_daemon_container(sdk, container, &mut self.logger) }
});
match delete_result {
Some(Ok(())) => {
self.containers.remove(sandbox_id);
WorkerError::Backend(anyhow::anyhow!(
"exec on sandbox {sandbox_id} could not be confirmed terminated ({detail}); \
the container was quarantined and deleted"
))
}
Some(Err(delete_error)) => {
if let Some(entry) = self.containers.get_mut(sandbox_id) {
entry.quarantined = true;
}
WorkerError::Backend(anyhow::anyhow!(
"exec on sandbox {sandbox_id} could not be confirmed terminated ({detail}); \
quarantine deletion failed and the sandbox remains blocked until \
deprovision succeeds: {}",
delete_error.error_message
))
}
None => {
if let Some(entry) = self.containers.get_mut(sandbox_id) {
entry.quarantined = true;
}
WorkerError::Backend(anyhow::anyhow!(
"exec on sandbox {sandbox_id} could not be confirmed terminated ({detail}); \
the sandbox remains quarantined because no active WSLc SDK is available"
))
}
}
}
fn stop(&mut self, config: StopConfig) -> Result<(), WorkerError> {
if !self.containers.contains_key(&config.sandbox_id) {
return Err(WorkerError::NotProvisioned(config.sandbox_id));
}
let sdk = self
.sdk
.as_ref()
.ok_or_else(|| anyhow::anyhow!("no active WSLc session"))?;
let entry = self
.containers
.get_mut(&config.sandbox_id)
.expect("checked above");
unsafe {
container_steps::stop_daemon_container(sdk, entry.container.as_raw(), &mut self.logger)
}
.map_err(sr_err)?;
entry.started = false;
Ok(())
}
fn retire(&mut self, sandbox_id: &str) {
if let Some(entry) = self.containers.get_mut(sandbox_id) {
entry.retired = true;
}
}
fn live_container_count(&self) -> usize {
self.containers.values().filter(|e| !e.retired).count() + self.pending.len()
}
fn deprovision(&mut self, config: DeprovisionConfig) -> Result<(), WorkerError> {
let container_raw = match self.containers.get(&config.sandbox_id) {
Some(e) => e.container.as_raw(),
None => return Err(WorkerError::NotProvisioned(config.sandbox_id)),
};
if let Some(sdk) = self.sdk.as_ref() {
unsafe {
container_steps::delete_daemon_container(sdk, container_raw, &mut self.logger)
}
.map_err(sr_err)?;
}
self.containers.remove(&config.sandbox_id);
Ok(())
}
fn shutdown(&mut self) {
for (_, pending) in self.pending.drain() {
let _ = pending.reply.send(Err(WorkerError::Backend(anyhow::anyhow!(
"the WSLc daemon shut down while pulling image '{}'",
pending.config.image
))));
}
if let Some(sdk) = self.sdk.as_ref() {
for (_, entry) in self.containers.drain() {
unsafe {
if entry.started {
let _ = container_steps::stop_daemon_container(
sdk,
entry.container.as_raw(),
&mut self.logger,
);
}
let _ = container_steps::delete_daemon_container(
sdk,
entry.container.as_raw(),
&mut self.logger,
);
}
}
} else {
self.containers.clear();
}
if !image::wait_for_pulls_in_flight(PULL_DRAIN_TIMEOUT) {
self.logger.log_line(
"a WSLC image pull is still running; leaking the session rather than \
releasing a handle it is using",
);
std::mem::forget(self.session.take());
std::mem::forget(self.sdk.take());
return;
}
self.session = None;
self.sdk = None;
}
}
pub fn spawn() -> Result<SessionHandle> {
let (tx, mut rx) = mpsc::unbounded_channel::<WorkerCommand>();
let active_execs = Arc::new(Mutex::new(HashMap::new()));
let worker_tx = tx.clone();
std::thread::Builder::new()
.name("wslc-session-worker".to_string())
.spawn(move || {
#[cfg(windows)]
let _com = match ComApartment::enter() {
Ok(com) => com,
Err(e) => {
eprintln!("[wslc-daemon] worker COM initialisation failed: {e:#}");
return;
}
};
let mut worker = Worker::new();
while let Some(cmd) = rx.blocking_recv() {
match cmd {
WorkerCommand::Provision { config, reply } => {
worker.begin_provision(config, reply, &worker_tx);
}
WorkerCommand::PullFinished { token, outcome } => {
worker.finish_provision(token, outcome);
}
WorkerCommand::Start { config, reply } => {
let _ = reply.send(worker.start(config));
}
WorkerCommand::Exec {
config,
sink,
cancellation,
registration: _registration,
admit,
done,
} => {
match worker.validate_exec(&config.sandbox_id) {
Err(e) => {
let _ = admit.send(Err(e));
}
Ok(_) if cancellation.load(Ordering::Acquire) => {
if admit.send(Ok(())).is_ok() {
let _ = done.send(Ok(ExecTerminal::Cancelled));
}
}
Ok(container) if admit.send(Ok(())).is_ok() => {
let sandbox_id = config.sandbox_id.clone();
let outcome = worker.exec(config, container, sink, &cancellation);
if let Err(orphaned) = done.send(outcome) {
worker.logger.log_line(&format!(
"exec on {sandbox_id} completed after the client \
disconnected; orphaned result: {orphaned:?}"
));
}
}
Ok(_) => {}
}
}
WorkerCommand::Stop { config, reply } => {
let _ = reply.send(worker.stop(config));
}
WorkerCommand::Deprovision { config, reply } => {
let _ = reply.send(worker.deprovision(config));
}
WorkerCommand::Retire { sandbox_id, reply } => {
worker.retire(&sandbox_id);
let _ = reply.send(());
}
WorkerCommand::ContainerCount { reply } => {
let _ = reply.send(worker.live_container_count());
}
WorkerCommand::Shutdown { reply } => {
worker.shutdown();
let _ = reply.send(());
break;
}
}
}
})
.map_err(|e| anyhow::anyhow!("spawn WSLc worker thread: {e}"))?;
Ok(SessionHandle { tx, active_execs })
}
#[cfg(windows)]
struct ComApartment;
#[cfg(windows)]
impl ComApartment {
fn enter() -> Result<Self> {
use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED};
let hr = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
if hr.is_err() {
anyhow::bail!("CoInitializeEx(MTA) failed: {hr:?}");
}
Ok(Self)
}
}
#[cfg(windows)]
impl Drop for ComApartment {
fn drop(&mut self) {
use windows::Win32::System::Com::CoUninitialize;
unsafe {
CoUninitialize();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn count(handle: &SessionHandle) -> usize {
handle.container_count().await.unwrap()
}
fn test_entry(retired: bool) -> ContainerEntry {
unsafe extern "C" fn release_noop(
_: mxc_sdk::wslc_common::wslc_bindings::WslcContainer,
) -> i32 {
0
}
let sentinel = std::ptr::dangling_mut();
ContainerEntry {
started: false,
quarantined: false,
retired,
container: unsafe { WslcContainerGuard::from_raw(sentinel, release_noop) },
}
}
#[test]
fn a_pull_that_lands_first_retires_its_deadline_thread() {
let (retire_deadline, retired) = std::sync::mpsc::channel::<()>();
let woke = std::thread::spawn(move || {
retired.recv_timeout(Duration::from_secs(30))
== Err(std::sync::mpsc::RecvTimeoutError::Disconnected)
});
drop(retire_deadline);
assert!(
woke.join().expect("timer thread"),
"dropping the parked provision must wake its deadline immediately"
);
}
#[test]
fn a_pending_pull_keeps_the_daemon_alive() {
let mut worker = Worker::new();
assert_eq!(worker.live_container_count(), 0);
let (reply, _rx) = oneshot::channel();
worker.pending.insert(
7,
PendingProvision {
config: ProvisionConfig {
image: "alpine:latest".to_string(),
image_tar_path: None,
volumes: Vec::new(),
network: Default::default(),
},
reply,
_retire_deadline: std::sync::mpsc::channel().0,
},
);
assert_eq!(
worker.live_container_count(),
1,
"a provision still waiting on its image must hold the daemon open"
);
}
#[test]
fn only_the_first_report_of_a_pull_answers_the_client() {
let mut worker = Worker::new();
let (reply, mut rx) = oneshot::channel();
worker.pending.insert(
3,
PendingProvision {
config: ProvisionConfig {
image: "alpine:latest".to_string(),
image_tar_path: None,
volumes: Vec::new(),
network: Default::default(),
},
reply,
_retire_deadline: std::sync::mpsc::channel().0,
},
);
worker.finish_provision(
3,
Err(image::pull_deadline_expired(
"alpine:latest",
PULL_DRAIN_TIMEOUT,
)),
);
assert!(rx.try_recv().is_ok(), "the first report answers the client");
worker.finish_provision(3, Ok(()));
assert_eq!(worker.live_container_count(), 0);
}
#[test]
fn a_retired_sandbox_stops_holding_the_daemon_open() {
let mut worker = Worker::new();
worker
.containers
.insert("wslc:orphan".to_string(), test_entry(false));
assert_eq!(worker.live_container_count(), 1);
worker.retire("wslc:orphan");
assert_eq!(
worker.live_container_count(),
0,
"a retired sandbox must not keep the daemon alive"
);
assert!(
worker.containers.contains_key("wslc:orphan"),
"the handle stays so shutdown can still delete the container"
);
}
#[test]
fn retiring_one_sandbox_leaves_the_others_counted() {
let mut worker = Worker::new();
worker
.containers
.insert("wslc:orphan".to_string(), test_entry(false));
worker
.containers
.insert("wslc:live".to_string(), test_entry(false));
worker.retire("wslc:orphan");
assert_eq!(worker.live_container_count(), 1);
}
#[test]
fn retiring_an_unknown_sandbox_is_a_no_op() {
let mut worker = Worker::new();
worker.retire("wslc:never-existed");
assert_eq!(worker.live_container_count(), 0);
}
#[test]
fn sr_err_carries_the_step_failure_phase() {
for (phase, expected) in [
(FailurePhase::BackendUnavailable, ErrKind::Unavailable),
(FailurePhase::Rejected, ErrKind::Rejected),
(FailurePhase::LaunchFailed, ErrKind::Backend),
(FailurePhase::PostLaunchFailed, ErrKind::Backend),
(FailurePhase::None, ErrKind::Backend),
] {
let resp = ScriptResponse {
exit_code: -1,
error_message: "boom".to_string(),
failure_phase: phase.clone(),
..Default::default()
};
assert_eq!(sr_err(resp).kind(), expected, "phase {phase:?}");
}
}
#[test]
fn sr_err_preserves_the_step_message() {
let resp = ScriptResponse {
exit_code: -1,
error_message: "WSLc components are missing".to_string(),
failure_phase: FailurePhase::BackendUnavailable,
..Default::default()
};
assert_eq!(sr_err(resp).to_string(), "WSLc components are missing");
}
#[tokio::test]
async fn start_unknown_sandbox_errors() {
let handle = spawn().unwrap();
let err = handle
.start(StartConfig {
sandbox_id: "wslc:does-not-exist".to_string(),
})
.await
.unwrap_err();
assert!(err.to_string().contains("unknown sandbox"));
handle.shutdown().await.unwrap();
}
#[tokio::test]
async fn exec_unknown_sandbox_errors() {
let handle = spawn().unwrap();
let err = handle
.exec(ExecConfig {
exec_id: "unknown-1".to_string(),
run_token: "run-unknown-1".to_string(),
sandbox_id: "wslc:does-not-exist".to_string(),
script_code: "echo hi".to_string(),
working_directory: String::new(),
env: Vec::new(),
env_scope: EnvScope::Merge,
timeout_ms: 0,
})
.await
.unwrap_err();
assert!(err.to_string().contains("unknown sandbox"));
handle.shutdown().await.unwrap();
}
#[tokio::test]
async fn stop_unknown_sandbox_errors() {
let handle = spawn().unwrap();
let err = handle
.stop(StopConfig {
sandbox_id: "wslc:does-not-exist".to_string(),
})
.await
.unwrap_err();
assert!(err.to_string().contains("unknown sandbox"));
handle.shutdown().await.unwrap();
}
#[tokio::test]
async fn deprovision_unknown_sandbox_errors() {
let handle = spawn().unwrap();
let err = handle
.deprovision(DeprovisionConfig {
sandbox_id: "wslc:does-not-exist".to_string(),
})
.await
.unwrap_err();
assert!(err.to_string().contains("unknown sandbox"));
assert_eq!(count(&handle).await, 0);
handle.shutdown().await.unwrap();
}
#[tokio::test]
async fn unknown_sandbox_maps_to_not_provisioned_kind() {
let handle = spawn().unwrap();
let err = handle
.start(StartConfig {
sandbox_id: "wslc:does-not-exist".to_string(),
})
.await
.unwrap_err();
assert_eq!(err.kind(), ErrKind::NotProvisioned);
handle.shutdown().await.unwrap();
}
#[tokio::test]
async fn exec_unknown_sandbox_admission_is_not_provisioned() {
let handle = spawn().unwrap();
let err = handle
.exec(ExecConfig {
exec_id: "unknown-2".to_string(),
run_token: "run-unknown-2".to_string(),
sandbox_id: "wslc:does-not-exist".to_string(),
script_code: "echo hi".to_string(),
working_directory: String::new(),
env: Vec::new(),
env_scope: EnvScope::Merge,
timeout_ms: 0,
})
.await
.unwrap_err();
assert_eq!(err.kind(), ErrKind::NotProvisioned);
handle.shutdown().await.unwrap();
}
#[test]
fn cancel_exec_marks_the_registered_run() {
let (tx, _rx) = mpsc::unbounded_channel();
let cancellation = Arc::new(AtomicBool::new(false));
let active_execs = Arc::new(Mutex::new(HashMap::from([(
"exec-1".to_string(),
ActiveExec {
run_token: "run-1".to_string(),
cancellation: Arc::downgrade(&cancellation),
},
)])));
let handle = SessionHandle { tx, active_execs };
handle.cancel_exec("exec-1", "run-1");
assert!(cancellation.load(Ordering::Acquire));
}
#[test]
fn delayed_cancellation_does_not_target_reused_exec_id() {
let (tx, _rx) = mpsc::unbounded_channel();
let cancellation = Arc::new(AtomicBool::new(false));
let active_execs = Arc::new(Mutex::new(HashMap::new()));
let registration =
register_exec(&active_execs, "exec-1", "replacement-run", &cancellation).unwrap();
let handle = SessionHandle { tx, active_execs };
handle.cancel_exec("exec-1", "completed-run");
assert!(!cancellation.load(Ordering::Acquire));
handle.cancel_exec("exec-1", "replacement-run");
assert!(cancellation.load(Ordering::Acquire));
drop(registration);
}
#[test]
fn duplicate_live_exec_id_is_rejected_without_replacing_registration() {
let active_execs = Arc::new(Mutex::new(HashMap::new()));
let first = Arc::new(AtomicBool::new(false));
let second = Arc::new(AtomicBool::new(false));
let registration = register_exec(&active_execs, "exec-1", "run-1", &first).unwrap();
let error = register_exec(&active_execs, "exec-1", "run-2", &second).unwrap_err();
assert_eq!(error.kind(), ErrKind::Rejected);
let registered = active_execs
.lock()
.unwrap()
.get("exec-1")
.and_then(|entry| entry.cancellation.upgrade())
.unwrap();
assert!(Arc::ptr_eq(®istered, &first));
drop(registration);
}
#[test]
fn stale_exec_id_can_be_registered_again() {
let stale = Arc::new(AtomicBool::new(false));
let active_execs = Arc::new(Mutex::new(HashMap::from([(
"exec-1".to_string(),
ActiveExec {
run_token: "stale-run".to_string(),
cancellation: Arc::downgrade(&stale),
},
)])));
drop(stale);
let cancellation = Arc::new(AtomicBool::new(false));
let registration =
register_exec(&active_execs, "exec-1", "replacement-run", &cancellation).unwrap();
let registered = active_execs
.lock()
.unwrap()
.get("exec-1")
.and_then(|entry| entry.cancellation.upgrade())
.unwrap();
assert!(Arc::ptr_eq(®istered, &cancellation));
drop(registration);
assert!(!active_execs.lock().unwrap().contains_key("exec-1"));
}
#[test]
fn older_registration_does_not_remove_replacement() {
let active_execs = Arc::new(Mutex::new(HashMap::new()));
let first = Arc::new(AtomicBool::new(false));
let first_registration = register_exec(&active_execs, "exec-1", "run-1", &first).unwrap();
let second = Arc::new(AtomicBool::new(false));
active_execs.lock().unwrap().insert(
"exec-1".to_string(),
ActiveExec {
run_token: "run-2".to_string(),
cancellation: Arc::downgrade(&second),
},
);
drop(first_registration);
let registered = active_execs
.lock()
.unwrap()
.get("exec-1")
.and_then(|entry| entry.cancellation.upgrade())
.unwrap();
assert!(Arc::ptr_eq(®istered, &second));
}
#[test]
fn cancelling_unknown_or_stale_exec_id_is_a_no_op() {
let (tx, _rx) = mpsc::unbounded_channel();
let stale = Arc::new(AtomicBool::new(false));
let active_execs = Arc::new(Mutex::new(HashMap::from([(
"stale".to_string(),
ActiveExec {
run_token: "stale-run".to_string(),
cancellation: Arc::downgrade(&stale),
},
)])));
drop(stale);
let handle = SessionHandle { tx, active_execs };
handle.cancel_exec("unknown", "unknown-run");
handle.cancel_exec("stale", "stale-run");
}
#[tokio::test]
async fn large_callback_split_into_frame_safe_chunks() {
use mxc_sdk::wslc_common::daemon_protocol::{encode_frame, StreamFrame, MAX_FRAME_SIZE};
let (tx, mut rx) = mpsc::channel::<OutputChunk>(LIVE_OUTPUT_CHANNEL_CAPACITY);
let payload = vec![b'x'; LIVE_OUTPUT_MAX_CHUNK_BYTES * 3 + 7];
let producer = tokio::task::spawn_blocking({
let payload = payload.clone();
move || {
let overflowed = AtomicBool::new(false);
enqueue_output(&tx, &overflowed, OutStream::Stdout, &payload)
}
});
let mut reassembled = Vec::new();
let mut chunks = 0usize;
while let Some((kind, data)) = rx.recv().await {
assert_eq!(kind, OutStream::Stdout);
assert!(data.len() <= LIVE_OUTPUT_MAX_CHUNK_BYTES);
let encoded = encode_frame(&StreamFrame::Stdout { data: data.clone() }).unwrap();
assert!(encoded.len() <= MAX_FRAME_SIZE);
reassembled.extend_from_slice(&data);
chunks += 1;
}
producer.await.unwrap();
assert_eq!(reassembled, payload);
assert!(
chunks >= 4,
"expected the callback to be split, got {chunks}"
);
}
#[tokio::test]
#[ignore = "requires a WSL2 host with alpine:latest already in the daemon session cache"]
async fn full_lifecycle_on_wsl_host() {
let handle = spawn().unwrap();
assert_eq!(count(&handle).await, 0);
let id = handle
.provision(ProvisionConfig {
image: "alpine:latest".to_string(),
image_tar_path: None,
volumes: Vec::new(),
network: Default::default(),
})
.await
.unwrap();
assert_eq!(count(&handle).await, 1);
handle
.start(StartConfig {
sandbox_id: id.clone(),
})
.await
.unwrap();
let mut exec = handle
.exec(ExecConfig {
exec_id: "full-lifecycle".to_string(),
run_token: "full-lifecycle-run".to_string(),
sandbox_id: id.clone(),
script_code: "echo hi".to_string(),
working_directory: String::new(),
env: Vec::new(),
env_scope: EnvScope::Merge,
timeout_ms: 30_000,
})
.await
.unwrap();
let mut stdout = Vec::new();
while let Some((kind, data)) = exec.output.recv().await {
if kind == OutStream::Stdout {
stdout.extend_from_slice(&data);
}
}
let code = exec.done.await.unwrap().unwrap();
assert_eq!(code, ExecTerminal::Exited(0));
assert_eq!(String::from_utf8_lossy(&stdout).trim(), "hi");
handle
.stop(StopConfig {
sandbox_id: id.clone(),
})
.await
.unwrap();
handle
.deprovision(DeprovisionConfig { sandbox_id: id })
.await
.unwrap();
assert_eq!(count(&handle).await, 0);
handle.shutdown().await.unwrap();
}
#[tokio::test]
#[ignore = "requires a WSL2 host with alpine:latest already in the daemon session cache"]
async fn cancelled_queued_exec_never_starts_process() {
let handle = spawn().unwrap();
let id = handle
.provision(ProvisionConfig {
image: "alpine:latest".to_string(),
image_tar_path: None,
volumes: Vec::new(),
network: Default::default(),
})
.await
.unwrap();
handle
.start(StartConfig {
sandbox_id: id.clone(),
})
.await
.unwrap();
let blocker = handle
.exec(ExecConfig {
exec_id: "queue-blocker".to_string(),
run_token: "queue-blocker-run".to_string(),
sandbox_id: id.clone(),
script_code: "sleep 2".to_string(),
working_directory: String::new(),
env: Vec::new(),
env_scope: EnvScope::Merge,
timeout_ms: 30_000,
})
.await
.unwrap();
let queued_handle = handle.clone();
let queued_id = id.clone();
let queued = tokio::spawn(async move {
queued_handle
.exec(ExecConfig {
exec_id: "cancelled-queued".to_string(),
run_token: "cancelled-queued-run".to_string(),
sandbox_id: queued_id,
script_code: "touch /tmp/mxc-cancelled-queued-marker".to_string(),
working_directory: String::new(),
env: Vec::new(),
env_scope: EnvScope::Merge,
timeout_ms: 30_000,
})
.await
});
for _ in 0..100 {
if handle
.active_execs
.lock()
.unwrap()
.contains_key("cancelled-queued")
{
break;
}
tokio::task::yield_now().await;
}
assert!(
handle
.active_execs
.lock()
.unwrap()
.contains_key("cancelled-queued"),
"queued exec was not registered"
);
handle.cancel_exec("cancelled-queued", "cancelled-queued-run");
assert_eq!(
blocker.done.await.unwrap().unwrap(),
ExecTerminal::Exited(0)
);
let queued = queued.await.unwrap().unwrap();
assert_eq!(queued.done.await.unwrap().unwrap(), ExecTerminal::Cancelled);
let marker_check = handle
.exec(ExecConfig {
exec_id: "marker-check".to_string(),
run_token: "marker-check-run".to_string(),
sandbox_id: id.clone(),
script_code: "test ! -e /tmp/mxc-cancelled-queued-marker".to_string(),
working_directory: String::new(),
env: Vec::new(),
env_scope: EnvScope::Merge,
timeout_ms: 30_000,
})
.await
.unwrap();
assert_eq!(
marker_check.done.await.unwrap().unwrap(),
ExecTerminal::Exited(0)
);
handle
.stop(StopConfig {
sandbox_id: id.clone(),
})
.await
.unwrap();
handle
.deprovision(DeprovisionConfig { sandbox_id: id })
.await
.unwrap();
handle.shutdown().await.unwrap();
}
}