@workflow/world-postgres 4.1.0-beta.9 → 4.1.1

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.
Files changed (62) hide show
  1. package/README.md +48 -8
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +14 -13
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +17 -2
  6. package/dist/config.d.ts.map +1 -1
  7. package/dist/config.js.map +1 -1
  8. package/dist/drizzle/cbor.d.ts +38 -0
  9. package/dist/drizzle/cbor.d.ts.map +1 -0
  10. package/dist/drizzle/cbor.js +10 -0
  11. package/dist/drizzle/cbor.js.map +1 -0
  12. package/dist/drizzle/index.d.ts +4 -2
  13. package/dist/drizzle/index.d.ts.map +1 -1
  14. package/dist/drizzle/index.js +3 -3
  15. package/dist/drizzle/index.js.map +1 -1
  16. package/dist/drizzle/schema.d.ts +756 -59
  17. package/dist/drizzle/schema.d.ts.map +1 -1
  18. package/dist/drizzle/schema.js +68 -37
  19. package/dist/drizzle/schema.js.map +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +28 -9
  22. package/dist/index.js.map +1 -1
  23. package/dist/message.d.ts +16 -0
  24. package/dist/message.d.ts.map +1 -0
  25. package/dist/{boss.js → message.js} +7 -6
  26. package/dist/message.js.map +1 -0
  27. package/dist/queue.d.ts +8 -6
  28. package/dist/queue.d.ts.map +1 -1
  29. package/dist/queue.js +335 -59
  30. package/dist/queue.js.map +1 -1
  31. package/dist/storage.d.ts.map +1 -1
  32. package/dist/storage.js +1046 -232
  33. package/dist/storage.js.map +1 -1
  34. package/dist/streamer.d.ts +13 -2
  35. package/dist/streamer.d.ts.map +1 -1
  36. package/dist/streamer.js +184 -12
  37. package/dist/streamer.js.map +1 -1
  38. package/dist/util.js.map +1 -1
  39. package/dist/zod.d.ts +1 -1
  40. package/dist/zod.d.ts.map +1 -1
  41. package/dist/zod.js +1 -1
  42. package/dist/zod.js.map +1 -1
  43. package/package.json +22 -19
  44. package/src/drizzle/migrations/{0000_redundant_smasher.sql → 0000_cultured_the_anarchist.sql} +17 -13
  45. package/src/drizzle/migrations/0001_tricky_sersi.sql +11 -0
  46. package/src/drizzle/migrations/0002_add_expired_at.sql +2 -0
  47. package/src/drizzle/migrations/0003_add_stream_run_id.sql +3 -0
  48. package/src/drizzle/migrations/0004_remove_run_pause_status.sql +14 -0
  49. package/src/drizzle/migrations/0005_add_spec_version.sql +5 -0
  50. package/src/drizzle/migrations/0006_add_error_cbor.sql +5 -0
  51. package/src/drizzle/migrations/0007_add_waits_table.sql +13 -0
  52. package/src/drizzle/migrations/0008_migrate_pgboss_to_graphile.sql +20 -0
  53. package/src/drizzle/migrations/0009_add_is_webhook.sql +1 -0
  54. package/src/drizzle/migrations/meta/0000_snapshot.json +499 -0
  55. package/src/drizzle/migrations/meta/0001_snapshot.json +548 -0
  56. package/src/drizzle/migrations/meta/0002_snapshot.json +554 -0
  57. package/src/drizzle/migrations/meta/0003_snapshot.json +576 -0
  58. package/src/drizzle/migrations/meta/0005_snapshot.json +575 -0
  59. package/src/drizzle/migrations/meta/_journal.json +76 -0
  60. package/dist/boss.d.ts +0 -15
  61. package/dist/boss.d.ts.map +0 -1
  62. package/dist/boss.js.map +0 -1
package/dist/storage.js CHANGED
@@ -1,10 +1,67 @@
1
- import { WorkflowAPIError } from '@workflow/errors';
2
- import { and, desc, eq, gt, lt, sql } from 'drizzle-orm';
1
+ import { EntityConflictError, HookNotFoundError, RunExpiredError, RunNotSupportedError, TooEarlyError, WorkflowRunNotFoundError, WorkflowWorldError, } from '@workflow/errors';
2
+ import { EventSchema, HookSchema, isLegacySpecVersion, requiresNewerWorld, SPEC_VERSION_CURRENT, StepSchema, stripEventDataRefs, validateUlidTimestamp, WorkflowRunSchema, } from '@workflow/world';
3
+ import { and, asc, desc, eq, gt, lt, notInArray, sql } from 'drizzle-orm';
3
4
  import { monotonicFactory } from 'ulid';
4
5
  import { Schema } from './drizzle/index.js';
5
6
  import { compact } from './util.js';
7
+ /**
8
+ * Parse legacy errorJson (text column with JSON-stringified StructuredError).
9
+ * Used for backwards compatibility when reading from deprecated error column.
10
+ */
11
+ function parseErrorJson(errorJson) {
12
+ if (!errorJson)
13
+ return null;
14
+ try {
15
+ const parsed = JSON.parse(errorJson);
16
+ if (typeof parsed === 'object' && parsed.message !== undefined) {
17
+ return {
18
+ message: parsed.message,
19
+ stack: parsed.stack,
20
+ code: parsed.code,
21
+ };
22
+ }
23
+ // Not a structured error object, treat as plain string
24
+ return { message: String(parsed) };
25
+ }
26
+ catch {
27
+ // Not JSON, treat as plain string error message
28
+ return { message: errorJson };
29
+ }
30
+ }
31
+ /**
32
+ * Deserialize run data, handling legacy error fields.
33
+ * The error field should already be deserialized from CBOR or fallback to errorJson.
34
+ * This function only handles very old legacy fields (errorStack, errorCode).
35
+ */
36
+ function deserializeRunError(run) {
37
+ const { errorStack, errorCode, ...rest } = run;
38
+ // If no legacy fields, return as-is (error is already a StructuredError or undefined)
39
+ if (!errorStack && !errorCode) {
40
+ return rest;
41
+ }
42
+ // Very old legacy: separate errorStack/errorCode fields
43
+ const existingError = rest.error;
44
+ return {
45
+ ...rest,
46
+ error: {
47
+ message: existingError?.message || '',
48
+ stack: existingError?.stack || errorStack,
49
+ code: existingError?.code || errorCode,
50
+ },
51
+ };
52
+ }
53
+ /**
54
+ * Deserialize step data, mapping DB columns to interface fields.
55
+ * The error field should already be deserialized from CBOR or fallback to errorJson.
56
+ */
57
+ function deserializeStepError(step) {
58
+ const { startedAt, ...rest } = step;
59
+ return {
60
+ ...rest,
61
+ startedAt,
62
+ };
63
+ }
6
64
  export function createRunsStorage(drizzle) {
7
- const ulid = monotonicFactory();
8
65
  const { runs } = Schema;
9
66
  const get = drizzle
10
67
  .select()
@@ -13,67 +70,21 @@ export function createRunsStorage(drizzle) {
13
70
  .limit(1)
14
71
  .prepare('workflow_runs_get');
15
72
  return {
16
- async get(id) {
73
+ get: (async (id, params) => {
17
74
  const [value] = await get.execute({ id });
18
75
  if (!value) {
19
- throw new WorkflowAPIError(`Run not found: ${id}`, { status: 404 });
20
- }
21
- return compact(value);
22
- },
23
- async cancel(id) {
24
- // TODO: we might want to guard this for only specific statuses
25
- const [value] = await drizzle
26
- .update(Schema.runs)
27
- .set({ status: 'cancelled', completedAt: sql `now()` })
28
- .where(eq(runs.runId, id))
29
- .returning();
30
- if (!value) {
31
- throw new WorkflowAPIError(`Run not found: ${id}`, { status: 404 });
32
- }
33
- return compact(value);
34
- },
35
- async pause(id) {
36
- // TODO: we might want to guard this for only specific statuses
37
- const [value] = await drizzle
38
- .update(Schema.runs)
39
- .set({ status: 'paused' })
40
- .where(eq(runs.runId, id))
41
- .returning();
42
- if (!value) {
43
- throw new WorkflowAPIError(`Run not found: ${id}`, { status: 404 });
76
+ throw new WorkflowRunNotFoundError(id);
44
77
  }
45
- return compact(value);
46
- },
47
- async resume(id) {
48
- // Fetch current run to check if startedAt is already set
49
- const [currentRun] = await drizzle
50
- .select()
51
- .from(runs)
52
- .where(eq(runs.runId, id))
53
- .limit(1);
54
- if (!currentRun) {
55
- throw new WorkflowAPIError(`Run not found: ${id}`, { status: 404 });
56
- }
57
- const updates = {
58
- status: 'running',
59
- };
60
- // Only set startedAt the first time the run transitions to 'running'
61
- if (!currentRun.startedAt) {
62
- updates.startedAt = new Date();
63
- }
64
- const [value] = await drizzle
65
- .update(Schema.runs)
66
- .set(updates)
67
- .where(and(eq(runs.runId, id), eq(runs.status, 'paused')))
68
- .returning();
69
- if (!value) {
70
- throw new WorkflowAPIError(`Paused run not found: ${id}`, {
71
- status: 404,
72
- });
73
- }
74
- return compact(value);
75
- },
76
- async list(params) {
78
+ value.output ||= value.outputJson;
79
+ value.input ||= value.inputJson;
80
+ value.executionContext ||= value.executionContextJson;
81
+ value.error ||= parseErrorJson(value.errorJson);
82
+ const deserialized = deserializeRunError(compact(value));
83
+ const parsed = WorkflowRunSchema.parse(deserialized);
84
+ const resolveData = params?.resolveData ?? 'all';
85
+ return filterRunData(parsed, resolveData);
86
+ }),
87
+ list: (async (params) => {
77
88
  const limit = params?.pagination?.limit ?? 20;
78
89
  const fromCursor = params?.pagination?.cursor;
79
90
  const all = await drizzle
@@ -84,93 +95,927 @@ export function createRunsStorage(drizzle) {
84
95
  .limit(limit + 1);
85
96
  const values = all.slice(0, limit);
86
97
  const hasMore = all.length > limit;
98
+ const resolveData = params?.resolveData ?? 'all';
87
99
  return {
88
- data: values.map(compact),
100
+ data: values.map((v) => {
101
+ v.output ||= v.outputJson;
102
+ v.input ||= v.inputJson;
103
+ v.executionContext ||= v.executionContextJson;
104
+ v.error ||= parseErrorJson(v.errorJson);
105
+ const deserialized = deserializeRunError(compact(v));
106
+ const parsed = WorkflowRunSchema.parse(deserialized);
107
+ return filterRunData(parsed, resolveData);
108
+ }),
89
109
  hasMore,
90
110
  cursor: values.at(-1)?.runId ?? null,
91
111
  };
92
- },
93
- async create(data) {
94
- const runId = `wrun_${ulid()}`;
95
- const [value] = await drizzle
96
- .insert(runs)
97
- .values({
98
- runId,
99
- input: data.input,
100
- executionContext: data.executionContext,
101
- deploymentId: data.deploymentId,
102
- status: 'pending',
103
- workflowName: data.workflowName,
104
- })
105
- .onConflictDoNothing()
106
- .returning();
107
- if (!value) {
108
- throw new WorkflowAPIError(`Run ${runId} already exists`, {
109
- status: 409,
110
- });
111
- }
112
- return compact(value);
113
- },
114
- async update(id, data) {
115
- // Fetch current run to check if startedAt is already set
116
- const [currentRun] = await drizzle
117
- .select()
118
- .from(runs)
119
- .where(eq(runs.runId, id))
120
- .limit(1);
121
- if (!currentRun) {
122
- throw new WorkflowAPIError(`Run not found: ${id}`, { status: 404 });
123
- }
124
- const updates = {
125
- ...data,
126
- output: data.output,
127
- };
128
- // Only set startedAt the first time transitioning to 'running'
129
- if (data.status === 'running' && !currentRun.startedAt) {
130
- updates.startedAt = new Date();
131
- }
132
- if (data.status === 'completed' ||
133
- data.status === 'failed' ||
134
- data.status === 'cancelled') {
135
- updates.completedAt = new Date();
136
- }
137
- const [value] = await drizzle
138
- .update(runs)
139
- .set(updates)
140
- .where(eq(runs.runId, id))
141
- .returning();
142
- if (!value) {
143
- throw new WorkflowAPIError(`Run not found: ${id}`, { status: 404 });
144
- }
145
- return compact(value);
146
- },
112
+ }),
147
113
  };
148
114
  }
149
115
  function map(obj, fn) {
150
116
  return obj ? fn(obj) : undefined;
151
117
  }
118
+ /**
119
+ * Handle events for legacy runs (pre-event-sourcing, specVersion < 2).
120
+ * Legacy runs use different behavior:
121
+ * - run_cancelled: Skip event storage, directly update run
122
+ * - wait_completed: Store event only (no entity mutation)
123
+ * - hook_received: Store event only (hooks exist via old system, no entity mutation)
124
+ * - Other events: Throw error (not supported for legacy runs)
125
+ */
126
+ async function handleLegacyEventPostgres(drizzle, runId, eventId, data, currentRun, params) {
127
+ const resolveData = params?.resolveData ?? 'all';
128
+ switch (data.eventType) {
129
+ case 'run_cancelled': {
130
+ // Legacy: Skip event storage, directly update run to cancelled
131
+ const now = new Date();
132
+ // Update run status to cancelled
133
+ await drizzle
134
+ .update(Schema.runs)
135
+ .set({
136
+ status: 'cancelled',
137
+ completedAt: now,
138
+ updatedAt: now,
139
+ })
140
+ .where(eq(Schema.runs.runId, runId));
141
+ // Delete all hooks and waits for this run
142
+ await Promise.all([
143
+ drizzle.delete(Schema.hooks).where(eq(Schema.hooks.runId, runId)),
144
+ drizzle.delete(Schema.waits).where(eq(Schema.waits.runId, runId)),
145
+ ]);
146
+ // Fetch updated run for return value
147
+ const [updatedRun] = await drizzle
148
+ .select()
149
+ .from(Schema.runs)
150
+ .where(eq(Schema.runs.runId, runId))
151
+ .limit(1);
152
+ // Return without event (legacy behavior skips event storage)
153
+ // Type assertion: EventResult expects WorkflowRun, filterRunData may return WorkflowRunWithoutData
154
+ return {
155
+ run: updatedRun
156
+ ? filterRunData(deserializeRunError(compact(updatedRun)), resolveData)
157
+ : undefined,
158
+ };
159
+ }
160
+ case 'wait_completed':
161
+ case 'hook_received': {
162
+ // Legacy: Store event only (no entity mutation)
163
+ // - wait_completed: for replay purposes
164
+ // - hook_received: hooks exist via old system, just record the event
165
+ const [insertedEvent] = await drizzle
166
+ .insert(Schema.events)
167
+ .values({
168
+ runId,
169
+ eventId,
170
+ correlationId: data.correlationId,
171
+ eventType: data.eventType,
172
+ eventData: 'eventData' in data ? data.eventData : undefined,
173
+ specVersion: SPEC_VERSION_CURRENT,
174
+ })
175
+ .returning({ createdAt: Schema.events.createdAt });
176
+ const event = EventSchema.parse({
177
+ ...data,
178
+ ...insertedEvent,
179
+ runId,
180
+ eventId,
181
+ });
182
+ return { event: stripEventDataRefs(event, resolveData) };
183
+ }
184
+ default:
185
+ throw new Error(`Event type '${data.eventType}' not supported for legacy runs ` +
186
+ `(specVersion: ${currentRun.specVersion || 'undefined'}). ` +
187
+ `Please upgrade @workflow packages.`);
188
+ }
189
+ }
152
190
  export function createEventsStorage(drizzle) {
153
191
  const ulid = monotonicFactory();
154
192
  const { events } = Schema;
193
+ // Prepared statements for validation queries (performance optimization)
194
+ const getRunForValidation = drizzle
195
+ .select({
196
+ status: Schema.runs.status,
197
+ specVersion: Schema.runs.specVersion,
198
+ })
199
+ .from(Schema.runs)
200
+ .where(eq(Schema.runs.runId, sql.placeholder('runId')))
201
+ .limit(1)
202
+ .prepare('events_get_run_for_validation');
203
+ const getStepForValidation = drizzle
204
+ .select({
205
+ status: Schema.steps.status,
206
+ startedAt: Schema.steps.startedAt,
207
+ retryAfter: Schema.steps.retryAfter,
208
+ })
209
+ .from(Schema.steps)
210
+ .where(and(eq(Schema.steps.runId, sql.placeholder('runId')), eq(Schema.steps.stepId, sql.placeholder('stepId'))))
211
+ .limit(1)
212
+ .prepare('events_get_step_for_validation');
213
+ const getHookByToken = drizzle
214
+ .select({ hookId: Schema.hooks.hookId })
215
+ .from(Schema.hooks)
216
+ .where(eq(Schema.hooks.token, sql.placeholder('token')))
217
+ .limit(1)
218
+ .prepare('events_get_hook_by_token');
219
+ const getWaitForValidation = drizzle
220
+ .select({
221
+ status: Schema.waits.status,
222
+ })
223
+ .from(Schema.waits)
224
+ .where(eq(Schema.waits.waitId, sql.placeholder('waitId')))
225
+ .limit(1)
226
+ .prepare('events_get_wait_for_validation');
155
227
  return {
156
- async create(runId, data) {
228
+ async create(runId, data, params) {
157
229
  const eventId = `wevt_${ulid()}`;
230
+ // For run_created events, use client-provided runId or generate one server-side
231
+ let effectiveRunId;
232
+ if (data.eventType === 'run_created' && (!runId || runId === '')) {
233
+ effectiveRunId = `wrun_${ulid()}`;
234
+ }
235
+ else if (!runId) {
236
+ throw new Error('runId is required for non-run_created events');
237
+ }
238
+ else {
239
+ effectiveRunId = runId;
240
+ }
241
+ // Validate client-provided runId timestamp is within acceptable threshold
242
+ if (data.eventType === 'run_created' && runId && runId !== '') {
243
+ const validationError = validateUlidTimestamp(effectiveRunId, 'wrun_');
244
+ if (validationError) {
245
+ throw new WorkflowWorldError(validationError);
246
+ }
247
+ }
248
+ // specVersion is always sent by the runtime, but we provide a fallback for safety
249
+ const effectiveSpecVersion = data.specVersion ?? SPEC_VERSION_CURRENT;
250
+ // Track entity created/updated for EventResult
251
+ let run;
252
+ let step;
253
+ let hook;
254
+ let wait;
255
+ const now = new Date();
256
+ // Helper to check if run is in terminal state
257
+ const isRunTerminal = (status) => ['completed', 'failed', 'cancelled'].includes(status);
258
+ // Helper to check if step is in terminal state
259
+ const isStepTerminal = (status) => ['completed', 'failed', 'cancelled'].includes(status);
260
+ // Terminal step statuses for use in SQL WHERE clauses (atomic guard).
261
+ // Must match the Vercel world's conditional expressions:
262
+ // ne(status, 'completed') AND ne(status, 'failed') AND ne(status, 'cancelled')
263
+ const terminalStepStatuses = ['completed', 'failed', 'cancelled'];
264
+ // ============================================================
265
+ // VALIDATION: Terminal state and event ordering checks
266
+ // ============================================================
267
+ // Get current run state for validation (if not creating a new run)
268
+ // Skip run validation for step_completed and step_retrying - they only operate
269
+ // on running steps, and running steps are always allowed to modify regardless
270
+ // of run state. This optimization saves database queries per step event.
271
+ let currentRun = null;
272
+ const skipRunValidationEvents = ['step_completed', 'step_retrying'];
273
+ if (data.eventType !== 'run_created' &&
274
+ !skipRunValidationEvents.includes(data.eventType)) {
275
+ // Use prepared statement for better performance
276
+ const [runValue] = await getRunForValidation.execute({
277
+ runId: effectiveRunId,
278
+ });
279
+ currentRun = runValue ?? null;
280
+ // Resilient start: run_started on non-existent run with eventData
281
+ // creates the run first, so the queue can bootstrap a run that
282
+ // failed to create during start().
283
+ if (data.eventType === 'run_started' &&
284
+ !currentRun &&
285
+ 'eventData' in data &&
286
+ data.eventData) {
287
+ const runInputData = data.eventData;
288
+ if (runInputData.deploymentId &&
289
+ runInputData.workflowName &&
290
+ runInputData.input !== undefined) {
291
+ // Create run + run_created event atomically. The
292
+ // transaction ensures we never have an orphaned run
293
+ // without its run_created event.
294
+ const [inserted] = await drizzle
295
+ .insert(Schema.runs)
296
+ .values({
297
+ runId: effectiveRunId,
298
+ deploymentId: runInputData.deploymentId,
299
+ workflowName: runInputData.workflowName,
300
+ specVersion: effectiveSpecVersion,
301
+ input: runInputData.input,
302
+ executionContext: runInputData.executionContext,
303
+ status: 'pending',
304
+ })
305
+ .onConflictDoNothing()
306
+ .returning();
307
+ if (inserted) {
308
+ const runCreatedEventId = `wevt_${ulid()}`;
309
+ await drizzle.insert(events).values({
310
+ runId: effectiveRunId,
311
+ eventId: runCreatedEventId,
312
+ eventType: 'run_created',
313
+ eventData: {
314
+ deploymentId: runInputData.deploymentId,
315
+ workflowName: runInputData.workflowName,
316
+ input: runInputData.input,
317
+ executionContext: runInputData.executionContext,
318
+ },
319
+ specVersion: effectiveSpecVersion,
320
+ });
321
+ }
322
+ const createdRun = inserted;
323
+ if (createdRun) {
324
+ currentRun = {
325
+ status: 'pending',
326
+ specVersion: effectiveSpecVersion,
327
+ };
328
+ }
329
+ else {
330
+ // Run already exists (concurrent run_created won the
331
+ // race). Re-read so downstream logic sees the real state.
332
+ const [runValue] = await getRunForValidation.execute({
333
+ runId: effectiveRunId,
334
+ });
335
+ currentRun = runValue ?? null;
336
+ }
337
+ }
338
+ }
339
+ }
340
+ // ============================================================
341
+ // VERSION COMPATIBILITY: Check run spec version
342
+ // ============================================================
343
+ // For events that have fetched the run, check version compatibility.
344
+ // Skip for run_created (no existing run) and runtime events (step_completed, step_retrying).
345
+ if (currentRun) {
346
+ // Check if run requires a newer world version
347
+ if (requiresNewerWorld(currentRun.specVersion)) {
348
+ throw new RunNotSupportedError(currentRun.specVersion, SPEC_VERSION_CURRENT);
349
+ }
350
+ // Route to legacy handler for pre-event-sourcing runs
351
+ if (isLegacySpecVersion(currentRun.specVersion)) {
352
+ return handleLegacyEventPostgres(drizzle, effectiveRunId, eventId, data, currentRun, params);
353
+ }
354
+ }
355
+ // Run terminal state validation
356
+ if (currentRun && isRunTerminal(currentRun.status)) {
357
+ const runTerminalEvents = [
358
+ 'run_started',
359
+ 'run_completed',
360
+ 'run_failed',
361
+ ];
362
+ // Idempotent operation: run_cancelled on already cancelled run is allowed
363
+ if (data.eventType === 'run_cancelled' &&
364
+ currentRun.status === 'cancelled') {
365
+ // Get full run for return value
366
+ const [fullRun] = await drizzle
367
+ .select()
368
+ .from(Schema.runs)
369
+ .where(eq(Schema.runs.runId, effectiveRunId))
370
+ .limit(1);
371
+ // Create the event (still record it)
372
+ const [value] = await drizzle
373
+ .insert(Schema.events)
374
+ .values({
375
+ runId: effectiveRunId,
376
+ eventId,
377
+ correlationId: data.correlationId,
378
+ eventType: data.eventType,
379
+ eventData: 'eventData' in data ? data.eventData : undefined,
380
+ specVersion: effectiveSpecVersion,
381
+ })
382
+ .returning({ createdAt: Schema.events.createdAt });
383
+ const result = { ...data, ...value, runId: effectiveRunId, eventId };
384
+ const parsed = EventSchema.parse(result);
385
+ const resolveData = params?.resolveData ?? 'all';
386
+ return {
387
+ event: stripEventDataRefs(parsed, resolveData),
388
+ run: fullRun ? deserializeRunError(compact(fullRun)) : undefined,
389
+ };
390
+ }
391
+ // For run_started on terminal runs, use RunExpiredError so the
392
+ // runtime knows to exit without retrying.
393
+ if (data.eventType === 'run_started') {
394
+ throw new RunExpiredError(`Workflow run "${effectiveRunId}" is already in terminal state "${currentRun.status}"`);
395
+ }
396
+ // Other run state transitions are not allowed on terminal runs
397
+ if (runTerminalEvents.includes(data.eventType) ||
398
+ data.eventType === 'run_cancelled') {
399
+ throw new EntityConflictError(`Cannot transition run from terminal state "${currentRun.status}"`);
400
+ }
401
+ // Creating new entities on terminal runs is not allowed
402
+ if (data.eventType === 'step_created' ||
403
+ data.eventType === 'hook_created' ||
404
+ data.eventType === 'wait_created') {
405
+ throw new EntityConflictError(`Cannot create new entities on run in terminal state "${currentRun.status}"`);
406
+ }
407
+ }
408
+ // Step-related event validation (ordering and terminal state)
409
+ // Fetch status + startedAt so we can reuse for step_started (avoid double read)
410
+ // Skip validation for step_completed/step_failed - use conditional UPDATE instead
411
+ let validatedStep = null;
412
+ const stepEventsNeedingValidation = ['step_started', 'step_retrying'];
413
+ if (stepEventsNeedingValidation.includes(data.eventType) &&
414
+ data.correlationId) {
415
+ // Use prepared statement for better performance
416
+ const [existingStep] = await getStepForValidation.execute({
417
+ runId: effectiveRunId,
418
+ stepId: data.correlationId,
419
+ });
420
+ validatedStep = existingStep ?? null;
421
+ // Event ordering: step must exist before these events
422
+ if (!validatedStep) {
423
+ throw new WorkflowWorldError(`Step "${data.correlationId}" not found`);
424
+ }
425
+ // Step terminal state validation
426
+ if (isStepTerminal(validatedStep.status)) {
427
+ throw new EntityConflictError(`Cannot modify step in terminal state "${validatedStep.status}"`);
428
+ }
429
+ // On terminal runs: only allow completing/failing in-progress steps
430
+ if (currentRun && isRunTerminal(currentRun.status)) {
431
+ if (validatedStep.status !== 'running') {
432
+ throw new RunExpiredError(`Cannot modify non-running step on run in terminal state "${currentRun.status}"`);
433
+ }
434
+ }
435
+ }
436
+ // Hook-related event validation (ordering)
437
+ const hookEventsRequiringExistence = ['hook_disposed', 'hook_received'];
438
+ if (hookEventsRequiringExistence.includes(data.eventType) &&
439
+ data.correlationId) {
440
+ const [existingHook] = await drizzle
441
+ .select({ hookId: Schema.hooks.hookId })
442
+ .from(Schema.hooks)
443
+ .where(eq(Schema.hooks.hookId, data.correlationId))
444
+ .limit(1);
445
+ if (!existingHook) {
446
+ throw new HookNotFoundError(data.correlationId);
447
+ }
448
+ }
449
+ // ============================================================
450
+ // Entity creation/updates based on event type
451
+ // ============================================================
452
+ // Handle run_created event: create the run entity atomically
453
+ if (data.eventType === 'run_created') {
454
+ const eventData = data.eventData;
455
+ const [runValue] = await drizzle
456
+ .insert(Schema.runs)
457
+ .values({
458
+ runId: effectiveRunId,
459
+ deploymentId: eventData.deploymentId,
460
+ workflowName: eventData.workflowName,
461
+ // Propagate specVersion from the event to the run entity
462
+ specVersion: effectiveSpecVersion,
463
+ input: eventData.input,
464
+ executionContext: eventData.executionContext,
465
+ status: 'pending',
466
+ })
467
+ .onConflictDoNothing()
468
+ .returning();
469
+ if (runValue) {
470
+ run = deserializeRunError(compact(runValue));
471
+ }
472
+ }
473
+ // Handle run_started event: update run status
474
+ if (data.eventType === 'run_started') {
475
+ // If the run is already running, return it without inserting a
476
+ // duplicate run_started event. This makes run_started idempotent
477
+ // for concurrent invocations: replay is deterministic, so letting
478
+ // multiple callers proceed with the same run is safe. We skip
479
+ // preloaded events here because this is a rare race-condition path
480
+ // — the runtime falls back to getAllWorkflowRunEvents().
481
+ if (currentRun?.status === 'running') {
482
+ const [fullRun] = await drizzle
483
+ .select()
484
+ .from(Schema.runs)
485
+ .where(eq(Schema.runs.runId, effectiveRunId))
486
+ .limit(1);
487
+ if (fullRun) {
488
+ return { run: deserializeRunError(compact(fullRun)) };
489
+ }
490
+ }
491
+ const [runValue] = await drizzle
492
+ .update(Schema.runs)
493
+ .set({
494
+ status: 'running',
495
+ startedAt: now,
496
+ updatedAt: now,
497
+ })
498
+ .where(eq(Schema.runs.runId, effectiveRunId))
499
+ .returning();
500
+ if (runValue) {
501
+ run = deserializeRunError(compact(runValue));
502
+ }
503
+ }
504
+ // Terminal run statuses for use in SQL WHERE clauses (atomic guard).
505
+ // Must match the Vercel world's conditional expressions:
506
+ // ne(status, 'completed') AND ne(status, 'failed') AND ne(status, 'cancelled')
507
+ const terminalRunStatuses = ['completed', 'failed', 'cancelled'];
508
+ // Handle run_completed event: update run status and cleanup hooks
509
+ // Uses conditional UPDATE to prevent completing an already-terminal run.
510
+ if (data.eventType === 'run_completed') {
511
+ const eventData = data.eventData;
512
+ const [runValue] = await drizzle
513
+ .update(Schema.runs)
514
+ .set({
515
+ status: 'completed',
516
+ output: eventData.output,
517
+ completedAt: now,
518
+ updatedAt: now,
519
+ })
520
+ .where(and(eq(Schema.runs.runId, effectiveRunId), notInArray(Schema.runs.status, terminalRunStatuses)))
521
+ .returning();
522
+ if (runValue) {
523
+ run = deserializeRunError(compact(runValue));
524
+ }
525
+ else {
526
+ const [existing] = await getRunForValidation.execute({
527
+ runId: effectiveRunId,
528
+ });
529
+ if (!existing) {
530
+ throw new WorkflowRunNotFoundError(effectiveRunId);
531
+ }
532
+ if (isRunTerminal(existing.status)) {
533
+ throw new EntityConflictError(`Cannot transition run from terminal state "${existing.status}"`);
534
+ }
535
+ }
536
+ // Delete all hooks and waits for this run to allow token reuse
537
+ await Promise.all([
538
+ drizzle
539
+ .delete(Schema.hooks)
540
+ .where(eq(Schema.hooks.runId, effectiveRunId)),
541
+ drizzle
542
+ .delete(Schema.waits)
543
+ .where(eq(Schema.waits.runId, effectiveRunId)),
544
+ ]);
545
+ }
546
+ // Handle run_failed event: update run status and cleanup hooks
547
+ // Uses conditional UPDATE to prevent failing an already-terminal run.
548
+ if (data.eventType === 'run_failed') {
549
+ const eventData = data.eventData;
550
+ const errorMessage = typeof eventData.error === 'string'
551
+ ? eventData.error
552
+ : (eventData.error?.message ?? 'Unknown error');
553
+ const [runValue] = await drizzle
554
+ .update(Schema.runs)
555
+ .set({
556
+ status: 'failed',
557
+ error: {
558
+ message: errorMessage,
559
+ stack: eventData.error?.stack,
560
+ code: eventData.errorCode,
561
+ },
562
+ completedAt: now,
563
+ updatedAt: now,
564
+ })
565
+ .where(and(eq(Schema.runs.runId, effectiveRunId), notInArray(Schema.runs.status, terminalRunStatuses)))
566
+ .returning();
567
+ if (runValue) {
568
+ run = deserializeRunError(compact(runValue));
569
+ }
570
+ else {
571
+ const [existing] = await getRunForValidation.execute({
572
+ runId: effectiveRunId,
573
+ });
574
+ if (!existing) {
575
+ throw new WorkflowRunNotFoundError(effectiveRunId);
576
+ }
577
+ if (isRunTerminal(existing.status)) {
578
+ throw new EntityConflictError(`Cannot transition run from terminal state "${existing.status}"`);
579
+ }
580
+ }
581
+ // Delete all hooks and waits for this run to allow token reuse
582
+ await Promise.all([
583
+ drizzle
584
+ .delete(Schema.hooks)
585
+ .where(eq(Schema.hooks.runId, effectiveRunId)),
586
+ drizzle
587
+ .delete(Schema.waits)
588
+ .where(eq(Schema.waits.runId, effectiveRunId)),
589
+ ]);
590
+ }
591
+ // Handle run_cancelled event: update run status and cleanup hooks
592
+ // Uses conditional UPDATE to prevent cancelling an already-terminal run.
593
+ // Note: idempotent run_cancelled on already-cancelled runs is handled
594
+ // earlier in the pre-validation block (creates event and returns early).
595
+ if (data.eventType === 'run_cancelled') {
596
+ const [runValue] = await drizzle
597
+ .update(Schema.runs)
598
+ .set({
599
+ status: 'cancelled',
600
+ completedAt: now,
601
+ updatedAt: now,
602
+ })
603
+ .where(and(eq(Schema.runs.runId, effectiveRunId), notInArray(Schema.runs.status, terminalRunStatuses)))
604
+ .returning();
605
+ if (runValue) {
606
+ run = deserializeRunError(compact(runValue));
607
+ }
608
+ else {
609
+ const [existing] = await getRunForValidation.execute({
610
+ runId: effectiveRunId,
611
+ });
612
+ if (!existing) {
613
+ throw new WorkflowRunNotFoundError(effectiveRunId);
614
+ }
615
+ if (isRunTerminal(existing.status)) {
616
+ throw new EntityConflictError(`Cannot transition run from terminal state "${existing.status}"`);
617
+ }
618
+ }
619
+ // Delete all hooks and waits for this run to allow token reuse
620
+ await Promise.all([
621
+ drizzle
622
+ .delete(Schema.hooks)
623
+ .where(eq(Schema.hooks.runId, effectiveRunId)),
624
+ drizzle
625
+ .delete(Schema.waits)
626
+ .where(eq(Schema.waits.runId, effectiveRunId)),
627
+ ]);
628
+ }
629
+ // Handle step_created event: create step entity
630
+ if (data.eventType === 'step_created') {
631
+ const eventData = data.eventData;
632
+ const [stepValue] = await drizzle
633
+ .insert(Schema.steps)
634
+ .values({
635
+ runId: effectiveRunId,
636
+ stepId: data.correlationId,
637
+ stepName: eventData.stepName,
638
+ input: eventData.input,
639
+ status: 'pending',
640
+ attempt: 0,
641
+ // Propagate specVersion from the event to the step entity
642
+ specVersion: effectiveSpecVersion,
643
+ })
644
+ .onConflictDoNothing()
645
+ .returning();
646
+ if (stepValue) {
647
+ step = deserializeStepError(compact(stepValue));
648
+ }
649
+ }
650
+ // Handle step_started event: increment attempt, set status to 'running'
651
+ // Sets startedAt (maps to startedAt) only on first start
652
+ // Uses conditional UPDATE to prevent re-starting a step that has already
653
+ // reached a terminal state (completed/failed). Without this guard a
654
+ // concurrent step_started could revert a completed step back to 'running',
655
+ // allowing a duplicate execution that corrupts the event log.
656
+ if (data.eventType === 'step_started') {
657
+ // Check if retryAfter timestamp hasn't been reached yet
658
+ if (validatedStep?.retryAfter &&
659
+ validatedStep.retryAfter.getTime() > Date.now()) {
660
+ throw new TooEarlyError(`Cannot start step "${data.correlationId}": retryAfter timestamp has not been reached yet`, {
661
+ retryAfter: Math.ceil((validatedStep.retryAfter.getTime() - Date.now()) / 1000),
662
+ });
663
+ }
664
+ const [stepValue] = await drizzle
665
+ .update(Schema.steps)
666
+ .set({
667
+ status: 'running',
668
+ // Increment attempt counter using SQL
669
+ attempt: sql `${Schema.steps.attempt} + 1`,
670
+ // Only set startedAt on first start — use COALESCE so concurrent
671
+ // step_started calls can't clobber the original timestamp.
672
+ startedAt: sql `COALESCE(${Schema.steps.startedAt}, ${now.toISOString()})`,
673
+ // Always clear retryAfter now that the step has started
674
+ retryAfter: null,
675
+ })
676
+ .where(and(eq(Schema.steps.runId, effectiveRunId), eq(Schema.steps.stepId, data.correlationId),
677
+ // Only update if not already in terminal state (prevents TOCTOU race)
678
+ notInArray(Schema.steps.status, terminalStepStatuses)))
679
+ .returning();
680
+ if (stepValue) {
681
+ step = deserializeStepError(compact(stepValue));
682
+ }
683
+ else {
684
+ // Step not updated - check if it exists and why
685
+ const [existing] = await getStepForValidation.execute({
686
+ runId: effectiveRunId,
687
+ stepId: data.correlationId,
688
+ });
689
+ if (!existing) {
690
+ throw new WorkflowWorldError(`Step "${data.correlationId}" not found`);
691
+ }
692
+ if (isStepTerminal(existing.status)) {
693
+ throw new EntityConflictError(`Cannot modify step in terminal state "${existing.status}"`);
694
+ }
695
+ }
696
+ }
697
+ // Handle step_completed event: update step status
698
+ // Uses conditional UPDATE to prevent completing an already-terminal step.
699
+ if (data.eventType === 'step_completed') {
700
+ const eventData = data.eventData;
701
+ const [stepValue] = await drizzle
702
+ .update(Schema.steps)
703
+ .set({
704
+ status: 'completed',
705
+ output: eventData.result,
706
+ completedAt: now,
707
+ })
708
+ .where(and(eq(Schema.steps.runId, effectiveRunId), eq(Schema.steps.stepId, data.correlationId), notInArray(Schema.steps.status, terminalStepStatuses)))
709
+ .returning();
710
+ if (stepValue) {
711
+ step = deserializeStepError(compact(stepValue));
712
+ }
713
+ else {
714
+ // Step not updated - check if it exists and why
715
+ const [existing] = await getStepForValidation.execute({
716
+ runId: effectiveRunId,
717
+ stepId: data.correlationId,
718
+ });
719
+ if (!existing) {
720
+ throw new WorkflowWorldError(`Step "${data.correlationId}" not found`);
721
+ }
722
+ if (isStepTerminal(existing.status)) {
723
+ throw new EntityConflictError(`Cannot modify step in terminal state "${existing.status}"`);
724
+ }
725
+ }
726
+ }
727
+ // Handle step_failed event: terminal state with error
728
+ // Uses conditional UPDATE to prevent failing an already-terminal step.
729
+ if (data.eventType === 'step_failed') {
730
+ const eventData = data.eventData;
731
+ const errorMessage = typeof eventData.error === 'string'
732
+ ? eventData.error
733
+ : (eventData.error?.message ?? 'Unknown error');
734
+ const [stepValue] = await drizzle
735
+ .update(Schema.steps)
736
+ .set({
737
+ status: 'failed',
738
+ error: {
739
+ message: errorMessage,
740
+ stack: eventData.stack,
741
+ },
742
+ completedAt: now,
743
+ })
744
+ .where(and(eq(Schema.steps.runId, effectiveRunId), eq(Schema.steps.stepId, data.correlationId), notInArray(Schema.steps.status, terminalStepStatuses)))
745
+ .returning();
746
+ if (stepValue) {
747
+ step = deserializeStepError(compact(stepValue));
748
+ }
749
+ else {
750
+ // Step not updated - check if it exists and why
751
+ const [existing] = await getStepForValidation.execute({
752
+ runId: effectiveRunId,
753
+ stepId: data.correlationId,
754
+ });
755
+ if (!existing) {
756
+ throw new WorkflowWorldError(`Step "${data.correlationId}" not found`);
757
+ }
758
+ if (isStepTerminal(existing.status)) {
759
+ throw new EntityConflictError(`Cannot modify step in terminal state "${existing.status}"`);
760
+ }
761
+ }
762
+ }
763
+ // Handle step_retrying event: sets status back to 'pending', records error
764
+ // Uses conditional UPDATE to prevent retrying an already-terminal step.
765
+ if (data.eventType === 'step_retrying') {
766
+ const eventData = data.eventData;
767
+ const errorMessage = typeof eventData.error === 'string'
768
+ ? eventData.error
769
+ : (eventData.error?.message ?? 'Unknown error');
770
+ const [stepValue] = await drizzle
771
+ .update(Schema.steps)
772
+ .set({
773
+ status: 'pending',
774
+ error: {
775
+ message: errorMessage,
776
+ stack: eventData.stack,
777
+ },
778
+ retryAfter: eventData.retryAfter,
779
+ })
780
+ .where(and(eq(Schema.steps.runId, effectiveRunId), eq(Schema.steps.stepId, data.correlationId), notInArray(Schema.steps.status, terminalStepStatuses)))
781
+ .returning();
782
+ if (stepValue) {
783
+ step = deserializeStepError(compact(stepValue));
784
+ }
785
+ else {
786
+ // Step not updated - check if it exists and why
787
+ const [existing] = await getStepForValidation.execute({
788
+ runId: effectiveRunId,
789
+ stepId: data.correlationId,
790
+ });
791
+ if (!existing) {
792
+ throw new WorkflowWorldError(`Step "${data.correlationId}" not found`);
793
+ }
794
+ if (isStepTerminal(existing.status)) {
795
+ throw new EntityConflictError(`Cannot modify step in terminal state "${existing.status}"`);
796
+ }
797
+ }
798
+ }
799
+ // Handle hook_created event: create hook entity
800
+ // Uses prepared statement for token uniqueness check (performance optimization)
801
+ if (data.eventType === 'hook_created') {
802
+ const eventData = data.eventData;
803
+ // Check for duplicate token using prepared statement
804
+ const [existingHook] = await getHookByToken.execute({
805
+ token: eventData.token,
806
+ });
807
+ if (existingHook) {
808
+ // Create hook_conflict event instead of throwing 409
809
+ // This allows the workflow to continue and fail gracefully when the hook is awaited
810
+ const conflictEventData = {
811
+ token: eventData.token,
812
+ };
813
+ const [conflictValue] = await drizzle
814
+ .insert(events)
815
+ .values({
816
+ runId: effectiveRunId,
817
+ eventId,
818
+ correlationId: data.correlationId,
819
+ eventType: 'hook_conflict',
820
+ eventData: conflictEventData,
821
+ specVersion: effectiveSpecVersion,
822
+ })
823
+ .returning({ createdAt: events.createdAt });
824
+ if (!conflictValue) {
825
+ throw new EntityConflictError(`Event ${eventId} could not be created`);
826
+ }
827
+ const conflictResult = {
828
+ eventType: 'hook_conflict',
829
+ correlationId: data.correlationId,
830
+ eventData: conflictEventData,
831
+ ...conflictValue,
832
+ runId: effectiveRunId,
833
+ eventId,
834
+ };
835
+ const parsedConflict = EventSchema.parse(conflictResult);
836
+ const resolveData = params?.resolveData ?? 'all';
837
+ return {
838
+ event: stripEventDataRefs(parsedConflict, resolveData),
839
+ run,
840
+ step,
841
+ hook: undefined,
842
+ };
843
+ }
844
+ const [hookValue] = await drizzle
845
+ .insert(Schema.hooks)
846
+ .values({
847
+ runId: effectiveRunId,
848
+ hookId: data.correlationId,
849
+ token: eventData.token,
850
+ metadata: eventData.metadata,
851
+ ownerId: '', // TODO: get from context
852
+ projectId: '', // TODO: get from context
853
+ environment: '', // TODO: get from context
854
+ // Propagate specVersion from the event to the hook entity
855
+ specVersion: effectiveSpecVersion,
856
+ isWebhook: eventData.isWebhook,
857
+ })
858
+ .onConflictDoNothing()
859
+ .returning();
860
+ if (hookValue) {
861
+ hookValue.metadata ||= hookValue.metadataJson;
862
+ hook = HookSchema.parse(compact(hookValue));
863
+ }
864
+ }
865
+ // Handle hook_disposed event: delete hook entity atomically.
866
+ // Uses DELETE ... RETURNING to ensure only one concurrent caller
867
+ // succeeds — if no rows are returned, the hook was already disposed.
868
+ if (data.eventType === 'hook_disposed' && data.correlationId) {
869
+ const [deleted] = await drizzle
870
+ .delete(Schema.hooks)
871
+ .where(eq(Schema.hooks.hookId, data.correlationId))
872
+ .returning({ hookId: Schema.hooks.hookId });
873
+ if (!deleted) {
874
+ throw new EntityConflictError(`Hook "${data.correlationId}" already disposed`);
875
+ }
876
+ }
877
+ // Handle wait_created event: create wait entity
878
+ if (data.eventType === 'wait_created') {
879
+ const eventData = data.eventData;
880
+ const waitId = `${effectiveRunId}-${data.correlationId}`;
881
+ const [waitValue] = await drizzle
882
+ .insert(Schema.waits)
883
+ .values({
884
+ waitId,
885
+ runId: effectiveRunId,
886
+ status: 'waiting',
887
+ resumeAt: eventData.resumeAt,
888
+ specVersion: effectiveSpecVersion,
889
+ })
890
+ .onConflictDoNothing()
891
+ .returning();
892
+ if (waitValue) {
893
+ wait = {
894
+ waitId: waitValue.waitId,
895
+ runId: waitValue.runId,
896
+ status: waitValue.status,
897
+ resumeAt: waitValue.resumeAt ?? undefined,
898
+ completedAt: waitValue.completedAt ?? undefined,
899
+ createdAt: waitValue.createdAt,
900
+ updatedAt: waitValue.updatedAt,
901
+ specVersion: waitValue.specVersion ?? undefined,
902
+ };
903
+ }
904
+ else {
905
+ throw new EntityConflictError(`Wait "${data.correlationId}" already exists`);
906
+ }
907
+ }
908
+ // Handle wait_completed event: transition wait to 'completed'
909
+ // Uses conditional UPDATE to reject duplicate completions (same pattern as step_completed)
910
+ if (data.eventType === 'wait_completed') {
911
+ const waitId = `${effectiveRunId}-${data.correlationId}`;
912
+ const [waitValue] = await drizzle
913
+ .update(Schema.waits)
914
+ .set({
915
+ status: 'completed',
916
+ completedAt: now,
917
+ })
918
+ .where(and(eq(Schema.waits.waitId, waitId), eq(Schema.waits.status, 'waiting')))
919
+ .returning();
920
+ if (waitValue) {
921
+ wait = {
922
+ waitId: waitValue.waitId,
923
+ runId: waitValue.runId,
924
+ status: waitValue.status,
925
+ resumeAt: waitValue.resumeAt ?? undefined,
926
+ completedAt: waitValue.completedAt ?? undefined,
927
+ createdAt: waitValue.createdAt,
928
+ updatedAt: waitValue.updatedAt,
929
+ specVersion: waitValue.specVersion ?? undefined,
930
+ };
931
+ }
932
+ else {
933
+ // Wait not updated - check if it exists and why
934
+ const [existing] = await getWaitForValidation.execute({
935
+ waitId,
936
+ });
937
+ if (!existing) {
938
+ throw new WorkflowWorldError(`Wait "${data.correlationId}" not found`);
939
+ }
940
+ if (existing.status === 'completed') {
941
+ throw new EntityConflictError(`Wait "${data.correlationId}" already completed`);
942
+ }
943
+ }
944
+ }
945
+ // Strip eventData from run_started — it belongs on run_created only.
946
+ const storedEventData = data.eventType === 'run_started'
947
+ ? undefined
948
+ : 'eventData' in data
949
+ ? data.eventData
950
+ : undefined;
158
951
  const [value] = await drizzle
159
952
  .insert(events)
160
953
  .values({
161
- runId,
954
+ runId: effectiveRunId,
162
955
  eventId,
163
956
  correlationId: data.correlationId,
164
957
  eventType: data.eventType,
165
- eventData: 'eventData' in data ? data.eventData : undefined,
958
+ eventData: storedEventData,
959
+ specVersion: effectiveSpecVersion,
166
960
  })
167
961
  .returning({ createdAt: events.createdAt });
168
962
  if (!value) {
169
- throw new WorkflowAPIError(`Event ${eventId} could not be created`, {
170
- status: 409,
963
+ throw new EntityConflictError(`Event ${eventId} could not be created`);
964
+ }
965
+ const result = {
966
+ ...data,
967
+ ...value,
968
+ runId: effectiveRunId,
969
+ eventId,
970
+ ...(storedEventData !== undefined
971
+ ? { eventData: storedEventData }
972
+ : {}),
973
+ };
974
+ // Strip eventData leaked by ...data spread for run_started events.
975
+ // The eventData (run input for resilient start) belongs on
976
+ // run_created only; storedEventData is already undefined above.
977
+ if (data.eventType === 'run_started') {
978
+ delete result.eventData;
979
+ }
980
+ const parsed = EventSchema.parse(result);
981
+ const resolveData = params?.resolveData ?? 'all';
982
+ // For run_started: include all events so the runtime can skip
983
+ // the initial events.list call and reduce TTFB.
984
+ let allEvents;
985
+ if (data.eventType === 'run_started' && run) {
986
+ const eventRows = await drizzle
987
+ .select()
988
+ .from(Schema.events)
989
+ .where(eq(Schema.events.runId, effectiveRunId))
990
+ .orderBy(Schema.events.eventId);
991
+ allEvents = eventRows.map((e) => {
992
+ e.eventData ||= e.eventDataJson;
993
+ const parsed = EventSchema.parse(compact(e));
994
+ return stripEventDataRefs(parsed, resolveData);
171
995
  });
172
996
  }
173
- return { ...data, ...value, runId, eventId };
997
+ return {
998
+ event: stripEventDataRefs(parsed, resolveData),
999
+ run,
1000
+ step,
1001
+ hook,
1002
+ wait,
1003
+ events: allEvents,
1004
+ };
1005
+ },
1006
+ async get(runId, eventId, params) {
1007
+ const [value] = await drizzle
1008
+ .select()
1009
+ .from(events)
1010
+ .where(and(eq(events.runId, runId), eq(events.eventId, eventId)))
1011
+ .limit(1);
1012
+ if (!value) {
1013
+ throw new WorkflowWorldError(`Event not found: ${eventId}`);
1014
+ }
1015
+ value.eventData ||= value.eventDataJson;
1016
+ const parsed = EventSchema.parse(compact(value));
1017
+ const resolveData = params?.resolveData ?? 'all';
1018
+ return stripEventDataRefs(parsed, resolveData);
174
1019
  },
175
1020
  async list(params) {
176
1021
  const limit = params?.pagination?.limit ?? 100;
@@ -185,8 +1030,13 @@ export function createEventsStorage(drizzle) {
185
1030
  .orderBy(order.by)
186
1031
  .limit(limit + 1);
187
1032
  const values = all.slice(0, limit);
1033
+ const resolveData = params?.resolveData ?? 'all';
188
1034
  return {
189
- data: values.map(compact),
1035
+ data: values.map((v) => {
1036
+ v.eventData ||= v.eventDataJson;
1037
+ const parsed = EventSchema.parse(compact(v));
1038
+ return stripEventDataRefs(parsed, resolveData);
1039
+ }),
190
1040
  cursor: values.at(-1)?.eventId ?? null,
191
1041
  hasMore: all.length > limit,
192
1042
  };
@@ -204,8 +1054,13 @@ export function createEventsStorage(drizzle) {
204
1054
  .orderBy(order.by)
205
1055
  .limit(limit + 1);
206
1056
  const values = all.slice(0, limit);
1057
+ const resolveData = params?.resolveData ?? 'all';
207
1058
  return {
208
- data: values.map(compact),
1059
+ data: values.map((v) => {
1060
+ v.eventData ||= v.eventDataJson;
1061
+ const parsed = EventSchema.parse(compact(v));
1062
+ return stripEventDataRefs(parsed, resolveData);
1063
+ }),
209
1064
  cursor: values.at(-1)?.eventId ?? null,
210
1065
  hasMore: all.length > limit,
211
1066
  };
@@ -221,98 +1076,60 @@ export function createHooksStorage(drizzle) {
221
1076
  .limit(1)
222
1077
  .prepare('workflow_hooks_get_by_token');
223
1078
  return {
224
- async get(hookId) {
1079
+ async get(hookId, params) {
225
1080
  const [value] = await drizzle
226
1081
  .select()
227
1082
  .from(hooks)
228
1083
  .where(eq(hooks.hookId, hookId))
229
1084
  .limit(1);
230
- return compact(value);
1085
+ value.metadata ||= value.metadataJson;
1086
+ const parsed = HookSchema.parse(compact(value));
1087
+ parsed.isWebhook ??= true;
1088
+ const resolveData = params?.resolveData ?? 'all';
1089
+ return filterHookData(parsed, resolveData);
231
1090
  },
232
- async create(runId, data) {
233
- const [value] = await drizzle
234
- .insert(hooks)
235
- .values({
236
- runId,
237
- hookId: data.hookId,
238
- token: data.token,
239
- ownerId: '', // TODO: get from context
240
- projectId: '', // TODO: get from context
241
- environment: '', // TODO: get from context
242
- })
243
- .onConflictDoNothing()
244
- .returning();
245
- if (!value) {
246
- throw new WorkflowAPIError(`Hook ${data.hookId} already exists`, {
247
- status: 409,
248
- });
249
- }
250
- return compact(value);
251
- },
252
- async getByToken(token) {
1091
+ async getByToken(token, params) {
253
1092
  const [value] = await getByToken.execute({ token });
254
1093
  if (!value) {
255
- throw new WorkflowAPIError(`Hook not found for token: ${token}`, {
256
- status: 404,
257
- });
1094
+ throw new HookNotFoundError(token);
258
1095
  }
259
- return compact(value);
1096
+ value.metadata ||= value.metadataJson;
1097
+ const parsed = HookSchema.parse(compact(value));
1098
+ parsed.isWebhook ??= true;
1099
+ const resolveData = params?.resolveData ?? 'all';
1100
+ return filterHookData(parsed, resolveData);
260
1101
  },
261
1102
  async list(params) {
262
1103
  const limit = params?.pagination?.limit ?? 100;
263
1104
  const fromCursor = params?.pagination?.cursor;
1105
+ const sortOrder = params?.pagination?.sortOrder ?? 'asc';
1106
+ const orderFn = sortOrder === 'asc' ? asc : desc;
1107
+ const cursorFn = sortOrder === 'asc' ? gt : lt;
264
1108
  const all = await drizzle
265
1109
  .select()
266
1110
  .from(hooks)
267
- .where(and(map(params.runId, (id) => eq(hooks.runId, id)), map(fromCursor, (c) => lt(hooks.hookId, c))))
268
- .orderBy(desc(hooks.hookId))
1111
+ .where(and(map(params.runId, (id) => eq(hooks.runId, id)), map(fromCursor, (c) => cursorFn(hooks.hookId, c))))
1112
+ .orderBy(orderFn(hooks.hookId))
269
1113
  .limit(limit + 1);
270
1114
  const values = all.slice(0, limit);
271
1115
  const hasMore = all.length > limit;
1116
+ const resolveData = params?.resolveData ?? 'all';
272
1117
  return {
273
- data: values.map(compact),
1118
+ data: values.map((v) => {
1119
+ v.metadata ||= v.metadataJson;
1120
+ const parsed = HookSchema.parse(compact(v));
1121
+ return filterHookData(parsed, resolveData);
1122
+ }),
274
1123
  cursor: values.at(-1)?.hookId ?? null,
275
1124
  hasMore,
276
1125
  };
277
1126
  },
278
- async dispose(hookId) {
279
- const [value] = await drizzle
280
- .delete(hooks)
281
- .where(eq(hooks.hookId, hookId))
282
- .returning();
283
- if (!value) {
284
- throw new WorkflowAPIError(`Hook not found: ${hookId}`, {
285
- status: 404,
286
- });
287
- }
288
- return compact(value);
289
- },
290
1127
  };
291
1128
  }
292
1129
  export function createStepsStorage(drizzle) {
293
1130
  const { steps } = Schema;
294
1131
  return {
295
- async create(runId, data) {
296
- const [value] = await drizzle
297
- .insert(steps)
298
- .values({
299
- runId,
300
- stepId: data.stepId,
301
- stepName: data.stepName,
302
- input: data.input,
303
- status: 'pending',
304
- attempt: 1,
305
- })
306
- .onConflictDoNothing()
307
- .returning();
308
- if (!value) {
309
- throw new WorkflowAPIError(`Step ${data.stepId} already exists`, {
310
- status: 409,
311
- });
312
- }
313
- return compact(value);
314
- },
315
- async get(runId, stepId) {
1132
+ get: (async (runId, stepId, params) => {
316
1133
  // If runId is not provided, query only by stepId
317
1134
  const whereClause = runId
318
1135
  ? and(eq(steps.stepId, stepId), eq(steps.runId, runId))
@@ -323,49 +1140,17 @@ export function createStepsStorage(drizzle) {
323
1140
  .where(whereClause)
324
1141
  .limit(1);
325
1142
  if (!value) {
326
- throw new WorkflowAPIError(`Step not found: ${stepId}`, {
327
- status: 404,
328
- });
1143
+ throw new WorkflowWorldError(`Step not found: ${stepId}`);
329
1144
  }
330
- return compact(value);
331
- },
332
- async update(runId, stepId, data) {
333
- // Fetch current step to check if startedAt is already set
334
- const [currentStep] = await drizzle
335
- .select()
336
- .from(steps)
337
- .where(and(eq(steps.stepId, stepId), eq(steps.runId, runId)))
338
- .limit(1);
339
- if (!currentStep) {
340
- throw new WorkflowAPIError(`Step not found: ${stepId}`, {
341
- status: 404,
342
- });
343
- }
344
- const updates = {
345
- ...data,
346
- output: data.output,
347
- };
348
- const now = new Date();
349
- // Only set startedAt the first time the step transitions to 'running'
350
- if (data.status === 'running' && !currentStep.startedAt) {
351
- updates.startedAt = now;
352
- }
353
- if (data.status === 'completed' || data.status === 'failed') {
354
- updates.completedAt = now;
355
- }
356
- const [value] = await drizzle
357
- .update(steps)
358
- .set(updates)
359
- .where(and(eq(steps.stepId, stepId), eq(steps.runId, runId)))
360
- .returning();
361
- if (!value) {
362
- throw new WorkflowAPIError(`Step not found: ${stepId}`, {
363
- status: 404,
364
- });
365
- }
366
- return compact(value);
367
- },
368
- async list(params) {
1145
+ value.output ||= value.outputJson;
1146
+ value.input ||= value.inputJson;
1147
+ value.error ||= parseErrorJson(value.errorJson);
1148
+ const deserialized = deserializeStepError(compact(value));
1149
+ const parsed = StepSchema.parse(deserialized);
1150
+ const resolveData = params?.resolveData ?? 'all';
1151
+ return filterStepData(parsed, resolveData);
1152
+ }),
1153
+ list: (async (params) => {
369
1154
  const limit = params?.pagination?.limit ?? 20;
370
1155
  const fromCursor = params?.pagination?.cursor;
371
1156
  const all = await drizzle
@@ -376,12 +1161,41 @@ export function createStepsStorage(drizzle) {
376
1161
  .limit(limit + 1);
377
1162
  const values = all.slice(0, limit);
378
1163
  const hasMore = all.length > limit;
1164
+ const resolveData = params?.resolveData ?? 'all';
379
1165
  return {
380
- data: values.map(compact),
1166
+ data: values.map((v) => {
1167
+ v.output ||= v.outputJson;
1168
+ v.input ||= v.inputJson;
1169
+ v.error ||= parseErrorJson(v.errorJson);
1170
+ const deserialized = deserializeStepError(compact(v));
1171
+ const parsed = StepSchema.parse(deserialized);
1172
+ return filterStepData(parsed, resolveData);
1173
+ }),
381
1174
  hasMore,
382
1175
  cursor: values.at(-1)?.stepId ?? null,
383
1176
  };
384
- },
1177
+ }),
385
1178
  };
386
1179
  }
1180
+ function filterStepData(step, resolveData) {
1181
+ if (resolveData === 'none') {
1182
+ const { input: _, output: __, ...rest } = step;
1183
+ return { input: undefined, output: undefined, ...rest };
1184
+ }
1185
+ return step;
1186
+ }
1187
+ function filterRunData(run, resolveData) {
1188
+ if (resolveData === 'none') {
1189
+ const { input: _, output: __, ...rest } = run;
1190
+ return { input: undefined, output: undefined, ...rest };
1191
+ }
1192
+ return run;
1193
+ }
1194
+ function filterHookData(hook, resolveData) {
1195
+ if (resolveData === 'none' && 'metadata' in hook) {
1196
+ const { metadata: _, ...rest } = hook;
1197
+ return { metadata: undefined, ...rest };
1198
+ }
1199
+ return hook;
1200
+ }
387
1201
  //# sourceMappingURL=storage.js.map