dust

Processes

Introduction

dust-framework's dust::process module provides an expressive API for invoking external processes (such as ffmpeg or git) from your application. It captures stdout, stderr, and exit codes, enforces timeouts, terminates child processes if the calling request is cancelled, and lets you fake external commands in tests so your suite never depends on installed binaries.

Running processes

Use process::run to execute a command and wait for it to finish. Pass arguments as an array so each item is passed directly to the program without invoking a shell:

rust
use dust::process;pub async fn show() -> dust::Result<String> {    let result = process::run(["git", "log", "-1", "--format=%h %s"]).await?;    Ok(result.output().into_owned())}

Inspect the returned ProcessResult with these methods:

rust
result.command();       // "git log -1 '--format=%h %s'"result.successful();    // exited with code 0result.failed();        // exited with another code, or was killedresult.exit_code();     // Some(0), or None when killedresult.output();        // standard output, as textresult.error_output();  // standard error, as textresult.see_in_output("Merge");result.see_in_error_output("warning");

For programs that output binary data such as images, read raw bytes with output_bytes() and error_output_bytes().

Failed processes

A non-zero exit code returns Ok(result) rather than an error. Some commands use non-zero exit codes during normal operation, such as grep returning 1 when no lines match. When a non-zero exit code should be treated as a failure, chain ensure_successful() to convert it into a ProcessFailed error:

rust
use dust::process;let result = process::run(["git", "pull"]).await?.ensure_successful()?;

ProcessFailed includes the command, exit code, and trailing output in its message so failures are clear in logs. Returning it from a handler produces a 500 response; inspect it directly with error.is::<ProcessFailed>().

run itself returns an error when the binary cannot be started (such as an dust::Error with ErrorKind::NotFound when the program is not installed) or when the process times out (ProcessTimedOut). You can inspect the returned dust::Error with downcast_ref to handle specific failures:

rust
use std::io;use dust::process::{self, ProcessTimedOut};match process::run(["ffmpeg", "-i", "clip.mp4", "thumb.jpg"]).await {    Ok(result) => {        result.ensure_successful()?;    }    Err(error) => {        if let Some(timed_out) = error.downcast_ref::<ProcessTimedOut>() {            tracing::warn!(                output = %timed_out.result().output(),                "thumbnail generation timed out"            );            return Ok(());        }        if let Some(dust) = error.downcast_ref::<dust::Error>()            && dust.kind() == dust::ErrorKind::NotFound        {            tracing::error!("ffmpeg is not installed");            return Ok(());        }        return Err(error);    }}

Shell commands

When you need shell features such as pipes, redirects, or globs, use Process::shell (sh -c on Unix, cmd /C on Windows):

rust
use dust::process::Process;let result = Process::shell("cat storage/logs/*.log | grep -c ERROR")    .run()    .await?;

[!WARNING] Never interpolate untrusted input into a shell command. Process::shell(format!("convert {name} thumbnail.png")) allows command injection. Pass user input as separate arguments to Process::new instead, where it is never interpreted by a shell.

Process options

Construct a Process builder to customize working directory, timeouts, environment variables, or standard input before calling run:

rust
use dust::prelude::*;use dust::process::Process;let result = Process::new(["bash", "import.sh"])    .path("scripts")    .timeout(2.minutes())    .env("IMPORT_PATH", "storage/imports")    .run()    .await?;
Method Effect
path(dir) Runs the process in dir, relative to the application or absolute
timeout(span) Kills the process after the span; defaults to 60 seconds
idle_timeout(span) Kills the process after it produces no output for the span
forever() Turns the timeout off
env(key, value), envs(pairs) Sets or overrides environment variables
remove_env(key) Removes an inherited variable
without_inheriting_env() Starts with an empty environment
input(bytes) Writes standard input, then closes it
quietly() Stops buffering output in the final result
on_output(callback) Receives output chunks as they arrive

Working directory

By default, processes run in your application's base path. Call path to run the process in a different working directory. For example, passing "frontend" runs the process inside the frontend directory of your application's base path. You may also pass an absolute path to run the process in a directory outside your application:

rust
use dust::process::Process;let result = Process::new(["npm", "run", "build"])    .path("frontend")    .run()    .await?;let result = Process::new(["git", "status"])    .path("/tmp/builds")    .run()    .await?;

Timeouts

By default, dust-framework terminates processes after 60 seconds and returns ProcessTimedOut. Adjust this limit with timeout, disable it with forever(), or set idle_timeout to stop a process that produces no output for a given duration:

rust
use dust::prelude::*;use dust::process::Process;Process::new(["bash", "import.sh"])    .timeout(10.minutes())    .idle_timeout(30.seconds())    .run()    .await?;

On ProcessTimedOut, error.result() exposes the output captured before termination and error.is_idle() tells you whether the idle timeout triggered.

Environment variables

Processes inherit your application's environment, including variables loaded from .env. Use env or envs to set variables, and remove_env to strip an inherited variable from the child process. Any variable passed to env or envs overwrites an existing or inherited variable with the same name:

rust
use dust::process::Process;Process::new(["bash", "import.sh"])    .env("IMPORT_PATH", "storage/imports")    .envs([("BATCH_SIZE", "500"), ("DRY_RUN", "1")])    .remove_env("AWS_SECRET_ACCESS_KEY")    .run()    .await?;

When invoking untrusted programs, prevent secrets like APP_KEY from leaking by calling without_inheriting_env() and passing only the variables the program needs (typically including PATH):

rust
Process::new(["node", "render.js"])    .without_inheriting_env()    .env("NODE_ENV", "production")    .env("PATH", "/usr/local/bin:/usr/bin:/bin")    .run()    .await?;

Input

Pass standard input to a process with input, which writes the bytes and closes stdin. Without input, stdin is immediately closed so programs never hang waiting for input:

rust
use dust::process::Process;let result = Process::new(["wc", "-l"])    .input("Taylor\nAbigail\n")    .run()    .await?;

Reading output while a process runs

For long-running builds or imports (such as inside a console command), pass a callback to on_output to receive stdout and stderr chunks as they arrive:

rust
use dust::process::{OutputKind, Process};Process::new(["npm", "run", "build"])    .on_output(|output| match output.kind() {        OutputKind::Stdout => print!("{}", output.text()),        OutputKind::Stderr => eprint!("{}", output.text()),    })    .run()    .await?;

Each chunk contains whatever bytes the OS delivered at once and may span partial or multiple lines; buffer and split on newlines yourself if you need line-by-line processing.

If a process writes large volumes of output that you do not want buffered in memory, chain .quietly(). on_output still receives every chunk while the final ProcessResult omits buffered output:

rust
use dust::process::Process;Process::new(["pg_dump", "production"])    .quietly()    .on_output(|output| print!("{}", output.text()))    .run()    .await?    .ensure_successful()?;

Starting processes

To launch a process asynchronously while performing other work, call start() to obtain a RunningProcess handle, then await wait() when you need its ProcessResult:

rust
use dust::process::Process;let import = Process::new(["bash", "import.sh"]).forever().start()?;// Perform other work while the import runs...let result = import.wait().await?.ensure_successful()?;

Call id() to inspect the OS process ID and running() to check whether the process is still active.

Reading output as it arrives

Call chunks() on a RunningProcess to consume its output as an async stream so you can await operations on each chunk as it arrives:

rust
use dust::process::Process;use dust::stream::StreamExt;let mut import = Process::new(["bash", "import.sh"]).forever().start()?;let mut chunks = import.chunks();while let Some(output) = chunks.next().await {    // Handle output.text() or output.bytes()...}let result = import.wait().await?;

chunks() may only be called once per process. To react to cancellation or other events while streaming, poll the stream inside task::select!.

Waiting for output

For background daemons or servers that keep running after startup, use wait_until to read output chunks until a predicate matches. It returns true when matched, or false if the process exited first:

rust
use dust::process::Process;let mut server = Process::new(["node", "bootstrap/ssr/app.js"])    .forever()    .start()?;if !server    .wait_until(|output| output.text().contains("Listening"))    .await{    server.wait().await?.ensure_successful()?;}

Keep the match pattern short, since longer strings may be split across two output chunks.

Signals and stopping

Stop a running process gracefully with stop(grace_period). On Unix, dust-framework sends Signal::Terminate and force-kills the process if it has not exited when the grace period elapses; on Windows, it terminates the process immediately. Like wait, stop returns a ProcessResult:

rust
use dust::prelude::*;use dust::process::Process;let server = Process::new(["node", "bootstrap/ssr/app.js"])    .forever()    .start()?;// ...let result = server.stop(10.seconds()).await?;

On Unix, send any Signal with signal:

rust
use dust::console::Signal;server.signal(Signal::User2)?;

Dropping a RunningProcess or cancelling an in-flight run, wait, or stop future (for example, when an HTTP client disconnects) automatically terminates the child process and, on Unix, its spawned process group.

Concurrent processes

Run multiple processes concurrently with task::try_join!. If any process fails to start or times out, try_join! returns that error and terminates the others:

rust
use dust::process;use dust::task;let (users, posts) = task::try_join!(    process::run(["bash", "import-users.sh"]),    process::run(["bash", "import-posts.sh"]),)?;println!("{}", users.output());

When a process fails

A process can fail in ways that look similar in logs but need different handling:

Symptom What run returns What to do
The program is not installed Err with ErrorKind::NotFound Install it or skip the feature
The program exits non-zero Ok(result) with failed() true Call ensure_successful() when non-zero is unexpected
The program exceeds timeout Err(ProcessTimedOut) Inspect result() for the output before the kill
The program goes quiet past idle_timeout Err(ProcessTimedOut) with is_idle() true Treat it as hung
The caller cancels the future The child is terminated Avoid cancelling work with side effects
The program is killed by a signal Ok(result) with no exit code Check exit_code() for None

When a process succeeds at the OS level but reports a problem in its output, rely on the exit code or parse output(); run does not interpret the text. When a command's failure is expected, such as grep finding no matches, do not call ensure_successful(), or inspect exit_code() before deciding.

Returning a ProcessFailed or ProcessTimedOut error from a handler produces a 500 response. When the failure is part of normal operation, catch it and return a domain error or a fallback value instead.

Testing

Call process::fake() in your tests to record external commands without executing them. By default, every faked process succeeds with empty output:

rust
use dust::process;use dust::testing::prelude::*;#[dust::test]async fn importing_runs_the_script(app: Application) {    let processes = process::fake();    app.post("/imports").await.assert_ok();    processes.assert_ran("bash import.sh");}

Keep the returned fake handle alive while exercising your application; dropping it restores real process execution.

Faking results

Use .with(pattern, result) to fake commands matching a wildcard pattern (* matches any text) in registration order. Pass a string, a process::result(), a process::sequence, or a closure receiving &Invocation:

rust
use dust::process::{self, Invocation};let processes = process::fake()    .with("git rev-parse *", "a1b2c3\n")    .with(        "bash import.sh",        process::result()            .output("Importing...\n")            .error_output("No such file\n")            .exit_code(1),    )    .with("ls *", process::sequence(["first\n", "second\n"]))    .with("wc -l", |process: &Invocation| {        let lines = process            .input()            .unwrap_or_default()            .iter()            .filter(|byte| **byte == b'\n')            .count();        process::result().output(format!("{lines}\n"))    });

Once a process::sequence runs out of results, any additional matching command returns an error. When your code streams output with on_output or chunks, dust-framework delivers faked output one line at a time.

Faking failures

Simulate timeouts with timed_out(), which fails with ProcessTimedOut, or startup failures with failed_to_start(kind), which fails with an dust::Error:

rust
use std::io;use dust::process;let processes = process::fake()    .with("ffmpeg *", process::result().output("frame=120\n").timed_out())    .with(        "convert *",        process::result().failed_to_start(dust::ErrorKind::NotFound),    )    .with(        "rsync *",        process::sequence([process::result().timed_out(), process::result()]),    );

Pairing a failure with a success in process::sequence lets you test retry logic.

Preventing stray processes

Call prevent_stray_processes to fail any command that does not match an explicit .with(..) pattern:

rust
use dust::process;let processes = process::fake()    .with("git *", "")    .prevent_stray_processes();

Available assertions

While a process fake is active, dust-framework records every command your application invokes so you can verify which processes ran, how many times they ran, and in what order. You can chain assertions directly on the handle returned by process::fake(), passing either a command pattern or a closure for custom checks:

rust
use dust::prelude::*;use dust::process;let processes = process::fake();// Exercise your application...processes    .assert_ran("git pull")    .assert_ran_times("git pull", 1)    .assert_not_ran("git push")    .assert_ran_in_order(["git pull", "bash import.sh"])    .assert_ran_where(|process| {        process.command() == "bash import.sh"            && process.timeout() == Some(5.minutes().into())    });processes.assert_nothing_ran();

Invocation exposes command, program, arguments, path, timeout, env, and input. Because command strings quote arguments containing spaces, such as convert 'my photo.png' thumbnail.png, compare program() and arguments() directly when checking exact argument lists:

rust
processes.assert_ran_where(|process| {    process.program() == "convert"        && process.arguments() == ["my photo.png", "thumbnail.png"]});