use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use tokio::sync::{Mutex, Notify};
use tokio_util::sync::CancellationToken;
use crate::engine::{EngineControl, VmEngine};
use crate::model::{
CancelOutput, ExecutionEvent, ExecutionEventsInput, ExecutionEventsOutput, ExecutionIdInput,
ExecutionInputInput, ExecutionSignalInput, ExecutionStartInput, ExecutionStartOutput,
InputOutput, ProviderError, SignalOutput,
};
struct ExecutionRecord {
events: Vec<ExecutionEvent>,
terminal: bool,
cancel_requested: bool,
control: Option<Arc<dyn EngineControl>>,
cancellation: CancellationToken,
notify: Arc<Notify>,
}
#[derive(Clone)]
pub struct ExecutionRegistry {
engine: Arc<dyn VmEngine>,
records: Arc<Mutex<HashMap<String, ExecutionRecord>>>,
}
#[cfg_attr(not(test), allow(dead_code))]
#[derive(Clone)]
pub struct EventSink {
execution_id: String,
records: Arc<Mutex<HashMap<String, ExecutionRecord>>>,
}
#[cfg_attr(not(test), allow(dead_code))]
impl EventSink {
pub async fn append(&self, event: ExecutionEvent) {
append_event(&self.records, &self.execution_id, event).await;
}
}
impl ExecutionRegistry {
pub fn new(engine: Arc<dyn VmEngine>) -> Self {
Self {
engine,
records: Arc::new(Mutex::new(HashMap::new())),
}
}
pub async fn start(&self, request: ExecutionStartInput) -> ExecutionStartOutput {
let execution_id = request.request_id.clone();
let cancellation = CancellationToken::new();
{
let mut records = self.records.lock().await;
if records.contains_key(&execution_id) {
return ExecutionStartOutput {
provider_execution_id: execution_id,
replayed: true,
};
}
records.insert(
execution_id.clone(),
ExecutionRecord {
events: vec![ExecutionEvent::accepted(&execution_id)],
terminal: false,
cancel_requested: false,
control: None,
cancellation: cancellation.clone(),
notify: Arc::new(Notify::new()),
},
);
}
let engine = Arc::clone(&self.engine);
let records = Arc::clone(&self.records);
let sink = EventSink {
execution_id: execution_id.clone(),
records: Arc::clone(&records),
};
let task_execution_id = execution_id.clone();
tokio::spawn(async move {
match engine.launch(request, sink, cancellation).await {
Ok(control) => {
{
let mut records = records.lock().await;
let Some(record) = records.get_mut(&task_execution_id) else {
return;
};
if record.terminal {
return;
}
record.control = Some(Arc::clone(&control));
record
.events
.push(ExecutionEvent::started(&task_execution_id));
record.notify.notify_waiters();
}
if let Err(error) = control.activate().await {
append_event(
&records,
&task_execution_id,
ExecutionEvent::error(&task_execution_id, &error.code, error.message),
)
.await;
}
}
Err(error) => {
append_event(
&records,
&task_execution_id,
ExecutionEvent::error(&task_execution_id, &error.code, error.message),
)
.await;
}
}
});
ExecutionStartOutput {
provider_execution_id: execution_id,
replayed: false,
}
}
pub async fn events(
&self,
input: ExecutionEventsInput,
) -> Result<ExecutionEventsOutput, ProviderError> {
let cursor = input
.cursor
.as_deref()
.unwrap_or("0")
.parse::<usize>()
.unwrap_or(0);
let wait = Duration::from_millis(input.wait_ms.min(1_000));
loop {
let (output, notify, ready) = {
let records = self.records.lock().await;
let record = records.get(&input.execution_id).ok_or_else(|| {
ProviderError::new(
"EXECUTION_NOT_FOUND",
format!("Provider execution {} was not found", input.execution_id),
)
})?;
let selected = record
.events
.iter()
.skip(cursor.min(record.events.len()))
.cloned()
.collect();
(
ExecutionEventsOutput {
cursor: record.events.len().to_string(),
events: selected,
},
Arc::clone(&record.notify),
record.events.len() > cursor || record.terminal || wait.is_zero(),
)
};
if ready {
return Ok(output);
}
if tokio::time::timeout(wait, notify.notified()).await.is_err() {
return Ok(output);
}
}
}
pub async fn cancel(&self, input: ExecutionIdInput) -> Result<CancelOutput, ProviderError> {
let (control, cancellation, terminal) = {
let mut records = self.records.lock().await;
let record = records.get_mut(&input.execution_id).ok_or_else(|| {
ProviderError::new(
"EXECUTION_NOT_FOUND",
format!("Provider execution {} was not found", input.execution_id),
)
})?;
if record.terminal {
(None, record.cancellation.clone(), true)
} else {
record.cancel_requested = true;
(record.control.clone(), record.cancellation.clone(), false)
}
};
if terminal {
return Ok(CancelOutput {
execution_id: input.execution_id,
canceled: false,
});
}
cancellation.cancel();
if let Some(control) = control {
control.cancel().await?;
}
append_event(
&self.records,
&input.execution_id,
ExecutionEvent::canceled(&input.execution_id),
)
.await;
Ok(CancelOutput {
execution_id: input.execution_id,
canceled: true,
})
}
pub async fn input(&self, input: ExecutionInputInput) -> Result<InputOutput, ProviderError> {
let data = base64::engine::general_purpose::STANDARD
.decode(&input.data_base64)
.map_err(|error| {
ProviderError::new("INVALID_INPUT", format!("data_base64 is invalid: {error}"))
})?;
let control = self.active_control(&input.execution_id).await?;
control.input(data.clone()).await?;
Ok(InputOutput {
execution_id: input.execution_id,
recipients: 1,
bytes: data.len() as u64,
})
}
pub async fn signal(&self, input: ExecutionSignalInput) -> Result<SignalOutput, ProviderError> {
let control = self.active_control(&input.execution_id).await?;
control.signal(input.signal.clone()).await?;
Ok(SignalOutput {
execution_id: input.execution_id,
signal: input.signal,
applied: true,
})
}
async fn active_control(
&self,
execution_id: &str,
) -> Result<Arc<dyn EngineControl>, ProviderError> {
let records = self.records.lock().await;
let record = records.get(execution_id).ok_or_else(|| {
ProviderError::new(
"EXECUTION_NOT_FOUND",
format!("Provider execution {execution_id} was not found"),
)
})?;
if record.terminal {
return Err(ProviderError::new(
"EXECUTION_NOT_ACTIVE",
format!("Provider execution {execution_id} is terminal"),
));
}
record.control.clone().ok_or_else(|| {
ProviderError::new(
"EXECUTION_NOT_ACTIVE",
format!("Provider execution {execution_id} has not started"),
)
})
}
}
async fn append_event(
records: &Arc<Mutex<HashMap<String, ExecutionRecord>>>,
execution_id: &str,
event: ExecutionEvent,
) {
let mut records = records.lock().await;
let Some(record) = records.get_mut(execution_id) else {
return;
};
if record.terminal {
return;
}
let event = if record.cancel_requested && event.terminal() {
ExecutionEvent::canceled(execution_id)
} else {
event
};
record.terminal = event.terminal();
if record.terminal {
record.control = None;
}
record.events.push(event);
record.notify.notify_waiters();
}
#[cfg(test)]
mod tests {
use std::sync::Mutex as StdMutex;
use super::*;
use crate::engine::EngineFuture;
use crate::model::IsolationStatus;
#[derive(Default)]
struct FakeControl {
inputs: StdMutex<Vec<Vec<u8>>>,
signals: StdMutex<Vec<String>>,
}
impl EngineControl for FakeControl {
fn input<'a>(&'a self, data: Vec<u8>) -> EngineFuture<'a, Result<(), ProviderError>> {
Box::pin(async move {
self.inputs.lock().unwrap().push(data);
Ok(())
})
}
fn signal<'a>(&'a self, signal: String) -> EngineFuture<'a, Result<(), ProviderError>> {
Box::pin(async move {
self.signals.lock().unwrap().push(signal);
Ok(())
})
}
fn cancel<'a>(&'a self) -> EngineFuture<'a, Result<(), ProviderError>> {
Box::pin(async { Ok(()) })
}
}
struct FakeEngine {
control: Arc<FakeControl>,
}
impl VmEngine for FakeEngine {
fn status(&self) -> Result<IsolationStatus, ProviderError> {
Ok(IsolationStatus::uninitialized())
}
fn warmup<'a>(
&'a self,
_request: crate::model::IsolationWarmupInput,
) -> EngineFuture<'a, Result<IsolationStatus, ProviderError>> {
Box::pin(async { Ok(IsolationStatus::uninitialized()) })
}
fn drain(&self) -> EngineFuture<'_, Result<IsolationStatus, ProviderError>> {
Box::pin(async { Ok(IsolationStatus::uninitialized()) })
}
fn launch<'a>(
&'a self,
request: ExecutionStartInput,
events: EventSink,
_cancellation: CancellationToken,
) -> EngineFuture<'a, Result<Arc<dyn EngineControl>, ProviderError>> {
let control: Arc<dyn EngineControl> = self.control.clone();
Box::pin(async move {
tokio::spawn(async move {
tokio::task::yield_now().await;
events
.append(ExecutionEvent {
kind: "stdout".to_string(),
request_id: Some(request.request_id.clone()),
data: Some("ready".to_string()),
data_base64: None,
exit_code: None,
error_code: None,
export_index: None,
})
.await;
events
.append(ExecutionEvent {
kind: "exit".to_string(),
request_id: Some(request.request_id),
data: None,
data_base64: None,
exit_code: Some(0),
error_code: None,
export_index: None,
})
.await;
});
Ok(control)
})
}
}
fn request(id: &str) -> ExecutionStartInput {
ExecutionStartInput {
protocol_version: 1,
request_id: id.to_string(),
argv: vec!["/bin/true".to_string()],
shell: false,
cwd: None,
env: Vec::new(),
tty: false,
timeout_ms: None,
image_ref: None,
vm_bundle: None,
workspace: None,
memory_mb: None,
cpu_count: None,
pids_max: None,
network: None,
exports: Vec::new(),
}
}
#[tokio::test]
async fn registry_replays_start_and_orders_one_terminal_event() {
let control = Arc::new(FakeControl::default());
let registry = ExecutionRegistry::new(Arc::new(FakeEngine { control }));
assert!(!registry.start(request("native-1")).await.replayed);
assert!(registry.start(request("native-1")).await.replayed);
let mut cursor = None;
let mut events = Vec::new();
loop {
let page = registry
.events(ExecutionEventsInput {
execution_id: "native-1".to_string(),
cursor,
wait_ms: 1_000,
})
.await
.unwrap();
cursor = Some(page.cursor);
let terminal = page.events.iter().any(ExecutionEvent::terminal);
events.extend(page.events);
if terminal {
break;
}
}
let kinds = events
.iter()
.map(|event| event.kind.as_str())
.collect::<Vec<_>>();
assert_eq!(kinds, ["accepted", "started", "stdout", "exit"]);
let canceled = registry
.cancel(ExecutionIdInput {
execution_id: "native-1".to_string(),
request_id: None,
})
.await
.unwrap();
assert!(!canceled.canceled);
}
}