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