use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::PathBuf;
use std::time::{Duration, Instant};
use aither_core::{IdLease, WeakIdLease};
use async_channel::{Receiver, Sender, WeakSender};
use futures_lite::io::AsyncWriteExt;
use crate::interpreter::Interpreter;
use crate::memory::MemoryDomain;
use crate::output_policy::OutputPolicy;
use crate::policy::SandboxMode;
#[cfg(unix)]
use crate::process_tree::KillTreeError;
use crate::process_tree::{JobTree, ProcessScanner};
use crate::terminal::TimeoutKill;
#[derive(Debug, Clone)]
pub struct JobInfo {
pub pid: u32,
pub task_id: String,
pub execution_key: String,
pub script: String,
pub interpreter: Interpreter,
pub mode: SandboxMode,
pub started_at: Instant,
pub status: JobStatus,
pub output_path: Option<PathBuf>,
pub place: JobPlace,
pub timeout: Option<Duration>,
}
impl JobInfo {
#[must_use]
pub fn remaining(&self) -> Option<Duration> {
self.timeout
.map(|timeout| timeout.saturating_sub(self.started_at.elapsed()))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JobStatus {
Running,
Completed {
exit_code: i32,
delivery: Delivery,
},
Failed {
error: String,
delivery: Delivery,
},
Killed {
cause: KillCause,
delivery: Delivery,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KillCause {
User,
Timeout(TimeoutKill),
MemoryRunaway {
footprint_bytes: u64,
capacity_bytes: u64,
domain: MemoryDomain,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum JobPlace {
Host,
Container,
Remote,
}
impl JobStatus {
#[must_use]
pub const fn delivery(&self) -> Option<Delivery> {
match self {
Self::Running => None,
Self::Completed { delivery, .. }
| Self::Failed { delivery, .. }
| Self::Killed { delivery, .. } => Some(*delivery),
}
}
#[must_use]
pub const fn kill_cause(&self) -> Option<KillCause> {
match self {
Self::Killed { cause, .. } => Some(*cause),
Self::Running | Self::Completed { .. } | Self::Failed { .. } => None,
}
}
#[must_use]
pub const fn completion_pending(&self) -> bool {
matches!(self.delivery(), Some(Delivery::Pending))
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum JobInputError {
#[error("unknown task_id: {task_id}")]
UnknownTask {
task_id: String,
},
#[error("task {task_id} is not running; current status: {status:?}")]
NotRunning {
task_id: String,
status: JobStatus,
},
#[error("task {task_id} reads no input: it started in the foreground, with no stdin pipe")]
NoStdin {
task_id: String,
},
#[error("terminal input channel closed for task {task_id}")]
Closed {
task_id: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Delivery {
Pending,
Taken,
}
#[must_use = "dropping it marks the completion taken"]
pub struct PendingCompletion {
tx: Sender<JobCommand>,
task_id: Option<IdLease>,
}
impl std::fmt::Debug for PendingCompletion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PendingCompletion")
.field("task_id", &self.task_id)
.finish_non_exhaustive()
}
}
impl PendingCompletion {
pub async fn take(mut self) {
let Some(task_id) = self.task_id.take() else {
return;
};
let (reply_tx, reply_rx) = async_channel::bounded(1);
if self
.tx
.send(
JobRequest::TakeCompletion {
task_id,
reply: reply_tx,
}
.into(),
)
.await
.is_ok()
{
let _ = reply_rx.recv().await;
}
}
}
impl Drop for PendingCompletion {
fn drop(&mut self) {
if let Some(task_id) = self.task_id.take() {
let _ = self
.tx
.try_send(StateCommand::TakeCompletion { task_id }.into());
}
}
}
pub struct JobWatch {
tx: Sender<JobCommand>,
task_id: IdLease,
}
impl std::fmt::Debug for JobWatch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JobWatch")
.field("task_id", &self.task_id)
.finish_non_exhaustive()
}
}
impl Drop for JobWatch {
fn drop(&mut self) {
let task_id = self.task_id.clone();
let _ = self.tx.try_send(StateCommand::Unwatch { task_id }.into());
}
}
#[derive(Debug)]
pub struct OwedCompletion {
pub info: JobInfo,
pub pending: Option<PendingCompletion>,
}
impl JobRead {
#[must_use]
pub fn into_delta(self) -> Option<JobDelta> {
match self {
Self::Delta(delta) => Some(delta),
Self::Unchanged { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JobDelta {
pub task_id: String,
pub cursor: usize,
pub total_bytes: usize,
pub bytes: Vec<u8>,
pub status: JobStatus,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JobRead {
Delta(JobDelta),
Unchanged {
task_id: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnchangedRead {
pub task_id: String,
}
pub type TerminalInputSender = Sender<Vec<u8>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TerminalStream {
Stdout,
Stderr,
}
#[derive(Debug)]
#[allow(clippy::struct_excessive_bools)]
struct JobState {
info: JobInfo,
task_id: IdLease,
terminal_buffer: Vec<u8>,
line_buffer: Vec<u8>,
stdout_partial: Vec<u8>,
stderr_partial: Vec<u8>,
stdout_buffer: Vec<u8>,
stderr_buffer: Vec<u8>,
stdout_closed: bool,
stderr_closed: bool,
input_tx: Option<TerminalInputSender>,
kill_switch: Option<Sender<()>>,
process_tree: Option<JobTree>,
kill_cause: Option<KillCause>,
kills_in_flight: usize,
deferred_end: Option<Ending>,
settled_waiters: Vec<SettledWaiter>,
ended_waiters: Vec<Sender<Option<JobInfo>>>,
output_redirect: Option<async_fs::File>,
finished_at: Option<Instant>,
completion_owed: bool,
claimed: bool,
watchers: usize,
}
#[derive(Debug)]
enum SettledWaiter {
Read(Sender<Option<JobInfo>>),
Owe {
ending: Result<i32, String>,
reply: Sender<Option<OwedCompletion>>,
},
}
enum StateCommand {
Register {
pid: u32,
task_id: IdLease,
execution_key: String,
script: String,
interpreter: Interpreter,
mode: SandboxMode,
output_path: Option<PathBuf>,
process_tree: Option<JobTree>,
place: JobPlace,
},
Bound {
task_id: IdLease,
timeout: Duration,
},
Launching {
task_id: IdLease,
},
Abandon {
task_id: IdLease,
},
AttachTerminalInput {
task_id: IdLease,
input_tx: TerminalInputSender,
},
AttachKillSwitch {
task_id: IdLease,
kill_tx: Sender<()>,
},
AppendTerminalOutput {
task_id: IdLease,
stream: TerminalStream,
chunk: Vec<u8>,
},
CloseTerminalStream {
task_id: IdLease,
stream: TerminalStream,
},
Complete {
task_id: IdLease,
exit_code: i32,
output_path: Option<PathBuf>,
},
Fail {
task_id: IdLease,
error: String,
output_path: Option<PathBuf>,
},
TakeCompletion {
task_id: IdLease,
},
Unwatch {
task_id: IdLease,
},
}
enum JobRequest {
List {
reply: Sender<Vec<JobInfo>>,
},
GetByTaskId {
task_id: String,
reply: Sender<Option<JobInfo>>,
},
GetByTaskIdSettled {
task_id: String,
reply: Sender<Option<JobInfo>>,
},
AppendTaskStdout {
task_id: IdLease,
chunk: Vec<u8>,
reply: Sender<bool>,
},
Lease {
task_id: String,
reply: Sender<Option<WeakIdLease>>,
},
OweCompletion {
task_id: String,
ending: Result<i32, String>,
reply: Sender<Option<OwedCompletion>>,
},
BeginKillByTaskId {
task_id: String,
cause: KillCause,
reply: Sender<KillPlan>,
},
BeginKillByExecutionKey {
execution_key: String,
cause: KillCause,
reply: Sender<Vec<(String, KillPlan)>>,
},
EndKill {
task_id: String,
killed: bool,
reply: Sender<bool>,
},
InputTerminal {
task_id: String,
bytes: Vec<u8>,
reply: Sender<Result<(), JobInputError>>,
},
StartOutputRedirect {
task_id: String,
output_path: PathBuf,
reply: Sender<Result<Vec<u8>, String>>,
},
TerminalOutput {
task_id: String,
reply: Sender<Option<(Vec<u8>, Vec<u8>)>>,
},
ReadJobDelta {
task_id: String,
cursor: usize,
max_bytes: usize,
tracked: bool,
reply: Sender<Result<JobRead, String>>,
},
WaitEnded {
task_id: String,
claim: bool,
reply: Sender<Option<JobInfo>>,
},
TerminalStreamsClosed {
task_id: String,
reply: Sender<bool>,
},
FormatRunning {
reply: Sender<String>,
},
HasRunning {
reply: Sender<bool>,
},
Watch {
task_id: String,
reply: Sender<Option<JobWatch>>,
},
TakeCompletion {
task_id: IdLease,
reply: Sender<()>,
},
}
enum KillPlan {
Done(bool),
Tree(JobTree),
Group(u32),
}
#[derive(Debug)]
enum Ending {
Complete {
exit_code: i32,
output_path: Option<PathBuf>,
},
Fail {
error: String,
output_path: Option<PathBuf>,
},
}
enum JobCommand {
State(StateCommand),
Request(JobRequest),
}
impl From<StateCommand> for JobCommand {
fn from(command: StateCommand) -> Self {
Self::State(command)
}
}
impl From<JobRequest> for JobCommand {
fn from(request: JobRequest) -> Self {
Self::Request(request)
}
}
#[derive(Clone, Debug)]
pub struct JobRegistry {
tx: Sender<JobCommand>,
#[cfg_attr(target_os = "linux", allow(dead_code))]
scanner: ProcessScanner,
}
#[derive(Debug)]
pub struct JobRegistryService {
rx: Receiver<JobCommand>,
tx: WeakSender<JobCommand>,
policy: OutputPolicy,
}
#[must_use]
pub fn job_registry_channel(policy: OutputPolicy) -> (JobRegistry, JobRegistryService) {
let (tx, rx) = async_channel::unbounded();
let weak = tx.downgrade();
(
JobRegistry {
tx,
scanner: ProcessScanner::default(),
},
JobRegistryService {
rx,
tx: weak,
policy,
},
)
}
impl JobRegistry {
async fn send_command(&self, command: impl Into<JobCommand>) {
self.tx
.send(command.into())
.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: &IdLease,
execution_key: &str,
script: &str,
mode: SandboxMode,
output_path: Option<PathBuf>,
) {
self.register_with_tree(
pid,
task_id,
execution_key,
script,
Interpreter::Shell,
mode,
output_path,
None,
JobPlace::Host,
)
.await;
}
#[allow(clippy::too_many_arguments)]
pub async fn register_at(
&self,
place: JobPlace,
pid: u32,
task_id: &IdLease,
execution_key: &str,
script: &str,
interpreter: Interpreter,
mode: SandboxMode,
) {
self.register_with_tree(
pid,
task_id,
execution_key,
script,
interpreter,
mode,
None,
None,
place,
)
.await;
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn register_with_tree(
&self,
pid: u32,
task_id: &IdLease,
execution_key: &str,
script: &str,
interpreter: Interpreter,
mode: SandboxMode,
output_path: Option<PathBuf>,
process_tree: Option<JobTree>,
place: JobPlace,
) {
self.send_command(StateCommand::Register {
place,
pid,
task_id: task_id.clone(),
execution_key: execution_key.to_string(),
script: script.to_string(),
interpreter,
mode,
output_path,
process_tree,
})
.await;
}
pub async fn bound_by_timeout(&self, task_id: &IdLease, timeout: Duration) {
self.send_command(StateCommand::Bound {
task_id: task_id.clone(),
timeout,
})
.await;
}
pub async fn attach_terminal_input(&self, task_id: &IdLease, input_tx: TerminalInputSender) {
self.send_command(StateCommand::AttachTerminalInput {
task_id: task_id.clone(),
input_tx,
})
.await;
}
pub async fn attach_kill_switch(&self, task_id: &IdLease, kill_tx: Sender<()>) {
self.send_command(StateCommand::AttachKillSwitch {
task_id: task_id.clone(),
kill_tx,
})
.await;
}
#[cfg_attr(target_os = "linux", allow(dead_code))]
pub(crate) fn scanner(&self) -> ProcessScanner {
self.scanner.clone()
}
pub async fn append_stdout(&self, task_id: &IdLease, chunk: Vec<u8>) {
self.append_output(task_id.clone(), TerminalStream::Stdout, chunk)
.await;
}
pub async fn append_stderr(&self, task_id: &IdLease, chunk: Vec<u8>) {
self.append_output(task_id.clone(), TerminalStream::Stderr, chunk)
.await;
}
pub(crate) async fn append_output(
&self,
task_id: IdLease,
stream: TerminalStream,
chunk: Vec<u8>,
) {
self.send_command(StateCommand::AppendTerminalOutput {
task_id,
stream,
chunk,
})
.await;
}
pub async fn append_task_stdout(&self, task_id: &IdLease, chunk: Vec<u8>) -> bool {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::AppendTaskStdout {
task_id: task_id.clone(),
chunk,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub(crate) async fn task_lease(&self, task_id: &str) -> Option<WeakIdLease> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::Lease {
task_id: task_id.to_string(),
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub(crate) async fn launching(&self, task_id: &IdLease) {
self.send_command(StateCommand::Launching {
task_id: task_id.clone(),
})
.await;
}
pub(crate) async fn abandon_launch(&self, task_id: &IdLease) {
self.send_command(StateCommand::Abandon {
task_id: task_id.clone(),
})
.await;
}
pub async fn close_stdout(&self, task_id: &IdLease) {
self.close_output(task_id.clone(), TerminalStream::Stdout)
.await;
}
pub async fn close_stderr(&self, task_id: &IdLease) {
self.close_output(task_id.clone(), TerminalStream::Stderr)
.await;
}
pub(crate) async fn close_output(&self, task_id: IdLease, stream: TerminalStream) {
self.send_command(StateCommand::CloseTerminalStream { task_id, stream })
.await;
}
pub async fn terminal_input(&self, task_id: &str, bytes: Vec<u8>) -> Result<(), JobInputError> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::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(JobRequest::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, task_id: &str) -> bool {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::TerminalStreamsClosed {
task_id: task_id.to_string(),
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn terminal_output(&self, task_id: &str) -> Option<(Vec<u8>, Vec<u8>)> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::TerminalOutput {
task_id: task_id.to_string(),
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<JobRead, String> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::ReadJobDelta {
task_id: task_id.to_string(),
cursor,
max_bytes,
tracked: true,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn monitor_read(
&self,
task_id: &str,
cursor: usize,
max_bytes: usize,
) -> Result<JobDelta, String> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::ReadJobDelta {
task_id: task_id.to_string(),
cursor,
max_bytes,
tracked: false,
reply: reply_tx,
})
.await;
match Self::recv_reply(reply_rx).await? {
JobRead::Delta(delta) => Ok(delta),
JobRead::Unchanged { task_id } => {
unreachable!("an untracked read of {task_id} is never unchanged")
}
}
}
pub async fn wait_ended(&self, task_id: &str) -> Option<JobInfo> {
self.wait(task_id, false).await
}
pub async fn wait_taking(&self, task_id: &str) -> Option<JobInfo> {
self.wait(task_id, true).await
}
async fn wait(&self, task_id: &str, claim: bool) -> Option<JobInfo> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::WaitEnded {
task_id: task_id.to_string(),
claim,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn complete(&self, task_id: &IdLease, exit_code: i32, output_path: Option<PathBuf>) {
self.send_command(StateCommand::Complete {
task_id: task_id.clone(),
exit_code,
output_path,
})
.await;
}
pub async fn fail(&self, task_id: &IdLease, error: &str, output_path: Option<PathBuf>) {
self.send_command(StateCommand::Fail {
task_id: task_id.clone(),
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(JobRequest::List { reply: reply_tx })
.await;
Self::recv_reply(reply_rx).await
}
pub async fn get_by_task_id(&self, task_id: &str) -> Option<JobInfo> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::GetByTaskId {
task_id: task_id.to_string(),
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn get_by_task_id_settled(&self, task_id: &str) -> Option<JobInfo> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::GetByTaskIdSettled {
task_id: task_id.to_string(),
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn owe_completion(
&self,
task_id: &str,
ending: Result<i32, String>,
) -> Option<OwedCompletion> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::OweCompletion {
task_id: task_id.to_string(),
ending,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn kill_timed_out(&self, task_id: &str, kill: TimeoutKill) -> bool {
self.kill_for(task_id, KillCause::Timeout(kill)).await
}
pub async fn kill_runaway(
&self,
task_id: &str,
footprint_bytes: u64,
capacity_bytes: u64,
domain: MemoryDomain,
) -> bool {
self.kill_for(
task_id,
KillCause::MemoryRunaway {
footprint_bytes,
capacity_bytes,
domain,
},
)
.await
}
async fn kill_for(&self, task_id: &str, cause: KillCause) -> bool {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::BeginKillByTaskId {
task_id: task_id.to_string(),
cause,
reply: reply_tx,
})
.await;
let plan = Self::recv_reply(reply_rx).await;
self.finish_kill(task_id, plan).await
}
pub async fn kill_by_task_id(&self, task_id: &str) -> bool {
self.kill_for(task_id, KillCause::User).await
}
pub async fn kill_running(&self) -> usize {
let jobs = self.list().await;
futures::future::join_all(
jobs.into_iter()
.filter(|job| job.status == JobStatus::Running)
.map(|job| async move { self.kill_by_task_id(&job.task_id).await }),
)
.await
.into_iter()
.filter(|killed| *killed)
.count()
}
pub async fn kill_by_execution_key(&self, execution_key: &str) -> usize {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::BeginKillByExecutionKey {
execution_key: execution_key.to_string(),
cause: KillCause::User,
reply: reply_tx,
})
.await;
let plans = Self::recv_reply(reply_rx).await;
futures::future::join_all(
plans
.into_iter()
.map(|(task_id, plan)| async move { self.finish_kill(&task_id, plan).await }),
)
.await
.into_iter()
.filter(|killed| *killed)
.count()
}
async fn finish_kill(&self, task_id: &str, plan: KillPlan) -> bool {
let killed = match plan {
KillPlan::Done(killed) => return killed,
KillPlan::Tree(tree) => match tree.kill().await {
Ok(()) => true,
#[cfg(unix)]
Err(KillTreeError::Ended) => {
tracing::debug!(task_id, "the job ended before the kill reached it");
false
}
Err(error) => {
tracing::warn!(task_id, error = %error, "failed to kill job");
false
}
},
KillPlan::Group(group) => match crate::process_tree::kill_process_tree(group).await {
Ok(()) => true,
Err(error) => {
tracing::warn!(task_id, error = %error, "failed to kill job");
false
}
},
};
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::EndKill {
task_id: task_id.to_string(),
killed,
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
pub async fn format_running_jobs(&self) -> String {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::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(JobRequest::HasRunning { reply: reply_tx })
.await;
Self::recv_reply(reply_rx).await
}
pub(crate) async fn watch(&self, task_id: &str) -> Option<JobWatch> {
let (reply_tx, reply_rx) = async_channel::bounded(1);
self.send_command(JobRequest::Watch {
task_id: task_id.to_string(),
reply: reply_tx,
})
.await;
Self::recv_reply(reply_rx).await
}
}
#[derive(Default)]
struct ParkedOutput {
by_task: HashMap<String, Parked>,
forgotten: Vec<WeakIdLease>,
bounds: HashMap<String, (WeakIdLease, Duration)>,
launching: HashMap<String, WeakIdLease>,
}
struct Parked {
lease: WeakIdLease,
appends: Vec<ParkedAppend>,
}
type ParkedAppend = (Vec<u8>, Sender<bool>);
impl ParkedOutput {
fn launching(&mut self, task_id: &IdLease) {
self.prune();
self.launching
.insert(task_id.to_string(), task_id.downgrade());
}
fn launching_lease(&mut self, task_id: &str) -> Option<WeakIdLease> {
self.prune();
self.launching.get(task_id).cloned()
}
fn abandon(&mut self, task_id: &IdLease) -> Vec<ParkedAppend> {
self.launching.remove(task_id.as_str());
let waiting = self.take(task_id);
self.forgot(task_id);
waiting
}
fn park(
&mut self,
task_id: &IdLease,
chunk: Vec<u8>,
reply: Sender<bool>,
) -> Option<Sender<bool>> {
self.prune();
if self
.forgotten
.iter()
.any(|forgotten| forgotten.refers_to(task_id))
{
return Some(reply);
}
let parked = self
.by_task
.entry(task_id.to_string())
.or_insert_with(|| Parked {
lease: task_id.downgrade(),
appends: Vec::new(),
});
assert!(
parked.lease.refers_to(task_id),
"two live leases share the task id '{task_id}'"
);
parked.appends.push((chunk, reply));
None
}
fn take(&mut self, task_id: &IdLease) -> Vec<ParkedAppend> {
self.prune();
self.by_task
.remove(task_id.as_str())
.map(|parked| {
assert!(
parked.lease.refers_to(task_id),
"two live leases share the task id '{task_id}'"
);
parked.appends
})
.unwrap_or_default()
}
fn bound(&mut self, task_id: &IdLease, timeout: Duration) {
self.prune();
self.bounds
.insert(task_id.to_string(), (task_id.downgrade(), timeout));
}
fn take_bound(&mut self, task_id: &IdLease) -> Option<Duration> {
self.prune();
self.bounds
.remove(task_id.as_str())
.map(|(lease, timeout)| {
assert!(
lease.refers_to(task_id),
"two live leases share the task id '{task_id}'"
);
timeout
})
}
fn forgot(&mut self, task_id: &IdLease) {
self.prune();
self.forgotten.push(task_id.downgrade());
}
fn prune(&mut self) {
self.by_task
.retain(|_, parked| parked.lease.upgrade().is_some());
self.forgotten
.retain(|forgotten| forgotten.upgrade().is_some());
self.bounds
.retain(|_, (lease, _)| lease.upgrade().is_some());
self.launching.retain(|_, lease| lease.upgrade().is_some());
}
}
#[derive(Default)]
struct ReadTracker {
delta_reads: HashMap<String, (usize, usize, JobStatus)>,
}
type Jobs = HashMap<String, JobState>;
impl JobRegistryService {
pub async fn serve(self) {
let mut jobs = Jobs::new();
let mut reads = ReadTracker::default();
let mut parked = ParkedOutput::default();
while let Ok(command) = self.rx.recv().await {
match command {
JobCommand::State(command) => {
handle_state_command(&mut jobs, &mut reads, &mut parked, command).await;
}
JobCommand::Request(request) => {
let preview = self.policy.get().job_preview_bytes;
handle_job_request(
&mut jobs,
&mut reads,
&mut parked,
&self.tx,
preview,
request,
)
.await;
}
}
}
}
}
async fn handle_state_command(
jobs: &mut Jobs,
reads: &mut ReadTracker,
parked: &mut ParkedOutput,
command: StateCommand,
) {
match command {
StateCommand::Register {
pid,
task_id,
execution_key,
script,
interpreter,
mode,
output_path,
process_tree,
place,
} => {
parked.launching.remove(task_id.as_str());
let waiting = parked.take(&task_id);
let timeout = parked.take_bound(&task_id);
let key = task_id.to_string();
register_job(
jobs,
pid,
task_id,
execution_key,
script,
interpreter,
mode,
output_path,
place,
timeout,
);
if let Some(job) = jobs.get_mut(&key) {
job.process_tree = process_tree;
}
for (chunk, reply) in waiting {
append_terminal_output(jobs, &key, TerminalStream::Stdout, chunk).await;
let _ = reply.send(true).await;
}
}
StateCommand::Bound { task_id, timeout } => parked.bound(&task_id, timeout),
StateCommand::Launching { task_id } => parked.launching(&task_id),
StateCommand::Abandon { task_id } => {
if !jobs.contains_key(task_id.as_str()) {
for (_, reply) in parked.abandon(&task_id) {
let _ = reply.send(false).await;
}
}
}
StateCommand::AttachTerminalInput { task_id, input_tx } => {
if let Some(job) = jobs
.get_mut(task_id.as_str())
.filter(|job| matches!(job.info.status, JobStatus::Running))
{
job.input_tx = Some(input_tx);
}
}
StateCommand::AttachKillSwitch { task_id, kill_tx } => {
if let Some(job) = jobs.get_mut(task_id.as_str()) {
job.kill_switch = Some(kill_tx);
}
}
StateCommand::AppendTerminalOutput {
task_id,
stream,
chunk,
} => {
append_terminal_output(jobs, &task_id, stream, chunk).await;
}
StateCommand::CloseTerminalStream { task_id, stream } => {
close_terminal_stream(jobs, &task_id, stream);
}
StateCommand::Complete {
task_id,
exit_code,
output_path,
} => complete_job(jobs, &task_id, exit_code, output_path).await,
StateCommand::Fail {
task_id,
error,
output_path,
} => fail_job(jobs, &task_id, error, output_path).await,
StateCommand::TakeCompletion { task_id } => {
take_completion(jobs, reads, parked, &task_id);
}
StateCommand::Unwatch { task_id } => {
if let Some(job) = jobs.get_mut(task_id.as_str()) {
job.watchers -= 1;
forget_if_done(jobs, reads, parked, &task_id);
}
}
}
}
fn forget_if_done(
jobs: &mut Jobs,
reads: &mut ReadTracker,
parked: &mut ParkedOutput,
task_id: &str,
) {
let job = &jobs[task_id];
if job.completion_owed
&& job.info.status.delivery() == Some(Delivery::Taken)
&& job.watchers == 0
{
let job = jobs.remove(task_id).expect("the job is registered");
reads.delta_reads.remove(task_id);
parked.forgot(&job.task_id);
tracing::debug!(task_id, pid = %job.info.pid, "forgot finished job");
}
}
#[allow(clippy::too_many_lines)]
async fn handle_job_request(
jobs: &mut Jobs,
reads: &mut ReadTracker,
parked: &mut ParkedOutput,
tx: &WeakSender<JobCommand>,
script_preview_bytes: usize,
request: JobRequest,
) {
match request {
JobRequest::AppendTaskStdout {
task_id,
chunk,
reply,
} => {
if let Some(job) = jobs.get(task_id.as_str()) {
assert!(
job.task_id.same_lease(&task_id),
"two live leases share the task id '{task_id}'"
);
let running = matches!(job.info.status, JobStatus::Running);
if running {
append_terminal_output(jobs, &task_id, TerminalStream::Stdout, chunk).await;
}
let _ = reply.send(running).await;
} else if let Some(reply) = parked.park(&task_id, chunk, reply) {
let _ = reply.send(false).await;
}
}
JobRequest::Lease { task_id, reply } => {
let lease = jobs
.get(&task_id)
.map(|job| job.task_id.downgrade())
.or_else(|| parked.launching_lease(&task_id));
let _ = reply.send(lease).await;
}
JobRequest::List { reply } => {
let items = jobs.values().map(|state| state.info.clone()).collect();
let _ = reply.send(items).await;
}
JobRequest::GetByTaskId { task_id, reply } => {
let item = jobs.get(&task_id).map(|state| state.info.clone());
let _ = reply.send(item).await;
}
JobRequest::GetByTaskIdSettled { task_id, reply } => {
get_settled_by_task_id(jobs, &task_id, reply).await;
}
JobRequest::OweCompletion {
task_id,
ending,
reply,
} => owe_settled_completion(jobs, reads, parked, &task_id, ending, reply, tx).await,
JobRequest::BeginKillByTaskId {
task_id,
cause,
reply,
} => {
let plan = begin_kill(jobs, &task_id, cause).await;
let _ = reply.send(plan).await;
}
JobRequest::BeginKillByExecutionKey {
execution_key,
cause,
reply,
} => {
let plans = begin_kill_by_execution_key(jobs, &execution_key, cause).await;
let _ = reply.send(plans).await;
}
JobRequest::EndKill {
task_id,
killed,
reply,
} => {
let result = end_kill(jobs, &task_id, killed).await;
release_settled_waiters(jobs, reads, parked, &task_id, tx).await;
let _ = reply.send(result).await;
}
JobRequest::InputTerminal {
task_id,
bytes,
reply,
} => {
let result = input_terminal(jobs, &task_id, bytes).await;
let _ = reply.send(result).await;
}
JobRequest::StartOutputRedirect {
task_id,
output_path,
reply,
} => {
let result = redirect_task_output(jobs, &task_id, output_path).await;
let _ = reply.send(result).await;
}
JobRequest::TerminalOutput { task_id, reply } => {
send_terminal_output(jobs, &task_id, reply).await;
}
JobRequest::ReadJobDelta {
task_id,
cursor,
max_bytes,
tracked,
reply,
} => {
let result = read_terminal_delta(jobs, &task_id, cursor, max_bytes, !tracked)
.map(|delta| tracked_delta(reads, &task_id, delta, tracked));
let _ = reply.send(result).await;
}
JobRequest::WaitEnded {
task_id,
claim,
reply,
} => {
wait_for_end(jobs, &task_id, claim, reply).await;
}
JobRequest::TerminalStreamsClosed { task_id, reply } => {
let closed = jobs
.get(&task_id)
.is_some_and(|job| job.stdout_closed && job.stderr_closed);
let _ = reply.send(closed).await;
}
JobRequest::FormatRunning { reply } => {
let _ = reply
.send(format_running_jobs(jobs, script_preview_bytes))
.await;
}
JobRequest::HasRunning { reply } => {
let _ = reply.send(has_running_job(jobs)).await;
}
JobRequest::TakeCompletion { task_id, reply } => {
take_completion(jobs, reads, parked, &task_id);
let _ = reply.send(()).await;
}
JobRequest::Watch { task_id, reply } => {
let watch = jobs.get_mut(&task_id).map(|job| {
job.watchers += 1;
JobWatch {
tx: tx
.upgrade()
.expect("a request arrives through a live registry handle"),
task_id: job.task_id.clone(),
}
});
let _ = reply.send(watch).await;
}
}
}
async fn send_terminal_output(
jobs: &Jobs,
task_id: &str,
reply: Sender<Option<(Vec<u8>, Vec<u8>)>>,
) {
let output = jobs
.get(task_id)
.map(|job| (job.stdout_buffer.clone(), job.stderr_buffer.clone()));
let _ = reply.send(output).await;
}
fn has_running_job(jobs: &Jobs) -> bool {
jobs.values()
.any(|job| matches!(job.info.status, JobStatus::Running))
}
#[allow(clippy::too_many_arguments)]
fn register_job(
jobs: &mut Jobs,
pid: u32,
task_id: IdLease,
execution_key: String,
script: String,
interpreter: Interpreter,
mode: SandboxMode,
output_path: Option<PathBuf>,
place: JobPlace,
timeout: Option<Duration>,
) {
let info = JobInfo {
timeout,
place,
pid,
task_id: task_id.to_string(),
execution_key,
script,
interpreter,
mode,
started_at: Instant::now(),
status: JobStatus::Running,
output_path,
};
let key = task_id.to_string();
let replaced = jobs.insert(key.clone(), JobState::new(info, task_id));
assert!(
replaced.is_none(),
"two live leases share the task id '{key}'"
);
tracing::debug!(task_id = %key, pid = %pid, "registered background job");
}
impl JobState {
const fn new(info: JobInfo, task_id: IdLease) -> Self {
Self {
info,
task_id,
terminal_buffer: Vec::new(),
line_buffer: Vec::new(),
stdout_partial: Vec::new(),
stderr_partial: Vec::new(),
stdout_buffer: Vec::new(),
stderr_buffer: Vec::new(),
stdout_closed: false,
stderr_closed: false,
input_tx: None,
kill_switch: None,
process_tree: None,
kill_cause: None,
kills_in_flight: 0,
deferred_end: None,
settled_waiters: Vec::new(),
ended_waiters: Vec::new(),
output_redirect: None,
finished_at: None,
completion_owed: false,
claimed: false,
watchers: 0,
}
}
}
enum JobEnd {
Completed { exit_code: i32 },
Failed { error: String },
Killed(KillCause),
}
fn finish(job: &mut JobState, end: JobEnd) {
assert!(
matches!(job.info.status, JobStatus::Running),
"job {} ended twice: it already reads {:?}",
job.info.task_id,
job.info.status
);
let delivery = if job.claimed {
Delivery::Taken
} else {
Delivery::Pending
};
job.info.status = match end {
JobEnd::Completed { exit_code } => JobStatus::Completed {
exit_code,
delivery,
},
JobEnd::Failed { error } => JobStatus::Failed { error, delivery },
JobEnd::Killed(cause) => JobStatus::Killed { cause, delivery },
};
job.finished_at = Some(Instant::now());
for waiter in std::mem::take(&mut job.ended_waiters) {
let _ = waiter.try_send(Some(job.info.clone()));
}
job.kill_switch = None;
job.input_tx = None;
}
fn take_completion(
jobs: &mut Jobs,
reads: &mut ReadTracker,
parked: &mut ParkedOutput,
task_id: &str,
) {
if let Some(job) = jobs.get_mut(task_id) {
mark_taken(job);
forget_if_done(jobs, reads, parked, task_id);
}
}
fn mark_taken(job: &mut JobState) {
let task_id = &job.info.task_id;
let delivery = match &mut job.info.status {
JobStatus::Running => panic!("job {task_id}'s completion was taken while it runs"),
JobStatus::Completed { delivery, .. }
| JobStatus::Failed { delivery, .. }
| JobStatus::Killed { delivery, .. } => delivery,
};
assert_eq!(
*delivery,
Delivery::Pending,
"job {task_id}'s completion was taken twice"
);
*delivery = Delivery::Taken;
}
async fn owe_settled_completion(
jobs: &mut Jobs,
reads: &mut ReadTracker,
parked: &mut ParkedOutput,
task_id: &str,
ending: Result<i32, String>,
reply: Sender<Option<OwedCompletion>>,
tx: &WeakSender<JobCommand>,
) {
let Some(job) = jobs.get_mut(task_id) else {
let _ = reply.send(None).await;
return;
};
if job.kills_in_flight > 0 {
job.settled_waiters
.push(SettledWaiter::Owe { ending, reply });
return;
}
let owed = owe_completion(jobs, task_id, ending, tx).await;
forget_if_done(jobs, reads, parked, task_id);
let _ = reply.send(Some(owed)).await;
}
async fn owe_completion(
jobs: &mut Jobs,
task_id: &str,
ending: Result<i32, String>,
tx: &WeakSender<JobCommand>,
) -> OwedCompletion {
if matches!(jobs[task_id].info.status, JobStatus::Running) {
match ending {
Ok(exit_code) => complete_job(jobs, task_id, exit_code, None).await,
Err(error) => fail_job(jobs, task_id, error, None).await,
}
}
let job = jobs.get_mut(task_id).expect("the job is registered");
assert!(
!job.completion_owed,
"job {task_id}'s completion was handed out twice"
);
let delivery = if job.claimed {
Delivery::Taken
} else {
Delivery::Pending
};
assert_eq!(
job.info.status.delivery(),
Some(delivery),
"job {task_id} owes a completion it never recorded: {:?}",
job.info.status
);
job.completion_owed = true;
let info = job.info.clone();
if job.claimed {
return OwedCompletion {
info,
pending: None,
};
}
OwedCompletion {
info,
pending: Some(PendingCompletion {
tx: tx
.upgrade()
.expect("a request arrives through a live registry handle"),
task_id: Some(job.task_id.clone()),
}),
}
}
async fn append_terminal_output(
jobs: &mut Jobs,
task_id: &str,
stream: TerminalStream,
chunk: Vec<u8>,
) {
if chunk.is_empty() {
return;
}
if let Some(job) = jobs.get_mut(task_id) {
job.terminal_buffer.extend_from_slice(&chunk);
if let Some(file) = job.output_redirect.as_mut()
&& let Err(error) = file.write_all(&chunk).await
{
if matches!(job.info.status, JobStatus::Running) {
mark_job_failed(
job,
format!(
"failed to append redirected output for task {}: {error}",
job.info.task_id
),
);
}
tracing::error!(
task_id,
error = %error,
"failed to append redirected output"
);
}
let (buffer, partial) = match stream {
TerminalStream::Stdout => (&mut job.stdout_buffer, &mut job.stdout_partial),
TerminalStream::Stderr => (&mut job.stderr_buffer, &mut job.stderr_partial),
};
buffer.extend_from_slice(&chunk);
partial.extend_from_slice(&chunk);
if let Some(last_newline) = partial.iter().rposition(|byte| *byte == b'\n') {
job.line_buffer.extend(partial.drain(..=last_newline));
}
}
}
fn close_terminal_stream(jobs: &mut Jobs, task_id: &str, stream: TerminalStream) {
if let Some(job) = jobs.get_mut(task_id) {
match stream {
TerminalStream::Stdout => job.stdout_closed = true,
TerminalStream::Stderr => job.stderr_closed = true,
}
}
}
async fn complete_job(
jobs: &mut Jobs,
task_id: &str,
exit_code: i32,
output_path: Option<PathBuf>,
) {
if let Some(job) = jobs.get_mut(task_id) {
if !matches!(job.info.status, JobStatus::Running) {
tracing::debug!(
task_id,
status = ?job.info.status,
"ignoring complete for non-running job"
);
return;
}
if job.kills_in_flight > 0 {
job.deferred_end = Some(Ending::Complete {
exit_code,
output_path,
});
return;
}
if let Err(error) = finalize_output_redirect(job).await {
tracing::error!(
task_id,
error = %error,
"failed to flush redirected output on complete"
);
mark_job_failed(job, error);
return;
}
finish(job, JobEnd::Completed { exit_code });
if output_path.is_some() {
job.info.output_path = output_path;
}
tracing::debug!(task_id, exit_code = %exit_code, "job completed");
}
}
async fn fail_job(jobs: &mut Jobs, task_id: &str, error: String, output_path: Option<PathBuf>) {
if let Some(job) = jobs.get_mut(task_id) {
if !matches!(job.info.status, JobStatus::Running) {
tracing::debug!(
task_id,
status = ?job.info.status,
"ignoring fail for non-running job"
);
return;
}
if job.kills_in_flight > 0 {
job.deferred_end = Some(Ending::Fail { error, output_path });
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);
if output_path.is_some() {
job.info.output_path = output_path;
}
tracing::debug!(task_id, "job failed");
}
}
async fn begin_kill_by_execution_key(
jobs: &mut Jobs,
execution_key: &str,
cause: KillCause,
) -> Vec<(String, KillPlan)> {
let task_ids: Vec<String> = jobs
.iter()
.filter(|(_, state)| {
state.info.execution_key == execution_key
&& matches!(state.info.status, JobStatus::Running)
})
.map(|(task_id, _)| task_id.clone())
.collect();
let mut plans = Vec::with_capacity(task_ids.len());
for task_id in task_ids {
let plan = begin_kill(jobs, &task_id, cause).await;
plans.push((task_id, plan));
}
plans
}
async fn input_terminal(jobs: &Jobs, task_id: &str, bytes: Vec<u8>) -> Result<(), JobInputError> {
let Some(job) = jobs.get(task_id) else {
return Err(JobInputError::UnknownTask {
task_id: task_id.to_owned(),
});
};
if !matches!(job.info.status, JobStatus::Running) {
return Err(JobInputError::NotRunning {
task_id: task_id.to_owned(),
status: job.info.status.clone(),
});
}
let Some(tx) = &job.input_tx else {
return Err(JobInputError::NoStdin {
task_id: task_id.to_owned(),
});
};
tx.send(bytes).await.map_err(|_| JobInputError::Closed {
task_id: task_id.to_owned(),
})
}
async fn redirect_task_output(
jobs: &mut Jobs,
task_id: &str,
output_path: PathBuf,
) -> Result<Vec<u8>, String> {
let Some(job) = jobs.get_mut(task_id) else {
return Err(format!("unknown task_id: {task_id}"));
};
start_output_redirect(job, output_path).await
}
fn tracked_delta(
reads: &mut ReadTracker,
task_id: &str,
delta: JobDelta,
tracked: bool,
) -> JobRead {
let returned = (delta.cursor, delta.total_bytes, delta.status.clone());
if !tracked {
return JobRead::Delta(delta);
}
if reads.delta_reads.get(task_id) == Some(&returned) {
JobRead::Unchanged {
task_id: task_id.to_string(),
}
} else {
reads.delta_reads.insert(task_id.to_string(), returned);
JobRead::Delta(delta)
}
}
async fn wait_for_end(jobs: &mut Jobs, task_id: &str, claim: bool, reply: Sender<Option<JobInfo>>) {
match jobs.get_mut(task_id) {
Some(job) if matches!(job.info.status, JobStatus::Running) => {
job.claimed |= claim && !job.completion_owed;
job.ended_waiters.push(reply);
}
Some(job) => {
if claim && !job.completion_owed && !job.claimed {
job.claimed = true;
mark_taken(job);
}
let _ = reply.send(Some(job.info.clone())).await;
}
None => {
let _ = reply.send(None).await;
}
}
}
fn read_terminal_delta(
jobs: &Jobs,
task_id: &str,
cursor: usize,
max_bytes: usize,
lines: bool,
) -> Result<JobDelta, String> {
jobs.get(task_id).map_or_else(
|| Err(format!("unknown task_id: {task_id}")),
|job| terminal_read(job, cursor, max_bytes, lines),
)
}
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) {
finish(job, JobEnd::Failed { error });
}
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(())
}
async fn begin_kill(jobs: &mut Jobs, task_id: &str, cause: KillCause) -> KillPlan {
let Some(job) = jobs.get_mut(task_id) else {
return KillPlan::Done(false);
};
if !matches!(job.info.status, JobStatus::Running) {
tracing::warn!(task_id, "cannot kill non-running job");
return KillPlan::Done(false);
}
if let Some(kill_switch) = job.kill_switch.take() {
if kill_switch.send(()).await.is_err() {
tracing::warn!(task_id, "failed to signal runtime kill switch");
return KillPlan::Done(false);
}
if let Err(error) = finalize_output_redirect(job).await {
tracing::warn!(
task_id,
error = %error,
"failed to flush redirected output after kill switch signal"
);
}
finish(job, JobEnd::Killed(cause));
job.stdout_closed = true;
job.stderr_closed = true;
tracing::info!(task_id, "killed job via runtime kill switch");
return KillPlan::Done(true);
}
if job.kills_in_flight == 0 {
job.kill_cause = Some(cause);
}
job.kills_in_flight += 1;
let group = job.info.pid;
job.process_tree
.as_ref()
.map_or(KillPlan::Group(group), |tree| KillPlan::Tree(tree.clone()))
}
async fn end_kill(jobs: &mut Jobs, task_id: &str, killed: bool) -> bool {
let Some(job) = jobs.get_mut(task_id) else {
return false;
};
job.kills_in_flight = job.kills_in_flight.saturating_sub(1);
if killed {
job.deferred_end = None;
if matches!(job.info.status, JobStatus::Running) {
if let Err(error) = finalize_output_redirect(job).await {
tracing::warn!(
task_id,
error = %error,
"failed to flush redirected output after kill"
);
}
let cause = job
.kill_cause
.expect("a kill in flight was asked for with a cause");
finish(job, JobEnd::Killed(cause));
job.stdout_closed = true;
job.stderr_closed = true;
tracing::info!(task_id, ?cause, "killed job");
}
return true;
}
match job.deferred_end.take() {
Some(Ending::Complete {
exit_code,
output_path,
}) => complete_job(jobs, task_id, exit_code, output_path).await,
Some(Ending::Fail { error, output_path }) => {
fail_job(jobs, task_id, error, output_path).await;
}
None => {}
}
false
}
async fn get_settled_by_task_id(jobs: &mut Jobs, task_id: &str, reply: Sender<Option<JobInfo>>) {
match jobs.get_mut(task_id) {
Some(job) if job.kills_in_flight > 0 => {
job.settled_waiters.push(SettledWaiter::Read(reply));
}
Some(job) => {
let _ = reply.send(Some(job.info.clone())).await;
}
None => {
let _ = reply.send(None).await;
}
}
}
async fn release_settled_waiters(
jobs: &mut Jobs,
reads: &mut ReadTracker,
parked: &mut ParkedOutput,
task_id: &str,
tx: &WeakSender<JobCommand>,
) {
let Some(job) = jobs.get_mut(task_id) else {
return;
};
if job.kills_in_flight > 0 {
return;
}
for waiter in std::mem::take(&mut job.settled_waiters) {
match waiter {
SettledWaiter::Read(reply) => {
let _ = reply.send(Some(jobs[task_id].info.clone())).await;
}
SettledWaiter::Owe { ending, reply } => {
let owed = owe_completion(jobs, task_id, ending, tx).await;
let _ = reply.send(Some(owed)).await;
}
}
}
forget_if_done(jobs, reads, parked, task_id);
}
fn script_preview(script: &str, limit: usize) -> String {
if script.len() <= limit {
return script.to_string();
}
let end = (0..=limit)
.rev()
.find(|index| script.is_char_boundary(*index))
.unwrap_or(0);
format!("{}...", &script[..end])
}
fn format_running_jobs(jobs: &Jobs, script_preview_bytes: usize) -> 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 = script_preview(&job.info.script, script_preview_bytes);
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,
lines: bool,
) -> Result<JobDelta, String> {
let buffer = if lines {
&job.line_buffer
} else {
&job.terminal_buffer
};
let total_bytes = 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(JobDelta {
task_id: job.info.task_id.clone(),
cursor: end,
total_bytes,
bytes: buffer[cursor..end].to_vec(),
status: job.info.status.clone(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_ids::lease;
use executor_core::Executor;
use executor_core::Task;
use executor_core::tokio::TokioGlobal;
use tempfile::tempdir;
fn spawn_registry() -> JobRegistry {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
}
#[tokio::test]
async fn a_job_reports_the_timeout_it_runs_under() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
tokio::spawn(service.serve());
let bounded = crate::test_ids::lease("bounded");
let free = crate::test_ids::lease("free");
registry
.bound_by_timeout(&bounded, Duration::from_secs(600))
.await;
registry
.register(1, &bounded, "exec", "run", SandboxMode::Sandboxed, None)
.await;
registry
.register(2, &free, "exec", "run", SandboxMode::Sandboxed, None)
.await;
let info = registry
.get_by_task_id("bounded")
.await
.expect("job exists");
assert_eq!(info.timeout, Some(Duration::from_secs(600)));
let remaining = info.remaining().expect("the job is bounded");
assert!(remaining > Duration::from_secs(590), "{remaining:?}");
let info = registry.get_by_task_id("free").await.expect("job exists");
assert_eq!(info.timeout, None);
assert_eq!(info.remaining(), None);
}
#[tokio::test]
async fn a_job_keeps_its_task_id_leased_until_the_registry_forgets_it() {
let ids = crate::test_ids::RecordingIds::default();
let allocator = ids.allocator();
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
let served = tokio::spawn(service.serve());
let first = allocator.lease().unwrap();
registry
.register(1, &first, "exec", "run", SandboxMode::Sandboxed, None)
.await;
let second = allocator.lease().unwrap();
registry
.register(2, &second, "exec", "run", SandboxMode::Sandboxed, None)
.await;
registry.complete(&first, 0, None).await;
drop((first, second));
assert!(registry.get_by_task_id("alfa").await.is_some());
assert!(ids.released().is_empty(), "the registry holds both");
drop(registry.owe_completion("alfa", Ok(0)).await.unwrap());
assert_eq!(registry.list().await.len(), 1);
assert_eq!(ids.released(), ["alfa"]);
drop(registry);
served.await.expect("the service ends with its last handle");
let mut released = ids.released();
released.sort();
assert_eq!(released, ["alfa", "bravo"]);
}
#[tokio::test]
async fn a_job_sharing_a_held_jobs_pid_does_not_replace_it() {
let registry = spawn_registry();
let (old, new) = (lease("old"), lease("new"));
registry
.register(4242, &old, "exec", "first", SandboxMode::Sandboxed, None)
.await;
registry.append_stdout(&old, b"old output\n".to_vec()).await;
registry.complete(&old, 3, None).await;
registry
.register(4242, &new, "exec", "second", SandboxMode::Sandboxed, None)
.await;
registry.append_stdout(&new, b"new output\n".to_vec()).await;
let mut jobs = registry.list().await;
jobs.sort_by(|a, b| a.task_id.cmp(&b.task_id));
assert_eq!(
jobs.iter()
.map(|job| (job.task_id.as_str(), job.pid))
.collect::<Vec<_>>(),
[("new", 4242), ("old", 4242)]
);
assert_eq!(
registry.get_by_task_id("old").await.unwrap().status,
JobStatus::Completed {
exit_code: 3,
delivery: Delivery::Pending
}
);
assert_eq!(
registry.get_by_task_id("new").await.unwrap().status,
JobStatus::Running
);
let (stdout, _) = registry.terminal_output("old").await.unwrap();
assert_eq!(stdout, b"old output\n");
let (stdout, _) = registry.terminal_output("new").await.unwrap();
assert_eq!(stdout, b"new output\n");
let read = registry
.terminal_read("old", 0, 1024)
.await
.unwrap()
.into_delta()
.unwrap();
assert_eq!(read.bytes, b"old output\n");
let owed = registry
.owe_completion("old", Ok(3))
.await
.expect("the first job is still registered");
assert!(owed.pending.is_some(), "its completion is still takeable");
drop(owed);
assert!(registry.get_by_task_id("old").await.is_none());
assert_eq!(
registry.get_by_task_id("new").await.unwrap().status,
JobStatus::Running,
"the second job is untouched"
);
}
#[tokio::test]
async fn a_claiming_wait_reads_the_job_taken_before_its_flow_settles() {
let registry = spawn_registry();
let (ended, ending) = (lease("ended"), lease("ending"));
registry
.register(1, &ended, "exec", "run", SandboxMode::Sandboxed, None)
.await;
registry
.register(2, &ending, "exec", "run", SandboxMode::Sandboxed, None)
.await;
let ended_watch = registry.watch("ended").await.expect("ended is held");
let ending_watch = registry.watch("ending").await.expect("ending is held");
registry.complete(&ended, 0, None).await;
let taken = JobStatus::Completed {
exit_code: 0,
delivery: Delivery::Taken,
};
assert_eq!(registry.wait_taking("ended").await.unwrap().status, taken);
assert_eq!(
registry.get_by_task_id("ended").await.unwrap().status,
taken
);
let mut waiting = std::pin::pin!(registry.wait_taking("ending"));
assert!(
futures_lite::future::poll_once(waiting.as_mut())
.await
.is_none()
);
registry.complete(&ending, 0, None).await;
assert_eq!(waiting.await.unwrap().status, taken);
assert_eq!(
registry.get_by_task_id("ending").await.unwrap().status,
taken
);
assert!(
!registry
.list()
.await
.iter()
.any(|job| job.status.completion_pending()),
"no turn is owed for a job its waiter read"
);
drop(ended_watch);
assert!(registry.terminal_output("ended").await.is_some());
for task_id in ["ended", "ending"] {
let owed = registry.owe_completion(task_id, Ok(0)).await.unwrap();
assert!(owed.pending.is_none(), "{task_id} owes nothing");
}
drop(ending_watch);
assert!(registry.get_by_task_id("ending").await.is_none());
}
#[tokio::test]
async fn a_claimed_job_unwatched_before_its_flow_settles_is_forgotten_as_it_settles() {
let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
let registry = spawn_registry();
let task_id = ids.lease().expect("river is free");
registry
.register(1, &task_id, "exec", "run", SandboxMode::Sandboxed, None)
.await;
let watch = registry.watch("river").await.expect("river is held");
let mut waiting = std::pin::pin!(registry.wait_taking("river"));
assert!(
futures_lite::future::poll_once(waiting.as_mut())
.await
.is_none()
);
registry.complete(&task_id, 0, None).await;
let taken = JobStatus::Completed {
exit_code: 0,
delivery: Delivery::Taken,
};
assert_eq!(waiting.await.unwrap().status, taken);
drop(watch);
assert!(
registry.terminal_output("river").await.is_some(),
"the flow still reads the job it has yet to settle"
);
let owed = registry.owe_completion("river", Ok(0)).await.unwrap();
assert!(owed.pending.is_none(), "the waiter took the completion");
assert_eq!(owed.info.status, taken);
drop(task_id);
assert!(registry.list().await.is_empty(), "the job is forgotten");
assert_eq!(&*ids.lease().expect("river is free again"), "river");
}
#[tokio::test]
async fn a_taken_completion_forgets_the_job_and_releases_its_id() {
let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
let registry = spawn_registry();
let river = ids.lease().unwrap();
registry
.register(1, &river, "exec", "run", SandboxMode::Sandboxed, None)
.await;
registry.append_stdout(&river, b"done\n".to_vec()).await;
registry.complete(&river, 0, None).await;
drop(river);
registry
.terminal_read("river", 0, 1024)
.await
.expect("a finished job reads until delivered");
assert!(ids.lease().is_err(), "the registry holds river");
let watch = registry.watch("river").await.expect("river is held");
let owed = registry.owe_completion("river", Ok(0)).await.unwrap();
drop(owed);
assert_eq!(
registry.get_by_task_id("river").await.unwrap().status,
JobStatus::Completed {
exit_code: 0,
delivery: Delivery::Taken
}
);
assert!(ids.lease().is_err(), "the watch holds river");
drop(watch);
assert!(registry.list().await.is_empty(), "the job is forgotten");
assert!(registry.get_by_task_id("river").await.is_none());
assert!(registry.terminal_read("river", 0, 1024).await.is_err());
assert!(!registry.kill_by_task_id("river").await);
assert!(
registry
.terminal_input("river", b"x".to_vec())
.await
.is_err()
);
let again = ids.lease().expect("river went back to the allocator");
registry
.register(2, &again, "exec", "run", SandboxMode::Sandboxed, None)
.await;
registry.append_stdout(&again, b"done\n".to_vec()).await;
registry.complete(&again, 0, None).await;
registry
.terminal_read("river", 0, 1024)
.await
.expect("a new job under a reused word reads afresh");
}
#[tokio::test]
async fn task_output_appended_before_registration_lands_first_and_in_order() {
let registry = spawn_registry();
let early = lease("early");
let appends = {
let registry = registry.clone();
let early = early.clone();
tokio::spawn(async move {
registry.append_task_stdout(&early, b"one\n".to_vec()).await;
registry.append_task_stdout(&early, b"two\n".to_vec()).await;
})
};
tokio::task::yield_now().await;
assert!(!appends.is_finished());
assert!(registry.get_by_task_id("early").await.is_none());
registry
.register(9, &early, "exec-e", "run", SandboxMode::Sandboxed, None)
.await;
appends.await.expect("appends are released by registration");
registry.append_stdout(&early, b"three\n".to_vec()).await;
let (stdout, _) = registry.terminal_output("early").await.expect("job exists");
assert_eq!(stdout, b"one\ntwo\nthree\n");
}
#[tokio::test]
async fn parked_output_never_reaches_a_later_job_under_the_same_word() {
let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
let registry = spawn_registry();
let first = ids.lease().unwrap();
let reporter = {
let registry = registry.clone();
let first = first.clone();
tokio::spawn(async move {
registry
.append_task_stdout(&first, b"stale\n".to_vec())
.await;
})
};
tokio::task::yield_now().await;
assert!(!reporter.is_finished(), "the report is parked");
drop(first);
assert!(ids.lease().is_err(), "the waiting reporter holds river");
reporter.abort();
assert!(reporter.await.unwrap_err().is_cancelled());
let second = ids.lease().expect("parked output holds no lease");
registry
.register(2, &second, "exec", "run", SandboxMode::Sandboxed, None)
.await;
registry
.append_task_stdout(&second, b"fresh\n".to_vec())
.await;
let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
assert_eq!(stdout, b"fresh\n");
}
#[tokio::test]
async fn output_for_a_forgotten_job_is_dropped() {
let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
let registry = spawn_registry();
let river = ids.lease().unwrap();
registry
.register(1, &river, "exec", "run", SandboxMode::Sandboxed, None)
.await;
registry.complete(&river, 0, None).await;
drop(registry.owe_completion("river", Ok(0)).await.unwrap());
assert!(registry.list().await.is_empty(), "the job is forgotten");
tokio::time::timeout(
std::time::Duration::from_secs(5),
registry.append_task_stdout(&river, b"late\n".to_vec()),
)
.await
.expect("a report to a forgotten job is answered");
assert!(registry.get_by_task_id("river").await.is_none());
drop(river);
let again = ids.lease().expect("nothing kept river");
registry
.register(2, &again, "exec", "run", SandboxMode::Sandboxed, None)
.await;
let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
assert!(stdout.is_empty(), "the late report reached no job");
}
#[tokio::test]
async fn unchanged_terminal_read_is_refused_then_succeeds_after_new_output() {
let registry = spawn_registry();
registry
.register(
7,
&lease("alpha"),
"exec-a",
"run",
SandboxMode::Sandboxed,
None,
)
.await;
registry
.append_stdout(&lease("alpha"), b"one".to_vec())
.await;
let first = registry
.terminal_read("alpha", 0, 1024)
.await
.expect("first read succeeds")
.into_delta()
.expect("the first read is a delta");
let second = registry.terminal_read("alpha", first.cursor, 1024).await;
assert!(
matches!(
&second,
Ok(JobRead::Unchanged { task_id }) if task_id == "alpha"
),
"an unchanged repeat read is reported as a poll: {second:?}"
);
registry
.append_stdout(&lease("alpha"), b"two".to_vec())
.await;
let third = registry
.terminal_read("alpha", first.cursor, 1024)
.await
.expect("read succeeds once output changed")
.into_delta()
.expect("changed output reads as a delta");
assert_eq!(third.bytes, b"two");
}
#[tokio::test]
async fn test_job_registry_lifecycle() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
12345,
&lease("amber"),
"exec-test",
"sleep 10",
SandboxMode::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");
assert_eq!(jobs[0].execution_key, "exec-test");
assert!(matches!(jobs[0].status, JobStatus::Running));
registry.complete(&lease("amber"), 0, None).await;
let job = registry.get_by_task_id("amber").await.unwrap();
assert_eq!(
job.status,
JobStatus::Completed {
exit_code: 0,
delivery: Delivery::Pending
}
);
}
#[tokio::test]
async fn test_format_running_jobs() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
1,
&lease("alpha"),
"exec-a",
"echo hello",
SandboxMode::Sandboxed,
None,
)
.await;
registry
.register(
2,
&lease("beta"),
"exec-b",
"sleep 5",
SandboxMode::Sandboxed,
None,
)
.await;
registry.complete(&lease("beta"), 0, None).await;
let running = registry.format_running_jobs().await;
assert!(running.contains("task alpha"));
assert!(!running.contains("task beta"));
}
#[tokio::test]
async fn test_output_redirect_streams_full_output() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
let temp = tempdir().unwrap();
let redirect_path = temp.path().join("stream.log");
registry
.register(
101,
&lease("stream"),
"exec-stream",
"printf one",
SandboxMode::Sandboxed,
None,
)
.await;
registry
.append_stdout(&lease("stream"), b"line1\nline2\n".to_vec())
.await;
let snapshot = registry
.start_output_redirect("stream", redirect_path.clone())
.await
.unwrap();
assert_eq!(String::from_utf8_lossy(&snapshot), "line1\nline2\n");
registry
.append_stderr(&lease("stream"), b"line3\n".to_vec())
.await;
registry.complete(&lease("stream"), 0, None).await;
let job = registry.get_by_task_id("stream").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(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
202,
&lease("delta"),
"exec-delta",
"tail -f log",
SandboxMode::Sandboxed,
None,
)
.await;
registry
.append_stdout(&lease("delta"), b"hello ".to_vec())
.await;
registry
.append_stderr(&lease("delta"), b"world".to_vec())
.await;
let first = registry
.terminal_read("delta", 0, 6)
.await
.unwrap()
.into_delta()
.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("delta", first.cursor, 32)
.await
.unwrap()
.into_delta()
.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 monitor_reads_whole_lines_when_partial_writes_interleave() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
203,
&lease("lines"),
"exec-lines",
"tail -F f",
SandboxMode::Sandboxed,
None,
)
.await;
let lines = lease("lines");
registry.append_stderr(&lines, b"tail: ".to_vec()).await;
registry.append_stdout(&lines, b"rotated\n".to_vec()).await;
registry
.append_stderr(&lines, b"'f' has been replaced\n".to_vec())
.await;
registry.append_stdout(&lines, b"unfinished".to_vec()).await;
let lines = registry.monitor_read("lines", 0, usize::MAX).await.unwrap();
assert_eq!(
String::from_utf8_lossy(&lines.bytes),
"rotated\ntail: 'f' has been replaced\n"
);
let merged = registry
.terminal_read("lines", 0, usize::MAX)
.await
.unwrap()
.into_delta()
.unwrap();
assert_eq!(
String::from_utf8_lossy(&merged.bytes),
"tail: rotated\n'f' has been replaced\nunfinished"
);
}
#[tokio::test]
async fn test_kill_by_execution_key_no_match() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
1,
&lease("alpha"),
"exec-a",
"echo hello",
SandboxMode::Sandboxed,
None,
)
.await;
registry.complete(&lease("alpha"), 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(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
555,
&lease("switch"),
"exec-kill-switch",
"sleep 10",
SandboxMode::Sandboxed,
None,
)
.await;
let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
registry.attach_kill_switch(&lease("switch"), kill_tx).await;
assert!(registry.kill_by_task_id("switch").await);
assert!(kill_rx.recv().await.is_ok());
let job = registry
.get_by_task_id("switch")
.await
.expect("job should exist");
assert!(matches!(job.status, JobStatus::Killed { .. }));
}
#[tokio::test]
async fn a_finished_job_releases_its_input_sender_and_refuses_input() {
let registry = spawn_registry();
registry
.register(
557,
&lease("input"),
"exec-input",
"cat",
SandboxMode::Sandboxed,
None,
)
.await;
let (input_tx, input_rx) = async_channel::unbounded::<Vec<u8>>();
registry
.attach_terminal_input(&lease("input"), input_tx)
.await;
registry
.terminal_input("input", b"x".to_vec())
.await
.expect("a running job takes input");
assert_eq!(input_rx.recv().await.expect("input arrives"), b"x");
registry.complete(&lease("input"), 0, None).await;
let error = registry
.terminal_input("input", b"y".to_vec())
.await
.expect_err("a finished job refuses input");
assert!(matches!(error, JobInputError::NotRunning { .. }), "{error}");
assert!(input_rx.is_closed(), "the registry must drop its sender");
}
#[tokio::test]
async fn test_complete_does_not_override_killed_status() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
556,
&lease("finished"),
"exec-killed-complete",
"sleep 10",
SandboxMode::Sandboxed,
None,
)
.await;
let (kill_tx, _kill_rx) = async_channel::bounded::<()>(1);
registry
.attach_kill_switch(&lease("finished"), kill_tx)
.await;
assert!(registry.kill_by_task_id("finished").await);
registry.complete(&lease("finished"), 0, None).await;
let job = registry
.get_by_task_id("finished")
.await
.expect("job should exist");
assert!(matches!(job.status, JobStatus::Killed { .. }));
}
#[tokio::test]
async fn test_format_running_jobs_cuts_a_multibyte_script_at_a_boundary() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
let script = "æ—¥".repeat(30);
let preview_bytes = crate::output_policy::fixture::LIMITS.job_preview_bytes;
assert!(!script.is_char_boundary(preview_bytes));
registry
.register(
1,
&lease("cjk"),
"exec-cjk",
&script,
SandboxMode::Sandboxed,
None,
)
.await;
let running = registry.format_running_jobs().await;
assert!(
running.contains(&format!("`{}...`", "æ—¥".repeat(16))),
"{running}"
);
assert_eq!(script_preview("short", 50), "short");
assert_eq!(script_preview(&"x".repeat(50), 50), "x".repeat(50));
assert_eq!(
script_preview(&"x".repeat(51), 50),
format!("{}...", "x".repeat(50))
);
assert_eq!(script_preview("abcdef", 3), "abc...");
}
fn running_job(pid: u32) -> Jobs {
let mut jobs = Jobs::new();
register_job(
&mut jobs,
pid,
lease("task"),
"exec".to_string(),
"true".to_string(),
Interpreter::Shell,
SandboxMode::Sandboxed,
None,
JobPlace::Host,
None,
);
jobs
}
#[tokio::test]
async fn overlapping_kills_hold_the_deferred_ending_until_the_last_ends() {
let mut jobs = running_job(7);
let user = KillCause::User;
assert!(matches!(
begin_kill(&mut jobs, "task", user).await,
KillPlan::Group(7)
));
assert!(matches!(
begin_kill(&mut jobs, "task", user).await,
KillPlan::Group(7)
));
complete_job(&mut jobs, "task", 0, None).await;
assert_eq!(
jobs["task"].info.status,
JobStatus::Running,
"the ending waits"
);
assert!(!end_kill(&mut jobs, "task", false).await);
assert_eq!(
jobs["task"].info.status,
JobStatus::Running,
"the other kill still runs"
);
assert!(!end_kill(&mut jobs, "task", false).await);
assert_eq!(
jobs["task"].info.status,
JobStatus::Completed {
exit_code: 0,
delivery: Delivery::Pending
},
"the last kill to fail releases the ending"
);
}
#[tokio::test]
async fn a_successful_kill_wins_over_a_deferred_ending() {
let mut jobs = running_job(8);
assert!(matches!(
begin_kill(&mut jobs, "task", KillCause::User).await,
KillPlan::Group(8)
));
complete_job(&mut jobs, "task", 0, None).await;
assert!(end_kill(&mut jobs, "task", true).await);
assert_eq!(
jobs["task"].info.status,
JobStatus::Killed {
cause: KillCause::User,
delivery: Delivery::Pending
}
);
}
#[tokio::test]
async fn the_settled_read_waits_for_a_kill_in_flight() {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
.register(
557,
&lease("settled"),
"exec-settled",
"sleep 10",
SandboxMode::Sandboxed,
None,
)
.await;
let (reply_tx, reply_rx) = async_channel::bounded(1);
registry
.send_command(JobRequest::BeginKillByTaskId {
task_id: "settled".to_string(),
cause: KillCause::User,
reply: reply_tx,
})
.await;
let plan = JobRegistry::recv_reply(reply_rx).await;
assert!(matches!(plan, KillPlan::Group(557)));
registry.complete(&lease("settled"), 137, None).await;
let running = registry.get_by_task_id("settled").await;
assert!(matches!(
running.expect("job should exist").status,
JobStatus::Running
));
let waiting = {
let registry = registry.clone();
tokio::spawn(async move { registry.get_by_task_id_settled("settled").await })
};
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
assert!(!waiting.is_finished(), "the kill is still in flight");
let (reply_tx, reply_rx) = async_channel::bounded(1);
registry
.send_command(JobRequest::EndKill {
task_id: "settled".to_string(),
killed: true,
reply: reply_tx,
})
.await;
assert!(JobRegistry::recv_reply(reply_rx).await);
let job = waiting.await.unwrap().expect("job should exist");
assert!(matches!(job.status, JobStatus::Killed { .. }));
}
fn host_sees_owed_turn(jobs: &[JobInfo]) -> bool {
jobs.iter()
.any(|job| job.status == JobStatus::Running || job.status.completion_pending())
}
#[tokio::test]
async fn a_job_reads_its_completion_pending_from_the_transition_that_finishes_it() {
let registry = spawn_registry();
registry
.register(
9,
&lease("owed"),
"exec",
"run",
SandboxMode::Sandboxed,
None,
)
.await;
registry.complete(&lease("owed"), 0, None).await;
let jobs = registry.list().await;
assert!(
host_sees_owed_turn(&jobs),
"a finished job whose completion was never delivered reads as done: {jobs:?}"
);
let owed = registry
.owe_completion("owed", Ok(0))
.await
.expect("the job is registered");
assert_eq!(owed.info.status.kill_cause(), None);
let jobs = registry.list().await;
assert!(host_sees_owed_turn(&jobs), "{jobs:?}");
drop(owed);
let jobs = registry.list().await;
assert!(jobs.is_empty(), "{jobs:?}");
assert!(!host_sees_owed_turn(&jobs));
}
#[tokio::test]
async fn a_completion_owed_by_a_job_still_running_ends_it_pending() {
let registry = spawn_registry();
registry
.register(
10,
&lease("lost"),
"exec",
"run",
SandboxMode::Sandboxed,
None,
)
.await;
let owed = registry
.owe_completion("lost", Err("output could not be saved".to_string()))
.await
.expect("the job is registered");
assert_eq!(owed.info.status.kill_cause(), None);
let job = registry
.get_by_task_id("lost")
.await
.expect("job should exist");
assert_eq!(
job.status,
JobStatus::Failed {
error: "output could not be saved".to_string(),
delivery: Delivery::Pending
}
);
assert!(
registry
.owe_completion("task-never-registered", Ok(0))
.await
.is_none()
);
}
#[tokio::test]
async fn a_completion_owed_during_a_kill_waits_for_its_outcome() {
let registry = spawn_registry();
registry
.register(
11,
&lease("kill"),
"exec",
"run",
SandboxMode::Sandboxed,
None,
)
.await;
let (reply_tx, reply_rx) = async_channel::bounded(1);
registry
.send_command(JobRequest::BeginKillByTaskId {
task_id: "kill".to_string(),
cause: KillCause::User,
reply: reply_tx,
})
.await;
assert!(matches!(
JobRegistry::recv_reply(reply_rx).await,
KillPlan::Group(11)
));
let (reply_tx, owed) = async_channel::bounded(1);
registry
.send_command(JobRequest::OweCompletion {
task_id: "kill".to_string(),
ending: Ok(137),
reply: reply_tx,
})
.await;
assert_eq!(
registry
.get_by_task_id("kill")
.await
.expect("job should exist")
.status,
JobStatus::Running
);
assert!(owed.is_empty(), "the kill is still in flight");
let (reply_tx, reply_rx) = async_channel::bounded(1);
registry
.send_command(JobRequest::EndKill {
task_id: "kill".to_string(),
killed: true,
reply: reply_tx,
})
.await;
assert!(JobRegistry::recv_reply(reply_rx).await);
let owed = JobRegistry::recv_reply(owed)
.await
.expect("the job is registered");
assert_eq!(owed.info.status.kill_cause(), Some(KillCause::User));
assert_eq!(
registry
.get_by_task_id("kill")
.await
.expect("job should exist")
.status,
JobStatus::Killed {
cause: KillCause::User,
delivery: Delivery::Pending
}
);
}
#[tokio::test]
#[should_panic(expected = "handed out twice")]
async fn a_completion_is_handed_out_once() {
let (tx, _rx) = async_channel::unbounded();
let weak = tx.downgrade();
let mut jobs = Jobs::new();
register_job(
&mut jobs,
12,
lease("twice"),
"exec".to_string(),
"run".to_string(),
Interpreter::Shell,
SandboxMode::Sandboxed,
None,
JobPlace::Host,
None,
);
let _first = owe_completion(&mut jobs, "twice", Ok(0), &weak).await;
let _second = owe_completion(&mut jobs, "twice", Ok(0), &weak).await;
}
}