SugarAsync
Shared async vocabulary for ReactPHP
Shared async vocabulary unifying ReactPHP usage across the SugarCraft monorepo. A CancellationSource owns the cancellation flag and hands out read-only CancellationTokens; Subscription handles make disposal uniform; AsyncOps covers timeouts, deadlines, retry with jittered backoff, single-flight coalescing, debounce, throttle and fan-in. Beside the promise helpers sit loop-free blocking engines, process helpers that run and pump child processes with deadlines and byte caps, and a bounded TTL AsyncCache that coalesces in-flight loads.
Install
composer require sugarcraft/sugar-async
Requires PHP 8.3 or newer, react/event-loop ^1.6, react/promise ^3.3 and sugarcraft/sugar-core, which this package pins to dev-master. A project on minimum-stability: stable may fail to resolve that require, so add "minimum-stability": "dev" with "prefer-stable": true to the consuming root manifest.
Quickstart
use SugarCraft\Async\{AsyncOps, CancellationSource};
$source = CancellationSource::new();
// Attach a cancellation callback
$source->token()->onCancel(function (): void { echo "Cancelled!\n"; });
$source->cancel(); // prints "Cancelled!"
// Timeout wrapper
$loop = \React\EventLoop\Loop::get();
$somePromise = \React\Promise\resolve('eventually');
$promise = AsyncOps::withTimeout($somePromise, 5.0, $loop);
// Retry with backoff
$attempts = 0;
$promise = AsyncOps::retry(
function () use (&$attempts) {
if (++$attempts < 3) {
return \React\Promise\reject(new \RuntimeException('transient failure'));
}
return \React\Promise\resolve('succeeded on attempt ' . $attempts);
},
attempts: 3,
baseBackoffSeconds: 0.5,
);
What's in the box
onRetry: and pendingNotice hooks, and the disposal pass behind Subscriptions::unsubscribe()) into the host's own diagnostics. setLogSink(null) restores the error_log() default, which writes to stderr under stock PHP and can corrupt a render in progress.Retry::bounded() runs a result-driven retry loop with every wait clamped to the remaining budget, with no event loop involved. Retry::nap() is a sleep re-armed after EINTR. Retry::reconnect() redials until success or cancellation. ChildPump::drain() runs one select loop over all pipes and answers a DrainResult. The AsyncOps forwarders delegate to them, and Backoff carries the schedule.ChildRun runs one child with a deadline and a per-stream byte cap, blocking through run() or on the loop through launch(). ChildPump reads its pipes to EOF without one wedged pipe blocking another. A timed-out child is terminated through a TERM, grace, KILL ladder.ForkChannel, and settles with the child's exit status. Requires ext-pcntl and ext-posix; without them it refuses up front.Concepts
The library has three ways to wait, and the choice decides which helper you call. Promise helpers (AsyncOps::withTimeout(), retry(), debounce()) return promises and arm their timers on a React\EventLoop\LoopInterface, which defaults to the shared loop. Blocking engines (Retry::bounded(), Retry::nap(), ChildPump::drain()) run a select or sleep loop of their own and never touch the event loop, so they suit a CLI that has no loop running. Await::until() is the one place a CLI entry point may block on the loop.
Cancellation is split in two. A CancellationSource is the writer and a CancellationToken is the reader. You pass the token down to every operation and keep the source where you decide to stop. Every registration returns a Subscription, so a component can unhook its callback when it is torn down.
Process helpers are built on the same vocabulary. ChildRun never hands argv to a shell, except through commandLine(), which is the one explicit exception. The default deadline and per-stream cap are ten seconds and 8 MiB.
Tasks and recipes
Cancel a retry from the UI. Pass the token to retry(), and cancelling the source aborts the attempts that have not started yet.
$source = CancellationSource::new();
$promise = AsyncOps::retry(
static fn () => fetchRemote(),
attempts: 5,
baseBackoffSeconds: 0.2,
token: $source->token(),
maxTotalSeconds: 10.0,
);
// Later, from a key handler:
$source->cancel();
Run a command with a deadline. ChildRun returns a ChildResult that reports how the child ended.
use SugarCraft\Async\ChildRun;
$r = ChildRun::new(['git', 'status', '--porcelain'])
->withTimeout(5.0)
->withMaxBytes(1_048_576)
->run();
if ($r->timedOut()) {
// the child was terminated after the deadline
} elseif ($r->succeeded()) {
// $r->stdout holds the captured output
}
Cache a slow lookup with a TTL. AsyncCache::fetch() coalesces concurrent loads for one key and, when enabled, keeps serving the last good value if a reload fails.
use SugarCraft\Async\AsyncCache;
$cache = AsyncCache::new(ttlSeconds: 30.0, serveStaleOnError: true, maxEntries: 200);
$cache->fetch('weather:Berlin', static fn () => loadWeather('Berlin'))
->then(static fn (array $w) => render($w));
Debounce a search box. AsyncOps::debounce() returns a Debounced handle, so each keystroke invokes it and only the last call inside the window runs.
$search = AsyncOps::debounce(static fn (string $q) => runSearch($q), 0.3);
$search('ma');
$search('mai');
$search('main'); // only this call runs, after 0.3 s of silence
Fan in several requests. all() resolves once every promise has settled, and race() adopts the first outcome.
AsyncOps::all([$a, $b, $c])->then(static fn (array $results) => print_r($results));
AsyncOps::race([$primary, $mirror])->then(static fn ($first) => use_result($first));
Configuration and options
There is no global configuration. Each helper takes its options as named arguments, and the constructor-style factories take the same knobs. The defaults below are the ones the source uses.
| Option | Where | Default | Effect |
|---|---|---|---|
attempts | AsyncOps::retry() | 3 | Total runs, including the first. Not a retry count. |
baseBackoffSeconds and jitter | AsyncOps::retry() | 0.1 and 0.0 | Base delay for the exponential schedule, and the jitter fraction applied to it. |
maxTotalSeconds | AsyncOps::retry() | null (no budget) | Overall budget. Exceeding it rejects with a TimeoutException. |
trailing | AsyncOps::throttle() | false | When true, the last suppressed call fires at the end of the window. |
ttlSeconds | AsyncCache::new() | 60.0 | How long a loaded value counts as fresh. |
serveStaleOnError | AsyncCache::new() | false | Serve the last value when a reload fails, instead of rejecting. |
maxEntries | AsyncCache::new() | null (no cap) | Caps stored keys. An adopt past the cap evicts the least-recently-stored entry. |
| Deadline and byte cap | ChildRun, ChildPump | 10 seconds and 8 MiB per stream | Set with withTimeout() and withMaxBytes() on ChildRun. On the pump, withDeadline() takes an absolute monotonic time, and withCap() sets the byte cap. |
MAX_FRAME_BYTES | ForkChannel | 16 MiB | Largest frame a channel will send or accept. A larger length prefix is treated as a broken peer. |
setLogSink() | AsyncOps | error_log() | Destination for swallowed-failure notices. |
Architecture
AsyncOps is a facade. Its methods forward to focused classes: Timeouts holds the timer machinery for withTimeout() and withDeadline(), Retry holds the waiting engines and Backoff holds the schedule, Debounced and Throttled hold the timer state behind the two rate limiters, and Pending carries the progress hook.
Child processes take two paths. ChildRun::run() drives ChildPump, a stream_select() loop over every open pipe, so a child that fills its stderr buffer cannot wedge a read of stdout. ChildRun::launch() builds a ChildRunLaunch that does the same work as loop callbacks. A periodic check, rather than a readable stream, observes the exit, and a child that is still running when its kill budget is spent is reaped on a later tick, so the loop never blocks on proc_close().
ForkedTask connects parent and child with a ForkChannel, a socket pair that carries 4-byte big-endian length-prefixed frames. The parent reads frames on the loop, and it kills and reaps the child when the token fires, the deadline passes or the collector throws.
Examples
examples/async-operations.phpcovers the timer-backed helpers on a private loop:debounce()andthrottle()return invokable handles, andall(),race()andboundWait()are demonstrated alongside them.examples/cache.phpshowsAsyncCacheas cache-aside with coalescing, a monotonic clock seam that needs no sleeps, serve-stale-on-error and the bounded entry cap.examples/cancellation.phpwalks the cancellation vocabulary: sources, tokens and disposable registrations, plus the rule that cancellation is not an error. Every promise there settles synchronously, so the example runs without an event loop.
Run them from the library directory with php examples/cache.php and the same pattern for the others, after composer install.
Testing
composer install && vendor/bin/phpunit
The suite runs from tests/bootstrap.php, which calls SugarCraft\Testing\LoopPin::pinStableClock(). That call matters because ext-uv computes timer deadlines against a clock refreshed once per loop iteration, so a timer armed after a long synchronous idle is already overdue. ExamplesTest lints and runs every example, and ReadmeSnippetsTest does the same for every PHP fence in the README. Tests that arm timers should assert scheduled state, using isPending() on the timer handles, and not wall-clock time.
ProgramSimulator from sugar-testing does not drive timers, because it pumps stdin only. Promises waiting on the shared \React\EventLoop\Loop::get() loop never settle under it, so drive async TUI flows with a real loop and a guard timer.
Troubleshooting
A rejected promise exits 0 with no message. ReactPHP does not print unhandled rejections. Attach a rejection handler in examples and tests, with then(null, ...) or otherwise().
A timeout never fires. The loop must run. Call $loop->run() on the loop you passed in, or let your host program's loop drive the timers this library arms.
A singleFlight or AsyncCache behaves oddly after a fork. Its state lives in one process. Create these objects after pcntl_fork(), in the process that will use them.
A ForkedTask call throws at once. It needs ext-pcntl and ext-posix, and it refuses up front with a RuntimeException rather than returning a promise that can never settle.
Failure notices interleave with the terminal output. The default sink writes to stderr. Install a sink with AsyncOps::setLogSink() to route notices into your own diagnostics.
Composer resolves an old candy-async. The package was renamed to sugarcraft/sugar-async in the 2026-10 rename, and no compatibility aliases were shipped. Update the use statements.
Upstream mapping
sugar-async is an original SugarCraft design, with no one-to-one Go counterpart. Some of its shapes are borrowed from other ecosystems, and the source cites them where they apply.
| SugarCraft type | Borrowed shape |
|---|---|
Cancellable, CancellationSource, CancellationToken | Go's context.Context Done channel, and the source and token split of .NET's CancellationTokenSource |
Subscription, CallbackSubscription | RxJS's Subscription, and Node's EventEmitter.removeListener |
Subscriptions | RxJS's Subscription group |
ForkChannel | The socketpair frame channels used by candy-code's child-process relays and candy-git-server's WorkerFork. This is an in-family shape, not an upstream one. |
Caveats
Every stateful surface is per-process. That covers a singleFlight closure's in-flight map, an AsyncCache store and its coalesced flights, a Debounced handle's pending burst, a Throttled handle's cooldown and queued trailing call, and a CancellationSource's registered callbacks. Sharing one across a fork boundary is unsafe. Promises settled in one process never reach the other, and a callback registered before the fork fires in whichever process cancels.
Changelog and versioning
There is no tagged release yet, so the package follows the dev-master track of the monorepo. The 2026-10 rename to sugar-async is the one name change on record. Watch the repository history for changes until a first release is cut.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Original SugarCraft design. No one-to-one Go counterpart.
API
| Class | Method | Description |
|---|---|---|
| CancellationSource | new(): self | Factory: create a new source with its own token |
| CancellationSource | token(): CancellationToken | Returns the read-only token for this source |
| CancellationSource | cancel(): void | Request cancellation. Idempotent. |
| CancellationSource | isCancelled(): bool | Returns true if cancel() has been called |
| CancellationSource | onCancel(callable): Subscription | Registers a cleanup callback on the source's own token (CancellationSource implements Cancellable); same fire-once, handle-un-registers semantics as CancellationToken::onCancel(). |
| CancellationToken | none(): self | Shared never-canceled sentinel — the safe default for optional token parameters; its onCancel() returns a born-spent handle and retains nothing |
| CancellationToken | isCancelled(): bool | Returns true if the source has been canceled |
| CancellationToken | onCancel(callable): Subscription | Register a callback; fires immediately if already canceled (the handle is then born spent). Returns a Subscription — unsubscribe() before the token fires un-registers the callback, which is the leak guard when a token outlives the operation that registered on it. |
| Cancellable | isCancelled() · cancel() · onCancel(callable) | Interface CancellationSource implements — type against it when a component must be cancellable |
| Subscription | unsubscribe(): void | Interface: disposes the registration; the removal closure runs at most once, from unsubscribe() |
| Subscription | isActive(): bool | Interface: false once unsubscribed, or born spent |
| CallbackSubscription | of(Closure): self | Live handle over a removal closure — the concrete Subscription onCancel() returns |
| CallbackSubscription | settled(): self | Born-spent handle (the callback already fired immediately); unsubscribe() is a no-op |
| Subscriptions | new(): self | Empty composite collection |
| Subscriptions | of(Closure): Subscription | Public glue: mints a standalone disposal handle from any cleanup closure (timers, listeners, temp-file owners) |
| Subscriptions | compose(Subscription ...): self | Combine multiple subscriptions into one atomic handle |
| Subscriptions | add(Subscription): void | Append one handle to the composite — the @internal path compose() builds through: on an already-unsubscribed composite an incoming handle is disposed immediately, and self-composition is ignored |
| Subscriptions | unsubscribe(): void | Dispose all underlying subscriptions |
| Subscriptions | isActive(): bool | Returns false after unsubscribe() |
| Subscriptions | count(): int · isEmpty(): bool | Size of the composite |
| Subscriptions | disposeAll(): void | @internal teardown worker behind unsubscribe(): snapshot-and-clear first, then dispose every handle; a throwing unsubscribe() is logged and never propagated — error_log() by default, redirectable via AsyncOps::setLogSink() (the same hook-failure contract as CancellationToken::fireCallbacks()) |
| AsyncOps | setLogSink(?callable $sink): void | The diagnostics door for the four swallowed-failure sites (cancellation callbacks, retry onRetry:, pendingNotice hooks, the Subscriptions::unsubscribe() disposal pass): route the notices into host logging; null restores the error_log() default |
| AsyncOps | withTimeout(PromiseInterface, float, ?LoopInterface, ?string label): PromiseInterface | Wrap a promise with a timeout; rejects with TimeoutException (seconds and optional label readable on it); null loop uses the shared one |
| AsyncOps | withDeadline(PromiseInterface, float, ?LoopInterface, ?callable onTimeout, ?string label): PromiseInterface | Ceiling on the remaining budget: on expiry rejects with TimeoutException and cancels the inner promise; late results are dropped, never adopted |
| AsyncOps | cancellable(PromiseInterface, ?CancellationToken, ?callable onCancel): PromiseInterface | Token guard: cancellation rejects with OperationCancelledException and runs the onCancel hook; the registration auto-un-registers when the inner promise settles — no loop parameter |
| AsyncOps | singleFlight(callable keyFn, callable worker): callable | Coalesces concurrent same-key calls into one in-flight worker — every joined caller receives the outcome; the slot frees on settle so the next call may start a fresh flight; the join is not abandonable by design (wrap it in cancellable() when the wait itself must be abandonable); stateful — never share across pcntl_fork |
| AsyncOps | retry(operation, attempts: 3, baseBackoffSeconds: 0.1, token:, maxTotalSeconds:, jitter: 0.0, loop:, now:, onRetry:): PromiseInterface | Retries a thunk with exponential backoff; a canceled token stops the remaining attempts (reject OperationCancelledException); maxTotalSeconds rejects with TimeoutException on budget exhaustion; onRetry fires when each backoff is scheduled and its errors are never propagated (they route through the log sink) |
| AsyncOps | retryBounded(operation, shouldRetry, budgetMs, backoff) | Forwarder to Retry::bounded() — blocking, result-driven, every wait clamped to the remaining budget |
| AsyncOps | nap(int $owedMicros) | Forwarder to Retry::nap() — a sleep that is re-armed after EINTR |
| AsyncOps | reconnect(dial, backoff, token:, loop:, onRetry:) | Forwarder to Retry::reconnect() — redials until success or cancellation; success ends the cycle |
| AsyncOps | drain(pipes, deadline, maxBytes) | Forwarder to ChildPump::drain() — one select loop over all pipes, returning a DrainResult |
| AsyncOps | all(iterable): PromiseInterface | Fan-in on every promise; empty input resolves to [] |
| AsyncOps | race(iterable): PromiseInterface | Adopts the first settled outcome; empty input throws InvalidArgumentException at the call site |
| AsyncOps | pendingNotice(PromiseInterface, float, callable onPending, ?LoopInterface): PromiseInterface | Fires the required advisory hook once if the promise is still unsettled after N seconds; the wait continues and the inner is never canceled |
| AsyncOps | boundWait(PromiseInterface, float, ?LoopInterface, ?string label): PromiseInterface | Bounded wait: still unsettled after N seconds rejects the wait with a TimeoutException naming (still pending) while the inner runs on |
| AsyncOps | debounce(callable, float, ?LoopInterface, ?CancellationSource): Debounced | Debounce wrapper returning a Debounced handle; only the last call fires after the window; optional source cancels it |
| AsyncOps | throttle(callable, float, ?LoopInterface, bool trailing): Throttled | Throttle wrapper returning a Throttled handle; fires at most once per interval, trailing edge opt-in |
| Debounced | __invoke(...) · flush() · isPending() · unsubscribe() · isActive() | Handle AsyncOps::debounce() returns: each invoke returns a promise — the scheduled call resolves with the result (rejects if the work throws), superseded calls resolve null; flush() runs the pending burst immediately and returns that PromiseInterface (give it a rejection handler, or a rejecting burst dies silently); unsubscribe() drops the burst (its promise resolves null) and spends the handle — later calls answer null without arming timers |
| Throttled | __invoke(...) · flush() · isPending() · unsubscribe() · isActive() | Handle AsyncOps::throttle() returns; suppressed calls resolve null, and with trailing: true the last suppressed call fires at window end consuming a fresh window (the once-per-window cap holds at every edge, not only the first); flush() runs a queued trailing call immediately and ends the cooldown — void, the outcome arrives on the suppressed call's own promise; unsubscribe() drops any queued trailing call (its promise resolves null) |
| Suspended | new(callable resume, mixed state = null) · resume(): ?Closure · state(): mixed | Paused command as data; resume() yields the Cmd closure exactly once (a second call returns null) |
| AsyncCache | new(ttlSeconds: 60.0, serveStaleOnError: false, ?clock, ?maxEntries): self | TTL'd async memo — loop-free, it arms no timers; injectable clock for tests; optional stored-key cap that evicts the least-recently-stored value (>= 1 when set) |
| AsyncCache | fetch(string key, callable loader): PromiseInterface | Fresh entry resolves instantly; otherwise the loader starts — concurrent same-key fetches coalesce; a synchronous throw counts as a failed load |
| AsyncCache | peek(string): mixed · has(string): bool · isFresh(string): bool | Render-path reads: last stored value (fresh or stale), a value is held, a held value is within TTL |
| AsyncCache | isLoaded(string): bool · ageSeconds(string): ?float | Fresh OR in-flight (the loading-indicator read); monotonic age of the held value, past the TTL on purpose |
| AsyncCache | invalidate(string): void · clear(): void | Drop a key / every entry and supersede in-flight loads — displaced arrivals resolve their own callers without adopting into the store |
| AsyncCache | count() · keys() · ttlSeconds() · servesStaleOnError() · maxEntries() · withTtl() · withServeStaleOnError() · withMaxEntries() | Introspection over stored keys (fresh or stale, insertion order) and settings; the with* setters return new handles over the same store |
| OperationCancelledException | (extends RuntimeException) | Rejection when a token-guarded operation is canceled — cancellable(), and a token canceled mid-retry — and when the caller abandons a wait wrapper: cancel() on a withTimeout(), withDeadline(), retry(), pendingNotice() or boundWait() handle rejects with this while the inner operation keeps running |
| TimeoutException | seconds(): ?float · label(): ?string | Rejection from withTimeout(), withDeadline(), boundWait() expiry, and retry()'s maxTotalSeconds budget; carries the budget and optional label for message building |
Only methods declared in sugar-async/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Async
AsyncCache final class
Loop-free async cache-aside primitive (needs no event loop: arms no timers): TTL freshness, concurrent-loader dedupe, optional serve-stale-on-error.
| Method | Summary |
|---|---|
static new(float $ttlSeconds = 60.0, bool $serveStaleOnError = false, ?callable $clock = null, ?int $maxEntries = null): self | |
ttlSeconds(): float | Freshness window for cache hits (seconds). |
servesStaleOnError(): bool | |
maxEntries(): ?int | The stored-key cap, or null when unbounded (the default). |
generation(): int | Epoch of the store: advanced by every invalidate() and clear(). A caller that starts a load records the epoch first and discards the result when the epoch has moved on, the same guard phlix's stores hand-rolled as a generation counter. Shared by every handle over the store. |
count(): int | Number of stored values, fresh or stale. In-flight loads are not stored. |
keys(): array | Stored keys (fresh or stale), least-recently-stored first. |
isLoaded(string $key): bool | True when the key is fresh OR a load is in flight — the loading-indicator read. |
ageSeconds(string $key): ?float | Monotonic age of the stored value, fresh or stale; null when none is held. Reads past the TTL on purpose: stale-serving and age reporting both consult peek semantics, not freshness. |
withTtl(float $ttlSeconds): self | |
withServeStaleOnError(bool $serveStaleOnError): self | |
withMaxEntries(?int $maxEntries): self | |
fetch(string $key, callable $loader): PromiseInterface | Cache-aside load: answer from a fresh entry, join the in-flight load, or start one. |
peek(string $key): mixed | Last stored value for a key, fresh or stale — the render-path read. Null covers both "never loaded" and "loaded as null"; has() tells them apart. |
has(string $key): bool | True when a value (fresh or stale) is held for the key. |
isFresh(string $key): bool | True when a value is held and its TTL has not elapsed. |
invalidate(string $key): void | Drop a key and supersede any in-flight load: the next fetch starts fresh, and the displaced arrival resolves its own callers without adopting into the store. |
clear(): void | Drop every entry and supersede every in-flight load. |
AsyncOps final class
Static helpers for async operations on top of ReactPHP.
| Method | Summary |
|---|---|
static setLogSink(?callable $sink): void | Redirect (or restore) the destination of swallowed-failure notices. |
static withTimeout(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?string $label = null): PromiseInterface | Wrap a promise with a timeout. If the timeout fires before the promise settles, the returned promise rejects with TimeoutException. The inner promise is NOT cancelled and keeps running to completion. The wait itself is abandonable: cancel() on the returned promise releases the timer and rejects with OperationCancelledException — abandon, not abort (stopping the work is withDeadline()'s contract). When the work itself must stop as the wait ends — a hung I/O holding its consumer's in-flight gate open forever — use withDeadline(), which cancels the inner operation on both expiry and abandonment. |
static withDeadline(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?callable $onTimeout = null, ?string $label = null): PromiseInterface | Wrap a promise with a deadline that CANCELS the inner promise when it fires; withTimeout() by contrast lets the inner run on. |
static cancellable(PromiseInterface $promise, ?CancellationToken $token, ?callable $onCancel = null, ?string $label = null): PromiseInterface | Bind a promise to a CancellationToken: cooperative, two-sided, immediate cancellation. |
static singleFlight(callable $keyFn, callable $worker): callable | Coalesce concurrent invocations of an async worker by key. |
static retry(callable $operation, int $attempts = 3, float $baseBackoffSeconds = 0.1, ?CancellationToken $token = null, ?float $maxTotalSeconds = null, float $jitter = 0.0, ?LoopInterface $loop = null, ?callable $now = null, ?callable $onRetry = null): PromiseInterface | Retry a callable $attempts times in total with exponential backoff. |
static all(iterable $promises): PromiseInterface | Fan-in: resolve with every value once ALL promises resolve, preserving keys; reject with the FIRST error the moment one arrives. Non-promise entries are treated as already-resolved values. An empty set resolves with []. These combinators are the package's own promise vocabulary: callers need all() and race() here and never reach past this package for a fan-in primitive. |
static race(iterable $promises): PromiseInterface | Fan-in: settle with whichever settles first — value or error. The empty set is a refusal, not a forever-pending promise — that shape renders as a screen frozen with no error to show. |
static pendingNotice(PromiseInterface $promise, float $seconds, callable $onPending, ?LoopInterface $loop = null): PromiseInterface | Announce slowness without interrupting the wait. If $promise is still pending after $seconds, $onPending runs ONCE (a "taking longer than expected" spinner hint). The returned promise tracks the inner one — the notice neither cancels nor abandons the work, and the E646 rule holds: this is an advisory tick, never a wall-clock killer of user-paced operations. A hook that throws is logged, never propagated. |
static boundWait(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?string $label = null): PromiseInterface | Bound the wait without stopping the work. If $promise is still pending after $seconds, the returned promise rejects with a TimeoutException whose message names (still pending) — the inner operation keeps running, like under withTimeout(). These are the bounded-wait semantics for user-paced operations: this library puts no blanket wall-clock timeout on operations whose pace belongs to the user. To announce a slow wait instead of ending it, use pendingNotice(). |
static debounce(callable $fn, float $seconds, ?LoopInterface $loop = null, ?CancellationSource $source = null): Debounced | Wrap a callable with debounce — only the last call within the window fires, and only after $seconds have elapsed since it. |
static throttle(callable $fn, float $seconds, ?LoopInterface $loop = null, bool $trailing = false): Throttled | Wrap a callable with throttle — the function fires at most once every $seconds, regardless of call frequency. Leading-edge by default: calls inside the window answer null. With $trailing true, the LAST suppressed call fires when the window closes instead, and that fire consumes a fresh window — the cap holds at every edge. |
static retryBounded(callable $operation, callable $shouldRetry, int $budgetMs, Backoff $backoff, ?callable $now = null, ?callable $sleep = null): mixed | Synchronous poll-until-final under a wall-clock budget. Forwards to Retry::bounded() so callers that already import AsyncOps need no second entry point; unlike retry() this blocks and keys off the result (not a rejection). |
static nap(int $owedMicros, ?callable $sleeper = null, ?callable $now = null, ?callable $onBeat = null): void | Pay a sleep debt that survives signal interruption. Forwards to Retry::nap(). |
static reconnect(callable $dial, Backoff $backoff, ?CancellationToken $token = null, ?LoopInterface $loop = null, ?callable $onRetry = null): PromiseInterface | Redial until a connection succeeds or the token fires. Forwards to Retry::reconnect(). |
static drain(array $pipes, float $deadline, int $maxBytes, ?callable $clock = null, bool $stopAtCap = false, array $discard = [], ?callable $running = null): DrainResult | Drain several child pipes against one deadline. Forwards to ChildPump::drain(). |
static deferred(\Closure $fn, ?LoopInterface $loop = null): PromiseInterface | Run $fn on the next loop tick instead of inline, answering its result as a promise. Use it to take a slow or re-entrant step off the caller's stack: the caller gets control back now, and $fn runs once the current callback has returned. |
Await final class
Synchronous wait on a promise: drive the loop until the promise settles or a budget elapses, then return its value or rethrow its rejection.
| Method | Summary |
|---|---|
static until(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null): mixed |
Backoff final class
One pure backoff law: exponential ceiling, optional full jitter, and a server-supplied hint that outranks both.
| Method | Summary |
|---|---|
static new(float $baseMs, float $factor = 2.0, ?int $capMs = null): self | |
withJitter(?callable $rng = null): self | Wait a uniform draw over [0, ceiling] instead of the ceiling itself. |
withoutJitter(): self | Back to the deterministic ceiling. |
serverHint(?float $seconds): self | The server's own instruction (seconds, e.g. a parsed Retry-After). While set, forAttempt() returns it un-jittered and un-capped by $capMs — clamping a server's instruction is the caller's policy, applied before it gets here. Null clears it. |
withAttempts(?int $attempts): self | Total tries allowed; null (the default) retries forever. See allows(). |
allows(int $n): bool | Whether a retry may follow the $n-th failure: with N total attempts the N-th failure is final. Always true for the null (forever) budget. |
ceiling(int $n): int | The deterministic ceiling after the $n-th failure, ms. 0 for $n < 1. |
forAttempt(int $n): int | How long to wait after the $n-th failure, in whole milliseconds: the server hint if one is set, else the ceiling — drawn down by full jitter when enabled. |
secondsForAttempt(int $n): float | forAttempt() in seconds. |
CallbackSubscription final class
Subscription handle backed by a single removal closure.
| Method | Summary |
|---|---|
static of(\Closure $onDispose): self | A live handle whose registration still awaits disposal. |
static settled(): self | A spent handle: what the caller gets when the callback has already fired immediately, so the subscription never lived here. Unsubscribing is a no-op, and isActive() reports false from birth. |
unsubscribe(): void | |
isActive(): bool |
Cancellable interface
Contract for a component that can be cancelled.
| Method | Summary |
|---|---|
isCancelled(): bool | Returns true if cancel() has been called. |
cancel(): void | Requests cancellation. Idempotent — calling multiple times has no additional effect. All registered onCancel callbacks fire in registration order, exactly once. |
onCancel(callable $callback): Subscription | Register a callback to fire when cancellation is requested. The callback receives no arguments. A throwing callback is logged and never propagated — see CancellationToken::fireCallbacks() for the one hook-failure contract shared across this library. Returns a handle that removes the registration while it is still pending. |
CancellationSource final class
Owns the mutable cancellation state and hands consumers the token view; triggering belongs by convention to this source's cancel().
| Method | Summary |
|---|---|
__construct() | |
static new(): self | Factory for idiomatic construction. |
token(): CancellationToken | Returns the read-only token for this source. |
isCancelled(): bool | The state lives in the token (single source of truth): a cancellation raised through the token's internal paths is visible here too, so the source and its token can never disagree on isCancelled(). |
cancel(): void | Requests cancellation. Idempotent — calling multiple times is a no-op. All callbacks registered on the token fire exactly once, in order. A throwing callback is logged and never propagates from here. |
onCancel(callable $callback): Subscription | Register a cancellation callback on this source's token. Part of the Cancellable contract — the contract makes it public. Returns the removal handle; see CancellationToken::onCancel(). |
CancellationToken final class
Read-only view of a cancellation state.
| Method | Summary |
|---|---|
__construct(CancellationSource $source) | |
static none(): self | The shared never-cancelled token. |
isCancelled(): bool | Returns true if the source has been cancelled. |
onCancel(callable $callback): Subscription | Register a callback to fire when cancellation is requested. Public contract (mirrors Cancellable::onCancel() — the contract itself makes it public, no visibility games). Fires immediately if the token is already cancelled, otherwise runs at most once, when cancel() happens. Either way a callback that throws is logged, never propagated: the immediate-fire path shares cancel()'s hook-failure seam, so registration cannot surface what cancellation promises to contain. |
ChildCapture final class
The per-slot byte ledger shared by the select arm, the Windows poll arm and the loop-driven ChildRun::launch(): keeps the HEAD of each retained slot up to a ceiling, counts what the ceiling refused, and offers every chunk to the live feed before any of that.
| Method | Summary |
|---|---|
__construct(array $slots, array $discard, private readonly int $maxBytes, private readonly ?\Closure $onChunk = null) | |
offer(int|string $slot, string $chunk): void | |
unread(int|string $slot): void | Records that bytes were left unread on $slot. The count is a floor, not a measurement: one byte, so DrainResult::truncated() reports the loss without claiming to know its size. A discarded slot is never retained, so it has no count to raise and nothing to report. |
anyFull(): bool | Whether any retained slot has reached the ceiling. |
result(string $reason, bool $abandonedAfterExit = false): DrainResult |
ChildPump final class
Read a child's output pipes to EOF without letting one wedge another, bounded by a deadline and a per-stream byte ceiling.
| Method | Summary |
|---|---|
static new(array $pipes): self | |
withDeadline(float $deadline): self | Absolute instant on the clock's scale; default is ten seconds after pump() starts. |
withCap(int $maxBytes): self | Per-retained-stream ceiling in bytes (>= 0). |
withStopAtCap(bool $stopAtCap = true): self | End the walk when a retained stream reaches the cap (the caller kills the child anyway). |
withDiscard(array $slots): self | |
withSlice(float $seconds): self | Longest single select wait before the deadline is rechecked. |
withSelectRetries(int $retries): self | |
withClock(?callable $clock): self | |
withSelect(?callable $select): self | The stream_select() seam (POSIX arm); tests inject an EINTR-shaped false. |
withRunning(?callable $running): self | Whether the child is still running (WindowsPipes::runningProbe()). |
withPollPipes(?bool $pollPipes): self | Force the Windows (true) or select (false) arm; null picks by the real runtime. |
withOnChunk(?callable $onChunk): self | Live feed: called with (slot, bytes) for every chunk read, including the slots that are drained but not kept. A TUI tail or a log tee rides this. |
withStdin($pipe, string $bytes): self | Feed $bytes to $pipe (the child's stdin) while the walk reads, then close $pipe: the child sees EOF. Refused on the Windows arm (LogicException). |
withOnStdinWrite(?callable $onStdinWrite): self | Called with the byte count of every stdin write the child accepted, as it happens. A child that keeps taking its stdin is alive and working, so a caller with an idle budget counts these writes as activity. Null removes the hook. |
withHeartbeat(float $seconds, callable $onBeat): self | Call $onBeat at most every $seconds while the walk is still open. The first beat comes one interval in, not at the start. |
withReap(?callable $reap): self | Run $reap once after the walk ends, after the last read, in a finally: the caller reaps the child (or kills it) only once its pipes are drained. |
withExitGrace(?float $seconds): self | Select arm, with a withRunning() probe: once the probe reports the child gone, keep reading until the pipes have been silent for $seconds, then end the walk as CLOSED. The budget counts from the later of the exit and the last chunk read, so a descendant that keeps writing keeps the walk reading (up to the deadline), and one that goes quiet is cut $seconds after its last write. A pipe still open at that cut is reported as abandoned on the result. The Windows poll arm ignores this budget and ends on the fixed WindowsPipes::EXIT_DRAIN_GRACE_SECONDS (see the class docblock). |
pump(): DrainResult | Read the pipes until they are all at EOF, the deadline passes, or the cap stops the walk, and return what was read and why it stopped. |
static drain(array $pipes, float $deadline, int $maxBytes, ?callable $clock = null, bool $stopAtCap = false, array $discard = [], float $sliceSeconds = 0.1, int $selectRetries = self::SELECT_RETRIES, ?callable $select = null, ?callable $running = null, ?bool $pollPipes = null): DrainResult | Static entry kept for the callers that predate the builder (AsyncOps::drain and candy-code's three call sites). Same contract as before the builder: see the class docblock for each argument. New code uses new(). |
ChildResult final class
What ChildRun read from a child and how the child ended.
| Method | Summary |
|---|---|
__construct(public readonly string $stdout, public readonly string $stderr, public readonly ?int $exitCode, public readonly string $status, public readonly int $droppedBytes, public readonly int $droppedStderrBytes = 0, public readonly bool $abandonedPipes = false, public readonly ?int $signal = null) | |
abandonedPipes(): bool | True exactly when a pipe was abandoned after the child exited, before it reached EOF. A pipe closed by the child's exit alone, or cut by a kill on the deadline, idle budget or cancel, is not abandoned. The Windows poll arm never reports an abandonment (see ChildRun). |
timedOut(): bool | |
cancelled(): bool | |
truncated(): bool | |
succeeded(): bool | Exited on its own with status 0 — a timeout or a pipe failure is never success. |
ChildRun final class
Run one child process with a deadline and a per-stream byte cap, and collect what it wrote: blocking with run(), or on a loop with launch().
| Method | Summary |
|---|---|
static new(array $argv): self | |
static commandLine(string $line): self | A command line proc_open() takes as one string, so the shell reads it: /bin/sh -c on POSIX, and cmd.exe on Windows. That is the form a shell string had before it was wrapped in an argv. An argv is escaped one element at a time on Windows, and the escaping of an embedded quote is not what cmd.exe reads, so a string command must travel as the raw line. Use new() for any command that is an argv already. |
withTimeout(float $seconds): self | Seconds from the start of the run before the child is killed. |
withExitGrace(?float $seconds): self | How long run() and launch() read on after the child's exit is seen, when a backgrounded grandchild still holds the output pipes. The budget is silence: the pipes are read until none has yielded a chunk for this many seconds, then abandoned. The default is the WindowsPipes grace. Null removes the grace: the call then reads until EOF or the deadline, so a held pipe keeps it going to its deadline, where the group is killed and the result is TIMED_OUT. Callers that bound a whole command by its budget pass null. |
withIdleTimeout(?float $seconds): self | Opt-in silence budget. The child is killed through the kill ladder once it has neither written to stdout or stderr nor accepted a stdin write for this many seconds, and reported as TIMED_OUT. Any chunk read resets the budget, dropped bytes included, and so does each stdin write the child takes: a child still consuming its input is working, not idle. That stdin count needs a pipe. On the Windows runtime a non-empty withStdin() payload is staged to a file with no pipe behind it, so the child's reads of that file are not counted: a child that reads a staged payload slowly and writes nothing is killed once the budget elapses, while it is still accepting its input. Null (the default) disables it, so a quiet child runs until its deadline. Once the child has exited the budget no longer applies: the exit grace governs its held pipes instead. |
withCancellation(?CancellationToken $token): self | Cancellation: once $token is cancelled the child is killed through the same ladder as the deadline, reaped, and the result reports CANCELLED. The caller holds the CancellationSource and calls cancel() on it. Null removes it. |
withMaxBytes(int $bytes): self | Bytes kept per stream (>= 0); output past it is read and counted, not kept. |
withStdin(?string $bytes): self | Payload for the child's stdin; null or '' gives the child an immediate EOF. |
withCwd(?string $dir): self | |
withEnv(?array $env): self | |
withGroupPid(?int $pid): self | The process group the child leads, for a child started behind a containment wrapper. The caller reads it with \SugarCraft\Core\Util\Proc\BoundedShutdown::groupId() while the child is alive. Each kill rung then signals the whole group, so descendants die with the wrapper. Null keeps the direct-child signal. |
withSetsidWrapped(bool $wrapped): self | Declares that the child was started behind a containment wrapper (a setsid prefix the caller adds to the argv), so the child leads its own process group once it has run. The launch path then falls back to the child's pid as the group id when the group was never read while the child lived, which is the case for a shell that backgrounds a job and exits before the first status poll. An unwrapped child leads no group of its own, so leave this false for it. |
withOnChunk(?callable $onChunk): self | Live feed: called with (slot, chunk) for every chunk read from stdout (1) or stderr (2), as it arrives, before the result is assembled. The buffered result is unchanged; the callback only observes. Null removes it. |
withOnSpawn(?callable $onSpawn): self | Spawn seam: called once, with the child's pid, right after the child starts and before anything is read or signalled. A child started behind a containment wrapper leads its own process group, so this pid is also the group id a kill rung needs; a runner records it here and passes it to withGroupPid() for the rest of the run, because the group id cannot be measured once the child has been reaped. Null removes the callback. |
withGroupLeader(bool $leads): self | The child leads its own process group because a containment wrapper started it (setsid -w), so its pid is the group id the kill rungs signal. The group is then taken from the pid at spawn, while the child is certainly alive, rather than measured with \SugarCraft\Core\Util\Proc\BoundedShutdown::groupId(), which answers null when the wrapper has not yet made itself a group leader or has already exited. Leave it false for an unwrapped child: that child shares this process's group, and a group kill would signal this process. |
withKillGrace(float $terminateSeconds, float $killSeconds): self | The kill ladder's two graces: the seconds it waits after SIGTERM before it sends SIGKILL, and after SIGKILL before it stops waiting and leaves the child to a late reap. The defaults are BoundedShutdown's, one second each. A caller whose own deadline has already spent its patience passes shorter ones. run() and launch() both use them. |
withOnKill(?callable $onKill): self | Kill seam: called once, with the child's pid, right before run()'s kill ladder sends its first signal, whatever started the ladder (the deadline, the idle budget, a cancel, a pipe failure or a throw from a callback). The child has not been signalled yet, so the caller can reach what the ladder cannot. On Windows the ladder ends at proc_terminate(), which kills only the direct child, and a caller walks the child's process tree from here. The ladder still runs after the hook, and still runs when the hook throws; the throw then propagates. |
withHeartbeat(float $seconds, callable $onBeat): self | Heartbeat: $onBeat is called at most every $seconds for as long as the child runs, so a caller can keep a liveness watchdog fed through a silent child. The first call comes one interval in. run() beats while it reads the pipes and while it waits for an exit after the output has closed; launch() beats on a loop timer until the run settles. Calls come from this process only. Unlike the idle budget, a beat never ends the run, unless the hook throws: the child is then killed and reaped, and run() rethrows the throw while launch() rejects with it. |
run(): ChildResult | Run the child to completion, blocking the caller, and return what it wrote. |
launch(LoopInterface $loop): PromiseInterface | Start the child on $loop and return a promise of its result. The loop is never blocked: output is read by stream callbacks, the deadline is a timer, and the reap is a short periodic check for the exit. A child still running after its kill budget is reaped by that same check once the kernel releases it, never by a blocking proc_close(). |
ChildRunLaunch final class
The loop-driven body of ChildRun::launch(): one child, its pipes, its deadline and its reap, all as callbacks on the loop. Built and started only by ChildRun; not a public entry point.
| Method | Summary |
|---|---|
__construct(private readonly LoopInterface $loop, private readonly mixed $proc, array $pipes, private readonly string $stdinBytes, private readonly float $timeout, int $maxBytes, private readonly Deferred $deferred, private readonly ?int $groupPid = null, ?\Closure $onChunk = null, private readonly ?float $idleTimeout = null, private readonly ?CancellationToken $cancellation = null, private readonly ?string $stagedStdin = null, private readonly ?float $exitGrace = null, private readonly ?float $heartbeatSeconds = null, private readonly ?\Closure $onHeartbeat = null, private readonly bool $setsidWrapped = false, private readonly float $terminateGrace = BoundedShutdown::TERMINATE_GRACE_SECONDS, private readonly float $killGrace = BoundedShutdown::KILL_GRACE_SECONDS, ?ChildStatus $status = null) | |
start(): void |
Containment final class
The process-group kill ladder for a child started behind a containment wrapper (a setsid session leader, or any child that leads its own group).
| Method | Summary |
|---|---|
static groupId(mixed $process): ?int | The group id to signal for a child, or null when it leads no group. |
static signal(mixed $process, ?int $groupPid, int $signal): bool | Signal the group when there is one, else the direct child. True when the signal was delivered to the group or the child. |
static terminate(mixed $process, int $signal = 15): bool | Signal a child in a way that reaches its descendants: the group when the child leads one (measured now), else proc_terminate(). |
static terminateBounded(mixed $process, ?int $groupPid = null, float $graceSeconds = BoundedShutdown::TERMINATE_GRACE_SECONDS, float $killGraceSeconds = BoundedShutdown::KILL_GRACE_SECONDS): ?int | The TERM, bounded poll, KILL, bounded poll ladder, then the reap. Blocks the caller; see BoundedShutdown::terminateBounded() for the contract. A non-null $groupPid makes every rung signal the group, and the child counts as gone only once the group is empty too. |
static terminateBoundedAsync(LoopInterface $loop, mixed $process, ?int $groupPid = null, ?callable $then = null, float $graceSeconds = BoundedShutdown::TERMINATE_GRACE_SECONDS, float $killGraceSeconds = BoundedShutdown::KILL_GRACE_SECONDS): void | The loop-driven ladder: the same rungs as terminateBounded() on loop timers, never blocking. $then receives the exit status, or null when the child cannot be reaped yet. |
Debounced final class
Invokable, disposable handle behind AsyncOps::debounce().
| Method | Summary |
|---|---|
static new(callable $fn, float $seconds, ?LoopInterface $loop = null, ?CancellationSource $source = null): self | |
__invoke(mixed ...$arguments): PromiseInterface | Schedule a call: any burst already waiting is superseded (answers null) and the window restarts. |
flush(): PromiseInterface | Run the scheduled call now instead of waiting out the window. With nothing pending this answers null and starts nothing. Paired by Throttled::flush() on the throttle handle. |
unsubscribe(): void | |
isActive(): bool | |
isPending(): bool | True while a burst is waiting out the window. |
DrainResult final class
What ChildPump::drain() read and why it stopped.
| Method | Summary |
|---|---|
__construct(public readonly array $buffers, public readonly array $dropped, public readonly string $reason, public readonly bool $abandonedAfterExit = false) | |
buffer(int|string $slot): string | |
droppedBytes(int|string $slot): int | Bytes refused for $slot (0 when none, or the slot was never retained). |
truncated(): bool | Whether any retained stream lost bytes to the ceiling. |
timedOut(): bool | The deadline ran out — a caller that owns the child kills it on this. |
closed(): bool |
ForkChannel final class
One end of a connected socket pair carrying length-prefixed frames between a parent process and a forked child.
| Method | Summary |
|---|---|
static pair(): array | A connected pair. Windows cannot pair AF_UNIX sockets, so it uses the loopback-TCP emulation PHP provides there instead. |
isOpen(): bool | True until close() runs or the peer goes away. |
send(string $frame): void | Write one frame, blocking until the kernel has taken all of it. |
onFrame(callable $onFrame, LoopInterface $loop): void | Deliver each complete inbound frame to $onFrame, read on $loop. |
onClose(callable $onClose): void | Run $onClose once when the channel stops, whether the peer hung up or close() ran. |
close(): void | Stop reading and release the stream. Idempotent. |
ForkedTask final class
Fork a child process, stream its frames back to the parent's loop, and settle with its exit status.
| Method | Summary |
|---|---|
static run(callable $child, callable $collect, LoopInterface $loop, ?CancellationToken $token = null, ?float $deadline = null): PromiseInterface |
Lang final class
Per-library translation facade for sugar-async.
LoopDeadline final class
One-shot deadline armed on an event loop: $onFire runs once when the budget elapses unless disarm() released it first.
| Method | Summary |
|---|---|
static arm(LoopInterface $loop, float $seconds, \Closure $onFire): self | |
fired(): bool | True once the budget has elapsed and $onFire has run. |
isArmed(): bool | True while the deadline is armed and has not yet fired. |
disarm(): void | Release the deadline so $onFire never runs. Idempotent; a no-op after firing. |
Notifier final class
Event-driven wake-up for a producer and a waiting consumer, in place of a poll loop over a mailbox.
| Method | Summary |
|---|---|
static new(?LoopInterface $loop = null): self | |
notify(): void | Wake every waiter, or remember one pending signal when none is waiting. |
waiting(): int | Number of waits currently parked on a notify. |
wait(?float $seconds = null): PromiseInterface |
OperationCancelledException final class
Thrown when an async retry or operation is cancelled via a CancellationToken before it could complete, or when a wrapper's wait is abandoned.
| Method | Summary |
|---|---|
__construct(string $message = '', int $code = 0, ?\Throwable $previous = null, private readonly ?string $label = null) | The constructor is exempt from signature-compatibility rules in PHP, so the structured label rides after the inherited trio (message, code, previous); every existing single-argument construction keeps working. |
label(): ?string | The operation label passed to the wrapper, or null when unlabelled. |
Pending final class
Pending-wait helpers: the advisory notice (pendingNotice()) and the bounded rejection (boundWait()) for user-paced operations.
| Method | Summary |
|---|---|
static pendingNotice(PromiseInterface $promise, float $seconds, callable $onPending, ?LoopInterface $loop = null): PromiseInterface | Announce slowness without interrupting the wait. If $promise is still pending after $seconds, $onPending runs ONCE (a "taking longer than expected" spinner hint). The returned promise tracks the inner one — the notice neither cancels nor abandons the work, and the E646 rule holds: this is an advisory tick, never a wall-clock killer of user-paced operations. A hook that throws is logged, never propagated. |
static boundWait(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?string $label = null): PromiseInterface | Bound the wait without stopping the work. If $promise is still pending after $seconds, the returned promise rejects with a TimeoutException whose message names (still pending) — the inner operation keeps running, like under withTimeout(). These are the bounded-wait semantics for user-paced operations: this library puts no blanket wall-clock timeout on operations whose pace belongs to the user. To announce a slow wait instead of ending it, use pendingNotice(). |
Poll final class
Poll-until on the loop: call $fn, and while it answers null wait out the backoff schedule and call it again.
| Method | Summary |
|---|---|
static until(callable $fn, Backoff $backoff, ?CancellationToken $token = null, ?LoopInterface $loop = null): PromiseInterface |
RateGate final class
Loop-free rate gate: allow() answers true at most once per interval.
| Method | Summary |
|---|---|
static new(float $seconds, ?callable $clock = null): self | |
seconds(): float | The configured spacing, in seconds. |
allow(): bool | Take the allowance if the window is open. |
reset(): void | Forget the last allowance: the next allow() is answered true. |
Retry final class
The seats around Backoff that actually wait: a budgeted synchronous poll (bounded()), the deadline-resume nap (nap()), and the loop-driven redial (reconnect()).
| Method | Summary |
|---|---|
static bounded(callable $operation, callable $shouldRetry, int $budgetMs, Backoff $backoff, ?callable $now = null, ?callable $sleep = null): mixed | Run $operation once, then again after each wait while $shouldRetry says its result is not final and the budget has not passed. |
static nap(int $owedMicros, ?callable $sleeper = null, ?callable $now = null, ?callable $onBeat = null): void | Sleep $owedMicros against a DEADLINE, not one usleep(): a usleep() is a wait until the next signal (EINTR), so it is re-armed from the clock until the debt is paid. A handler that takes time is paid out of the wait instead of added to it. |
static reconnect(callable $dial, Backoff $backoff, ?CancellationToken $token = null, ?LoopInterface $loop = null, ?callable $onRetry = null): PromiseInterface | Redial until $dial succeeds. Each failure waits $backoff->forAttempt(n) and tries again; with $backoff->withAttempts(null) (the default) that is forever, until the token fires. A bounded Backoff rejects with the last failure once Backoff::allows() says no. |
static retry(callable $operation, int $attempts = 3, float $baseBackoffSeconds = 0.1, ?CancellationToken $token = null, ?float $maxTotalSeconds = null, float $jitter = 0.0, ?LoopInterface $loop = null, ?callable $now = null, ?callable $onRetry = null): PromiseInterface | Retry a callable $attempts times in total with exponential backoff. |
StagedStdin final class
Removal of the temp file a Windows child reads as its stdin (see \SugarCraft\Core\Util\Proc\WindowsPipes::stageStdin()). On Windows a file a live child holds open cannot be unlinked, so a removal attempted before the child is reaped can fail with the payload still on disk. The retry decision lives here, apart from the platform, so every platform can test it.
| Method | Summary |
|---|---|
static removeAfterExit(LoopInterface $loop, string $path, ?callable $unlink = null, int $attempts = self::EXITED_UNLINK_ATTEMPTS, float $retrySeconds = self::EXITED_UNLINK_RETRY_SECONDS): void | Removes the payload once the child has been reaped, so the child no longer holds it. A refused removal is retried on the loop a bounded number of times, the first attempt included, and then left behind: the retries never block. |
static removeOrRetry(string $path, bool $childReaped, ?callable $unlink = null): bool | Unlinks $path. A failure while the child is still alive is retry-worthy: the caller keeps the path and removes it again on the reap path. A failure after the reap is final, because the child no longer holds the file. |
static reapHook(?string $path, bool $retry, ?callable $unlink = null): ?\Closure | The callback a reap runs to remove a payload the live child refused. Null when nothing is owed: no path, or a removal that was already final. |
StdinStagingException final class
ChildRun could not stage the stdin payload to a temp file, so no child was started. Only the Windows runtime stages a payload (ChildRun::withStdin()), and the cause is the temp directory: no file could be created there, or the payload could not be written to it.
| Method | Summary |
|---|---|
__construct(string $message = '', int $code = 0, ?\Throwable $previous = null, private readonly ?string $tempDir = null) | The constructor is exempt from signature-compatibility rules in PHP, so the temp directory rides after the inherited three (message, code, previous). |
tempDir(): ?string | The directory the payload was to be staged in, or null when unknown. |
Subscription interface
Contract for a subscription handle returned by onCancel(), debounce(), and throttle().
| Method | Summary |
|---|---|
unsubscribe(): void | Dispose of the subscription. Idempotent — calling multiple times is a no-op. |
isActive(): bool | Returns true if the subscription has not yet been unsubscribed. |
Subscriptions final class
Manages multiple subscriptions as a single atomic unit.
| Method | Summary |
|---|---|
static new(): self | An empty composite, ready to accumulate via add(). |
static of(\Closure $onUnsubscribe): Subscription | Mint a standalone disposal handle from a cleanup closure — the public entry point for consumers who need a Subscription without a producer that hands one out (timers, listeners, temp-file owners). The closure runs at most once, from unsubscribe(). |
static compose(Subscription ...$subscriptions): self | Compose multiple subscriptions into a single atomic handle. |
add(Subscription $subscription): void | Register a subscription on this composite as things arrive. |
unsubscribe(): void | |
isActive(): bool | |
count(): int | |
isEmpty(): bool |
Suspended final class
Value-object representing a command paused across update cycles.
| Method | Summary |
|---|---|
__construct(callable $resume, private mixed $state = null) | |
static new(callable $resume, mixed $state = null): self | |
resume(): ?\Closure | Resume the paused operation. Returns the Cmd closure to be dispatched — once. A second call yields null instead of re-running the effect: a handle handed to two schedulers must not double-fire the command. |
state(): mixed |
SynchronousLoop final class
A blocking LoopInterface for callers that run on a plain synchronous thread and still want Poll::until() as their wait primitive.
| Method | Summary |
|---|---|
static new(?callable $sleeper = null): self | |
addTimer($interval, $callback): TimerInterface | |
cancelTimer(TimerInterface $timer): void | |
run(): void | Drains the pending timer: sleeps its interval, then fires it. A callback that arms the next timer keeps the drain going until nothing is pending or stop() is called. |
stop(): void | |
addReadStream($stream, $listener) | |
addWriteStream($stream, $listener) | |
removeReadStream($stream) | |
removeWriteStream($stream) | |
addPeriodicTimer($interval, $callback) | |
futureTick($listener) | |
addSignal($signal, $listener) | |
removeSignal($signal, $listener) |
Throttled final class
Invokable, disposable handle behind AsyncOps::throttle().
| Method | Summary |
|---|---|
static new(callable $fn, float $seconds, ?LoopInterface $loop = null, bool $trailing = false): self | |
__invoke(mixed ...$arguments): PromiseInterface | Lead or queue a call. |
unsubscribe(): void | |
isActive(): bool | |
isPending(): bool | True while a trailing call waits for the window to close. |
flush(): void | Run a pending trailing call now instead of waiting for the window to close, and end the cooldown. With nothing pending this starts nothing. The call's outcome reaches whoever the suppressed call answered — the promise returned by that call — so flush() itself returns void. |
TimeoutException final class
Rejection when a time bound is hit: AsyncOps::withTimeout(), AsyncOps::withDeadline() and AsyncOps::retry()'s exhausted budget. Carries the bound that was set (and the operation's label, when the caller gave one) as structured fields, so a handler can report or branch on the duration without parsing the human-readable message.
| Method | Summary |
|---|---|
__construct(string $message = '', int $code = 0, ?\Throwable $previous = null, private readonly ?float $seconds = null, private readonly ?string $label = null) | The constructor is exempt from signature-compatibility rules in PHP, so the extra structured fields ride after the inherited three (message, code, previous); every existing single-argument construction keeps working unchanged. |
seconds(): ?float | The bound in seconds that was exceeded, or null when unknown. |
label(): ?string | The operation label passed to the wrapper, or null when unlabelled. |
Timeouts final class
Timeout and deadline combinators: the caller-side bound (withTimeout()) and the work-side bound that cancels the operation (withDeadline()), plus the shared rejection-message vocabulary both use.
| Method | Summary |
|---|---|
static withTimeout(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?string $label = null): PromiseInterface | Wrap a promise with a timeout. If the timeout fires before the promise settles, the returned promise rejects with TimeoutException. The inner promise is NOT cancelled and keeps running to completion. The wait itself is abandonable: cancel() on the returned promise releases the timer and rejects with OperationCancelledException — abandon, not abort (stopping the work is withDeadline()'s contract). When the work itself must stop as the wait ends — a hung I/O holding its consumer's in-flight gate open forever — use withDeadline(), which cancels the inner operation on both expiry and abandonment. |
static withDeadline(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?callable $onTimeout = null, ?string $label = null): PromiseInterface | Wrap a promise with a deadline that CANCELS the inner promise when it fires; withTimeout() by contrast lets the inner run on. |
static subject(?string $label): string | |
static cancellationMessage(?string $label): string | |
static timeoutMessage(?string $label, float $seconds): string | |
static deadlineMessage(?string $label, float $seconds): string |
WindowsPipes final class
sugar-async's handle on sugar-core's CoreWindowsPipes: non-blocking reads of proc_open pipes on Windows, where PHP's own non-blocking machinery does not apply to them. The measurements and reasoning live on the sugar-core class (the primitive sits there so libraries that do not depend on sugar-async can use it too); ChildPump::drain() reads through it.
| Method | Summary |
|---|---|
static runtimeNeedsIt(): bool | Whether THIS PHP runtime has the blocking-pipe behavior (the real OS). |
static available($pipe): int | Bytes readable from $pipe right now, without blocking. |
static readAvailable($pipe, int $max = 8192): string | Read what is already waiting in $pipe, at most $max bytes; never blocks. |
static runningProbe($process): \Closure | A "child still running" probe for ChildPump::drain()'s running:. |