Repository navigation
Expand file tree
/
Copy pathstorage.ts
More file actions
4118 lines (3950 loc) · 159 KB
/
Copy pathstorage.ts
File metadata and controls
4118 lines (3950 loc) · 159 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AsyncLocalStorage } from 'node:async_hooks';
import { createHash } from 'node:crypto';
import {
EntityConflictError,
HookForceClaimedError,
HookNotFoundError,
InBandSupersededError,
RunExpiredError,
RunNotSupportedError,
START_HOOK_ADMISSION_REJECTED,
TooEarlyError,
WorkflowRunNotFoundError,
WorkflowWorldError,
} from '@workflow/errors';
import type {
AnyEventRequest,
AttributeChange,
CreateEventParams,
Event,
EventListResponse,
EventLogSnapshot,
EventResult,
EventsResolveData,
EventsSubscribeOptions,
ExperimentalSetAttributesResult,
GetEventParams,
Hook,
ListEventsParams,
ListHooksParams,
PaginatedResponse,
ResolveData,
SerializedData,
StartHook,
Step,
StepWithoutData,
Storage,
Wait,
WorkflowRun,
WorkflowRunWithoutData,
} from '@workflow/world';
import {
ATTRIBUTE_MAX_PER_RUN,
AttributeValidationError,
EVENT_ID_BODY_LENGTH,
EVENT_ID_PREFIX,
EventSchema,
entityResolveData,
eventIdToSlot,
FIRST_EVENT_SLOT,
getMaxEventsPerRun,
HookSchema,
isChildEntityCreationEvent,
isChildEntityCreationEventType,
isHookEventRequiringExistence,
isLegacySpecVersion,
isStartHookId,
isTerminalRunEventType,
isTerminalStepStatus,
isTerminalWorkflowRunStatus,
RETENTION_ATTRIBUTE,
RETENTION_ZERO,
requiresNewerWorld,
SPEC_VERSION_CURRENT,
SPEC_VERSION_LEGACY,
SPEC_VERSION_MAX_SUPPORTED,
SPEC_VERSION_SINGLE_ORCHESTRATOR,
SPEC_VERSION_SUPPORTS_HOOK_FORCE_CLAIM,
StepSchema,
slotToEventId,
stripEventDataRefs,
TERMINAL_STEP_STATUSES,
TERMINAL_WORKFLOW_RUN_STATUSES,
validateAttributeChanges,
validateUlidTimestamp,
WorkflowRunSchema,
} from '@workflow/world';
import { encode } from 'cbor-x';
import {
and,
asc,
desc,
eq,
exists,
getTableColumns,
gt,
inArray,
isNull,
lt,
lte,
notExists,
notInArray,
or,
type SQL,
sql,
} from 'drizzle-orm';
import { monotonicFactory } from 'ulid';
import { type Drizzle, type DrizzleHandle, Schema } from './drizzle/index.js';
import type { SerializedContent } from './drizzle/schema.js';
import {
invocationDataExpired,
invocationExpiredError,
} from './invocation-retention.js';
import {
purgeRunUserDataIfZeroRetention,
scrubStepWriteIfRunPurged,
} from './retention.js';
import { announceRunEvents, type RunEventsFeed } from './run-events.js';
import {
notifyRunTerminal,
RUN_STATUS_POLL_INTERVAL_MS,
type RunStatusListener,
} from './run-status.js';
import {
admittedStartHook,
decideStartHookAdmission,
HOOK_TOKEN_CLAIM_UNIQUE,
runStartHook,
type StartHookDecision,
startHookConflict,
} from './start-hook.js';
import { compact } from './util.js';
const DAY_MS = 24 * 60 * 60 * 1000;
/**
* A drizzle handle, either the pool or a transaction. Slot allocation runs on
* whichever one the caller is already inside, so the position an insert takes
* commits or rolls back with the insert itself.
*/
type DrizzleLike = Pick<
Drizzle,
'insert' | 'update' | 'select' | 'with' | '$with'
>;
/** Only for legacy (pre-slot) runs; see `allocateEventId`. */
const legacyEventUlid = monotonicFactory();
/**
* How many positions one insert will try before giving up. Reached only when a
* run is taking concurrent writes faster than any of them can commit.
*/
const SLOT_INSERT_MAX_ATTEMPTS = 40;
/**
* Collisions that retry the instant the conflicting writer settles.
*
* `ON CONFLICT DO NOTHING` does not skip an uncommitted conflicting row: the
* unique-index check waits on that writer's transaction and only then reports
* the conflict, so a lost race has already waited for exactly the thing the
* next position depends on. Sleeping on top of that adds latency to a
* suspension flush and buys nothing.
*
* The backoff below covers the shape blocking does not: writers that keep
* arriving while the loop spins, where jittering the herd is the only way the
* loop converges before it exhausts its attempts.
*/
const SLOT_INSERT_IMMEDIATE_ATTEMPTS = 8;
/** Backoff between collisions, so a wide fan-out spreads rather than lockstep. */
const SLOT_INSERT_BASE_DELAY_MS = 2;
const SLOT_INSERT_MAX_DELAY_MS = 40;
/**
* Isolation for every transaction an event insert can run inside.
*
* {@link insertEventRow} answers a collision by recomputing the next position
* and inserting again, which only terminates if the retry can see rows
* committed since the transaction began. Under REPEATABLE READ or SERIALIZABLE
* it cannot: every attempt reads the transaction's original snapshot, computes
* the same taken position, and the loop runs to its limit and 503s. READ
* COMMITTED is Postgres' default, so this is a statement of the requirement
* rather than a change, and it keeps a database whose
* `default_transaction_isolation` was raised from turning event writes into
* timeouts. Inserts outside a transaction need nothing: a lone statement takes
* a fresh snapshot at every isolation level.
*/
const SLOT_INSERT_TRANSACTION = { isolationLevel: 'read committed' } as const;
/** The pg error behind a drizzle wrapper, or an empty shape if there is none. */
function pgErrorOf(err: unknown): { code?: string; constraint?: string } {
const direct = err as { code?: string; constraint?: string };
if (direct?.code) {
return direct;
}
return (
(err as { cause?: { code?: string; constraint?: string } })?.cause ?? {}
);
}
/**
* The position a slot-numbered insert takes: one above the highest the run
* already holds, read inside the INSERT that takes it.
*
* Nothing hands out a position ahead of the write that fills it. A writer that
* loses a dedup race, or whose transaction rolls back, leaves the numbering
* untouched, so a log missing a position is missing an *event* rather than
* merely a number. The runtime depends on exactly that: it refuses to replay a
* log with a hole, because a position nothing occupies cannot be told apart
* from an event that never happened.
*
* A counter column would be cheaper and is what this used to be. It cannot
* hold that property: a number handed out before the write lands is a number
* lost whenever the write does not, and the resulting holes are permanent.
*
* The subquery is an index-only read of the primary key's last row for the
* run, not a scan. Ordering is lexicographic, which is the same order as by
* position because every body is zero-padded to a fixed width.
*
* Every numeric parameter is cast explicitly. `substring(text from $n)` with an
* untyped parameter resolves to the *regular expression* overload rather than
* the positional one, which quietly returns NULL for every id and hands every
* writer the first slot.
*/
function nextSlotId(runId: string): SQL<string> {
const bodyFrom = sql.raw(String(EVENT_ID_PREFIX.length + 1));
const width = sql.raw(String(EVENT_ID_BODY_LENGTH));
const noEvents = sql.raw(String(FIRST_EVENT_SLOT - 1));
return sql<string>`${EVENT_ID_PREFIX} || lpad((coalesce((select cast(substring(prev.id from ${bodyFrom}) as bigint) from ${Schema.events} prev where prev.run_id = ${runId} order by prev.id desc limit 1), ${noEvents}) + 1)::text, ${width}, '0')`;
}
/**
* RETURNING columns of a step write: the step row, and whether its run asked
* for zero retention (fixed when the run starts), so a write that may land
* after the run's purge is checked (`scrubStepWriteIfRunPurged`) without a
* query for every other run.
*/
function stepRowAndRetention(runId: string) {
return {
...getTableColumns(Schema.steps),
zeroRetention: sql<boolean>`coalesce((select r.attributes ->> ${RETENTION_ATTRIBUTE} = ${RETENTION_ZERO} from ${Schema.runs} r where r.id = ${runId}), false)`,
};
}
/**
* The id an insert for `runId` should allocate with: a slot expression for a
* slot-numbered run, a fresh ULID for one that predates slots.
*
* A row in `workflow_event_slots` is the marker for the first case. Its
* absence is exactly the "this run predates slots" signal, which is why the
* table is still read even though nothing advances it any more.
*
* A legacy run keeps minting under the original `wevt_` prefix rather than
* moving to `evnt_`: a mid-life prefix change would sort every new event
* before every old one, since `evnt_` < `wevt_`.
*/
async function allocateEventId(
db: DrizzleLike,
runId: string
): Promise<string | SQL<string>> {
const [row] = await db
.select({ runId: Schema.eventSlots.runId })
.from(Schema.eventSlots)
.where(eq(Schema.eventSlots.runId, runId))
.limit(1);
return row ? nextSlotId(runId) : `wevt_${legacyEventUlid()}`;
}
/**
* The refusal for a `hook_received` to a hook that no longer exists because
* another run took its token over (`experimental_force`): a redirect, so
* `resumeHook()` follows the token instead of dropping the payload. The
* evidence is the hook's own `hook_disposed{forceClaimedBy}` row, which the
* takeover writes in the hook's run; that the token now belongs to a hook
* with a `claimedFrom` is not enough, since a hook its run disposed itself
* may share its token with a later owner that took it from somebody else.
* The error names the token's current owner (the end of a chain of
* takeovers), falling back to the claimer the row names. `undefined` when
* the hook was not taken over: the caller answers not-found.
*/
async function forceClaimRefusal(
db: DrizzleLike,
runId: string,
hookId: string,
eventData: unknown
): Promise<HookForceClaimedError | undefined> {
const [disposal] = await db
.select({
eventData: Schema.events.eventData,
eventDataJson: Schema.events.eventDataJson,
})
.from(Schema.events)
.where(
and(
eq(Schema.events.runId, runId),
eq(Schema.events.correlationId, hookId),
eq(Schema.events.eventType, 'hook_disposed')
)
)
.limit(1);
const disposalData = (disposal?.eventData ?? disposal?.eventDataJson) as
| {
token?: unknown;
forceClaimedBy?: { runId?: unknown; hookId?: unknown };
}
| undefined;
const claimedBy = disposalData?.forceClaimedBy;
if (
typeof claimedBy?.runId !== 'string' ||
typeof claimedBy.hookId !== 'string'
) {
return undefined;
}
const requestToken = (eventData as { token?: unknown } | undefined)?.token;
const token =
typeof requestToken === 'string'
? requestToken
: typeof disposalData?.token === 'string'
? disposalData.token
: undefined;
const [successor] =
token === undefined
? []
: await db
.select({ runId: Schema.hooks.runId, hookId: Schema.hooks.hookId })
.from(Schema.hooks)
.where(eq(Schema.hooks.token, token))
.limit(1);
return new HookForceClaimedError(
token ?? '',
successor?.runId ?? claimedBy.runId,
successor?.hookId ?? claimedBy.hookId
);
}
/*
* The in-band writer fence (`WorldCapabilities.inBandFence`).
*
* `workflow_event_slots.seq_in_band` counts the positions accepted from
* in-band writes (writes by the run's orchestrator), `run_created` included,
* so a run starts at {@link IN_BAND_SEQ_AT_RUN_CREATION}. An in-band create
* is accepted only when its `expectedSeqInBand` equals the count, and the
* check and the advance happen in the INSERT that takes the event's slot: a
* data-modifying CTE runs
*
* UPDATE workflow_event_slots SET seq_in_band = seq_in_band + 1
* WHERE run_id = $run AND seq_in_band = $expected
*
* and the event's id is the next slot only when that UPDATE matched, NULL
* otherwise. A NULL id violates the primary key's NOT NULL, so a refused
* write fails as a whole and allocates nothing, and an accepted one commits
* its event and its count together: a reader never sees the count include an
* event it cannot list.
*
* Several event types also update an entity row (the run's status or
* attributes, a wait, an inline step) ahead of that insert. So every fenced
* create runs in one transaction that first locks the run's slots row
* (`SELECT ... FOR UPDATE`) and compares the count: a stale writer is refused
* before it touches any row, and of concurrent writers holding the same count
* only the first through the lock writes anything, its entity updates and
* its event committing together. The CTE still guards the insert itself.
* Only in-band writers take that lock; out-of-band writes never wait on it.
*
* A primary-key conflict (another writer took the slot first) is absorbed by
* `ON CONFLICT DO NOTHING` after the CTE has already advanced the count, so
* the insert puts it back before it retries at the next slot; when it cannot
* (another in-band writer moved it meanwhile), this writer has been
* superseded.
*
* Out-of-band writes never touch the count.
*/
/** Postgres error code for a NOT NULL violation. */
const NOT_NULL_VIOLATION = '23502';
/** The fence one in-band create applies to the first event it inserts for its run. */
interface PendingFence {
runId: string;
expected: number;
/**
* The write's `occurredAt`, stored as the event's `createdAt`: an in-band
* write's time is the one its orchestrator chose, which a workflow that ran
* ahead of the write has already read (see `Storage.events`).
*/
occurredAt?: Date;
/** Set once the fenced insert committed; later inserts are unfenced. */
consumed: boolean;
}
// per-copy-ok: set and read within one `create` call, which runs entirely
// inside the module copy that defines it, so a context never has to cross a
// copy boundary.
const pendingFence = new AsyncLocalStorage<PendingFence>();
async function readSeqInBand(
db: DrizzleLike,
runId: string
): Promise<number | undefined> {
const [row] = await db
.select({ seqInBand: Schema.eventSlots.seqInBand })
.from(Schema.eventSlots)
.where(eq(Schema.eventSlots.runId, runId))
.limit(1);
return row?.seqInBand;
}
async function supersededError(
db: DrizzleLike,
runId: string,
expected: number
): Promise<InBandSupersededError> {
const current = await readSeqInBand(db, runId).catch(() => undefined);
return new InBandSupersededError(
`In-band write on run ${runId} expected seqInBand ${expected}, but the run is at ${current ?? 'unknown'}. Another orchestrator wrote in-band events this one has not seen; stop writing and redeliver.`,
current !== undefined ? { seqInBand: current } : undefined
);
}
/**
* One attempt of a fenced insert. Returns the committed row, `undefined` for
* a slot conflict (the count was advanced and must be put back), or throws
* {@link InBandSupersededError} when the count did not match.
*/
async function fencedInsertAttempt(
db: DrizzleLike,
values: Omit<typeof Schema.events.$inferInsert, 'eventId'> & {
eventId: SQL<string>;
},
fence: PendingFence
): Promise<{ eventId: string; createdAt: Date } | undefined> {
const slots = Schema.eventSlots;
const advanced = db
.$with('in_band_fence', { runId: slots.runId })
.as(
sql`update ${slots} set ${sql.identifier(slots.seqInBand.name)} = ${slots.seqInBand} + 1 where ${slots.runId} = ${fence.runId} and ${slots.seqInBand} = ${sql`${fence.expected}::integer`} returning ${slots.runId}`
);
try {
const [row] = await db
.with(advanced)
.insert(Schema.events)
.values({
...values,
...(fence.occurredAt ? { createdAt: fence.occurredAt } : {}),
eventId: sql<string>`(select ${values.eventId} from ${advanced})`,
} as unknown as typeof Schema.events.$inferInsert)
.onConflictDoNothing({
target: [Schema.events.runId, Schema.events.eventId],
})
.returning({
eventId: Schema.events.eventId,
createdAt: Schema.events.createdAt,
});
return row;
} catch (err) {
if (pgErrorOf(err).code === NOT_NULL_VIOLATION) {
throw await supersededError(db, fence.runId, fence.expected);
}
throw err;
}
}
/** Puts back the count a fenced attempt advanced before losing its slot. */
async function revertFenceAdvance(
db: DrizzleLike,
fence: PendingFence
): Promise<boolean> {
const rows = await db
.update(Schema.eventSlots)
.set({ seqInBand: sql`${Schema.eventSlots.seqInBand} - 1` })
.where(
and(
eq(Schema.eventSlots.runId, fence.runId),
eq(Schema.eventSlots.seqInBand, fence.expected + 1)
)
)
.returning({ runId: Schema.eventSlots.runId });
return rows.length > 0;
}
/**
* Inserts one event row, retrying while the position it computed is taken.
*
* The primary-key conflict is absorbed by `ON CONFLICT DO NOTHING` rather than
* raised, so a lost race costs a retry instead of the enclosing transaction.
* An error inside a transaction would poison it, and these inserts run in one.
* Every other unique violation still raises, which is what lets callers
* translate a dedup conflict on `workflow_events_entity_creation_unique`.
*
* Returns `undefined` only for an id that is a plain string (a legacy ULID, or
* the reserved first slot), where a conflict is the caller's answer rather
* than something to retry.
*/
async function insertEventRow(
db: DrizzleLike,
values: Omit<typeof Schema.events.$inferInsert, 'eventId'> & {
eventId: string | SQL<string>;
}
): Promise<{ eventId: string; createdAt: Date } | undefined> {
const runId = values.runId;
const allocates = typeof values.eventId !== 'string';
// The create's own event on a fenced run is the first slot-allocating
// insert for that run; see the in-band writer fence above.
const fence = pendingFence.getStore();
const fenced =
allocates && fence !== undefined && !fence.consumed && fence.runId === runId
? fence
: undefined;
for (let attempt = 0; ; attempt++) {
const [row] = fenced
? [
await fencedInsertAttempt(
db,
values as typeof values & { eventId: SQL<string> },
fenced
),
]
: await db
.insert(Schema.events)
.values(values as typeof Schema.events.$inferInsert)
.onConflictDoNothing({
target: [Schema.events.runId, Schema.events.eventId],
})
.returning({
eventId: Schema.events.eventId,
createdAt: Schema.events.createdAt,
});
if (row) {
if (fenced) fenced.consumed = true;
return row;
}
if (fenced && !(await revertFenceAdvance(db, fenced))) {
throw await supersededError(db, fenced.runId, fenced.expected);
}
if (!allocates || attempt >= SLOT_INSERT_MAX_ATTEMPTS) {
if (!allocates) {
return undefined;
}
throw new WorkflowWorldError(
`Could not allocate an event slot for run "${runId}" after ${SLOT_INSERT_MAX_ATTEMPTS} attempts`,
{ status: 503 }
);
}
if (attempt >= SLOT_INSERT_IMMEDIATE_ATTEMPTS) {
const delay = Math.min(
SLOT_INSERT_MAX_DELAY_MS,
SLOT_INSERT_BASE_DELAY_MS *
2 ** (attempt - SLOT_INSERT_IMMEDIATE_ATTEMPTS)
);
await new Promise((resolve) =>
setTimeout(resolve, Math.random() * delay)
);
}
}
}
/**
* Marks a run being created as slot-numbered and returns its first event id.
*
* The row records the scheme and nothing else; positions come from the log
* itself, see {@link nextSlotId}.
*
* `DO NOTHING` on conflict because the arbitration that matters is the event
* insert: two writers racing one run_created both take the first slot, and the
* composite events primary key rejects the loser.
*/
async function openEventSlots(db: DrizzleLike, runId: string): Promise<string> {
await db.insert(Schema.eventSlots).values({ runId }).onConflictDoNothing();
return slotToEventId(FIRST_EVENT_SLOT);
}
/**
* The report half of bump-and-report: the events sitting on the slots between
* the one the writer asked for and the one its write actually landed on.
*
* Returns `undefined` when there is nothing to report: the write took the slot
* it asked for, the run is not slot-numbered, or the caller sent a count from a
* log that is already ahead of this write.
*
* The set can be short of the slot span it covers. A position is taken by the
* INSERT that computes it, and that INSERT commits on its own, so at the moment
* this reads the span a concurrent writer holding a lower position may not have
* committed yet. Its row appears shortly after and no position is left behind,
* because a write that fails never took one. `hasMore` says the report is a
* lower bound for now rather than a permanent one, and it is advisory either
* way: the caller's ordinary incremental read still runs.
*/
async function reportSkippedSlots(
db: DrizzleHandle,
runId: string,
committedEventId: string,
askedFor: number,
resolveData: EventsResolveData
): Promise<{ events: Event[]; hasMore: boolean } | undefined> {
const committedSlot = eventIdToSlot(committedEventId);
if (
committedSlot === null ||
askedFor < FIRST_EVENT_SLOT ||
committedSlot <= askedFor + 1
) {
return undefined;
}
const rows = await db
.select()
.from(Schema.events)
.where(
and(
eq(Schema.events.runId, runId),
gt(Schema.events.eventId, slotToEventId(askedFor)),
lt(Schema.events.eventId, committedEventId)
)
)
.orderBy(Schema.events.eventId);
const events = rows.map((row) => {
row.eventData ||= row.eventDataJson;
return stripEventDataRefs(EventSchema.parse(compact(row)), resolveData);
});
return {
events,
hasMore: events.length < committedSlot - askedFor - 1,
};
}
function getHookRetentionLimitMs(): number {
const days = Number(
process.env.WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS ?? 30
);
if (!Number.isFinite(days) || days <= 0) {
throw new WorkflowWorldError(
'WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS must be a positive number',
{ status: 400 }
);
}
return days * DAY_MS;
}
/** Persist a hook event and deduplicate retries using its resumeId. */
async function createHookResume(
drizzle: DrizzleHandle,
runId: string,
data: Extract<AnyEventRequest, { eventType: 'hook_received' }>,
params: CreateEventParams & { resumeId: string }
): Promise<EventResult> {
if (!data.correlationId)
throw new WorkflowWorldError('Hook identity is required', { status: 400 });
const bytes =
data.eventData.payload instanceof Uint8Array
? data.eventData.payload
: encode(data.eventData.payload);
const digest = createHash('sha256').update(bytes).digest('hex');
if (params.resumePayloadDigest && params.resumePayloadDigest !== digest) {
throw new WorkflowWorldError(
'Hook resume digest does not match its payload',
{ status: 422 }
);
}
const event = await drizzle.transaction(async (tx) => {
const [run] = await tx
.select({
status: Schema.runs.status,
attributes: Schema.runs.attributes,
expiredAt: Schema.runs.expiredAt,
})
.from(Schema.runs)
.where(eq(Schema.runs.runId, runId))
.for('update')
.limit(1);
if (!run) throw new WorkflowRunNotFoundError(runId);
if (invocationDataExpired(run)) throw invocationExpiredError();
const [prior] = await tx
.select()
.from(Schema.events)
.where(
and(
eq(Schema.events.runId, runId),
eq(Schema.events.resumeId, params.resumeId),
eq(Schema.events.eventType, 'hook_received')
)
)
.limit(1);
if (prior) {
const parsed = EventSchema.parse(
compact({ ...prior, eventData: prior.eventData ?? prior.eventDataJson })
);
if (
parsed.eventType !== 'hook_received' ||
prior.correlationId !== data.correlationId ||
prior.resumePayloadDigest !== digest ||
parsed.eventData?.token !== data.eventData.token
) {
throw new WorkflowWorldError(
'Hook resume identity reused with different contents',
{ status: 422 }
);
}
return parsed;
}
if (isTerminalWorkflowRunStatus(run.status))
throw new RunExpiredError('Cannot resume a hook on a terminal run');
const [hook] = await tx
.select()
.from(Schema.hooks)
.where(
and(
eq(Schema.hooks.hookId, data.correlationId),
eq(Schema.hooks.runId, runId)
)
)
.for('update')
.limit(1);
if (
!hook ||
(data.eventData.token !== undefined &&
hook.token !== data.eventData.token)
) {
throw new HookNotFoundError(data.correlationId);
}
const created = await insertEventRow(tx, {
runId,
eventId: await allocateEventId(tx, runId),
eventType: 'hook_received',
correlationId: data.correlationId,
eventData: data.eventData,
specVersion: data.specVersion ?? SPEC_VERSION_CURRENT,
resumeId: params.resumeId,
resumePayloadDigest: digest,
});
if (!created)
throw new EntityConflictError('Hook resume event could not be created');
return EventSchema.parse({
...data,
...created,
runId,
resumeId: params.resumeId,
});
}, SLOT_INSERT_TRANSACTION);
const resolveData = params.resolveData ?? 'all';
const result: EventResult = { event: stripEventDataRefs(event, resolveData) };
if (typeof params.sinceCursor === 'string') {
const rows = await drizzle
.select()
.from(Schema.events)
.where(
and(
eq(Schema.events.runId, runId),
gt(Schema.events.eventId, params.sinceCursor)
)
)
.orderBy(Schema.events.eventId)
.limit(101);
const events = rows.slice(0, 100).map((row) =>
stripEventDataRefs(
EventSchema.parse(
compact({
...row,
eventData: row.eventData ?? row.eventDataJson,
})
),
resolveData
)
);
return {
...result,
events,
cursor: events.at(-1)?.eventId ?? null,
hasMore: rows.length > 100,
};
} else if (params.eventCount !== undefined) {
const skipped = await reportSkippedSlots(
drizzle,
runId,
event.eventId,
params.eventCount,
resolveData
);
if (skipped)
return {
...result,
events: skipped.events,
hasMore: skipped.hasMore,
cursor: null,
};
}
return result;
}
/**
* Read helper for the deprecated `error` text column (legacy: JSON-stringified
* `StructuredError`). In the current event-sourced model, the `error` field on
* entities is `SerializedData` (Uint8Array) produced by the new error
* serialization pipeline; legacy text-column records pre-date that pipeline
* and cannot be hydrated back into the original thrown value.
*
* Returns `null` unconditionally so downstream consumers treat legacy errors
* as absent rather than receiving a shape that `hydrateStepError` /
* `hydrateRunError` can't process. Callers that need to inspect the raw
* legacy payload should read the `errorJson` column directly.
*/
function parseErrorJson(_errorJson: string | null): SerializedData | null {
return null;
}
/**
* Pass-through helper kept for backwards compatibility with the run read path.
* In the current event-sourced model, `error` is already `SerializedData`
* (Uint8Array) on the entity, and any legacy `errorStack` / `errorCode`
* fields are no longer populated by the current write path.
*/
function deserializeRunError(run: any): WorkflowRun {
// Drop any stale legacy-only fields we might still encounter on read, and
// the internal `jobPrefix` routing column, which is not part of a run.
const { errorStack: _errorStack, jobPrefix: _jobPrefix, ...rest } = run;
return rest as WorkflowRun;
}
/**
* Deserialize step data, mapping DB columns to interface fields.
* The error field should already be deserialized from CBOR or fallback to errorJson.
*/
function deserializeStepError(step: any): Step {
const { startedAt, ...rest } = step;
return {
...rest,
startedAt,
} as Step;
}
/**
* `runs.list`, optionally narrowed by an extra predicate that callers of the
* public interface never see.
*/
function createRunsList(
drizzle: Drizzle,
scope?: SQL
): Storage['runs']['list'] {
const { runs } = Schema;
return (async (params) => {
const limit = params?.pagination?.limit ?? 20;
const fromCursor = params?.pagination?.cursor;
// Run ids are ULIDs, so id order is creation order.
const sortOrder = params?.pagination?.sortOrder ?? 'desc';
const orderFn = sortOrder === 'asc' ? asc : desc;
const cursorFn = sortOrder === 'asc' ? gt : lt;
const all = await drizzle
.select()
.from(runs)
.where(
and(
scope,
map(fromCursor, (c) => cursorFn(runs.runId, c)),
map(params?.workflowName, (wf) => eq(runs.workflowName, wf)),
map(params?.status, (s) =>
Array.isArray(s) ? inArray(runs.status, s) : eq(runs.status, s)
)
)
)
.orderBy(orderFn(runs.runId))
.limit(limit + 1);
const values = all.slice(0, limit);
const hasMore = all.length > limit;
const resolveData = params?.resolveData ?? 'all';
return {
data: values.map((v) => {
v.output ||= v.outputJson;
v.input ||= v.inputJson;
v.executionContext ||= v.executionContextJson;
v.error ||= parseErrorJson(v.errorJson);
const deserialized = deserializeRunError(compact(v));
const parsed = WorkflowRunSchema.parse(deserialized);
return filterRunData(parsed, resolveData);
}),
hasMore,
cursor: values.at(-1)?.runId ?? null,
};
}) as Storage['runs']['list'];
}
/**
* A `runs.list` for startup recovery: only the runs a World with this
* `jobPrefix` created, plus runs with no prefix (created before
* `workflow_runs.job_prefix` existed, or by storage constructed without a
* World).
*
* Recovery re-enqueues each listed run into this World's own Graphile task,
* and this World's runner then drives it. Listing every active run in a
* shared database would hand other apps' runs to this runner on every boot,
* whatever their `jobPrefix`. The public `runs.list` stays unscoped.
*/
export function createRecoverableRunsList(
drizzle: Drizzle,
jobPrefix: string
): Storage['runs']['list'] {
const { runs } = Schema;
return createRunsList(
drizzle,
or(eq(runs.jobPrefix, jobPrefix), isNull(runs.jobPrefix))
);
}
export function createRunsStorage(
drizzle: Drizzle,
/**
* Shared `LISTEN` subscription used by `waitForTerminalStatus`. Omit it and
* the wait still works, purely on its backstop re-read, which is what a
* direct caller constructing storage without a pool gets.
*/
runStatusListener?: RunStatusListener
): Storage['runs'] {
const { runs } = Schema;
const get = drizzle
.select()
.from(runs)
.where(eq(runs.runId, sql.placeholder('id')))
.limit(1)
.prepare('workflow_runs_get');
const getRun = (async (id, params) => {
const [value] = await get.execute({ id });
if (!value) {
throw new WorkflowRunNotFoundError(id);
}
value.output ||= value.outputJson;
value.input ||= value.inputJson;
value.executionContext ||= value.executionContextJson;
value.error ||= parseErrorJson(value.errorJson);
const deserialized = deserializeRunError(compact(value));
const parsed = WorkflowRunSchema.parse(deserialized);
const resolveData = params?.resolveData ?? 'all';
return filterRunData(parsed, resolveData);
}) as Storage['runs']['get'];
return {
get: getRun,
/**
* Long poll for a terminal run status. See
* `Storage['runs'].waitForTerminalStatus`.
*
* Reads the run, and while it is non-terminal parks on the run-terminal
* `NOTIFY` (bounded by the backstop re-read interval) before reading
* again. Returns the latest snapshot once `timeoutMs` is up, whatever its
* status, and propagates `WorkflowRunNotFoundError` exactly as `get` does.
*/
waitForTerminalStatus: (async (id, params) => {
const deadline = Date.now() + (params?.timeoutMs ?? 0);
while (true) {
const run = await getRun(id, params);
if (isTerminalWorkflowRunStatus(run.status)) return run;
const remainingMs = deadline - Date.now();
if (remainingMs <= 0 || params?.signal?.aborted) return run;
const waitMs = Math.min(remainingMs, RUN_STATUS_POLL_INTERVAL_MS);
if (runStatusListener) {
await runStatusListener.wait(id, waitMs, params?.signal);
} else {
await new Promise((resolve) => setTimeout(resolve, waitMs));
}
}
}) as NonNullable<Storage['runs']['waitForTerminalStatus']>,
getMany: (async (ids, params) => {
const uniqueIds = [...new Set(ids)];
if (uniqueIds.length === 0) {
return [];
}
const values = await drizzle
.select()
.from(runs)
.where(inArray(runs.runId, uniqueIds));
const resolveData = params?.resolveData ?? 'all';
const runsById = new Map(
values.map((value) => {
value.output ||= value.outputJson;
value.input ||= value.inputJson;
value.executionContext ||= value.executionContextJson;
value.error ||= parseErrorJson(value.errorJson);
const parsed = WorkflowRunSchema.parse(
deserializeRunError(compact(value))
);
return [value.runId, filterRunData(parsed, resolveData)] as const;
})
);
return ids.map((id) => runsById.get(id) ?? null);
}) as NonNullable<Storage['runs']['getMany']>,
list: createRunsList(drizzle),
experimentalSetAttributes: async (
runId: string,
changes: AttributeChange[],
options?: { allowReservedAttributes?: boolean }
): Promise<ExperimentalSetAttributesResult> => {
// Load existing attributes so the SDK-shape validator can produce
// a precise error message (cap, duplicate keys, reserved prefix,
// byte length). The authoritative cap enforcement happens inside
// the UPDATE statement below (see the `WHERE` clause), so the
// race between this read and the UPDATE cannot push the row past
// the per-run cap.
const [existing] = await drizzle
.select({ attributes: runs.attributes })
.from(runs)
.where(eq(runs.runId, runId))
.limit(1);
if (!existing) {
throw new WorkflowRunNotFoundError(runId);
}
try {
validateAttributeChanges(changes, {
existingKeys: Object.keys(existing.attributes ?? {}),