kariricode / async-primitives
Async building blocks for PHP 8.4 below the event loop: retries with backoff, resource pools, time limits, in-process metrics, runtime detection and graceful worker shutdown.
Requires
- php: ^8.4
- kariricode/contract: ^2.11
- kariricode/exception: ^2.0.2
- psr/clock: ^1.0
Requires (Dev)
None
Suggests
- ext-pcntl: Signal handling in Process\WorkerRunner and interruption in Timeout\TimeoutExecutor
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-27 19:14:46 UTC
README
The building blocks the KaririCode async stack shares, for PHP 8.4: retries
with backoff (and kariricode/contract's RetryPolicy), resource pools, time
limits, in-process metrics, runtime detection and graceful shutdown on
signals. There is no event loop here — everything works in plain PHP, in
PHP-FPM or a CLI worker — and kariricode/eventloop,
kariricode/async and kariricode/queue build on it.
Installation
composer require kariricode/async-primitives
Requires PHP 8.4. ext-pcntl is suggested: without it a time limit cannot interrupt the code it guards, and no signal is caught.
Retries
use KaririCode\AsyncPrimitives\Retry\ExponentialBackoff; use KaririCode\AsyncPrimitives\Retry\RetryExecutor; $retry = new RetryExecutor(new ExponentialBackoff(baseDelayMs: 100, maxDelayMs: 2_000)); $rates = $retry->execute(static fn (): array => $client->fetchRates(), maxAttempts: 4);
Which failures are retried: a kariricode/contract Runtime failure, and any
exception from outside the contract (PDOException, a client library's
RuntimeException). Never retried: the other contract families
(Validation, Configuration …), engine errors such as TypeError, and
LogicException. Pass isRetriable: to decide yourself.
What the caller receives: a failure that is not retried propagates as it
was thrown, so an HTTP edge still maps its family; a retriable failure that
outlasts the attempts ends in RetryFailedException (1000), with the last
failure as getPrevious(). The waits block the process (usleep()).
BackoffRetryPolicy implements KaririCode\Contract\Resilience\RetryPolicy,
and RetryExecutor::run() drives any implementation of that port. A circuit
breaker's CallNotPermittedException::$retryAfterSeconds stretches the
wait.
use KaririCode\AsyncPrimitives\Retry\BackoffRetryPolicy; use KaririCode\AsyncPrimitives\Retry\RetryExecutor; // 3 attempts, exponential backoff with full jitter $rates = RetryExecutor::run(static fn (): array => $client->fetchRates(), BackoffRetryPolicy::default());
Backoff strategies
All delays are whole milliseconds, never above maxDelayMs; $attempt is
the number of calls that already failed.
| Strategy | Delay |
|---|---|
FixedBackoff(250) |
250 every time |
LinearBackoff(200, 2_000) |
200, 400, 600 … up to 2 000 |
ExponentialBackoff(100, 2.0, 30_000, 0.1) |
100, 200, 400 … up to 30 000, minus up to 10 % jitter |
JitteredBackoff(100, 30_000, JitterMode::Full) |
random(0, cap), cap = 100 × 2^(attempt − 1) |
JitterMode::Equal |
cap/2 + random(0, cap/2) |
JitterMode::Decorrelated |
random(base, previous × 3), restarting at attempt 1 |
Jitter draws from an injectable Random\Randomizer; a seeded engine makes it
reproducible in tests.
Time limits
use KaririCode\AsyncPrimitives\Timeout\TimeoutConfiguration; use KaririCode\AsyncPrimitives\Timeout\TimeoutExecutor; $timeouts = new TimeoutExecutor(new TimeoutConfiguration(defaultSeconds: 5.0, message: 'warehouse report')); $report = $timeouts->execute(static fn (): array => $warehouse->buildReport());
- With ext-pcntl, outside a fiber, a SIGALRM interrupts the operation:
TimeoutException::exceeded()(1200). The alarm works in whole seconds (a 0.3 s limit fires after 1 s); the previous handler and any enclosing alarm are restored. - Without pcntl, or inside a fiber, nothing can be interrupted. An operation
that returns past its limit fails with
TimeoutException::completedLate()(1201): its effects have happened, so do not blindly retry side-effecting work on it.$e->operationCompletedtells the two cases apart.
PromiseTimeout::withTimeout($operation, 2.0) does the same for one call.
Resource pools
use KaririCode\AsyncPrimitives\Pool\GenericPool; use KaririCode\AsyncPrimitives\Pool\PoolConfiguration; $pool = new GenericPool( static fn (): Connection => Connection::open($dsn), // implements PoolableResource new PoolConfiguration(minSize: 2, maxSize: 10, maxIdleTimeSec: 300), ); $connection = $pool->acquire(); try { $connection->query('SELECT 1'); } finally { $pool->release($connection); }
release()resets the resource at once (rolling back what the borrower left open) and closes it whenreset()fails; a secondrelease()of the same resource does nothing.acquire()closes idle resources that waited longer thanmaxIdleTimeSec(0 keeps them) or fail the health check, and never waits: beyondmaxSizeit throwsPoolExhaustedException(1100).$pool->statisticscounts acquisitions, releases, creations, closes, idle evictions, failed health checks and exhaustion.
Metrics
use KaririCode\AsyncPrimitives\Monitor\InMemoryMetricsCollector; $metrics = new InMemoryMetricsCollector(); $metrics->increment('orders.imported'); $metrics->recordLatency('orders.import', 12.5); $metrics->snapshot()->counters; // ['orders.imported' => 1] $metrics->tracker('orders.import')?->p99(); // 12.5
LatencyTracker keeps the last 1 024 durations of an operation (nearest-rank
percentiles); ThroughputCalculator counts operations per second over a
sliding window. Both read time from an injectable PSR-20 clock.
Workers and signals
use KaririCode\AsyncPrimitives\Process\WorkerRunner; $runner = new WorkerRunner(sleepMs: 100); $runner->run(static function (int $iteration) use ($queue): bool { $queue->processNext(); return true; // false stops the loop });
The runner stops between ticks on SIGTERM or SIGINT (GracefulShutdown,
ext-pcntl), on requestShutdown(), or after maxIterations.
SignalHandler::on($signal, $listener) lets several listeners share a
signal; it refuses SIGKILL and SIGSTOP with ProcessSignalException
(1400).
One entry point
ArfaBridge combines the pieces for resilient I/O: retries, a limit per
attempt and metrics per operation.
use KaririCode\AsyncPrimitives\Integration\ArfaBridge; use KaririCode\AsyncPrimitives\Retry\ExponentialBackoff; use KaririCode\AsyncPrimitives\Retry\RetryConfiguration; use KaririCode\AsyncPrimitives\Timeout\TimeoutConfiguration; $bridge = new ArfaBridge(new RetryConfiguration(new ExponentialBackoff(), maxAttempts: 3), new TimeoutConfiguration(2.0)); $rates = $bridge->execute('rates.fetch', static fn (): array => $client->fetchRates()); $bridge->metrics->snapshot()->counters; // ['rates.fetch.success' => 1]
Errors
Every exception is final, implements one kariricode/contract family and carries a code from block 1000–1499 (prefix AP) of the ecosystem registry:
| Code | Exception (family) | When |
|---|---|---|
| 1000 | RetryFailedException (Runtime) |
retriable failures used up the attempts |
| 1001 | RetryFailedException (Runtime) |
every operation of a fallback chain failed |
| 1100 | PoolExhaustedException (Runtime) |
the pool is at maxSize |
| 1200 | TimeoutException (Runtime) |
interrupted at the limit |
| 1201 | TimeoutException (Runtime) |
finished past the limit, not interrupted |
| 1400 | ProcessSignalException (Configuration) |
a signal handler could not be installed |
| 1450 | InvalidConfigurationException (Configuration) |
a configuration value breaks its rule |
Messages start with [AP_<code>] and never repeat input.
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 | architecture and behaviour |
| ADR-001 | dependencies |
| ADR-002 | readonly classes and private(set) |
| ADR-003 | position below the async stack, runtimes |
| ADR-004 | the contract's retry policy, what the retry loop returns |
| ADR-005 | package name |
| ADR-006 | time and randomness |
| ADR-007 | exceptions, codes 1000–1499 |
| ADR-008 | quality gates |
| ADR-009 | time limits |
| ADR-010 | pool lending rules |
| Quality report | Spec V4.3.3 gates and deviations |
| Security policy | reporting, threat model |
License
MIT. See LICENSE.