@workflow/world-postgres 5.0.0-beta.3 → 5.0.0-beta.4

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/dist/storage.js CHANGED
@@ -5,50 +5,30 @@ import { monotonicFactory } from 'ulid';
5
5
  import { Schema } from './drizzle/index.js';
6
6
  import { compact } from './util.js';
7
7
  /**
8
- * Parse legacy errorJson (text column with JSON-stringified StructuredError).
9
- * Used for backwards compatibility when reading from deprecated error column.
8
+ * Read helper for the deprecated `error` text column (legacy: JSON-stringified
9
+ * `StructuredError`). In the current event-sourced model, the `error` field on
10
+ * entities is `SerializedData` (Uint8Array) produced by the new error
11
+ * serialization pipeline; legacy text-column records pre-date that pipeline
12
+ * and cannot be hydrated back into the original thrown value.
13
+ *
14
+ * Returns `null` unconditionally so downstream consumers treat legacy errors
15
+ * as absent rather than receiving a shape that `hydrateStepError` /
16
+ * `hydrateRunError` can't process. Callers that need to inspect the raw
17
+ * legacy payload should read the `errorJson` column directly.
10
18
  */
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
- }
19
+ function parseErrorJson(_errorJson) {
20
+ return null;
30
21
  }
31
22
  /**
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).
23
+ * Pass-through helper kept for backwards compatibility with the run read path.
24
+ * In the current event-sourced model, `error` is already `SerializedData`
25
+ * (Uint8Array) on the entity, and any legacy `errorStack` / `errorCode`
26
+ * fields are no longer populated by the current write path.
35
27
  */
36
28
  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
- };
29
+ // Drop any stale legacy-only fields we might still encounter on read.
30
+ const { errorStack: _errorStack, ...rest } = run;
31
+ return rest;
52
32
  }
53
33
  /**
54
34
  * Deserialize step data, mapping DB columns to interface fields.
@@ -477,7 +457,7 @@ export function createEventsStorage(drizzle) {
477
457
  // for concurrent invocations: replay is deterministic, so letting
478
458
  // multiple callers proceed with the same run is safe. We skip
479
459
  // preloaded events here because this is a rare race-condition path
480
- // — the runtime falls back to getAllWorkflowRunEvents().
460
+ // — the runtime falls back to loadWorkflowRunEvents().
481
461
  if (currentRun?.status === 'running') {
482
462
  const [fullRun] = await drizzle
483
463
  .select()
@@ -547,18 +527,15 @@ export function createEventsStorage(drizzle) {
547
527
  // Uses conditional UPDATE to prevent failing an already-terminal run.
548
528
  if (data.eventType === 'run_failed') {
549
529
  const eventData = data.eventData;
550
- const errorMessage = typeof eventData.error === 'string'
551
- ? eventData.error
552
- : (eventData.error?.message ?? 'Unknown error');
530
+ // The error field is SerializedData (Uint8Array) produced by
531
+ // dehydrateRunError. We store it verbatim in the error_cbor column;
532
+ // consumers hydrate via hydrateRunError.
553
533
  const [runValue] = await drizzle
554
534
  .update(Schema.runs)
555
535
  .set({
556
536
  status: 'failed',
557
- error: {
558
- message: errorMessage,
559
- stack: eventData.error?.stack,
560
- code: eventData.errorCode,
561
- },
537
+ error: eventData.error,
538
+ errorCode: eventData.errorCode,
562
539
  completedAt: now,
563
540
  updatedAt: now,
564
541
  })
@@ -728,17 +705,14 @@ export function createEventsStorage(drizzle) {
728
705
  // Uses conditional UPDATE to prevent failing an already-terminal step.
729
706
  if (data.eventType === 'step_failed') {
730
707
  const eventData = data.eventData;
731
- const errorMessage = typeof eventData.error === 'string'
732
- ? eventData.error
733
- : (eventData.error?.message ?? 'Unknown error');
708
+ // The error field is SerializedData (Uint8Array) produced by
709
+ // dehydrateStepError. We store it verbatim in the error_cbor column;
710
+ // consumers hydrate via hydrateStepError.
734
711
  const [stepValue] = await drizzle
735
712
  .update(Schema.steps)
736
713
  .set({
737
714
  status: 'failed',
738
- error: {
739
- message: errorMessage,
740
- stack: eventData.stack,
741
- },
715
+ error: eventData.error,
742
716
  completedAt: now,
743
717
  })
744
718
  .where(and(eq(Schema.steps.runId, effectiveRunId), eq(Schema.steps.stepId, data.correlationId), notInArray(Schema.steps.status, terminalStepStatuses)))
@@ -764,17 +738,11 @@ export function createEventsStorage(drizzle) {
764
738
  // Uses conditional UPDATE to prevent retrying an already-terminal step.
765
739
  if (data.eventType === 'step_retrying') {
766
740
  const eventData = data.eventData;
767
- const errorMessage = typeof eventData.error === 'string'
768
- ? eventData.error
769
- : (eventData.error?.message ?? 'Unknown error');
770
741
  const [stepValue] = await drizzle
771
742
  .update(Schema.steps)
772
743
  .set({
773
744
  status: 'pending',
774
- error: {
775
- message: errorMessage,
776
- stack: eventData.stack,
777
- },
745
+ error: eventData.error,
778
746
  retryAfter: eventData.retryAfter,
779
747
  })
780
748
  .where(and(eq(Schema.steps.runId, effectiveRunId), eq(Schema.steps.stepId, data.correlationId), notInArray(Schema.steps.status, terminalStepStatuses)))
@@ -854,6 +822,7 @@ export function createEventsStorage(drizzle) {
854
822
  // Propagate specVersion from the event to the hook entity
855
823
  specVersion: effectiveSpecVersion,
856
824
  isWebhook: eventData.isWebhook,
825
+ isSystem: eventData.isSystem ?? false,
857
826
  })
858
827
  .onConflictDoNothing()
859
828
  .returning();
@@ -948,17 +917,49 @@ export function createEventsStorage(drizzle) {
948
917
  : 'eventData' in data
949
918
  ? data.eventData
950
919
  : undefined;
951
- const [value] = await drizzle
952
- .insert(events)
953
- .values({
954
- runId: effectiveRunId,
955
- eventId,
956
- correlationId: data.correlationId,
957
- eventType: data.eventType,
958
- eventData: storedEventData,
959
- specVersion: effectiveSpecVersion,
960
- })
961
- .returning({ createdAt: events.createdAt });
920
+ let value;
921
+ try {
922
+ [value] = await drizzle
923
+ .insert(events)
924
+ .values({
925
+ runId: effectiveRunId,
926
+ eventId,
927
+ correlationId: data.correlationId,
928
+ eventType: data.eventType,
929
+ eventData: storedEventData,
930
+ specVersion: effectiveSpecVersion,
931
+ })
932
+ .returning({ createdAt: events.createdAt });
933
+ }
934
+ catch (err) {
935
+ // Translate unique-violation on the entity-creation partial index
936
+ // (workflow_events_entity_creation_unique) into EntityConflictError
937
+ // so the runtime's existing dedup catch path can handle it. Without
938
+ // this, two concurrent invocations producing identical
939
+ // correlationIds (e.g. snapshot runtime deterministic ULIDs) would
940
+ // surface as unhandled DB errors instead of dedup signals.
941
+ // Drizzle wraps the underlying pg error in DrizzleQueryError; the
942
+ // pg error (with .code === '23505') lives on .cause. We additionally
943
+ // gate on the violated constraint name so other 23505 violations on
944
+ // these event types (e.g. the events primary key, or any future
945
+ // unique constraint we might add) don't get misclassified as a
946
+ // correlationId conflict.
947
+ const isEntityCreatingEvent = data.eventType === 'step_created' ||
948
+ data.eventType === 'hook_created' ||
949
+ data.eventType === 'wait_created';
950
+ const pgErr = err.code
951
+ ? err
952
+ : (err
953
+ .cause ?? {});
954
+ const pgCode = pgErr.code;
955
+ const pgConstraint = pgErr.constraint;
956
+ if (isEntityCreatingEvent &&
957
+ pgCode === '23505' &&
958
+ pgConstraint === 'workflow_events_entity_creation_unique') {
959
+ throw new EntityConflictError(`${data.eventType} for correlationId "${data.correlationId}" already exists in run "${effectiveRunId}"`);
960
+ }
961
+ throw err;
962
+ }
962
963
  if (!value) {
963
964
  throw new EntityConflictError(`Event ${eventId} could not be created`);
964
965
  }