All 48 libraries

SugarAsync

Shared async vocabulary for ReactPHP

original — no 1:1 Go counterpart async cancellation reactphp foundation

SugarAsync code coverage

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

CancellationTokenRead-only view of a cancellation state. Consumers observe isCancelled() and register onCancel() callbacks; the trigger methods are @internal-tagged but public, so restriction is by convention, not visibility. Do not hand tokens to untrusted code.
CancellationSourceOwns the mutable cancellation flag. Create via CancellationSource::new(). Call cancel() to flip the flag and fire all registered callbacks; repeated calls are no-ops.
Cancellable interfaceContract for components that can be canceled. Implemented by CancellationSource. Callbacks fire exactly once, even on repeated cancel() calls.
Subscription interfaceDisposal handle returned by onCancel(), debounce() and throttle(). unsubscribe() disposes the subscription; isActive() reports whether it is still live.
Subscriptions::compose()Combine multiple subscriptions into a single handle. Calling unsubscribe() on the composite disposes all underlying subscriptions.
AsyncOps::withTimeout()Wrap a promise with a timeout. Rejects with TimeoutException if the timeout fires before the promise settles.
AsyncOps::retry()Runs an operation up to N times in total with exponential backoff. attempts: 3 means three runs, not three retries. Respects CancellationToken: cancelling aborts remaining attempts.
AsyncOps::debounce()Wrap a callable so only the last call within the window fires, after silence.
AsyncOps::throttle()Wrap a callable so it fires at most once per interval. Suppressed calls resolve null, visible in the promise chain. With trailing: true the last suppressed call fires at window end.
AsyncOps::withDeadline()Budget-aware ceiling: rejects with TimeoutException on expiry and cancels the inner operation so no late result is ever adopted; the optional onTimeout hook gets one shot at aborting server-side work.
AsyncOps::cancellable()Guards a promise with a token: cancellation rejects the guard with OperationCancelledException and runs the onCancel cleanup hook.
AsyncOps::singleFlight()Coalesces concurrent same-key calls into one in-flight worker. One round-trip per key, and every caller receives the outcome. Stateful: never share a singleFlight closure across a pcntl_fork boundary.
AsyncOps::all() / race()Fan-in helpers: all() waits for every promise (empty input resolves to []); race() adopts the first settled outcome (empty input throws InvalidArgumentException at the call site).
AsyncOps::pendingNotice() / AsyncOps::boundWait()pendingNotice fires a progress hook when a promise is still unsettled after N seconds, a spinner signal for slow calls. boundWait ends only the waiting, rejecting with a TimeoutException while the inner operation runs on.
AsyncOps::setLogSink()Redirects the swallowed-failure notices (cancellation callbacks, retry 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.
Blocking enginesRetry::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.
Child processesChildRun 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.
ForkedTaskForks a child, streams its frames back to the loop over a ForkChannel, and settles with the child's exit status. Requires ext-pcntl and ext-posix; without them it refuses up front.
AsyncCacheTTL'd async memo. It is loop-free and arms no timers: fetch(key, loader) coalesces in-flight loads, serves fresh entries instantly and can serve stale values on loader failure. An optional entry cap evicts the least-recently-stored value.
SuspendedA paused command as data: a resume closure paired with its state. resume() hands the Cmd closure to the resumer exactly once; a second call yields null, never a double-fire.
CallbackSubscriptionThe disposable handle onCancel() and Subscriptions::of() hand out. unsubscribe() drops a registration that has not fired; handles for work already done are born spent.
Timeout / cancellation exceptionsOperationCancelledException and TimeoutException are plain RuntimeException subclasses. TimeoutException carries seconds() and label() context.

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.

OptionWhereDefaultEffect
attemptsAsyncOps::retry()3Total runs, including the first. Not a retry count.
baseBackoffSeconds and jitterAsyncOps::retry()0.1 and 0.0Base delay for the exponential schedule, and the jitter fraction applied to it.
maxTotalSecondsAsyncOps::retry()null (no budget)Overall budget. Exceeding it rejects with a TimeoutException.
trailingAsyncOps::throttle()falseWhen true, the last suppressed call fires at the end of the window.
ttlSecondsAsyncCache::new()60.0How long a loaded value counts as fresh.
serveStaleOnErrorAsyncCache::new()falseServe the last value when a reload fails, instead of rejecting.
maxEntriesAsyncCache::new()null (no cap)Caps stored keys. An adopt past the cap evicts the least-recently-stored entry.
Deadline and byte capChildRun, ChildPump10 seconds and 8 MiB per streamSet with withTimeout() and withMaxBytes() on ChildRun. On the pump, withDeadline() takes an absolute monotonic time, and withCap() sets the byte cap.
MAX_FRAME_BYTESForkChannel16 MiBLargest frame a channel will send or accept. A larger length prefix is treated as a broken peer.
setLogSink()AsyncOpserror_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.php covers the timer-backed helpers on a private loop: debounce() and throttle() return invokable handles, and all(), race() and boundWait() are demonstrated alongside them.
  • examples/cache.php shows AsyncCache as cache-aside with coalescing, a monotonic clock seam that needs no sleeps, serve-stale-on-error and the bounded entry cap.
  • examples/cancellation.php walks 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 typeBorrowed shape
Cancellable, CancellationSource, CancellationTokenGo's context.Context Done channel, and the source and token split of .NET's CancellationTokenSource
Subscription, CallbackSubscriptionRxJS's Subscription, and Node's EventEmitter.removeListener
SubscriptionsRxJS's Subscription group
ForkChannelThe 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

Try the quickstart →

API

Public API surface of sugar-async: class, method signature, and behavior.
ClassMethodDescription
CancellationSourcenew(): selfFactory: create a new source with its own token
CancellationSourcetoken(): CancellationTokenReturns the read-only token for this source
CancellationSourcecancel(): voidRequest cancellation. Idempotent.
CancellationSourceisCancelled(): boolReturns true if cancel() has been called
CancellationSourceonCancel(callable): SubscriptionRegisters a cleanup callback on the source's own token (CancellationSource implements Cancellable); same fire-once, handle-un-registers semantics as CancellationToken::onCancel().
CancellationTokennone(): selfShared never-canceled sentinel — the safe default for optional token parameters; its onCancel() returns a born-spent handle and retains nothing
CancellationTokenisCancelled(): boolReturns true if the source has been canceled
CancellationTokenonCancel(callable): SubscriptionRegister 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.
CancellableisCancelled() · cancel() · onCancel(callable)Interface CancellationSource implements — type against it when a component must be cancellable
Subscriptionunsubscribe(): voidInterface: disposes the registration; the removal closure runs at most once, from unsubscribe()
SubscriptionisActive(): boolInterface: false once unsubscribed, or born spent
CallbackSubscriptionof(Closure): selfLive handle over a removal closure — the concrete Subscription onCancel() returns
CallbackSubscriptionsettled(): selfBorn-spent handle (the callback already fired immediately); unsubscribe() is a no-op
Subscriptionsnew(): selfEmpty composite collection
Subscriptionsof(Closure): SubscriptionPublic glue: mints a standalone disposal handle from any cleanup closure (timers, listeners, temp-file owners)
Subscriptionscompose(Subscription ...): selfCombine multiple subscriptions into one atomic handle
Subscriptionsadd(Subscription): voidAppend 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
Subscriptionsunsubscribe(): voidDispose all underlying subscriptions
SubscriptionsisActive(): boolReturns false after unsubscribe()
Subscriptionscount(): int · isEmpty(): boolSize of the composite
SubscriptionsdisposeAll(): 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())
AsyncOpssetLogSink(?callable $sink): voidThe 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
AsyncOpswithTimeout(PromiseInterface, float, ?LoopInterface, ?string label): PromiseInterfaceWrap a promise with a timeout; rejects with TimeoutException (seconds and optional label readable on it); null loop uses the shared one
AsyncOpswithDeadline(PromiseInterface, float, ?LoopInterface, ?callable onTimeout, ?string label): PromiseInterfaceCeiling on the remaining budget: on expiry rejects with TimeoutException and cancels the inner promise; late results are dropped, never adopted
AsyncOpscancellable(PromiseInterface, ?CancellationToken, ?callable onCancel): PromiseInterfaceToken guard: cancellation rejects with OperationCancelledException and runs the onCancel hook; the registration auto-un-registers when the inner promise settles — no loop parameter
AsyncOpssingleFlight(callable keyFn, callable worker): callableCoalesces 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
AsyncOpsretry(operation, attempts: 3, baseBackoffSeconds: 0.1, token:, maxTotalSeconds:, jitter: 0.0, loop:, now:, onRetry:): PromiseInterfaceRetries 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)
AsyncOpsretryBounded(operation, shouldRetry, budgetMs, backoff)Forwarder to Retry::bounded() — blocking, result-driven, every wait clamped to the remaining budget
AsyncOpsnap(int $owedMicros)Forwarder to Retry::nap() — a sleep that is re-armed after EINTR
AsyncOpsreconnect(dial, backoff, token:, loop:, onRetry:)Forwarder to Retry::reconnect() — redials until success or cancellation; success ends the cycle
AsyncOpsdrain(pipes, deadline, maxBytes)Forwarder to ChildPump::drain() — one select loop over all pipes, returning a DrainResult
AsyncOpsall(iterable): PromiseInterfaceFan-in on every promise; empty input resolves to []
AsyncOpsrace(iterable): PromiseInterfaceAdopts the first settled outcome; empty input throws InvalidArgumentException at the call site
AsyncOpspendingNotice(PromiseInterface, float, callable onPending, ?LoopInterface): PromiseInterfaceFires the required advisory hook once if the promise is still unsettled after N seconds; the wait continues and the inner is never canceled
AsyncOpsboundWait(PromiseInterface, float, ?LoopInterface, ?string label): PromiseInterfaceBounded wait: still unsettled after N seconds rejects the wait with a TimeoutException naming (still pending) while the inner runs on
AsyncOpsdebounce(callable, float, ?LoopInterface, ?CancellationSource): DebouncedDebounce wrapper returning a Debounced handle; only the last call fires after the window; optional source cancels it
AsyncOpsthrottle(callable, float, ?LoopInterface, bool trailing): ThrottledThrottle 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)
Suspendednew(callable resume, mixed state = null) · resume(): ?Closure · state(): mixedPaused command as data; resume() yields the Cmd closure exactly once (a second call returns null)
AsyncCachenew(ttlSeconds: 60.0, serveStaleOnError: false, ?clock, ?maxEntries): selfTTL'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)
AsyncCachefetch(string key, callable loader): PromiseInterfaceFresh entry resolves instantly; otherwise the loader starts — concurrent same-key fetches coalesce; a synchronous throw counts as a failed load
AsyncCachepeek(string): mixed · has(string): bool · isFresh(string): boolRender-path reads: last stored value (fresh or stale), a value is held, a held value is within TTL
AsyncCacheisLoaded(string): bool · ageSeconds(string): ?floatFresh OR in-flight (the loading-indicator read); monotonic age of the held value, past the TTL on purpose
AsyncCacheinvalidate(string): void · clear(): voidDrop a key / every entry and supersede in-flight loads — displaced arrivals resolve their own callers without adopting into the store
AsyncCachecount() · 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
TimeoutExceptionseconds(): ?float · label(): ?stringRejection 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.

MethodSummary
static new(float $ttlSeconds = 60.0, bool $serveStaleOnError = false, ?callable $clock = null, ?int $maxEntries = null): self
ttlSeconds(): floatFreshness window for cache hits (seconds).
servesStaleOnError(): bool
maxEntries(): ?intThe stored-key cap, or null when unbounded (the default).
generation(): intEpoch 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(): intNumber of stored values, fresh or stale. In-flight loads are not stored.
keys(): arrayStored keys (fresh or stale), least-recently-stored first.
isLoaded(string $key): boolTrue when the key is fresh OR a load is in flight — the loading-indicator read.
ageSeconds(string $key): ?floatMonotonic 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): PromiseInterfaceCache-aside load: answer from a fresh entry, join the in-flight load, or start one.
peek(string $key): mixedLast 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): boolTrue when a value (fresh or stale) is held for the key.
isFresh(string $key): boolTrue when a value is held and its TTL has not elapsed.
invalidate(string $key): voidDrop 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(): voidDrop every entry and supersede every in-flight load.

AsyncOps final class

Static helpers for async operations on top of ReactPHP.

MethodSummary
static setLogSink(?callable $sink): voidRedirect (or restore) the destination of swallowed-failure notices.
static withTimeout(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?string $label = null): PromiseInterfaceWrap 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): PromiseInterfaceWrap 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): PromiseInterfaceBind a promise to a CancellationToken: cooperative, two-sided, immediate cancellation.
static singleFlight(callable $keyFn, callable $worker): callableCoalesce 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): PromiseInterfaceRetry a callable $attempts times in total with exponential backoff.
static all(iterable $promises): PromiseInterfaceFan-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): PromiseInterfaceFan-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): PromiseInterfaceAnnounce 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): PromiseInterfaceBound 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): DebouncedWrap 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): ThrottledWrap 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): mixedSynchronous 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): voidPay 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): PromiseInterfaceRedial 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): DrainResultDrain several child pipes against one deadline. Forwards to ChildPump::drain().
static deferred(\Closure $fn, ?LoopInterface $loop = null): PromiseInterfaceRun $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.

MethodSummary
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.

MethodSummary
static new(float $baseMs, float $factor = 2.0, ?int $capMs = null): self
withJitter(?callable $rng = null): selfWait a uniform draw over [0, ceiling] instead of the ceiling itself.
withoutJitter(): selfBack to the deterministic ceiling.
serverHint(?float $seconds): selfThe 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): selfTotal tries allowed; null (the default) retries forever. See allows().
allows(int $n): boolWhether 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): intThe deterministic ceiling after the $n-th failure, ms. 0 for $n < 1.
forAttempt(int $n): intHow 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): floatforAttempt() in seconds.

CallbackSubscription final class

Subscription handle backed by a single removal closure.

MethodSummary
static of(\Closure $onDispose): selfA live handle whose registration still awaits disposal.
static settled(): selfA 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.

MethodSummary
isCancelled(): boolReturns true if cancel() has been called.
cancel(): voidRequests cancellation. Idempotent — calling multiple times has no additional effect. All registered onCancel callbacks fire in registration order, exactly once.
onCancel(callable $callback): SubscriptionRegister 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().

MethodSummary
__construct()
static new(): selfFactory for idiomatic construction.
token(): CancellationTokenReturns the read-only token for this source.
isCancelled(): boolThe 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(): voidRequests 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): SubscriptionRegister 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.

MethodSummary
__construct(CancellationSource $source)
static none(): selfThe shared never-cancelled token.
isCancelled(): boolReturns true if the source has been cancelled.
onCancel(callable $callback): SubscriptionRegister 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.

MethodSummary
__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): voidRecords 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(): boolWhether 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.

MethodSummary
static new(array $pipes): self
withDeadline(float $deadline): selfAbsolute instant on the clock's scale; default is ten seconds after pump() starts.
withCap(int $maxBytes): selfPer-retained-stream ceiling in bytes (>= 0).
withStopAtCap(bool $stopAtCap = true): selfEnd the walk when a retained stream reaches the cap (the caller kills the child anyway).
withDiscard(array $slots): self
withSlice(float $seconds): selfLongest single select wait before the deadline is rechecked.
withSelectRetries(int $retries): self
withClock(?callable $clock): self
withSelect(?callable $select): selfThe stream_select() seam (POSIX arm); tests inject an EINTR-shaped false.
withRunning(?callable $running): selfWhether the child is still running (WindowsPipes::runningProbe()).
withPollPipes(?bool $pollPipes): selfForce the Windows (true) or select (false) arm; null picks by the real runtime.
withOnChunk(?callable $onChunk): selfLive 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): selfFeed $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): selfCalled 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): selfCall $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): selfRun $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): selfSelect 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(): DrainResultRead 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): DrainResultStatic 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.

MethodSummary
__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(): boolTrue 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(): boolExited 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().

MethodSummary
static new(array $argv): self
static commandLine(string $line): selfA 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): selfSeconds from the start of the run before the child is killed.
withExitGrace(?float $seconds): selfHow 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): selfOpt-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): selfCancellation: 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): selfBytes kept per stream (>= 0); output past it is read and counted, not kept.
withStdin(?string $bytes): selfPayload for the child's stdin; null or '' gives the child an immediate EOF.
withCwd(?string $dir): self
withEnv(?array $env): self
withGroupPid(?int $pid): selfThe 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): selfDeclares 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): selfLive 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): selfSpawn 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): selfThe 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): selfThe 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): selfKill 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): selfHeartbeat: $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(): ChildResultRun the child to completion, blocking the caller, and return what it wrote.
launch(LoopInterface $loop): PromiseInterfaceStart 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.

MethodSummary
__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).

MethodSummary
static groupId(mixed $process): ?intThe group id to signal for a child, or null when it leads no group.
static signal(mixed $process, ?int $groupPid, int $signal): boolSignal 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): boolSignal 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): ?intThe 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): voidThe 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().

MethodSummary
static new(callable $fn, float $seconds, ?LoopInterface $loop = null, ?CancellationSource $source = null): self
__invoke(mixed ...$arguments): PromiseInterfaceSchedule a call: any burst already waiting is superseded (answers null) and the window restarts.
flush(): PromiseInterfaceRun 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(): boolTrue while a burst is waiting out the window.

DrainResult final class

What ChildPump::drain() read and why it stopped.

MethodSummary
__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): intBytes refused for $slot (0 when none, or the slot was never retained).
truncated(): boolWhether any retained stream lost bytes to the ceiling.
timedOut(): boolThe 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.

MethodSummary
static pair(): arrayA connected pair. Windows cannot pair AF_UNIX sockets, so it uses the loopback-TCP emulation PHP provides there instead.
isOpen(): boolTrue until close() runs or the peer goes away.
send(string $frame): voidWrite one frame, blocking until the kernel has taken all of it.
onFrame(callable $onFrame, LoopInterface $loop): voidDeliver each complete inbound frame to $onFrame, read on $loop.
onClose(callable $onClose): voidRun $onClose once when the channel stops, whether the peer hung up or close() ran.
close(): voidStop 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.

MethodSummary
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.

MethodSummary
static arm(LoopInterface $loop, float $seconds, \Closure $onFire): self
fired(): boolTrue once the budget has elapsed and $onFire has run.
isArmed(): boolTrue while the deadline is armed and has not yet fired.
disarm(): voidRelease 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.

MethodSummary
static new(?LoopInterface $loop = null): self
notify(): voidWake every waiter, or remember one pending signal when none is waiting.
waiting(): intNumber 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.

MethodSummary
__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(): ?stringThe 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.

MethodSummary
static pendingNotice(PromiseInterface $promise, float $seconds, callable $onPending, ?LoopInterface $loop = null): PromiseInterfaceAnnounce 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): PromiseInterfaceBound 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.

MethodSummary
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.

MethodSummary
static new(float $seconds, ?callable $clock = null): self
seconds(): floatThe configured spacing, in seconds.
allow(): boolTake the allowance if the window is open.
reset(): voidForget 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()).

MethodSummary
static bounded(callable $operation, callable $shouldRetry, int $budgetMs, Backoff $backoff, ?callable $now = null, ?callable $sleep = null): mixedRun $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): voidSleep $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): PromiseInterfaceRedial 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): PromiseInterfaceRetry 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.

MethodSummary
static removeAfterExit(LoopInterface $loop, string $path, ?callable $unlink = null, int $attempts = self::EXITED_UNLINK_ATTEMPTS, float $retrySeconds = self::EXITED_UNLINK_RETRY_SECONDS): voidRemoves 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): boolUnlinks $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): ?\ClosureThe 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.

MethodSummary
__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(): ?stringThe 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().

MethodSummary
unsubscribe(): voidDispose of the subscription. Idempotent — calling multiple times is a no-op.
isActive(): boolReturns true if the subscription has not yet been unsubscribed.

Subscriptions final class

Manages multiple subscriptions as a single atomic unit.

MethodSummary
static new(): selfAn empty composite, ready to accumulate via add().
static of(\Closure $onUnsubscribe): SubscriptionMint 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): selfCompose multiple subscriptions into a single atomic handle.
add(Subscription $subscription): voidRegister 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.

MethodSummary
__construct(callable $resume, private mixed $state = null)
static new(callable $resume, mixed $state = null): self
resume(): ?\ClosureResume 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.

MethodSummary
static new(?callable $sleeper = null): self
addTimer($interval, $callback): TimerInterface
cancelTimer(TimerInterface $timer): void
run(): voidDrains 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().

MethodSummary
static new(callable $fn, float $seconds, ?LoopInterface $loop = null, bool $trailing = false): self
__invoke(mixed ...$arguments): PromiseInterfaceLead or queue a call.
unsubscribe(): void
isActive(): bool
isPending(): boolTrue while a trailing call waits for the window to close.
flush(): voidRun 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.

MethodSummary
__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(): ?floatThe bound in seconds that was exceeded, or null when unknown.
label(): ?stringThe 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.

MethodSummary
static withTimeout(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?string $label = null): PromiseInterfaceWrap 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): PromiseInterfaceWrap 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.

MethodSummary
static runtimeNeedsIt(): boolWhether THIS PHP runtime has the blocking-pipe behavior (the real OS).
static available($pipe): intBytes readable from $pipe right now, without blocking.
static readAvailable($pipe, int $max = 8192): stringRead what is already waiting in $pipe, at most $max bytes; never blocks.
static runningProbe($process): \ClosureA "child still running" probe for ChildPump::drain()'s running:.