Search by

kariricode / eventloop

growthcodeoficial

Event loop for PHP 8.4: timers, stream readiness, signals, deferred callbacks and microtasks, fiber suspensions and cooperative cancellation, on stream_select.

v4.2.0 2026-11-27 20:03 UTC

This package is auto-updated.

Last update: 2026-11-27 20:10:54 UTC


README

An event loop for PHP 8.4: timers, stream readiness, signals, deferred callbacks and microtasks, fiber suspensions and cooperative cancellation, behind one EventLoop contract. It runs on stream_select(), with no extension required; ext-pcntl adds signal watchers. kariricode/async builds its promises on it.

CI

Installation

composer require kariricode/eventloop

Requires PHP 8.4. Runtime dependencies: kariricode/contract, kariricode/exception and kariricode/async-primitives (for the metrics bridge). ext-pcntl is suggested: without it signal watchers are refused.

Quick start

use KaririCode\EventLoop\LoopFactory;

$loop = LoopFactory::create(); // one per process or worker, passed to what needs it

$loop->defer(static fn () => print "first, on the next tick\n");
$loop->delay(0.5, static fn () => print "half a second later\n");

$tick = $loop->repeat(0.2, static fn () => print "tick\n");
$loop->delay(0.7, static fn () => $loop->cancel($tick));

$loop->run(); // returns when no referenced callback is left, or after stop()

There is no process-wide loop: static state outlives the request on persistent runtimes (Spec V4.3.3 §12), so the loop is created once and passed explicitly, typed as the EventLoop contract (ADR-007).

Callback ids

Every registration returns an id, and the same five operations work for every kind of callback:

$heartbeat = $loop->repeat(5.0, $sendHeartbeat);
$loop->unreference($heartbeat); // runs while there is other work, never keeps run() alive alone

$reader = $loop->onReadable($socket, $consume);
$loop->disable($reader); // backpressure: it neither runs nor keeps the loop alive
$loop->enable($reader);  // back on the watcher
$loop->cancel($reader);  // removed for good

cancel(), disable() and unreference() ignore an unknown id — a delay or defer is unregistered before it runs, a stream callback when its stream is closed — while enable() and reference() throw UnknownCallbackException (2050).

Streams

[$server, $client] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
stream_set_blocking($server, false);

$loop->onReadable($server, static function ($stream): void {
    echo fread($stream, 1024), "\n"; // "ping"
    fclose($stream);                 // its callbacks are cancelled at the end of the tick
});
fwrite($client, 'ping');

$loop->run();

Several callbacks may watch one stream. stream_select() cannot watch a descriptor numbered 1024 or above on most builds; ADR-010 explains the choice.

Signals

$shutdown = $loop->onSignal(SIGTERM, static function (int $signal) use ($loop, &$shutdown): void {
    echo "draining\n";       // on the loop, never inside the pcntl handler
    $loop->cancel($shutdown); // the handler that was there before comes back
});

$loop->delay(0.1, static fn () => posix_kill(posix_getpid(), SIGTERM));
$loop->run();

SIGKILL, SIGSTOP and numbers outside the platform's range are refused (2301), and so is every signal without ext-pcntl (2300).

Suspensions

A suspension lets a function wait for the loop and keep an ordinary signature:

// In {main}: suspend() runs the loop until resume() or throw()
$suspension = $loop->createSuspension();
$loop->delay(0.1, static fn () => $suspension->resume('socket ready'));
echo $suspension->suspend(), "\n"; // "socket ready"

// In a fiber: suspend() parks the fiber, resume() continues it
$fiber = new Fiber(static function () use ($loop): void {
    $suspension = $loop->createSuspension();
    $loop->delay(0.1, static fn () => $suspension->resume(42));
    echo $suspension->suspend(), "\n"; // 42
});
$fiber->start();
$loop->run();

A suspension is single-use; one settled before suspend() returns at once. Code inside a loop callback suspends from a fiber: a suspension in {main} cannot run the loop from inside it (2002), and one the loop can no longer resume throws instead of returning null (2003).

Cancellation

use KaririCode\EventLoop\Cancellation\CancellationSource;
use KaririCode\EventLoop\Cancellation\CompositeCancellation;
use KaririCode\EventLoop\Cancellation\TimeoutCancellation;
use KaririCode\EventLoop\Exception\CancelledException;

$shutdown = new CancellationSource();           // cancelled by the worker's SIGTERM callback, say
$timeout = new TimeoutCancellation($loop, 0.2); // cancelled after 0.2 s; never keeps run() alive
$either = new CompositeCancellation($shutdown->token, $timeout->token);

$suspension = $loop->createSuspension();
$either->token->onCancel(static fn (CancelledException $reason) => $suspension->throw($reason));
$reply = $loop->delay(1.0, static fn () => $suspension->resume('reply')); // the slow operation

try {
    echo $suspension->suspend(), "\n";
} catch (CancelledException $e) {
    echo $e->getMessage(), "\n"; // [EL_2401] The operation was cancelled after 0.2s without finishing.
} finally {
    $loop->cancel($reply);
    $timeout->dispose();
    $either->dispose(); // unsubscribes from $shutdown, which lives on
}

A cancelled token runs every listener, even when one throws, then rethrows the first failure.

Metrics

use KaririCode\AsyncPrimitives\Monitor\InMemoryMetricsCollector;
use KaririCode\EventLoop\Integration\LoopMetricsBridge;
use KaririCode\EventLoop\LoopFactory;

$metrics = new InMemoryMetricsCollector();
$loop = new LoopMetricsBridge(LoopFactory::create(), $metrics); // the same EventLoop contract

$loop->repeat(1.0, $flush);
$metrics->snapshot()->gauges['eventloop.timer.active']; // 1

The bridge writes the gauges eventloop.timer.active, eventloop.stream.active and eventloop.signal.active and the counters eventloop.callback.registered and eventloop.run.started, counting what is registered through it (ADR-012).

Errors

Every exception is final, implements one kariricode/contract family and carries a code from block 2000–2499 (prefix EL) of the ecosystem registry:

Code Exception (family) When
2000 LoopMisuseException (Configuration) a suspension is resumed twice
2001 LoopMisuseException (Configuration) a suspension is suspended again or reused
2002 LoopMisuseException (Configuration) suspend() in {main} from inside a loop callback
2003 LoopMisuseException (Configuration) the loop stopped before a {main} suspension was resumed
2004 LoopMisuseException (Configuration) run() while the loop runs
2050 UnknownCallbackException (NotFound) enable() or reference() with an unknown id
2100 LoopMisuseException (Configuration) a negative, infinite or NAN time
2200 InvalidStreamException (Configuration) not an open stream
2300 UnsupportedSignalException (Configuration) a signal watcher without ext-pcntl
2301 UnsupportedSignalException (Configuration) SIGKILL, SIGSTOP or an out-of-range signal
2400 CancelledException (Runtime) a cancellation source was cancelled
2401 CancelledException (Runtime) a timeout cancellation ran out
2450 LoopMisuseException (Configuration) a composite cancellation with fewer than two tokens

Messages start with [EL_<code>] and never repeat input unquoted. Without an error handler, a callback's exception leaves run(); handleErrorsWith($handler) sends it to $handler instead.

Development

composer install
kcode init          # KaririCode Devkit 1.2.1: installs the pinned toolchain into .kcode/
composer check      # style, PHPStan (max), Psalm (1), complexity, tests, mutation
composer security   # composer audit (runtime and toolchain), secret scan

Documentation

Document Topic
SPEC-001 the contract and its behaviour
ADR-001 composition: scheduler, watchers, adapter
ADR-002 one registry for every callback
ADR-003 suspensions
ADR-004 cancellation
ADR-005 the global facade (superseded)
ADR-006 signals, EINTR, the error handler
ADR-007 no process-wide loop
ADR-008 exceptions, codes 2000–2499
ADR-009 quality gates
ADR-010 the native adapter only
ADR-011 one name per operation
ADR-012 metrics through kariricode/async-primitives
Quality report Spec V4.3.3 gates and deviations
Security policy reporting, threat model

License

MIT. See LICENSE.