@anureo/workflow 0.3.0 → 0.3.2
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 +96 -70
- package/package.json +18 -16
- package/src/agent-adapters.test.ts +121 -0
- package/src/agent-execution.ts +220 -0
- package/src/agent.test.ts +470 -0
- package/src/agent.ts +136 -0
- package/src/fixtures/workflow-crash.ts +69 -0
- package/src/index.ts +9 -0
- package/src/output-schema.test.ts +159 -0
- package/src/output-schema.ts +237 -0
- package/src/parallel.test.ts +96 -0
- package/src/parallel.ts +33 -0
- package/src/persistence/checkpoint-files.ts +83 -0
- package/src/persistence/journal.ts +132 -0
- package/src/persistence/json.ts +83 -0
- package/src/persistence/records.ts +103 -0
- package/src/persistence/replay.ts +93 -0
- package/src/persistence/store.ts +315 -0
- package/src/pipeline.test.ts +201 -0
- package/src/pipeline.ts +99 -0
- package/src/test-helpers.ts +23 -0
- package/src/workflow-state.ts +131 -0
- package/src/workflow-types.ts +38 -0
- package/src/workflow.test.ts +503 -0
- package/src/workflow.ts +112 -0
- package/tsconfig.json +13 -0
- package/LICENSE +0 -201
- package/src/agent-outcome.d.ts +0 -15
- package/src/agent-outcome.js +0 -28
- package/src/agent.d.ts +0 -49
- package/src/agent.js +0 -206
- package/src/index.d.ts +0 -6
- package/src/index.js +0 -5
- package/src/output-schema.d.ts +0 -27
- package/src/output-schema.js +0 -192
- package/src/parallel.d.ts +0 -18
- package/src/parallel.js +0 -25
- package/src/persistence/atomic.d.ts +0 -9
- package/src/persistence/atomic.js +0 -48
- package/src/persistence/journal.d.ts +0 -54
- package/src/persistence/journal.js +0 -106
- package/src/persistence/json.d.ts +0 -17
- package/src/persistence/json.js +0 -75
- package/src/persistence/read-json.d.ts +0 -11
- package/src/persistence/read-json.js +0 -46
- package/src/persistence/records.d.ts +0 -92
- package/src/persistence/records.js +0 -70
- package/src/persistence/replay.d.ts +0 -11
- package/src/persistence/replay.js +0 -79
- package/src/persistence/store.d.ts +0 -45
- package/src/persistence/store.js +0 -238
- package/src/pipeline.d.ts +0 -41
- package/src/pipeline.js +0 -24
- package/src/run-context.d.ts +0 -16
- package/src/run-context.js +0 -13
- package/src/test-helpers.d.ts +0 -11
- package/src/test-helpers.js +0 -21
- package/src/workflow-state.d.ts +0 -44
- package/src/workflow-state.js +0 -96
- package/src/workflow-types.d.ts +0 -39
- package/src/workflow-types.js +0 -0
- package/src/workflow.d.ts +0 -17
- package/src/workflow.js +0 -104
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { hostname } from 'node:os'
|
|
3
|
+
import { lstat, mkdir, open, readdir, realpath, unlink, type FileHandle } from 'node:fs/promises'
|
|
4
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
5
|
+
import { HarnessSdkError } from '@anureo/sdk'
|
|
6
|
+
import type { WorkflowOptions } from '../workflow-types'
|
|
7
|
+
import { atomicPublish, storageError, syncDirectory } from './checkpoint-files'
|
|
8
|
+
import { canonicalJson, digest, jsonCopy, type JsonValue } from './json'
|
|
9
|
+
import { AgentJournal } from './journal'
|
|
10
|
+
import { checkpointFormat, invalidCheckpoint, record, runIdSchema, type Manifest, type StoredFailure } from './records'
|
|
11
|
+
import { loadSourceJournal } from './replay'
|
|
12
|
+
|
|
13
|
+
/** Internal identity saved before workflow enters its body. */
|
|
14
|
+
export interface RunIdentity {
|
|
15
|
+
/** Validated basename of the run within directory. */
|
|
16
|
+
runId: string
|
|
17
|
+
/** Canonical parent containing the run's subdirectory. */
|
|
18
|
+
directory: string
|
|
19
|
+
/** Workflow name used to match a compatible source run. */
|
|
20
|
+
name: string
|
|
21
|
+
/** Application revision used to match a compatible source run. */
|
|
22
|
+
revision: string
|
|
23
|
+
/** Isolated persistence snapshot. The body receives its own frozen copy from prepareRun. */
|
|
24
|
+
input: JsonValue
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Internal storage ownership returned to workflow. Drain agent work before finish or abort,
|
|
28
|
+
* and always await close in finally. The handle serializes finish and abort. AgentJournal
|
|
29
|
+
* serializes its own appends. */
|
|
30
|
+
export interface RunHandle {
|
|
31
|
+
/** Provides the canonical storage directory for workflow's error details. */
|
|
32
|
+
readonly identity: RunIdentity
|
|
33
|
+
/** Installed by completeRun as the journal for agent calls in the body. */
|
|
34
|
+
readonly journal: AgentJournal
|
|
35
|
+
/** Publish result.json before the terminal manifest and resolve after both publications.
|
|
36
|
+
* A rejection may leave a result or manifest already replaced. A queued call that starts
|
|
37
|
+
* after closure rejects with WORKFLOW_CLOSED. */
|
|
38
|
+
finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void>
|
|
39
|
+
/** Publish a failed manifest and keep any earlier result file and the writer lock.
|
|
40
|
+
* Publication failures reject, as does a queued call that starts after closure. */
|
|
41
|
+
abort(failure: StoredFailure): Promise<void>
|
|
42
|
+
/** Wait for queued manifests, then release the owned writer lock and close its descriptor.
|
|
43
|
+
* Lock-release failures reject. Sequential repeats are no-ops, including after rejection.
|
|
44
|
+
* Callers must finish scheduling work before closure. */
|
|
45
|
+
close(): Promise<void>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Create a fresh file-backed run for workflow, publishing its journal and running manifest
|
|
49
|
+
* before returning. An optional inactive source supplies replay events, never the final result.
|
|
50
|
+
* The returned handle owns the writer lock and must be closed after registered agent work drains.
|
|
51
|
+
* SDK errors propagate unless lock rollback fails. Rollback failures and otherwise unclassified
|
|
52
|
+
* I/O failures reject as WORKFLOW_STORAGE_FAILED. If publication left run files behind,
|
|
53
|
+
* a later attempt on the same target rejects with WORKFLOW_RUN_EXISTS. */
|
|
54
|
+
export async function openFileRun(options: FileRunOptions): Promise<RunHandle> {
|
|
55
|
+
validateRunOptions(options)
|
|
56
|
+
try {
|
|
57
|
+
const prepared = await prepareRunStorage(options)
|
|
58
|
+
return await initializeLockedRun({ options, prepared })
|
|
59
|
+
} catch (cause) { throw storageError(cause) }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
type FileRunOptions = WorkflowOptions<JsonValue> & { runId: string }
|
|
63
|
+
type SourceRun = { directory: string; runId: string }
|
|
64
|
+
|
|
65
|
+
/** Storage coordinates prepared before claiming writer ownership. */
|
|
66
|
+
interface PreparedRun {
|
|
67
|
+
directory: string
|
|
68
|
+
path: string
|
|
69
|
+
input: JsonValue
|
|
70
|
+
source: SourceRun | null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Own the open lock descriptor and serialize manifest transitions until workflow releases it. */
|
|
74
|
+
class FileRunHandle implements RunHandle {
|
|
75
|
+
/** Take ownership only after initial publication; initialization retains rollback responsibility. */
|
|
76
|
+
constructor({ identity, path, lock, manifest, journal }: {
|
|
77
|
+
identity: RunIdentity
|
|
78
|
+
path: string
|
|
79
|
+
lock: FileHandle
|
|
80
|
+
manifest: Manifest
|
|
81
|
+
journal: AgentJournal
|
|
82
|
+
}) {
|
|
83
|
+
this.identity = identity
|
|
84
|
+
this.path = path
|
|
85
|
+
this.lock = lock
|
|
86
|
+
this.manifest = manifest
|
|
87
|
+
this.journal = journal
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** completeRun awaits both publications before returning the body result to workflow.
|
|
91
|
+
* The manifest comes last so it refers to an already published result. */
|
|
92
|
+
async finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void> {
|
|
93
|
+
await this.updateManifest(async () => {
|
|
94
|
+
const { journalDigest } = this.journal.checkpoint()
|
|
95
|
+
await atomicPublish(join(this.path, checkpointFormat.result), result)
|
|
96
|
+
await this.publishManifest({ status, journalDigest, resultDigest: digest(result), failure: null })
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** abortRun awaits this after draining. Replay treats the failed manifest as authoritative
|
|
101
|
+
* even if finish left an earlier result file. */
|
|
102
|
+
async abort(failure: StoredFailure): Promise<void> {
|
|
103
|
+
await this.updateManifest(async () => {
|
|
104
|
+
const { journalDigest, unpublishedUnknownFailures } = this.journal.checkpoint()
|
|
105
|
+
await this.publishManifest({ status: 'failed', journalDigest, resultDigest: null, failure: {
|
|
106
|
+
...failure,
|
|
107
|
+
...(unpublishedUnknownFailures.length ? { unpublishedUnknownFailures } : {}),
|
|
108
|
+
} })
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** workflow awaits this in finally and records any rejection as a storage failure.
|
|
113
|
+
* A failed publication already reached finish or abort, so proceed with lock release. */
|
|
114
|
+
async close(): Promise<void> {
|
|
115
|
+
if (this.closed) return
|
|
116
|
+
try {
|
|
117
|
+
await this.manifestQueue.catch(() => {})
|
|
118
|
+
await releaseLock(join(this.path, checkpointFormat.lock), this.lock)
|
|
119
|
+
} catch (cause) {
|
|
120
|
+
throw storageError(cause)
|
|
121
|
+
} finally {
|
|
122
|
+
this.closed = true
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
readonly identity: RunIdentity
|
|
127
|
+
readonly journal: AgentJournal
|
|
128
|
+
|
|
129
|
+
private closed = false
|
|
130
|
+
private manifestQueue: Promise<void> = Promise.resolve()
|
|
131
|
+
private readonly path: string
|
|
132
|
+
private readonly lock: FileHandle
|
|
133
|
+
private manifest: Manifest
|
|
134
|
+
|
|
135
|
+
/** Run finish/abort's publication callback in order, checking closure when it actually starts.
|
|
136
|
+
* A rejected predecessor still permits abort publication. Non-SDK failures are normalized. */
|
|
137
|
+
private updateManifest(update: () => Promise<void>): Promise<void> {
|
|
138
|
+
const next = this.manifestQueue.catch(() => {}).then(async () => {
|
|
139
|
+
if (this.closed) throw new HarnessSdkError('WORKFLOW_CLOSED')
|
|
140
|
+
try { await update() } catch (cause) { throw storageError(cause) }
|
|
141
|
+
})
|
|
142
|
+
this.manifestQueue = next
|
|
143
|
+
return next
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Recompute the digest from payload only for every terminal transition, then publish it.
|
|
147
|
+
* Keep the in-memory transition even if publication rejects, as abort may follow a failed finish. */
|
|
148
|
+
private async publishManifest(update: Pick<Manifest, 'status' | 'journalDigest' | 'resultDigest' | 'failure'>): Promise<void> {
|
|
149
|
+
const { recordDigest: _, ...payload } = this.manifest
|
|
150
|
+
this.manifest = record({ ...payload, ...update })
|
|
151
|
+
await atomicPublish(join(this.path, checkpointFormat.manifest), this.manifest)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Throw INVALID_PARAMS for malformed target identity before copying input or touching storage. */
|
|
156
|
+
function validateRunOptions(options: FileRunOptions): void {
|
|
157
|
+
const issues: string[] = []
|
|
158
|
+
if (!runIdSchema.safeParse(options.runId).success) {
|
|
159
|
+
issues.push('runId must be a valid directory basename (at most 255 UTF-8 bytes)')
|
|
160
|
+
}
|
|
161
|
+
if (typeof options.name !== 'string' || !options.name) issues.push('name must be a nonempty string')
|
|
162
|
+
if (typeof options.revision !== 'string' || !options.revision) issues.push('revision must be a nonempty string')
|
|
163
|
+
if (typeof options.directory !== 'string' || !options.directory) issues.push('directory must be a nonempty string')
|
|
164
|
+
if (issues.length) throw new HarnessSdkError('INVALID_PARAMS', `Invalid workflow options: ${issues.join(', ')}`)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Snapshot input, resolve parent/source paths, and create a real target directory before locking.
|
|
168
|
+
* Flush the parent when creating the target. Initialization checks existing contents under the lock. */
|
|
169
|
+
async function prepareRunStorage(options: FileRunOptions): Promise<PreparedRun> {
|
|
170
|
+
const input = jsonCopy(options.input)
|
|
171
|
+
const root = resolve(options.directory)
|
|
172
|
+
if (options.resumeFrom !== undefined && typeof options.resumeFrom !== 'string') {
|
|
173
|
+
const directory = await prospectiveDirectory(root)
|
|
174
|
+
await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path: join(directory, options.runId) })
|
|
175
|
+
}
|
|
176
|
+
await mkdir(root, { recursive: true, mode: 0o700 })
|
|
177
|
+
const directory = await realpath(root)
|
|
178
|
+
const path = join(directory, options.runId)
|
|
179
|
+
const source = await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path })
|
|
180
|
+
try {
|
|
181
|
+
await mkdir(path, { mode: 0o700 })
|
|
182
|
+
await syncDirectory(directory)
|
|
183
|
+
} catch (cause) {
|
|
184
|
+
if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause
|
|
185
|
+
}
|
|
186
|
+
if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
|
|
187
|
+
if (source && overlaps(await realpath(path), join(source.directory, source.runId))) {
|
|
188
|
+
throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
|
|
189
|
+
}
|
|
190
|
+
return { directory, path, input, source }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Resolve existing ancestors so the overlap check can run before creating a missing root. */
|
|
194
|
+
async function prospectiveDirectory(path: string): Promise<string> {
|
|
195
|
+
try {
|
|
196
|
+
return await realpath(path)
|
|
197
|
+
} catch (cause) {
|
|
198
|
+
const parent = dirname(path)
|
|
199
|
+
if ((cause as NodeJS.ErrnoException).code !== 'ENOENT' || parent === path) throw cause
|
|
200
|
+
return join(await prospectiveDirectory(parent), relative(parent, path))
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Resolve optional replay coordinates before target creation so overlapping source/target trees
|
|
205
|
+
* reject before a writer claim. Omission selects fresh execution. A string uses the target's
|
|
206
|
+
* canonical parent, while an object supplies its own parent to resolve. */
|
|
207
|
+
async function resolveSourceRun({ resumeFrom, directory, path }: {
|
|
208
|
+
resumeFrom: FileRunOptions['resumeFrom']
|
|
209
|
+
directory: string
|
|
210
|
+
path: string
|
|
211
|
+
}): Promise<SourceRun | null> {
|
|
212
|
+
if (resumeFrom === undefined) return null
|
|
213
|
+
const reference = typeof resumeFrom === 'string' ? { directory, runId: resumeFrom } : resumeFrom
|
|
214
|
+
if (!reference || !runIdSchema.safeParse(reference.runId).success || typeof reference.directory !== 'string') {
|
|
215
|
+
throw new HarnessSdkError('INVALID_PARAMS')
|
|
216
|
+
}
|
|
217
|
+
const source = { directory: await realpath(resolve(reference.directory)), runId: reference.runId }
|
|
218
|
+
if (overlaps(path, join(source.directory, source.runId))) throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
|
|
219
|
+
return source
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Exclusively claim and initialize the lock before inspecting target contents or source records.
|
|
223
|
+
* Transfer ownership only on successful publication; rollback also covers partial lock writes.
|
|
224
|
+
* Cleanup failure takes precedence as WORKFLOW_STORAGE_FAILED; other failures reach openFileRun. */
|
|
225
|
+
async function initializeLockedRun({ options, prepared }: {
|
|
226
|
+
options: FileRunOptions
|
|
227
|
+
prepared: PreparedRun
|
|
228
|
+
}): Promise<RunHandle> {
|
|
229
|
+
const lockPath = join(prepared.path, checkpointFormat.lock)
|
|
230
|
+
const lock = await open(lockPath, 'wx', 0o600).catch(cause => {
|
|
231
|
+
if ((cause as NodeJS.ErrnoException).code === 'EEXIST') throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
|
|
232
|
+
throw cause
|
|
233
|
+
})
|
|
234
|
+
try {
|
|
235
|
+
await writeWriterClaim(lock)
|
|
236
|
+
if ((await readdir(prepared.path)).some(name => name !== checkpointFormat.lock)) {
|
|
237
|
+
throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
|
|
238
|
+
}
|
|
239
|
+
return await publishInitialRun({ options, prepared, lock })
|
|
240
|
+
} catch (cause) {
|
|
241
|
+
try { await releaseLock(lockPath, lock) }
|
|
242
|
+
catch { throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED') }
|
|
243
|
+
throw cause
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Write and flush the claim on the exclusively opened descriptor. Replay validates this
|
|
248
|
+
* record before probing its writer, and initializeLockedRun owns rollback on rejection. */
|
|
249
|
+
async function writeWriterClaim(lock: FileHandle): Promise<void> {
|
|
250
|
+
const claim = record({
|
|
251
|
+
checkpointFormatVersion: checkpointFormat.version,
|
|
252
|
+
token: randomUUID(),
|
|
253
|
+
hostname: hostname(),
|
|
254
|
+
pid: process.pid,
|
|
255
|
+
createdAt: new Date().toISOString(),
|
|
256
|
+
})
|
|
257
|
+
await lock.writeFile(`${canonicalJson(claim)}\n`)
|
|
258
|
+
await lock.sync()
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Validate replay under the target lock, publish a self-contained journal before its manifest,
|
|
262
|
+
* then hand the descriptor to FileRunHandle. Failures leave lock cleanup to initializeLockedRun. */
|
|
263
|
+
async function publishInitialRun({ options, prepared, lock }: {
|
|
264
|
+
options: FileRunOptions
|
|
265
|
+
prepared: PreparedRun
|
|
266
|
+
lock: FileHandle
|
|
267
|
+
}): Promise<RunHandle> {
|
|
268
|
+
const { directory, path, input, source } = prepared
|
|
269
|
+
const inherited = source
|
|
270
|
+
? await loadSourceJournal(join(source.directory, source.runId), {
|
|
271
|
+
name: options.name, revision: options.revision, runId: source.runId,
|
|
272
|
+
})
|
|
273
|
+
: []
|
|
274
|
+
const journalPath = join(path, checkpointFormat.journal)
|
|
275
|
+
const journal = new AgentJournal(journalPath, inherited)
|
|
276
|
+
await atomicPublish(journalPath, [...inherited])
|
|
277
|
+
const identity = { runId: options.runId, directory, name: options.name, revision: options.revision, input }
|
|
278
|
+
const manifest: Manifest = record({
|
|
279
|
+
checkpointFormatVersion: checkpointFormat.version,
|
|
280
|
+
identity,
|
|
281
|
+
createdAt: new Date().toISOString(),
|
|
282
|
+
resumedFrom: source,
|
|
283
|
+
status: 'running',
|
|
284
|
+
journalDigest: null,
|
|
285
|
+
resultDigest: null,
|
|
286
|
+
failure: null,
|
|
287
|
+
})
|
|
288
|
+
await atomicPublish(join(path, checkpointFormat.manifest), manifest)
|
|
289
|
+
return new FileRunHandle({ identity, path, lock, manifest, journal })
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Detect equal or nested run trees in either direction. resolveSourceRun uses canonical
|
|
293
|
+
* parent directories so writes cannot overlap the selected source tree. */
|
|
294
|
+
function overlaps(a: string, b: string): boolean {
|
|
295
|
+
const inside = (parent: string, child: string) => {
|
|
296
|
+
const path = relative(parent, child)
|
|
297
|
+
return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path))
|
|
298
|
+
}
|
|
299
|
+
return inside(a, b) || inside(b, a)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Compare the on-disk entry with the held descriptor before unlinking, so rollback also works
|
|
303
|
+
* for a partially written lock. Flush the parent after unlinking and always close the descriptor.
|
|
304
|
+
* An observed inode or file kind mismatch rejects as WORKFLOW_LOCK_OWNERSHIP_LOST. */
|
|
305
|
+
async function releaseLock(path: string, handle: FileHandle): Promise<void> {
|
|
306
|
+
try {
|
|
307
|
+
const held = await handle.stat()
|
|
308
|
+
const actual = await lstat(path)
|
|
309
|
+
if (actual.dev !== held.dev || actual.ino !== held.ino || !actual.isFile()) {
|
|
310
|
+
throw new HarnessSdkError('WORKFLOW_LOCK_OWNERSHIP_LOST')
|
|
311
|
+
}
|
|
312
|
+
await unlink(path)
|
|
313
|
+
await syncDirectory(dirname(path))
|
|
314
|
+
} finally { await handle.close() }
|
|
315
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { pipeline } from './index'
|
|
3
|
+
|
|
4
|
+
test('a fast item reaches the next stage without waiting for a slow item', async () => {
|
|
5
|
+
let releaseSlow!: () => void
|
|
6
|
+
let reachedFast!: () => void
|
|
7
|
+
const slow = new Promise<void>(resolve => { releaseSlow = resolve })
|
|
8
|
+
const fast = new Promise<void>(resolve => { reachedFast = resolve })
|
|
9
|
+
const result = pipeline(
|
|
10
|
+
['fast', 'slow'],
|
|
11
|
+
async value => { if (value === 'slow') await slow; return { value } },
|
|
12
|
+
value => { if (value.value === 'fast') reachedFast(); return value.value.toUpperCase() },
|
|
13
|
+
)
|
|
14
|
+
await fast
|
|
15
|
+
releaseSlow()
|
|
16
|
+
expect(await result).toEqual(['FAST', 'SLOW'])
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
test('supports multiple asynchronous type transitions', async () => {
|
|
20
|
+
expect(await pipeline(
|
|
21
|
+
['one', 'four'],
|
|
22
|
+
value => ({ length: value.length }),
|
|
23
|
+
async value => value.length,
|
|
24
|
+
value => value > 3,
|
|
25
|
+
async value => value ? new Date(0) : null,
|
|
26
|
+
)).toEqual([null, new Date(0)])
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
test('supports one stage, empty input, and ordinary object identity', async () => {
|
|
30
|
+
const map = new Map([['key', 1]])
|
|
31
|
+
const values = await pipeline([map], value => value)
|
|
32
|
+
expect(values[0]).toBe(map)
|
|
33
|
+
expect(await pipeline([] as number[], value => value + 1)).toEqual([])
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test('supports arbitrarily long chains of typed stage functions', async () => {
|
|
37
|
+
const increment = (value: number) => value + 1
|
|
38
|
+
expect(await pipeline([0], increment, increment, increment, increment, increment, increment, increment, increment)).toEqual([8])
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
test('a failed item skips its remaining stages while other items continue', async () => {
|
|
42
|
+
const failure = new Error('bad item')
|
|
43
|
+
let release!: () => void
|
|
44
|
+
let completed!: () => void
|
|
45
|
+
const gate = new Promise<void>(resolve => { release = resolve })
|
|
46
|
+
const sibling = new Promise<void>(resolve => { completed = resolve })
|
|
47
|
+
const finalItems: number[] = []
|
|
48
|
+
let settled = false
|
|
49
|
+
const result = pipeline(
|
|
50
|
+
[1, 2],
|
|
51
|
+
async value => { if (value === 1) throw failure; await gate; return value },
|
|
52
|
+
value => { finalItems.push(value); completed(); return value },
|
|
53
|
+
).then(values => { settled = true; return values })
|
|
54
|
+
// Give the failed item's rejection handling a chance to advance before checking
|
|
55
|
+
// that the sibling blocked on gate keeps the pipeline pending. These two yields
|
|
56
|
+
// provide bounded scheduling progress, without guaranteeing failure handling is complete.
|
|
57
|
+
await Promise.resolve()
|
|
58
|
+
await Promise.resolve()
|
|
59
|
+
expect(settled).toBe(false)
|
|
60
|
+
expect(finalItems).toEqual([])
|
|
61
|
+
release()
|
|
62
|
+
await sibling
|
|
63
|
+
expect(finalItems).toEqual([2])
|
|
64
|
+
expect(await result).toEqual([null, 2])
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test('passes the previous result, original item and index to every stage', async () => {
|
|
68
|
+
const first = Promise.resolve('first')
|
|
69
|
+
const second = Promise.resolve('second')
|
|
70
|
+
const originals = [first, second] as const
|
|
71
|
+
const seen: unknown[][] = []
|
|
72
|
+
const result = await pipeline(
|
|
73
|
+
originals,
|
|
74
|
+
(value, original, index) => {
|
|
75
|
+
expect(original).toBe(originals[index]!)
|
|
76
|
+
seen.push([value, index])
|
|
77
|
+
return value.length
|
|
78
|
+
},
|
|
79
|
+
async (length, original, index) => {
|
|
80
|
+
expect(original).toBe(originals[index]!)
|
|
81
|
+
return { length, item: await original, index }
|
|
82
|
+
},
|
|
83
|
+
)
|
|
84
|
+
expect(seen).toEqual([['first', 0], ['second', 1]])
|
|
85
|
+
expect(result).toEqual([{ length: 5, item: 'first', index: 0 }, { length: 6, item: 'second', index: 1 }])
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test('snapshots input entries and indices before starting any item chain', async () => {
|
|
89
|
+
const resolved = Promise.resolve('first')
|
|
90
|
+
const first: PromiseLike<string> = {
|
|
91
|
+
get then() {
|
|
92
|
+
// Awaiting this entry reads `then` while the other item chains are still being started.
|
|
93
|
+
items.splice(1, 1, Promise.resolve('replacement'))
|
|
94
|
+
return resolved.then.bind(resolved)
|
|
95
|
+
},
|
|
96
|
+
}
|
|
97
|
+
const second = Promise.resolve('second')
|
|
98
|
+
const items = [first, second]
|
|
99
|
+
const results = await pipeline(items, (value, original, index) => ({ value, original, index }))
|
|
100
|
+
|
|
101
|
+
expect(results.map(result => result && [result.value, result.index])).toEqual([['first', 0], ['second', 1]])
|
|
102
|
+
expect(results[0]?.original).toBe(first)
|
|
103
|
+
expect(results[1]?.original).toBe(second)
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
test('null input or stage results skip later stages while other falsy values continue', async () => {
|
|
107
|
+
const entered: unknown[] = []
|
|
108
|
+
const next: unknown[] = []
|
|
109
|
+
const result = await pipeline(
|
|
110
|
+
[null, 0, false, '', undefined, 'drop'],
|
|
111
|
+
value => { entered.push(value); return value === 'drop' ? null : value },
|
|
112
|
+
value => { next.push(value); return value },
|
|
113
|
+
)
|
|
114
|
+
expect(result).toEqual([null, 0, false, '', undefined, null])
|
|
115
|
+
expect(entered).toEqual([0, false, '', undefined, 'drop'])
|
|
116
|
+
expect(next).toEqual([0, false, '', undefined])
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
test('isolates rejected input promises and synchronous stage failures', async () => {
|
|
120
|
+
const entered: number[] = []
|
|
121
|
+
expect(await pipeline(
|
|
122
|
+
[Promise.reject(new Error('input')), Promise.resolve(1), Promise.resolve(2)],
|
|
123
|
+
value => { entered.push(value); if (value === 1) throw new Error('stage'); return value * 10 },
|
|
124
|
+
)).toEqual([null, null, 20])
|
|
125
|
+
expect(entered).toEqual([1, 2])
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
test('zero stages await input values and convert input rejection to null', async () => {
|
|
129
|
+
expect(await pipeline([Promise.resolve(1), Promise.reject(new Error('failed')), null, 0, undefined])).toEqual([1, null, null, 0, undefined])
|
|
130
|
+
expect(await pipeline([])).toEqual([])
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
test('validates arrays and all stages before processing nonempty input', async () => {
|
|
134
|
+
let started = false
|
|
135
|
+
// @ts-expect-error invalid stage from a JavaScript caller
|
|
136
|
+
await expect(pipeline([1], () => { started = true }, undefined)).rejects.toBeInstanceOf(TypeError)
|
|
137
|
+
expect(started).toBe(false)
|
|
138
|
+
// @ts-expect-error array-like objects are not arrays
|
|
139
|
+
await expect(pipeline({ map: () => [] })).rejects.toBeInstanceOf(TypeError)
|
|
140
|
+
// @ts-expect-error missing input
|
|
141
|
+
await expect(pipeline()).rejects.toBeInstanceOf(TypeError)
|
|
142
|
+
// @ts-expect-error empty inputs return before validating stages, matching the reference
|
|
143
|
+
expect(await pipeline([], undefined)).toEqual([])
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
/** Compile-only assertions for stage compatibility, context and nullable results; never invoked at runtime. */
|
|
147
|
+
function checkTypes() {
|
|
148
|
+
const firstStage = (value: string) => value.length
|
|
149
|
+
const secondStage = (value: number) => value > 0
|
|
150
|
+
const namedStages: Promise<(boolean | null)[]> = pipeline(['x'], firstStage, secondStage)
|
|
151
|
+
const increment = (value: number) => value + 1
|
|
152
|
+
const longChain: Promise<(number | null)[]> = pipeline([0], increment, increment, increment, increment, increment, increment, increment)
|
|
153
|
+
// @ts-expect-error the last named stage cannot consume the preceding number
|
|
154
|
+
pipeline([0], increment, increment, increment, increment, increment, increment, (value: string) => value)
|
|
155
|
+
const result = pipeline(
|
|
156
|
+
['file.ts'],
|
|
157
|
+
file => ({ file, valid: true }),
|
|
158
|
+
async review => review.valid,
|
|
159
|
+
valid => valid ? 1 : 0,
|
|
160
|
+
)
|
|
161
|
+
const values: Promise<(number | null)[]> = result
|
|
162
|
+
// @ts-expect-error the last stage returns numbers
|
|
163
|
+
const wrong: Promise<(string | null)[]> = result
|
|
164
|
+
// @ts-expect-error failure or an earlier null result can skip the final stage
|
|
165
|
+
const missingNull: Promise<number[]> = result
|
|
166
|
+
// @ts-expect-error stage two expects a string but stage one produces a number
|
|
167
|
+
pipeline(['x'], value => value.length, (value: string) => value.toUpperCase())
|
|
168
|
+
// @ts-expect-error first stage must accept the input item type
|
|
169
|
+
pipeline([1], (value: string) => value)
|
|
170
|
+
const zero: Promise<(number | null)[]> = pipeline([Promise.resolve(1)])
|
|
171
|
+
const empty: Promise<null[]> = pipeline([])
|
|
172
|
+
const context = pipeline([Promise.resolve('x')], (value, original, index) => {
|
|
173
|
+
const text: string = value
|
|
174
|
+
const input: Promise<string> = original
|
|
175
|
+
const position: number = index
|
|
176
|
+
void input
|
|
177
|
+
return text.length + position
|
|
178
|
+
}, (value, original, index) => {
|
|
179
|
+
const length: number = value
|
|
180
|
+
const input: Promise<string> = original
|
|
181
|
+
void input
|
|
182
|
+
return length + index
|
|
183
|
+
})
|
|
184
|
+
const nullable: Promise<(number | null)[]> = pipeline([1], () => Math.random() ? null : 1, value => {
|
|
185
|
+
const number: number = value
|
|
186
|
+
return number + 1
|
|
187
|
+
})
|
|
188
|
+
pipeline([undefined as number | undefined | null], value => {
|
|
189
|
+
const allowed: number | undefined = value
|
|
190
|
+
// @ts-expect-error undefined is passed to stages normally
|
|
191
|
+
const required: number = value
|
|
192
|
+
void required
|
|
193
|
+
return allowed
|
|
194
|
+
})
|
|
195
|
+
const six = pipeline(['x'], value => value.length, value => value > 0,
|
|
196
|
+
value => ({ valid: value }), value => value.valid ? 'yes' : 'no',
|
|
197
|
+
(value, original, index) => value.length + original.length + index, value => value > 0)
|
|
198
|
+
const sixResult: Promise<(boolean | null)[]> = six
|
|
199
|
+
void values; void wrong; void missingNull; void namedStages; void longChain; void zero; void empty; void context; void nullable; void sixResult
|
|
200
|
+
}
|
|
201
|
+
void checkTypes
|
package/src/pipeline.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run each input through sequential stages at its own pace. Each stage receives the awaited input
|
|
3
|
+
* or prior result, the original array entry as supplied and its zero-based index in the snapshot.
|
|
4
|
+
* Inline stages infer their input types through six stages. Longer chains can use typed functions
|
|
5
|
+
* that accept the preceding stage's awaited result with `null` excluded.
|
|
6
|
+
*
|
|
7
|
+
* The promise resolves after all item chains settle and returns their final values in input order.
|
|
8
|
+
* An input or stage that resolves to `null` or rejects ends that item's chain with `null`.
|
|
9
|
+
* A synchronous stage throw has the same effect. Sibling chains continue after a failure,
|
|
10
|
+
* and other falsy values advance normally. With zero stages, return awaited inputs with
|
|
11
|
+
* rejections as `null`.
|
|
12
|
+
*
|
|
13
|
+
* Handle input and stage failures before they reach the pipeline to retain the original cause.
|
|
14
|
+
* The caller owns concurrency limits, cancellation, retries and resource cleanup for input
|
|
15
|
+
* work and stages. Return the work each stage needs the pipeline to await.
|
|
16
|
+
*
|
|
17
|
+
* A non-array input rejects with `TypeError`. The function snapshots the array and resolves to `[]`
|
|
18
|
+
* for an empty snapshot. For nonempty input, a non-function stage rejects with `TypeError` before
|
|
19
|
+
* item processing starts.
|
|
20
|
+
*/
|
|
21
|
+
export function pipeline<Input>(items: readonly Input[]): Promise<(Awaited<Input> | null)[]>
|
|
22
|
+
export function pipeline<A, B>(items: readonly A[], first: Stage<A, A, B>): Promise<(Awaited<B> | null)[]>
|
|
23
|
+
export function pipeline<A, B, C>(
|
|
24
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
25
|
+
): Promise<(Awaited<C> | null)[]>
|
|
26
|
+
export function pipeline<A, B, C, D>(
|
|
27
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
28
|
+
third: Stage<C, A, D>,
|
|
29
|
+
): Promise<(Awaited<D> | null)[]>
|
|
30
|
+
export function pipeline<A, B, C, D, E>(
|
|
31
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
32
|
+
third: Stage<C, A, D>, fourth: Stage<D, A, E>,
|
|
33
|
+
): Promise<(Awaited<E> | null)[]>
|
|
34
|
+
export function pipeline<A, B, C, D, E, F>(
|
|
35
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
36
|
+
third: Stage<C, A, D>, fourth: Stage<D, A, E>, fifth: Stage<E, A, F>,
|
|
37
|
+
): Promise<(Awaited<F> | null)[]>
|
|
38
|
+
export function pipeline<A, B, C, D, E, F, G>(
|
|
39
|
+
items: readonly A[], first: Stage<A, A, B>, second: Stage<B, A, C>,
|
|
40
|
+
third: Stage<C, A, D>, fourth: Stage<D, A, E>,
|
|
41
|
+
fifth: Stage<E, A, F>, sixth: Stage<F, A, G>,
|
|
42
|
+
): Promise<(Awaited<G> | null)[]>
|
|
43
|
+
/**
|
|
44
|
+
* Run a nonempty chain of typed stages, checking each stage against its predecessor. Resolve
|
|
45
|
+
* with the last stage's awaited results in input order, using `null` for failed or skipped items.
|
|
46
|
+
*/
|
|
47
|
+
export function pipeline<Input, Outputs extends readonly unknown[]>(
|
|
48
|
+
items: readonly Input[],
|
|
49
|
+
...stages: Stages<Input, Outputs> & { 0: Stage<Input, Input, unknown> }
|
|
50
|
+
): Promise<(LastAwaitedOutput<Outputs> | null)[]>
|
|
51
|
+
export async function pipeline(
|
|
52
|
+
items: readonly unknown[],
|
|
53
|
+
...stages: Stage<never, never, unknown>[]
|
|
54
|
+
): Promise<unknown[]> {
|
|
55
|
+
if (!Array.isArray(items)) throw new TypeError('pipeline expects an array as the first argument')
|
|
56
|
+
const inputs = [...items]
|
|
57
|
+
if (!inputs.length) return []
|
|
58
|
+
if (stages.some(stage => typeof stage !== 'function')) throw new TypeError('pipeline stages must be functions')
|
|
59
|
+
// The overloads check compatibility between adjacent stages. The runner only needs their order.
|
|
60
|
+
const orderedStages = stages as unknown as readonly Stage<unknown, unknown, unknown>[]
|
|
61
|
+
const settledItems = await Promise.allSettled(
|
|
62
|
+
inputs.map((originalItem, index) => runItem(originalItem, index, orderedStages)),
|
|
63
|
+
)
|
|
64
|
+
return settledItems.map(result => result.status === 'fulfilled' ? result.value : null)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Advance one pipeline item by awaiting its input and each stage in turn. Pass the original
|
|
69
|
+
* entry and snapshot index to every stage, and return early on `null`. Input rejections and
|
|
70
|
+
* stage errors reject this chain so `pipeline` can collect `null` at the item's original position.
|
|
71
|
+
*/
|
|
72
|
+
async function runItem(
|
|
73
|
+
originalItem: unknown,
|
|
74
|
+
index: number,
|
|
75
|
+
stages: readonly Stage<unknown, unknown, unknown>[],
|
|
76
|
+
): Promise<unknown> {
|
|
77
|
+
let value = await originalItem
|
|
78
|
+
for (const stage of stages) {
|
|
79
|
+
if (value === null) return null
|
|
80
|
+
value = await stage(value, originalItem, index)
|
|
81
|
+
}
|
|
82
|
+
return value
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Align each stage with its predecessor's output by prepending the original input type. */
|
|
86
|
+
type PreviousStageOutput<Input, Outputs extends readonly unknown[], K> =
|
|
87
|
+
K extends '0' ? Input : [Input, ...Outputs][K & keyof [Input, ...Outputs]]
|
|
88
|
+
|
|
89
|
+
/** Check each variadic stage against the preceding output while retaining the original input context. */
|
|
90
|
+
type Stages<Input, Outputs extends readonly unknown[]> = {
|
|
91
|
+
[K in keyof Outputs]: Stage<PreviousStageOutput<Input, Outputs, K>, Input, Outputs[K]>
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Infer the pipeline's resolved value type from the final stage of a typed chain. */
|
|
95
|
+
type LastAwaitedOutput<Outputs extends readonly unknown[]> =
|
|
96
|
+
Outputs extends readonly [...unknown[], infer Output] ? Awaited<Output> : never
|
|
97
|
+
|
|
98
|
+
/** Exclude only null from a stage's awaited input because null short-circuits the item at runtime. */
|
|
99
|
+
type Stage<Previous, Input, Output> = (value: Exclude<Awaited<Previous>, null>, originalItem: Input, index: number) => Output
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Scripted client setup shared by workflow tests; each suite retains its own disposal registry.
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { createClient, type Client } from '@anureo/sdk'
|
|
4
|
+
import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Give the agent and workflow suites a factory for initialized scripted clients. Register each
|
|
8
|
+
* initialized client in the caller's registry. Both suites dispose those clients in afterEach.
|
|
9
|
+
* Initialization failures reject before registration.
|
|
10
|
+
*/
|
|
11
|
+
export function createFixture(clients: Client[]) {
|
|
12
|
+
/**
|
|
13
|
+
* Forward optional hook and capability overrides to the scripted adapter. Return the initialized
|
|
14
|
+
* client and adapter for dispatch assertions. Give each fixture a distinct runtime identity so
|
|
15
|
+
* journal replay can distinguish clients.
|
|
16
|
+
*/
|
|
17
|
+
return async function fixture(options?: FakeAdapterOptions) {
|
|
18
|
+
const adapter = createScriptedAdapter(options)
|
|
19
|
+
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
|
|
20
|
+
clients.push(client)
|
|
21
|
+
return { client, adapter }
|
|
22
|
+
}
|
|
23
|
+
}
|