SugarAsync
Shared async vocabulary for ReactPHP
Shared async vocabulary unifying ReactPHP usage across the SugarCraft monorepo: a CancellationSource owns the mutable flag and its cancel() trigger while consumers hold a read-only CancellationToken, Subscription handles make disposal uniform (compose() gathers many into one), and the AsyncOps helpers cover timeout and deadline ceilings, retry with jittered backoff and a total budget, single-flight coalescing, debounce and throttle timers, all/race fan-in, and a pending-notice combinator — plus loop-free blocking engines behind AsyncOps forwarders (Retry, Backoff, ChildPump) and a bounded TTL AsyncCache that coalesces in-flight loads.
Install
composer require sugarcraft/sugar-async
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($loop, $somePromise, 5.0);
// 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.
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 atomic 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, never silently dropped. 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; the registration un-registers itself when the inner promise settles.
AsyncOps::singleFlight()Coalesces concurrent same-key calls into one in-flight worker — one round-trip per key, 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 required 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 naming the abandonment while the inner operation runs on. (The deprecated onPending() delegates to the pair.)
AsyncOps::setLogSink()Redirects the swallowed-failure notices — cancellation callbacks, the 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 (stderr under stock PHP, where one interleaved line can corrupt an in-progress render).Blocking engines
Retry::bounded() runs a result-driven retry loop with every wait clamped to the remaining budget (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. AsyncOps::retryBounded() / nap() / reconnect() / drain() forward to them; Backoff carries the schedule (ceiling, full jitter, server hint, attempts).AsyncCacheTTL'd async memo — loop-free, it arms no timers: fetch(key, loader) coalesces in-flight loads, serves fresh entries instantly, optionally serves stale on loader failure, with an entry cap that 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 — plain RuntimeException subclasses; TimeoutException carries seconds() and label() context.
Use it for
- Unified cancellation — replace ad-hoc cancellation scattered across async consumers with one shared pattern; the dependents census as of 2026-11 is sugar-forms, sugar-vterm, candy-sql, candy-mail, candy-git-server and candy-codetime.
- Subscription lifecycle ownership — Subscriptions::compose() gathers many disposal handles so teardown can dispose them all atomically (the sugar-core runtime keeps its own internal variant; this is the public standalone one).
- Async operation helpers — withTimeout, retry, debounce, throttle built on top of react/promise and react/event-loop; loop-free blocking engines (
Retry::bounded(),nap(),reconnect(),ChildPump::drain()) sit behind theAsyncOpsforwarders.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Original SugarCraft design — no 1:1 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(?LoopInterface, PromiseInterface, float, ?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(?LoopInterface, PromiseInterface, float, ?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 (a hook passed to the deprecated onPending() delegates here) |
| 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 (the null-hook mode of the deprecated onPending() delegates here) |
| 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 |