Festi Async Framework
A small PHP 8 framework for building long-running TCP services — multiplayer game servers, persistent socket APIs, real-time backends. It gives you a clean lifecycle, a JSON-RPC layer, pluggable I/O, and an offline test harness, so the code you write is domain logic instead of socket plumbing.
Package: festi-team/festi-framework-async.
Table of contents
- What it does
- How it fits together
- Requirements
- Install
- Hello world: an echo daemon
- Building a JSON-RPC service
- Timers
- HTTP and Server-Sent Events
- Project structure for a real service
- Testing
- Docker
- Running in production
- Quality gates
- Project layout
- Further reading
What it does
You write a small Service class. The framework gives you:
- A non-blocking event loop (Swoole, behind the
IEventWrapperinterface, so another loop can be added). - A wire protocol (
FestiJsonProtocolby default: JSON frames terminated by^). - A request lifecycle:
onInit→onStart→ per-messageonRequest→onClose. SubclassPersistServicefor connection-persistent servers. - A JSON-RPC 2.0 extension — write methods annotated with
#[RpcMethod]on plain classes (called plugins); parameters are auto-deserialised from the request, including typed value objects. - Sessions per connection that survive across requests on the same socket.
- Timers scoped to the event loop.
- An offline test harness that drives your service through an in-memory wrapper — no real sockets, no flakiness.
Two single-letter conventions to remember: requests/responses are JSON frames terminated by ^, and the loop is single-threaded — never block inside a handler.
How it fits together
┌─────────────────────────────────────────────────────────────┐
│ Your Service │
│ extends AbstractService | PersistService │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Extensions (composable, run in order) │ │
│ │ ┌─────────────┐ ┌────────────────┐ │ │
│ │ │ RpcExtension│ │ Your extension │ ... │ │
│ │ │ → plugins │ │ │ │ │
│ │ └─────────────┘ └────────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Protocol (IProtocol) ────► reads/writes wire frames │
│ Event wrapper (IEventWrapper) ────► Swoole / │
│ TestEventWrapper │
└─────────────────────────────────────────────────────────────┘
Three single-responsibility interfaces — IEventWrapper (I/O), IProtocol (framing), IExtension (handler) — make every layer swappable. The same service code runs against a real Swoole socket in production and against TestEventWrapper in your unit tests.
Requirements
- PHP 8.0+ (CI runs PHP 8.4)
- The
swooleextension. It is the only event loopWrapperFactorycreates; without it a service stops at start withNot found non-blocking IO lib. The offline test harness (TestEventWrapper) needs no extension. - PHP extensions:
pcntl,pdo,intl,sockets,json,simplexml - Composer
- For integration tests:
screenandpson$PATH(the test harness forks daemons viascreen -d -m) - For HTTP and Server-Sent Events:
swoolespecifically. It is a composersuggest, not arequire: a service that only uses the socket wrappers or the in-memory test wrapper does not need it.
Install
composer require festi-team/festi-framework-async:dev-develop
This brings in the four festi-framework-* sibling packages it depends on (core, cacher, database, serialization).
Upgrading from core\async\*
The package now uses Festi\Async\*, in line with the rest of the Festi
stack, and core\logger\* moved to Festi\Async\Logger\*. Directory names
under src/ follow the namespace segments, as PSR-4 requires.
Code that resolves the old names keeps working: they are registered as
aliases of the new ones, so core\async\service\AbstractService still
resolves. New code should use the new names, because the aliases exist to
give consumers time rather than to stay for ever.
Code that names an old name in a type declaration does not. PHP does not
consult an autoloader when it checks a parameter or return type, so a
signature written against core\async\wrapper\IEventWrapper fails with a
TypeError before the alias is ever created, even though class_exists() on
the same name would have made it. Anything that implements an interface of
this package, or type hints one, has to be updated. Everything else can wait.
A second PSR-4 mapping could not have done this. PSR-4 finds a file from a class name and then expects that file to declare that class, and these files now declare the new names, so an alias is what answers the old one.
Upgrading to strict types and native types
Every file of the package that a test runs now starts with
declare(strict_types=1);, and its methods and properties have native types.
This changes nothing for a caller that passes the documented types. It can
change these things for a consumer:
- A subclass that declares a property of
AbstractService,BaseProtocol,AbstractWrapperorWrapperConnectionagain must give it the same type. - An override of a method that now has a native return type must declare a
compatible return type. Examples are
WrapperConnection::getID()(mixed),Model::get()(mixed) andSessionStorage::set()(mixed). - The interfaces keep their docblock return types, so a class that implements one does not need to change.
- The event type constants are integers, and core's
addEventListener()takes a string. Code that declaresstrict_typesmust convert the constant:(string) ServiceEvent::EVENT_ON_BEFORE_CLOSE_CONNECTION. - An exception whose code is text, such as the SQLSTATE
HY000of aPDOException, now reaches the client with the code 0. Before, the exception handler stopped with aTypeError. A numeric text code such as23000reaches the client as the number. - In the test helpers,
OfflineFestiTestCase::$testConnectionIDis now$idTestConnection. The magic__get()ofOfflineFestiTestCaseand itsRemotePluginclass are removed: they called methods that do not exist, so every call failed.Thread::kill()andThread::setRunnable()return nothing, as they always did.
Hello world: an echo daemon
A complete server, runnable end-to-end. Save as server.php:
<?php
require __DIR__ . '/vendor/autoload.php';
use Festi\Async\Wrapper\WrapperFactory;
use Festi\Async\Wrapper\WrapperConfig;
use Festi\Async\Wrapper\IConnection;
use Festi\Async\Service\PersistService;
use Festi\Async\Service\ISessionStorage;
use Festi\Async\Service\SessionStorage;
use Festi\Async\Service\Model\Request;
use Festi\Async\Service\Model\Response;
use Festi\Async\Service\Model\Session;
final class EchoService extends PersistService
{
protected function onInit(): void {}
protected function onStart(): void {}
public function onRequest(
Request &$request,
Response &$response,
Session &$session,
IConnection $connection
): bool {
$response['echo'] = $request['msg'] ?? null;
return true; // mark request handled
}
public function createSessionStorage(): ISessionStorage
{
$store = [];
return new SessionStorage(\Cacher::factory($store));
}
}
$wrapper = WrapperFactory::create(new WrapperConfig());
$server = new EchoService('tcp://0.0.0.0:20001', $wrapper);
$server->start();
Run it:
php server.php
Talk to it:
$ telnet 127.0.0.1 20001
{"msg":"hi"}^
{"echo":"hi"}^
The ^ is the protocol's frame terminator. Send it after every JSON document. The server replies with another ^-terminated frame.
Building a JSON-RPC service
The echo service above uses raw onRequest. For anything non-trivial, register RpcExtension and let it dispatch to plain plugin classes:
// src/plugin/MathPlugin.php
namespace app\plugin;
use Festi\Async\Service\Plugin\AbstractAsyncPlugin;
use Festi\Async\Service\Rpc\RpcMethod;
class MathPlugin extends AbstractAsyncPlugin
{
#[RpcMethod] // exposed as "add"
public function add(int $a, int $b): int
{
return $a + $b;
}
#[RpcMethod(name: 'math.sub')] // exposed as "math.sub"
public function subtract(int $a, int $b): int
{
return $a - $b;
}
}
Wire it up inside your service's onInit:
public function onInit(): void
{
$rpc = new \Festi\Async\Service\Rpc\RpcExtension($this->logger);
$rpc->addComponent(\app\plugin\MathPlugin::class);
$this->addExtension($rpc);
}
Call it:
$ telnet 127.0.0.1 20001
{"jsonrpc":"2.0","method":"add","params":[2,3],"id":1}^
{"jsonrpc":"2.0","id":1,"result":5}^
What you get for free:
- Exceptions thrown from a plugin become
{"error":{"code":...,"message":...}}responses: the exception's own code and message pass through. Anything that is not an\Exception(a PHPError) is logged and answered with Internal Error. - The extension's own errors use the JSON-RPC 2.0 codes, available as
RpcExceptionconstants:
| Code | Constant | When |
|---|---|---|
-32600 |
ERROR_CODE_INVALID_REQUEST |
the request names no method |
-32601 |
ERROR_CODE_METHOD_NOT_FOUND |
no plugin exposes the method |
-32602 |
ERROR_CODE_INVALID_PARAMS |
fewer parameters than the method requires, more than it takes, or params that is not a list |
-32603 |
ERROR_CODE_INTERNAL |
a PHP Error inside the call |
Breaking change: these replace the earlier 302 (unknown or missing method), 400 (parameters) and 500 (internal). A client that checks for those numbers has to be updated. RpcException::ERROR_CODE_BAD_REQUEST (302) is kept, deprecated, for code that still references it.
- Typed object parameters in plugin signatures are auto-hydrated by ObjectParameterDecorator. Type-hint a value object and the RPC layer instantiates and populates it from the JSON payload.
- Batch calls work: send a JSON array of requests, get an array of responses.
- Plugins can access the active session ($this->session), connection ($this->connection), and service ($this->service) — they're injected before each call.
Timers
Schedule recurring work on the event loop with addTimer. Use it from onStart (or anywhere you hold a service reference) for heartbeats, queue drains, garbage collection, broadcast ticks, etc:
protected function onStart(): void
{
$tick = 0;
$this->addTimer('heartbeat', function () use (&$tick) {
$tick++;
$this->logger->i("heartbeat #{$tick}");
if ($tick >= 10) {
$this->removeTimer('heartbeat');
}
}, 2000); // interval in milliseconds
}
Timer names are unique per service — re-registering a name throws. Callbacks must not block; the loop is single-threaded.
HTTP and Server-Sent Events
The socket wrappers above keep a TCP connection open and write to it whenever they like, which is the hard half of Server-Sent Events. This section adds the other half: HTTP.
SwooleHttpWrapper runs on Swoole\Http\Server, so Swoole parses HTTP and the
package carries no hand written parser. Everything else stays where it was:
IProtocol still does framing, IExtension still handles requests, and
IEventWrapper is untouched, so the socket services and their consumers are
unaffected.
Swoole only. ext-swoole is a composer suggest, not a require. A
service that only uses TestEventWrapper or one of the socket wrappers does
not need it; SwooleHttpWrapper::onInit() throws a HttpException with a
clear message if it is missing.
A daemon built on this holds connections. Do not run Festi Core business logic inside it: the current user, permission caches and the request scoped singletons all assume one request per process. Keep the daemon to transport and hand the work to something that is built for it.
A minimal SSE daemon
This is tests/util/ReadmeClockService.php, word for word. A test executes it
and compares it with this block, so the example cannot drift out of date.
declare(strict_types=1);
use Festi\Async\Protocol\ServerSentEvents\LastEventID;
use Festi\Async\Protocol\ServerSentEvents\Event;
use Festi\Async\Protocol\ServerSentEvents\Stream;
use Festi\Async\Service\IService;
use Festi\Async\Service\Http\HttpService;
use Festi\Async\Wrapper\IConnection;
use Festi\Async\Wrapper\Http\HttpRequest;
use Festi\Async\Wrapper\Http\IStreamResponder;
/**
* The README's worked example, kept here so a test executes it and it cannot
* rot. ReadmeExampleTest asserts that the README block and this file are the
* same text.
*/
class ReadmeClockService extends HttpService
{
const EVENT_NAME = 'tick';
/**
* Replay is bounded, or a daemon that runs for days grows for days.
*/
const HISTORY_LIMIT = 100;
/**
* @var Stream[] connection id => stream
*/
private array $_streams = [];
/**
* @var string[] sequence => payload
*/
private array $_history = [];
private int $_sequence = 0;
protected function onInit(): void
{
parent::onInit();
// HttpService owns the one route extension; routes go on it.
$onSubscribe = [
$this,
'onSubscribe',
];
$this->getRoutes()->addCallback('GET', '/clock/events', $onSubscribe);
} // end onInit
protected function onStart(): void
{
// Registers the keep-alive timer, which is also how a peer that
// vanished without a FIN is noticed.
parent::onStart();
$onTick = [
$this,
'onTick',
];
$this->addTimer('clock', $onTick, 1000);
} // end onStart
/**
* Subscribe, replay, then stay. The handler returns immediately: the
* stream is fed by the timer, so one client costs one coroutine.
*
* @param HttpRequest $request
* @param array<string, string> $parameters
* @param IStreamResponder $responder
* @return void
*/
public function onSubscribe(HttpRequest $request, array $parameters, IStreamResponder $responder): void
{
unset($parameters);
$stream = new Stream($responder);
if (!$stream->start()) {
return;
}
$resume = LastEventID::fromRequest($request);
foreach ($this->getEventsAfter($resume->getSequence()) as $sequence => $payload) {
if (!$stream->event(Event::withID((string) $sequence, self::EVENT_NAME, $payload))) {
return;
}
}
$this->_streams[$responder->getConnectionID()] = $stream;
} // end onSubscribe
/**
* @return string[] sequence => payload
*/
public function getEventsAfter(int $sequence): array
{
$result = [];
foreach ($this->_history as $known => $payload) {
if ($known > $sequence) {
$result[$known] = $payload;
}
}
return $result;
} // end getEventsAfter
public function onTick(): void
{
$now = ['now' => time()];
$this->publish(json_encode($now));
}
public function publish(string $payload): int
{
$this->_sequence++;
$this->_history[$this->_sequence] = $payload;
// Not array_shift(): it renumbers integer keys, and the keys here
// are the sequence numbers a client resumes from.
while (count($this->_history) > self::HISTORY_LIMIT) {
unset($this->_history[array_key_first($this->_history)]);
}
$event = Event::withID((string) $this->_sequence, self::EVENT_NAME, $payload);
foreach ($this->_streams as $id => $stream) {
// False means the client left or fell too far behind the buffer
// cap; either way it is gone and will reconnect.
if (!$stream->event($event)) {
unset($this->_streams[$id]);
}
}
return $this->_sequence;
} // end publish
public function getSubscriberCount(): int
{
return count($this->_streams);
}
protected function onClose(IConnection &$connection, IService &$service): bool
{
unset($this->_streams[(int) $connection->getID()]);
return parent::onClose($connection, $service);
} // end onClose
}
Start it with any HTTP wrapper:
use Festi\Async\Wrapper\WrapperConfig;
use Festi\Async\Wrapper\Http\HttpServerOptions;
use Festi\Async\Wrapper\Swoole\Http\SwooleHttpWrapper;
$service = new ReadmeClockService(
'http://0.0.0.0:9501',
new SwooleHttpWrapper(new WrapperConfig(), HttpServerOptions::forStreaming())
);
$service->start();
A larger version with rooms, a health route and a publish route is
tests/server/SseClockDaemon.php;
curl -N http://127.0.0.1:9501/rooms/lobby/events shows the stream.
The pieces
| Class | What it is for |
|---|---|
wrapper\http\IHttpEventWrapper |
Capability interface. Test with instanceof; the socket wrappers need no stubs. |
wrapper\http\IStreamResponder |
One long lived response: open(), send(), end(). |
wrapper\http\HttpRequest |
The request as a value object. Vendor request objects never leave the wrapper. |
wrapper\http\HttpServerOptions |
The Swoole settings that matter, as a value object. |
wrapper\http\StreamBufferPolicy |
How far one stream may fall behind before it is dropped. |
wrapper\http\HttpHeaders |
Header validation: a name that is not a token, or a value carrying CR, LF or NUL, is refused rather than written. |
wrapper\swoole\http\SwooleHttpWrapper |
The wrapper itself. |
protocol\http\HttpProtocol |
Framing: HTTP message to Request, Response to HTTP message. Needs a wrapper that speaks HTTP; see the note below. |
protocol\sse\Stream, Event, LastEventID |
SSE framing, ids, keep-alive comments and the resume point. |
service\http\HttpService |
AbstractService with the stream lifecycle wired in. |
service\http\HttpRouteExtension, HttpRoute, Route |
Routing, by registration or by #[Route] attribute. |
wrapper\test\TestHttpEventWrapper, TestStreamResponder |
The same service under PHPUnit, with no socket. |
util\pool\CoroutinePool |
A bounded pool for anything a coroutine must not share. |
HTTP needs an HTTP wrapper. HttpProtocol reads a message through an
IHttpEventWrapper, where the vendor has already framed it. Its own
decode() is a parser and not a transport: it takes one complete message
from one complete string, so it consults no Content-Length, cannot wait
for a body that arrives in a second read, and would fold two pipelined
requests into one. Given a plain socket wrapper, read() therefore refuses
rather than parsing half a request. Use SwooleHttpWrapper in production
and TestHttpEventWrapper under PHPUnit; the socket wrappers in this
package are for protocols of your own, not for HTTP.
Timers run in every worker. Swoole timers are per process, and so are
streams: each worker keeps its own responders and its own StreamRegistry.
The loop-create event is therefore raised in every worker, which is what
lets HttpServerOptions::forStreaming()->withWorkers(4) keep-alive all of
its streams rather than the quarter that happens to live in worker 0.
Routes can also be declared as attributes, next to #[RpcMethod]:
class RunRoutes
{
#[Route('GET', '/runs/{id}/events')]
public function stream(HttpRequest $request, array $parameters, IStreamResponder $responder): void
{
// $parameters['id']
}
}
$routes->addComponent(RunRoutes::class);
RpcExtension still works over HTTP: a JSON body is flattened into the
Request for POST, PUT and PATCH, so a JSON-RPC 2.0 call to the same service
needs no new code. A query string is never flattened, so
GET /rpc?method=something.destructive cannot reach a JSON-RPC method; a
handler that wants a query parameter reads
$httpRequest->getQueryParameter(). The HTTP envelope lives under the
reserved http key so it can never collide with a method or params in the
payload.
A service owns exactly one HttpRouteExtension, because AbstractService keys
extensions by class name and a second one would silently replace the first.
HttpService creates it and hands it out through getRoutes(); adding another
throws a RouteException rather than losing the parent's routes.
A path that exists under a different verb is answered 405 with an Allow
header, not 404. Route parameters arrive decoded exactly once and can never
contain a path separator or a traversal segment, so a handler may use one as a
file name without guessing.
A handler that throws is contained: the route extension catches \Throwable,
logs it with its cause, answers 500 when the response has not started and
ends the stream when it has. Nothing reaches the Swoole callback, where an
uncaught error would take down the process holding every other stream.
Swoole settings that matter, and why
HttpServerOptions::forStreaming() sets these. Change them through the value
object rather than by hand.
| Setting | Value | Why |
|---|---|---|
| server mode | SWOOLE_BASE |
The process that holds the streams is the one that gets the shutdown. |
enable_coroutine |
true |
One coroutine per request, so a slow handler blocks only itself. |
hook_flags |
SWOOLE_HOOK_ALL |
Makes ordinary PDO, curl and stream clients non blocking. Set here and exactly once, not with Swoole\Runtime::enableCoroutine(), whose signature changed between Swoole majors. A script that needs hooks outside a server calls SwooleRuntime::enableCoroutineHooks(), which handles both signatures. |
http_compression |
false |
Compression re-buffers whole chunks and stalls the stream. |
open_http2_protocol |
false |
SSE here is HTTP/1.1 chunked. |
max_request |
0 |
Never recycle a worker that is holding streams. |
send_yield |
true |
A full socket buffer suspends the coroutine instead of erroring. |
worker_num |
1 |
Streams live in worker memory. More workers means more processes each holding a slice, and any broker connection multiplied by the same number. |
HttpServerOptions is a value object: every with*() returns a copy, so
handing one to a wrapper and then deriving another cannot change the running
server's settings.
SwooleHttpWrapper needs ext-swoole 4.6.0 or newer for
Swoole\Http\Response::isWritable(), and refuses to start on anything older
rather than guessing whether a peer is still there. The buffer cap additionally
uses send_queued_bytes from Server::getClientInfo(), which older builds do
not report; there the guard counts what it wrote itself, which still bounds
memory.
Backpressure: what happens to a client that stops reading
A chunked HTTP write in Swoole does not block and does not fail while a peer
falls behind. Measured run, probe-chunked-write-backpressure.php against a
client that connects and never reads, on Swoole 6.2.2 and PHP 8.4.24:
chunk 0 write=0.000076s queued=0
chunk 60 write=0.000093s queued=1342218
chunk 120 write=0.000205s queued=5274918
chunk 159 write=0.000039s queued=7831173
accepted 10485760 bytes by a peer that read nothing
mean write 0.000040s slowest 0.000259s
Ten megabytes went into the connection, every write() returned true, and the
mean write took 40 microseconds. Left alone, one browser on a bad link grows
the worker without limit. (The numbers above are the run's own output. To
take the measurement again, on your own Swoole and PHP:
tools/probe-chunked-write-backpressure.php.)
The one number that does tell the truth is in that output: send_queued_bytes.
So every stream carries a StreamBufferPolicy. After each chunk the responder
asks the server how many bytes are still queued for that one connection, and
once that passes the cap it ends the stream. The client reconnects on its own
and resumes from Last-Event-ID, so the drop costs a round trip and not data.
The default cap is 1 MiB:
$options = HttpServerOptions::forStreaming()
->withBufferPolicy(new StreamBufferPolicy(262144));
Unknown is not zero. When the transport cannot report its queue depth (an
fd the server no longer tracks, or a build that does not carry the counter) the
responder counts what it wrote since the last trustworthy reading and trips on
that instead, so a degraded transport degrades into dropping one stream rather
than into an unbounded one. An operator who would rather keep streaming blind
has to say so: (new StreamBufferPolicy(262144))->allowUnknownQueueDepth().
A cap of zero turns the policy off entirely, for a daemon that would rather grow than ever drop a client.
Shutdown
On SIGTERM the wrapper raises HttpWrapperEvent::EVENT_ON_BEFORE_SHUTDOWN
and HttpService clears its timers and ends every open stream with a final
:shutdown comment, so clients reconnect instead of guessing. Set what that
last chunk says with setShutdownNotice(), or null to end streams silently.
HttpService also registers a keep-alive timer by default, which writes one
comment on every open stream every Stream::KEEP_ALIVE_SECONDS. That is
how a client that vanished without a FIN is noticed at all: nothing else ever
writes to an idle stream. Turn it off with setKeepAliveEnabled(false) only if
the service writes on its own schedule.
Swoole claims SIGTERM in both server modes, so a handler registered with
Swoole\Process::signal() is refused; the wrapper registers beforeShutdown
and workerStop as well and the first one to fire wins.
Behind nginx
SSE through a buffering proxy looks like a hung page. Every stream sends
X-Accel-Buffering: no, which covers nginx even when the location block does
not, but set the directives too so a second proxy cannot undo it:
location /rooms/ {
proxy_pass http://festi-sse:9501;
proxy_http_version 1.1; # chunked streaming; 1.0 buffers
proxy_set_header Connection ""; # keep the upstream connection alive
proxy_buffering off; # do not accumulate the response
proxy_cache off;
gzip off; # gzip re-buffers the stream
proxy_read_timeout 3600s; # longer than the longest stream
proxy_send_timeout 3600s;
chunked_transfer_encoding on;
}
Non blocking I/O inside a handler
With hook_flags on, PDO, curl and stream clients yield instead of blocking,
so a slow query in one request does not stall the other streams. Two rules
follow from that:
- Never share a handle between coroutines. A PDO handle used by two
coroutines at once corrupts the protocol. Take one from a
CoroutinePoolfor the length of a query and give it straight back; never hold one across a long lived loop.
$pool = new CoroutinePool(function () use ($dsn) { return new PDO($dsn); }, 32);
$handle = $pool->borrow();
try {
$rows = $handle->query($sql)->fetchAll();
} finally {
$pool->give($handle);
}
One connection per stream is the mistake to avoid: two hundred streams need two hundred coroutines and a handful of handles, not two hundred handles.
-
Use a pure PHP client, not a C extension, for anything that must yield. For RabbitMQ that means
php-amqplib(streams, hooked) and notext-amqp(blocking C sockets, which stall the whole loop). Two things to get right with php-amqplib under hooks: -
AMQPTimeoutExceptionfrom$channel->wait()is a quiet window, not an outage. CatchingThrowablearound the consume loop turns an idle connection into a reconnect storm. - Call
$connection->set_close_on_destruct(false)right after connecting and close the connection explicitly from inside a coroutine. The destructor runs at process shutdown, outside any coroutine, and itsstream_select()raisesSwoole\Error: API must be called in the coroutine, which takes the worker down.
Testing an HTTP service without a socket
TestHttpEventWrapper feeds the service fake requests and captures the status,
the headers and every streamed chunk. TestStreamResponder decodes the SSE
frames and can play a client that leaves or one that stops reading.
class ClockServiceTest extends OfflineHttpTestCase
{
protected function createService(TestHttpEventWrapper $wrapper): IService
{
return new ClockService('http://0.0.0.0:9501', $wrapper);
}
public function testAReconnectingBrowserReceivesOnlyWhatItMissed(): void
{
$responder = $this->get('/rooms/lobby/events', array('Last-Event-ID' => '2'));
$events = $responder->getEvents();
$this->assertSame('3', $events[0]['id']);
}
}
$this->wrapper->disconnect($id) plays a client that left, shutdown() plays
SIGTERM, and tickTimers() fires the service's timers by hand.
The suite that talks to a real daemon over a real socket is opt in, because it
needs ext-swoole and a free port:
composer test-http-integration
MCP Streamable HTTP on top of this
The same wrapper can carry a full MCP Streamable HTTP front later, with one
addition. POST /mcp answering either a JSON body or an upgraded event stream
is HttpRouteExtension plus the existing RpcExtension, since the responder
supports both shapes. GET /mcp for the server initiated stream is the SSE
route with a session outbox in place of a room. Last-Event-ID resumption
carries over unchanged. The one genuinely new piece is Mcp-Session-Id:
ISessionStorage is keyed per connection and an MCP session outlives a
connection, so it needs a storage keyed by session id with a TTL, which is a
class next to SessionStorage rather than a change to it.
Project structure for a real service
Production consumers follow this shape:
my-service/
├── bin/
│ ├── server.sh # supervisor-friendly start script
│ ├── main.php # boots WrapperFactory + your Service
│ ├── common.php # loads config, autoload, include_path
│ └── config.php # constants: DB creds, ports, log dir
├── src/
│ ├── MyService.php # extends PersistService, registers extensions
│ ├── plugin/ # RPC plugins (#[RpcMethod] entry points)
│ ├── facade/ # business logic services
│ ├── storage/ # repositories
│ ├── domain/ # entities and domain events
│ └── libs/
│ ├── DefaultPlugin.php # your project's plugin base
│ └── vo/ # value objects auto-hydrated by RPC
├── tests/
│ ├── bootstrap.php
│ ├── phpunit.xml
│ └── MyServiceTestCase.php # extends OfflineFestiTestCase
└── composer.json
A typical bin/main.php:
<?php
define('FS_ROOT', __DIR__ . DIRECTORY_SEPARATOR);
[$host, $port] = [$argv[1] ?? '0.0.0.0', $argv[2] ?? '20001'];
require_once FS_ROOT . 'common.php';
$wrapper = \Festi\Async\Wrapper\WrapperFactory::create(
new \Festi\Async\Wrapper\WrapperConfig()
);
$server = new \app\MyService(
"tcp://$host:$port",
$wrapper,
new \Festi\Async\Logger\Logger($CONFIG['FS_LOGS'])
);
$server->start();
A typical plugin base that pulls session helpers into one place:
namespace app\libs;
use Festi\Async\Service\Plugin\AbstractAsyncPlugin;
class DefaultPlugin extends AbstractAsyncPlugin
{
protected function getUserID(): int
{
$id = $this->session->get('id_user');
if (!$id) {
throw new \app\exception\PermissionException();
}
return $id;
}
}
Combine with a DI container (festi-team/festi-framework-di) and your plugins become thin RPC adapters in front of injected facades — testable in isolation.
Testing
Write tests against the real service class with TestEventWrapper instead of a real socket. No process fork, no port, no flake:
// tests/MyServiceTestCase.php
use Festi\Async\Service\IService;
use Festi\Async\Wrapper\Test\TestEventWrapper;
use Festi\Async\Logger\Logger;
class MyServiceTestCase extends \OfflineFestiTestCase
{
protected function createService(): IService
{
return new \app\MyService(
'tcp://0.0.0.0:' . DAEMON_PORT,
new TestEventWrapper(),
new Logger(FS_LOGS)
);
}
protected function rpc(string $method, array $params = []): array
{
return $this->request([
'jsonrpc' => '2.0',
'method' => $method,
'params' => $params,
]);
}
}
// tests/Plugins/MathPluginTest.php
class MathPluginTest extends MyServiceTestCase
{
public function testAddsTwoNumbers(): void
{
$response = $this->rpc('add', [2, 3]);
$this->assertSame(5, $response['result']);
}
}
OfflineFestiTestCase is exposed via the framework's dev autoload. Your composer.json needs to map it:
"autoload-dev": {
"psr-4": {
"": ["tests", "vendor/festi-team/festi-framework-async/tests/util"]
}
}
Run from the tests/ directory (the bootstrap uses relative paths):
cd tests
../vendor/bin/phpunit --configuration ./phpunit.xml
The http-integration group is excluded from that run: it starts a real Swoole
HTTP daemon and needs ext-swoole and a free port. Ask for it by name:
cd tests
../vendor/bin/phpunit --configuration ./phpunit.xml --group http-integration
For end-to-end tests that exercise a real socket, extend FestiAsyncTestCase instead — it forks a real daemon via screen and talks to it over TCP. For HTTP and SSE, extend OfflineHttpTestCase (in memory) or HttpDaemonTestCase (real daemon) — see HTTP and Server-Sent Events.
Docker
A Dockerfile and docker-compose.yml ship in the repo for the framework's own test suite, and the same image is a good starting point for your service.
composer install # on the host, where your SSH keys live
docker compose build # PHP 8.4 + Swoole + everything tests need
docker compose run --rm test
The compose test service mounts . into /app and runs phpunit against the host's vendor/. For an interactive shell with ~/.ssh mounted read-only:
docker compose --profile dev run --rm shell
Running in production
The shipped pattern is dead simple — bin/server.sh runs the daemon foreground for one tick, then again in the background:
#!/bin/bash
php main.php 0.0.0.0 2010
php main.php 0.0.0.0 2010 &>/dev/null &
In real deployments people usually replace this with systemd, supervisor, or a container orchestrator that respawns the process on exit. Whatever supervises it should:
- Restart on non-zero exit.
- Send
SIGTERMfor graceful shutdown —stop()calls$eventAdapter->stopBaseLoop(). - Rotate the log file passed to
Festi\Async\Logger\Logger.
Quality gates
# Code style: the Festi standard with the project's exclusions, whole tree
./vendor/bin/phpcs --standard=./.phan/ruleset.xml -d memory_limit=1024M --extensions=php --ignore='vendor/**,.phan/**' ./
# The same, for the lines your branch changed only
./vendor/bin/festi-phpcs-diff --standard=./.phan/ruleset.xml --ignore='vendor/**,.phan/**' ./
# Static analysis (target: PHP 8.0). Add --allow-polyfill-parser without ext-ast.
./vendor/bin/phan --config-file .phan/config.php
# Tests, then the http-integration group
composer test
composer test-http-integration
The standard and the phan baseline come from festi-team/coding-standard, the
package every Festi project shares. .phan/ruleset.xml adds only per-file
exclusions, each with its reason, and .phan/config.php holds only what is
specific to this project. .gitlab-ci.yml runs all of the above on every
pipeline, and a style violation anywhere in the tree fails the pipeline.
Project layout
src/
├── service/ AbstractService, PersistService, models/, extension/, rpc/
│ ├── AbstractService.php # base service: lifecycle + extension dispatch
│ ├── PersistService.php # connection-persistent variant
│ ├── extension/ # IExtension contract + Extension trait
│ ├── rpc/ # RpcExtension, RpcMethod attribute, plugin factory
│ ├── plugin/ # AbstractAsyncPlugin (base for RPC plugins)
│ └── model/ # Request, Response, Session DTOs
│ └── http/ # HttpService, HttpRouteExtension, HttpRoute, Route
├── protocol/ BaseProtocol, FestiJsonProtocol
│ ├── http/ HttpProtocol (HTTP message framing)
│ └── sse/ Stream, Event, LastEventID
├── wrapper/ IEventWrapper + adapters
│ ├── http/ IHttpEventWrapper, IStreamResponder, HttpRequest, options, buffer policy
│ ├── swoole/ Production adapter
│ │ └── http/ SwooleHttpWrapper, SwooleStreamResponder
│ └── test/ TestEventWrapper, TestHttpEventWrapper for offline unit tests
├── logger/ ILogger, default file Logger
└── util/
├── decorator/ Parameter decoders for the RPC extension
└── pool/ CoroutinePool, a bounded pool for coroutine-unsafe resources
tests/
├── Integration/ Spawn a real daemon and connect over TCP
├── Service/ Offline tests via TestEventWrapper
├── EventWrapper/ Wrapper-layer tests
├── Extension/ RpcExtension tests
├── Http/ HTTP and SSE tests via TestHttpEventWrapper
├── HttpIntegration/ Real Swoole daemon over a real socket (group http-integration, opt in)
└── util/ OfflineFestiTestCase, OfflineHttpTestCase, HttpDaemonTestCase, helpers
tools/ Project scaffolder (`bash tools/install.sh`)
.phan/ phan config (project overrides) + stubs for Swoole/libevent
Further reading
AGENTS.md— architecture notes and recipes for AI coding assistants and human contributors digging into framework internals.CLAUDE.mdis a symlink to the same file.