Skip to main content

aither_sandbox/
jobs.rs

1//! A shell's jobs: the handle that lists, reads, feeds, waits for and kills
2//! them.
3
4use std::sync::Arc;
5
6use aither_core::WeakIdLease;
7use aither_core::llm::{CommandOutcome, CommandResult, CommandStream, Interruption};
8
9use crate::events::ShellEvents;
10use crate::job_registry::{
11    JobInfo, JobInputError, JobRead, JobRegistry, JobStatus, JobWatch, KillCause,
12};
13use crate::output::{MediaResolution, OutputFormat, OutputStore};
14use crate::wording::CommandKilled;
15
16/// How a script ended.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum RunOutcome {
19    /// It ran to its end.
20    Exited {
21        /// Its exit code.
22        code: i32,
23    },
24    /// It was killed, and why.
25    Killed(KillCause),
26}
27
28/// What a script printed and how it ended, as data: the embedder words it
29/// where it hands a result to its model.
30#[derive(Debug, Clone)]
31pub struct ScriptResult {
32    /// What the script wrote to its stdout.
33    pub stdout: CommandStream,
34    /// What it wrote to its stderr, when it wrote any.
35    pub stderr: Option<CommandStream>,
36    /// How it ended.
37    pub outcome: RunOutcome,
38    /// The sleep and offline intervals it ran through.
39    pub interruptions: Vec<Interruption>,
40}
41
42impl ScriptResult {
43    /// The result a tool returns for the script of task `task_id`, a kill
44    /// worded by the store's wording.
45    pub(crate) fn into_command_result(self, task_id: &str, store: &OutputStore) -> CommandResult {
46        let outcome = match self.outcome {
47            RunOutcome::Exited { code } => CommandOutcome::Exited { code },
48            RunOutcome::Killed(cause) => CommandOutcome::Killed {
49                task_id: task_id.to_owned(),
50                notice: store.wording().command_killed(&CommandKilled::of(&cause)),
51            },
52        };
53        CommandResult {
54            stdout: self.stdout,
55            stderr: self.stderr,
56            outcome,
57            interruptions: self.interruptions,
58        }
59    }
60}
61
62/// Why waiting for a job did not end in a result.
63#[derive(Debug, thiserror::Error)]
64pub enum JobWaitError {
65    /// The job failed rather than exited.
66    #[error("job {task_id} failed: {error}")]
67    Failed {
68        /// The job.
69        task_id: String,
70        /// What went wrong.
71        error: String,
72    },
73    /// The job's output could not be stored.
74    #[error("job {task_id}'s output could not be stored: {source}")]
75    Output {
76        /// The job.
77        task_id: String,
78        /// The store's error.
79        source: std::io::Error,
80    },
81}
82
83/// The jobs of one shell: every script that outlived its call, was started
84/// in the background or watched by a monitor.
85///
86/// Cloning shares the shell's jobs.
87#[derive(Debug, Clone)]
88pub struct Jobs {
89    pub(crate) registry: JobRegistry,
90    events: ShellEvents,
91    outputs: OutputStore,
92}
93
94impl Jobs {
95    pub(crate) const fn new(
96        registry: JobRegistry,
97        events: ShellEvents,
98        outputs: OutputStore,
99    ) -> Self {
100        Self {
101            registry,
102            events,
103            outputs,
104        }
105    }
106
107    /// Every job the shell holds, running or ended and not yet taken.
108    pub async fn list(&self) -> Vec<JobInfo> {
109        self.registry.list().await
110    }
111
112    /// The job named `task_id`, when the shell holds it.
113    ///
114    /// The shell keeps the job, and its name, for as long as the handle
115    /// lives, so the handle never addresses another job that is later given
116    /// the same name.
117    pub async fn get(&self, task_id: &str) -> Option<Job> {
118        let watch = self.registry.watch(task_id).await?;
119        Some(Job::new(self.clone(), task_id.to_owned(), watch))
120    }
121
122    /// A way to append to the output of the job named `task_id`; `None`
123    /// when the shell holds no such job. The shell holds a job from before
124    /// its process starts, so the `task_id` of a [`crate::LaunchInfo`] it
125    /// handed out always names one while the process can run; what is
126    /// appended before the job registers lands ahead of the process's own
127    /// output.
128    ///
129    /// The appender refers to that job alone: it keeps neither the job nor
130    /// its name, and never writes into a later job given the same name.
131    pub async fn output_appender(&self, task_id: &str) -> Option<JobOutputAppender> {
132        Some(JobOutputAppender {
133            registry: self.registry.clone(),
134            task_id: self.registry.task_lease(task_id).await?,
135        })
136    }
137
138    /// Kills the job named `task_id` with its whole process tree; `false`
139    /// when no running job has that name.
140    pub async fn kill(&self, task_id: &str) -> bool {
141        self.registry.kill_by_task_id(task_id).await
142    }
143
144    /// Kills every running job and returns how many it killed.
145    pub async fn kill_all(&self) -> usize {
146        self.registry.kill_running().await
147    }
148
149    /// The facts raised about the shell's jobs.
150    #[must_use]
151    pub fn events(&self) -> ShellEvents {
152        self.events.clone()
153    }
154}
155
156/// Whether [`JobOutputAppender::append`] reached its job.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158#[must_use]
159pub enum AppendOutcome {
160    /// The bytes are in the job's output.
161    Appended,
162    /// The job ended, was forgotten or is another job than the appender's;
163    /// the bytes went nowhere.
164    JobEnded,
165}
166
167/// Appends to the output of one running job, such as the progress an
168/// embedder's command reports while the script that called it runs.
169///
170/// What it appends joins the job's own output in arrival order, so
171/// [`Job::read`], the job's stored output and the shell's output events see
172/// it. Cloning shares the reference to the job, which is weak.
173#[derive(Debug, Clone)]
174pub struct JobOutputAppender {
175    registry: JobRegistry,
176    task_id: WeakIdLease,
177}
178
179impl JobOutputAppender {
180    /// Appends `bytes` to the job's output, returning once they are in it.
181    pub async fn append(&self, bytes: &[u8]) -> AppendOutcome {
182        // The lease is held until the registry answers, so its word cannot
183        // name another job meanwhile.
184        let Some(task_id) = self.task_id.upgrade() else {
185            return AppendOutcome::JobEnded;
186        };
187        if self
188            .registry
189            .append_task_stdout(&task_id, bytes.to_vec())
190            .await
191        {
192            AppendOutcome::Appended
193        } else {
194            AppendOutcome::JobEnded
195        }
196    }
197}
198
199/// One job of a shell.
200///
201/// Cloning shares the hold on the job.
202#[derive(Debug, Clone)]
203pub struct Job {
204    task_id: String,
205    jobs: Jobs,
206    /// Keeps the job, and the word naming it, in the shell's registry.
207    _watch: Arc<JobWatch>,
208}
209
210impl Job {
211    pub(crate) fn new(jobs: Jobs, task_id: String, watch: JobWatch) -> Self {
212        Self {
213            task_id,
214            jobs,
215            _watch: Arc::new(watch),
216        }
217    }
218
219    /// The word the job is named by.
220    #[must_use]
221    pub fn task_id(&self) -> &str {
222        &self.task_id
223    }
224
225    /// The job as the shell holds it now.
226    ///
227    /// # Panics
228    /// Panics when the shell no longer holds the job, which a handle's own
229    /// hold on it prevents.
230    pub async fn info(&self) -> JobInfo {
231        self.jobs
232            .registry
233            .get_by_task_id(&self.task_id)
234            .await
235            .expect("the job this handle watches is held")
236    }
237
238    /// Waits for the job to end and returns what it printed and how it
239    /// ended. The wait takes the job's completion: a job read here owes its
240    /// agent no turn, so the end it raises carries no
241    /// [pending completion](crate::JobEnded::into_parts).
242    ///
243    /// # Errors
244    /// Returns an error when the job failed or its output could not be
245    /// stored.
246    ///
247    /// # Panics
248    /// Panics when the shell no longer holds the job, which a handle's own
249    /// hold on it prevents.
250    pub async fn wait(&self) -> Result<ScriptResult, JobWaitError> {
251        let ended = self
252            .jobs
253            .registry
254            .wait_taking(&self.task_id)
255            .await
256            .expect("the job this handle watches is held");
257        let outcome = match ended.status {
258            JobStatus::Running => unreachable!("a wait ends once the job stopped running"),
259            JobStatus::Completed { exit_code, .. } => RunOutcome::Exited { code: exit_code },
260            JobStatus::Failed { error, .. } => {
261                return Err(JobWaitError::Failed {
262                    task_id: self.task_id.clone(),
263                    error,
264                });
265            }
266            JobStatus::Killed { cause, .. } => RunOutcome::Killed(cause),
267        };
268        let (stdout, stderr) = self
269            .jobs
270            .registry
271            .terminal_output(&self.task_id)
272            .await
273            .expect("the job this handle watches is held");
274        let outputs = &self.jobs.outputs;
275        let output = |source| JobWaitError::Output {
276            task_id: self.task_id.clone(),
277            source,
278        };
279        // The output the job already stored is the job's; a new file is
280        // written only for what it did not store.
281        let stdout = match &ended.output_path {
282            Some(path) => outputs.stream_of_file(path).await,
283            None => {
284                outputs
285                    .save(&stdout, OutputFormat::Text, MediaResolution::Auto)
286                    .await
287            }
288        }
289        .map_err(output)?;
290        let stderr = outputs
291            .save(&stderr, OutputFormat::Text, MediaResolution::Auto)
292            .await
293            .map_err(output)?;
294        let stderr = (!stderr.is_empty()).then_some(stderr);
295        Ok(ScriptResult {
296            stdout,
297            stderr,
298            outcome,
299            interruptions: Vec::new(),
300        })
301    }
302
303    /// Reads the job's output past `cursor`, at most `max_bytes` of it; a
304    /// read that would return what the job's last read returned is
305    /// [`JobRead::Unchanged`].
306    ///
307    /// # Errors
308    /// Returns an error when the shell does not hold the job.
309    pub async fn read(&self, cursor: usize, max_bytes: usize) -> Result<JobRead, String> {
310        self.jobs
311            .registry
312            .terminal_read(&self.task_id, cursor, max_bytes)
313            .await
314    }
315
316    /// Writes `bytes` to the job's stdin.
317    ///
318    /// # Errors
319    /// Returns an error when the job is not running or takes no input: one
320    /// started in the foreground has no stdin pipe, promoted or not.
321    pub async fn input(&self, bytes: Vec<u8>) -> Result<(), JobInputError> {
322        self.jobs
323            .registry
324            .terminal_input(&self.task_id, bytes)
325            .await
326    }
327
328    /// Kills the job with its whole process tree; `false` when it is not
329    /// running.
330    pub async fn kill(&self) -> bool {
331        self.jobs.kill(&self.task_id).await
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use crate::job_registry::job_registry_channel;
339    use crate::policy::SandboxMode;
340    use crate::test_ids::lease;
341    use executor_core::Executor;
342    use executor_core::Task;
343    use executor_core::tokio::TokioGlobal;
344
345    fn spawn_registry() -> JobRegistry {
346        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
347        TokioGlobal
348            .spawn(async move { service.serve().await })
349            .detach();
350        registry
351    }
352
353    async fn appender(registry: &JobRegistry, task_id: &str) -> JobOutputAppender {
354        JobOutputAppender {
355            registry: registry.clone(),
356            task_id: registry.task_lease(task_id).await.expect("the job is held"),
357        }
358    }
359
360    #[tokio::test]
361    async fn appended_lines_interleave_with_the_jobs_own_output() {
362        let registry = spawn_registry();
363        registry
364            .register(
365                1,
366                &lease("river"),
367                "exec",
368                "run",
369                SandboxMode::Sandboxed,
370                None,
371            )
372            .await;
373        let appender = appender(&registry, "river").await;
374
375        registry
376            .append_stdout(&lease("river"), b"one\n".to_vec())
377            .await;
378        assert_eq!(
379            appender.append(b"progress\n").await,
380            AppendOutcome::Appended
381        );
382        registry
383            .append_stdout(&lease("river"), b"two\n".to_vec())
384            .await;
385
386        let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
387        assert_eq!(stdout, b"one\nprogress\ntwo\n");
388        let JobRead::Delta(delta) = registry
389            .terminal_read("river", 0, 1024)
390            .await
391            .expect("job exists")
392        else {
393            panic!("a first read is a delta");
394        };
395        assert_eq!(delta.bytes, b"one\nprogress\ntwo\n");
396    }
397
398    #[tokio::test]
399    async fn a_launching_job_takes_appends_ahead_of_its_registration() {
400        let registry = spawn_registry();
401        let river = lease("river");
402        registry.launching(&river).await;
403        let appender = appender(&registry, "river").await;
404
405        let append = tokio::spawn(async move { appender.append(b"early\n").await });
406        tokio::task::yield_now().await;
407        assert!(!append.is_finished(), "the append waits for the job");
408
409        registry
410            .register(1, &river, "exec", "run", SandboxMode::Sandboxed, None)
411            .await;
412        assert_eq!(append.await.unwrap(), AppendOutcome::Appended);
413        registry.append_stdout(&river, b"late\n".to_vec()).await;
414        let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
415        assert_eq!(stdout, b"early\nlate\n");
416    }
417
418    #[tokio::test]
419    async fn a_launch_that_never_registers_releases_its_appenders() {
420        let registry = spawn_registry();
421        let river = lease("river");
422        registry.launching(&river).await;
423        let appender = appender(&registry, "river").await;
424
425        let waiting = {
426            let appender = appender.clone();
427            tokio::spawn(async move { appender.append(b"early\n").await })
428        };
429        tokio::task::yield_now().await;
430        registry.abandon_launch(&river).await;
431
432        assert_eq!(waiting.await.unwrap(), AppendOutcome::JobEnded);
433        assert_eq!(appender.append(b"more\n").await, AppendOutcome::JobEnded);
434        assert!(registry.task_lease("river").await.is_none());
435    }
436
437    #[tokio::test]
438    async fn a_held_appender_does_nothing_once_the_job_ended() {
439        let registry = spawn_registry();
440        registry
441            .register(
442                1,
443                &lease("river"),
444                "exec",
445                "run",
446                SandboxMode::Sandboxed,
447                None,
448            )
449            .await;
450        let appender = appender(&registry, "river").await;
451        registry.complete(&lease("river"), 0, None).await;
452
453        assert_eq!(appender.append(b"late\n").await, AppendOutcome::JobEnded);
454        let (stdout, _) = registry
455            .terminal_output("river")
456            .await
457            .expect("job is held");
458        assert_eq!(stdout, b"");
459    }
460
461    #[tokio::test]
462    async fn an_appender_never_reaches_a_later_job_under_the_same_word() {
463        let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
464        let registry = spawn_registry();
465        let first = ids.lease().unwrap();
466        registry
467            .register(1, &first, "exec", "run", SandboxMode::Sandboxed, None)
468            .await;
469        let appender = appender(&registry, "river").await;
470        registry.complete(&first, 0, None).await;
471        drop(registry.owe_completion("river", Ok(0)).await.unwrap());
472        drop(first);
473        assert!(registry.list().await.is_empty(), "the job is forgotten");
474
475        let second = ids.lease().expect("nothing keeps river");
476        registry
477            .register(2, &second, "exec", "run", SandboxMode::Sandboxed, None)
478            .await;
479        assert_eq!(appender.append(b"stale\n").await, AppendOutcome::JobEnded);
480        let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
481        assert!(stdout.is_empty(), "the stale appender reached no job");
482    }
483}