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
8 changes: 8 additions & 0 deletions bin/WorkerState.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,12 @@ class WorkerState
public $lastRequestTime;

public $ready = false;

public int $handledRequests = 0;

public int $maxRequests = 0;

public bool $recycleRequested = false;

public bool $recycleTriggered = false;
}
3 changes: 3 additions & 0 deletions bin/swoole-server
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use Laravel\Octane\Swoole\Handlers\OnWorkerStop;
use Laravel\Octane\Swoole\ServerStateFile;
use Laravel\Octane\Swoole\SwooleExtension;
use Laravel\Octane\Swoole\WorkerState;
use Laravel\Octane\Swoole\Actions\StopWorkerIfMaxRequestsExceeded;
use Laravel\Octane\Swoole\Coroutine\Context;
use Laravel\Octane\Swoole\Coroutine\Monitor;
use Swoole\Coroutine;
Expand Down Expand Up @@ -195,6 +196,8 @@ $server->on('request', function ($request, $response) use ($server, $workerState

Monitor::unregisterRequestCoroutine($cid);

(new StopWorkerIfMaxRequestsExceeded($server, $workerState))();

// Ensure coroutine context is cleared (Swoole does this automatically, but explicit is safe)
Context::clear();
}
Expand Down
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@
"spiral/roadrunner-http": "<3.3.0"
},
"autoload": {
"classmap": [
"bin/WorkerState.php"
],
"psr-4": {
"Laravel\\Octane\\": "src"
}
Expand Down
22 changes: 16 additions & 6 deletions 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 All @@ -156,11 +156,14 @@ protected function defaultServerOptions(SwooleExtension $extension)
// Log level: INFO in local, ERROR in production for better performance
'log_level' => app()->environment('local') ? SWOOLE_LOG_INFO : SWOOLE_LOG_ERROR,

// Max requests per worker before restart (prevents memory leaks)
'max_request' => $this->option('max-requests'),

// Randomize worker recycling so all busy workers do not restart together.
'max_request_grace' => $this->maxRequestGrace(),
// Disable Swoole's built-in HTTP worker recycling. In coroutine
// mode it can close an upstream request while Nginx is still
// reading the response. The bin/swoole-server request loop applies
// the same max-requests limit cooperatively after response cleanup.
'max_request' => 0,

// Randomization is applied by the cooperative recycler.
'max_request_grace' => 0,

// Max size of request/response package (10MB)
'package_max_length' => 10 * 1024 * 1024,
Expand Down Expand Up @@ -205,6 +208,13 @@ protected function defaultServerOptions(SwooleExtension $extension)
// Number of worker processes
'worker_num' => $this->workerCount($extension),
], config('octane.swoole.options', []));

// Keep HTTP worker recycling under the cooperative request-loop guard
// even when applications publish custom low-level Swoole options.
$options['max_request'] = 0;
$options['max_request_grace'] = 0;

return $options;
}

/**
Expand Down
60 changes: 60 additions & 0 deletions src/Swoole/Actions/StopWorkerIfMaxRequestsExceeded.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace Laravel\Octane\Swoole\Actions;

use Laravel\Octane\Swoole\Coroutine\Monitor;
use Laravel\Octane\Swoole\WorkerState;
use Throwable;

class StopWorkerIfMaxRequestsExceeded
{
public function __construct(
protected mixed $server,
protected WorkerState $workerState
) {
}

public function __invoke(): bool
{
if ($this->workerState->maxRequests <= 0 || $this->workerState->recycleTriggered) {
return false;
}

$this->workerState->handledRequests++;

if ($this->workerState->handledRequests >= $this->workerState->maxRequests) {
$this->workerState->recycleRequested = true;
}

if (! $this->workerState->recycleRequested || Monitor::getActiveRequestCount() > 0) {
return false;
}

$this->workerState->recycleTriggered = true;

try {
$stopped = $this->server->stop($this->workerState->workerId);
} catch (Throwable $e) {
$this->workerState->recycleTriggered = false;

error_log("⚠️ Failed to recycle worker #{$this->workerState->workerId}: {$e->getMessage()}");

return false;
}

if ($stopped === false) {
$this->workerState->recycleTriggered = false;

error_log("⚠️ Swoole refused to recycle worker #{$this->workerState->workerId}");

return false;
}

error_log(
"♻️ WORKER #{$this->workerState->workerId} recycling after ".
"{$this->workerState->handledRequests}/{$this->workerState->maxRequests} handled requests"
);

return true;
}
}
22 changes: 22 additions & 0 deletions src/Swoole/Handlers/OnWorkerStart.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public function __invoke($server, int $workerId)
$this->workerState->server = $server;
$this->workerState->workerId = $workerId;
$this->workerState->workerPid = posix_getpid();
$this->configureCooperativeMaxRequests($server, $workerId);
$this->workerState->worker = $this->bootWorker($server, $workerId);

$this->dispatchServerTickTaskEverySecond($server);
Expand All @@ -74,6 +75,27 @@ public function __invoke($server, int $workerId)
error_log("✅ {$workerType} #{$workerId} (PID: {$this->workerState->workerPid}) initialized and ready!");
}

protected function configureCooperativeMaxRequests($server, int $workerId): void
{
$workerNum = $server->setting['worker_num'] ?? 1;

if ($workerId >= $workerNum) {
return;
}

$maxRequests = max(0, (int) ($this->serverState['maxRequests'] ?? 0));
$maxRequestGrace = max(0, (int) ($this->serverState['maxRequestGrace'] ?? 0));

if ($maxRequests > 0 && $maxRequestGrace > 0) {
$maxRequests += random_int(0, $maxRequestGrace);
}

$this->workerState->handledRequests = 0;
$this->workerState->maxRequests = $maxRequests;
$this->workerState->recycleRequested = false;
$this->workerState->recycleTriggered = false;
}

/**
* Boot the Octane worker and application.
*
Expand Down
Loading
Loading