Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/utils.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641import { MAX_ACTIVE_CHILDREN } from './scope.ts';import type { BranchView, Cause, ChildHandle, Exit, WorkflowOperation, PullSource, Resolve, Step, StepExit, Supervision,} from './kernel.ts';
/** * Owns the internal cause error state used by the live structured-concurrency kernel. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */class CauseError extends Error { readonly cause_: Cause;
constructor(cause: Cause) { super('Live operation failed.'); this.cause_ = cause; }}
/** Create an operation that returns an already available value. */export function value<Value>(result: Value): WorkflowOperation<Value> { return Object.freeze({ /** * Returns the native iterator view used by synchronous iteration protocols. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ *[Symbol.iterator](): Generator<Step<unknown>, Value, Exit<unknown>> { yield* []; return result; }, });}
/** * Adapt one AbortSignal-aware Promise producer into an owned Step. * * Cancellation does not pretend to force-stop an arbitrary Promise. The branch * aborts its signal, calls the Step discard function, and waits until the * producer settles before unwind can continue. */export function fromPromise<Value>( name: string, producer: (signal: AbortSignal, checkpoint: () => Promise<void>) => Promise<Value>,): WorkflowOperation<Value> { if (name.trim().length === 0) throw new TypeError('Promise operation name must not be empty.'); return stepOperation<Value>(Object.freeze({ name, /** * Enters the operation and returns the cleanup/discard path owned by the live structured-concurrency kernel. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */ enter(resolve: Resolve<Value>, branch: BranchView): StepExit { let settled = false; let discardDone: Resolve<void> | undefined; const settleDiscard = (): void => { if (discardDone === undefined) return; const done = discardDone; discardDone = undefined; done(Object.freeze({ type: 'success', value: undefined })); }; void producer(branch.signal, () => branch.checkpoint()).then( (value) => { if (!settled) { settled = true; resolve(Object.freeze({ type: 'success', value })); } settleDiscard(); }, (failure) => { if (!settled) { settled = true; const cause: Cause = Object.freeze({ type: 'failure', failure }); resolve(Object.freeze({ type: 'failure', cause })); } settleDiscard(); }, ); return (done) => { if (settled) done(Object.freeze({ type: 'success', value: undefined })); else discardDone = done; }; }, }));}
/** Adapt a callback source with an explicit discard operation. */export function fromCallback<Value>( name: string, start: ( resolve: (value: Value) => void, reject: (failure: unknown) => void, signal: AbortSignal, ) => void | (() => void | Promise<void>),): WorkflowOperation<Value> { if (name.trim().length === 0) throw new TypeError('Callback operation name must not be empty.'); return stepOperation<Value>(Object.freeze({ name, /** * Enters the operation and returns the cleanup/discard path owned by the live structured-concurrency kernel. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */ enter(resolve: Resolve<Value>, branch: BranchView): StepExit { let settled = false; const finish = (exit: Exit<Value>): void => { if (settled) return; settled = true; resolve(exit); }; const discard = start( (value) => finish(Object.freeze({ type: 'success', value })), (failure) => { const cause: Cause = Object.freeze({ type: 'failure', failure }); finish(Object.freeze({ type: 'failure', cause })); }, branch.signal, ); return (done) => { if (discard === undefined) return done(Object.freeze({ type: 'success', value: undefined })); let released: void | Promise<void>; try { released = discard(); } catch (failure) { const cause: Cause = Object.freeze({ type: 'failure', failure }); done(Object.freeze({ type: 'failure', cause })); return; } void Promise.resolve(released).then( () => done(Object.freeze({ type: 'success', value: undefined })), (failure) => done(Object.freeze({ type: 'failure', cause: Object.freeze({ type: 'failure', failure }) })), ); }; }, }));}
/** Register asynchronous cleanup on the current branch Scope. */export function defer(dispose: () => void | PromiseLike<void>): WorkflowOperation<void> { return stepOperation(Object.freeze({ name: 'defer cleanup', /** * Enters the operation and returns the cleanup/discard path owned by the live structured-concurrency kernel. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */ enter(resolve: Resolve<void>, branch: BranchView): StepExit { branch.defer(dispose); resolve(Object.freeze({ type: 'success', value: undefined })); return (done) => done(Object.freeze({ type: 'success', value: undefined })); }, }));}
/** Spawn one owned child branch without exposing it outside the local kernel. */export function spawn<Value>(child: WorkflowOperation<Value>, supervision: Supervision): WorkflowOperation<ChildHandle<Value>> { return stepOperation(Object.freeze({ name: 'spawn child branch', /** * Enters the operation and returns the cleanup/discard path owned by the live structured-concurrency kernel. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */ enter(resolve: Resolve<ChildHandle<Value>>, branch: BranchView): StepExit { const handle = branch.spawn(child, supervision); resolve(Object.freeze({ type: 'success', value: handle })); return (done) => done(Object.freeze({ type: 'success', value: undefined })); }, }));}
/** Run one child in an owned child Scope and return only after it is terminal. */export function scoped<Value>(child: WorkflowOperation<Value>): WorkflowOperation<Value> { return Object.freeze({ /** * Returns the native iterator view used by synchronous iteration protocols. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ *[Symbol.iterator](): Generator<Step<unknown>, Value, Exit<unknown>> { const handle = yield* spawn(child, 'isolate')[Symbol.iterator](); const exit = yield* fromPromise('join scoped child', async () => await handle.result())[Symbol.iterator](); if (exit.type === 'success') return exit.value; throw new CauseError(exit.cause); }, });}
/** * Run owned children fail-fast and preserve input order. * * The first failed child stops admission, cancels every unfinished sibling, and * waits for those siblings before the failure reaches the caller. Promise.race * observes child terminal promises only; Branch and Scope retain ownership. */export function all<const Values extends readonly WorkflowOperation<unknown>[]>( operations: Values,): WorkflowOperation<{ readonly [Key in keyof Values]: WorkflowOperationValue<Values[Key]> }> { assertBranchCount(operations.length, 'workflow all'); return Object.freeze({ /** * Returns the native iterator view used by synchronous iteration protocols. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ *[Symbol.iterator](): Generator< Step<unknown>, { readonly [Key in keyof Values]: WorkflowOperationValue<Values[Key]> }, Exit<unknown> > { const handles: ChildHandle<unknown>[] = []; for (const child of operations) handles.push(yield* spawn(child, 'isolate')[Symbol.iterator]()); const exits = new Array<Exit<unknown>>(handles.length); const pending = new Set(handles.map((_handle, index) => index)); while (pending.size > 0) { const next = yield* fromPromise('wait for next child', async () => await Promise.race( [...pending].map(async (index) => ({ index, exit: await handles[index]!.result() })), ))[Symbol.iterator](); exits[next.index] = next.exit; pending.delete(next.index); if (next.exit.type !== 'failure') continue; const primaryCause = next.exit.cause;
const cancellations = [...pending].map((index) => handles[index]!.cancel(primaryCause)); yield* fromPromise('cancel failed siblings', async () => await Promise.all(cancellations).then(() => undefined)) [Symbol.iterator](); const terminal = yield* fromPromise( 'join failed siblings', async () => await Promise.all(handles.map((handle) => handle.result())), )[Symbol.iterator](); const cleanupCauses = terminal .filter((_exit, index) => index !== next.index) .filter((exit): exit is Extract<Exit<unknown>, { readonly type: 'failure' }> => exit.type === 'failure') .map((exit) => exit.cause) .filter((cause) => cause.type !== 'cancelled'); const causes = cleanupCauses.length === 0 ? [primaryCause] : [primaryCause, ...cleanupCauses]; throw new CauseError( causes.length === 1 ? causes[0]! : Object.freeze({ type: 'multiple', causes: Object.freeze(causes) }), ); } return exits.map((exit) => (exit as Extract<Exit<unknown>, { readonly type: 'success' }>).value) as { readonly [Key in keyof Values]: WorkflowOperationValue<Values[Key]>; }; }, });}
/** Run owned children without sibling cancellation and return every Exit. */export function allSettled<const Values extends readonly WorkflowOperation<unknown>[]>( operations: Values,): WorkflowOperation<{ readonly [Key in keyof Values]: Exit<WorkflowOperationValue<Values[Key]>> }> { assertBranchCount(operations.length, 'workflow allSettled'); return Object.freeze({ /** * Returns the native iterator view used by synchronous iteration protocols. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ *[Symbol.iterator](): Generator< Step<unknown>, { readonly [Key in keyof Values]: Exit<WorkflowOperationValue<Values[Key]>> }, Exit<unknown> > { const handles: ChildHandle<unknown>[] = []; for (const child of operations) handles.push(yield* spawn(child, 'collect')[Symbol.iterator]()); return (yield* fromPromise( 'join all settled children', async () => await Promise.all(handles.map((handle) => handle.result())), )[Symbol.iterator]()) as { readonly [Key in keyof Values]: Exit<WorkflowOperationValue<Values[Key]>>; }; }, });}
/** * Return the first terminal owned child after every loser has stopped. * * Promise.race is only an observer over child `result()` promises. It does not * own or cancel those branches. The explicit cancellation and join phase keeps * the structured-concurrency guarantee intact. */export function race<const Values extends readonly WorkflowOperation<unknown>[]>( operations: Values,): WorkflowOperation<WorkflowOperationValue<Values[number]>> { assertBranchCount(operations.length, 'workflow race'); if (operations.length === 0) throw new TypeError('Workflow race requires at least one operation.'); return Object.freeze({ /** * Returns the native iterator view used by synchronous iteration protocols. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ *[Symbol.iterator](): Generator<Step<unknown>, WorkflowOperationValue<Values[number]>, Exit<unknown>> { const handles: ChildHandle<unknown>[] = []; for (const child of operations) handles.push(yield* spawn(child, 'isolate')[Symbol.iterator]()); const first = yield* fromPromise('wait for first child', async () => await Promise.race( handles.map(async (handle, index) => ({ index, exit: await handle.result() })), ))[Symbol.iterator](); const cancellations = handles.map((handle, index) => index === first.index ? Promise.resolve() : handle.cancel(first.exit) ); yield* fromPromise('cancel race losers', async () => await Promise.all(cancellations).then(() => undefined)) [Symbol.iterator](); const settled = yield* fromPromise( 'join race children', async () => await Promise.all(handles.map((handle) => handle.result())), )[Symbol.iterator](); const cleanupCauses = settled .filter((_exit, index) => index !== first.index) .filter((exit): exit is Extract<Exit<unknown>, { readonly type: 'failure' }> => exit.type === 'failure') .map((exit) => exit.cause) .filter((cause) => cause.type !== 'cancelled'); if (first.exit.type === 'failure') { const causes = cleanupCauses.length === 0 ? [first.exit.cause] : [first.exit.cause, ...cleanupCauses]; throw new CauseError( causes.length === 1 ? causes[0]! : Object.freeze({ type: 'multiple', causes: Object.freeze(causes) }), ); } if (cleanupCauses.length > 0) { throw new CauseError(Object.freeze({ type: 'multiple', causes: Object.freeze(cleanupCauses) })); } return first.exit.value as WorkflowOperationValue<Values[number]>; }, });}
/** * Adapt a synchronous iterator without materializing its values. * * The returned source is owned by the current branch Scope. Each call to * `next()` is one local operation. Scope closure invokes `iterator.return()` at * most once when the source did not finish normally. */export function fromIterator<Value, Return = unknown>( iterator: Iterator<Value, Return>,): WorkflowOperation<PullSource<Value, Return>> { return sourceOperation(iterator, 'iterator');}
/** * Adapt an asynchronous iterator without cross-feeding values between branches. * * Cancellation calls `return()` and waits for it before branch unwind. */export function fromAsyncIterator<Value, Return = unknown>( iterator: AsyncIterator<Value, Return>,): WorkflowOperation<PullSource<Value, Return>> { return sourceOperation(iterator, 'async iterator');}
/** * Adapt a WHATWG ReadableStream into a pull source with exact reader ownership. * * A read error cancels the reader before surfacing the failure. Normal stream * completion releases the reader lock. Branch cancellation cancels the reader * and waits for `releaseLock()` before unwind. */export function fromReadableStream<Value>(stream: ReadableStream<Value>): WorkflowOperation<PullSource<Value, undefined>> { return Object.freeze({ /** * Returns the native iterator view used by synchronous iteration protocols. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ *[Symbol.iterator](): Generator<Step<unknown>, PullSource<Value, undefined>, Exit<unknown>> { const source = yield* fromCallback<PullSource<Value, undefined>>( 'acquire readable stream', (resolve, reject, signal) => { let reader: ReadableStreamDefaultReader<Value>; try { reader = stream.getReader(); } catch (error) { reject(error); return; } const handle = readableSource(reader); if (signal.aborted) { void handle.close(signal.reason).then(() => reject(signal.reason), reject); return; } resolve(handle); return () => handle.close(signal.reason); }, )[Symbol.iterator](); yield* defer(() => source.close())[Symbol.iterator](); return source; }, });}
/** * Adapts a Step factory into a live WorkflowOperation whose settlement remains owned by the executing Branch. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */function stepOperation<Value>(step: Step<Value>): WorkflowOperation<Value> { return Object.freeze({ /** * Returns the native iterator view used by synchronous iteration protocols. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ *[Symbol.iterator](): Generator<Step<unknown>, Value, Exit<unknown>> { const exit = yield step as Step<unknown>; if (exit.type === 'success') return exit.value as Value; throw new CauseError(exit.cause); }, });}
/** Convert an internal operation exception back into a structured Cause. */export function causeFromError(error: unknown): Cause { return error instanceof CauseError ? error.cause_ : Object.freeze({ type: 'failure', failure: error });}
/** Extract the concrete failure value when callers need to bridge to Promise code. */export function failureFromCause(cause: Cause): unknown { if (cause.type === 'failure') return cause.failure; if (cause.type === 'fault') return cause.fault; if (cause.type === 'cancelled') return cause.reason; const failures = cause.causes.map(failureFromCause); return new AggregateError(failures, 'Live operation failed for multiple reasons.');}
/** * Builds the source operation adapter consumed by the live structured-concurrency kernel. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */function sourceOperation<Value, Return>( iterator: Iterator<Value, Return> | AsyncIterator<Value, Return>, name: string,): WorkflowOperation<PullSource<Value, Return>> { return Object.freeze({ /** * Returns the native iterator view used by synchronous iteration protocols. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ *[Symbol.iterator](): Generator<Step<unknown>, PullSource<Value, Return>, Exit<unknown>> { const source = iteratorSource(iterator, name); yield* defer(() => source.close())[Symbol.iterator](); return source; }, });}
/** * Wraps an iterator as a pull source whose `return()` cleanup is owned and invoked exactly once. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */function iteratorSource<Value, Return>( iterator: Iterator<Value, Return> | AsyncIterator<Value, Return>, name: string,): PullSource<Value, Return> { let done = false; let closing: Promise<void> | undefined; const close = (_reason?: unknown): Promise<void> => { if (done) return Promise.resolve(); if (closing !== undefined) return closing; closing = Promise.resolve(iterator.return?.()).then( () => { done = true; }, (error) => { done = true; throw error; }, ); return closing; }; const source: PullSource<Value, Return> = Object.freeze({ /** * Advances to the next value without crossing ownership between independent consumers of the live structured-concurrency kernel. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */ next(): WorkflowOperation<IteratorResult<Value, Return>> { return fromCallback(`${name} next`, (resolve, reject, signal) => { if (done) { resolve(Object.freeze({ done: true, value: undefined as Return })); return; } void Promise.resolve(iterator.next()).then((result) => { if (result.done) done = true; resolve(result); }, reject); return () => close(signal.reason); }); }, close, /** * Releases owned state and waits for cleanup completion when used with `await using`. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ async [Symbol.asyncDispose](): Promise<void> { await close(); }, }); return source;}
/** * Reads a ReadableStream source under the module's cancellation and ownership rules. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */function readableSource<Value>(reader: ReadableStreamDefaultReader<Value>): PullSource<Value, undefined> { let released = false; let done = false; let closing: Promise<void> | undefined; const release = (): void => { if (released) return; released = true; reader.releaseLock(); }; const close = (reason?: unknown): Promise<void> => { if (released) return Promise.resolve(); if (closing !== undefined) return closing; closing = (done ? Promise.resolve() : Promise.resolve(reader.cancel(reason))) .then( () => { done = true; release(); }, (error) => { done = true; release(); throw error; }, ); return closing; }; return Object.freeze({ /** * Advances to the next value without crossing ownership between independent consumers of the live structured-concurrency kernel. * * The kernel gives every branch one active Step and child Scope while the Reducer serializes generator advancement, cancellation, and cleanup. * * @internal */ next(): WorkflowOperation<IteratorResult<Value, undefined>> { return fromCallback('read stream chunk', (resolve, reject, signal) => { if (done || released) { resolve(Object.freeze({ done: true, value: undefined })); return; } void reader.read().then((result) => { if (result.done) { done = true; release(); resolve(Object.freeze({ done: true, value: undefined })); return; } resolve(Object.freeze({ done: false, value: result.value })); }, (error) => { void close(error).then( () => reject(error), (cleanupError) => reject(new AggregateError([error, cleanupError], 'ReadableStream read and cleanup both failed.')), ); }); return () => close(signal.reason); }); }, close, /** * Releases owned state and waits for cleanup completion when used with `await using`. * * It implements live structured concurrency: a Branch owns one active Step and child Scope, while the Reducer serializes state transitions. * * @internal */ async [Symbol.asyncDispose](): Promise<void> { await close(); }, });}
/** Compile-time success value extracted from one internal workflow operation. */type WorkflowOperationValue<Value> = Value extends WorkflowOperation<infer Output> ? Output : never;
/** Reject dynamic combinators that would exceed the scope active-child safety bound. */function assertBranchCount(count: number, label: string): void { if (count > MAX_ACTIVE_CHILDREN) { throw new RangeError(`${label} cannot start more than ${MAX_ACTIVE_CHILDREN} child operations.`); }}