laravel-rust-bridge maintained by sandermuller
Laravel Rust Bridge
Queue jobs from a Laravel PHP app for a Laravel Rust worker, and handle the jobs that worker sends back.
Laravel Rust's queue workers don't run PHP's jobs. A PHP job holds a serialize()d object, and Laravel Rust reads its own JSON payload. This package writes that payload, so a PHP app can hand one piece of work to Rust and keep everything else in PHP.
use SanderMuller\LaravelRustBridge\Facades\RustBridge;
RustBridge::dispatch('exports.statistics', ['export_id' => $export->id]);
#[derive(Queueable)]
pub struct ExportStatistics {
pub export_id: i64,
}
#[job(name = "exports.statistics")]
impl ExportStatistics {
pub async fn handle(self) -> laravel::Result<()> {
// ...
Ok(())
}
}
[!WARNING] Laravel Rust is in beta, and its payload format is internal to the framework. This package writes payload version 1, which
laravel-rust0.1.x reads. Pin the crate to an exact version (laravel-rust = "=0.1.3") and upgrade both sides together. If the format changes, the worker fails the job with "queued in payload format 1, which this application can't read" instead of misreading it.
Requirements
- PHP 8.4+, Laravel 12 or 13
- A Laravel Rust app on
laravel-rust0.1.x, with itsredisorsqsfeature - For Redis: phpredis or Predis
Installation
composer require sandermuller/laravel-rust-bridge
php artisan vendor:publish --tag=laravel-rust-bridge-config
Configuration
Redis
Laravel Rust reads its queue from unprefixed keys (queues:{name}), and Laravel PHP prefixes Redis keys by default. Add a connection without a prefix to config/database.php, on the Redis database the worker reads:
'redis' => [
// ...
'rust' => [
'url' => env('RUST_REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('RUST_REDIS_DB', '5'),
'options' => ['prefix' => ''],
],
],
The bridge asks the Redis client for its prefix before every dispatch, and throws a MisconfiguredBridge exception if there is one, because the worker would never see those jobs. Laravel takes the prefix from the connection's prefix key, then its options.prefix, then the global database.redis.options.prefix. Set options.prefix to '' on this connection and don't give it a prefix key; the global prefix can stay.
On the Rust side, point REDIS_URL and REDIS_DB at the same database and set QUEUE_CONNECTION=redis.
SQS
Set RUST_BRIDGE_TRANSPORT=sqs. The bridge sends through your PHP app's sqs queue connection, so queue names resolve against its prefix and suffix like any other job.
Give the Rust worker its own queue. Laravel PHP, Laravel Rust and the bridge all default to the queue default, and each worker fails any job of the other side's that it receives. The bridge throws a MisconfiguredBridge exception when a job would go to the connection's default queue, which PHP workers read. Set RUST_BRIDGE_QUEUE to the Rust queue, for example rust, and set SQS_QUEUE in the Rust app to the same name. An SQS connection that only the bridge uses needs a queue option other than the Rust queue too. The bridge checks only the connection it sends through. If PHP workers read another SQS connection, make sure that connection's queue is not the Rust queue either.
Laravel's SQS overflow (overflow.enabled on the connection) rewrites large payloads into a cache pointer that Laravel Rust can't read. Keep job data small: send ids, not records.
Options
| Key | Env | Default |
|---|---|---|
transport |
RUST_BRIDGE_TRANSPORT |
redis |
queue |
RUST_BRIDGE_QUEUE |
default |
redis.connection |
RUST_BRIDGE_REDIS_CONNECTION |
rust |
sqs.connection |
RUST_BRIDGE_SQS_CONNECTION |
sqs |
Dispatching jobs to Rust
$id = RustBridge::dispatch('exports.statistics', ['export_id' => 42]);
$id = RustBridge::dispatch('imports.viewers', ['import_id' => 7], queue: 'rust-imports');
jobis the name in the Rust job's#[job(name = "..")]. Always set a stable name on the Rust side: without one, the name is the Rust module path, and renaming the module breaks every job PHP sends.databecomes the Rust job struct's fields. The keys must match the field names, and the values must decode into the field types.dispatch()returns the job id, a UUIDv7, which is the id the Rust worker logs.
You can also inject SanderMuller\LaravelRustBridge\RustBridge instead of using the facade.
Not supported yet: delays, chains and batches.
Handling jobs from Rust
The Rust app writes a small JSON message to a callback queue, and the package fires a RustCallbackReceived event for it:
use SanderMuller\LaravelRustBridge\Events\RustCallbackReceived;
Event::listen(function (RustCallbackReceived $event): void {
if ($event->name === 'export.finished') {
ExportFinished::dispatch(Export::findOrFail($event->data['export_id']));
}
});
The callback connection
Never let the Rust app write to one of your ordinary queues. Laravel's worker trusts what it reads from a queue: it builds the class a message names, and it unserializes the job a message carries, so anything that can write to a queue can run code in your PHP app.
Callbacks get a queue connection of their own instead, with the rust-callbacks driver. On this connection every message is rewritten into a RustCallback job, holding only a name and a data array, before Laravel reads it. A message can't name another class, and nothing in it is unserialized: not when it runs, not when it fails, and not when queue:retry picks it up again.
Add the connection to config/queue.php, on the database:
'rust-callbacks' => [
'driver' => 'rust-callbacks',
'via' => 'database',
'connection' => env('DB_CONNECTION'),
'table' => 'rust_callbacks',
'queue' => 'default',
'retry_after' => 90,
],
php artisan vendor:publish --tag=laravel-rust-bridge-migrations
php artisan migrate
Or on SQS, with the same options as Laravel's sqs driver:
'rust-callbacks' => [
'driver' => 'rust-callbacks',
'via' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX'),
'queue' => env('RUST_CALLBACKS_SQS_QUEUE', 'rust-callbacks'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
SQS overflow (overflow.enabled) is refused on this connection: a message could point the worker at any key in the overflow cache store.
Then run a worker for it, next to your other workers:
php artisan queue:work rust-callbacks
Sending a callback from Rust
The message the Rust app writes:
{
"data": { "name": "export.finished", "data": { "export_id": 42 } },
"maxTries": 3
}
The package reads only these fields:
data.name: letters, digits,.,_,:and-, up to 255 characters.data.data: a JSON object. Leave it out to send an empty one.maxTries: a whole number from 1 to 10. 0 or less becomes 1, because Laravel reads 0 as "retry forever", and more than 10 becomes 10. Leave it out to use the worker's--tries.
Every other field is ignored, and each message gets a new UUID. A message larger than 1 MiB fails without being decoded, and so does a message that grows past 1 MiB when the package rewrites it. A message that breaks these rules fails on its first try and lands in PHP's failed jobs. The exception names the problem, never the message's values.
On the database, insert it into rust_callbacks. Laravel PHP stores Unix-second timestamps there:
use laravel::db;
async fn export_finished(export_id: i64) -> laravel::Result<()> {
let php = db::connection("php")?;
let payload = serde_json::json!({
"data": { "name": "export.finished", "data": { "export_id": export_id } },
"maxTries": 3,
})
.to_string();
let now = laravel::now().timestamp().as_second();
db::query!(
php,
"INSERT INTO rust_callbacks (queue, payload, attempts, reserved_at, available_at, created_at) VALUES ('default', {payload}, 0, NULL, {now}, {now})"
)
.insert()
.await?;
Ok(())
}
On SQS, send the same JSON as the message body to the callback queue.
Security
- Authorize in PHP, before you dispatch. A Rust job doesn't know which user asked for it. Pass ids you have already checked, never raw request input.
- Treat callback data as input. Validate
RustCallbackReceived::$databefore you act on it. - Send ids, not secrets. Payloads sit unencrypted in Redis or SQS, and a failed callback's data stays in
failed_jobs.
If you restrict permissions, this is what each side needs:
- Database: the Rust app needs
INSERTonrust_callbacks(plusUSAGEon its id sequence on PostgreSQL). - SQS: PHP needs
SendMessageon the Rust queues, andReceiveMessage,DeleteMessageandChangeMessageVisibilityon the callback queue. Rust needs those three on its own queues,SendMessageon the callback queue, andGetQueueUrlif it looks queues up by name. - Redis ACL: PHP needs
EVAL,HSETandRPUSHonqueues:{<your rust queues>}*, plusSELECTfor a database other than 0.
Report security issues as described in SECURITY.md.
Testing
composer test
The Redis tests need a Redis server on 127.0.0.1:6379 and use database 15. Set REDIS_HOST, REDIS_PORT or RUST_BRIDGE_TEST_REDIS_DB to change that.
License
MIT. See LICENSE.