kariricode / runtime
Persistent worker runtime for KaririCode applications: one PSR-15 handler served by FrankenPHP worker mode, RoadRunner, Swoole, or a classic PHP-FPM/CGI SAPI.
Requires
- php: ^8.4
- kariricode/contract: ^2.11
- kariricode/exception: ^2.0.2
- psr/container: ^2.0
- psr/http-message: ^2.0
- psr/http-server-handler: ^1.0
- psr/log: ^3.0
Requires (Dev)
- nyholm/psr7: ^1.8.2
- nyholm/psr7-server: ^1.1
- psr/http-factory: ^1.1
- spiral/roadrunner-http: ^3.5
- spiral/roadrunner-worker: ^3.6.1
- swoole/ide-helper: ^6.0
Suggests
- ext-swoole: Required by the Swoole driver (ext-openswoole 22+ also works through its \Swoole namespace)
- nyholm/psr7: Required by every driver (PSR-7/PSR-17 implementation)
- nyholm/psr7-server: Required by the FrankenPHP, Swoole and PHP-FPM drivers (ServerRequestCreator)
- spiral/roadrunner-http: Required by the RoadRunner driver (PSR-7 worker)
- spiral/roadrunner-worker: Required by the RoadRunner driver (worker relay)
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-06 15:29:34 UTC
README
Keep a PSR-15 application booted between requests on FrankenPHP, RoadRunner or Swoole — or run it unchanged on PHP-FPM.
1. Why KaririCode\Runtime
Under PHP-FPM every request pays the full bootstrap: autoloading, container build, configuration, routes. Worker runtimes pay it once per worker and then serve many requests from the same process. What you gain is the bootstrap cost removed from each request, so it depends on how heavy your bootstrap is — measure it with your own application.
A persistent process brings two obligations this package handles for you:
- State isolation —
RequestSandboxrestores request-scoped state after every request. - Worker hygiene — recycling by request count or memory, generic error responses, and PSR-3 logging of every failure.
2. Installation
# FrankenPHP, Swoole or PHP-FPM composer require kariricode/runtime nyholm/psr7 nyholm/psr7-server # RoadRunner composer require kariricode/runtime nyholm/psr7 spiral/roadrunner-http spiral/roadrunner-worker # Swoole also needs the extension (ext-openswoole 22+ works through its \Swoole namespace) pecl install swoole
The package itself depends only on PSR interfaces, kariricode/contract and kariricode/exception; the driver stacks above are what the driver you run needs.
3. Quick Start
<?php // public/index.php declare(strict_types=1); use KaririCode\Runtime\Runtime; require dirname(__DIR__) . '/vendor/autoload.php'; $app = require dirname(__DIR__) . '/bootstrap/app.php'; // PSR-15 handler, booted once $runtime = Runtime::boot(); // detects the driver, reads KARIRICODE_* $runtime->sandbox->register('tenant', $app->tenant()); // services with request state $runtime->run($app); // never returns
The same file serves every runtime. Server configuration examples (worker-mode Caddyfile, .rr.yaml) are in SPEC-001 §10.
4. Drivers and Detection
| Driver | Selected when | Recycling |
|---|---|---|
| FrankenPHP | frankenphp_handle_request() exists and FRANKENPHP_WORKER is set (worker mode) |
request count and memory, in the PHP loop |
| RoadRunner | RR_MODE=http |
request count and memory, stop handshake |
| Swoole | only when selected: KARIRICODE_RUNTIME_DRIVER=swoole |
native max_request |
| PHP-FPM | otherwise — also FrankenPHP classic mode, CGI, mod_php | php-fpm pm.max_requests |
There is no silent fallback: a detected or explicit driver whose requirements are missing fails at boot with RT_9401 and a message naming what is missing. A RoadRunner worker started for another plugin (RR_MODE=jobs, grpc…) is rejected the same way. Swoole is never auto-detected because the extension is often loaded in FPM images.
5. RequestSandbox — Per-Request State Isolation
use KaririCode\Runtime\Contract\Sandboxable; use KaririCode\Runtime\Sandbox\SandboxSnapshot; final class TenantContext implements Sandboxable { public private(set) ?string $tenantId = null; public function switchTo(string $tenantId): void { $this->tenantId = $tenantId; } public function snapshot(): SandboxSnapshot { return SandboxSnapshot::capture('tenant', ['tenantId' => $this->tenantId]); } public function restore(SandboxSnapshot $snapshot): void { $tenantId = $snapshot->state['tenantId'] ?? null; $this->tenantId = is_string($tenantId) ? $tenantId : null; } }
Snapshot only request state (tenant, identity, locale), not caches or connection pools meant to persist. If any restore() fails, every other service is still restored and the worker ends with RT_9430. Requests in one process run strictly one at a time; under Swoole this is why coroutines are disabled (ADR-006).
6. Lifecycle Hooks and Observability
use KaririCode\Runtime\Contract\WorkerLifecycleHook; use KaririCode\Runtime\Enum\WorkerEvent; $runtime = Runtime::boot(logger: $psr3Logger); $runtime->addLifecycleHook(new class implements WorkerLifecycleHook { public function onWorkerEvent(WorkerEvent $event): void { // Started, RequestBegin, RequestFailed, RequestEnd, MemoryLimitExceeded, Stopping } });
A handler exception is logged at error with the Throwable under the PSR-3 exception key and answered with {"error":"Internal Server Error"} — the client never sees details. $runtime->metrics() returns handled/failed counts, failure rate, uptime, peak memory and mean request duration for the worker.
7. Worker Recycling
After each response, the worker stops serving when it has served KARIRICODE_MAX_REQUESTS requests (failed ones included) or when real memory exceeds KARIRICODE_MEMORY_LIMIT_MB — by default 80% of PHP's memory_limit, so the recycle happens before PHP's own fatal error. Garbage collection also runs after each response, off the client's critical path. See ADR-003 and ADR-005.
8. Framework Integration and Custom Drivers
use KaririCode\Runtime\Provider\RuntimeFactory; use KaririCode\Runtime\Provider\RuntimeServiceProvider; // Any PSR-11 container: the factory reuses the container's RequestSandbox $runtime = (new RuntimeFactory())($container); // Any BindableContainer of kariricode/contract, such as kariricode/dependency-injection's (new RuntimeServiceProvider())->register($container);
Custom drivers are injected; there is no global registry:
$runtime = Runtime::boot( driverFactory: static fn(RequestSandbox $sandbox, WorkerLifecycle $lifecycle): RuntimeDriver => new MyDriver($sandbox, $lifecycle), );
9. Environment Variables
| Variable | Default | Applies to |
|---|---|---|
KARIRICODE_RUNTIME_DRIVER |
detected | all (frankenphp, roadrunner, swoole, phpfpm; case-insensitive) |
KARIRICODE_MAX_REQUESTS |
500 | FrankenPHP, RoadRunner, Swoole (0 = never) |
KARIRICODE_MEMORY_LIMIT_MB |
80% of memory_limit |
FrankenPHP, RoadRunner (0 = disabled) |
KARIRICODE_WORKERS |
4 | Swoole |
KARIRICODE_LISTEN |
0.0.0.0:8000 |
Swoole (host:port, [ipv6]:port) |
KARIRICODE_HTTP2 |
true | Swoole |
Malformed values fail at boot (RT_9402) instead of silently becoming defaults. Worker counts and request timeouts for FrankenPHP, RoadRunner and PHP-FPM belong to the server configuration.
10. Error Codes
Every exception implements KaririCode\Runtime\Exception\RuntimeException, carries an RtCode case in $errorCode (block 9400–9499 of the ecosystem registry) and extends the kariricode/exception base of one family (ADR-008). Messages start with [RT_<code>]; a rejected value stays in $subject, out of the message.
| Code | Exception | Meaning |
|---|---|---|
| RT_9400 | ConfigurationException |
KARIRICODE_RUNTIME_DRIVER names no driver |
| RT_9401 | ConfigurationException |
driver requirements not met (SAPI marker, extension or package) |
| RT_9402 | ConfigurationException |
malformed runtime environment variable |
| RT_9403 | ConfigurationException |
nyholm/psr7 or nyholm/psr7-server missing |
| RT_9410 | ConfigurationException |
worker setting out of range |
| RT_9411 | ConfigurationException |
malformed listen address |
| RT_9420 | ContainerEntryException |
a container entry RuntimeFactory reads has the wrong type |
| RT_9430 | SandboxException |
request state could not be restored; the worker ends |
11. Ecosystem Position
application (PSR-15 handler)
│
kariricode/runtime ── PSR-7 / PSR-15 boundary (nyholm), PSR-3 logging, PSR-11 factory
│
FrankenPHP · RoadRunner · Swoole · PHP-FPM
Other components integrate through contracts, not code dependencies: stateful registries (e.g. tenancy) implement Sandboxable; the framework registers the runtime through RuntimeServiceProvider (ADR-004). The runtime depends only on PSR packages, kariricode/contract and kariricode/exception.
12. Architecture and Quality Gates
src/
├── Runtime.php composition root: boot, run, metrics
├── Configuration/ Environment (strict env parsing)
├── Contract/ RuntimeDriver, Sandboxable, WorkerLifecycleHook
├── Driver/ FrankenPhp, RoadRunner, Swoole, PhpFpm (transport only)
├── Enum/ DriverType, WorkerEvent, RecycleReason
├── Exception/ RtCode, RuntimeException (marker), Configuration-, ContainerEntry-, SandboxException
├── Http/ HttpMessageFactory (PSR-7 conversion, SAPI emitter)
├── Lifecycle/ RequestCycle (shared request bracket), WorkerLifecycle
├── Provider/ RuntimeFactory (PSR-11), RuntimeServiceProvider
├── Sandbox/ RequestSandbox, SandboxSnapshot
└── ValueObject/ WorkerConfig, ListenAddress, RuntimeResult
The eight gates of KaririCode Specification V4.3.3 §29.1 run through KaririCode Devkit with the configs committed here (ADR-007):
composer install && kcode init # the runtime, then the toolchain pinned in devkit.php composer check # style, PHPStan max, Psalm 1, complexity, the three suites, mutation composer test # unit, integration (PHP's built-in server) and conformance suites composer mutation # Infection: MSI ≥ 80 composer security # validate, audit of both locks, secret scan composer sbom # CycloneDX 1.5
The measured results, open items and judgment calls are in QD-V433-COMPLIANCE; the threat model in SECURITY.md; how to contribute in CONTRIBUTING.md. Design decisions: ADR-001 to ADR-008. Full specification and errata: SPEC-001. Changes: CHANGELOG.
13. License
MIT © 2025-2026 Walmir Silva. See LICENSE.