Search by

phasync / ext-swerve

frodeborli

PHP extension for hosting PHP requests in a PHP-written server: sapi() runs a request under a host object, run_next(), include_global(), a memo, an evented stat cache and a GC grace. Builds on ext-phasync.

Package info

github.com/phasync/ext-swerve

Type:php-ext

Ext name:ext-swerve

pkg:composer/phasync/ext-swerve

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.0 2026-11-28 19:21 UTC

This package is auto-updated.

Last update: 2026-11-29 14:18:03 UTC


README

The request side of a web server written in PHP, as a PHP extension. It builds on ext-phasync (the coroutines: a blocking call in a managed fiber waits through an event loop) and is what Swerve uses to run one PHP request per coroutine as a SAPI would, in a worker that serves many of them.

  • Swerve\ext\sapi($code, $sapi): a request under a host object; its own superglobals, output, headers, body, session and ini changes, and php-fpm's abort rules.
  • Swerve\ext\run_next($script) and dup2($stream, $fd): a fresh request in the same CLI process.
  • Swerve\ext\include_global($file): run an application's entry file in the global scope, from inside a method, a closure or a Fiber.
  • A memo for json_decode(), unserialize(), file_get_contents(), scandir() and glob(), an evented stat cache (Linux) and a grace period for young garbage (swerve.gc_grace), across requests.

It needs PHP 8.3 to 8.6 (NTS, or ZTS with one PHP thread per process) on Linux or macOS. ext-phasync is optional to load but is what makes requests concurrent; swerve loads after it (and after Scope, ext/session and pcntl) whatever the order in php.ini. Until ext-phasync 2.0.9 all of this was part of ext-phasync: see CHANGELOG.md.

Build and test

phpize
./configure --enable-swerve
make
# the tests run on ext-phasync's coroutines: point at a built ext-phasync
PHASYNC_SO=/path/to/ext-phasync/modules/phasync.so tools/run-tests.sh

swerve_arginfo.h is maintained by hand (Makefile.frag keeps make from regenerating it): never regenerate it with gen_stub.

Install

pie install phasync/ext-phasync
pie install phasync/ext-swerve

PIE downloads a prebuilt binary from the release (PHP 8.3-8.6 NTS and ZTS; Linux x86_64/arm64 glibc/musl and macOS arm64/x86_64) and builds from source otherwise. By hand:

php -d extension=/path/to/phasync.so -d extension=/path/to/swerve.so your-server.php

API

namespace Swerve\ext;

function sapi(\Closure $code, object $sapi): mixed;   // one request; its return value is returned
function run_next(string $script): void;               // CLI: run $script once more as a fresh request when this one ends
function dup2(mixed $stream, int $fd): void;           // as dup2(2): $fd stays open across requests, owned by no PHP resource
function include_global(string $file): mixed;          // require $file in the global scope, wherever this is called from
function memo_stats(): array;
function gc_grace_stats(): array;
function stat_cache_stats(): array;

The docblocks in swerve.stub.php are the reference.

One request per coroutine: sapi()

sapi($code, $sapi) is the SAPI-facing side of a web server written in PHP: it runs $code (a \Closure; a file path is not accepted) as a request. While it runs, and in every fiber started inside it, echo, output buffering, header(), headers_list(), http_response_code(), setcookie(), php://input, request_parse_body() and the session are that request's own, so many requests interleave in one worker. A request's session is written and closed the way RSHUTDOWN would when it returns or throws; two requests on the same session id serialise on the files handler's lock cooperatively instead of blocking the worker. A userland session handler may suspend too. Concurrent requests that use sessions need sapi() (Swerve uses it): outside it, ext/session's state belongs to the whole process, whether or not the handler suspends. Nothing else is isolated: statics, declarations, other globals, shutdown functions and error handlers are the worker's.

A request starts as it does under php-fpm: before $code runs, PHP's own request startup creates $_GET, $_POST, $_COOKIE, $_FILES, $_SERVER and $_REQUEST from what request_info() returns, with variables_order, request_order, max_input_vars, post_max_size, enable_post_data_reading and the upload limits applied and their warnings reported as "PHP Request Startup". A form POST's body is read before $code starts (up to post_max_size), so parsing it never waits for the client. filter_input() sees the request's own input. The superglobals are written into the current Scope (ext-scope keeps them per Scope), so a host runs each sapi() call in its own Scope to keep them apart; the output, headers, body and session are the request's own either way. $_SESSION follows the installed request the way ext/session keeps it in step with session_start().

What leaves the request goes to $sapi as a SAPI would receive it:

Method
name(): string required; what PHP_SAPI and php_sapi_name() report inside the request
write(string $data): bool required; the response body, piece by piece; false: the client is gone
send_headers(int $status, ?string $statusLine, array $headers): void required; once, before the first output
read(int $length): string the request body, '' at its end
request_info(): array method, content_type, content_length, query_string, request_uri, cookie (the raw Cookie header), server (the $_SERVER entries, beyond PHP's own)
flush(), connection_aborted(): bool flush() and the client's departure

exit() is not intercepted: it ends the script as under any SAPI, after the request's output has reached $sapi. write() and read() may wait for the client, suspending the request. write() returning false means the client is gone: connection_aborted() turns true and later output is discarded; with ignore_user_abort() off (the default), the request stops right there -- no catch, no finally, like exit() -- and sapi() returns null to its caller, which continues; other requests running concurrently in the same worker (each sapi() call is its own coroutine) are unaffected. Nesting throws. The full contract is the docblock in swerve.stub.php.

Fresh request, same process: run_next()

run_next($script) makes the CLI process, once the current script has ended, run $script as a new request in the same process: shutdown functions, destructors and output buffers of the first run finish, then statics, globals, declarations, constants, ini values, handlers and output buffers start over as in the first request, as under FPM. The opcache stays warm; no fork, no workers. A run that calls run_next() again is followed by another, so a script can restart itself for as long as it wants; the recording is used once. Whatever ended a run (exit(), a fatal error, an uncaught exception), the next run still happens, and the process exits with the last run's status.

The working directory, umask, signal mask and alarm() are put back to what the process started with. STDIN, STDOUT and STDERR are defined again; descriptors 0-2 and every inherited descriptor stay open, so a socket passed as fd 3 can be served across runs: set stream_set_read_buffer($s, 0) to read exactly what is consumed, since a stream's read buffer is lost with its request. Resource limits are not reset, and a fork()ed child that ends does not run the next request. $script must be readable when called (a ValueError otherwise), and the SAPI must be the CLI (an Error).

dup2($stream, $fd) puts $stream's descriptor on $fd (as dup2(2)), owned by no PHP resource afterwards, so it survives request shutdown and is there in every later run_next() run — the way a pcntl_fork()ed worker keeps a channel to its parent on a fixed descriptor across restarts.

Memo: json_decode(), unserialize(), file_get_contents(), scandir(), glob() across requests

With swerve.memo_memory (PHP_INI_SYSTEM, default 16M; 0 turns it off), the process remembers results, so a later request, in the same run_next() run or a later one, gets them without the work:

  • json_decode($json, true) and json_decode($json), default depth and flags, keyed by the text;
  • unserialize($data) (no options, or allowed_classes alone) when the result holds no references and no objects but stdClass, each once; with allowed_classes, only object-free results;
  • file_get_contents($path) of a regular file up to 4 MB, whole or from an offset and/or for a length, checked by a stat() each call (device, inode, size, mtime, ctime), so a changed file is read again;
  • scandir() and glob() (wildcards in the last path component only), keyed by the listed directory's stat; never on kernel file systems (/proc).

Something is stored the second time the process produces it, and only from a call that raised no error, warning or deprecation, so a hit behaves as the native call did. A json_decode() or unserialize() that took less than swerve.memo_min_ns (default 500) is not stored: decoding again costs no more. Entries live in persistent memory as immutable values, laid out as opcache lays out literal arrays: a hit costs nothing, and PHP copies the value when it is written to. An object-mode result is handed out as new stdClass instances each time, sharing every table and string that holds no object.

Least recently used entries go past swerve.memo_memory, counted in the bytes the entries take. A request may still use an evicted value, so it is freed when the request ends. Within one request that never ends (a Swerve async worker), evicted entries are kept up to swerve.memo_memory more; past that, nothing new is stored until a request ends. The memo never takes more than twice swerve.memo_memory. memo_stats() reports it.

Stat cache: file_exists(), is_file(), filemtime(), ... without a syscall (Linux)

With swerve.stat_cache=1 (PHP_INI_SYSTEM; default 0), file_exists(), is_file(), is_dir(), is_link(), is_readable(), is_writable(), is_executable(), filemtime(), filesize(), filectime(), fileperms(), fileinode(), fileowner(), filegroup(), filetype(), stat(), lstat() and a failing realpath() answer absolute plain-file paths from remembered results, kept valid by inotify watches on the directories they lie in (and every one above); a change, by this process or another, is seen by the next call. Results are PHP's own, warnings and open_basedir included. Network and FUSE file systems, symlinked directories and relative paths are never cached. At most swerve.stat_cache_watches (default 4096) directories are watched; past that, everything starts over. The memo's keys use the same results. stat_cache_stats() reports it; docs/stat-cache.md has the design.

Young objects skip the cycle collector: swerve.gc_grace

swerve.gc_grace (milliseconds, php.ini or -d, default 0 = off) makes gc_collect_cycles() skip the properties of objects younger than that: data a request just built is almost always still in use, and walking it costs the collection most of its time. Hiding an object's children can only make things look alive, so nothing live is freed; an object hidden while young is put back in the root buffer once it is old, so its garbage is still collected then. Age is counted per request (each run_next() run starts over), and collections in the request's shutdown hide nothing. The trade: cyclic garbage lives up to the grace period longer. It helps when collections run while a lot of young data is live: many concurrent requests suspended in one worker (the event loop collects at idle moments and every 0.5 s while busy), or a large request that triggers collections itself. With 0, nothing is installed. Swerve\ext\gc_grace_stats() returns the request's counters.

Measured (2026-10-29, one process, phasync's loop; each request builds 20,000 objects and waits on I/O twice): when the request's objects form cycles, gc_grace=100 saves 12% CPU per request at 50 concurrent requests and 4% at 10, for 45-70% more peak memory, since cyclic garbage waits out the grace period; when they don't, it changes nothing at 1, 10 or 50. That is why it is off by default.

Ini

All PHP_INI_SYSTEM: swerve.memo_memory (default 16M, 0 is off), swerve.memo_min_ns (500), swerve.stat_cache (0), swerve.stat_cache_watches (4096), swerve.gc_grace (ms, 0 is off) and, for tests, swerve.test_stat_cache_untrusted.

License

MIT, see LICENSE (and LICENSE.php-src for what is derived from php-src).