@juicesharp/rpiv-workflow 1.19.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -8
- package/api.ts +18 -703
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +154 -0
- package/audit.ts +158 -190
- package/built-ins.ts +40 -45
- package/chain-state.ts +220 -0
- package/command-run.ts +64 -31
- package/command.ts +123 -21
- package/docs/workflow-authoring.md +356 -63
- package/{lifecycle.ts → events.ts} +161 -37
- package/execution-host.ts +75 -0
- package/host.ts +149 -64
- package/index.ts +25 -81
- package/internal-utils.ts +171 -71
- package/internal.ts +22 -1
- package/judge.ts +241 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +27 -106
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +24 -0
- package/loop-def.ts +285 -0
- package/loop-kinds.ts +750 -0
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +330 -0
- package/loops/constructors.ts +334 -0
- package/loops/derivations.ts +65 -0
- package/loops/introspection.ts +184 -0
- package/loops/panel.ts +196 -0
- package/loops/verify.ts +99 -0
- package/messages.ts +249 -156
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +4 -18
- package/outcomes/collectors/union.ts +30 -10
- package/outcomes/collectors/url.ts +9 -14
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.ts +190 -100
- package/outcomes/index.ts +1 -0
- package/outcomes/parsers/json-body.ts +2 -2
- package/outcomes/side-effect.ts +3 -3
- package/output-spec.ts +36 -10
- package/output.ts +98 -20
- package/package.json +27 -11
- package/predicates.ts +11 -8
- package/preview.ts +81 -21
- package/registration.ts +117 -36
- package/routing-dsl.ts +322 -0
- package/routing.ts +48 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +84 -56
- package/runner/errors.ts +10 -0
- package/runner/failure.ts +163 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +16 -23
- package/runner/preflight.ts +169 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +121 -0
- package/runner/resume-loop.ts +131 -0
- package/runner/resume.ts +368 -262
- package/runner/run-context.ts +165 -0
- package/runner/run-stage.ts +490 -0
- package/runner/runner.ts +202 -449
- package/runner/script-stage.ts +104 -112
- package/schema-compat.ts +12 -1
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +146 -81
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +3 -1
- package/sessions/locate.ts +141 -0
- package/sessions/reattach.ts +71 -0
- package/sessions/sessions.ts +114 -199
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +86 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +4 -4
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +595 -0
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +4 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +20 -0
- package/state/raw.ts +77 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +135 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +290 -78
- package/validate/contract-compat.ts +198 -0
- package/validate/graph.ts +134 -0
- package/validate/issue.ts +328 -0
- package/validate/stage-rules.ts +499 -0
- package/validate-output.ts +82 -7
- package/validate-workflow.ts +57 -759
- package/validation-bounds.ts +35 -0
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -74
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -110
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -59
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -107
- package/outcomes/git-commit.test.ts +0 -194
- package/outcomes/parsers/json-body.test.ts +0 -80
- package/runner/by-name.test.ts +0 -95
- package/runner/by-run-id.test.ts +0 -115
- package/runner/resume-fanout.test.ts +0 -331
- package/runner/resume-fanout.ts +0 -136
- package/runner/resume-iterate.test.ts +0 -444
- package/runner/resume-iterate.ts +0 -111
- package/runner/resume.test.ts +0 -1130
- package/runner/stage-lifecycle.ts +0 -500
package/runner/script-stage.ts
CHANGED
|
@@ -9,65 +9,60 @@
|
|
|
9
9
|
* returns `{ kind, artifacts, data }` (`produces.script`) or `void`
|
|
10
10
|
* (`acts.script` / `terminal.script`), and the runner stamps `meta`,
|
|
11
11
|
* persists the JSONL row, advances the rolling primary slot, fires
|
|
12
|
-
* lifecycle events, and recurses through `
|
|
12
|
+
* lifecycle events, and recurses through the injected `advance`.
|
|
13
13
|
*
|
|
14
|
-
* The
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* The retry policy is the SHARED `runValidationRetryLoop`
|
|
15
|
+
* (validate-output.ts) — same structure the skill path's extraction runs;
|
|
16
|
+
* success persistence is the SHARED `persistStageSuccess` (audit-rows.ts) —
|
|
17
|
+
* so the audit row shape, the lifecycle fire order (`onStageStart` →
|
|
17
18
|
* `onStageRetry`* → `onStageEnd` | `onStageError`), and the
|
|
18
19
|
* primary-artifact advance behaviour stay aligned across the two
|
|
19
|
-
* stage kinds.
|
|
20
|
+
* stage kinds by construction.
|
|
20
21
|
*
|
|
21
22
|
* Invariants this file relies on (enforced at load time by
|
|
22
23
|
* `validateWorkflow:checkScriptStageInvariants`):
|
|
23
24
|
* - `stage.skill` is unset.
|
|
24
25
|
* - `stage.outcome` is unset (no collector to run).
|
|
25
|
-
* - `stage.
|
|
26
|
+
* - `stage.loop` is unset (the runner's per-unit machinery doesn't
|
|
26
27
|
* apply; authors write their own loop inside `run()`).
|
|
27
28
|
* - `stage.sessionPolicy !== "continue"` (no session to continue).
|
|
28
29
|
*/
|
|
29
30
|
|
|
30
31
|
import type { ScriptContext } from "../api.js";
|
|
31
|
-
import { auditCtxFor,
|
|
32
|
-
import
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
32
|
+
import { auditCtxFor, failAuditWrite, failedArgs, recordTerminalFailure } from "../audit.js";
|
|
33
|
+
import { allocateStageNumber, persistStageSuccess } from "../audit-rows.js";
|
|
34
|
+
import { lifecycleCtxFor, scriptStageRef } from "../events.js";
|
|
35
|
+
import type { Artifact } from "../handle.js";
|
|
36
|
+
import { formatError, nowIso } from "../internal-utils.js";
|
|
37
|
+
import { FAIL_SCRIPT_THREW, FAIL_VALIDATION_EXHAUSTED } from "../messages.js";
|
|
38
|
+
import { finalizeOutput, type Output, outputMeta } from "../output.js";
|
|
39
|
+
import type { RunContext, WorkflowHostContext } from "../types.js";
|
|
35
40
|
import {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
STATUS_KEY,
|
|
44
|
-
STATUS_STAGE,
|
|
45
|
-
} from "../messages.js";
|
|
46
|
-
import { finalizeOutput, type Output } from "../output.js";
|
|
47
|
-
import type { RunContext, RunState, WorkflowHostContext } from "../types.js";
|
|
48
|
-
import { DEFAULT_VALIDATION_RETRIES, describeFailure, validateOutputData } from "../validate-output.js";
|
|
49
|
-
import { advanceChain } from "./chain-advance.js";
|
|
50
|
-
import { lifecycleCtxFor } from "./runner.js";
|
|
51
|
-
import type { ResolvedStage } from "./stage-lifecycle.js";
|
|
41
|
+
DEFAULT_VALIDATION_RETRIES,
|
|
42
|
+
describeFailure,
|
|
43
|
+
runValidationRetryLoop,
|
|
44
|
+
validateOutputData,
|
|
45
|
+
} from "../validate-output.js";
|
|
46
|
+
import type { AdvanceFn, ChainOutcome } from "./failure.js";
|
|
47
|
+
import type { ResolvedStage } from "./resolve-stage.js";
|
|
52
48
|
|
|
53
49
|
/**
|
|
54
50
|
* Drive a script stage: lifecycle-fire `onStageStart`, retry-loop the
|
|
55
51
|
* `run` body against `outputSchema`, then either persist + advance or
|
|
56
52
|
* record a terminal failure. Sole entry point — `runStage` branches
|
|
57
|
-
* here
|
|
53
|
+
* here on `mode === "script"`, passing the composed `advance`.
|
|
58
54
|
*
|
|
59
55
|
* Caller pre-conditions (held by `runStage`):
|
|
60
|
-
* - `ensureInputValid` already passed
|
|
61
|
-
* - `
|
|
56
|
+
* - `ensureInputValid` already passed.
|
|
57
|
+
* - `mode === "script"` (a script stage cannot carry a `loop`).
|
|
62
58
|
*/
|
|
63
59
|
export async function runScript(
|
|
64
60
|
curCtx: WorkflowHostContext,
|
|
65
61
|
stage: ResolvedStage,
|
|
66
62
|
idx: number,
|
|
67
63
|
run: RunContext,
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
64
|
+
advance: AdvanceFn,
|
|
65
|
+
): Promise<ChainOutcome> {
|
|
71
66
|
const ref = scriptStageRef(stage.name, stage.stageNumber);
|
|
72
67
|
await run.lifecycle.fire(curCtx, "onStageStart", ref, lifecycleCtxFor(run));
|
|
73
68
|
|
|
@@ -77,44 +72,77 @@ export async function runScript(
|
|
|
77
72
|
state: run.state,
|
|
78
73
|
};
|
|
79
74
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const invocation = await invokeRun(curCtx, stage, scriptCtx, ref, run);
|
|
85
|
-
if (!invocation.ok) return;
|
|
75
|
+
// One allocation per activation, BEFORE any output is built — the
|
|
76
|
+
// envelope, the success/failure row, and lifecycle bookkeeping share it
|
|
77
|
+
// (mirrors `produceAndValidateOutput` on the skill path).
|
|
78
|
+
const stageNumber = allocateStageNumber(run.state);
|
|
86
79
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
})
|
|
105
|
-
|
|
80
|
+
// `halt: "recorded"` = invokeRun already recorded the terminal failure.
|
|
81
|
+
const result = await runValidationRetryLoop<Output, "recorded">(
|
|
82
|
+
{
|
|
83
|
+
maxRetries: stage.def.maxRetries ?? DEFAULT_VALIDATION_RETRIES,
|
|
84
|
+
failFast: (stage.def.onInvalid ?? "retry") === "halt",
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
produce: async () => {
|
|
88
|
+
const invocation = await invokeRun(curCtx, stage, scriptCtx, run, stageNumber);
|
|
89
|
+
if (!invocation.ok) return { kind: "aborted", abort: "recorded" };
|
|
90
|
+
const output = finalizeOutput(
|
|
91
|
+
invocation.raw,
|
|
92
|
+
outputMeta({
|
|
93
|
+
stage: stage.name,
|
|
94
|
+
stageNumber,
|
|
95
|
+
ts: nowIso(),
|
|
96
|
+
runId: run.runId,
|
|
97
|
+
}),
|
|
98
|
+
);
|
|
99
|
+
return { kind: "ok", value: output };
|
|
100
|
+
},
|
|
101
|
+
validate: async (output) => {
|
|
102
|
+
if (!(stage.def.kind === "produces" && stage.def.outputSchema)) {
|
|
103
|
+
return { kind: "ok", result: { valid: true, failures: [] } };
|
|
106
104
|
}
|
|
105
|
+
// No catch: a throwing author schema propagates to the runner's
|
|
106
|
+
// single catch site (today's contract).
|
|
107
|
+
return {
|
|
108
|
+
kind: "ok",
|
|
109
|
+
result: await Promise.resolve(validateOutputData(stage.def.outputSchema, output.data)),
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
onRetry: async (attempt) => {
|
|
107
113
|
await run.lifecycle.fire(curCtx, "onStageRetry", ref, attempt, lifecycleCtxFor(run));
|
|
108
|
-
|
|
109
|
-
}
|
|
110
|
-
}
|
|
114
|
+
return { kind: "ok" };
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
);
|
|
111
118
|
|
|
112
|
-
|
|
119
|
+
if (result.kind === "aborted") return "halted";
|
|
120
|
+
if (result.kind === "exhausted") {
|
|
121
|
+
const failureSummary = result.failures.map(describeFailure).join("; ");
|
|
122
|
+
await recordTerminalFailure(
|
|
123
|
+
curCtx,
|
|
124
|
+
scriptAuditCtx(run, stage, stageNumber),
|
|
125
|
+
failedArgs(FAIL_VALIDATION_EXHAUSTED(stage.name, failureSummary)),
|
|
126
|
+
);
|
|
127
|
+
return "halted";
|
|
128
|
+
}
|
|
113
129
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
130
|
+
const output = result.value;
|
|
131
|
+
// `skill` is intentionally absent on script-stage rows — JSON.stringify
|
|
132
|
+
// drops `undefined` so the JSONL row carries no skill field at all.
|
|
133
|
+
// `session: null` is explicit: script stages never open a Pi session.
|
|
134
|
+
const persisted = persistStageSuccess(
|
|
135
|
+
run.state,
|
|
136
|
+
{ cwd: run.cwd, runId: run.runId, stage: stage.name, output, session: null, preAllocated: stageNumber },
|
|
137
|
+
stage.def,
|
|
138
|
+
);
|
|
139
|
+
if (!persisted) {
|
|
140
|
+
failAuditWrite(curCtx, run.state, stage.name);
|
|
141
|
+
return "halted";
|
|
117
142
|
}
|
|
143
|
+
|
|
144
|
+
await run.lifecycle.fire(curCtx, "onStageEnd", ref, output, lifecycleCtxFor(run));
|
|
145
|
+
return advance(curCtx, stage.name, idx, run);
|
|
118
146
|
}
|
|
119
147
|
|
|
120
148
|
type ScriptInvocationResult =
|
|
@@ -132,8 +160,8 @@ async function invokeRun(
|
|
|
132
160
|
curCtx: WorkflowHostContext,
|
|
133
161
|
stage: ResolvedStage,
|
|
134
162
|
scriptCtx: ScriptContext,
|
|
135
|
-
ref: ReturnType<typeof scriptStageRef>,
|
|
136
163
|
run: RunContext,
|
|
164
|
+
stageNumber: number,
|
|
137
165
|
): Promise<ScriptInvocationResult> {
|
|
138
166
|
try {
|
|
139
167
|
const result = await Promise.resolve(stage.def.run!(scriptCtx));
|
|
@@ -143,65 +171,29 @@ async function invokeRun(
|
|
|
143
171
|
: { kind: "side-effect", artifacts: [] as readonly Artifact[], data: {} as unknown };
|
|
144
172
|
return { ok: true, raw };
|
|
145
173
|
} catch (e) {
|
|
146
|
-
const reason =
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
// `_ref` arg here so the caller doesn't fire a second time.
|
|
155
|
-
void ref;
|
|
174
|
+
const reason = formatError(e);
|
|
175
|
+
// `recordTerminalFailure` fires `onStageError` itself — the caller must
|
|
176
|
+
// not fire a second time on the `ok: false` return.
|
|
177
|
+
await recordTerminalFailure(
|
|
178
|
+
curCtx,
|
|
179
|
+
scriptAuditCtx(run, stage, stageNumber),
|
|
180
|
+
failedArgs(FAIL_SCRIPT_THREW(stage.name, reason)),
|
|
181
|
+
);
|
|
156
182
|
return { ok: false };
|
|
157
183
|
}
|
|
158
184
|
}
|
|
159
185
|
|
|
160
|
-
/**
|
|
161
|
-
* Persist the success row + advance the rolling primary-artifact slot.
|
|
162
|
-
* Returns `true` iff the JSONL row landed. Mirrors
|
|
163
|
-
* `tryRecordStage` + `recordStageSuccess` in `sessions/sessions.ts`,
|
|
164
|
-
* specialised for the script path (no SessionContext, no skill field,
|
|
165
|
-
* no `onStageEnd` fire — caller owns lifecycle ordering here).
|
|
166
|
-
*/
|
|
167
|
-
function recordScriptSuccess(
|
|
168
|
-
curCtx: WorkflowHostContext,
|
|
169
|
-
stage: ResolvedStage,
|
|
170
|
-
output: Output,
|
|
171
|
-
state: RunState,
|
|
172
|
-
cwd: string,
|
|
173
|
-
runId: string,
|
|
174
|
-
): boolean {
|
|
175
|
-
const assigned = recordStage(
|
|
176
|
-
cwd,
|
|
177
|
-
runId,
|
|
178
|
-
// `skill` is intentionally absent on script-stage rows — JSON.stringify
|
|
179
|
-
// drops `undefined` so the JSONL row carries no skill field at all.
|
|
180
|
-
{ stage: stage.name, status: "completed", ts: nowIso(), output },
|
|
181
|
-
state,
|
|
182
|
-
);
|
|
183
|
-
if (assigned === undefined) {
|
|
184
|
-
curCtx.ui.notify(MSG_AUDIT_WRITE_FAILED(stage.name), "error");
|
|
185
|
-
state.termination.error = ERR_AUDIT_WRITE_FAILED(stage.name);
|
|
186
|
-
return false;
|
|
187
|
-
}
|
|
188
|
-
applyCompletedStage(state, stage.def, stage.name, output);
|
|
189
|
-
state.output = output;
|
|
190
|
-
state.stagesCompleted++;
|
|
191
|
-
curCtx.ui.notify(MSG_STAGE_COMPLETE(stage.name), "info");
|
|
192
|
-
return true;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
186
|
/**
|
|
196
187
|
* Build the `AuditCtx`-shaped object `recordTerminalFailure` needs for
|
|
197
188
|
* a script-stage halt. The `skill` field doubles as the lifecycle
|
|
198
189
|
* `onStageError` ref payload — using `stage.name` keeps the failure
|
|
199
190
|
* attribution aligned with the success row's `stage` identity.
|
|
200
191
|
*/
|
|
201
|
-
function scriptAuditCtx(run: RunContext, stage: ResolvedStage) {
|
|
192
|
+
function scriptAuditCtx(run: RunContext, stage: ResolvedStage, stageNumber: number) {
|
|
202
193
|
// `skill` doubles as the notify-message subject (`MSG_VALIDATION_EXHAUSTED`,
|
|
203
194
|
// `MSG_STAGE_FAILED`); set to the stage name so the user sees the stage
|
|
204
195
|
// identity. `isScript: true` ensures the JSONL row drops the field and
|
|
205
196
|
// `onStageError` fires with `scriptStageRef` (no `skill` payload).
|
|
206
|
-
|
|
197
|
+
// `allocatedStageNumber` lets a failure row reuse the activation's number.
|
|
198
|
+
return auditCtxFor(run, stage.name, stage.name, { isScript: true, allocatedStageNumber: stageNumber });
|
|
207
199
|
}
|
package/schema-compat.ts
CHANGED
|
@@ -14,7 +14,18 @@
|
|
|
14
14
|
|
|
15
15
|
import { deepEqual } from "./internal-utils.js";
|
|
16
16
|
import type { JsonSchemaObject } from "./json-schema.js";
|
|
17
|
-
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Result of a conservative structural compatibility check between a
|
|
20
|
+
* producer's output schema and a consumer's input schema. Owned by the
|
|
21
|
+
* engine that defines its semantics (this module); the contract domain
|
|
22
|
+
* (`skill-contract.ts`) re-exports it so `CompositionComparator` consumers
|
|
23
|
+
* stay self-contained.
|
|
24
|
+
*/
|
|
25
|
+
export interface SchemaCompatResult {
|
|
26
|
+
ok: boolean;
|
|
27
|
+
reason?: string;
|
|
28
|
+
}
|
|
18
29
|
|
|
19
30
|
/** The set of JSON-Schema `type`s a schema allows (string or string[]), or undefined if untyped. */
|
|
20
31
|
function typeSet(schema: JsonSchemaObject): Set<string> | undefined {
|
package/semaphore.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* semaphore.ts — bounded-concurrency gate for the parallel fanout dispatcher.
|
|
3
|
+
*
|
|
4
|
+
* `run(fn)` acquires a slot (queuing FIFO if `limit` are already in flight),
|
|
5
|
+
* runs `fn`, and releases on settle. When `signal` aborts, every QUEUED waiter
|
|
6
|
+
* rejects with a `WorkflowAbortError` so not-yet-started units never run;
|
|
7
|
+
* already-active children are aborted by the host (the dispatcher threads
|
|
8
|
+
* `signal` into each `spawnChild`). A fresh `acquire` after abort rejects
|
|
9
|
+
* immediately. `Semaphore(1)` serializes — the cursor/`state.named`
|
|
10
|
+
* representation is then identical to the sequential path.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { WorkflowAbortError, WorkflowConfigError } from "./internal-utils.js";
|
|
14
|
+
|
|
15
|
+
export class Semaphore {
|
|
16
|
+
private active = 0;
|
|
17
|
+
private readonly queue: Array<{ resolve: () => void; reject: (e: unknown) => void }> = [];
|
|
18
|
+
|
|
19
|
+
constructor(
|
|
20
|
+
private readonly limit: number,
|
|
21
|
+
private readonly signal?: AbortSignal,
|
|
22
|
+
) {
|
|
23
|
+
if (limit < 1) throw new WorkflowConfigError(`Semaphore limit must be ≥ 1, got ${limit}`);
|
|
24
|
+
signal?.addEventListener("abort", () => this.drain(), { once: true });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async run<T>(fn: () => Promise<T>): Promise<T> {
|
|
28
|
+
await this.acquire();
|
|
29
|
+
try {
|
|
30
|
+
return await fn();
|
|
31
|
+
} finally {
|
|
32
|
+
this.release();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private acquire(): Promise<void> {
|
|
37
|
+
if (this.signal?.aborted) return Promise.reject(new WorkflowAbortError());
|
|
38
|
+
if (this.active < this.limit) {
|
|
39
|
+
this.active++;
|
|
40
|
+
return Promise.resolve();
|
|
41
|
+
}
|
|
42
|
+
return new Promise<void>((resolve, reject) => this.queue.push({ resolve, reject }));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private release(): void {
|
|
46
|
+
const next = this.queue.shift();
|
|
47
|
+
if (next)
|
|
48
|
+
next.resolve(); // transfer the slot to the next waiter (active unchanged)
|
|
49
|
+
else this.active--;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
private drain(): void {
|
|
53
|
+
while (this.queue.length > 0) this.queue.shift()?.reject(new WorkflowAbortError());
|
|
54
|
+
}
|
|
55
|
+
}
|