All 42 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 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 enginesRetry::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 the AsyncOps forwarders.

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(?LoopInterface, PromiseInterface, float, ?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(?LoopInterface, PromiseInterface, float, ?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 (a hook passed to the deprecated onPending() delegates here)
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 (the null-hook mode of the deprecated onPending() delegates here)
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