spool-engine 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +12 -2
  3. package/dist/config.js +130 -0
  4. package/dist/config.js.map +1 -0
  5. package/dist/domain/errors.js +108 -0
  6. package/dist/domain/errors.js.map +1 -0
  7. package/dist/domain/journal.js +21 -0
  8. package/dist/domain/journal.js.map +1 -0
  9. package/dist/domain/json.js +55 -0
  10. package/dist/domain/json.js.map +1 -0
  11. package/dist/domain/llm.js +22 -0
  12. package/dist/domain/llm.js.map +1 -0
  13. package/dist/domain/retry.js +21 -0
  14. package/dist/domain/retry.js.map +1 -0
  15. package/dist/domain/run-status.js +40 -0
  16. package/dist/domain/run-status.js.map +1 -0
  17. package/dist/domain/sleep.js +7 -0
  18. package/dist/domain/sleep.js.map +1 -0
  19. package/dist/engine.js +131 -0
  20. package/dist/engine.js.map +1 -0
  21. package/dist/loops/every.js +32 -0
  22. package/dist/loops/every.js.map +1 -0
  23. package/dist/loops/listener.js +58 -0
  24. package/dist/loops/listener.js.map +1 -0
  25. package/dist/loops/live-runs.js +30 -0
  26. package/dist/loops/live-runs.js.map +1 -0
  27. package/dist/loops/queue-depth.js +28 -0
  28. package/dist/loops/queue-depth.js.map +1 -0
  29. package/dist/loops/reaper.js +71 -0
  30. package/dist/loops/reaper.js.map +1 -0
  31. package/dist/loops/waker.js +42 -0
  32. package/dist/loops/waker.js.map +1 -0
  33. package/dist/main.js +48 -0
  34. package/dist/main.js.map +1 -0
  35. package/dist/observability/logger.js +9 -0
  36. package/dist/observability/logger.js.map +1 -0
  37. package/dist/observability/metrics.js +97 -0
  38. package/dist/observability/metrics.js.map +1 -0
  39. package/dist/observability/tracing.js +146 -0
  40. package/dist/observability/tracing.js.map +1 -0
  41. package/dist/proto/limits_pb.d.ts +212 -0
  42. package/dist/proto/limits_pb.js +76 -0
  43. package/dist/proto/runs_pb.d.ts +740 -0
  44. package/dist/proto/runs_pb.js +147 -0
  45. package/dist/proto/workers_pb.d.ts +900 -0
  46. package/dist/proto/workers_pb.js +168 -0
  47. package/dist/services/admission.js +47 -0
  48. package/dist/services/admission.js.map +1 -0
  49. package/dist/services/cancel-run.js +43 -0
  50. package/dist/services/cancel-run.js.map +1 -0
  51. package/dist/services/claim-tasks.js +59 -0
  52. package/dist/services/claim-tasks.js.map +1 -0
  53. package/dist/services/complete-task.js +45 -0
  54. package/dist/services/complete-task.js.map +1 -0
  55. package/dist/services/fail-step.js +102 -0
  56. package/dist/services/fail-step.js.map +1 -0
  57. package/dist/services/group-commit.js +83 -0
  58. package/dist/services/group-commit.js.map +1 -0
  59. package/dist/services/live-tokens.js +90 -0
  60. package/dist/services/live-tokens.js.map +1 -0
  61. package/dist/services/next-step.js +33 -0
  62. package/dist/services/next-step.js.map +1 -0
  63. package/dist/services/notifier.js +54 -0
  64. package/dist/services/notifier.js.map +1 -0
  65. package/dist/services/query-runs.js +14 -0
  66. package/dist/services/query-runs.js.map +1 -0
  67. package/dist/services/replay-run.js +63 -0
  68. package/dist/services/replay-run.js.map +1 -0
  69. package/dist/services/report-step.js +129 -0
  70. package/dist/services/report-step.js.map +1 -0
  71. package/dist/services/run-watches.js +46 -0
  72. package/dist/services/run-watches.js.map +1 -0
  73. package/dist/services/send-event.js +16 -0
  74. package/dist/services/send-event.js.map +1 -0
  75. package/dist/services/sleep-run.js +47 -0
  76. package/dist/services/sleep-run.js.map +1 -0
  77. package/dist/services/throttle-step.js +76 -0
  78. package/dist/services/throttle-step.js.map +1 -0
  79. package/dist/services/trigger-run.js +38 -0
  80. package/dist/services/trigger-run.js.map +1 -0
  81. package/dist/services/wait-for-event.js +73 -0
  82. package/dist/services/wait-for-event.js.map +1 -0
  83. package/dist/services/wakeups.js +70 -0
  84. package/dist/services/wakeups.js.map +1 -0
  85. package/dist/services/watch-run.js +36 -0
  86. package/dist/services/watch-run.js.map +1 -0
  87. package/dist/services/worker-session.js +198 -0
  88. package/dist/services/worker-session.js.map +1 -0
  89. package/dist/store/errors.js +42 -0
  90. package/dist/store/errors.js.map +1 -0
  91. package/dist/store/events.js +96 -0
  92. package/dist/store/events.js.map +1 -0
  93. package/dist/store/idempotency.js +29 -0
  94. package/dist/store/idempotency.js.map +1 -0
  95. package/dist/store/json.js +9 -0
  96. package/dist/store/json.js.map +1 -0
  97. package/dist/store/limits.js +60 -0
  98. package/dist/store/limits.js.map +1 -0
  99. package/dist/store/migrate.js +20 -0
  100. package/dist/store/migrate.js.map +1 -0
  101. package/dist/store/run-views.js +96 -0
  102. package/dist/store/run-views.js.map +1 -0
  103. package/dist/store/runs.js +104 -0
  104. package/dist/store/runs.js.map +1 -0
  105. package/dist/store/schema.js +191 -0
  106. package/dist/store/schema.js.map +1 -0
  107. package/dist/store/steps.js +114 -0
  108. package/dist/store/steps.js.map +1 -0
  109. package/dist/store/tasks.js +463 -0
  110. package/dist/store/tasks.js.map +1 -0
  111. package/dist/store/transaction.js +23 -0
  112. package/dist/store/transaction.js.map +1 -0
  113. package/dist/store/waits.js +75 -0
  114. package/dist/store/waits.js.map +1 -0
  115. package/dist/store/watches.js +31 -0
  116. package/dist/store/watches.js.map +1 -0
  117. package/dist/transport/auth.js +26 -0
  118. package/dist/transport/auth.js.map +1 -0
  119. package/dist/transport/channel.js +46 -0
  120. package/dist/transport/channel.js.map +1 -0
  121. package/dist/transport/errors.js +74 -0
  122. package/dist/transport/errors.js.map +1 -0
  123. package/dist/transport/limits-service.js +60 -0
  124. package/dist/transport/limits-service.js.map +1 -0
  125. package/dist/transport/protocol.js +14 -0
  126. package/dist/transport/protocol.js.map +1 -0
  127. package/dist/transport/run-events.js +133 -0
  128. package/dist/transport/run-events.js.map +1 -0
  129. package/dist/transport/run-messages.js +78 -0
  130. package/dist/transport/run-messages.js.map +1 -0
  131. package/dist/transport/run-service.js +147 -0
  132. package/dist/transport/run-service.js.map +1 -0
  133. package/dist/transport/server.js +227 -0
  134. package/dist/transport/server.js.map +1 -0
  135. package/dist/transport/validation.js +61 -0
  136. package/dist/transport/validation.js.map +1 -0
  137. package/dist/transport/worker-service.js +396 -0
  138. package/dist/transport/worker-service.js.map +1 -0
  139. package/drizzle/0000_init.sql +95 -0
  140. package/drizzle/0001_tasks_storage.sql +2 -0
  141. package/drizzle/0002_waits_route.sql +3 -0
  142. package/drizzle/0003_event_waits.sql +8 -0
  143. package/drizzle/0004_llm_steps.sql +2 -0
  144. package/drizzle/0005_tasks_notify.sql +19 -0
  145. package/drizzle/0006_drop_tasks_notify.sql +8 -0
  146. package/drizzle/0007_tasks_fair.sql +5 -0
  147. package/drizzle/0008_concurrency_limits.sql +8 -0
  148. package/drizzle/0009_rate_limits.sql +12 -0
  149. package/drizzle/0010_run_listings.sql +2 -0
  150. package/drizzle/0011_run_replays.sql +7 -0
  151. package/drizzle/0012_run_watches.sql +8 -0
  152. package/drizzle/meta/0000_snapshot.json +668 -0
  153. package/drizzle/meta/0001_snapshot.json +668 -0
  154. package/drizzle/meta/0002_snapshot.json +680 -0
  155. package/drizzle/meta/0003_snapshot.json +723 -0
  156. package/drizzle/meta/0004_snapshot.json +733 -0
  157. package/drizzle/meta/0005_snapshot.json +733 -0
  158. package/drizzle/meta/0006_snapshot.json +733 -0
  159. package/drizzle/meta/0007_snapshot.json +739 -0
  160. package/drizzle/meta/0008_snapshot.json +791 -0
  161. package/drizzle/meta/0009_snapshot.json +843 -0
  162. package/drizzle/meta/0010_snapshot.json +881 -0
  163. package/drizzle/meta/0011_snapshot.json +903 -0
  164. package/drizzle/meta/0012_snapshot.json +958 -0
  165. package/drizzle/meta/_journal.json +97 -0
  166. package/package.json +58 -3
@@ -0,0 +1,38 @@
1
+ import { IdempotencyConflictError } from "../domain/errors.js";
2
+ import { claimIdempotencyKey } from "../store/idempotency.js";
3
+ import { insertRun } from "../store/runs.js";
4
+ import { insertTask } from "../store/tasks.js";
5
+ import { withTransaction } from "../store/transaction.js";
6
+ /** Creates a run and its first task, or returns the run an idempotency key already holds. */
7
+ export async function triggerRun(sql, command) {
8
+ const { tenantId, workflow, queue, input, idempotencyKey, concurrencyKey } = command;
9
+ return withTransaction(sql, async (tx) => {
10
+ let reservedId;
11
+ if (idempotencyKey !== undefined) {
12
+ const claim = await claimIdempotencyKey(tx, {
13
+ tenantId,
14
+ workflow,
15
+ key: idempotencyKey,
16
+ input,
17
+ });
18
+ if (claim.kind === "existing") {
19
+ if (!claim.sameInput)
20
+ throw new IdempotencyConflictError();
21
+ return { runId: claim.runId, created: false };
22
+ }
23
+ reservedId = claim.runId;
24
+ }
25
+ const runId = await insertRun(tx, {
26
+ id: reservedId,
27
+ tenantId,
28
+ workflow,
29
+ input,
30
+ idempotencyKey,
31
+ concurrencyKey,
32
+ queue,
33
+ });
34
+ await insertTask(tx, { runId, queue, tenantId, workflow, concurrencyKey });
35
+ return { runId, created: true };
36
+ });
37
+ }
38
+ //# sourceMappingURL=trigger-run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trigger-run.js","sourceRoot":"","sources":["../../src/services/trigger-run.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAE/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAkB1D,6FAA6F;AAC7F,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,GAAQ,EAAE,OAA0B;IACnE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC;IAErF,OAAO,eAAe,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QACvC,IAAI,UAA8B,CAAC;QACnC,IAAI,cAAc,KAAK,SAAS,EAAE,CAAC;YACjC,MAAM,KAAK,GAAG,MAAM,mBAAmB,CAAC,EAAE,EAAE;gBAC1C,QAAQ;gBACR,QAAQ;gBACR,GAAG,EAAE,cAAc;gBACnB,KAAK;aACN,CAAC,CAAC;YACH,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;gBAC9B,IAAI,CAAC,KAAK,CAAC,SAAS;oBAAE,MAAM,IAAI,wBAAwB,EAAE,CAAC;gBAC3D,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;YAChD,CAAC;YACD,UAAU,GAAG,KAAK,CAAC,KAAK,CAAC;QAC3B,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,EAAE,EAAE;YAChC,EAAE,EAAE,UAAU;YACd,QAAQ;YACR,QAAQ;YACR,KAAK;YACL,cAAc;YACd,cAAc;YACd,KAAK;SACN,CAAC,CAAC;QACH,MAAM,UAAU,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC,CAAC;QAC3E,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAClC,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,73 @@
1
+ import { LeaseLostError } from "../domain/errors.js";
2
+ import { findUndeliveredEvent, insertDelivery, lockEventName } from "../store/events.js";
3
+ import { markRunParked, markRunRunning } from "../store/runs.js";
4
+ import { insertStep } from "../store/steps.js";
5
+ import { deleteTask, recordProgress, rescheduleTask } from "../store/tasks.js";
6
+ import { withTransaction } from "../store/transaction.js";
7
+ import { insertEventWait } from "../store/waits.js";
8
+ import { lockForNextStep } from "./next-step.js";
9
+ /**
10
+ * Starts a wait for an event (F9), in one transaction (invariant 3). Fences the lease and
11
+ * takes the event name's lock, so an event sent at the same moment is either seen here or
12
+ * sees this wait. If a matching event arrived since the run started and the run has
13
+ * not taken it, the wait's step is recorded with it and the task goes straight back to the
14
+ * queue; otherwise the task is given up and the run waits until an event or the timeout
15
+ * ends the wait. Either way the worker stops the run and the next attempt replays the step.
16
+ *
17
+ * Not idempotent, like a sleep: the first copy releases the task, so a resent copy gets
18
+ * LEASE_LOST.
19
+ */
20
+ export async function waitForEvent(deps, command) {
21
+ try {
22
+ const { outcome, locked } = await withTransaction(deps.sql, async (tx) => {
23
+ const locked = await lockForNextStep(tx, command);
24
+ const { runId, tenantId } = locked;
25
+ await lockEventName(tx, tenantId, command.eventName);
26
+ const early = await findUndeliveredEvent(tx, {
27
+ runId,
28
+ tenantId,
29
+ name: command.eventName,
30
+ match: command.match,
31
+ });
32
+ if (early !== undefined) {
33
+ await insertDelivery(tx, runId, early.id);
34
+ await insertStep(tx, {
35
+ runId,
36
+ kind: "wait_event",
37
+ seq: command.seq,
38
+ name: command.name,
39
+ output: early.payload,
40
+ durationMs: 0,
41
+ });
42
+ await markRunRunning(tx, runId);
43
+ // Progress resets the retry counts; then the task is free for the next claim.
44
+ await recordProgress(tx, command.taskId, deps.leaseMs);
45
+ await rescheduleTask(tx, command.taskId, 0, 0);
46
+ return { outcome: "received", locked };
47
+ }
48
+ await deleteTask(tx, command.taskId);
49
+ await insertEventWait(tx, {
50
+ ...locked,
51
+ seq: command.seq,
52
+ stepName: command.name,
53
+ eventName: command.eventName,
54
+ match: command.match,
55
+ timeoutMs: command.timeoutMs,
56
+ });
57
+ if (!(await markRunParked(tx, runId, "waiting"))) {
58
+ throw new Error(`run ${runId} has a task but cannot move to waiting`);
59
+ }
60
+ return { outcome: "waiting", locked };
61
+ });
62
+ // Either way the lease ended: the task went back to the queue or away.
63
+ if (locked.concurrencyKey !== null)
64
+ deps.slotFreed?.(locked.queue);
65
+ return outcome;
66
+ }
67
+ catch (error) {
68
+ if (error instanceof LeaseLostError)
69
+ deps.metrics.fencedCompletions.inc();
70
+ throw error;
71
+ }
72
+ }
73
+ //# sourceMappingURL=wait-for-event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wait-for-event.js","sourceRoot":"","sources":["../../src/services/wait-for-event.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACzF,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AA8BjD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,IAAsB,EACtB,OAA4B;IAE5B,IAAI,CAAC;QACH,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;YACvE,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;YAClD,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;YACnC,MAAM,aAAa,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;YAErD,MAAM,KAAK,GAAG,MAAM,oBAAoB,CAAC,EAAE,EAAE;gBAC3C,KAAK;gBACL,QAAQ;gBACR,IAAI,EAAE,OAAO,CAAC,SAAS;gBACvB,KAAK,EAAE,OAAO,CAAC,KAAK;aACrB,CAAC,CAAC;YACH,IAAI,KAAK,KAAK,SAAS,E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;QACH,uEAAuE;QACvE,IAAI,MAAM,CAAC,cAAc,KAAK,IAAI;YAAE,IAAI,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnE,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,cAAc;YAAE,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,GAAG,EAAE,CAAC;QAC1E,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Where an engine's idle worker streams wait for work. A notification for a queue,
3
+ * from Postgres LISTEN, wakes the stream on that queue that has waited longest, and only
4
+ * that one: waking every idle stream would send them all to claim the same task, and all
5
+ * but one would find nothing. A stream that claims a full batch passes the wake on, so a
6
+ * burst still spreads. Every wait also ends after the poll interval, so a missed
7
+ * notification costs at most one interval, never a stuck task. Holds no state Postgres
8
+ * lacks: losing it loses only wake-ups (invariant 5).
9
+ */
10
+ export class Wakeups {
11
+ #waiting = new Map();
12
+ /**
13
+ * Waits for a notification on `queue`, for at most `timeoutMs`, or until `signal`
14
+ * aborts. Resolves true when woken by a notification, false otherwise.
15
+ */
16
+ wait(queue, timeoutMs, signal) {
17
+ return new Promise((resolve) => {
18
+ let waiters = this.#waiting.get(queue);
19
+ if (waiters === undefined) {
20
+ waiters = new Set();
21
+ this.#waiting.set(queue, waiters);
22
+ }
23
+ const queueWaiters = waiters;
24
+ const finish = (woken) => {
25
+ clearTimeout(timer);
26
+ signal.removeEventListener("abort", aborted);
27
+ queueWaiters.delete(waiter);
28
+ if (queueWaiters.size === 0 && this.#waiting.get(queue) === queueWaiters) {
29
+ this.#waiting.delete(queue);
30
+ }
31
+ resolve(woken);
32
+ };
33
+ const waiter = {
34
+ wake: () => {
35
+ finish(true);
36
+ },
37
+ };
38
+ const aborted = () => {
39
+ finish(false);
40
+ };
41
+ const timer = setTimeout(() => {
42
+ finish(false);
43
+ }, timeoutMs);
44
+ if (signal.aborted) {
45
+ finish(false);
46
+ return;
47
+ }
48
+ signal.addEventListener("abort", aborted, { once: true });
49
+ queueWaiters.add(waiter);
50
+ });
51
+ }
52
+ /** Wakes the longest-waiting stream on `queue`; false if none was waiting. */
53
+ notify(queue) {
54
+ const waiters = this.#waiting.get(queue);
55
+ // A Set iterates in insertion order: the first is the one that has waited longest.
56
+ const first = waiters?.values().next();
57
+ if (first === undefined || first.done === true)
58
+ return false;
59
+ first.value.wake();
60
+ return true;
61
+ }
62
+ /** Wakes every waiting stream: after notifications may have been missed (a reconnect). */
63
+ notifyAll() {
64
+ for (const waiters of [...this.#waiting.values()]) {
65
+ for (const waiter of [...waiters])
66
+ waiter.wake();
67
+ }
68
+ }
69
+ }
70
+ //# sourceMappingURL=wakeups.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wakeups.js","sourceRoot":"","sources":["../../src/services/wakeups.ts"],"names":[],"mappings":"AAIA;;;;;;;;GAQG;AACH,MAAM,OAAO,OAAO;IACT,QAAQ,GAAG,IAAI,GAAG,EAAuB,CAAC;IAEnD;;;OAGG;IACH,IAAI,CAAC,KAAa,EAAE,SAAiB,EAAE,MAAmB;QACxD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC7B,IAAI,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YACvC,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;gBAC1B,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC;gBACpB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YACpC,CAAC;YACD,MAAM,YAAY,GAAG,OAAO,CAAC;YAC7B,MAAM,MAAM,GAAG,CAAC,KAAc,EAAE,EAAE;gBAChC,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAA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AAK,CAAC,IAAI,EAAE,CAAC;QACnB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0FAA0F;IAC1F,SAAS;QACP,KAAK,MAAM,OAAO,IAAI,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;YAClD,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,OAAO,CAAC;gBAAE,MAAM,CAAC,IAAI,EAAE,CAAC;QACnD,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,36 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { RunNotFoundError } from "../domain/errors.js";
3
+ import { isTerminal } from "../domain/run-status.js";
4
+ import { getRunDetail, runFingerprint } from "../store/run-views.js";
5
+ /**
6
+ * The run as it is now, then again each time it changes, until it finishes (F15): the
7
+ * last snapshot yielded is the finished run. Polls a fingerprint of the run and reads it
8
+ * whole only when the fingerprint changed, so a quiet run costs one small query per
9
+ * interval per watcher, on any engine, whichever engine runs its steps. Throws
10
+ * RunNotFoundError when there is no such run; returns early when `signal` aborts.
11
+ */
12
+ export async function* watchRun(sql, runId, options) {
13
+ let seen;
14
+ while (!options.signal.aborted) {
15
+ const fingerprint = await runFingerprint(sql, runId);
16
+ if (fingerprint === undefined)
17
+ throw new RunNotFoundError();
18
+ if (fingerprint !== seen) {
19
+ const run = await getRunDetail(sql, runId);
20
+ if (run === undefined)
21
+ throw new RunNotFoundError();
22
+ // The snapshot may be newer than the fingerprint; the next look settles on it.
23
+ seen = fingerprint;
24
+ yield run;
25
+ if (isTerminal(run.status))
26
+ return;
27
+ }
28
+ try {
29
+ await delay(options.intervalMs, undefined, { signal: options.signal });
30
+ }
31
+ catch {
32
+ return;
33
+ }
34
+ }
35
+ }
36
+ //# sourceMappingURL=watch-run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch-run.js","sourceRoot":"","sources":["../../src/services/watch-run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAkB,MAAM,uBAAuB,CAAC;AASrF;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,QAAQ,CAC7B,GAAQ,EACR,KAAa,EACb,OAAqB;IAErB,IAAI,IAAwB,CAAC;IAC7B,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAC/B,MAAM,WAAW,GAAG,MAAM,cAAc,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACrD,IAAI,WAAW,KAAK,SAAS;YAAE,MAAM,IAAI,gBAAgB,EAAE,CAAC;QAC5D,IAAI,WAAW,KAAK,IAAI,EAAE,CAAC;YACzB,MAAM,GAAG,GAAG,MAAM,YAAY,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YAC3C,IAAI,GAAG,KAAK,SAAS;gBAAE,MAAM,IAAI,gBAAgB,EAAE,CAAC;YACpD,+EAA+E;YAC/E,IAAI,GAAG,WAAW,CAAC;YACnB,MAAM,GAAG,CAAC;YACV,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC;gBAAE,OAAO;QACrC,CAAC;QACD,IAAI,CAAC;YACH,MAAM,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QACzE,CAAC;QAAC,MAAM,CAAC;YACP,OAAO;QACT,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -0,0 +1,198 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { DatabaseUnavailableError, InvalidArgumentError } from "../domain/errors.js";
3
+ import { isDatabaseUnavailable } from "../store/errors.js";
4
+ import { MAX_CLAIM_BATCH, renewLeases } from "../store/tasks.js";
5
+ import { claimTasksForWorker, } from "./claim-tasks.js";
6
+ import { completeTask } from "./complete-task.js";
7
+ import { failStep } from "./fail-step.js";
8
+ import { sleepRun } from "./sleep-run.js";
9
+ import { throttleStep } from "./throttle-step.js";
10
+ import { waitForEvent } from "./wait-for-event.js";
11
+ /** Most tasks a worker may have asked for and not yet received. */
12
+ export const MAX_OUTSTANDING_PULL = MAX_CLAIM_BATCH;
13
+ /**
14
+ * One connected worker. Holds only what the stream itself needs (how many tasks the
15
+ * worker asked for); every lease and result lives in Postgres, so the session can vanish
16
+ * at any moment and the worker can carry on through another engine (invariant 5).
17
+ */
18
+ export class WorkerSession {
19
+ deps;
20
+ identity;
21
+ #wanted;
22
+ /**
23
+ * The tasks delivered on this stream lately, by task id, with their run and attempt: live
24
+ * tokens are accepted only for one of them. Bounded by keeping the latest
25
+ * deliveries; a worker runs at most MAX_OUTSTANDING_PULL tasks at once, so this keeps
26
+ * every task it can still be running.
27
+ */
28
+ #delivered = new Map();
29
+ #pulled;
30
+ constructor(deps, identity, initialPull) {
31
+ this.deps = deps;
32
+ this.identity = identity;
33
+ this.#wanted = 0;
34
+ if (initialPull > 0)
35
+ this.pull(initialPull);
36
+ }
37
+ /** Tasks asked for and not yet delivered. */
38
+ get wanted() {
39
+ return this.#wanted;
40
+ }
41
+ /** The worker freed `count` more slots. */
42
+ pull(count) {
43
+ if (!Number.isInteger(count) || count < 1) {
44
+ throw new InvalidArgumentError("pull count must be a positive integer");
45
+ }
46
+ if (this.#wanted + count > MAX_OUTSTANDING_PULL) {
47
+ throw new InvalidArgumentError(`at most ${String(MAX_OUTSTANDING_PULL)} tasks may be pulled and not yet received`);
48
+ }
49
+ this.#wanted += count;
50
+ this.#pulled?.();
51
+ }
52
+ /**
53
+ * Claims tasks while the worker has asked for them and hands each to `deliver`, until
54
+ * `signal` aborts. Never claims more than the worker asked for (invariant 9). Tasks
55
+ * claimed by a claim already in flight when the signal aborts are still delivered, so
56
+ * nothing is leased that the worker did not receive while the stream is open.
57
+ */
58
+ async dispatch(signal, deliver) {
59
+ const { sql, logger, leaseMs, pollIntervalMs, wakeups, turns, metrics } = this.deps;
60
+ const { queue } = this.identity;
61
+ while (!signal.aborted) {
62
+ if (this.#wanted === 0) {
63
+ await this.#untilPulled(signal);
64
+ continue;
65
+ }
66
+ let claim;
67
+ const asked = this.#wanted;
68
+ const endClaimTimer = metrics.claimDuration.startTimer();
69
+ try {
70
+ claim = await claimTasksForWorker(sql, { ...this.identity, maxTasks: asked, after: turns.after(queue) }, leaseMs);
71
+ endClaimTimer();
72
+ }
73
+ catch (error) {
74
+ if (isDatabaseUnavailable(error))
75
+ logger.warn({ err: error }, "claim failed: database unavailable");
76
+ else
77
+ logger.error({ err: error }, "claim failed");
78
+ await pause(pollIntervalMs, signal);
79
+ continue;
80
+ }
81
+ turns.advance(queue, claim.lastTenant);
82
+ const { tasks } = claim;
83
+ for (const task of tasks) {
84
+ this.#wanted--;
85
+ // A clamp: run_after and the claim share the database clock, but a task made due
86
+ // by the claim's own statement time can read a hair negative.
87
+ metrics.scheduleLag.observe({ queue }, Math.max(0, task.waitedMs) / 1000);
88
+ const log = { runId: task.runId, taskId: task.taskId, attempt: task.attempt };
89
+ if (deliver(task)) {
90
+ this.#remember(task);
91
+ logger.debug({ ...log, workerId: this.identity.workerId }, "task sent");
92
+ }
93
+ // The stream closed under us: the lease expires and another worker gets the task.
94
+ else
95
+ logger.info(log, "claimed task could not be sent; its lease will expire");
96
+ }
97
+ // A full claim may have left more behind: pass the wake on to another idle stream.
98
+ if (tasks.length === asked)
99
+ wakeups.notify(queue);
100
+ // Nothing to claim from any tenant: wait for a notification that work arrived, or the
101
+ // poll interval. An empty claim that left tenants unseen goes on to the next ones.
102
+ if (tasks.length === 0 && claim.sawEveryTenant) {
103
+ await wakeups.wait(queue, pollIntervalMs, signal);
104
+ }
105
+ }
106
+ }
107
+ #remember(task) {
108
+ this.#delivered.delete(task.taskId);
109
+ this.#delivered.set(task.taskId, { runId: task.runId, attempt: task.attempt });
110
+ if (this.#delivered.size > 2 * MAX_OUTSTANDING_PULL) {
111
+ const oldest = this.#delivered.keys().next();
112
+ if (oldest.done !== true)
113
+ this.#delivered.delete(oldest.value);
114
+ }
115
+ }
116
+ /**
117
+ * Passes a model call's text on to the run's live viewers, if any. Dropped when this
118
+ * stream was not given the task at that attempt; no database work either way.
119
+ */
120
+ liveTokens(tokens) {
121
+ const held = this.#delivered.get(tokens.taskId);
122
+ if (held?.attempt !== tokens.attempt)
123
+ return;
124
+ this.deps.relay?.forward({ runId: held.runId, seq: tokens.seq, text: tokens.text });
125
+ }
126
+ reportStep(report) {
127
+ return this.deps.stepReports.submit({ ...report, workerId: this.identity.workerId });
128
+ }
129
+ failStep(failure) {
130
+ return failStep(this.#leaseEnding, { ...failure, workerId: this.identity.workerId });
131
+ }
132
+ sleep(request) {
133
+ return sleepRun(this.#leaseEnding, { ...request, workerId: this.identity.workerId });
134
+ }
135
+ /** Takes a rate limit's token before a step; a wait over 0 means the run parked. */
136
+ throttle(request) {
137
+ return throttleStep(this.#leaseEnding, { ...request, workerId: this.identity.workerId });
138
+ }
139
+ async waitForEvent(request) {
140
+ const outcome = await waitForEvent(this.#leaseEnding, {
141
+ ...request,
142
+ workerId: this.identity.workerId,
143
+ });
144
+ // The event had arrived: the run's task is back in the queue, claimable now.
145
+ if (outcome === "received")
146
+ this.deps.notifier.claimable(this.identity.queue);
147
+ return outcome;
148
+ }
149
+ async complete(completion) {
150
+ await completeTask(this.#leaseEnding, { ...completion, workerId: this.identity.workerId });
151
+ }
152
+ /**
153
+ * The dependencies of the calls that end a lease: a lease ending on a run with a
154
+ * concurrency key frees a slot under its limit, which can make that queue claimable.
155
+ */
156
+ get #leaseEnding() {
157
+ return {
158
+ ...this.deps,
159
+ slotFreed: (queue) => {
160
+ this.deps.notifier.claimable(queue);
161
+ },
162
+ };
163
+ }
164
+ /** Renews the leases this worker still holds; returns the ones it no longer holds. */
165
+ async heartbeat(leases) {
166
+ let renewed;
167
+ try {
168
+ renewed = new Set(await renewLeases(this.deps.sql, this.identity.workerId, leases, this.deps.leaseMs));
169
+ }
170
+ catch (error) {
171
+ if (isDatabaseUnavailable(error))
172
+ throw new DatabaseUnavailableError({ cause: error });
173
+ throw error;
174
+ }
175
+ return leases.filter((lease) => !renewed.has(lease.taskId));
176
+ }
177
+ #untilPulled(signal) {
178
+ return new Promise((resolve) => {
179
+ const done = () => {
180
+ signal.removeEventListener("abort", done);
181
+ this.#pulled = undefined;
182
+ resolve();
183
+ };
184
+ this.#pulled = done;
185
+ signal.addEventListener("abort", done, { once: true });
186
+ });
187
+ }
188
+ }
189
+ /** Waits, returning early (without throwing) when the signal aborts. */
190
+ async function pause(ms, signal) {
191
+ try {
192
+ await delay(ms, undefined, { signal });
193
+ }
194
+ catch {
195
+ // Aborted: the caller's loop checks the signal.
196
+ }
197
+ }
198
+ //# sourceMappingURL=worker-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-session.js","sourceRoot":"","sources":["../../src/services/worker-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAKrF,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EACL,mBAAmB,GAIpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,QAAQ,EAAwB,MAAM,gBAAgB,CAAC;AAIhE,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAwB,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAAE,YAAY,EAAoB,MAAM,qBAAqB,CAAC;AAKrE,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,MAAM,IAAI,wBAAwB,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YACvF,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IAC9D,CAAC;IAED,YAAY,CAAC,MAAmB;QAC9B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC7B,MAAM,IAAI,GAAG,GAAG,EAAE;gBAChB,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC1C,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;gBACzB,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC;YACF,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;YACpB,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACzD,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED,wEAAwE;AACxE,KAAK,UAAU,KAAK,CAAC,EAAU,EAAE,MAAmB;IAClD,IAAI,CAAC;QACH,MAAM,KAAK,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IACzC,CAAC;IAAC,MAAM,CAAC;QACP,gDAAgD;IAClD,CAAC;AACH,CAAC"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Codes for a lost or refused database connection: SQLSTATE classes 08 (connection
3
+ * exception) and 57P (operator intervention, such as a restart or terminated backend),
4
+ * plus the driver's and the socket's own codes. Constraint violations and other errors
5
+ * are deliberately absent: retrying them cannot help.
6
+ */
7
+ const UNAVAILABLE_CODES = new Set([
8
+ "08000",
9
+ "08001",
10
+ "08003",
11
+ "08004",
12
+ "08006",
13
+ "57P01",
14
+ "57P02",
15
+ "57P03",
16
+ "CONNECTION_CLOSED",
17
+ "CONNECTION_ENDED",
18
+ "CONNECTION_DESTROYED",
19
+ "CONNECT_TIMEOUT",
20
+ "ECONNREFUSED",
21
+ "ECONNRESET",
22
+ "EPIPE",
23
+ "ETIMEDOUT",
24
+ ]);
25
+ /**
26
+ * Postgres aborted the transaction because of a conflict with another one (deadlock
27
+ * detected, or a serialization failure): the same transaction can succeed if run again.
28
+ */
29
+ const CONFLICT_CODES = new Set(["40P01", "40001"]);
30
+ export function isTransactionConflict(error) {
31
+ return (error instanceof Error &&
32
+ "code" in error &&
33
+ typeof error.code === "string" &&
34
+ CONFLICT_CODES.has(error.code));
35
+ }
36
+ export function isDatabaseUnavailable(error) {
37
+ return (error instanceof Error &&
38
+ "code" in error &&
39
+ typeof error.code === "string" &&
40
+ UNAVAILABLE_CODES.has(error.code));
41
+ }
42
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/store/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC;IAChC,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,mBAAmB;IACnB,kBAAkB;IAClB,sBAAsB;IACtB,iBAAiB;IACjB,cAAc;IACd,YAAY;IACZ,OAAO;IACP,WAAW;CACZ,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;AAEnD,MAAM,UAAU,qBAAqB,CAAC,KAAc;IAClD,OAAO,CACL,KAAK,YAAY,KAAK;QACtB,MAAM,IAAI,KAAK;QACf,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,cAAc,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAC/B,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAAc;IAClD,OAAO,CACL,KAAK,YAAY,KAAK;QACtB,MAAM,IAAI,KAAK;QACf,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,iBAAiB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAClC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,96 @@
1
+ import { statusesThatCanBecome } from "../domain/run-status.js";
2
+ import { jsonb } from "./json.js";
3
+ /**
4
+ * Namespace of the per-event-name advisory locks, in the two-integer lock space, which
5
+ * never overlaps the single-bigint space the migration lock uses.
6
+ */
7
+ const EVENT_LOCK_NAMESPACE = 7_365_002;
8
+ /**
9
+ * Serialises the transactions that send an event of this name and that start waiting for
10
+ * one, for one tenant, until the transaction ends. Without it the two can commit side by
11
+ * side, each blind to the other (the wait finds no event, the event finds no wait), and
12
+ * the event is missed until the wait times out. Different names may share a lock (a hash
13
+ * collision), which only serialises them.
14
+ */
15
+ export async function lockEventName(tx, tenantId, name) {
16
+ await tx `
17
+ SELECT pg_advisory_xact_lock(${EVENT_LOCK_NAMESPACE}, hashtext(${tenantId} || chr(1) || ${name}))`;
18
+ }
19
+ /** Keeps an event, so a run that starts waiting for it later still receives it. */
20
+ export async function insertEvent(tx, event) {
21
+ const [row] = await tx `
22
+ INSERT INTO events (tenant_id, name, payload)
23
+ VALUES (${event.tenantId}, ${event.name}, ${jsonb(event.payload)}::text::jsonb)
24
+ RETURNING id::text AS id`;
25
+ if (row === undefined)
26
+ throw new Error("INSERT ... RETURNING returned no row");
27
+ return row.id;
28
+ }
29
+ /**
30
+ * The oldest event a run may still take for a wait: of this name and tenant, containing
31
+ * `match`, received since the run was created, and not already delivered to it.
32
+ *
33
+ * Plan: Index Scan on events_lookup (tenant_id, name, created_at >= the run's creation) in
34
+ * id order, the containment and the delivery anti-join as filters.
35
+ */
36
+ export async function findUndeliveredEvent(tx, query) {
37
+ const [row] = await tx `
38
+ SELECT e.id::text AS id, e.payload
39
+ FROM events e
40
+ WHERE e.tenant_id = ${query.tenantId}
41
+ AND e.name = ${query.name}
42
+ AND e.created_at >= (SELECT created_at FROM runs WHERE id = ${query.runId})
43
+ AND e.payload @> ${jsonb(query.match)}::text::jsonb
44
+ AND NOT EXISTS (
45
+ SELECT 1 FROM event_deliveries d WHERE d.run_id = ${query.runId} AND d.event_id = e.id)
46
+ ORDER BY e.id
47
+ LIMIT 1`;
48
+ return row;
49
+ }
50
+ /** Records that a run took an event; the primary key refuses a second delivery. */
51
+ export async function insertDelivery(tx, runId, eventId) {
52
+ await tx `INSERT INTO event_deliveries (run_id, event_id) VALUES (${runId}, ${eventId}::bigint)`;
53
+ }
54
+ /**
55
+ * Ends every wait the event matches, in one statement: removes the waits, records each
56
+ * wait's step with the event's payload as its output, notes the delivery, moves the runs
57
+ * back to queued and gives each a task. A wait is ended once: the DELETE decides, so a
58
+ * timeout or another event racing for the same wait finds it gone. Returns the resumed
59
+ * run ids.
60
+ *
61
+ * Plan: Index Scan on waits_event (tenant_id, event_name) with the containment as a
62
+ * filter, then primary-key work per matched wait.
63
+ */
64
+ export async function resolveWaits(tx, event) {
65
+ const payload = jsonb(event.payload);
66
+ const rows = await tx `
67
+ WITH matched AS (
68
+ DELETE FROM waits
69
+ WHERE kind = 'event' AND tenant_id = ${event.tenantId} AND event_name = ${event.name}
70
+ AND ${payload}::text::jsonb @> match
71
+ RETURNING run_id, seq, step_name, tenant_id, queue, workflow
72
+ ),
73
+ requeued AS (
74
+ UPDATE runs r
75
+ SET status = 'queued', updated_at = now()
76
+ FROM matched m
77
+ WHERE r.id = m.run_id AND r.status = ANY(${statusesThatCanBecome("queued")}::text[])
78
+ RETURNING r.id, r.concurrency_key
79
+ ),
80
+ delivered AS (
81
+ INSERT INTO event_deliveries (run_id, event_id)
82
+ SELECT id, ${event.id}::bigint FROM requeued
83
+ ),
84
+ journaled AS (
85
+ INSERT INTO steps (run_id, seq, name, kind, status, output, attempts, started_at, finished_at)
86
+ SELECT m.run_id, m.seq, m.step_name, 'wait_event', 'succeeded', ${payload}::text::jsonb, 1,
87
+ now(), now()
88
+ FROM matched m JOIN requeued q ON q.id = m.run_id
89
+ )
90
+ INSERT INTO tasks (run_id, queue, tenant_id, workflow, concurrency_key)
91
+ SELECT m.run_id, m.queue, m.tenant_id, m.workflow, q.concurrency_key
92
+ FROM matched m JOIN requeued q ON q.id = m.run_id
93
+ RETURNING run_id AS "runId"`;
94
+ return rows.map((row) => row.runId);
95
+ }
96
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/store/events.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAGlC;;;GAGG;AACH,MAAM,oBAAoB,GAAG,SAAS,CAAC;AAEvC;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,EAAa,EAAE,QAAgB,EAAE,IAAY;IAC/E,MAAM,EAAE,CAAA;mCACyB,oBAAoB,cAAc,QAAQ,iBAAiB,IAAI,IAAI,CAAC;AACvG,CAAC;AAQD,mFAAmF;AACnF,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,EAAa,EAAE,KAAe;IAC9D,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,EAAE,CAAkB;;cAE5B,KAAK,CAAC,QAAQ,KAAK,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC;6BACvC,CAAC;IAC5B,IAAI,GAAG,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC/E,OAAO,GAAG,CAAC,EAAE,CAAC;AAChB,CAAC;AASD;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,EAAa,EACb,KAAiB;IAEjB,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,EAAE,CAAsC;;;0BAGpC,KAAK,CAAC,QAAQ;qBACnB,KAAK,CAAC,IAAI;oEACqC,KAAK,CAAC,KAAK;yBACtD,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC;;4DAEiB,KAAK,CAAC,KAAK;;YAE3D,CAAC;IACX,OAAO,GAAG,CAAC;AACb,CAAC;AAED,mFAAmF;AACnF,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,EAAa,EAAE,KAAa,EAAE,OAAe;IAChF,MAAM,EAAE,CAAA,2DAA2D,KAAK,KAAK,OAAO,WAAW,CAAC;AAClG,CAAC;AASD;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,EAAa,EAAE,KAAqB;IACrE,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,IAAI,GAAG,MAAM,EAAE,CAAqB;;;6CAGC,KAAK,CAAC,QAAQ,qBAAqB,KAAK,CAAC,IAAI;cAC5E,OAAO;;;;;;;iDAO4B,qBAAqB,CAAC,QAAQ,CAAC;;;;;mBAK7D,KAAK,CAAC,EAAE;;;;wEAI6C,OAAO;;;;;;;gCAO/C,CAAC;IAC/B,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { jsonb } from "./json.js";
2
+ /**
3
+ * Claims a run-level idempotency key, or reports the run that already holds it. The
4
+ * primary key decides the race, not this code: a concurrent insert of the same key waits
5
+ * for the first transaction and then does nothing. Inputs are hashed as jsonb text, which
6
+ * Postgres normalises, so object key order does not matter.
7
+ *
8
+ * Must run inside the transaction that creates the run, so a failed trigger frees the key.
9
+ */
10
+ export async function claimIdempotencyKey(tx, { tenantId, workflow, key, input }) {
11
+ const inputHash = tx `sha256(convert_to(${jsonb(input)}::text::jsonb::text, 'UTF8'))`;
12
+ const [claimed] = await tx `
13
+ INSERT INTO idempotency_keys (tenant_id, workflow, key, run_id, input_hash)
14
+ VALUES (${tenantId}, ${workflow}, ${key}, uuidv7(), ${inputHash})
15
+ ON CONFLICT (tenant_id, workflow, key) DO NOTHING
16
+ RETURNING run_id AS "runId"`;
17
+ if (claimed !== undefined)
18
+ return { kind: "claimed", runId: claimed.runId };
19
+ // Read committed: this statement sees the row of the transaction we waited for.
20
+ const [existing] = await tx `
21
+ SELECT run_id AS "runId", input_hash = ${inputHash} AS "sameInput"
22
+ FROM idempotency_keys
23
+ WHERE tenant_id = ${tenantId} AND workflow = ${workflow} AND key = ${key}`;
24
+ if (existing === undefined) {
25
+ throw new Error("idempotency key conflicted but no row was found");
26
+ }
27
+ return { kind: "existing", ...existing };
28
+ }
29
+ //# sourceMappingURL=idempotency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotency.js","sourceRoot":"","sources":["../../src/store/idempotency.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAclC;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,EAAa,EACb,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,EAAE,KAAK,EAAkB;IAElD,MAAM,SAAS,GAAG,EAAE,CAAA,qBAAqB,KAAK,CAAC,KAAK,CAAC,+BAA+B,CAAC;IAErF,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,EAAE,CAAqB;;cAEnC,QAAQ,KAAK,QAAQ,KAAK,GAAG,eAAe,SAAS;;gCAEnC,CAAC;IAC/B,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC;IAE5E,gFAAgF;IAChF,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,EAAE,CAAyC;6CACzB,SAAS;;wBAE9B,QAAQ,mBAAmB,QAAQ,cAAc,GAAG,EAAE,CAAC;IAC7E,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,CAAC;AAC3C,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * JSON text for a `${...}::text::jsonb` parameter. Both halves of the cast matter: the
3
+ * driver's json helper sends JSON `null` as SQL NULL (a NOT NULL violation for a valid
4
+ * payload), and a bare `::jsonb` makes the driver JSON-encode this text a second time.
5
+ */
6
+ export function jsonb(value) {
7
+ return JSON.stringify(value);
8
+ }
9
+ //# sourceMappingURL=json.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json.js","sourceRoot":"","sources":["../../src/store/json.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,UAAU,KAAK,CAAC,KAAgB;IACpC,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC"}