Search by

olgunozoktas / laravel-rust-bridge

olgunozoktas

Pure Laravel (11/12/13) and PHP (8.2–8.6) integration bridge for connecting independent Rust ext-php-rs extensions and Tokio sidecar daemons — including first-party Laravel Rust components.

Package info

github.com/olgunozoktas/laravel-rust-bridge

pkg:composer/olgunozoktas/laravel-rust-bridge

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.3.4 2026-12-03 01:55 UTC

This package is auto-updated.

Last update: 2026-12-03 01:59:56 UTC


README

CI Release Binaries Packagist Version PHP 8.2–8.6 Laravel 11 / 12 / 13 License: MIT

Use any Rust crate — including first-party Laravel for Rust (laravel-rust) crates — inside Laravel 11 / 12 / 13 and PHP 8.2 / 8.3 / 8.4 / 8.5 / 8.6 applications through typed PHP interfaces and Laravel dependency injection.

src/ contains only the pure bridge core (no image, HTTP, or domain logic). Every Rust feature plugs in as an independent native extension or Tokio sidecar — including the standalone examples in examples/.

Install · Requirements · Prebuilt Downloads · ext-php-rs vs Tokio Sidecar · Examples · Benchmarks · Website · Documentation

Install via Composer

composer require olgunozoktas/laravel-rust-bridge
php artisan vendor:publish --tag=rust-bridge-config
php artisan rust-bridge:status --no-probe

RustBridgeServiceProvider and the RustBridge facade auto-register via Composer package discovery.

Requirements

You do not need Rust installed on your machine if you download prebuilt binaries from GitHub Releases.

Use Case Required on Your Machine
PHP Bridge + Prebuilt Binaries (no compiling) PHP 8.2–8.6 (ext-json), Composer 2.x, Laravel 11 / 12 / 13. Optional: ext-gd (with WebP) only if you want the pure-PHP fallback in examples/image-variants.
Compile Tokio Sidecars from Source (Linux, macOS, Windows) Rust 1.99+ (rustup / cargo, Rust 2024 edition). Zero PHP headers and zero libclang needed.
Compile Native ext-php-rs Extensions (.so / .dylib / .dll) from Source Linux: Rust 1.99+, php8.x-dev (php-config), clang, libclang-dev, pkg-config.
macOS: Rust 1.99+, Homebrew php (php-config), Xcode Command Line Tools (libclang).
Windows: Rust nightly (for abi_vectorcall) + rust-lld linker, LLVM (libclang.dll), PHP 8.2–8.4 NTS (ext-php-rs downloads the matching PHP DevelPack automatically).

Download Prebuilt Binaries (Linux, macOS, Windows)

Every tagged release (v*) builds, smoke-tests, checksums (SHA256SUMS.txt), and attaches ready-to-run binaries to GitHub Releases via .github/workflows/release-binaries.yml:

Platform Tokio Sidecars (any PHP 8.2–8.6) Native ext-php-rs Extension (examples/image-variants)
Linux x86_64 laravel-rust-http-sidecar-linux-x86_64
laravel-rust-async-fanout-sidecar-linux-x86_64
liblaravel_rust_image_variants-linux-x86_64-php8.{2,3,4,5}-nts.so
Linux arm64 laravel-rust-http-sidecar-linux-arm64
laravel-rust-async-fanout-sidecar-linux-arm64
liblaravel_rust_image_variants-linux-arm64-php8.{2,3,4,5}-nts.so
macOS Apple Silicon (arm64) laravel-rust-http-sidecar-macos-arm64
laravel-rust-async-fanout-sidecar-macos-arm64
liblaravel_rust_image_variants-macos-arm64-php8.{2,3,4,5}-nts.dylib
macOS Intel (x86_64) laravel-rust-http-sidecar-macos-x86_64
laravel-rust-async-fanout-sidecar-macos-x86_64
liblaravel_rust_image_variants-macos-x86_64-php8.{2,3,4,5}-nts.dylib
Windows x86_64 (NTS) laravel-rust-http-sidecar-windows-x86_64.exe
laravel-rust-async-fanout-sidecar-windows-x86_64.exe
laravel_rust_image_variants-windows-x86_64-php8.{2,3,4}-nts.dll

Verify checksums and load a downloaded binary immediately:

# Verify SHA-256 checksum
sha256sum -c SHA256SUMS.txt --ignore-missing

# Load native extension for a single PHP command (or add `extension=/path/to/lib...` to php.ini)
php -d extension=/absolute/path/to/liblaravel_rust_image_variants-linux-x86_64-php8.4-nts.so artisan rust-bridge:status --no-probe

# Or run a prebuilt Tokio sidecar (no php.ini change needed)
chmod +x laravel-rust-http-sidecar-linux-x86_64
./laravel-rust-http-sidecar-linux-x86_64 --listen tcp://127.0.0.1:7878

30-Second Laravel Example (Horizon WebP Job + Safe PHP Fallback)

Adopt Rust one job at a time behind a normal PHP interface. If the native .so / .dylib / .dll is loaded, Rust runs in-process at ~55 µs FFI overhead; if disabled or absent in auto mode, Laravel falls back transparently to pure PHP GD:

use Olgun\RustBridge\Examples\ImageVariants\Contracts\ImageVariantGenerator;

final class ScreenshotController
{
    public function store(Request $request, ImageVariantGenerator $variants)
    {
        $batch = $variants->generateWebpVariants(
            imageBytes: (string) $request->getContent(),
            widths: [768, 960, 1536],
            quality: 80,
        );

        return response()->json([
            'backend' => $batch->backend, // "native" (Rust) or "php-gd" (fallback)
            'sizes' => array_map(fn ($v) => [$v->width, $v->height, $v->sizeBytes], $batch->variants),
        ]);
    }
}

Architecture at a Glance

flowchart LR
    App["Laravel App (Controllers, Services, Horizon Jobs)"]
    Bridge["Pure Bridge Core (RustBridge / BridgeManager)"]

    App -->|"Typed PHP Contract (DI)"| Bridge

    subgraph InProcess["Path A: In-Process Native Extension (ext-php-rs)"]
        Detector["NativeExtensionRegistry (Cached ABI Check)"]
        RustExt["Compiled Rust .so / .dylib (~55 us FFI, catch_unwind)"]
        PhpFallback["Pure PHP Fallback + NativeFallbackTriggered"]
        Detector -->|"Loaded & ABI Match"| RustExt
        Detector -->|"Missing & auto mode"| PhpFallback
    end

    subgraph OutOfProcess["Path B: Out-of-Process Tokio Sidecar (NDJSON RPC v1)"]
        SidecarMgr["SidecarManager (default + Named Connections)"]
        Breaker["CircuitBreakerTransport + Persistent Socket"]
        Daemon["Standalone Tokio Sidecar (laravel_rust_bridge_sidecar)"]
        SidecarMgr --> Breaker
        Breaker -->|"Unix 0600 or Loopback TCP"| Daemon
    end

    Bridge -->|"NativeModuleDefinition"| Detector
    Bridge -->|"SidecarModuleDefinition"| SidecarMgr
Loading

ext-php-rs vs Tokio Sidecar

This bridge supports two Rust execution models behind one unified Laravel API (RustBridge). Understanding the difference takes 30 seconds:

  • Native Extension (ext-php-rs) compiles to a .so / .dylib loaded inside PHP (like ext-gd or ext-redis). Calls pass raw bytes directly over C FFI (~55 µs overhead) with zero sockets or JSON encoding.
  • Tokio Sidecar (laravel_rust_bridge_sidecar) runs as a separate long-lived Rust daemon beside PHP-FPM / Horizon over a persistent Unix socket (0600) or loopback TCP (NDJSON RPC v1). One Tokio runtime stays warm across thousands of PHP requests and works with any PHP version (8.2–8.6) without recompiling.
flowchart TD
    Start["Which Rust Transport Fits Your Crate?"]
    Q1{"Needs Tokio, async I/O, persistent pools, or laravel-rust?"}
    Q2{"Passes multi-MB raw bytes or needs <0.5 ms call overhead?"}
    Q3{"Need crash isolation or zero PHP-version ABI coupling?"}
    Sidecar["Use Tokio Sidecar (laravel_rust_bridge_sidecar)"]
    Native["Use Native Extension (ext-php-rs + optional PHP fallback)"]

    Start --> Q1
    Q1 -->|Yes| Sidecar
    Q1 -->|No| Q2
    Q2 -->|Yes| Native
    Q2 -->|No| Q3
    Q3 -->|Yes| Sidecar
    Q3 -->|No| Native
Loading
Native Extension (ext-php-rs) Tokio Sidecar (SidecarModule)
Runs where Inside PHP-FPM / Horizon process Separate long-lived Rust process
Overhead ~55 µs (+0.055 ms, zero IPC) ~0.2–1.5 ms (Unix socket / TCP NDJSON)
Best for CPU-bound transforms on bytes or strings (images, Markdown, HTML, CSV, PDF, hashing, compression) Async I/O, connection pools, 10k–100k concurrent tasks, gRPC, streaming, first-party laravel-rust
Large binary payloads Fast (BinarySlice zero-IPC bytes) Avoid over JSON (pass file paths instead)
Persistent pools across PHP requests Tied to each PHP worker Shared warm across all PHP workers
Crash isolation Wrap every entry in catch_unwind Process-isolated + optional CircuitBreakerTransport
PHP version coupling Compile per PHP minor (ZEND_MODULE_API) Zero coupling — upgrade PHP independently
Built-in PHP fallback Yes (auto / native / php modes) Optional in your PHP service
Examples in this repo examples/image-variants/ examples/laravel-http/, examples/async-fanout/

Rule of thumb:

  1. Need Tokio, async I/O, persistent connection pools, process isolation, or laravel-rust? → Tokio Sidecar.
  2. Running synchronous CPU work on bytes/strings or need sub-millisecond FFI latency? → ext-php-rs.
  3. Need both? Combine them in the same Laravel controller or Horizon job — both inject as normal typed interfaces.

Read the complete deep dive, sequence diagrams, workload catalog, and pitfalls: docs/ext-php-rs-vs-sidecar.md.

PHP & Laravel Compatibility

The pure Composer package (src/) requires PHP ^8.2 and Laravel 11 / 12 / 13.

PHP Version ZEND_MODULE_API Laravel Versions Bridge Core (src/) Tokio Sidecars Native ext-php-rs (0.16.5)
PHP 8.2 20220829 Laravel 11, 12 Supported Supported (no rebuild) Supported (compile with php8.2-dev)
PHP 8.3 20230831 Laravel 11, 12 Supported Supported (no rebuild) Supported (compile with php8.3-dev)
PHP 8.4 20240924 Laravel 11, 12, 13 Supported & tested Supported & benchmarked Supported, tested & benchmarked
PHP 8.5 20250925 Laravel 12, 13 Supported & lint-verified Supported (no rebuild) Supported (compile with php8.5-dev)
PHP 8.6 20260924 Future / dev Supported & lint-verified Supported (no rebuild) Supported (compile with php8.6-dev)

Why sidecars survive PHP upgrades untouched: A Tokio sidecar communicates over NDJSON RPC v1 and never links against libphp. Upgrading PHP 8.2 → 8.4 → 8.5 requires zero sidecar changes. For ext-php-rs extensions, download the matching release binary or rebuild once per target PHP minor version with PHP=/usr/bin/php8.X PHP_CONFIG=/usr/bin/php-config8.X cargo build --release.

Standalone Examples (examples/)

Everything outside the pure bridge core lives cleanly under examples/:

laravel-rust-bridge/
├── src/                        # Pure Laravel <-> Rust bridge core only
├── config/rust_bridge.php      # Pure bridge config (native mode + sidecars)
├── rust/sidecar/               # Pure reusable Tokio RPC server library crate
├── docs/                       # Complete documentation hub (docs/README.md)
├── .claude/skills/             # Bundled AI agent skill for building extensions
├── benchmarks/                 # Reproducible PHP vs Rust benchmarks
└── examples/
    ├── image-variants/         # Standalone ext-php-rs WebP extension + PHP GD fallback
    ├── laravel-http/           # Standalone Tokio sidecar powered by laravel-rust =0.1.4
    └── async-fanout/           # Standalone Tokio sidecar (100,000 concurrent async jobs)

Example 1: Horizon Job & Native ext-php-rs (examples/image-variants)

Run the same typed ImageVariantGenerator contract inside a queued Laravel Horizon job (examples/image-variants/src/Jobs/GenerateScreenshotVariantsJob.php):

use Olgun\RustBridge\Examples\ImageVariants\Jobs\GenerateScreenshotVariantsJob;

GenerateScreenshotVariantsJob::dispatch(
    sourcePath: 'screenshots/homepage.png',
    outputDirectory: 'screenshots/homepage/variants',
    disk: 'local',
    screenshotId: 'shot-42',
)->onQueue('media');

Example 2: First-Party laravel-rust =0.1.4 HTTP Sidecar (examples/laravel-http)

Start the long-lived sidecar once:

./target/release/laravel-rust-http-sidecar --listen tcp://127.0.0.1:7878

Inject ConcurrentHttpClient anywhere in Laravel:

use Olgun\RustBridge\Examples\LaravelHttp\Contracts\ConcurrentHttpClient;
use Olgun\RustBridge\Examples\LaravelHttp\Data\HttpBatchRequest;

final class CatalogAggregator
{
    public function __construct(private ConcurrentHttpClient $http) {}

    public function fetchDashboard(): array
    {
        $batch = $this->http->sendBatch([
            HttpBatchRequest::get('catalog', 'https://internal.service/catalog'),
            HttpBatchRequest::get('pricing', 'https://internal.service/pricing'),
            HttpBatchRequest::postJson('audit', 'https://internal.service/events', ['type' => 'view']),
        ], maxConcurrency: 8);

        return [
            'laravel_rust_version' => $batch->crateVersion, // "0.1.4"
            'catalog' => $batch->get('catalog')?->json(),
            'pricing' => $batch->get('pricing')?->json(),
        ];
    }
}

Example 3: 100,000 Concurrent Async Tasks (examples/async-fanout)

use Olgun\RustBridge\Examples\AsyncFanout\Contracts\ConcurrentTaskRunner;

$report = app(ConcurrentTaskRunner::class)->runSimulatedIoJobs(count: 100_000, delayMs: 1000);
// ~1,079 ms wall, ~48.3 MB peak RSS (368 bytes/job)

Build Your Own Rust Extension (No Fork Needed)

Ship an independent Composer package + Rust extension or sidecar and register it in your package's ServiceProvider::boot().

Plug in a Native ext-php-rs Extension

use Illuminate\Contracts\Foundation\Application;
use Olgun\RustBridge\Data\NativeExtensionSpec;
use Olgun\RustBridge\Facades\RustBridge;
use Olgun\RustBridge\Modules\NativeModuleDefinition;
use Olgun\RustBridge\Native\NativeExtensionDetector;

RustBridge::registerNativeModule(new NativeModuleDefinition(
    name: 'acme-markdown',
    extension: NativeExtensionSpec::forExtension(
        extensionName: 'acme_markdown',
        expectedAbiVersion: 1,
        requiredFunctions: ['acme_markdown_to_html'],
    ),
    nativeFactory: fn (Application $app, NativeExtensionDetector $detector) => new NativeMarkdownRenderer($detector),
    fallbackFactory: fn (Application $app) => new PhpMarkdownRenderer(),
    contract: MarkdownRenderer::class,
    package: 'acme/laravel-rust-markdown',
));

Plug in a Dedicated Tokio Sidecar Daemon

use Illuminate\Contracts\Foundation\Application;
use Olgun\RustBridge\Contracts\SidecarTransportInterface;
use Olgun\RustBridge\Data\SidecarEndpointConfig;
use Olgun\RustBridge\Facades\RustBridge;
use Olgun\RustBridge\Modules\SidecarModuleDefinition;

RustBridge::registerSidecar('acme-search', new SidecarEndpointConfig(
    endpoint: 'unix:///run/acme-search.sock',
    authToken: config('acme_search.token'),
    circuitBreakerEnabled: true,
));

RustBridge::registerSidecarModule(new SidecarModuleDefinition(
    name: 'acme-search',
    factory: fn (Application $app, SidecarTransportInterface $transport) => new RustSearchClient($transport),
    contract: FullTextSearch::class,
    sidecarConnection: 'acme-search',
    package: 'acme/laravel-rust-search',
));

Full third-party authoring guide: docs/building-a-third-party-package.md and docs/protocol-v1.md.

AI Agent Skill

This repository ships a dedicated agent skill at .claude/skills/laravel-rust-bridge/SKILL.md with focused optimization and security references:

Building the Reference Extensions (Separate from Composer)

Composer installs PHP code only. Build the Rust workspace crates separately for your target host and PHP version (PHP 8.2, 8.3, 8.4, 8.5, or 8.6 on Linux or macOS):

# Linux — set PHP_VER to 8.2, 8.3, 8.4, or 8.5
PHP_VER=8.4
PHP="/usr/bin/php${PHP_VER}" \
PHP_CONFIG="/usr/bin/php-config${PHP_VER}" \
cargo build --release \
  -p laravel-rust-image-variants-ext \
  -p laravel-rust-http-sidecar \
  -p laravel-rust-async-fanout-sidecar

# macOS — Homebrew PHP (php@8.2, php@8.3, php@8.4, or php) + Xcode Command Line Tools
PHP=/opt/homebrew/bin/php \
PHP_CONFIG=/opt/homebrew/bin/php-config \
LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib \
cargo build --release \
  -p laravel-rust-image-variants-ext \
  -p laravel-rust-http-sidecar \
  -p laravel-rust-async-fanout-sidecar

Hardened production sidecar example (Unix socket 0600, constant-time auth, anti-DNS-rebinding SSRF blocking):

export RUST_BRIDGE_SIDECAR_TOKEN="replace-with-high-entropy-secret"

./target/release/laravel-rust-http-sidecar \
  --listen unix:///run/laravel-rust-bridge/http-sidecar.sock \
  --auth-token-env RUST_BRIDGE_SIDECAR_TOKEN \
  --block-private-networks \
  --allowed-hosts api.example.com,*.trusted.example

Full Linux phpenmod, php8.4-fpm, Horizon restart, and macOS instructions: docs/building-the-extension.md.

Benchmarks

Measured uncontended on 2026-12-02 (macOS arm64, PHP 8.4.24, Rust 1.99.1 --release):

1. Native ext-php-rs (examples/image-variants, 1920x1080 PNG → [768, 960, 1536] WebP, 30 iterations)

Each preset (effort = 4 and effort = 2) was run in its own paired three-tier benchmark (benchmarks/results-latest.json and benchmarks/results-effort2.json). Both paired PHP GD baselines are shown below so the speedup denominators stay explicit:

Run & Tier Mean wall (ms) p95 wall (ms) CPU / iter (ms) Gain vs Paired GD Baseline
Run A (effort = 4): Pure PHP GD baseline (results-latest.json) 131.205 137.186 130.767 Run A baseline
Run A: PHP → ext-php-rs (effort = 4, strict GD parity) 57.793 58.419 94.724 2.27x mean (2.35x p95, 1.38x CPU)
Run B (effort = 2): Pure PHP GD baseline (results-effort2.json) 146.227 290.091 136.822 Run B baseline
Run B: PHP → ext-php-rs (effort = 2, fast Horizon preset) 35.512 35.928 57.677 4.12x vs Run B GD (146.227 ms) · 3.70x vs Run A GD (131.205 ms) · +55 µs FFI delta

2. Tokio Sidecar Concurrency (examples/async-fanout, 100,000 × 1s Async Jobs)

Runner Jobs Wall (ms) Peak Mem (MB) Bytes / Job
PHP sequential (exact math) 100,000 100,000,000 (27h 46m) n/a n/a
PHP 8.4 Fibers 10,000 1,055.5 168.00 17,406
PHP → Tokio sidecar 100,000 1,079.3 48.34 368 (47.3x smaller)

3. First-Party laravel-rust =0.1.4 HTTP (examples/laravel-http, 200 × 100ms Concurrent Requests)

  • PHP curl_multi (Http::pool): 138.9 ms wall, 10.50 ms PHP CPU.
  • PHP → laravel-rust-http-sidecar: 112.8 ms wall (1.23x faster), 1.19 ms PHP CPU (8.8x less PHP CPU).

Run the benchmarks yourself:

php benchmarks/run_all.php --iterations=30 --warmup=5 --effort=4 --profile
php benchmarks/run_all.php --iterations=30 --warmup=5 --effort=2 --profile
NO_PROXY=127.0.0.1,localhost php benchmarks/run_concurrency_bench.php

Verification & Tests

# Rust workspace tests
cargo test --release -p laravel-rust-bridge-sidecar -p bridge-image-variants -p bridge-async-fanout -p bridge-laravel-http

# Package Pest suite (without and with native extension)
php vendor/bin/pest
php -d extension=./target/release/liblaravel_rust_image_variants.dylib vendor/bin/pest

Documentation (/docs)

Browse the complete index at docs/README.md:

Guide Purpose
docs/ext-php-rs-vs-sidecar.md Detailed comparison of native ext-php-rs extensions vs Tokio sidecar modules
docs/building-the-extension.md Linux PHP 8.4 & macOS compilation, installation, and daemon supervision
docs/building-a-third-party-package.md Ship your own Laravel + Rust Composer package without forking
docs/adding-a-crate.md Add a new standalone example crate inside this workspace
docs/protocol-v1.md Sidecar NDJSON RPC Wire Protocol v1 specification
docs/architecture-and-security.md SOLID design patterns, performance architecture, and defense-in-depth security
docs/benchmarks.md Full methodology, hardware specs, and stage profiles
docs/adr/0001-dual-transport-and-laravel-rust-integration.md Architecture Decision Record for dual transport & laravel-rust
docs/laravel-rust-ecosystem-audit.md Verified public APIs and features of official laravel-rust crates

More products by the same author

Other production web applications and developer tools maintained by the same author:

Logo Product What it is
Main App Main App Curated multi-platform application directory (macOS, web, iOS, Windows) running Laravel + Livewire.
FindUtils FindUtils 460+ free browser tools — converters, formatters, PDF tools, generators, and calculators with no signup and local-first browser processing.
Emoji Favicons Emoji Favicons Turn any of 3,773 Unicode emojis into an edge-hosted SVG, PNG, or ICO favicon with one <link> tag and a documented API.
DataVisitors DataVisitors Privacy-first software analytics for websites, apps, and servers — no cookies on visitors by default, tracking sources, behavior, and conversions.

License

MIT — see LICENSE.