@multiplier-labs/stepflow 0.3.4 → 0.3.6
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 +9 -0
- package/dist/{chunk-U3PCVK6O.js → chunk-D5HW7VEG.js} +4 -2
- package/dist/chunk-D5HW7VEG.js.map +1 -0
- package/dist/{chunk-5XJBAPXF.js → chunk-JUPZEBR3.js} +3 -1
- package/dist/{chunk-5XJBAPXF.js.map → chunk-JUPZEBR3.js.map} +1 -1
- package/dist/events/index.d.ts +2 -0
- package/dist/events/index.js +1 -1
- package/dist/index.js +2 -2
- package/dist/storage/index.js +1 -1
- package/package.json +23 -12
- package/.codekin/reports/code-review/2026-04-11_code-review-daily.md +0 -146
- package/.codekin/reports/code-review/2026-04-13_code-review-daily.md +0 -74
- package/.codekin/reports/comments/2026-04-04_comment-assessment.md +0 -179
- package/.codekin/reports/comments/2026-04-11_comment-assessment.md +0 -161
- package/.codekin/reports/comments/2026-04-14_comment-assessment.md +0 -34
- package/.codekin/reports/complexity/2026-04-03_complexity-report.md +0 -152
- package/.codekin/reports/complexity/2026-04-11_complexity-report.md +0 -152
- package/.codekin/reports/complexity/2026-04-14_complexity-report.md +0 -34
- package/.codekin/reports/dependencies/2026-04-04_dependency-health.md +0 -94
- package/.codekin/reports/dependencies/2026-04-11_dependency-health.md +0 -93
- package/.codekin/reports/docs-audit/2026-04-04_docs-audit.md +0 -10
- package/.codekin/reports/docs-audit/2026-04-11_docs-audit.md +0 -138
- package/.codekin/reports/docs-audit/2026-04-13_docs-audit.md +0 -121
- package/.codekin/reports/security/2026-04-03_security-audit.md +0 -208
- package/.codekin/reports/security/2026-04-11_security-audit.md +0 -297
- package/.github/CODEOWNERS +0 -15
- package/.github/dependabot.yml +0 -23
- package/.github/workflows/ci.yml +0 -38
- package/.github/workflows/publish.yml +0 -42
- package/.github/workflows/security.yml +0 -29
- package/CHANGELOG.md +0 -34
- package/SECURITY.md +0 -40
- package/dist/chunk-U3PCVK6O.js.map +0 -1
- package/docs/github-packages-setup.md +0 -97
- package/docs/stepflow-api-reference.md +0 -1663
- package/src/core/engine/concurrency.ts +0 -229
- package/src/core/engine/lifecycle.ts +0 -176
- package/src/core/engine.test.ts +0 -1435
- package/src/core/engine.ts +0 -598
- package/src/core/index.ts +0 -7
- package/src/core/orchestrator/persistence.ts +0 -165
- package/src/core/orchestrator/plan-resolution.ts +0 -140
- package/src/core/orchestrator/state-transitions.ts +0 -109
- package/src/core/orchestrator/step-runner.ts +0 -427
- package/src/core/orchestrator.ts +0 -252
- package/src/core/types.ts +0 -220
- package/src/events/index.ts +0 -8
- package/src/events/memory.test.ts +0 -107
- package/src/events/memory.ts +0 -92
- package/src/events/socketio.test.ts +0 -378
- package/src/events/socketio.ts +0 -262
- package/src/events/types.ts +0 -118
- package/src/events/webhook.test.ts +0 -949
- package/src/events/webhook.ts +0 -807
- package/src/index.ts +0 -270
- package/src/planning/evaluate-condition.test.ts +0 -153
- package/src/planning/evaluate-condition.ts +0 -105
- package/src/planning/index.ts +0 -55
- package/src/planning/planner.ts +0 -494
- package/src/planning/planning.test.ts +0 -727
- package/src/planning/registry.test.ts +0 -398
- package/src/planning/registry.ts +0 -283
- package/src/planning/types.ts +0 -566
- package/src/scheduler/cron.test.ts +0 -479
- package/src/scheduler/cron.ts +0 -438
- package/src/scheduler/index.ts +0 -8
- package/src/scheduler/postgres-persistence.ts +0 -530
- package/src/scheduler/sqlite-persistence.test.ts +0 -235
- package/src/scheduler/sqlite-persistence.ts +0 -286
- package/src/scheduler/types.ts +0 -73
- package/src/storage/index.ts +0 -27
- package/src/storage/memory.test.ts +0 -349
- package/src/storage/memory.ts +0 -227
- package/src/storage/postgres-core.ts +0 -550
- package/src/storage/postgres-migration.test.ts +0 -69
- package/src/storage/postgres-transaction-pagination.test.ts +0 -107
- package/src/storage/postgres.ts +0 -835
- package/src/storage/sqlite-core.ts +0 -151
- package/src/storage/sqlite.test.ts +0 -642
- package/src/storage/sqlite.ts +0 -717
- package/src/storage/types.ts +0 -343
- package/src/utils/errors.test.ts +0 -150
- package/src/utils/errors.ts +0 -161
- package/src/utils/id.ts +0 -21
- package/src/utils/index.ts +0 -10
- package/src/utils/logger.test.ts +0 -121
- package/src/utils/logger.ts +0 -96
- package/src/utils/pinned-fetch.test.ts +0 -84
- package/src/utils/pinned-fetch.ts +0 -118
- package/src/utils/postgres-deps.ts +0 -79
- package/src/utils/retry.test.ts +0 -177
- package/src/utils/retry.ts +0 -121
- package/src/utils/safe-json.test.ts +0 -166
- package/src/utils/safe-json.ts +0 -107
- package/src/utils/webhook-signature.test.ts +0 -111
- package/src/utils/webhook-signature.ts +0 -74
- package/tsconfig.json +0 -21
- package/tsup.config.ts +0 -14
- package/vitest.config.ts +0 -9
package/src/core/engine.ts
DELETED
|
@@ -1,598 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Main WorkflowEngine class.
|
|
3
|
-
*
|
|
4
|
-
* This is the primary entry point for the workflow engine.
|
|
5
|
-
* It provides methods for registering workflows, starting runs,
|
|
6
|
-
* and managing workflow execution.
|
|
7
|
-
*
|
|
8
|
-
* Internal concerns are decomposed into co-located submodules under
|
|
9
|
-
* `./engine/` (see `engine/concurrency.ts`, `engine/lifecycle.ts`).
|
|
10
|
-
* WorkflowEngine itself stays the thin public face.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import type {
|
|
14
|
-
WorkflowKind,
|
|
15
|
-
WorkflowDefinition,
|
|
16
|
-
WorkflowContext,
|
|
17
|
-
Logger,
|
|
18
|
-
SpawnChildOptions,
|
|
19
|
-
} from './types';
|
|
20
|
-
import type { StorageAdapter, WorkflowRunRecord } from '../storage/types';
|
|
21
|
-
import type { EventTransport, EventCallback, Unsubscribe, WorkflowEvent } from '../events/types';
|
|
22
|
-
import { MemoryStorageAdapter } from '../storage/memory';
|
|
23
|
-
import { MemoryEventTransport } from '../events/memory';
|
|
24
|
-
import { executeWorkflow } from './orchestrator';
|
|
25
|
-
import {
|
|
26
|
-
WorkflowNotFoundError,
|
|
27
|
-
WorkflowAlreadyRegisteredError,
|
|
28
|
-
RunNotFoundError,
|
|
29
|
-
WaitForRunTimeoutError,
|
|
30
|
-
} from '../utils/errors';
|
|
31
|
-
import { ConsoleLogger } from '../utils/logger';
|
|
32
|
-
import { ConcurrencyManager, type QueuedRun } from './engine/concurrency';
|
|
33
|
-
import { LifecycleManager } from './engine/lifecycle';
|
|
34
|
-
|
|
35
|
-
// ============================================================================
|
|
36
|
-
// Configuration Types
|
|
37
|
-
// ============================================================================
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Configuration for the workflow engine.
|
|
41
|
-
*/
|
|
42
|
-
export interface WorkflowEngineConfig {
|
|
43
|
-
/** Storage adapter for persistence (default: MemoryStorageAdapter) */
|
|
44
|
-
storage?: StorageAdapter;
|
|
45
|
-
|
|
46
|
-
/** Event transport for real-time updates (default: MemoryEventTransport) */
|
|
47
|
-
events?: EventTransport;
|
|
48
|
-
|
|
49
|
-
/** Logger instance (default: ConsoleLogger) */
|
|
50
|
-
logger?: Logger;
|
|
51
|
-
|
|
52
|
-
/** Global settings */
|
|
53
|
-
settings?: {
|
|
54
|
-
/** Default timeout for workflows in ms */
|
|
55
|
-
defaultTimeout?: number;
|
|
56
|
-
|
|
57
|
-
/** Maximum concurrent workflows */
|
|
58
|
-
maxConcurrency?: number;
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Options for starting a workflow run.
|
|
64
|
-
*/
|
|
65
|
-
export interface StartRunOptions<TInput = Record<string, unknown>> {
|
|
66
|
-
/** Workflow type to run */
|
|
67
|
-
kind: WorkflowKind;
|
|
68
|
-
|
|
69
|
-
/** Input parameters */
|
|
70
|
-
input?: TInput;
|
|
71
|
-
|
|
72
|
-
/** Optional metadata (e.g., userId, topicId) */
|
|
73
|
-
metadata?: Record<string, unknown>;
|
|
74
|
-
|
|
75
|
-
/** Parent run ID (for child workflows) */
|
|
76
|
-
parentRunId?: string;
|
|
77
|
-
|
|
78
|
-
/** Delay before starting (ms) */
|
|
79
|
-
delay?: number;
|
|
80
|
-
|
|
81
|
-
/** Priority for queue ordering (higher = runs first, default: 0) */
|
|
82
|
-
priority?: number;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// ============================================================================
|
|
86
|
-
// WorkflowEngine Class
|
|
87
|
-
// ============================================================================
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Main workflow engine class.
|
|
91
|
-
*
|
|
92
|
-
* @example
|
|
93
|
-
* ```typescript
|
|
94
|
-
* const engine = new WorkflowEngine({
|
|
95
|
-
* storage: new MemoryStorageAdapter(),
|
|
96
|
-
* });
|
|
97
|
-
*
|
|
98
|
-
* engine.registerWorkflow({
|
|
99
|
-
* kind: 'my.workflow',
|
|
100
|
-
* name: 'My Workflow',
|
|
101
|
-
* steps: [
|
|
102
|
-
* {
|
|
103
|
-
* key: 'step1',
|
|
104
|
-
* name: 'First Step',
|
|
105
|
-
* handler: async (ctx) => {
|
|
106
|
-
* return { message: 'Hello!' };
|
|
107
|
-
* },
|
|
108
|
-
* },
|
|
109
|
-
* ],
|
|
110
|
-
* });
|
|
111
|
-
*
|
|
112
|
-
* const runId = await engine.startRun({ kind: 'my.workflow' });
|
|
113
|
-
* ```
|
|
114
|
-
*/
|
|
115
|
-
export class WorkflowEngine {
|
|
116
|
-
private registry = new Map<WorkflowKind, WorkflowDefinition>();
|
|
117
|
-
private storage: StorageAdapter;
|
|
118
|
-
private events: EventTransport;
|
|
119
|
-
private logger: Logger;
|
|
120
|
-
private settings: NonNullable<WorkflowEngineConfig['settings']>;
|
|
121
|
-
private concurrency: ConcurrencyManager;
|
|
122
|
-
private lifecycle: LifecycleManager;
|
|
123
|
-
|
|
124
|
-
constructor(config: WorkflowEngineConfig = {}) {
|
|
125
|
-
this.storage = config.storage ?? new MemoryStorageAdapter();
|
|
126
|
-
this.events = config.events ?? new MemoryEventTransport();
|
|
127
|
-
this.logger = config.logger ?? new ConsoleLogger();
|
|
128
|
-
this.settings = config.settings ?? {};
|
|
129
|
-
this.concurrency = new ConcurrencyManager({
|
|
130
|
-
storage: this.storage,
|
|
131
|
-
events: this.events,
|
|
132
|
-
logger: this.logger,
|
|
133
|
-
maxConcurrency: this.settings.maxConcurrency,
|
|
134
|
-
});
|
|
135
|
-
this.lifecycle = new LifecycleManager({
|
|
136
|
-
storage: this.storage,
|
|
137
|
-
events: this.events,
|
|
138
|
-
logger: this.logger,
|
|
139
|
-
registry: this.registry,
|
|
140
|
-
concurrency: this.concurrency,
|
|
141
|
-
launchRun: (runId, def, input, metadata, delay, checkpoint) =>
|
|
142
|
-
this.launchRun(runId, def, input, metadata, delay, checkpoint),
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* Initialize the engine and its storage/event adapters.
|
|
148
|
-
* Call this before starting runs if your storage adapter requires initialization
|
|
149
|
-
* (e.g., PostgresStorageAdapter).
|
|
150
|
-
*/
|
|
151
|
-
async initialize(): Promise<void> {
|
|
152
|
-
return this.lifecycle.initialize();
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Get the current number of active runs.
|
|
157
|
-
*/
|
|
158
|
-
getActiveRunCount(): number {
|
|
159
|
-
return this.concurrency.getActiveCount();
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* Get the number of queued runs waiting for capacity.
|
|
164
|
-
*/
|
|
165
|
-
getQueuedRunCount(): number {
|
|
166
|
-
return this.concurrency.getQueuedCount();
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
// ============================================================================
|
|
170
|
-
// Workflow Registration
|
|
171
|
-
// ============================================================================
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Register a workflow definition.
|
|
175
|
-
* Must be called before runs of this type can be started.
|
|
176
|
-
*
|
|
177
|
-
* @param definition - The workflow definition
|
|
178
|
-
* @throws WorkflowAlreadyRegisteredError if already registered
|
|
179
|
-
*/
|
|
180
|
-
registerWorkflow<TInput = Record<string, unknown>>(
|
|
181
|
-
definition: WorkflowDefinition<TInput>
|
|
182
|
-
): void {
|
|
183
|
-
if (this.registry.has(definition.kind)) {
|
|
184
|
-
throw new WorkflowAlreadyRegisteredError(definition.kind);
|
|
185
|
-
}
|
|
186
|
-
this.registry.set(definition.kind, definition as WorkflowDefinition);
|
|
187
|
-
this.logger.debug(`Registered workflow: ${definition.kind}`);
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/**
|
|
191
|
-
* Unregister a workflow definition.
|
|
192
|
-
*
|
|
193
|
-
* @param kind - The workflow kind to unregister
|
|
194
|
-
* @returns true if the workflow was unregistered, false if not found
|
|
195
|
-
*/
|
|
196
|
-
unregisterWorkflow(kind: WorkflowKind): boolean {
|
|
197
|
-
const deleted = this.registry.delete(kind);
|
|
198
|
-
if (deleted) {
|
|
199
|
-
this.logger.debug(`Unregistered workflow: ${kind}`);
|
|
200
|
-
}
|
|
201
|
-
return deleted;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
* Get a registered workflow definition.
|
|
206
|
-
*
|
|
207
|
-
* @param kind - The workflow kind
|
|
208
|
-
* @returns The workflow definition or undefined
|
|
209
|
-
*/
|
|
210
|
-
getWorkflow(kind: WorkflowKind): WorkflowDefinition | undefined {
|
|
211
|
-
return this.registry.get(kind);
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/**
|
|
215
|
-
* Get all registered workflow kinds.
|
|
216
|
-
*/
|
|
217
|
-
getRegisteredWorkflows(): WorkflowKind[] {
|
|
218
|
-
return Array.from(this.registry.keys());
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// ============================================================================
|
|
222
|
-
// Run Management
|
|
223
|
-
// ============================================================================
|
|
224
|
-
|
|
225
|
-
/**
|
|
226
|
-
* Start a new workflow run (non-blocking).
|
|
227
|
-
* The run executes asynchronously and this method returns immediately.
|
|
228
|
-
* If maxConcurrency is set and reached, the run is queued.
|
|
229
|
-
*
|
|
230
|
-
* @param options - Run options including kind and input
|
|
231
|
-
* @returns The generated run ID
|
|
232
|
-
* @throws WorkflowNotFoundError if the workflow kind is not registered
|
|
233
|
-
*/
|
|
234
|
-
async startRun<TInput = Record<string, unknown>>(
|
|
235
|
-
options: StartRunOptions<TInput>
|
|
236
|
-
): Promise<string> {
|
|
237
|
-
const definition = this.registry.get(options.kind);
|
|
238
|
-
if (!definition) {
|
|
239
|
-
throw new WorkflowNotFoundError(options.kind);
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// Create run record (status: queued)
|
|
243
|
-
const run = await this.storage.createRun({
|
|
244
|
-
kind: options.kind,
|
|
245
|
-
status: 'queued',
|
|
246
|
-
parentRunId: options.parentRunId,
|
|
247
|
-
input: (options.input ?? {}) as Record<string, unknown>,
|
|
248
|
-
metadata: options.metadata ?? {},
|
|
249
|
-
context: {},
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
const runId = run.id;
|
|
253
|
-
|
|
254
|
-
// Emit run created event
|
|
255
|
-
this.events.emit({
|
|
256
|
-
runId,
|
|
257
|
-
kind: options.kind,
|
|
258
|
-
eventType: 'run.created',
|
|
259
|
-
timestamp: new Date(),
|
|
260
|
-
payload: { input: options.input, metadata: options.metadata, priority: options.priority ?? 0 },
|
|
261
|
-
});
|
|
262
|
-
|
|
263
|
-
// Check if we have capacity to start immediately
|
|
264
|
-
if (this.concurrency.hasCapacity()) {
|
|
265
|
-
// Start execution immediately
|
|
266
|
-
this.executeRun(
|
|
267
|
-
runId,
|
|
268
|
-
definition,
|
|
269
|
-
(options.input ?? {}) as Record<string, unknown>,
|
|
270
|
-
options.metadata,
|
|
271
|
-
options.delay
|
|
272
|
-
);
|
|
273
|
-
} else {
|
|
274
|
-
// Queue the run for later execution
|
|
275
|
-
this.concurrency.enqueue({
|
|
276
|
-
runId,
|
|
277
|
-
definition,
|
|
278
|
-
input: (options.input ?? {}) as Record<string, unknown>,
|
|
279
|
-
metadata: options.metadata,
|
|
280
|
-
priority: options.priority ?? 0,
|
|
281
|
-
queuedAt: new Date(),
|
|
282
|
-
});
|
|
283
|
-
|
|
284
|
-
this.logger.debug(`Run ${runId} queued (${this.concurrency.getQueuedCount()} in queue)`);
|
|
285
|
-
|
|
286
|
-
// Emit queued event
|
|
287
|
-
this.events.emit({
|
|
288
|
-
runId,
|
|
289
|
-
kind: options.kind,
|
|
290
|
-
eventType: 'run.queued',
|
|
291
|
-
timestamp: new Date(),
|
|
292
|
-
payload: { queuePosition: this.concurrency.getQueuedCount() },
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
return runId;
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
/**
|
|
300
|
-
* Execute a run (internal method).
|
|
301
|
-
*/
|
|
302
|
-
private executeRun(
|
|
303
|
-
runId: string,
|
|
304
|
-
definition: WorkflowDefinition,
|
|
305
|
-
input: Record<string, unknown>,
|
|
306
|
-
metadata?: Record<string, unknown>,
|
|
307
|
-
delay?: number
|
|
308
|
-
): void {
|
|
309
|
-
this.launchRun(runId, definition, input, metadata, delay);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/**
|
|
313
|
-
* Launch a workflow run asynchronously.
|
|
314
|
-
* Shared by both executeRun (new runs) and resumeRun (checkpoint recovery).
|
|
315
|
-
*/
|
|
316
|
-
private launchRun(
|
|
317
|
-
runId: string,
|
|
318
|
-
definition: WorkflowDefinition,
|
|
319
|
-
input: Record<string, unknown>,
|
|
320
|
-
metadata?: Record<string, unknown>,
|
|
321
|
-
delay?: number,
|
|
322
|
-
checkpoint?: { completedStepKeys: Set<string>; results: Record<string, unknown> }
|
|
323
|
-
): void {
|
|
324
|
-
const abortController = new AbortController();
|
|
325
|
-
this.concurrency.registerActive(runId, abortController);
|
|
326
|
-
|
|
327
|
-
const execute = async () => {
|
|
328
|
-
try {
|
|
329
|
-
await executeWorkflow({
|
|
330
|
-
runId,
|
|
331
|
-
definition,
|
|
332
|
-
input,
|
|
333
|
-
metadata,
|
|
334
|
-
storage: this.storage,
|
|
335
|
-
events: this.events,
|
|
336
|
-
logger: this.logger,
|
|
337
|
-
abortController,
|
|
338
|
-
spawnChild: (childOptions: SpawnChildOptions) => this.spawnChild(runId, childOptions),
|
|
339
|
-
checkpoint,
|
|
340
|
-
});
|
|
341
|
-
} finally {
|
|
342
|
-
this.concurrency.unregisterActive(runId);
|
|
343
|
-
this.processQueue();
|
|
344
|
-
}
|
|
345
|
-
};
|
|
346
|
-
|
|
347
|
-
// executeWorkflow has its own try/catch that converts errors into a failed
|
|
348
|
-
// run record, but the surrounding `finally` (unregisterActive + processQueue)
|
|
349
|
-
// could still throw, and `setTimeout`/`setImmediate` discards the returned
|
|
350
|
-
// promise — leaving any rejection unhandled and capable of crashing Node.
|
|
351
|
-
// Wrap the launch so those rejections are logged instead.
|
|
352
|
-
const guarded = () => {
|
|
353
|
-
execute().catch((err) => {
|
|
354
|
-
this.concurrency.unregisterActive(runId);
|
|
355
|
-
this.logger.error(`Unhandled error launching run ${runId}`, err);
|
|
356
|
-
});
|
|
357
|
-
};
|
|
358
|
-
|
|
359
|
-
this.concurrency.scheduleLaunch(guarded, delay);
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
/**
|
|
363
|
-
* Drain the queue, dispatching each ready run via `executeRun`. Resilience
|
|
364
|
-
* against per-item dispatch failures lives in `ConcurrencyManager.processQueue`.
|
|
365
|
-
*/
|
|
366
|
-
private processQueue(): void {
|
|
367
|
-
this.concurrency.processQueue((next) => {
|
|
368
|
-
this.executeRun(next.runId, next.definition, next.input, next.metadata);
|
|
369
|
-
});
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* Start a child workflow from within a parent workflow.
|
|
374
|
-
* Called internally by the context.spawnChild helper.
|
|
375
|
-
*/
|
|
376
|
-
private async spawnChild(parentRunId: string, options: SpawnChildOptions): Promise<string> {
|
|
377
|
-
return this.startRun({
|
|
378
|
-
kind: options.kind,
|
|
379
|
-
input: options.input,
|
|
380
|
-
metadata: options.metadata,
|
|
381
|
-
parentRunId,
|
|
382
|
-
});
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
/**
|
|
386
|
-
* Cancel a running workflow.
|
|
387
|
-
* Signals the workflow to stop at the next cancellation point.
|
|
388
|
-
*
|
|
389
|
-
* @param runId - The run ID to cancel
|
|
390
|
-
* @throws {RunNotFoundError} If no run with the given ID exists
|
|
391
|
-
*/
|
|
392
|
-
async cancelRun(runId: string): Promise<void> {
|
|
393
|
-
const run = await this.storage.getRun(runId);
|
|
394
|
-
if (!run) {
|
|
395
|
-
throw new RunNotFoundError(runId);
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
// Don't overwrite terminal statuses
|
|
399
|
-
if (['succeeded', 'failed', 'canceled', 'timeout'].includes(run.status)) {
|
|
400
|
-
return;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
// Remove from queue if queued, then signal abort if active
|
|
404
|
-
this.concurrency.removeFromQueue(runId);
|
|
405
|
-
this.concurrency.abortActive(runId);
|
|
406
|
-
|
|
407
|
-
// Update status in storage (the orchestrator will also update on completion)
|
|
408
|
-
await this.storage.updateRun(runId, {
|
|
409
|
-
status: 'canceled',
|
|
410
|
-
finishedAt: new Date(),
|
|
411
|
-
});
|
|
412
|
-
|
|
413
|
-
this.events.emit({
|
|
414
|
-
runId,
|
|
415
|
-
kind: run.kind,
|
|
416
|
-
eventType: 'run.canceled',
|
|
417
|
-
timestamp: new Date(),
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
/**
|
|
422
|
-
* Get the current status of a run.
|
|
423
|
-
*
|
|
424
|
-
* @param runId - The run ID to look up
|
|
425
|
-
* @returns The run record or null if not found
|
|
426
|
-
*/
|
|
427
|
-
async getRunStatus(runId: string): Promise<WorkflowRunRecord | null> {
|
|
428
|
-
return this.storage.getRun(runId);
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
private static readonly TERMINAL_STATUSES = ['succeeded', 'failed', 'canceled', 'timeout'];
|
|
432
|
-
private static readonly TERMINAL_EVENT_TYPES = ['run.completed', 'run.failed', 'run.canceled', 'run.timeout'];
|
|
433
|
-
|
|
434
|
-
/**
|
|
435
|
-
* Wait for a run to complete.
|
|
436
|
-
* Subscribes to run events and resolves when a terminal event fires.
|
|
437
|
-
* Falls back to an initial storage read to avoid race conditions.
|
|
438
|
-
*
|
|
439
|
-
* @param runId - The run ID to wait for
|
|
440
|
-
* @param options - Wait options
|
|
441
|
-
* @returns The final run record
|
|
442
|
-
*/
|
|
443
|
-
async waitForRun(
|
|
444
|
-
runId: string,
|
|
445
|
-
options: { timeout?: number } = {}
|
|
446
|
-
): Promise<WorkflowRunRecord> {
|
|
447
|
-
const timeout = options.timeout ?? 60000;
|
|
448
|
-
|
|
449
|
-
return new Promise<WorkflowRunRecord>(async (resolve, reject) => {
|
|
450
|
-
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
451
|
-
let unsubscribe: (() => void) | undefined;
|
|
452
|
-
let settled = false;
|
|
453
|
-
|
|
454
|
-
const cleanup = () => {
|
|
455
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
456
|
-
if (unsubscribe) unsubscribe();
|
|
457
|
-
};
|
|
458
|
-
|
|
459
|
-
const settle = (fn: () => void) => {
|
|
460
|
-
if (settled) return;
|
|
461
|
-
settled = true;
|
|
462
|
-
cleanup();
|
|
463
|
-
fn();
|
|
464
|
-
};
|
|
465
|
-
|
|
466
|
-
// Set up timeout
|
|
467
|
-
timeoutId = setTimeout(() => {
|
|
468
|
-
settle(() => reject(new WaitForRunTimeoutError(runId, timeout)));
|
|
469
|
-
}, timeout);
|
|
470
|
-
|
|
471
|
-
// Subscribe to run events FIRST to avoid missing terminal events
|
|
472
|
-
unsubscribe = this.events.subscribe(runId, async (event) => {
|
|
473
|
-
if (WorkflowEngine.TERMINAL_EVENT_TYPES.includes(event.eventType)) {
|
|
474
|
-
try {
|
|
475
|
-
const run = await this.storage.getRun(runId);
|
|
476
|
-
settle(() => {
|
|
477
|
-
if (!run) {
|
|
478
|
-
reject(new RunNotFoundError(runId));
|
|
479
|
-
} else {
|
|
480
|
-
resolve(run);
|
|
481
|
-
}
|
|
482
|
-
});
|
|
483
|
-
} catch (err) {
|
|
484
|
-
settle(() => reject(err));
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
});
|
|
488
|
-
|
|
489
|
-
// THEN check storage for already-terminal runs
|
|
490
|
-
try {
|
|
491
|
-
const existingRun = await this.storage.getRun(runId);
|
|
492
|
-
if (!existingRun) {
|
|
493
|
-
settle(() => reject(new RunNotFoundError(runId)));
|
|
494
|
-
return;
|
|
495
|
-
}
|
|
496
|
-
if (WorkflowEngine.TERMINAL_STATUSES.includes(existingRun.status)) {
|
|
497
|
-
settle(() => resolve(existingRun));
|
|
498
|
-
return;
|
|
499
|
-
}
|
|
500
|
-
} catch (err) {
|
|
501
|
-
settle(() => reject(err));
|
|
502
|
-
}
|
|
503
|
-
});
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
// ============================================================================
|
|
507
|
-
// Resume Support
|
|
508
|
-
// ============================================================================
|
|
509
|
-
|
|
510
|
-
/**
|
|
511
|
-
* Resume an interrupted workflow run from its checkpoint.
|
|
512
|
-
* The run must be in 'queued' or 'running' status.
|
|
513
|
-
*
|
|
514
|
-
* @param runId - The run ID to resume
|
|
515
|
-
* @returns The run ID (same as input)
|
|
516
|
-
* @throws {RunNotFoundError} If no run with the given ID exists
|
|
517
|
-
* @throws {Error} If the run status is not 'queued' or 'running'
|
|
518
|
-
* @throws {WorkflowNotFoundError} If the workflow kind is not registered
|
|
519
|
-
*/
|
|
520
|
-
async resumeRun(runId: string): Promise<string> {
|
|
521
|
-
return this.lifecycle.resumeRun(runId);
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* Get all runs that were interrupted and can be resumed.
|
|
526
|
-
* Returns runs with status 'queued' or 'running'.
|
|
527
|
-
*/
|
|
528
|
-
async getResumableRuns(): Promise<WorkflowRunRecord[]> {
|
|
529
|
-
return this.lifecycle.getResumableRuns();
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
/**
|
|
533
|
-
* Resume all interrupted runs.
|
|
534
|
-
* Useful for recovering after a server restart.
|
|
535
|
-
*
|
|
536
|
-
* @returns Array of resumed run IDs
|
|
537
|
-
*/
|
|
538
|
-
async resumeAllInterrupted(): Promise<string[]> {
|
|
539
|
-
return this.lifecycle.resumeAllInterrupted();
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
// ============================================================================
|
|
543
|
-
// Event Subscription
|
|
544
|
-
// ============================================================================
|
|
545
|
-
|
|
546
|
-
/**
|
|
547
|
-
* Subscribe to events for a specific run.
|
|
548
|
-
*
|
|
549
|
-
* @param runId - The run ID to subscribe to
|
|
550
|
-
* @param callback - Event handler
|
|
551
|
-
* @returns Unsubscribe function
|
|
552
|
-
*/
|
|
553
|
-
subscribeToRun(runId: string, callback: EventCallback): Unsubscribe {
|
|
554
|
-
return this.events.subscribe(runId, callback);
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
/**
|
|
558
|
-
* Subscribe to all workflow events.
|
|
559
|
-
*
|
|
560
|
-
* @param callback - Event handler
|
|
561
|
-
* @returns Unsubscribe function
|
|
562
|
-
*/
|
|
563
|
-
subscribeToAll(callback: EventCallback): Unsubscribe {
|
|
564
|
-
return this.events.subscribeAll(callback);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
// ============================================================================
|
|
568
|
-
// Storage Access
|
|
569
|
-
// ============================================================================
|
|
570
|
-
|
|
571
|
-
/**
|
|
572
|
-
* Get the storage adapter.
|
|
573
|
-
* Useful for querying runs and steps directly.
|
|
574
|
-
*/
|
|
575
|
-
getStorage(): StorageAdapter {
|
|
576
|
-
return this.storage;
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
/**
|
|
580
|
-
* Get the event transport.
|
|
581
|
-
* Useful for custom event handling.
|
|
582
|
-
*/
|
|
583
|
-
getEvents(): EventTransport {
|
|
584
|
-
return this.events;
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
// ============================================================================
|
|
588
|
-
// Lifecycle
|
|
589
|
-
// ============================================================================
|
|
590
|
-
|
|
591
|
-
/**
|
|
592
|
-
* Shutdown the engine gracefully.
|
|
593
|
-
* Cancels all active runs and closes resources.
|
|
594
|
-
*/
|
|
595
|
-
async shutdown(): Promise<void> {
|
|
596
|
-
return this.lifecycle.shutdown();
|
|
597
|
-
}
|
|
598
|
-
}
|