Skip to main content

artifactize_core/
process.rs

1//! Literal process launches, bounded capture, and process-group cleanup.
2
3use std::{
4    collections::BTreeMap, ffi::OsString, future::Future, io, path::PathBuf, process::Stdio,
5    time::Duration,
6};
7
8use artifactize_foundation::platform::process::{ResolvedCommand as NativeCommand, resolve_with};
9use thiserror::Error;
10use tokio::{
11    io::AsyncWriteExt,
12    time::{Instant, sleep_until},
13};
14use tokio_util::sync::CancellationToken;
15
16use crate::{
17    platform::{self, Child},
18    tools::human::log::{End, Lines, Run, Stream},
19};
20
21/// Retain bounded stdout/stderr audit per stream while continuing to drain the pipes.
22pub(crate) const OUTPUT_LIMIT: usize = 128 * 1024;
23pub use artifactize_foundation::platform::process::{ChildIdentity, ProcessId};
24pub(crate) use artifactize_foundation::platform::process::{child_identity, is_alive, terminate};
25
26mod capture;
27pub use capture::{CaptureError, StreamFailure};
28#[cfg(test)]
29pub(crate) use capture::{OUTPUT_CLOSE_GRACE, slow_disk};
30
31/// Arguments have already been resolved by the caller. No shell is added.
32#[derive(Debug, Clone)]
33pub struct Command {
34    pub program: OsString,
35    pub args: Vec<OsString>,
36    pub cwd: PathBuf,
37    /// The complete child environment, not additions to the parent's environment.
38    pub env: BTreeMap<OsString, OsString>,
39    pub timeout: Duration,
40}
41
42#[derive(Debug)]
43pub struct Output {
44    pub status: platform::ProcessOutcome,
45    pub stdout: Vec<u8>,
46    pub stderr: Vec<u8>,
47    pub truncated: bool,
48    /// The last bytes of each stream, whatever the prefix kept.
49    pub stdout_tail: Vec<u8>,
50    pub stderr_tail: Vec<u8>,
51    pub duration: Duration,
52}
53
54/// Characters of a failed command's output its issue keeps.
55const REASON_CHARS: usize = 2000;
56
57impl Output {
58    /// Why a command that exited with `exit_code` failed: the end of what it wrote to stderr,
59    /// else to stdout, else that it exited with that code.
60    pub(crate) fn reason(&self, exit_code: i32) -> String {
61        [&self.stderr_tail, &self.stdout_tail]
62            .into_iter()
63            .map(|tail| platform::output_text(tail))
64            .find(|text| !text.trim().is_empty())
65            .map_or_else(
66                || crate::store::exited_with(exit_code),
67                |text| crate::store::output_tail(&text, REASON_CHARS),
68            )
69    }
70}
71
72/// Run a program artifactize itself uses, such as git, found through the shared program
73/// lookup, and return its standard output when it succeeds. `None` when it is missing or
74/// fails.
75pub(crate) fn tool_output<'a>(
76    program: &str,
77    args: impl IntoIterator<Item = &'a std::ffi::OsStr>,
78) -> Option<Vec<u8>> {
79    platform::program::tool_output(program, args)
80}
81
82/// Starts a built-in's program, such as `help`'s, through this process layer: in one process
83/// group or Job Object from before it runs, cleaned up with its children, with exactly the
84/// environment given here.
85pub(crate) struct Launcher {
86    pub env: BTreeMap<OsString, OsString>,
87}
88
89impl artifactize_tools::launch::Launcher for Launcher {
90    fn run<'a>(
91        &'a self,
92        launch: artifactize_tools::launch::Launch,
93        cancellation: &'a CancellationToken,
94    ) -> artifactize_tools::launch::Running<'a> {
95        use artifactize_tools::launch::{Finished, LaunchError};
96        Box::pin(async move {
97            let command = Command {
98                program: launch.program.into(),
99                args: launch.args,
100                cwd: launch.cwd,
101                env: self.env.clone(),
102                timeout: launch.timeout,
103            };
104            match run_unregistered(command, None, launch.output_limit, cancellation.clone()).await {
105                Ok(output) => Ok(Finished {
106                    status: output.status,
107                    stdout: output.stdout,
108                    stderr: output.stderr,
109                    truncated: output.truncated,
110                }),
111                Err(Error::Timeout) => Err(LaunchError::TimedOut),
112                Err(Error::Cancelled) => Err(LaunchError::Cancelled),
113                Err(error) => Err(LaunchError::Failed(
114                    error
115                        .argument_refusal()
116                        .unwrap_or_else(|| error.to_string()),
117                )),
118            }
119        })
120    }
121}
122
123#[derive(Debug, Error)]
124pub enum Error {
125    #[error("process could not be spawned: {0}")]
126    Spawn(#[source] io::Error),
127    #[error("child registration failed: {0}")]
128    Registration(#[source] io::Error),
129    #[error("process supervision failed: {0}")]
130    Io(#[from] io::Error),
131    #[error("process cleanup could not be confirmed: {0}")]
132    Cleanup(#[source] io::Error),
133    #[error("process supervision task failed: {0}")]
134    Task(#[from] tokio::task::JoinError),
135    #[error("process timeout is too large to represent as a deadline")]
136    InvalidTimeout,
137    #[error("process timed out")]
138    Timeout,
139    #[error("process was cancelled")]
140    Cancelled,
141    /// The process ended, but its output could not be captured to the end; the error keeps
142    /// how it ended and the output read.
143    #[error(transparent)]
144    Capture(Box<CaptureError>),
145}
146
147impl Error {
148    /// Every ordinary run error is returned only after cleanup or before admission.
149    /// Cleanup/task failures are the exceptions: retain any admission record.
150    pub(crate) fn cleanup_confirmed(&self) -> bool {
151        match self {
152            Self::Cleanup(_) | Self::Task(_) => false,
153            Self::Spawn(_)
154            | Self::Registration(_)
155            | Self::Io(_)
156            | Self::InvalidTimeout
157            | Self::Timeout
158            | Self::Cancelled
159            | Self::Capture(_) => true,
160        }
161    }
162
163    pub(crate) fn argument_refusal(&self) -> Option<String> {
164        match self {
165            Self::Spawn(error) if error.kind() == io::ErrorKind::InvalidInput => Some(format!(
166                "Process arguments could not be passed safely: {error}"
167            )),
168            _ => None,
169        }
170    }
171}
172
173/// Register the inert child before allowing exec. A rejected, cancelled, or timed-out
174/// registration cannot start user code. The callback must not block its executor.
175/// Dropping this future cancels execution; its supervisor still kills and reaps it.
176pub async fn run<F, R>(
177    command: Command,
178    cancellation: CancellationToken,
179    register: F,
180) -> Result<Output, Error>
181where
182    F: FnOnce(ChildIdentity) -> R + Send + 'static,
183    R: Future<Output = io::Result<()>> + Send + 'static,
184{
185    run_with_input(command, None, cancellation, register).await
186}
187
188pub(crate) async fn run_with_input<F, R>(
189    command: Command,
190    input: Option<Vec<u8>>,
191    cancellation: CancellationToken,
192    register: F,
193) -> Result<Output, Error>
194where
195    F: FnOnce(ChildIdentity) -> R + Send + 'static,
196    R: Future<Output = io::Result<()>> + Send + 'static,
197{
198    run_with_input_limit(command, input, OUTPUT_LIMIT, cancellation, register).await
199}
200
201pub(crate) async fn run_with_input_limit<F, R>(
202    command: Command,
203    input: Option<Vec<u8>>,
204    output_limit: usize,
205    cancellation: CancellationToken,
206    register: F,
207) -> Result<Output, Error>
208where
209    F: FnOnce(ChildIdentity) -> R + Send + 'static,
210    R: Future<Output = io::Result<()>> + Send + 'static,
211{
212    let cancellation = cancellation.child_token();
213    let _cancel_on_drop = cancellation.clone().drop_guard();
214    crate::task::joined(
215        tokio::spawn(run_inner(
216            command,
217            input,
218            output_limit,
219            Capture::default(),
220            cancellation,
221            Some(register),
222            SpawnOn::Caller,
223        ))
224        .await,
225    )?
226}
227
228/// A registration nobody makes: the type of [`run_inner`]'s and [`spawn_owned`]'s absent
229/// `register`.
230pub(crate) type Unregistered = fn(ChildIdentity) -> std::future::Ready<io::Result<()>>;
231
232/// Run a child nobody registers, such as a fingerprint script or a tool's protocol call: it
233/// runs at once, in its own process group or Job Object, and is cleaned up with its children.
234pub(crate) async fn run_unregistered(
235    command: Command,
236    input: Option<Vec<u8>>,
237    output_limit: usize,
238    cancellation: CancellationToken,
239) -> Result<Output, Error> {
240    run_unregistered_on(command, input, output_limit, cancellation, SpawnOn::Caller).await
241}
242
243pub(crate) async fn run_fingerprint(
244    command: Command,
245    input: Vec<u8>,
246    cancellation: CancellationToken,
247) -> Result<Output, Error> {
248    run_unregistered_on(
249        command,
250        Some(input),
251        OUTPUT_LIMIT,
252        cancellation,
253        SpawnOn::Worker,
254    )
255    .await
256}
257
258#[derive(Clone, Copy)]
259enum SpawnOn {
260    Caller,
261    Worker,
262}
263
264async fn run_unregistered_on(
265    command: Command,
266    input: Option<Vec<u8>>,
267    output_limit: usize,
268    cancellation: CancellationToken,
269    spawn_on: SpawnOn,
270) -> Result<Output, Error> {
271    let cancellation = cancellation.child_token();
272    let _cancel_on_drop = cancellation.clone().drop_guard();
273    crate::task::joined(
274        tokio::spawn(run_inner(
275            command,
276            input,
277            output_limit,
278            Capture::default(),
279            cancellation,
280            None::<Unregistered>,
281            spawn_on,
282        ))
283        .await,
284    )?
285}
286
287/// Where a run's output goes besides its bounded capture: its log files, and the lines a
288/// Tool log shows while it runs.
289#[derive(Default)]
290struct Capture {
291    logs: Option<PathBuf>,
292    lines: Option<(Lines, Lines)>,
293}
294
295/// Run a Human output tool, its output reaching `run`'s Tool log line by line as it arrives
296/// as well as its bounded capture.
297pub(crate) async fn run_watched(
298    command: Command,
299    cancellation: CancellationToken,
300    run: &Run,
301) -> Result<Output, Error> {
302    let cancellation = cancellation.child_token();
303    let _cancel_on_drop = cancellation.clone().drop_guard();
304    let capture = Capture {
305        logs: None,
306        lines: Some((run.lines(Stream::Stdout), run.lines(Stream::Stderr))),
307    };
308    crate::task::joined(
309        tokio::spawn(run_inner(
310            command,
311            None,
312            OUTPUT_LIMIT,
313            capture,
314            cancellation,
315            None::<Unregistered>,
316            SpawnOn::Caller,
317        ))
318        .await,
319    )?
320}
321
322async fn run_inner<F, R>(
323    command: Command,
324    input: Option<Vec<u8>>,
325    output_limit: usize,
326    Capture { logs, lines }: Capture,
327    cancellation: CancellationToken,
328    register: Option<F>,
329    spawn_on: SpawnOn,
330) -> Result<Output, Error>
331where
332    F: FnOnce(ChildIdentity) -> R,
333    R: Future<Output = io::Result<()>>,
334{
335    let started = Instant::now();
336    let deadline = started
337        .checked_add(command.timeout)
338        .ok_or(Error::InvalidTimeout)?;
339    if cancellation.is_cancelled() {
340        return Err(Error::Cancelled);
341    }
342    if command.timeout.is_zero() {
343        return Err(Error::Timeout);
344    }
345
346    let mut child = spawn_child(
347        &command,
348        input.is_some(),
349        cancellation.clone(),
350        deadline,
351        register,
352        spawn_on,
353    )
354    .await?;
355
356    let stdout = child.stdout().take().expect("stdout is piped");
357    let stderr = child.stderr().take().expect("stderr is piped");
358    let stdin = child.stdin().take();
359    // Cancelled once the process group is gone: from then on only a process outside it can
360    // hold the pipes.
361    let gone = CancellationToken::new();
362    let feed = async {
363        if let (Some(mut stdin), Some(input)) = (stdin, input) {
364            tokio::select! {
365                _ = gone.cancelled() => {},
366                _ = cancellation.cancelled() => {},
367                _ = sleep_until(deadline) => {},
368                result = stdin.write_all(&input) => {
369                    // Fingerprint scripts may intentionally ignore their context.
370                    if let Err(error) = result && error.kind() != io::ErrorKind::BrokenPipe {
371                        return Err(Error::Io(error));
372                    }
373                }
374            }
375        }
376        Ok(())
377    };
378    let wait = async {
379        let result = tokio::select! {
380            biased;
381            _ = cancellation.cancelled() => Err(Error::Cancelled),
382            _ = sleep_until(deadline) => Err(Error::Timeout),
383            status = child.wait() => status.map_err(Error::Io),
384        };
385        let cleanup = if result.is_err() {
386            terminate(&mut child).await
387        } else {
388            // An ordinary main-process exit must not leave its descendants running.
389            child.cleanup().await.map(|_| ())
390        };
391        gone.cancel();
392        cleanup.map_err(Error::Cleanup)?;
393        result
394    };
395    let (stdout_lines, stderr_lines) = lines.unzip();
396    let evidence = |name| logs.as_ref().map(|directory| directory.join(name));
397    let streams = async {
398        tokio::join!(
399            capture::capture(
400                stdout,
401                output_limit,
402                evidence("runtime.stdout"),
403                stdout_lines,
404                &gone
405            ),
406            capture::capture(
407                stderr,
408                output_limit,
409                evidence("runtime.stderr"),
410                stderr_lines,
411                &gone
412            )
413        )
414    };
415    let (status, (stdout, stderr), input) = tokio::join!(wait, streams, feed);
416    let status = status?;
417    input?;
418    capture::finish(status, stdout, stderr, started.elapsed())
419}
420
421/// Spawn shared by one-shot calls and long-lived tool sessions. With `register` the child is
422/// held before exec until registered; the caller must own this future in a supervisor so
423/// dropping a request cannot abandon admission. Without it the child runs at once:
424/// there is no registration to wait for.
425pub(crate) async fn spawn_owned<F, R>(
426    command: &Command,
427    input: bool,
428    cancellation: CancellationToken,
429    deadline: Instant,
430    register: Option<F>,
431) -> Result<Child, Error>
432where
433    F: FnOnce(ChildIdentity) -> R,
434    R: Future<Output = io::Result<()>>,
435{
436    spawn_child(
437        command,
438        input,
439        cancellation,
440        deadline,
441        register,
442        SpawnOn::Caller,
443    )
444    .await
445}
446
447async fn spawn_child<F, R>(
448    command: &Command,
449    input: bool,
450    cancellation: CancellationToken,
451    deadline: Instant,
452    register: Option<F>,
453    spawn_on: SpawnOn,
454) -> Result<Child, Error>
455where
456    F: FnOnce(ChildIdentity) -> R,
457    R: Future<Output = io::Result<()>>,
458{
459    let mut child = child_command(command)?;
460    child
461        .stdin(if input { Stdio::piped() } else { Stdio::null() })
462        .stdout(Stdio::piped())
463        .stderr(Stdio::piped())
464        .kill_on_drop(true);
465    let Some(register) = register else {
466        let spawn = artifactize_foundation::platform::process::spawn_in_owner_session(child);
467        return match spawn_on {
468            SpawnOn::Caller => spawn.await,
469            // Native spawn can wait for exec. Fingerprinting has a semaphore but must not
470            // serialize independent launches waiting in that system call.
471            SpawnOn::Worker => {
472                let runtime = tokio::runtime::Handle::current();
473                crate::task::joined(
474                    tokio::task::spawn_blocking(move || runtime.block_on(spawn)).await,
475                )?
476            }
477        }
478        .map_err(Error::Spawn);
479    };
480    let (gate, mut spawning) = platform::spawn_gated(child).map_err(Error::Spawn)?;
481    let admission = tokio::select! {
482        biased;
483        _ = cancellation.cancelled() => Err(Error::Cancelled),
484        _ = sleep_until(deadline) => Err(Error::Timeout),
485        result = async {
486            let gate = gate.identify().await?;
487            let child = child_identity(gate.pid()).map_err(Error::Registration)?;
488            register(child).await.map_err(Error::Registration)?;
489            Ok::<_, Error>(gate)
490        } => result,
491    };
492    // Cancellation may have arrived during the callback's final poll.
493    let admission = admission.and_then(|gate| {
494        if cancellation.is_cancelled() {
495            Err(Error::Cancelled)
496        } else if Instant::now() >= deadline {
497            Err(Error::Timeout)
498        } else {
499            gate.admit().map_err(Error::Io)
500        }
501    });
502    let spawned = crate::task::joined((&mut spawning).await)?;
503    let mut child = match spawned {
504        Ok(child) => child,
505        Err(error) => {
506            return Err(match admission {
507                Err(error @ (Error::Registration(_) | Error::Cancelled | Error::Timeout)) => error,
508                _ => Error::Spawn(error),
509            });
510        }
511    };
512    if let Err(error) = admission {
513        terminate(&mut child).await.map_err(Error::Cleanup)?;
514        return Err(error);
515    }
516
517    Ok(child)
518}
519
520fn child_command(command: &Command) -> Result<NativeCommand, Error> {
521    let environment = platform::environment::for_child(&command.env);
522    let program = resolve_with(
523        std::path::Path::new(&command.program),
524        &command.cwd,
525        |name| platform::environment::lookup(&environment, name).map(ToOwned::to_owned),
526    )
527    .map_err(Error::Spawn)?;
528    let mut child = program.command(&command.args).map_err(Error::Spawn)?;
529    child
530        .current_dir(&command.cwd)
531        .env_clear()
532        .envs(environment.iter());
533    Ok(child)
534}
535
536/// Intentional desktop handoff: no owned process group, pipes, or kill-on-drop policy.
537fn launch_detached(
538    program: &std::ffi::OsStr,
539    args: &[impl AsRef<std::ffi::OsStr>],
540    cwd: &std::path::Path,
541    run: &mut Run,
542) -> Result<(), Error> {
543    let program = resolve_with(
544        std::path::Path::new(program),
545        cwd,
546        platform::environment::var,
547    )
548    .map_err(Error::Spawn)?;
549    let mut command = program.command(args).map_err(Error::Spawn)?;
550    command
551        .current_dir(cwd)
552        .env_clear()
553        .envs(platform::environment::snapshot())
554        .stdin(Stdio::null())
555        .stdout(Stdio::null())
556        .stderr(Stdio::null())
557        .kill_on_drop(false);
558    let child = platform::spawn_detached(command).map_err(Error::Spawn)?;
559    run.launched(child.pid());
560    child.reap();
561    Ok(())
562}
563
564/// A desktop handoff whose output a Tool log shows: like [`launch_detached`] it is never
565/// owned, killed or waited on by the review, but its stdout and stderr are pipes, drained
566/// line by line into `run` until the program closes them and exits, whoever still listens.
567/// An unwatched run gets the plain handoff. A failed spawn hands the run back to be ended.
568pub(crate) fn launch_watched(
569    program: &std::ffi::OsStr,
570    args: &[impl AsRef<std::ffi::OsStr>],
571    cwd: &std::path::Path,
572    mut run: Run,
573) -> Result<(), (Error, Run)> {
574    if !run.watched() {
575        return match launch_detached(program, args, cwd, &mut run) {
576            Ok(()) => {
577                run.end(End::Launched);
578                Ok(())
579            }
580            Err(error) => Err((error, run)),
581        };
582    }
583    let program = match resolve_with(
584        std::path::Path::new(program),
585        cwd,
586        platform::environment::var,
587    ) {
588        Ok(program) => program,
589        Err(error) => return Err((Error::Spawn(error), run)),
590    };
591    let mut command = match program.command(args) {
592        Ok(command) => command,
593        Err(error) => return Err((Error::Spawn(error), run)),
594    };
595    command
596        .current_dir(cwd)
597        .env_clear()
598        .envs(platform::environment::snapshot())
599        .stdin(Stdio::null())
600        .stdout(Stdio::piped())
601        .stderr(Stdio::piped())
602        .kill_on_drop(false);
603    let mut child = match platform::spawn_watched(command) {
604        Ok(child) => child,
605        Err(error) => return Err((Error::Spawn(error), run)),
606    };
607    run.launched(child.pid());
608    let (stdout, stderr) = child.take_output();
609    tokio::spawn(async move {
610        // Nothing is retained: the lines go to the log, the rest is discarded. Nobody owns
611        // this program's group, so its pipes are read for as long as anything holds them.
612        let held = CancellationToken::new();
613        let (status, _, _) = tokio::join!(
614            child.wait(),
615            capture::capture(stdout, 0, None, Some(run.lines(Stream::Stdout)), &held),
616            capture::capture(stderr, 0, None, Some(run.lines(Stream::Stderr)), &held),
617        );
618        run.end(match status {
619            Ok(status) => End::exited(&status),
620            Err(error) => End::Failed(error.to_string()),
621        });
622    });
623    Ok(())
624}
625
626/// Resolve the installed CLI, with sibling build outputs for Rust library consumers/tests.
627pub(crate) fn artifactize_executable() -> Result<std::path::PathBuf, String> {
628    platform::program::resolve_near_current("artifactize".as_ref()).map_err(|e| e.to_string())
629}
630
631/// The supervisor and executor append diagnostics to the same Run-local file.
632fn worker_stderr(directory: &std::path::Path) -> std::path::PathBuf {
633    directory.join("worker.stderr")
634}
635
636pub(crate) fn run_worker_diagnostics(state: &std::path::Path, id: &crate::types::RunId) -> String {
637    use std::io::Read;
638    // Operational diagnostics stay bounded independently of authored command output.
639    const DIAGNOSTIC_BYTES: u64 = 64 * 1024;
640    let mut bytes = Vec::new();
641    if let Ok(log) = platform::open_regular(&worker_stderr(&state.join("runs").join(id.as_str()))) {
642        let _ = log.take(DIAGNOSTIC_BYTES).read_to_end(&mut bytes);
643    }
644    platform::output_lines(&bytes)
645}
646
647/// The internal supervisor and executor have no inherited requester stdio/lifetime.
648#[derive(Clone, Copy)]
649pub(crate) enum RunEntry {
650    Supervisor,
651    Executor,
652}
653pub(crate) fn spawn_run(
654    program: &std::path::Path,
655    id: &crate::types::RunId,
656    repo: &std::path::Path,
657    state: &std::path::Path,
658    entry: RunEntry,
659) -> Result<(ChildIdentity, platform::DetachedChild), Error> {
660    let mut options = platform::private_options();
661    options.write(true);
662    match entry {
663        RunEntry::Supervisor => {
664            options.create_new(true);
665        }
666        RunEntry::Executor => {
667            options.append(true);
668        }
669    }
670    let directory = state.join("runs").join(id.as_str());
671    let stderr = options
672        .open(worker_stderr(&directory))
673        .map_err(Error::Spawn)?;
674    let program = resolve_with(program, repo, platform::environment::var).map_err(Error::Spawn)?;
675    let args = [
676        std::ffi::OsStr::new("--repo"),
677        repo.as_os_str(),
678        std::ffi::OsStr::new("--state-dir"),
679        state.as_os_str(),
680        std::ffi::OsStr::new(match entry {
681            RunEntry::Supervisor => "__verify",
682            RunEntry::Executor => "__execute",
683        }),
684        std::ffi::OsStr::new(id.as_str()),
685    ];
686    let mut command = program.command(args).map_err(Error::Spawn)?;
687    command
688        // Internal workers must not pin the repository after publishing a terminal Run.
689        // Authored commands still use their declared repository cwd in `spawn_owned`.
690        .current_dir(directory)
691        .env_clear()
692        .envs(platform::environment::snapshot())
693        .stdin(Stdio::null())
694        .stdout(Stdio::null())
695        .stderr(Stdio::from(stderr))
696        .kill_on_drop(false);
697    let child = platform::spawn_run(command).map_err(Error::Spawn)?;
698    let identity = child_identity(child.pid()).map_err(Error::Registration)?;
699    Ok((identity, child))
700}
701pub(crate) fn launch_run(
702    program: &std::path::Path,
703    id: &crate::types::RunId,
704    repo: &std::path::Path,
705    state: &std::path::Path,
706) -> Result<ChildIdentity, Error> {
707    let (identity, child) = spawn_run(program, id, repo, state, RunEntry::Supervisor)?;
708    child.reap();
709    Ok(identity)
710}
711
712/// Runtime logs live with their Run and are pruned with it. The caller owns this
713/// future in a supervisor that survives its result waiter; protocol callers retain
714/// prefix-only capture because changing protocol bytes to head/tail would corrupt replies.
715pub(crate) async fn run_logged<F, R>(
716    command: Command,
717    directory: PathBuf,
718    cancellation: CancellationToken,
719    register: F,
720) -> Result<Output, Error>
721where
722    F: FnOnce(ChildIdentity) -> R + Send + 'static,
723    R: Future<Output = io::Result<()>> + Send + 'static,
724{
725    run_inner(
726        command,
727        None,
728        OUTPUT_LIMIT,
729        Capture {
730            logs: Some(directory),
731            lines: None,
732        },
733        cancellation,
734        Some(register),
735        SpawnOn::Caller,
736    )
737    .await
738}