Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ With 1-second blocking operations, this means only **~8 requests/second** throug

## 🎯 The Solution: Runtime Coroutine Hooks

This fork enables **Swoole's coroutine runtime hooks** (`SWOOLE_HOOK_ALL`), which automatically converts PHP's blocking functions into non-blocking, coroutine-safe versions:
This fork enables **Swoole's coroutine runtime hooks** (`SWOOLE_HOOK_ALL` minus `FILE`/`STDIO` by default), which automatically converts PHP's blocking network/sleep functions into non-blocking, coroutine-safe versions:

> **Note:** `SWOOLE_HOOK_FILE` / `SWOOLE_HOOK_STDIO` stay off by default. Hooked file I/O deadlocks ZipArchive, SplFileObject, PhpSpreadsheet, and hangs Livewire uploads. Re-enable only via `octane.swoole.hook_file` / `hook_stdio` (or an explicit `hook_flags` bitmask) if your stack is coroutine-safe.

```
32 workers × ~87 concurrent requests per worker = 2,784+ concurrent requests
Expand Down Expand Up @@ -396,14 +398,14 @@ Each worker can efficiently handle **~87 concurrent requests** thanks to corouti

### Runtime Hooks

Enabled automatically on worker start:
Enabled automatically on worker start via `RuntimeHooks` (`SWOOLE_HOOK_ALL` minus `FILE`/`STDIO` by default):

```php
// src/Swoole/Handlers/OnWorkerStart.php
\Swoole\Runtime::enableCoroutine(SWOOLE_HOOK_ALL);
RuntimeHooks::enable($swooleConfig);
```

This converts all blocking I/O to coroutine-safe operations without any code changes required.
Network/sleep I/O becomes coroutine-safe without app code changes. File hooks stay off so ZipArchive / Livewire uploads do not hang — override with `octane.swoole.hook_file` if needed.

### Worker Initialization

Expand Down
20 changes: 16 additions & 4 deletions bin/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,13 @@

$_ENV['APP_RUNNING_IN_CONSOLE'] = false;

use Swoole\Runtime;

// Configure coroutine settings BEFORE any coroutine operations
// max_coroutine: Maximum number of concurrent coroutines (application-level concurrency)
// Default: 3000, Recommended for high traffic: 100000
Swoole\Coroutine::set([
'max_coroutine' => 100000,
]);

Runtime::enableCoroutine(SWOOLE_HOOK_ALL);

/*
|--------------------------------------------------------------------------
| Find Application Base Path
Expand Down Expand Up @@ -56,4 +52,20 @@

require_once $autoload_file;

/*
|--------------------------------------------------------------------------
| Enable Coroutine Runtime Hooks
|--------------------------------------------------------------------------
|
| FILE/STDIO hooks are excluded by default — ZipArchive, SplFileObject,
| PhpSpreadsheet, and Livewire uploads hang under SWOOLE_HOOK_FILE.
|
*/

$swooleConfig = (isset($serverState) && is_array($serverState['octaneConfig']['swoole'] ?? null))
? $serverState['octaneConfig']['swoole']
: [];

Laravel\Octane\Swoole\Coroutine\RuntimeHooks::enable($swooleConfig);

return $basePath;
19 changes: 19 additions & 0 deletions config/octane.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,25 @@

'timeout_sweep_interval_ms' => env('OCTANE_TIMEOUT_SWEEP_INTERVAL_MS', 5000),

/*
|--------------------------------------------------------------------------
| Runtime Hook Flags
|--------------------------------------------------------------------------
|
| By default Octane enables SWOOLE_HOOK_ALL except FILE and STDIO.
| Hooked file I/O deadlocks ZipArchive / SplFileObject / PhpSpreadsheet
| and hangs Livewire (and similar) uploads on Swoole workers.
|
| Set hook_file / hook_stdio to true only if you know your I/O stack is
| coroutine-safe. Or pass an explicit integer bitmask via hook_flags.
|
*/

'hook_flags' => null,

'hook_file' => env('OCTANE_SWOOLE_HOOK_FILE', false),

'hook_stdio' => env('OCTANE_SWOOLE_HOOK_STDIO', false),

/*
|--------------------------------------------------------------------------
Expand Down
8 changes: 7 additions & 1 deletion src/Commands/StartSwooleCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ protected function writeServerStateFile(
*/
protected function defaultServerOptions(SwooleExtension $extension)
{
return array_merge([
$options = array_merge([
// Enable coroutine support for async I/O operations
'enable_coroutine' => true,

Expand Down Expand Up @@ -205,6 +205,12 @@ protected function defaultServerOptions(SwooleExtension $extension)
// Number of worker processes
'worker_num' => $this->workerCount($extension),
], config('octane.swoole.options', []));

// Runtime hooks + Livewire coroutine locking require request callbacks
// to run inside coroutines. Forcing false deadlocks uploads/updates.
$options['enable_coroutine'] = true;

return $options;
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/Concerns/ProvidesDefaultConfigurationOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ protected static function prepareApplicationForNextOperationListeners(): array
\Laravel\Octane\Listeners\FlushStrCache::class,
\Laravel\Octane\Listeners\FlushTranslatorCache::class,
\Laravel\Octane\Listeners\FlushVite::class,
\Laravel\Octane\Listeners\PrepareBladeComponentsForNextOperation::class,

// First-Party Packages...
\Laravel\Octane\Listeners\PrepareInertiaForNextOperation::class,
Expand Down
6 changes: 6 additions & 0 deletions src/Listeners/GiveNewRequestInstanceToApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

namespace Laravel\Octane\Listeners;

use Illuminate\Http\Request;
use Laravel\Octane\Swoole\Coroutine\Context;
use Laravel\Octane\Swoole\Coroutine\CoroutineApplication;
use Laravel\Octane\Swoole\Coroutine\WorkerRequestBinding;

class GiveNewRequestInstanceToApplication
{
Expand All @@ -17,6 +19,10 @@ public function handle($event): void
$event->sandbox->instance('request', $event->request);

if (Context::inCoroutine() || $event->sandbox instanceof CoroutineApplication) {
// Do not pin Request on the shared worker app (race under concurrency).
// Bind a Context-aware factory so worker-container resolution still works.
WorkerRequestBinding::install($event->app);

return;
}

Expand Down
33 changes: 33 additions & 0 deletions src/Listeners/PrepareBladeComponentsForNextOperation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Laravel\Octane\Listeners;

use Illuminate\View\Component;

class PrepareBladeComponentsForNextOperation
{
/**
* Handle the event.
*
* Livewire lazy placeholders (and other inline Blade components) cache
* `__components::…` view names in a static property. Octane resets the
* view finder between operations, so a cache hit can occur without the
* `__components` namespace being registered again.
*
* @param mixed $event
*/
public function handle($event): void
{
Component::flushCache();
Component::forgetFactory();

if (! $event->sandbox->bound('view')) {
return;
}

$event->sandbox->make('view')->addNamespace(
'__components',
$event->sandbox->make('config')->get('view.compiled'),
);
}
}
12 changes: 12 additions & 0 deletions src/Swoole/Actions/EnsureRequestsDontExceedMaxExecutionTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Laravel\Octane\Swoole\Actions;

use Laravel\Octane\Swoole\Coroutine\LivewireCoroutineMutex;
use Laravel\Octane\Swoole\SwooleExtension;
use Swoole\Coroutine;
use Swoole\Http\Response;
Expand Down Expand Up @@ -60,6 +61,7 @@ public function __invoke()
error_log("⏱️ Request timeout (client gone): Coroutine #{$coroutineId} ran {$age}s of {$this->maxExecutionTime}s budget on worker {$row['worker_pid']}; fd {$row['fd']} already closed");

$this->cancelCoroutine($coroutineId);
$this->resetLivewireMutex();

continue;
}
Expand All @@ -68,6 +70,7 @@ public function __invoke()
error_log("⏱️ Request timeout: Coroutine #{$coroutineId} ran {$age}s, exceeded {$this->maxExecutionTime}s max execution time (worker {$row['worker_pid']}, fd {$row['fd']})");

$cancelled = $this->cancelCoroutine($coroutineId);
$this->resetLivewireMutex();

if (!$cancelled) {
// If coroutine cancellation failed, ask Swoole to recycle the
Expand Down Expand Up @@ -135,6 +138,15 @@ protected function cancelCoroutine(int $coroutineId): bool
}
}

protected function resetLivewireMutex(): void
{
try {
(new LivewireCoroutineMutex)->forceReset();
} catch (\Throwable $e) {
error_log('⚠️ Failed to reset LivewireCoroutineMutex: '.$e->getMessage());
}
}

public static function normalizeFallbackSignal(int|string|null $signal): int
{
if (is_int($signal)) {
Expand Down
35 changes: 34 additions & 1 deletion src/Swoole/Coroutine/LivewireCoroutineMutex.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ class LivewireCoroutineMutex
{
private const DEPTH_KEY = 'octane.livewire_mutex_depth';

/**
* Seconds to wait for the Livewire render lock before healing a stuck channel.
*
* A cancelled/timed-out coroutine can skip finally blocks and leave the
* channel empty, which otherwise deadlocks every later Livewire request
* on this worker (including file-upload updates).
*/
private const ACQUIRE_TIMEOUT_SECONDS = 30.0;

private static $channel = null;

public function acquire(): void
Expand All @@ -24,7 +33,13 @@ public function acquire(): void
return;
}

$this->channel()->pop();
$token = $this->channel()->pop(self::ACQUIRE_TIMEOUT_SECONDS);

if ($token === false) {
error_log('⚠️ LivewireCoroutineMutex acquire timed out after '.self::ACQUIRE_TIMEOUT_SECONDS.'s; resetting lock to unblock Livewire');
$this->forceReset();
$this->channel()->pop(0.01);
}

Context::set(self::DEPTH_KEY, 1);
}
Expand Down Expand Up @@ -63,6 +78,24 @@ public function releaseAllForCurrentCoroutine(): void
}
}

/**
* Re-seed the lock after a cancelled coroutine may have leaked it.
*/
public function forceReset(): void
{
if (! class_exists(Channel::class)) {
return;
}

$channel = $this->channel();

while ($channel->pop(0.001) !== false) {
// Drain any residual tokens before re-seeding.
}

$channel->push(true);
}

/**
* @template TValue
*
Expand Down
Loading