laravel-rust 0.1.4

Laravel for Rust: a full-stack Rust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# Processes

- [Introduction]#introduction
- [Running processes]#running-processes
    - [Failed processes]#failed-processes
    - [Shell commands]#shell-commands
- [Process options]#process-options
    - [Working directory]#working-directory
    - [Timeouts]#timeouts
    - [Environment variables]#environment-variables
    - [Input]#input
- [Reading output while a process runs]#process-output
- [Starting processes]#starting-processes
    - [Reading output as it arrives]#reading-output-as-it-arrives
    - [Waiting for output]#waiting-for-output
    - [Signals and stopping]#signals-and-stopping
- [Concurrent processes]#concurrent-processes
- [Testing]#testing
    - [Faking results]#faking-results
    - [Faking failures]#faking-failures
    - [Preventing stray processes]#preventing-stray-processes
    - [Available assertions]#available-assertions

<a name="introduction"></a>
## Introduction

Laravel's `laravel::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.

<a name="running-processes"></a>
## 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 laravel::process;

pub async fn show() -> laravel::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 0
result.failed();        // exited with another code, or was killed
result.exit_code();     // Some(0), or None when killed
result.output();        // standard output, as text
result.error_output();  // standard error, as text
result.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()`.

<a name="failed-processes"></a>
### 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 laravel::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 `io::Error` with `ErrorKind::NotFound` when the program is not installed) or when the process [times out](#timeouts) (`ProcessTimedOut`). You can inspect the returned `laravel::Error` with `downcast_ref` to handle specific failures:

```rust
use std::io;

use laravel::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(io) = error.downcast_ref::<io::Error>()
            && io.kind() == io::ErrorKind::NotFound
        {
            tracing::error!("ffmpeg is not installed");

            return Ok(());
        }

        return Err(error);
    }
}
```

<a name="shell-commands"></a>
### 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 laravel::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.

<a name="process-options"></a>
## Process options

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

```rust
use laravel::prelude::*;
use laravel::process::Process;

let result = Process::new(["bash", "import.sh"])
    .path("scripts")
    .timeout(2.minutes())
    .env("IMPORT_PATH", "storage/imports")
    .run()
    .await?;
```

<a name="working-directory"></a>
### Working directory

By default, processes run in your application's [base path](configuration.md#the-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 laravel::process::Process;

let result = Process::new(["npm", "run", "build"])
    .path("frontend")
    .run()
    .await?;

let result = Process::new(["git", "status"])
    .path("/tmp/builds")
    .run()
    .await?;
```

<a name="timeouts"></a>
### Timeouts

By default, Laravel 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 laravel::prelude::*;
use laravel::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.

<a name="environment-variables"></a>
### 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 laravel::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?;
```

<a name="input"></a>
### 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 laravel::process::Process;

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

<a name="process-output"></a>
## Reading output while a process runs

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

```rust
use laravel::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 laravel::process::Process;

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

<a name="starting-processes"></a>
## 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 laravel::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.

<a name="reading-output-as-it-arrives"></a>
### 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 laravel::process::Process;
use laravel::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!`](tasks.md#concurrent-operations).

<a name="waiting-for-output"></a>
### 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 laravel::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.

<a name="signals-and-stopping"></a>
### Signals and stopping

Stop a running process gracefully with `stop(grace_period)`. On Unix, Laravel 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 laravel::prelude::*;
use laravel::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`](console.md#handling-signals) with `signal`:

```rust
use laravel::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.

<a name="concurrent-processes"></a>
## Concurrent processes

Run multiple processes concurrently with [`task::try_join!`](tasks.md#concurrent-operations). If any process fails to start or times out, `try_join!` returns that error and terminates the others:

```rust
use laravel::process;
use laravel::task;

let (users, posts) = task::try_join!(
    process::run(["bash", "import-users.sh"]),
    process::run(["bash", "import-posts.sh"]),
)?;

println!("{}", users.output());
```

<a name="testing"></a>
## 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 laravel::process;
use laravel::testing::prelude::*;

#[laravel::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.

<a name="faking-results"></a>
### 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 laravel::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`, Laravel delivers faked output one line at a time.

<a name="faking-failures"></a>
### Faking failures

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

```rust
use std::io;

use laravel::process;

let processes = process::fake()
    .with("ffmpeg *", process::result().output("frame=120\n").timed_out())
    .with(
        "convert *",
        process::result().failed_to_start(io::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.

<a name="preventing-stray-processes"></a>
### Preventing stray processes

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

```rust
use laravel::process;

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

<a name="available-assertions"></a>
### Available assertions

While a process fake is active, Laravel 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 laravel::prelude::*;
use laravel::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"]
});
```