use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::PathBuf;
use std::time::Instant;
use async_channel::{Receiver, Sender};
use futures_lite::io::AsyncWriteExt;
use crate::permission::TerminalMode;
#[derive(Debug, Clone)]
pub struct JobInfo {
pub pid: u32,
pub task_id: String,
pub execution_key: String,
pub script: String,
pub mode: TerminalMode,
pub started_at: Instant,
pub status: JobStatus,
pub output_path: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JobStatus {
Running,
Completed {
exit_code: i32,
},
Failed {
error: String,
},
Killed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TerminalDelta {
pub task_id: String,
pub cursor: usize,
pub total_bytes: usize,
pub bytes: Vec<u8>,
pub status: JobStatus,
}
pub type TerminalInputSender = Sender<Vec<u8>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TerminalStream {
Stdout,
Stderr,
}
#[derive(Debug)]
struct JobState {
info: JobInfo,
terminal_buffer: Vec<u8>,
stdout_buffer: Vec<u8>,
stderr_buffer: Vec<u8>,
stdout_closed: bool,
stderr_closed: bool,
input_tx: Option<TerminalInputSender>,
kill_switch: Option<Sender<()>>,
output_redirect: Option<async_fs::File>,
finished_at: Option<Instant>,
}
enum JobCommand {
Register {
pid: u32,
task_id: String,
execution_key: String,
script: String,
mode: TerminalMode,
output_path: Option<PathBuf>,
},
AttachTerminalInput {
pid: u32,
input_tx: TerminalInputSender,
},
AttachKillSwitch {
pid: u32,
kill_tx: Sender<()>,
},
AppendTerminalOutput {
pid: u32,
stream: TerminalStream,
chunk: Vec<u8>,
},
CloseTerminalStream {
pid: u32,
stream: TerminalStream,
},
Complete {
pid: u32,
exit_code: i32,
output_path: Option<PathBuf>,
},
Fail {
pid: u32,
error: String,
output_path: Option<PathBuf>,
},
List {
reply: Sender<Vec<JobInfo>>,
},
Get {
pid: u32,
reply: Sender<Option<JobInfo>>,
},
Kill {
pid: u32,
reply: Sender<bool>,
},
KillByTaskId {
task_id: String,
reply: Sender<bool>,
},
KillByExecutionKey {
execution_key: String,
reply: Sender<usize>,
},
InputTerminal {
task_id: String,
bytes: Vec<u8>,
reply: Sender<Result<(), String>>,
},
StartOutputRedirect {
task_id: String,
output_path: PathBuf,
reply: Sender<Result<Vec<u8>, String>>,
},
TerminalOutput {
pid: u32,
reply: Sender<Option<(Vec<u8>, Vec<u8>)>>,
},
ReadTerminalDelta {
task_id: String,
cursor: usize,
max_bytes: usize,
reply: Sender<Result<TerminalDelta, String>>,
},
TerminalStreamsClosed {
pid: u32,
reply: Sender<bool>,
},
FormatRunning {
reply: Sender<String>,
},
HasRunning {
reply: Sender<bool>,
},
}
#[derive(Clone, Debug)]
pub struct JobRegistry {
tx: Sender<JobCommand>,
}
#[derive(Debug)]
pub struct JobRegistryService {
rx: Receiver<JobCommand>,
}
#[must_use]
pub fn job_registry_channel() -> (JobRegistry, JobRegistryService) {
let (tx, rx) = async_channel::unbounded();
(JobRegistry { tx }, JobRegistryService { rx })
}
impl JobRegistry {
async fn send_command(&self, command: JobCommand) {
self.tx
.send(command)
.await
.expect("job registry service unavailable");
}
async fn recv_reply<T>(reply_rx: Receiver<T>) -> T {
reply_rx
.recv()
.await
.expect("job registry response dropped")
}
pub async fn register(
&self,
pid: u32,
task_id: &str,
execution_key: &str,
script: &str,
mode: TerminalMode,
output_path: Option<PathBuf>,
) {
self.send_command(JobCommand::Register {
pid,
task_id: task_id.to_string(),
execution_key: execution_key.to_string(),
script: script.to_string(),
mode,
output_path,
})
.await;
}
pub async fn attach_terminal_input(&self, pid: u32, input_tx: TerminalInputSender) {
self.send_command(JobCommand::AttachTerminalInput { pid, input_tx })
.await;
}
pub async fn attach_kill_switch(&self, pid: u32, kill_tx: Sender<()>) {
self.send_command(JobCommand::AttachKillSwitch { pid, kill_tx })
.await;
}
pub async fn append_stdout(&self, pid: u32, chunk: Vec<u8>) {
self.send_command(JobCommand::AppendTerminalOutput {
pid,
stream: TerminalStream::Stdout,
chunk,
})
.await;
}
pub async fn append_stderr(&self, pid: u32, chunk: Vec<u8>) {
self.send_command(JobCommand::AppendTerminalOutput {
pid,
stream: TerminalStream::Stderr,
chunk,
})
.await;
}
pub async fn close_stdout(&self, pid: u32) {
self.send_command(JobCommand::CloseTerminalStream {
pid,
stream: TerminalStream::Stdout,
})
.await;
}
pub async fn close_stderr(&self, pid: u32) {
self.send_command(JobCommand::CloseTerminalStream {
pid,
stream: TerminalStream::Stderr,
})
.await;
}
pub async fn terminal_input(&self, task_id: &str, bytes: Vec<u8>) -> Result<(), String> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::InputTerminal {
task_id: task_id.to_string(),
bytes,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn start_output_redirect(
&self,
task_id: &str,
output_path: PathBuf,
) -> Result<Vec<u8>, String> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::StartOutputRedirect {
task_id: task_id.to_string(),
output_path,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn terminal_streams_closed(&self, pid: u32) -> bool {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::TerminalStreamsClosed {
pid,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn terminal_output(&self, pid: u32) -> Option<(Vec<u8>, Vec<u8>)> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::TerminalOutput {
pid,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn terminal_read(
&self,
task_id: &str,
cursor: usize,
max_bytes: usize,
) -> Result<TerminalDelta, String> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::ReadTerminalDelta {
task_id: task_id.to_string(),
cursor,
max_bytes,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn complete(&self, pid: u32, exit_code: i32, output_path: Option<PathBuf>) {
self.send_command(JobCommand::Complete {
pid,
exit_code,
output_path,
})
.await;
}
pub async fn fail(&self, pid: u32, error: &str, output_path: Option<PathBuf>) {
self.send_command(JobCommand::Fail {
pid,
error: error.to_string(),
output_path,
})
.await;
}
pub async fn list(&self) -> Vec<JobInfo> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::List { reply: reply_tx })
.await;
Self::recv_reply(reply_rx).await
}
pub async fn get(&self, pid: u32) -> Option<JobInfo> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::Get {
pid,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn kill(&self, pid: u32) -> bool {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::Kill {
pid,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn kill_by_task_id(&self, task_id: &str) -> bool {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::KillByTaskId {
task_id: task_id.to_string(),
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn kill_running(&self) -> usize {
let running_pids = self
.list()
.await
.into_iter()
.filter(|job| job.status == JobStatus::Running)
.map(|job| job.pid)
.collect::<Vec<_>>();
let mut killed = 0;
for pid in running_pids {
killed += usize::from(self.kill(pid).await);
}
killed
}
pub async fn kill_by_execution_key(&self, execution_key: &str) -> usize {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::KillByExecutionKey {
execution_key: execution_key.to_string(),
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
#[must_use]
pub fn kill_by_execution_key_blocking(&self, execution_key: &str) -> usize {
let (reply_tx, reply_rx) = async_channel::bounded(1);
if self
.tx
.send_blocking(JobCommand::KillByExecutionKey {
execution_key: execution_key.to_string(),
reply: reply_tx,
})
.is_err()
{
return 0;
}
reply_rx.recv_blocking().unwrap_or(0)
}
pub async fn format_running_jobs(&self) -> String {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::FormatRunning { reply: reply_tx })
.await;
Self::recv_reply(reply_rx).await
}
pub async fn has_running(&self) -> bool {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobCommand::HasRunning { reply: reply_tx })
.await;
Self::recv_reply(reply_rx).await
}
}
impl JobRegistryService {
pub async fn serve(self) {
let mut jobs: HashMap<u32, JobState> = HashMap::new();
while let Ok(cmd) = self.rx.recv().await {
handle_job_command(&mut jobs, cmd).await;
}
}
}
async fn handle_job_command(jobs: &mut HashMap<u32, JobState>, cmd: JobCommand) {
match cmd {
JobCommand::Register {
pid,
task_id,
execution_key,
script,
mode,
output_path,
} => register_job(jobs, pid, task_id, execution_key, script, mode, output_path),
JobCommand::AttachTerminalInput { pid, input_tx } => {
if let Some(job) = jobs.get_mut(&pid) {
job.input_tx = Some(input_tx);
}
}
JobCommand::AttachKillSwitch { pid, kill_tx } => {
if let Some(job) = jobs.get_mut(&pid) {
job.kill_switch = Some(kill_tx);
}
}
JobCommand::AppendTerminalOutput { pid, stream, chunk } => {
append_terminal_output(jobs, pid, stream, chunk).await;
}
JobCommand::CloseTerminalStream { pid, stream } => close_terminal_stream(jobs, pid, stream),
JobCommand::Complete {
pid,
exit_code,
output_path,
} => complete_job(jobs, pid, exit_code, output_path).await,
JobCommand::Fail {
pid,
error,
output_path,
} => fail_job(jobs, pid, error, output_path).await,
JobCommand::List { reply } => {
let items = jobs.values().map(|state| state.info.clone()).collect();
let _ = reply.send(items).await;
}
JobCommand::Get { pid, reply } => {
let item = jobs.get(&pid).map(|state| state.info.clone());
let _ = reply.send(item).await;
}
JobCommand::Kill { pid, reply } => {
let result = kill_job(jobs, pid).await;
let _ = reply.send(result).await;
}
JobCommand::KillByTaskId { task_id, reply } => {
let result = kill_by_task_id(jobs, &task_id).await;
let _ = reply.send(result).await;
}
JobCommand::KillByExecutionKey {
execution_key,
reply,
} => {
let killed = kill_by_execution_key(jobs, &execution_key).await;
let _ = reply.send(killed).await;
}
JobCommand::InputTerminal {
task_id,
bytes,
reply,
} => {
let result = input_terminal(jobs, &task_id, bytes).await;
let _ = reply.send(result).await;
}
JobCommand::StartOutputRedirect {
task_id,
output_path,
reply,
} => {
let result = redirect_task_output(jobs, &task_id, output_path).await;
let _ = reply.send(result).await;
}
JobCommand::TerminalOutput { pid, reply } => {
send_terminal_output(jobs, pid, reply).await;
}
JobCommand::ReadTerminalDelta {
task_id,
cursor,
max_bytes,
reply,
} => {
let result = read_terminal_delta(jobs, &task_id, cursor, max_bytes);
let _ = reply.send(result).await;
}
JobCommand::TerminalStreamsClosed { pid, reply } => {
let closed = jobs
.get(&pid)
.is_some_and(|job| job.stdout_closed && job.stderr_closed);
let _ = reply.send(closed).await;
}
JobCommand::FormatRunning { reply } => {
let _ = reply.send(format_running_jobs(jobs)).await;
}
JobCommand::HasRunning { reply } => {
let _ = reply.send(has_running_job(jobs)).await;
}
}
}
async fn send_terminal_output(
jobs: &HashMap<u32, JobState>,
pid: u32,
reply: Sender<Option<(Vec<u8>, Vec<u8>)>>,
) {
let output = jobs
.get(&pid)
.map(|job| (job.stdout_buffer.clone(), job.stderr_buffer.clone()));
let _ = reply.send(output).await;
}
fn has_running_job(jobs: &HashMap<u32, JobState>) -> bool {
jobs.values()
.any(|job| matches!(job.info.status, JobStatus::Running))
}
fn register_job(
jobs: &mut HashMap<u32, JobState>,
pid: u32,
task_id: String,
execution_key: String,
script: String,
mode: TerminalMode,
output_path: Option<PathBuf>,
) {
let info = JobInfo {
pid,
task_id,
execution_key,
script,
mode,
started_at: Instant::now(),
status: JobStatus::Running,
output_path,
};
jobs.insert(pid, JobState::new(info));
tracing::debug!(pid = %pid, "registered background job");
}
impl JobState {
const fn new(info: JobInfo) -> Self {
Self {
info,
terminal_buffer: Vec::new(),
stdout_buffer: Vec::new(),
stderr_buffer: Vec::new(),
stdout_closed: false,
stderr_closed: false,
input_tx: None,
kill_switch: None,
output_redirect: None,
finished_at: None,
}
}
}
async fn append_terminal_output(
jobs: &mut HashMap<u32, JobState>,
pid: u32,
stream: TerminalStream,
chunk: Vec<u8>,
) {
if chunk.is_empty() {
return;
}
if let Some(job) = jobs.get_mut(&pid) {
job.terminal_buffer.extend_from_slice(&chunk);
if let Some(file) = job.output_redirect.as_mut()
&& let Err(error) = file.write_all(&chunk).await
{
mark_job_failed(
job,
format!(
"failed to append redirected output for task {}: {error}",
job.info.task_id
),
);
tracing::error!(
pid = %pid,
error = %error,
"failed to append redirected output"
);
}
match stream {
TerminalStream::Stdout => job.stdout_buffer.extend_from_slice(&chunk),
TerminalStream::Stderr => job.stderr_buffer.extend_from_slice(&chunk),
}
}
}
fn close_terminal_stream(jobs: &mut HashMap<u32, JobState>, pid: u32, stream: TerminalStream) {
if let Some(job) = jobs.get_mut(&pid) {
match stream {
TerminalStream::Stdout => job.stdout_closed = true,
TerminalStream::Stderr => job.stderr_closed = true,
}
}
}
async fn complete_job(
jobs: &mut HashMap<u32, JobState>,
pid: u32,
exit_code: i32,
output_path: Option<PathBuf>,
) {
if let Some(job) = jobs.get_mut(&pid) {
if !matches!(job.info.status, JobStatus::Running) {
tracing::debug!(
pid = %pid,
status = ?job.info.status,
"ignoring complete for non-running job"
);
return;
}
if let Err(error) = finalize_output_redirect(job).await {
tracing::error!(
pid = %pid,
error = %error,
"failed to flush redirected output on complete"
);
mark_job_failed(job, error);
return;
}
job.info.status = JobStatus::Completed { exit_code };
job.finished_at = Some(Instant::now());
job.kill_switch = None;
if output_path.is_some() {
job.info.output_path = output_path;
}
tracing::debug!(pid = %pid, exit_code = %exit_code, "job completed");
}
}
async fn fail_job(
jobs: &mut HashMap<u32, JobState>,
pid: u32,
error: String,
output_path: Option<PathBuf>,
) {
if let Some(job) = jobs.get_mut(&pid) {
if !matches!(job.info.status, JobStatus::Running) {
tracing::debug!(
pid = %pid,
status = ?job.info.status,
"ignoring fail for non-running job"
);
return;
}
let status_error = if let Err(finalize_error) = finalize_output_redirect(job).await {
format!("{error}; additionally failed to flush redirected output: {finalize_error}")
} else {
error
};
mark_job_failed(job, status_error);
job.kill_switch = None;
if output_path.is_some() {
job.info.output_path = output_path;
}
tracing::debug!(pid = %pid, "job failed");
}
}
async fn kill_by_task_id(jobs: &mut HashMap<u32, JobState>, task_id: &str) -> bool {
if let Some(pid) = find_pid_by_task_id(jobs, task_id) {
kill_job(jobs, pid).await
} else {
false
}
}
async fn kill_by_execution_key(jobs: &mut HashMap<u32, JobState>, execution_key: &str) -> usize {
let pids: Vec<u32> = jobs
.iter()
.filter_map(|(pid, state)| {
(state.info.execution_key == execution_key
&& matches!(state.info.status, JobStatus::Running))
.then_some(*pid)
})
.collect();
let mut killed = 0usize;
for pid in pids {
if kill_job(jobs, pid).await {
killed += 1;
}
}
killed
}
async fn input_terminal(
jobs: &HashMap<u32, JobState>,
task_id: &str,
bytes: Vec<u8>,
) -> Result<(), String> {
let Some(pid) = find_pid_by_task_id(jobs, task_id) else {
return Err(format!("unknown task_id: {task_id}"));
};
let Some(job) = jobs.get(&pid) else {
return Err(format!("unknown task_id: {task_id}"));
};
if !matches!(job.info.status, JobStatus::Running) {
return Err(format!(
"task {} is not running; current status: {:?}",
task_id, job.info.status
));
}
let Some(tx) = &job.input_tx else {
return Err(format!(
"task {task_id} does not support terminal input in this runtime"
));
};
tx.send(bytes)
.await
.map_err(|_| format!("terminal input channel closed for task {task_id}"))
}
async fn redirect_task_output(
jobs: &mut HashMap<u32, JobState>,
task_id: &str,
output_path: PathBuf,
) -> Result<Vec<u8>, String> {
let Some(pid) = find_pid_by_task_id(jobs, task_id) else {
return Err(format!("unknown task_id: {task_id}"));
};
let Some(job) = jobs.get_mut(&pid) else {
return Err(format!("unknown task_id: {task_id}"));
};
start_output_redirect(job, output_path).await
}
fn read_terminal_delta(
jobs: &HashMap<u32, JobState>,
task_id: &str,
cursor: usize,
max_bytes: usize,
) -> Result<TerminalDelta, String> {
find_pid_by_task_id(jobs, task_id).map_or_else(
|| Err(format!("unknown task_id: {task_id}")),
|pid| {
jobs.get(&pid).map_or_else(
|| Err(format!("unknown task_id: {task_id}")),
|job| terminal_read(job, cursor, max_bytes),
)
},
)
}
async fn start_output_redirect(
job: &mut JobState,
output_path: PathBuf,
) -> Result<Vec<u8>, String> {
if let Some(existing) = job.info.output_path.as_ref() {
if existing != &output_path {
return Err(format!(
"task {} already redirects output to {}",
job.info.task_id,
existing.display()
));
}
return Ok(job.terminal_buffer.clone());
}
let mut file = async_fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(&output_path)
.await
.map_err(|error| {
format!(
"failed to open output redirect file {}: {error}",
output_path.display()
)
})?;
file.write_all(&job.terminal_buffer)
.await
.map_err(|error| {
format!(
"failed to write initial output redirect snapshot for task {}: {error}",
job.info.task_id
)
})?;
file.flush().await.map_err(|error| {
format!(
"failed to flush initial output redirect snapshot for task {}: {error}",
job.info.task_id
)
})?;
job.info.output_path = Some(output_path);
job.output_redirect = Some(file);
Ok(job.terminal_buffer.clone())
}
fn mark_job_failed(job: &mut JobState, error: String) {
job.info.status = JobStatus::Failed { error };
job.finished_at = Some(Instant::now());
job.kill_switch = None;
}
async fn finalize_output_redirect(job: &mut JobState) -> Result<(), String> {
if let Some(mut file) = job.output_redirect.take()
&& let Err(error) = file.flush().await
{
return Err(format!(
"failed to flush redirected output for task {}: {error}",
job.info.task_id
));
}
Ok(())
}
fn find_pid_by_task_id(jobs: &HashMap<u32, JobState>, task_id: &str) -> Option<u32> {
jobs.iter().find_map(|(pid, state)| {
if state.info.task_id == task_id {
Some(*pid)
} else {
None
}
})
}
async fn kill_job(jobs: &mut HashMap<u32, JobState>, pid: u32) -> bool {
if let Some(job) = jobs.get_mut(&pid) {
if !matches!(job.info.status, JobStatus::Running) {
tracing::warn!(pid = %pid, "cannot kill non-running job");
return false;
}
if let Some(kill_switch) = job.kill_switch.take() {
if kill_switch.send(()).await.is_err() {
tracing::warn!(pid = %pid, "failed to signal runtime kill switch");
return false;
}
if let Err(error) = finalize_output_redirect(job).await {
tracing::warn!(
pid = %pid,
error = %error,
"failed to flush redirected output after kill switch signal"
);
}
job.info.status = JobStatus::Killed;
job.finished_at = Some(Instant::now());
job.stdout_closed = true;
job.stderr_closed = true;
tracing::info!(pid = %pid, "killed job via runtime kill switch");
return true;
}
#[cfg(unix)]
{
let result = unsafe { libc::kill(-pid.cast_signed(), libc::SIGKILL) };
if result == 0 {
if let Err(error) = finalize_output_redirect(job).await {
tracing::warn!(
pid = %pid,
error = %error,
"failed to flush redirected output after kill"
);
}
job.info.status = JobStatus::Killed;
job.finished_at = Some(Instant::now());
job.stdout_closed = true;
job.stderr_closed = true;
tracing::info!(pid = %pid, "killed job");
return true;
}
let error = std::io::Error::last_os_error();
tracing::warn!(pid = %pid, error = %error, "failed to kill job");
return false;
}
#[cfg(windows)]
{
let output = async_process::Command::new("taskkill")
.args(["/F", "/T", "/PID", &pid.to_string()])
.output()
.await;
match output {
Ok(output) if output.status.success() => {
if let Err(error) = finalize_output_redirect(job).await {
tracing::warn!(
pid = %pid,
error = %error,
"failed to flush redirected output after kill"
);
}
job.info.status = JobStatus::Killed;
job.finished_at = Some(Instant::now());
job.stdout_closed = true;
job.stderr_closed = true;
tracing::info!(pid = %pid, "killed job (Windows)");
return true;
}
Ok(output) => {
tracing::warn!(
pid = %pid,
status = %output.status,
stderr = %String::from_utf8_lossy(&output.stderr),
"taskkill reported failure"
);
return false;
}
Err(err) => {
tracing::warn!(pid = %pid, error = %err, "failed to kill job (Windows)");
return false;
}
}
}
}
false
}
fn format_running_jobs(jobs: &HashMap<u32, JobState>) -> String {
let running: Vec<_> = jobs
.values()
.filter(|job| matches!(job.info.status, JobStatus::Running))
.collect();
if running.is_empty() {
return String::new();
}
let mut output = String::new();
for job in running {
let script_preview = if job.info.script.len() > 50 {
format!("{}...", &job.info.script[..50])
} else {
job.info.script.clone()
};
let output_path = job
.info
.output_path
.as_ref()
.map_or_else(|| "(no output)".to_string(), |p| p.display().to_string());
let _ = writeln!(
output,
" - task {} (pid {}): `{}` -> {}",
job.info.task_id, job.info.pid, script_preview, output_path
);
}
output
}
fn terminal_read(job: &JobState, cursor: usize, max_bytes: usize) -> Result<TerminalDelta, String> {
let total_bytes = job.terminal_buffer.len();
if cursor > total_bytes {
return Err(format!(
"cursor {cursor} exceeds terminal buffer size {total_bytes} for task {}",
job.info.task_id
));
}
let end = total_bytes.min(cursor.saturating_add(max_bytes));
Ok(TerminalDelta {
task_id: job.info.task_id.clone(),
cursor: end,
total_bytes,
bytes: job.terminal_buffer[cursor..end].to_vec(),
status: job.info.status.clone(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use executor_core::Executor;
use executor_core::Task;
use executor_core::tokio::TokioGlobal;
use tempfile::tempdir;
#[tokio::test]
async fn test_job_registry_lifecycle() {
let (registry, service) = job_registry_channel();
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
12345,
"amber-forest-thunder-pearl",
"exec-test",
"sleep 10",
TerminalMode::Sandboxed,
Some(PathBuf::from("outputs/12345.txt")),
)
.await;
let jobs = registry.list().await;
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].pid, 12345);
assert_eq!(jobs[0].task_id, "amber-forest-thunder-pearl");
assert_eq!(jobs[0].execution_key, "exec-test");
assert!(matches!(jobs[0].status, JobStatus::Running));
registry.complete(12345, 0, None).await;
let job = registry.get(12345).await.unwrap();
assert!(matches!(job.status, JobStatus::Completed { exit_code: 0 }));
}
#[tokio::test]
async fn test_format_running_jobs() {
let (registry, service) = job_registry_channel();
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
1,
"task-a",
"exec-a",
"echo hello",
TerminalMode::Sandboxed,
None,
)
.await;
registry
.register(
2,
"task-b",
"exec-b",
"sleep 5",
TerminalMode::Sandboxed,
None,
)
.await;
registry.complete(2, 0, None).await;
let running = registry.format_running_jobs().await;
assert!(running.contains("task task-a"));
assert!(!running.contains("task task-b"));
}
#[tokio::test]
async fn test_output_redirect_streams_full_output() {
let (registry, service) = job_registry_channel();
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
let temp = tempdir().unwrap();
let redirect_path = temp.path().join("task-stream.log");
registry
.register(
101,
"task-stream",
"exec-stream",
"printf one",
TerminalMode::Sandboxed,
None,
)
.await;
registry
.append_stdout(101, b"line1\nline2\n".to_vec())
.await;
let snapshot = registry
.start_output_redirect("task-stream", redirect_path.clone())
.await
.unwrap();
assert_eq!(String::from_utf8_lossy(&snapshot), "line1\nline2\n");
registry.append_stderr(101, b"line3\n".to_vec()).await;
registry.complete(101, 0, None).await;
let job = registry.get(101).await.unwrap();
assert!(matches!(job.status, JobStatus::Completed { exit_code: 0 }));
let redirected = async_fs::read(&redirect_path).await.unwrap();
assert_eq!(
String::from_utf8_lossy(&redirected),
"line1\nline2\nline3\n"
);
}
#[tokio::test]
async fn test_read_terminal_delta_reads_incrementally() {
let (registry, service) = job_registry_channel();
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
202,
"task-delta",
"exec-delta",
"tail -f log",
TerminalMode::Sandboxed,
None,
)
.await;
registry.append_stdout(202, b"hello ".to_vec()).await;
registry.append_stderr(202, b"world".to_vec()).await;
let first = registry.terminal_read("task-delta", 0, 6).await.unwrap();
assert_eq!(String::from_utf8_lossy(&first.bytes), "hello ");
assert_eq!(first.cursor, 6);
assert_eq!(first.total_bytes, 11);
assert!(matches!(first.status, JobStatus::Running));
let second = registry
.terminal_read("task-delta", first.cursor, 32)
.await
.unwrap();
assert_eq!(String::from_utf8_lossy(&second.bytes), "world");
assert_eq!(second.cursor, 11);
assert_eq!(second.total_bytes, 11);
}
#[tokio::test]
async fn test_kill_by_execution_key_no_match() {
let (registry, service) = job_registry_channel();
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
1,
"task-a",
"exec-a",
"echo hello",
TerminalMode::Sandboxed,
None,
)
.await;
registry.complete(1, 0, None).await;
let killed = registry.kill_by_execution_key("exec-b").await;
assert_eq!(killed, 0);
}
#[tokio::test]
async fn test_kill_switch_path_marks_job_killed() {
let (registry, service) = job_registry_channel();
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
555,
"task-kill-switch",
"exec-kill-switch",
"sleep 10",
TerminalMode::Sandboxed,
None,
)
.await;
let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
registry.attach_kill_switch(555, kill_tx).await;
assert!(registry.kill_by_task_id("task-kill-switch").await);
assert!(kill_rx.recv().await.is_ok());
let job = registry.get(555).await.expect("job should exist");
assert!(matches!(job.status, JobStatus::Killed));
}
#[tokio::test]
async fn test_complete_does_not_override_killed_status() {
let (registry, service) = job_registry_channel();
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
556,
"task-killed-complete",
"exec-killed-complete",
"sleep 10",
TerminalMode::Sandboxed,
None,
)
.await;
let (kill_tx, _kill_rx) = async_channel::bounded::<()>(1);
registry.attach_kill_switch(556, kill_tx).await;
assert!(registry.kill_by_task_id("task-killed-complete").await);
registry.complete(556, 0, None).await;
let job = registry.get(556).await.expect("job should exist");
assert!(matches!(job.status, JobStatus::Killed));
}
}