Rust Playbook

Course › Week 4 · Async and plugging into Laravel › Day 5 · lesson 26 of 42 · 30 min reading + 60 min practice

Calling Rust from Laravel

Run the binary with Process, JSON over stdin and stdout, and handle every failure in PHP.

Process facadestdinstdoutstderr

On this page
  1. 1. The protocol
  2. 2. The Rust side
  3. 3. The other exit codes, for real
  4. 4. Where the binary lives
  5. 5. The PHP side
  6. 6. Running it from a queued job
  7. 7. Testing the PHP side without the binary
  8. Why a process, and not something else
  9. Practice
  10. Remember

This is the day the two halves of the course meet. A Laravel app runs a Rust binary, hands it work, and reads back the result, with no HTTP server, no shared memory, no PHP extension. Just a process, the way php artisan itself runs.

It only works reliably with a clear protocol: four channels, each with one job. Today defines it, builds a small Rust program that follows it, and the Laravel code that calls it. Tomorrow’s worker uses exactly this protocol with a database behind it.

A note on what was run: the Rust program on this page was built and fed real input, and its outputs are real. The PHP is syntax-checked with php -l but not executed here, because there is no Laravel app on the machine that builds this site. Run it in yours.

1. The protocol

ChannelDirectionCarries
stdinLaravel → RustThe job: one JSON document
stdoutRust → LaravelThe result: one JSON document, and nothing else
stderrRust → LaravelLogs and messages for people; Laravel logs them
exit codeRust → Laravel0 done · 1 failed, retry later · 2 bad job, do not retry · 3 partly done

JSON over stdin rather than command-line arguments: a job of 500 evaluations does not fit in an argument list (Linux caps it, and arguments are visible to every user in ps). The exit codes are the table from the config and logging lesson.

2. The Rust side

A program called score: it reads evaluations with their answers, and returns the average score of each, in tenths. Everything in it is from earlier lessons. The new parts are the two ends:

serde_json::from_reader(io::stdin().lock()) decodes the job straight from stdin, reading it as it arrives. At the other end, to_writer writes the result into stdout; writeln! adds the final newline and flush() makes sure it is all out before the exit code is returned. Each step can fail (Laravel may have closed the pipe), so the three are chained with and_then and checked once.

src/main.rs
use std::io::{self, Write};
use std::process::ExitCode;

use serde::{Deserialize, Serialize};

/// What Laravel sends on stdin.
#[derive(Deserialize)]
struct Job {
    evaluations: Vec<Evaluation>,
}

#[derive(Deserialize)]
struct Evaluation {
    id: u64,
    scores: Vec<u8>,
}

/// What Laravel reads from stdout: one JSON document, nothing else.
#[derive(Serialize)]
struct Output {
    results: Vec<Scored>,
    failed: Vec<Failed>,
}

#[derive(Serialize)]
struct Scored {
    id: u64,
    answers: usize,
    average_tenths: u32,
}

#[derive(Serialize)]
struct Failed {
    id: u64,
    reason: String,
}

fn score(evaluation: &Evaluation) -> Result<Scored, String> {
    if evaluation.scores.is_empty() {
        return Err(String::from("no answers"));
    }
    if let Some(bad) = evaluation.scores.iter().find(|s| !(1..=5).contains(*s)) {
        return Err(format!("score {bad} is outside 1 to 5"));
    }
    let sum: u32 = evaluation.scores.iter().map(|&s| u32::from(s)).sum();
    let answers = evaluation.scores.len();
    let count = u32::try_from(answers).map_err(|_| "too many answers")?;
    Ok(Scored {
        id: evaluation.id,
        answers,
        average_tenths: sum * 10 / count,
    })
}

fn main() -> ExitCode {
    // stdin: the job. Unreadable input is the caller's mistake: exit 2, retrying cannot help.
    let job: Job = match serde_json::from_reader(io::stdin().lock()) {
        Ok(job) => job,
        Err(error) => {
            eprintln!("score: the job on stdin is not valid: {error}");
            return ExitCode::from(2);
        }
    };

    let mut output = Output {
        results: Vec::new(),
        failed: Vec::new(),
    };
    for evaluation in &job.evaluations {
        match score(evaluation) {
            Ok(scored) => output.results.push(scored),
            Err(reason) => {
                eprintln!("score: evaluation {} skipped: {reason}", evaluation.id);
                output.failed.push(Failed {
                    id: evaluation.id,
                    reason,
                });
            }
        }
    }

    // stdout: the result, as one JSON document and a newline.
    let mut stdout = io::stdout().lock();
    let written = serde_json::to_writer(&mut stdout, &output)
        .map_err(io::Error::from)
        .and_then(|()| writeln!(stdout))
        .and_then(|()| stdout.flush());
    if let Err(error) = written {
        eprintln!("score: cannot write the result: {error}");
        return ExitCode::FAILURE;
    }

    eprintln!(
        "score: {} scored, {} failed",
        output.results.len(),
        output.failed.len()
    );
    if output.failed.is_empty() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(3)
    }
}
job.json
{"evaluations": [{"id": 1042, "scores": [5, 4, 4]}, {"id": 1043, "scores": [3, 2, 4, 5]}]}
$ cargo run < job.json
{"results":[{"id":1042,"answers":3,"average_tenths":43},{"id":1043,"answers":4,"average_tenths":35}],"failed":[]}
score: 2 scored, 0 failed

.map_err(io::Error::from) converts serde’s error into an io::Error, so the three steps share one error type and and_then can chain them. u32::try_from(answers) converts the usize count without as: if it ever did not fit, it would be an error, not a wrong number.

Only the JSON went to stdout; the summary line is on stderr. Laravel reads them separately, so it can parse one and log the other.

3. The other exit codes, for real

job.json
{"evaluations": [{"id": 1042, "scores": [5, 4, 4]}, {"id": 1044, "scores": []}, {"id": 1045, "scores": [4, 9]}]}
$ cargo run < job.json
{"results":[{"id":1042,"answers":3,"average_tenths":43}],"failed":[{"id":1044,"reason":"no answers"},{"id":1045,"reason":"score 9 is outside 1 to 5"}]}
score: evaluation 1044 skipped: no answers
score: evaluation 1045 skipped: score 9 is outside 1 to 5
score: 1 scored, 2 failed
exit code 3

Two evaluations could not be scored. The good one is still in results, the two bad ones are in failed with their reasons, and the exit code is 3: partly done. The PHP side saves the results and reports the failures, without retrying the batch.

job.json
{"evaluations": [{"id": 1042, "scores": [5, 4, 4]}
$ cargo run < job.json
score: the job on stdin is not valid: EOF while parsing a list at line 1 column 50
exit code 2

Truncated JSON: exit 2, and nothing on stdout at all. The job was wrong, so sending it again would fail again; the PHP side treats this as a bug in itself, not as something to retry.

job.json
{"evaluations": [{"id": "1042", "scores": [5]}]}
$ cargo run < job.json
score: the job on stdin is not valid: invalid type: string "1042", expected u64 at line 1 column 30
exit code 2

An id sent as a string, the kind of thing a missing cast in a Laravel model produces: rejected with the exact position, before any work is done.

4. Where the binary lives

The Laravel app runs a compiled file, so the file must exist on every server, built for that server’s system. The usual setup:

StepHow
Build it in CI or in the deploy, not on your laptopcargo build --release in a job that runs on the same OS and CPU type as the servers (for Docker, in the same base image)
Put it at a path the app knowse.g. bin/score inside the Laravel project, listed in .gitignore, or /usr/local/bin/score
Configure the path, never hard-code itconfig/services.php: 'score' => ['binary' => env('SCORE_BINARY', base_path('bin/score'))]
Check it at deploy timebin/score < /dev/null; test $? -eq 2 proves it starts and rejects empty input

A binary built on an M-series Mac does not run on an x86 Linux server, and the error you get there (“Exec format error”) does not say why. Build where you deploy.

5. The PHP side

One class owns the protocol, so the rest of the app never sees exit codes. Process::input() writes the job to the binary’s stdin; timeout() bounds the run; run() waits for it and returns a result with exitCode(), output() (stdout) and errorOutput() (stderr).

app/Services/Score/ScoreRunner.php
<?php

namespace App\Services\Score;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use InvalidArgumentException;

final class ScoreRunner
{
    public function __construct(private readonly string $binary)
    {
    }

    /**
     * @param  array<int, list<int>>  $scoresByEvaluation  evaluation id => scores
     *
     * @throws ScoreFailed  the run failed; safe to retry later
     * @throws InvalidArgumentException  the job itself was rejected; a bug on this side
     */
    public function run(array $scoresByEvaluation): ScoreResult
    {
        $job = ['evaluations' => []];
        foreach ($scoresByEvaluation as $id => $scores) {
            $job['evaluations'][] = ['id' => (int) $id, 'scores' => array_map('intval', $scores)];
        }

        $result = Process::input(json_encode($job, JSON_THROW_ON_ERROR))
            ->timeout(120)
            ->run([$this->binary]);   // an array: no shell, no quoting problems

        if (trim($result->errorOutput()) !== '') {
            Log::info('score: ' . trim($result->errorOutput()));
        }

        return match ($result->exitCode()) {
            0, 3 => ScoreResult::fromJson($result->output()),
            2 => throw new InvalidArgumentException('score rejected the job: ' . trim($result->errorOutput())),
            default => throw new ScoreFailed('score exited with ' . $result->exitCode() . ': ' . trim($result->errorOutput())),
        };
    }
}

Every exit code has a decision: 0 and 3 parse the result, 2 is a bug on the PHP side (a missing cast, a wrong key), anything else, including 1, a panic’s 101, or a timeout, is a failure worth retrying later. There is no branch where a failure is ignored.

Passing the command as an array runs the binary directly, without a shell, so a path with spaces or a strange character cannot break it or be abused.

The result, typed

app/Services/Score/ScoreResult.php
<?php

namespace App\Services\Score;

use JsonException;

final readonly class ScoreResult
{
    /**
     * @param  array<int, int>  $averageTenths  evaluation id => average score × 10
     * @param  array<int, string>  $failed  evaluation id => reason
     */
    private function __construct(public array $averageTenths, public array $failed)
    {
    }

    /** @throws ScoreFailed */
    public static function fromJson(string $stdout): self
    {
        try {
            $data = json_decode($stdout, true, flags: JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
            throw new ScoreFailed('score wrote something that is not JSON: ' . $e->getMessage(), previous: $e);
        }

        $averages = [];
        foreach ($data['results'] ?? [] as $row) {
            $averages[(int) $row['id']] = (int) $row['average_tenths'];
        }
        $failed = [];
        foreach ($data['failed'] ?? [] as $row) {
            $failed[(int) $row['id']] = (string) $row['reason'];
        }

        return new self($averages, $failed);
    }
}
app/Services/Score/ScoreFailed.php
<?php

namespace App\Services\Score;

use RuntimeException;

/** The score binary did not finish its job. Retrying later may succeed. */
final class ScoreFailed extends RuntimeException
{
}

Registering it

app/Providers/AppServiceProvider.php (part of register)
<?php

use App\Services\Score\ScoreRunner;

$this->app->singleton(ScoreRunner::class, fn () => new ScoreRunner(config('services.score.binary')));

6. Running it from a queued job

A job is where retries belong. ScoreFailed is thrown again, so the queue retries with backoff; InvalidArgumentException fails the job at once, because retrying a rejected job is pointless:

app/Jobs/ScoreEvaluations.php
<?php

namespace App\Jobs;

use App\Models\Answer;
use App\Models\Evaluation;
use App\Services\Score\ScoreRunner;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;

final class ScoreEvaluations implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;

    /** @var list<int> seconds to wait before each retry */
    public array $backoff = [30, 120];

    /** @param  list<int>  $evaluationIds */
    public function __construct(public readonly array $evaluationIds)
    {
    }

    public function handle(ScoreRunner $runner): void
    {
        $scores = Answer::query()
            ->whereIn('evaluation_id', $this->evaluationIds)
            ->get(['evaluation_id', 'score'])
            ->groupBy('evaluation_id')
            ->map(fn ($answers) => $answers->pluck('score')->all())
            ->all();

        try {
            $result = $runner->run($scores);
        } catch (InvalidArgumentException $e) {
            $this->fail($e);   // do not retry: the job we built is wrong

            return;
        }

        DB::transaction(function () use ($result) {
            foreach ($result->averageTenths as $id => $tenths) {
                Evaluation::whereKey($id)->update(['average_tenths' => $tenths]);
            }
        });

        foreach ($result->failed as $id => $reason) {
            Log::warning('evaluation not scored', ['evaluation_id' => $id, 'reason' => $reason]);
        }
    }
}

Evaluations with no answers never reach the binary from this query, since groupBy only has the ids that have answers. The binary still checks, because it must not trust its input.

7. Testing the PHP side without the binary

Process::fake() replaces every process run with a canned result, so the job’s logic is tested without Rust installed, including the outcomes that are hard to cause for real: a partial result, a rejected job, a crash.

tests/Unit/ScoreRunnerTest.php
<?php

use App\Services\Score\ScoreFailed;
use App\Services\Score\ScoreRunner;
use Illuminate\Support\Facades\Process;

it('reads results and failures from a partial run', function () {
    Process::fake([
        '*' => Process::result(
            output: '{"results":[{"id":1042,"answers":3,"average_tenths":43}],"failed":[{"id":1044,"reason":"no answers"}]}',
            errorOutput: 'score: 1 scored, 1 failed',
            exitCode: 3,
        ),
    ]);

    $result = (new ScoreRunner('/usr/local/bin/score'))->run([1042 => [5, 4, 4], 1044 => []]);

    expect($result->averageTenths)->toBe([1042 => 43])
        ->and($result->failed)->toBe([1044 => 'no answers']);

    Process::assertRan(fn ($process) => str_contains($process->input, '"id":1044'));
});

it('treats a crash as a failure worth retrying', function () {
    Process::fake(['*' => Process::result(errorOutput: "thread 'main' panicked", exitCode: 101)]);

    (new ScoreRunner('/usr/local/bin/score'))->run([1042 => [5]]);
})->throws(ScoreFailed::class);

Fakes test the PHP side’s decisions. One more test belongs in CI: run the real binary with a known job and compare its stdout, so a change to the Rust side’s JSON breaks the build instead of production.

Why a process, and not something else

Way to call Rust from LaravelWhen it fits
A process with stdin/stdout (today)Batch work from a job or a command. Simple, isolated: a crash cannot take PHP down.
An HTTP service (Week 5)Many small requests, or several apps sharing it. A server to run and monitor.
A PHP extension written in RustCalls inside a request, with no process cost. Much harder to build, deploy and debug.

A process costs a few milliseconds to start. For a job that processes thousands of rows, that is nothing; for a call inside every web request, it adds up, and the HTTP service of Week 5 is the better shape.

PracticeRun it from your own Laravel app

In a Laravel project of yours: build score with cargo build --release, copy it to bin/score, add the config entry, and call ScoreRunner from php artisan tinker with a few made-up evaluations. Then break each channel on purpose: put a println!("starting") before the JSON, make the binary exit 1, give it a 1-second timeout and a sleep of 5. Watch which branch of the match each one ends in.

Remember

  • The protocol: job on stdin, one JSON result on stdout, logs on stderr, exit code 0 done · 1 retry · 2 bad job · 3 partly done.
  • One PHP class owns the protocol and maps every exit code to exactly one decision.

Tomorrow is a build day: the Laravel worker. An artisan command sends a batch of evaluations to Rust, which loads them from Postgres, calls an analysis API concurrently, and writes every result in one transaction.