use std::sync::Arc;
use aither_core::WeakIdLease;
use aither_core::llm::{CommandOutcome, CommandResult, CommandStream, Interruption};
use crate::events::ShellEvents;
use crate::job_registry::{
JobInfo, JobInputError, JobRead, JobRegistry, JobStatus, JobWatch, KillCause,
};
use crate::output::{MediaResolution, OutputFormat, OutputStore};
use crate::wording::CommandKilled;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunOutcome {
Exited {
code: i32,
},
Killed(KillCause),
}
#[derive(Debug, Clone)]
pub struct ScriptResult {
pub stdout: CommandStream,
pub stderr: Option<CommandStream>,
pub outcome: RunOutcome,
pub interruptions: Vec<Interruption>,
}
impl ScriptResult {
pub(crate) fn into_command_result(self, task_id: &str, store: &OutputStore) -> CommandResult {
let outcome = match self.outcome {
RunOutcome::Exited { code } => CommandOutcome::Exited { code },
RunOutcome::Killed(cause) => CommandOutcome::Killed {
task_id: task_id.to_owned(),
notice: store.wording().command_killed(&CommandKilled::of(&cause)),
},
};
CommandResult {
stdout: self.stdout,
stderr: self.stderr,
outcome,
interruptions: self.interruptions,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum JobWaitError {
#[error("job {task_id} failed: {error}")]
Failed {
task_id: String,
error: String,
},
#[error("job {task_id}'s output could not be stored: {source}")]
Output {
task_id: String,
source: std::io::Error,
},
}
#[derive(Debug, Clone)]
pub struct Jobs {
pub(crate) registry: JobRegistry,
events: ShellEvents,
outputs: OutputStore,
}
impl Jobs {
pub(crate) const fn new(
registry: JobRegistry,
events: ShellEvents,
outputs: OutputStore,
) -> Self {
Self {
registry,
events,
outputs,
}
}
pub async fn list(&self) -> Vec<JobInfo> {
self.registry.list().await
}
pub async fn get(&self, task_id: &str) -> Option<Job> {
let watch = self.registry.watch(task_id).await?;
Some(Job::new(self.clone(), task_id.to_owned(), watch))
}
pub async fn output_appender(&self, task_id: &str) -> Option<JobOutputAppender> {
Some(JobOutputAppender {
registry: self.registry.clone(),
task_id: self.registry.task_lease(task_id).await?,
})
}
pub async fn kill(&self, task_id: &str) -> bool {
self.registry.kill_by_task_id(task_id).await
}
pub async fn kill_all(&self) -> usize {
self.registry.kill_running().await
}
#[must_use]
pub fn events(&self) -> ShellEvents {
self.events.clone()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use]
pub enum AppendOutcome {
Appended,
JobEnded,
}
#[derive(Debug, Clone)]
pub struct JobOutputAppender {
registry: JobRegistry,
task_id: WeakIdLease,
}
impl JobOutputAppender {
pub async fn append(&self, bytes: &[u8]) -> AppendOutcome {
let Some(task_id) = self.task_id.upgrade() else {
return AppendOutcome::JobEnded;
};
if self
.registry
.append_task_stdout(&task_id, bytes.to_vec())
.await
{
AppendOutcome::Appended
} else {
AppendOutcome::JobEnded
}
}
}
#[derive(Debug, Clone)]
pub struct Job {
task_id: String,
jobs: Jobs,
_watch: Arc<JobWatch>,
}
impl Job {
pub(crate) fn new(jobs: Jobs, task_id: String, watch: JobWatch) -> Self {
Self {
task_id,
jobs,
_watch: Arc::new(watch),
}
}
#[must_use]
pub fn task_id(&self) -> &str {
&self.task_id
}
pub async fn info(&self) -> JobInfo {
self.jobs
.registry
.get_by_task_id(&self.task_id)
.await
.expect("the job this handle watches is held")
}
pub async fn wait(&self) -> Result<ScriptResult, JobWaitError> {
let ended = self
.jobs
.registry
.wait_taking(&self.task_id)
.await
.expect("the job this handle watches is held");
let outcome = match ended.status {
JobStatus::Running => unreachable!("a wait ends once the job stopped running"),
JobStatus::Completed { exit_code, .. } => RunOutcome::Exited { code: exit_code },
JobStatus::Failed { error, .. } => {
return Err(JobWaitError::Failed {
task_id: self.task_id.clone(),
error,
});
}
JobStatus::Killed { cause, .. } => RunOutcome::Killed(cause),
};
let (stdout, stderr) = self
.jobs
.registry
.terminal_output(&self.task_id)
.await
.expect("the job this handle watches is held");
let outputs = &self.jobs.outputs;
let output = |source| JobWaitError::Output {
task_id: self.task_id.clone(),
source,
};
let stdout = match &ended.output_path {
Some(path) => outputs.stream_of_file(path).await,
None => {
outputs
.save(&stdout, OutputFormat::Text, MediaResolution::Auto)
.await
}
}
.map_err(output)?;
let stderr = outputs
.save(&stderr, OutputFormat::Text, MediaResolution::Auto)
.await
.map_err(output)?;
let stderr = (!stderr.is_empty()).then_some(stderr);
Ok(ScriptResult {
stdout,
stderr,
outcome,
interruptions: Vec::new(),
})
}
pub async fn read(&self, cursor: usize, max_bytes: usize) -> Result<JobRead, String> {
self.jobs
.registry
.terminal_read(&self.task_id, cursor, max_bytes)
.await
}
pub async fn input(&self, bytes: Vec<u8>) -> Result<(), JobInputError> {
self.jobs
.registry
.terminal_input(&self.task_id, bytes)
.await
}
pub async fn kill(&self) -> bool {
self.jobs.kill(&self.task_id).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::job_registry::job_registry_channel;
use crate::policy::SandboxMode;
use crate::test_ids::lease;
use executor_core::Executor;
use executor_core::Task;
use executor_core::tokio::TokioGlobal;
fn spawn_registry() -> JobRegistry {
let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
TokioGlobal
.spawn(async move { service.serve().await })
.detach();
registry
}
async fn appender(registry: &JobRegistry, task_id: &str) -> JobOutputAppender {
JobOutputAppender {
registry: registry.clone(),
task_id: registry.task_lease(task_id).await.expect("the job is held"),
}
}
#[tokio::test]
async fn appended_lines_interleave_with_the_jobs_own_output() {
let registry = spawn_registry();
registry
.register(
1,
&lease("river"),
"exec",
"run",
SandboxMode::Sandboxed,
None,
)
.await;
let appender = appender(®istry, "river").await;
registry
.append_stdout(&lease("river"), b"one\n".to_vec())
.await;
assert_eq!(
appender.append(b"progress\n").await,
AppendOutcome::Appended
);
registry
.append_stdout(&lease("river"), b"two\n".to_vec())
.await;
let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
assert_eq!(stdout, b"one\nprogress\ntwo\n");
let JobRead::Delta(delta) = registry
.terminal_read("river", 0, 1024)
.await
.expect("job exists")
else {
panic!("a first read is a delta");
};
assert_eq!(delta.bytes, b"one\nprogress\ntwo\n");
}
#[tokio::test]
async fn a_launching_job_takes_appends_ahead_of_its_registration() {
let registry = spawn_registry();
let river = lease("river");
registry.launching(&river).await;
let appender = appender(®istry, "river").await;
let append = tokio::spawn(async move { appender.append(b"early\n").await });
tokio::task::yield_now().await;
assert!(!append.is_finished(), "the append waits for the job");
registry
.register(1, &river, "exec", "run", SandboxMode::Sandboxed, None)
.await;
assert_eq!(append.await.unwrap(), AppendOutcome::Appended);
registry.append_stdout(&river, b"late\n".to_vec()).await;
let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
assert_eq!(stdout, b"early\nlate\n");
}
#[tokio::test]
async fn a_launch_that_never_registers_releases_its_appenders() {
let registry = spawn_registry();
let river = lease("river");
registry.launching(&river).await;
let appender = appender(®istry, "river").await;
let waiting = {
let appender = appender.clone();
tokio::spawn(async move { appender.append(b"early\n").await })
};
tokio::task::yield_now().await;
registry.abandon_launch(&river).await;
assert_eq!(waiting.await.unwrap(), AppendOutcome::JobEnded);
assert_eq!(appender.append(b"more\n").await, AppendOutcome::JobEnded);
assert!(registry.task_lease("river").await.is_none());
}
#[tokio::test]
async fn a_held_appender_does_nothing_once_the_job_ended() {
let registry = spawn_registry();
registry
.register(
1,
&lease("river"),
"exec",
"run",
SandboxMode::Sandboxed,
None,
)
.await;
let appender = appender(®istry, "river").await;
registry.complete(&lease("river"), 0, None).await;
assert_eq!(appender.append(b"late\n").await, AppendOutcome::JobEnded);
let (stdout, _) = registry
.terminal_output("river")
.await
.expect("job is held");
assert_eq!(stdout, b"");
}
#[tokio::test]
async fn an_appender_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();
registry
.register(1, &first, "exec", "run", SandboxMode::Sandboxed, None)
.await;
let appender = appender(®istry, "river").await;
registry.complete(&first, 0, None).await;
drop(registry.owe_completion("river", Ok(0)).await.unwrap());
drop(first);
assert!(registry.list().await.is_empty(), "the job is forgotten");
let second = ids.lease().expect("nothing keeps river");
registry
.register(2, &second, "exec", "run", SandboxMode::Sandboxed, None)
.await;
assert_eq!(appender.append(b"stale\n").await, AppendOutcome::JobEnded);
let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
assert!(stdout.is_empty(), "the stale appender reached no job");
}
}