import { 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(result: Value): WorkflowOperation { 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, Value, Exit> { 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( name: string, producer: (signal: AbortSignal, checkpoint: () => Promise) => Promise, ): WorkflowOperation { if (name.trim().length === 0) throw new TypeError('Promise operation name must not be empty.'); return stepOperation(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, branch: BranchView): StepExit { let settled = false; let discardDone: Resolve | 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( name: string, start: ( resolve: (value: Value) => void, reject: (failure: unknown) => void, signal: AbortSignal, ) => void | (() => void | Promise), ): WorkflowOperation { if (name.trim().length === 0) throw new TypeError('Callback operation name must not be empty.'); return stepOperation(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, branch: BranchView): StepExit { let settled = false; const finish = (exit: Exit): 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; 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): WorkflowOperation { 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, 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(child: WorkflowOperation, supervision: Supervision): WorkflowOperation> { 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>, 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(child: WorkflowOperation): WorkflowOperation { 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, Value, Exit> { 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[]>( operations: Values, ): WorkflowOperation<{ readonly [Key in keyof Values]: WorkflowOperationValue }> { 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, { readonly [Key in keyof Values]: WorkflowOperationValue }, Exit > { const handles: ChildHandle[] = []; for (const child of operations) handles.push(yield* spawn(child, 'isolate')[Symbol.iterator]()); const exits = new Array>(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, { 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, { readonly type: 'success' }>).value) as { readonly [Key in keyof Values]: WorkflowOperationValue; }; }, }); } /** Run owned children without sibling cancellation and return every Exit. */ export function allSettled[]>( operations: Values, ): WorkflowOperation<{ readonly [Key in keyof Values]: Exit> }> { 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, { readonly [Key in keyof Values]: Exit> }, Exit > { const handles: ChildHandle[] = []; 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>; }; }, }); } /** * 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[]>( operations: Values, ): WorkflowOperation> { 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, WorkflowOperationValue, Exit> { const handles: ChildHandle[] = []; 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, { 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; }, }); } /** * 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( iterator: Iterator, ): WorkflowOperation> { 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( iterator: AsyncIterator, ): WorkflowOperation> { 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(stream: ReadableStream): WorkflowOperation> { 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, PullSource, Exit> { const source = yield* fromCallback>( 'acquire readable stream', (resolve, reject, signal) => { let reader: ReadableStreamDefaultReader; 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(step: Step): WorkflowOperation { 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, Value, Exit> { const exit = yield step as Step; 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( iterator: Iterator | AsyncIterator, name: string, ): WorkflowOperation> { 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, PullSource, Exit> { 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( iterator: Iterator | AsyncIterator, name: string, ): PullSource { let done = false; let closing: Promise | undefined; const close = (_reason?: unknown): Promise => { 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 = 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> { 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 { 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(reader: ReadableStreamDefaultReader): PullSource { let released = false; let done = false; let closing: Promise | undefined; const release = (): void => { if (released) return; released = true; reader.releaseLock(); }; const close = (reason?: unknown): Promise => { 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> { 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 { await close(); }, }); } /** Compile-time success value extracted from one internal workflow operation. */ type WorkflowOperationValue = Value extends WorkflowOperation ? 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.`); } }