diff --git a/README.md b/README.md index ae7bc7f..6e8669a 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/bin/bootstrap.php b/bin/bootstrap.php index d3517d9..a643c93 100644 --- a/bin/bootstrap.php +++ b/bin/bootstrap.php @@ -4,8 +4,6 @@ $_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 @@ -13,8 +11,6 @@ 'max_coroutine' => 100000, ]); -Runtime::enableCoroutine(SWOOLE_HOOK_ALL); - /* |-------------------------------------------------------------------------- | Find Application Base Path @@ -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; diff --git a/config/octane.php b/config/octane.php index 2b503f1..89e6a63 100644 --- a/config/octane.php +++ b/config/octane.php @@ -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), /* |-------------------------------------------------------------------------- diff --git a/src/Commands/StartSwooleCommand.php b/src/Commands/StartSwooleCommand.php index ea47ea2..ff9c828 100644 --- a/src/Commands/StartSwooleCommand.php +++ b/src/Commands/StartSwooleCommand.php @@ -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, @@ -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; } /** diff --git a/src/Concerns/ProvidesDefaultConfigurationOptions.php b/src/Concerns/ProvidesDefaultConfigurationOptions.php index b9c3acd..7f9df99 100644 --- a/src/Concerns/ProvidesDefaultConfigurationOptions.php +++ b/src/Concerns/ProvidesDefaultConfigurationOptions.php @@ -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, diff --git a/src/Listeners/GiveNewRequestInstanceToApplication.php b/src/Listeners/GiveNewRequestInstanceToApplication.php index 395b745..3b2071d 100644 --- a/src/Listeners/GiveNewRequestInstanceToApplication.php +++ b/src/Listeners/GiveNewRequestInstanceToApplication.php @@ -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 { @@ -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; } diff --git a/src/Listeners/PrepareBladeComponentsForNextOperation.php b/src/Listeners/PrepareBladeComponentsForNextOperation.php new file mode 100644 index 0000000..44358fc --- /dev/null +++ b/src/Listeners/PrepareBladeComponentsForNextOperation.php @@ -0,0 +1,33 @@ +sandbox->bound('view')) { + return; + } + + $event->sandbox->make('view')->addNamespace( + '__components', + $event->sandbox->make('config')->get('view.compiled'), + ); + } +} diff --git a/src/Swoole/Actions/EnsureRequestsDontExceedMaxExecutionTime.php b/src/Swoole/Actions/EnsureRequestsDontExceedMaxExecutionTime.php index f084876..aa1c228 100644 --- a/src/Swoole/Actions/EnsureRequestsDontExceedMaxExecutionTime.php +++ b/src/Swoole/Actions/EnsureRequestsDontExceedMaxExecutionTime.php @@ -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; @@ -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; } @@ -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 @@ -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)) { diff --git a/src/Swoole/Coroutine/LivewireCoroutineMutex.php b/src/Swoole/Coroutine/LivewireCoroutineMutex.php index 880317e..bb9f340 100644 --- a/src/Swoole/Coroutine/LivewireCoroutineMutex.php +++ b/src/Swoole/Coroutine/LivewireCoroutineMutex.php @@ -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 @@ -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); } @@ -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 * diff --git a/src/Swoole/Coroutine/RequestScope.php b/src/Swoole/Coroutine/RequestScope.php index 50cb3b5..3957c21 100644 --- a/src/Swoole/Coroutine/RequestScope.php +++ b/src/Swoole/Coroutine/RequestScope.php @@ -345,6 +345,14 @@ protected function resolveSpecializedBinding(string $key, Application $sandbox) return $this->createSentryTracingMiddleware(); } + if ($this->isStanclTenantContractBinding($key)) { + return $this->resolveStanclTenant($sandbox); + } + + if ($this->isStanclTenancyBinding($key)) { + return $this->createTenancy($sandbox); + } + return match ($key) { 'auth' => $this->createAuthManager($sandbox), \Illuminate\Bus\Dispatcher::class => $this->createBusDispatcher($sandbox), @@ -356,10 +364,12 @@ protected function resolveSpecializedBinding(string $key, Application $sandbox) 'cookie' => $this->createCookieJar(), 'db.transactions' => new DatabaseTransactionsManager, DeferredCallbackCollection::class => new DeferredCallbackCollection, + 'events', EventDispatcher::class, \Illuminate\Events\Dispatcher::class => $this->createEventDispatcher($sandbox), 'gate', \Illuminate\Contracts\Auth\Access\Gate::class, \Illuminate\Auth\Access\Gate::class => $this->createGate($sandbox), 'filesystem', FilesystemManager::class, \Illuminate\Contracts\Filesystem\Factory::class => $this->createFilesystemManager($sandbox), 'filesystem.disk', \Illuminate\Contracts\Filesystem\Filesystem::class => $this->createFilesystemDisk($sandbox), 'filesystem.cloud', \Illuminate\Contracts\Filesystem\Cloud::class => $this->createFilesystemCloud($sandbox), + \Illuminate\Log\Context\Repository::class => $this->createLogContextRepository($sandbox), \Inertia\ResponseFactory::class => $this->createInertiaResponseFactory(), 'log', \Psr\Log\LoggerInterface::class => $this->createLogManager($sandbox), 'queue', QueueManager::class, \Illuminate\Contracts\Queue\Factory::class, \Illuminate\Contracts\Queue\Monitor::class => $this->createQueueManager($sandbox), @@ -375,13 +385,156 @@ protected function resolveSpecializedBinding(string $key, Application $sandbox) 'url' => $this->createUrlGenerator($sandbox), \Illuminate\Foundation\Vite::class => $this->createVite(), 'view', \Illuminate\Contracts\View\Factory::class => $this->createViewFactory($sandbox), - \Illuminate\Routing\Contracts\CallableDispatcher::class => new \Illuminate\Routing\CallableDispatcher($sandbox), - \Illuminate\Routing\Contracts\ControllerDispatcher::class => new \Illuminate\Routing\ControllerDispatcher($sandbox), + 'themes.finder' => $this->createThemesFinder($sandbox), + \Illuminate\Routing\Contracts\CallableDispatcher::class => $this->createCallableDispatcher($sandbox), + \Illuminate\Routing\Contracts\ControllerDispatcher::class => $this->createControllerDispatcher($sandbox), \Illuminate\Contracts\Routing\ResponseFactory::class => $this->createResponseFactory($sandbox), default => null, }; } + /** + * Create a fresh Laravel Context repository for this coroutine. + * + * Context is registered as scoped on the worker app; without a per-request + * instance, tenant_id (and other keys) leak across concurrent coroutines. + * + * @param \Illuminate\Foundation\Application $sandbox + * @return \Illuminate\Log\Context\Repository + */ + protected function createLogContextRepository(Application $sandbox): \Illuminate\Log\Context\Repository + { + return new \Illuminate\Log\Context\Repository( + $sandbox->make(EventDispatcher::class) + ); + } + + /** + * Create an isolated Stancl Tenancy manager for this coroutine. + * + * @param \Illuminate\Foundation\Application $sandbox + * @return mixed + */ + protected function createTenancy(Application $sandbox) + { + $tenancy = clone $this->app->make(\Stancl\Tenancy\Tenancy::class); + $tenancy->initialized = false; + $tenancy->tenant = null; + + return $tenancy; + } + + /** + * Resolve Stancl's Tenant contract from the coroutine-local Tenancy manager. + * + * The framework bind is `fn ($app) => $app[Tenancy::class]->tenant`. When that + * closure runs against the worker base container it reads the shared Tenancy + * singleton (usually null), while `tenancy()` already returns the RequestScope + * clone — so `tenancy()->initialized` is true but `tenant()` is null and queue + * payload hooks call getTenantKey() on null during deferred dispatch. + * + * @param \Illuminate\Foundation\Application $sandbox + * @return mixed + */ + protected function resolveStanclTenant(Application $sandbox) + { + return $sandbox->make(\Stancl\Tenancy\Tenancy::class)->tenant; + } + + /** + * Determine if the binding is Stancl's Tenant contract. + */ + protected function isStanclTenantContractBinding(string $key): bool + { + return interface_exists(\Stancl\Tenancy\Contracts\Tenant::class) + && $key === \Stancl\Tenancy\Contracts\Tenant::class + && $this->app->bound(\Stancl\Tenancy\Tenancy::class); + } + + /** + * Determine if the binding is Stancl's Tenancy manager. + */ + protected function isStanclTenancyBinding(string $key): bool + { + return class_exists(\Stancl\Tenancy\Tenancy::class) + && ($key === 'tenancy' || $key === \Stancl\Tenancy\Tenancy::class) + && $this->app->bound(\Stancl\Tenancy\Tenancy::class); + } + + /** + * Create a controller dispatcher for the coroutine sandbox. + * + * Honor the base application's ControllerDispatcher binding (e.g. Bright's + * dispatcher that wraps array controller returns in Themes Responsable). + * Hard-coding Laravel's stock dispatcher skips that pipeline and turns + * views like /login into blank JSON `[]` under enable_coroutine. + * + * @param \Illuminate\Foundation\Application $sandbox + * @return \Illuminate\Routing\Contracts\ControllerDispatcher + */ + protected function createControllerDispatcher(Application $sandbox): \Illuminate\Routing\Contracts\ControllerDispatcher + { + $class = $this->resolveBoundConcreteClass( + \Illuminate\Routing\Contracts\ControllerDispatcher::class, + \Illuminate\Routing\ControllerDispatcher::class, + ); + + return new $class($sandbox); + } + + /** + * Create a callable dispatcher for the coroutine sandbox. + * + * @param \Illuminate\Foundation\Application $sandbox + * @return \Illuminate\Routing\Contracts\CallableDispatcher + */ + protected function createCallableDispatcher(Application $sandbox): \Illuminate\Routing\Contracts\CallableDispatcher + { + $class = $this->resolveBoundConcreteClass( + \Illuminate\Routing\Contracts\CallableDispatcher::class, + \Illuminate\Routing\CallableDispatcher::class, + ); + + return new $class($sandbox); + } + + /** + * Resolve a concrete class from the base container binding. + * + * Laravel stores class-string binds as Closures in getBindings(), so we + * may need to instantiate once on the base app to discover the class, then + * construct a fresh instance with the coroutine sandbox. + * + * @param class-string $abstract + * @param class-string $default + * @return class-string + */ + protected function resolveBoundConcreteClass(string $abstract, string $default): string + { + if (! $this->app->bound($abstract)) { + return $default; + } + + $binding = $this->app->getBindings()[$abstract] ?? null; + $concrete = is_array($binding) ? ($binding['concrete'] ?? null) : null; + + if (is_string($concrete) && class_exists($concrete)) { + return $concrete; + } + + try { + $resolved = $this->app->make($abstract); + + if (is_object($resolved)) { + return $resolved::class; + } + } catch (\Throwable) { + // Fall back to the Laravel default dispatcher. + } + + return $default; + } + /** * Determine if the binding is Lab404's impersonation manager. * @@ -723,6 +876,11 @@ protected function rememberAliasBindings(string $key, $resolved): void 'queue.connection', \Illuminate\Contracts\Queue\Queue::class, ], $resolved), + 'tenancy', + 'Stancl\\Tenancy\\Tenancy' => $this->storeScopedAliases([ + 'tenancy', + \Stancl\Tenancy\Tenancy::class, + ], $resolved), default => null, }; } @@ -943,6 +1101,26 @@ protected function cloneConfig() return clone $this->app->make('config'); } + /** + * Create an isolated event dispatcher bound to the coroutine sandbox. + * + * Class listeners are resolved through the dispatcher's container. Leaving + * that on the worker base app makes constructor-injected Request resolve + * outside RequestScope — so StartSession's store never appears on the + * request and login listeners throw "Session store not set on request." + * + * @param \Illuminate\Foundation\Application $sandbox + * @return \Illuminate\Contracts\Events\Dispatcher + */ + protected function createEventDispatcher(Application $sandbox): EventDispatcher + { + $events = clone $this->app->make('events'); + + $this->setObjectProperty($events, 'container', $sandbox); + + return $events; + } + /** * Create an isolated auth manager bound to the coroutine sandbox. * @@ -1522,6 +1700,7 @@ protected function createViewFactory(Application $sandbox): \Illuminate\Contract { /** @var \Illuminate\View\Factory $view */ $view = clone $this->app->make('view'); + $view->setFinder(clone $view->getFinder()); $view->setContainer($sandbox); $view->share('__env', $view); $view->share('app', $sandbox); @@ -1530,6 +1709,20 @@ protected function createViewFactory(Application $sandbox): \Illuminate\Contract return $view; } + /** + * Resolve the theme view finder for the current coroutine. + * + * Diviky registers themes.finder as a worker singleton and assigns it to the + * view factory. Livewire components temporarily prepend colocated view paths + * (for example analytics "sent") via that finder. Without a per-coroutine + * finder, concurrent requests flush or reset paths and trigger random + * "View [sent] not found" errors under Swoole coroutines. + */ + protected function createThemesFinder(Application $sandbox): \Illuminate\View\ViewFinderInterface + { + return $sandbox->make(\Illuminate\Contracts\View\Factory::class)->getFinder(); + } + /** * Create an isolated log manager for the current coroutine. * diff --git a/src/Swoole/Coroutine/RuntimeHooks.php b/src/Swoole/Coroutine/RuntimeHooks.php new file mode 100644 index 0000000..77a26ed --- /dev/null +++ b/src/Swoole/Coroutine/RuntimeHooks.php @@ -0,0 +1,56 @@ + $swooleConfig + */ + public static function enable(array $swooleConfig = []): void + { + if (! \extension_loaded('swoole') || ! \class_exists(\Swoole\Runtime::class)) { + return; + } + + // When the Swoole server runs without request coroutines, arming hooks + // is unnecessary for uploads and can interact badly with blocking I/O. + $options = is_array($swooleConfig['options'] ?? null) ? $swooleConfig['options'] : []; + if (array_key_exists('enable_coroutine', $options) && ! $options['enable_coroutine']) { + return; + } + + \Swoole\Runtime::enableCoroutine(static::flags($swooleConfig)); + } + + /** + * @param array $swooleConfig + */ + public static function flags(array $swooleConfig = []): int + { + if (isset($swooleConfig['hook_flags']) && is_int($swooleConfig['hook_flags'])) { + return $swooleConfig['hook_flags']; + } + + $flags = \defined('SWOOLE_HOOK_ALL') ? SWOOLE_HOOK_ALL : 0; + + if (! ($swooleConfig['hook_file'] ?? false) && \defined('SWOOLE_HOOK_FILE')) { + $flags &= ~SWOOLE_HOOK_FILE; + } + + if (! ($swooleConfig['hook_stdio'] ?? false) && \defined('SWOOLE_HOOK_STDIO')) { + $flags &= ~SWOOLE_HOOK_STDIO; + } + + return $flags; + } +} diff --git a/src/Swoole/Coroutine/WorkerRequestBinding.php b/src/Swoole/Coroutine/WorkerRequestBinding.php new file mode 100644 index 0000000..5169254 --- /dev/null +++ b/src/Swoole/Coroutine/WorkerRequestBinding.php @@ -0,0 +1,59 @@ + + */ + protected static array $abstracts = [ + 'request', + Request::class, + SymfonyRequest::class, + ]; + + /** + * Install (or refresh) the Context-aware request factory on the worker app. + */ + public static function install(Application $app): void + { + foreach (static::$abstracts as $abstract) { + if (method_exists($app, 'forgetInstance')) { + $app->forgetInstance($abstract); + } + } + + $resolver = static function () { + $scope = Context::get('octane.request_scope'); + + if ($scope instanceof RequestScope && $scope->has('request')) { + return $scope->get('request'); + } + + throw new RuntimeException( + 'Coroutine request is not available on the worker container.' + ); + }; + + $app->bind('request', $resolver); + + // Ensure class type-hints resolve through the same factory even when + // aliases were wiped by a prior instance() call on the worker app. + $app->alias('request', Request::class); + $app->alias('request', SymfonyRequest::class); + } +} diff --git a/src/Swoole/Handlers/OnWorkerStart.php b/src/Swoole/Handlers/OnWorkerStart.php index 156fdd7..3ee9d29 100644 --- a/src/Swoole/Handlers/OnWorkerStart.php +++ b/src/Swoole/Handlers/OnWorkerStart.php @@ -16,6 +16,7 @@ use Swoole\Http\Server; use Throwable; use Laravel\Octane\Swoole\Coroutine\CoroutineApplication; +use Laravel\Octane\Swoole\Coroutine\RuntimeHooks; use Illuminate\Container\Container; use Illuminate\Support\Facades\Facade; @@ -47,8 +48,12 @@ public function __invoke($server, int $workerId) $workerType = $isTaskWorker ? 'TASK WORKER' : 'WORKER'; error_log("🚀 {$workerType} #{$workerId} STARTING (max_request: {$maxRequest}, reload_async: {$reloadAsync})"); - // Enable coroutine hooks to make blocking functions (sleep, file_get_contents, etc.) coroutine-safe - \Swoole\Runtime::enableCoroutine(SWOOLE_HOOK_ALL); + // Enable coroutine hooks (FILE/STDIO excluded by default — see RuntimeHooks) + $swooleConfig = is_array($this->serverState['octaneConfig']['swoole'] ?? null) + ? $this->serverState['octaneConfig']['swoole'] + : []; + + RuntimeHooks::enable($swooleConfig); if ($this->shouldClearOpcodeCache()) { $this->clearOpcodeCache(); diff --git a/tests/Unit/LivewireCoroutineMutexTest.php b/tests/Unit/LivewireCoroutineMutexTest.php index 47249ab..c230598 100644 --- a/tests/Unit/LivewireCoroutineMutexTest.php +++ b/tests/Unit/LivewireCoroutineMutexTest.php @@ -91,4 +91,34 @@ public function test_it_is_reentrant_within_a_coroutine(): void $this->assertTrue($completed); } + + public function test_force_reset_unblocks_a_leaked_lock(): void + { + if (! extension_loaded('swoole') || ! class_exists(Channel::class)) { + $this->markTestSkipped('Swoole is required for coroutine mutex tests.'); + } + + $acquiredAfterReset = false; + + \Swoole\Coroutine\run(function () use (&$acquiredAfterReset): void { + $mutex = new LivewireCoroutineMutex; + + Context::clear(); + $mutex->acquire(); + + // Simulate a cancelled coroutine leaking the lock without release. + Context::clear(); + + $mutex->forceReset(); + + Context::clear(); + $mutex->acquire(); + $acquiredAfterReset = true; + $mutex->release(); + + Context::clear(); + }); + + $this->assertTrue($acquiredAfterReset); + } } diff --git a/tests/Unit/PrepareBladeComponentsForNextOperationTest.php b/tests/Unit/PrepareBladeComponentsForNextOperationTest.php new file mode 100644 index 0000000..defcdb3 --- /dev/null +++ b/tests/Unit/PrepareBladeComponentsForNextOperationTest.php @@ -0,0 +1,54 @@ +assertContains( + PrepareBladeComponentsForNextOperation::class, + Octane::prepareApplicationForNextOperation(), + ); + } + + public function test_registers_the_components_view_namespace_on_the_sandbox(): void + { + $listener = new PrepareBladeComponentsForNextOperation; + + $listener->handle((object) ['sandbox' => $this->app]); + + $finder = $this->app->make('view')->getFinder(); + $this->assertInstanceOf(FileViewFinder::class, $finder); + + $reflection = new ReflectionClass($finder); + $hints = $reflection->getProperty('hints'); + $hints->setAccessible(true); + + $this->assertArrayHasKey('__components', $hints->getValue($finder)); + $this->assertSame( + [config('view.compiled')], + $hints->getValue($finder)['__components'], + ); + } + + public function test_flushes_blade_component_static_cache_between_operations(): void + { + $reflection = new ReflectionClass(Component::class); + $cache = $reflection->getProperty('bladeViewCache'); + $cache->setAccessible(true); + $cache->setValue(null, ['test::cache' => '__components::cached']); + + $listener = new PrepareBladeComponentsForNextOperation; + $listener->handle((object) ['sandbox' => $this->app]); + + $this->assertSame([], $cache->getValue()); + } +} diff --git a/tests/Unit/RequestScopeControllerDispatcherIsolationTest.php b/tests/Unit/RequestScopeControllerDispatcherIsolationTest.php new file mode 100644 index 0000000..5e2909d --- /dev/null +++ b/tests/Unit/RequestScopeControllerDispatcherIsolationTest.php @@ -0,0 +1,47 @@ +bind(ControllerDispatcher::class, CustomControllerDispatcher::class); + + $sandbox = new Application; + $scope = new RequestScope($base, Request::create('/login', 'GET')); + + $dispatcher = $scope->resolve(ControllerDispatcher::class, $sandbox); + + $this->assertInstanceOf(CustomControllerDispatcher::class, $dispatcher); + } + + public function test_it_falls_back_to_laravel_controller_dispatcher(): void + { + $base = new Application; + $sandbox = new Application; + $scope = new RequestScope($base, Request::create('/login', 'GET')); + + $dispatcher = $scope->resolve(ControllerDispatcher::class, $sandbox); + + $this->assertInstanceOf(LaravelControllerDispatcher::class, $dispatcher); + $this->assertNotInstanceOf(CustomControllerDispatcher::class, $dispatcher); + } + } +} diff --git a/tests/Unit/RequestScopeEventDispatcherIsolationTest.php b/tests/Unit/RequestScopeEventDispatcherIsolationTest.php new file mode 100644 index 0000000..9713371 --- /dev/null +++ b/tests/Unit/RequestScopeEventDispatcherIsolationTest.php @@ -0,0 +1,107 @@ +instance('events', new Dispatcher($base)); + + $request = Request::create('/login', 'POST'); + $request->setLaravelSession($this->arraySession()); + + $scope = new RequestScope($base, $request); + $sandbox = new CoroutineApplication($base); + + Context::set('octane.request_scope', $scope); + + try { + $events = $sandbox->make('events'); + + $this->assertInstanceOf(Dispatcher::class, $events); + $this->assertNotSame($base->make('events'), $events); + $this->assertSame($sandbox, $this->readProperty($events, 'container')); + + $resolved = $sandbox->make(Request::class); + $this->assertSame($request, $resolved); + $this->assertTrue($resolved->hasSession()); + $this->assertSame($request->session(), $resolved->session()); + + $this->assertSame($events, $sandbox->make(EventDispatcherContract::class)); + } finally { + Context::clear(); + } + } + + private function arraySession(): Store + { + $handler = new class implements SessionHandlerInterface + { + private array $data = []; + + public function open(string $path, string $name): bool + { + return true; + } + + public function close(): bool + { + return true; + } + + public function read(string $id): string|false + { + return $this->data[$id] ?? ''; + } + + public function write(string $id, string $data): bool + { + $this->data[$id] = $data; + + return true; + } + + public function destroy(string $id): bool + { + unset($this->data[$id]); + + return true; + } + + public function gc(int $max_lifetime): int|false + { + return 0; + } + }; + + return new Store('test', $handler); + } + + private function readProperty(object $object, string $property): mixed + { + $reflection = new ReflectionClass($object); + + while (! $reflection->hasProperty($property) && $reflection->getParentClass()) { + $reflection = $reflection->getParentClass(); + } + + $instanceProperty = $reflection->getProperty($property); + $instanceProperty->setAccessible(true); + + return $instanceProperty->getValue($object); + } +} diff --git a/tests/Unit/RequestScopeTenancyIsolationTest.php b/tests/Unit/RequestScopeTenancyIsolationTest.php new file mode 100644 index 0000000..9e6b417 --- /dev/null +++ b/tests/Unit/RequestScopeTenancyIsolationTest.php @@ -0,0 +1,79 @@ +markTestSkipped('stancl/tenancy is not installed.'); + } + } + + public function test_tenant_contract_reads_from_request_scoped_tenancy(): void + { + $base = new Application(__DIR__); + $baseTenancy = new Tenancy; + $base->singleton(Tenancy::class, fn () => $baseTenancy); + $base->bind(Tenant::class, fn ($app) => $app[Tenancy::class]->tenant); + + $sandbox = new CoroutineApplication($base); + $scope = new RequestScope($base, Request::create('/')); + Context::set('octane.request_scope', $scope); + + try { + $scopedTenancy = $sandbox->make(Tenancy::class); + $this->assertNotSame($baseTenancy, $scopedTenancy); + $this->assertFalse($scopedTenancy->initialized); + $this->assertNull($sandbox->make(Tenant::class)); + + $tenant = new class implements Tenant + { + public function getTenantKeyName(): string + { + return 'id'; + } + + public function getTenantKey() + { + return 7; + } + + public function getInternal(string $key) + { + return null; + } + + public function setInternal(string $key, $value) + { + return $this; + } + + public function run(callable $callback) + { + return $callback($this); + } + }; + + $scopedTenancy->tenant = $tenant; + $scopedTenancy->initialized = true; + + $this->assertSame($tenant, $sandbox->make(Tenant::class)); + $this->assertNull($baseTenancy->tenant); + } finally { + Context::clear(); + } + } +} diff --git a/tests/Unit/RequestScopeViewIsolationTest.php b/tests/Unit/RequestScopeViewIsolationTest.php index 61826e0..a67ba5a 100644 --- a/tests/Unit/RequestScopeViewIsolationTest.php +++ b/tests/Unit/RequestScopeViewIsolationTest.php @@ -7,6 +7,7 @@ use Illuminate\Foundation\Application; use Illuminate\View\Engines\EngineResolver; use Illuminate\View\Factory; +use Illuminate\View\FileViewFinder; use Illuminate\View\ViewFinderInterface; use Laravel\Octane\Swoole\Coroutine\Context; use Laravel\Octane\Swoole\Coroutine\CoroutineApplication; @@ -64,4 +65,53 @@ public function test_view_factory_shared_data_is_isolated_per_request_scope(): v Context::clear(); } } + + public function test_view_finder_paths_are_isolated_per_request_scope(): void + { + $base = new Application(__DIR__); + + $finder = new FileViewFinder( + new \Illuminate\Filesystem\Filesystem, + [__DIR__], + ); + + $view = new Factory( + new EngineResolver, + $finder, + new Dispatcher($base) + ); + $view->setContainer($base); + + $base->instance('view', $view); + $base->instance(ViewFactoryContract::class, $view); + + $sandbox = new CoroutineApplication($base); + + Context::set('octane.request_scope', new RequestScope($base)); + + try { + $firstFinder = $sandbox->make('view')->getFinder(); + $firstFinder->addLocation('/tmp/octane-coroutine-scope-alpha'); + + $this->assertContains('/tmp/octane-coroutine-scope-alpha', $firstFinder->getPaths()); + } finally { + Context::clear(); + } + + Context::set('octane.request_scope', new RequestScope($base)); + + try { + $secondFinder = $sandbox->make('view')->getFinder(); + $secondFinder->setPaths([__DIR__]); + + $this->assertSame([__DIR__], $secondFinder->getPaths()); + $this->assertNotContains('/tmp/octane-coroutine-scope-alpha', $secondFinder->getPaths()); + + $firstFinderAgain = $sandbox->make('view')->getFinder(); + $this->assertSame($secondFinder, $firstFinderAgain); + $this->assertNotContains('/tmp/octane-coroutine-scope-alpha', $firstFinderAgain->getPaths()); + } finally { + Context::clear(); + } + } } diff --git a/tests/Unit/RuntimeHooksTest.php b/tests/Unit/RuntimeHooksTest.php new file mode 100644 index 0000000..06bfa22 --- /dev/null +++ b/tests/Unit/RuntimeHooksTest.php @@ -0,0 +1,65 @@ +markTestSkipped('Swoole extension is required.'); + } + + $flags = RuntimeHooks::flags(); + + $this->assertSame(0, $flags & SWOOLE_HOOK_FILE); + + if (defined('SWOOLE_HOOK_STDIO')) { + $this->assertSame(0, $flags & SWOOLE_HOOK_STDIO); + } + + $this->assertNotSame(0, $flags); + $this->assertNotSame(SWOOLE_HOOK_ALL, $flags); + } + + public function test_hook_file_can_be_reenabled_via_config(): void + { + if (! extension_loaded('swoole') || ! defined('SWOOLE_HOOK_FILE')) { + $this->markTestSkipped('Swoole extension is required.'); + } + + $flags = RuntimeHooks::flags(['hook_file' => true]); + + $this->assertNotSame(0, $flags & SWOOLE_HOOK_FILE); + } + + public function test_explicit_hook_flags_override_defaults(): void + { + if (! extension_loaded('swoole') || ! defined('SWOOLE_HOOK_TCP')) { + $this->markTestSkipped('Swoole extension is required.'); + } + + $this->assertSame(SWOOLE_HOOK_TCP, RuntimeHooks::flags([ + 'hook_flags' => SWOOLE_HOOK_TCP, + 'hook_file' => true, + ])); + } + public function test_enable_skips_when_enable_coroutine_is_false(): void + { + if (! extension_loaded('swoole') || ! class_exists(\Swoole\Runtime::class)) { + $this->markTestSkipped('Swoole extension is required.'); + } + + \Swoole\Runtime::enableCoroutine(0); + \Laravel\Octane\Swoole\Coroutine\RuntimeHooks::enable([ + 'options' => ['enable_coroutine' => false], + 'hook_file' => true, + ]); + + $this->assertSame(0, \Swoole\Runtime::getHookFlags()); + } + +} diff --git a/tests/Unit/StartSwooleCommandOptionsTest.php b/tests/Unit/StartSwooleCommandOptionsTest.php index 3c38f15..323a0fa 100644 --- a/tests/Unit/StartSwooleCommandOptionsTest.php +++ b/tests/Unit/StartSwooleCommandOptionsTest.php @@ -38,6 +38,20 @@ public function test_swoole_options_default_to_ten_percent_max_request_grace(): $this->assertSame(10, $options['max_request_grace']); $this->assertSame(10, $options['task_max_request_grace']); } + + public function test_swoole_options_force_enable_coroutine_true(): void + { + config(['octane.swoole.options.enable_coroutine' => false]); + + $command = new TestableStartSwooleCommandForOptions([ + 'max-requests' => 100, + 'max-request-grace' => null, + ]); + + $options = $command->defaultServerOptionsForTest(new SwooleExtension()); + + $this->assertTrue($options['enable_coroutine']); + } } class TestableStartSwooleCommandForOptions extends StartSwooleCommand diff --git a/tests/Unit/WorkerRequestBindingTest.php b/tests/Unit/WorkerRequestBindingTest.php new file mode 100644 index 0000000..a4f3c8c --- /dev/null +++ b/tests/Unit/WorkerRequestBindingTest.php @@ -0,0 +1,151 @@ +markTestSkipped('Swoole is required for coroutine context.'); + } + + $base = new Application(__DIR__); + $base->instance('events', new Dispatcher($base)); + + $request = Request::create('/login', 'POST'); + $request->setLaravelSession($this->arraySession()); + + $ran = false; + + \Swoole\Coroutine\run(function () use ($base, $request, &$ran): void { + $scope = new RequestScope($base, $request); + Context::set('octane.request_scope', $scope); + + $sandbox = new CoroutineApplication($base); + Context::set('octane.app', $sandbox); + + $listener = new GiveNewRequestInstanceToApplication; + $listener->handle((object) [ + 'app' => $base, + 'sandbox' => $sandbox, + 'request' => $request, + ]); + + // Simulate Laravel resolving a listener via the worker/base container. + $resolved = $base->make(Request::class); + + $this->assertSame($request, $resolved); + $this->assertSame($request, $base->make('request')); + $this->assertSame($request, $base->make(SymfonyRequest::class)); + $this->assertTrue($resolved->hasSession()); + + $listenerInstance = $base->make(WorkerRequestBindingProbeListener::class); + $this->assertSame($request, $listenerInstance->request); + $this->assertTrue($listenerInstance->request->hasSession()); + + $ran = true; + + Context::clear(); + }); + + $this->assertTrue($ran); + } + + public function test_concurrent_coroutines_do_not_share_worker_request_instances(): void + { + if (! extension_loaded('swoole') || ! class_exists(\Swoole\Coroutine\Channel::class)) { + $this->markTestSkipped('Swoole is required for coroutine context.'); + } + + $base = new Application(__DIR__); + WorkerRequestBinding::install($base); + + $seen = []; + + \Swoole\Coroutine\run(function () use ($base, &$seen): void { + $channel = new \Swoole\Coroutine\Channel(2); + + foreach (['/one', '/two'] as $path) { + \Swoole\Coroutine::create(function () use ($base, $path, $channel): void { + $request = Request::create($path, 'GET'); + $scope = new RequestScope($base, $request); + Context::set('octane.request_scope', $scope); + + $channel->push($base->make(Request::class)->getPathInfo()); + + Context::clear(); + }); + } + + $seen[] = $channel->pop(); + $seen[] = $channel->pop(); + }); + + sort($seen); + + $this->assertSame(['/one', '/two'], $seen); + } + + private function arraySession(): Store + { + $handler = new class implements SessionHandlerInterface + { + private array $data = []; + + public function open(string $path, string $name): bool + { + return true; + } + + public function close(): bool + { + return true; + } + + public function read(string $id): string|false + { + return $this->data[$id] ?? ''; + } + + public function write(string $id, string $data): bool + { + $this->data[$id] = $data; + + return true; + } + + public function destroy(string $id): bool + { + unset($this->data[$id]); + + return true; + } + + public function gc(int $max_lifetime): int|false + { + return 0; + } + }; + + return new Store('test', $handler); + } +} + +class WorkerRequestBindingProbeListener +{ + public function __construct(public Request $request) {} +}