Alpha ZealPHP is early-stage and under active development. APIs may change between minor versions until v1.0. Feedback and bug reports welcome on GitHub.
API Index — Namespaces, Packages, Reports, Indices

WorkerPool
in package

FinalYes

Master-side pool manager for ZealPHP's native FCGI-style worker pool.

Spawns N persistent PHP subprocesses (via proc_open) at construction. Each subprocess loops on stdin frames — reads a request payload, runs the requested PHP file in its own clean global scope (mod_php-style isolation per request), writes a response frame, then yields. Auto- respawns any subprocess that dies (crash, exit(), OOM) or hits the recycle limit (FPM pm.max_requests parity).

Concurrency: idle subprocesses live in a Coroutine\Channel. Multiple coroutines on the parent OpenSwoole worker dispatch in parallel — each dispatch() call pops a worker from the channel (yields the coroutine if the channel is empty), writes the request frame, reads the response frame (pipe I/O yields under HOOK_ALL), and pushes the worker back to the channel. The parent worker handles thousands of concurrent dispatch coroutines while the subprocess pool executes legacy PHP synchronously.

That's the architectural shape: PHP HTTP server (OpenSwoole worker) + FPM-style isolation (subprocess pool) + async dispatch (coroutines).

Outside a coroutine context (tests, CLI tools), dispatch() falls back to a synchronous LIFO array — the same code path the spike used. This makes the test surface trivial: new WorkerPool() → $pool->dispatch() works without wrapping in Co::run().

Table of Contents

Constants

DIAG_CAP_BYTES  : mixed = 1024 * 1024
Most stray stdout / stderr kept per dispatch for the log; the rest is read and dropped.
PIPE_BUF  : mixed = 4096
Bytes per request-pipe write inside a coroutine (POSIX PIPE_BUF on Linux); see exchange().

Properties

$channelPopulated  : bool
true after the sync idle queue has been migrated into $idleChan on the first coroutine dispatch.
$closed  : bool
true after close() has been called; prevents double-close and guards dispatch().
$idleChan  : Channel|null
Coroutine idle queue. Created lazily — Channel push REQUIRES coroutine context, so we can't populate it at constructor time (parent worker boot is typically non-coroutine). First dispatch in a coroutine transfers the sync queue into the channel; from then on, all idle/busy transitions go through the channel for proper parallel-dispatch yield.
$idleSync  : array<int, int>
$maxRequestsPerWorker  : int
$size  : int
Total number of worker slots allocated at construction (immutable after __construct()).
$spawnFailed  : array<int, true>
Slots whose replacement subprocess could not be started. The slot stays in the pool (it used to be lost for good, shrinking the pool with every failed spawn) and is spawned again when next checked out.
$workerEntry  : string|null
$workers  : array<int, array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int}>
FD-3 IPC architecture: the subprocess writes the response metadata frame (status, headers, cookies, body_length, body_fd = 3) to fd 3 and the body bytes right after it on fd 3. App code cannot reach fd 3 by accident, so nothing it does can shift the framing.

Methods

__construct()  : mixed
Spawn $size worker subprocesses immediately. All workers are ready (READY signal received) before the constructor returns.
__destruct()  : mixed
close()  : void
Shut down all workers cleanly (close pipes, wait for exit).
dispatch()  : array<string, mixed>
Dispatch one request to an idle worker and return the response frame.
filterSubprocessEnv()  : array<string, string>
Build the environment handed to a pool subprocess.
servedCounts()  : array<int, int>
Per-worker served counter (for tests / observability / /healthz).
size()  : int
How many workers are alive right now.
ensureChannelPopulated()  : void
One-time promotion of the sync idle queue into a Coroutine\Channel.
exchange()  : array<string|int, mixed>
Run one request/response exchange with a subprocess over non-blocking pipes: write $frame to stdin, read the response from fd 3, and drain stdout + stderr throughout so the child can never block on a full pipe.
hasUnsolicitedBytes()  : bool
True when the subprocess has written to fd 3 while no request was in flight. Never blocks: fd 3 is non-blocking.
isAlive()  : bool
logProtocolError()  : void
Log a broken exchange; the caller replaces the subprocess.
logSubprocessOutput()  : void
Send a subprocess's stray stdout / stderr to the framework log. Never to the client: under FPM and mod_php, php://stdout is not the response.
parseFrame()  : array<string|int, mixed>|false|null
Decode one complete length-prefixed frame from the front of $buf.
popIdleWorker()  : int|null
Pop an idle worker index. In a coroutine, lazy-promotes the queue to a Coroutine\Channel (first call) and yields on it until a worker is freed or the timeout expires. Outside a coroutine, uses the synchronous LIFO — no yield, returns null if empty.
reap()  : void
Close every pipe of the subprocess at $idx and wait for it to exit.
reapAndSpawn()  : void
Reap the slot's subprocess (unless already reaped) and start a new one; never throws.
replace()  : void
Kill the subprocess at $idx (it is not trusted to exit by itself, and whatever it still writes must not reach anyone) and put a fresh one in its slot. Unlike respawn(), the slot is NOT returned to the idle pool: the caller is still holding it.
respawn()  : void
Close all pipes for the worker at $idx, reap the subprocess via proc_close(), spawn a fresh replacement, and immediately return it to the idle pool. Called when a worker dies mid-request, hits its $maxRequestsPerWorker limit, or sends the _exit flag in its IPC frame.
returnToIdle()  : void
Return a worker to the idle pool. Routes to the channel (in coroutine context, once promoted) so any coroutine waiting on pop wakes up; otherwise pushes to the sync LIFO.
spawn()  : array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int}

Constants

DIAG_CAP_BYTES

Most stray stdout / stderr kept per dispatch for the log; the rest is read and dropped.

private mixed DIAG_CAP_BYTES = 1024 * 1024

PIPE_BUF

Bytes per request-pipe write inside a coroutine (POSIX PIPE_BUF on Linux); see exchange().

private mixed PIPE_BUF = 4096

Properties

$channelPopulated

true after the sync idle queue has been migrated into $idleChan on the first coroutine dispatch.

private bool $channelPopulated = false

$closed

true after close() has been called; prevents double-close and guards dispatch().

private bool $closed = false

$idleChan

Coroutine idle queue. Created lazily — Channel push REQUIRES coroutine context, so we can't populate it at constructor time (parent worker boot is typically non-coroutine). First dispatch in a coroutine transfers the sync queue into the channel; from then on, all idle/busy transitions go through the channel for proper parallel-dispatch yield.

private Channel|null $idleChan = null

$idleSync

private array<int, int> $idleSync = []

Idle worker indices — primary queue at boot + the fallback when no coroutine context.

$maxRequestsPerWorker read-only

private int $maxRequestsPerWorker = 500

$size read-only

Total number of worker slots allocated at construction (immutable after __construct()).

private int $size

$spawnFailed

Slots whose replacement subprocess could not be started. The slot stays in the pool (it used to be lost for good, shrinking the pool with every failed spawn) and is spawned again when next checked out.

private array<int, true> $spawnFailed = []

$workerEntry read-only

private string|null $workerEntry = null

$workers

FD-3 IPC architecture: the subprocess writes the response metadata frame (status, headers, cookies, body_length, body_fd = 3) to fd 3 and the body bytes right after it on fd 3. App code cannot reach fd 3 by accident, so nothing it does can shift the framing.

private array<int, array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int}> $workers = []

The metadata channel uses a destructor on a static class instance — PHP runs destructors EVEN AFTER exit() from inside a shutdown function (phpMyAdmin's ResponseRenderer->response() does exactly this). Routing metadata through fd 3 gives us a guaranteed delivery path for status/headers regardless of how the app terminates.

STDOUT is NOT the body. It used to be (only the length was framed), and any direct write to fd 1 (fwrite(STDOUT), a php://stdout logger, a destructor echo after output buffering closed) then leaked into the NEXT request's response on that subprocess. STDOUT and STDERR are now drained on every dispatch and logged, never returned to a client.

Backward compat — entry scripts that put the body on STDOUT after an fd 3 frame without body_fd, or the whole frame on STDOUT with no fd 3 frame at all, are still read (see exchange()).

Methods

__construct()

Spawn $size worker subprocesses immediately. All workers are ready (READY signal received) before the constructor returns.

public __construct([int $size = 4 ][, int $maxRequestsPerWorker = 500 ][, string|null $workerEntry = null ]) : mixed
Parameters
$size : int = 4

Number of persistent worker subprocesses (pool concurrency).

$maxRequestsPerWorker : int = 500

Requests served before a worker is recycled (pm.max_requests parity).

$workerEntry : string|null = null

Absolute path to the pool worker entry script; defaults to src/pool_worker.php.

Tags
throws
InvalidArgumentException

When $size < 1.

RuntimeException

When a worker subprocess fails to start or doesn't emit READY within 10 s.

close()

Shut down all workers cleanly (close pipes, wait for exit).

public close() : void

dispatch()

Dispatch one request to an idle worker and return the response frame.

public dispatch(array<string|int, mixed> $request[, float $timeout = 30.0 ]) : array<string, mixed>

Coroutine-aware: yields if all workers are busy until one frees up.

Parameters
$request : array<string|int, mixed>
$timeout : float = 30.0

Max seconds to wait for an idle worker before returning 503.

Return values
array<string, mixed> —

Response (status, headers, cookies, body, return_value).

filterSubprocessEnv()

Build the environment handed to a pool subprocess.

public static filterSubprocessEnv(array<string, string> $parentEnv, array<int, string> $allowlist, int $maxRequests) : array<string, string>

Previously this was array_merge(getenv(), …) — every parent env var (DB passwords, ZEALPHP_TIERED_INVALIDATION_SECRET, AWS_*, k8s/systemd secrets) was inherited by the long-lived subprocess running arbitrary legacy app code, and — unlike the proc/fork CGI path (Dispatcher::buildCgiEnv) — the request-controlled HTTP_PROXY was forwarded (httpoxy, CVE-2016-5385).

Default (empty $allowlist): pass the parent env through for legacy-app compatibility but ALWAYS drop HTTP_PROXY. Set App::cgiPoolEnvAllowlist() to a list of exact names / PREFIX* globs to harden to a strict allowlist (the pool IPC var is always included). Per-request CGI vars travel over the fd-3 IPC frame, not this spawn env, so a strict allowlist does not lose them.

Parameters
$parentEnv : array<string, string>

Usually getenv().

$allowlist : array<int, string>

Exact names or PREFIX* globs; empty = pass-through.

$maxRequests : int
Return values
array<string, string>

servedCounts()

Per-worker served counter (for tests / observability / /healthz).

public servedCounts() : array<int, int>
Return values
array<int, int>

size()

How many workers are alive right now.

public size() : int
Return values
int

ensureChannelPopulated()

One-time promotion of the sync idle queue into a Coroutine\Channel.

private ensureChannelPopulated() : void

Runs on the first dispatch inside a coroutine context, where push is legal. After this, the sync queue is empty and the channel owns idle-worker tracking for all subsequent dispatches.

exchange()

Run one request/response exchange with a subprocess over non-blocking pipes: write $frame to stdin, read the response from fd 3, and drain stdout + stderr throughout so the child can never block on a full pipe.

private exchange(array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int} $w, string $frame, float $timeout[, string|null $token = null ]) : array<string|int, mixed>

The request write happens inside the same select loop, under the same deadline, in a coroutine too (C3): a child that is not reading its stdin costs one timed-out request, never a slot held forever.

Response shapes accepted, in order of preference:

  • fd 3 frame with body_fd = 3: the body follows the frame on fd 3 (body_length bytes). Everything on STDOUT is stray output.
  • fd 3 frame without body_fd (older entry scripts / test stubs): the body is the first body_length bytes on STDOUT.
  • no fd 3, or fd 3 closed without a frame: a single legacy frame (metadata + body) on STDOUT.

Integrity (C1, C4): with a $token (proto=2 subprocess) the frame must carry it. Bytes left on the response channel after the response (fd 3, or STDOUT when STDOUT carried the body), a body_length over the cap, or a complete-but-undecodable frame set error; the caller then kills the subprocess, because those bytes would otherwise be read as the next request's response.

Returns resp = null on timeout or when every channel hit EOF before a full response arrived (eof = true for the latter). stdout holds the STDOUT bytes not used as body, stderr everything read from stderr (each capped at self::DIAG_CAP_BYTES; the rest is read and discarded).

Parameters
$w : array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int}
$frame : string
$timeout : float
$token : string|null = null
Return values
array<string|int, mixed>

hasUnsolicitedBytes()

True when the subprocess has written to fd 3 while no request was in flight. Never blocks: fd 3 is non-blocking.

private static hasUnsolicitedBytes(array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int} $w) : bool
Parameters
$w : array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int}
Return values
bool

isAlive()

private isAlive(array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int} $w) : bool
Parameters
$w : array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int}
Return values
bool

logProtocolError()

Log a broken exchange; the caller replaces the subprocess.

private static logProtocolError(int $pid, string $what) : void
Parameters
$pid : int
$what : string

logSubprocessOutput()

Send a subprocess's stray stdout / stderr to the framework log. Never to the client: under FPM and mod_php, php://stdout is not the response.

private static logSubprocessOutput(string $channel, int $pid, string $bytes) : void
Parameters
$channel : string
$pid : int
$bytes : string

parseFrame()

Decode one complete length-prefixed frame from the front of $buf.

private static parseFrame(string $buf) : array<string|int, mixed>|false|null
Parameters
$buf : string
Return values
array<string|int, mixed>|false|null

popIdleWorker()

Pop an idle worker index. In a coroutine, lazy-promotes the queue to a Coroutine\Channel (first call) and yields on it until a worker is freed or the timeout expires. Outside a coroutine, uses the synchronous LIFO — no yield, returns null if empty.

private popIdleWorker(float $timeout) : int|null
Parameters
$timeout : float
Return values
int|null

reap()

Close every pipe of the subprocess at $idx and wait for it to exit.

private reap(int $idx) : void
Parameters
$idx : int

reapAndSpawn()

Reap the slot's subprocess (unless already reaped) and start a new one; never throws.

private reapAndSpawn(int $idx) : void
Parameters
$idx : int

replace()

Kill the subprocess at $idx (it is not trusted to exit by itself, and whatever it still writes must not reach anyone) and put a fresh one in its slot. Unlike respawn(), the slot is NOT returned to the idle pool: the caller is still holding it.

private replace(int $idx) : void
Parameters
$idx : int

respawn()

Close all pipes for the worker at $idx, reap the subprocess via proc_close(), spawn a fresh replacement, and immediately return it to the idle pool. Called when a worker dies mid-request, hits its $maxRequestsPerWorker limit, or sends the _exit flag in its IPC frame.

private respawn(int $idx) : void
Parameters
$idx : int

returnToIdle()

Return a worker to the idle pool. Routes to the channel (in coroutine context, once promoted) so any coroutine waiting on pop wakes up; otherwise pushes to the sync LIFO.

private returnToIdle(int $idx) : void
Parameters
$idx : int

spawn()

private spawn() : array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int}
Return values
array{proc: resource, stdin: resource, stdout: resource, stderr: resource, fd3: resource|null, pid: int, served: int, proto: int}
On this page