@dudousxd/nestjs-durable-transport-db 0.2.2 → 0.3.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.
package/dist/index.cjs CHANGED
@@ -71,6 +71,8 @@ function mikroOrmExecutor(em) {
71
71
  __name(mikroOrmExecutor, "mikroOrmExecutor");
72
72
 
73
73
  // src/db-transport.ts
74
+ var RUNS_INSERT_CHUNK = 500;
75
+ var RUNS_CLAIM_MAX = 50;
74
76
  function numberOption(value, fallback, min) {
75
77
  return value !== void 0 && Number.isFinite(value) && value >= min ? value : fallback;
76
78
  }
@@ -83,6 +85,8 @@ var DbTransport = class {
83
85
  group;
84
86
  tasksTable;
85
87
  resultsTable;
88
+ runsTable;
89
+ runConsumers = /* @__PURE__ */ new Set();
86
90
  pollMs;
87
91
  leaseMs;
88
92
  batchSize;
@@ -108,6 +112,7 @@ var DbTransport = class {
108
112
  const prefix = options.prefix ?? "durable";
109
113
  this.tasksTable = `${prefix}_transport_tasks`;
110
114
  this.resultsTable = `${prefix}_transport_results`;
115
+ this.runsTable = `${prefix}_transport_runs`;
111
116
  this.pollMs = numberOption(options.pollMs, 500, 0);
112
117
  this.leaseMs = numberOption(options.leaseMs, 3e4, 1);
113
118
  this.batchSize = Math.floor(numberOption(options.batchSize, 10, 1));
@@ -181,6 +186,18 @@ var DbTransport = class {
181
186
  ${this.q("claimed_at")} bigint,
182
187
  ${this.q("created_at")} bigint NOT NULL
183
188
  )`);
189
+ await this.createIfMissing(`CREATE TABLE IF NOT EXISTS ${this.q(this.runsTable)} (
190
+ ${this.q("run_id")} ${str} PRIMARY KEY,
191
+ ${this.q("ns")} ${str} NOT NULL,
192
+ ${this.q("priority")} integer NOT NULL,
193
+ ${this.q("wake")} integer NOT NULL,
194
+ ${this.q("claimed_by")} ${str},
195
+ ${this.q("claim_token")} ${str},
196
+ ${this.q("claimed_at")} bigint,
197
+ ${this.q("created_at")} bigint NOT NULL
198
+ )`);
199
+ await this.exec.query(`CREATE INDEX ${this.q(`${this.runsTable}_ns_idx`)} ON ${this.q(this.runsTable)} (${this.q("ns")}, ${this.q("priority")}, ${this.q("created_at")})`).catch(() => {
200
+ });
184
201
  await this.exec.query(`CREATE INDEX ${this.q(`${this.tasksTable}_grp_idx`)} ON ${tasks} (${this.q("grp")}, ${this.q("status")}, ${this.q("created_at")})`).catch(() => {
185
202
  });
186
203
  }
@@ -224,6 +241,166 @@ var DbTransport = class {
224
241
  }
225
242
  onHeartbeat(_handler) {
226
243
  }
244
+ // ── run queue (engine ↔ engine) ─────────────────────────────────────────────────────────────
245
+ /**
246
+ * Queue `pending` runs for whichever engine instance polls the run queue first: one row per run,
247
+ * keyed by run id, so a run already waiting is not queued twice. A run whose row an instance holds
248
+ * right now is released for another take, so a dispatch landing while the run's previous entry is
249
+ * being handled is not lost when that entry is deleted. Up to {@link RUNS_INSERT_CHUNK} rows per
250
+ * insert.
251
+ */
252
+ async dispatchRuns(runs, opts) {
253
+ if (runs.length === 0) return;
254
+ await this.ensureSchema();
255
+ const byRun = /* @__PURE__ */ new Map();
256
+ for (const run of runs) {
257
+ if (!byRun.has(run.runId) || run.reason === "wake") byRun.set(run.runId, run);
258
+ }
259
+ const unique = [
260
+ ...byRun.values()
261
+ ];
262
+ const t = this.q(this.runsTable);
263
+ const cols = [
264
+ "run_id",
265
+ "ns",
266
+ "priority",
267
+ "wake",
268
+ "created_at"
269
+ ];
270
+ const now = this.now();
271
+ for (let at = 0; at < unique.length; at += RUNS_INSERT_CHUNK) {
272
+ const chunk = unique.slice(at, at + RUNS_INSERT_CHUNK);
273
+ const values = chunk.map((_, r) => `(${cols.map((__, c) => this.ph(r * cols.length + c + 1)).join(", ")})`).join(", ");
274
+ const insert = `INTO ${t} (${cols.map((c) => this.q(c)).join(", ")}) VALUES ${values}`;
275
+ const release = [
276
+ "claimed_by",
277
+ "claim_token",
278
+ "claimed_at"
279
+ ].map((c) => `${this.q(c)} = NULL`).join(", ");
280
+ const wake = this.q("wake");
281
+ const sql = this.isPg ? `INSERT ${insert} ON CONFLICT (${this.q("run_id")}) DO UPDATE SET ${release}, ${wake} = GREATEST(${t}.${wake}, EXCLUDED.${wake})` : `INSERT ${insert} ON DUPLICATE KEY UPDATE ${release}, ${wake} = GREATEST(${wake}, VALUES(${wake}))`;
282
+ await this.exec.query(sql, chunk.flatMap((run, r) => [
283
+ run.runId,
284
+ opts?.namespace ?? "",
285
+ run.priority ?? 0,
286
+ run.reason === "wake" ? 1 : 0,
287
+ now + r
288
+ ]));
289
+ }
290
+ }
291
+ /**
292
+ * Poll the run queue, at most `opts.concurrency` runs in flight on this instance. Rows are claimed
293
+ * with `FOR UPDATE SKIP LOCKED` (instances never take the same run), highest priority then oldest
294
+ * first; a row is deleted once its handler settles, and its lease is renewed meanwhile, so a row is
295
+ * re-taken only after the instance holding it went down. The returned stop takes no more rows and
296
+ * resolves once the runs in flight settled.
297
+ */
298
+ onDispatchedRun(handler, opts) {
299
+ const consumer = {
300
+ stopped: false,
301
+ inflight: /* @__PURE__ */ new Set(),
302
+ slotFreed: void 0,
303
+ loop: Promise.resolve()
304
+ };
305
+ const concurrency = Math.max(1, Math.floor(opts.concurrency));
306
+ const ns = opts.namespace ?? "";
307
+ consumer.loop = this.consumeRuns(consumer, handler, concurrency, ns).catch((err) => {
308
+ this.onError(err);
309
+ });
310
+ this.runConsumers.add(consumer);
311
+ return () => this.stopRunConsumer(consumer);
312
+ }
313
+ async stopRunConsumer(consumer) {
314
+ consumer.stopped = true;
315
+ consumer.slotFreed?.();
316
+ await consumer.loop;
317
+ this.runConsumers.delete(consumer);
318
+ }
319
+ async consumeRuns(consumer, handler, concurrency, ns) {
320
+ const renew = setInterval(() => void this.renewRunLeases(consumer).catch(() => void 0), Math.max(1e3, Math.floor(this.leaseMs / 3)));
321
+ renew.unref?.();
322
+ const settled = /* @__PURE__ */ new Set();
323
+ try {
324
+ while (this.running && !consumer.stopped) {
325
+ const free = concurrency - consumer.inflight.size;
326
+ if (free <= 0) {
327
+ await new Promise((resolve) => {
328
+ consumer.slotFreed = resolve;
329
+ });
330
+ consumer.slotFreed = void 0;
331
+ continue;
332
+ }
333
+ let rows = [];
334
+ try {
335
+ await this.ensureSchema();
336
+ rows = await this.claimRuns(ns, Math.min(free, RUNS_CLAIM_MAX));
337
+ } catch (err) {
338
+ if (this.running && !consumer.stopped) this.onError(err);
339
+ }
340
+ for (const { run, token } of rows) {
341
+ consumer.inflight.add(token);
342
+ const done = handler(run).catch(() => void 0).then(() => this.exec.query(`DELETE FROM ${this.q(this.runsTable)} WHERE ${this.q("claim_token")} = ${this.ph(1)}`, [
343
+ token
344
+ ]).catch(() => void 0)).finally(() => {
345
+ consumer.inflight.delete(token);
346
+ settled.delete(done);
347
+ consumer.slotFreed?.();
348
+ });
349
+ settled.add(done);
350
+ }
351
+ if (rows.length === 0) await this.sleep(this.pollMs);
352
+ }
353
+ await Promise.allSettled([
354
+ ...settled
355
+ ]);
356
+ } finally {
357
+ clearInterval(renew);
358
+ }
359
+ }
360
+ async claimRuns(ns, limit) {
361
+ const t = this.q(this.runsTable);
362
+ const staleBefore = this.now() - this.leaseMs;
363
+ return this.exec.transaction(async (tx) => {
364
+ const rows = await tx.query(`SELECT ${this.q("run_id")}, ${this.q("wake")} FROM ${t}
365
+ WHERE ${this.q("ns")} = ${this.ph(1)}
366
+ AND (${this.q("claimed_at")} IS NULL OR ${this.q("claimed_at")} < ${this.ph(2)})
367
+ ORDER BY ${this.q("priority")} DESC, ${this.q("created_at")} ASC
368
+ LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED`, [
369
+ ns,
370
+ staleBefore
371
+ ]);
372
+ const claimed = rows.map((r) => ({
373
+ run: {
374
+ runId: r.run_id,
375
+ reason: Number(r.wake) === 1 ? "wake" : "start"
376
+ },
377
+ token: globalThis.crypto.randomUUID()
378
+ }));
379
+ const now = this.now();
380
+ for (const { run: { runId }, token } of claimed) {
381
+ await tx.query(`UPDATE ${t} SET ${this.q("claimed_by")} = ${this.ph(1)}, ${this.q("claim_token")} = ${this.ph(2)}, ${this.q("claimed_at")} = ${this.ph(3)}
382
+ WHERE ${this.q("run_id")} = ${this.ph(4)}`, [
383
+ this.instanceId,
384
+ token,
385
+ now,
386
+ runId
387
+ ]);
388
+ }
389
+ return claimed;
390
+ });
391
+ }
392
+ /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */
393
+ async renewRunLeases(consumer) {
394
+ const tokens = [
395
+ ...consumer.inflight
396
+ ];
397
+ if (tokens.length === 0) return;
398
+ await this.exec.query(`UPDATE ${this.q(this.runsTable)} SET ${this.q("claimed_at")} = ${this.ph(1)}
399
+ WHERE ${this.q("claim_token")} IN (${tokens.map((_, i) => this.ph(i + 2)).join(", ")})`, [
400
+ this.now(),
401
+ ...tokens
402
+ ]);
403
+ }
227
404
  // ── polling ──────────────────────────────────────────────────────────────────────────────────
228
405
  /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */
229
406
  async loop(tick) {
@@ -499,7 +676,10 @@ var DbTransport = class {
499
676
  this.running = false;
500
677
  await Promise.allSettled([
501
678
  this.taskLoop,
502
- this.resultLoop
679
+ this.resultLoop,
680
+ ...[
681
+ ...this.runConsumers
682
+ ].map((c) => this.stopRunConsumer(c))
503
683
  ]);
504
684
  await Promise.allSettled([
505
685
  ...this.runningTasks
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/db-transport.ts","../src/executors.ts"],"sourcesContent":["export * from './db-transport';\n","import { randomUUID } from 'node:crypto';\nimport {\n type Heartbeat,\n type RemoteTask,\n type StepHandler,\n type StepResult,\n type Transport,\n runStepHandler,\n} from '@dudousxd/nestjs-durable-core';\nimport type { SqlExecutor, SqlTx } from './executors';\n\nexport { mikroOrmExecutor, type SqlExecutor, type SqlTx, typeOrmExecutor } from './executors';\n\n/** Raw row shapes returned by `SELECT *` (declared fields, so they're not `| undefined` under noUncheckedIndexedAccess). */\ninterface TaskRow {\n step_id: string;\n run_id: string;\n seq: string | number;\n name: string;\n input: string | null;\n attempt: string | number;\n}\ninterface ResultRow {\n step_id: string;\n run_id: string;\n seq: string | number;\n status: string;\n output: string | null;\n error: string | null;\n started_at: string | number | null;\n}\n\nexport interface DbTransportOptions {\n /**\n * How to run SQL — built from the app's **own** ORM/connection (no broker, no extra connection).\n * Use `mikroOrmExecutor(em)` to ride the app's MikroORM, `typeOrmExecutor(dataSource)` for TypeORM,\n * `drizzlePgExecutor(db)` (from `@dudousxd/nestjs-durable-store-drizzle/pg`) for Drizzle on\n * Postgres, or implement `SqlExecutor` for anything else.\n */\n executor: SqlExecutor;\n /** The worker group this instance serves. Required to register `handle()` consumers. */\n group?: string;\n /** Table-name prefix. Tables: `${prefix}_transport_tasks` / `${prefix}_transport_results`. Default `durable`. */\n prefix?: string;\n /** Poll interval in ms when a queue is empty. Default 500. */\n pollMs?: number;\n /**\n * How long a claimed row is owned before it's reclaimable (crash recovery), in ms. Default 30_000.\n * Every claim this instance holds is renewed every `leaseMs / 3` while it is waiting or running, so\n * a step may run longer than `leaseMs`; only a crashed (or event-loop-blocked) instance loses it.\n */\n leaseMs?: number;\n /**\n * Max rows claimed per poll. Default 10. The task loop claims only as many rows as it has free\n * {@link concurrency} slots (capped by this); the results loop claims up to this many.\n */\n batchSize?: number;\n /**\n * How many tasks this instance runs at once (worker side). Default 1. A row is claimed only when a\n * slot is free to run it, so rows never wait claimed behind a slow task while a sibling sits idle.\n */\n concurrency?: number;\n /**\n * Where a transport failure is reported: a failing poll, a throwing result handler (the result is\n * re-delivered after the lease), a lost claim. Default `console.error`.\n */\n onError?: (err: unknown) => void;\n /** Create the two tables on first use if missing. Default true. */\n autoCreate?: boolean;\n /** Identifies this instance in `claimed_by` (for debugging). Defaults to a random id. */\n instanceId?: string;\n}\n\n/**\n * A numeric option: `fallback` unless `value` is a finite number of at least `min`. `Math.max(1, NaN)`\n * is `NaN`, so a clamp alone would let a `NaN` through (to `LIMIT NaN`, or a `NaN` timer).\n */\nfunction numberOption(value: number | undefined, fallback: number, min: number): number {\n return value !== undefined && Number.isFinite(value) && value >= min ? value : fallback;\n}\n\n/**\n * A SQL-backed `Transport` — DBOS-style. Instead of a broker (Redis/SQS), remote steps are **rows**\n * in the same database the durable store already uses: `dispatch` inserts a task row, a worker\n * claims it with `SELECT … FOR UPDATE SKIP LOCKED` (so instances never double-claim), runs it, and\n * writes a result row the engine polls. Zero new infrastructure — the DB you already have IS the\n * queue.\n *\n * Trade-off vs a real broker: throughput is bounded by polling + row contention. Great for\n * workflow/pipeline scale (modest rate, long steps); not for high-fanout firehoses.\n *\n * Requires `FOR UPDATE SKIP LOCKED` — **MySQL 8+** or **Postgres 9.5+** (not SQLite). Run one\n * instance engine-side (`onResult`, dispatches) and one per worker process (`handle()` for its group).\n */\nexport class DbTransport implements Transport {\n private readonly exec: SqlExecutor;\n private readonly group?: string | undefined;\n private readonly tasksTable: string;\n private readonly resultsTable: string;\n private readonly pollMs: number;\n private readonly leaseMs: number;\n private readonly batchSize: number;\n private readonly concurrency: number;\n private readonly onError: (err: unknown) => void;\n private readonly autoCreate: boolean;\n private readonly instanceId: string;\n private readonly isPg: boolean;\n\n private readonly handlers = new Map<string, StepHandler>();\n private running = true;\n private schemaReady?: Promise<void> | undefined;\n private taskLoop?: Promise<void>;\n private resultLoop?: Promise<void>;\n /** Tasks running on this instance (at most `concurrency`). */\n private readonly runningTasks = new Set<Promise<void>>();\n /** Claim tokens this instance holds, by table — every one is renewed on `renewTimer`. */\n private readonly held = new Map<string, Set<string>>();\n private renewTimer?: ReturnType<typeof setInterval> | undefined;\n private renewal?: Promise<void> | undefined;\n\n constructor(options: DbTransportOptions) {\n this.exec = options.executor;\n this.group = options.group;\n const prefix = options.prefix ?? 'durable';\n this.tasksTable = `${prefix}_transport_tasks`;\n this.resultsTable = `${prefix}_transport_results`;\n this.pollMs = numberOption(options.pollMs, 500, 0);\n this.leaseMs = numberOption(options.leaseMs, 30_000, 1);\n this.batchSize = Math.floor(numberOption(options.batchSize, 10, 1));\n this.concurrency = Math.floor(numberOption(options.concurrency, 1, 1));\n this.onError = options.onError ?? ((err) => console.error('[DbTransport]', err));\n this.autoCreate = options.autoCreate ?? true;\n // Random, not time-based: two instances booted in the same millisecond must not share an id.\n this.instanceId = options.instanceId ?? `db-${randomUUID()}`;\n this.isPg = this.exec.dialect === 'postgres';\n }\n\n // ── dialect helpers ──────────────────────────────────────────────────────────────────────────\n /** Positional placeholder for param `i` (1-based): `$i` on Postgres, `?` elsewhere. */\n private ph(i: number): string {\n return this.isPg ? `$${i}` : '?';\n }\n private q(id: string): string {\n return this.exec.escapeId(id);\n }\n private now(): number {\n return Math.floor(Date.now());\n }\n\n // ── schema ───────────────────────────────────────────────────────────────────────────────────\n private ensureSchema(): Promise<void> {\n if (!this.schemaReady) {\n // A failed attempt is not cached: the next call tries again instead of failing forever.\n this.schemaReady = this.createTables().catch((err) => {\n this.schemaReady = undefined;\n throw err;\n });\n }\n return this.schemaReady;\n }\n\n /**\n * Run one `CREATE … IF NOT EXISTS`. Two instances booting on a fresh database race it, and Postgres\n * can reject the loser with a unique violation on its catalog even with `IF NOT EXISTS`; the\n * statement is simply re-run, by which point the table exists and it is a no-op.\n */\n private async createIfMissing(sql: string): Promise<void> {\n try {\n await this.exec.query(sql);\n } catch {\n await this.exec.query(sql);\n }\n }\n\n private async createTables(): Promise<void> {\n if (!this.autoCreate) return;\n const str = 'varchar(191)';\n const txt = this.isPg ? 'text' : 'longtext';\n const tasks = this.q(this.tasksTable);\n const results = this.q(this.resultsTable);\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${tasks} (\n ${this.q('step_id')} ${str} PRIMARY KEY,\n ${this.q('run_id')} ${str} NOT NULL,\n ${this.q('seq')} integer NOT NULL,\n ${this.q('name')} ${str} NOT NULL,\n ${this.q('grp')} ${str} NOT NULL,\n ${this.q('input')} ${txt},\n ${this.q('attempt')} integer NOT NULL,\n ${this.q('status')} varchar(32) NOT NULL,\n ${this.q('claimed_by')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${results} (\n ${this.q('step_id')} ${str} PRIMARY KEY,\n ${this.q('run_id')} ${str} NOT NULL,\n ${this.q('seq')} integer NOT NULL,\n ${this.q('status')} varchar(32) NOT NULL,\n ${this.q('output')} ${txt},\n ${this.q('error')} ${txt},\n ${this.q('started_at')} bigint,\n ${this.q('claimed_by')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n // Best-effort index for the group poll (MySQL has no CREATE INDEX IF NOT EXISTS < 8.0.13).\n await this.exec\n .query(\n `CREATE INDEX ${this.q(`${this.tasksTable}_grp_idx`)} ON ${tasks} (${this.q('grp')}, ${this.q('status')}, ${this.q('created_at')})`,\n )\n .catch(() => {});\n }\n\n // ── engine → worker ────────────────────────────────────────────────────────────────────────\n async dispatch(task: RemoteTask): Promise<void> {\n await this.ensureSchema();\n const t = this.q(this.tasksTable);\n // Idempotent: a redelivered dispatch for the same step_id is ignored (the row already exists).\n const ignore = this.isPg\n ? `INSERT INTO ${t} (...) ON CONFLICT (${this.q('step_id')}) DO NOTHING`\n : `INSERT IGNORE INTO ${t} (...)`;\n const cols = [\n 'step_id',\n 'run_id',\n 'seq',\n 'name',\n 'grp',\n 'input',\n 'attempt',\n 'status',\n 'created_at',\n ];\n const sql = ignore.replace(\n '(...)',\n `(${cols.map((c) => this.q(c)).join(', ')}) VALUES (${cols.map((_, i) => this.ph(i + 1)).join(', ')})`,\n );\n await this.exec.query(sql, [\n task.stepId,\n task.runId,\n task.seq,\n task.name,\n task.group,\n JSON.stringify(task.input ?? null),\n task.attempt,\n 'pending',\n this.now(),\n ]);\n }\n\n // ── worker → engine ────────────────────────────────────────────────────────────────────────\n handle(name: string, fn: StepHandler): void {\n if (!this.group) throw new Error('DbTransport needs a `group` to register handlers');\n this.handlers.set(name, fn);\n if (!this.taskLoop) this.taskLoop = this.loop(() => this.drainTasks(this.group as string));\n }\n\n onResult(handler: (result: StepResult) => Promise<void>): void {\n if (!this.resultLoop) this.resultLoop = this.loop(() => this.drainResults(handler));\n }\n\n onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void {\n // Not modelled; the lease/reclaim on `claimed_at` is the liveness mechanism.\n }\n\n // ── polling ──────────────────────────────────────────────────────────────────────────────────\n /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */\n private async loop(tick: () => Promise<number>): Promise<void> {\n while (this.running) {\n let processed = 0;\n try {\n await this.ensureSchema();\n processed = await tick();\n } catch (err) {\n if (this.running) this.onError(err);\n }\n if (processed === 0 && this.running) await this.sleep(this.pollMs);\n }\n }\n\n /**\n * One task-loop round: claim as many rows as there are free slots (never more — a claimed row that\n * isn't running is one an idle sibling can't run), and start each. With every slot busy, wait for\n * one to free instead of polling.\n */\n private async drainTasks(group: string): Promise<number> {\n const free = this.concurrency - this.runningTasks.size;\n if (free <= 0) {\n await Promise.race(this.runningTasks);\n return 1;\n }\n const { rows, token } = await this.claim<TaskRow>(\n this.tasksTable,\n Math.min(free, this.batchSize),\n `${this.q('grp')} = ${this.ph(1)}`,\n [group],\n );\n if (rows.length === 0) return 0;\n this.hold(this.tasksTable, token);\n let left = rows.length;\n for (const row of rows) {\n const run = this.runTask(row, group, token).finally(() => {\n this.runningTasks.delete(run);\n left -= 1;\n if (left === 0) this.release(this.tasksTable, token);\n });\n this.runningTasks.add(run);\n }\n return rows.length;\n }\n\n /**\n * Run one claimed task and settle it — only while this instance still holds the claim: the claim is\n * re-checked before running, and the task row is deleted and its result written in ONE transaction,\n * conditional on the claim token, so an instance whose claim was taken over neither deletes the new\n * holder's row nor publishes a second result.\n */\n private async runTask(row: TaskRow, group: string, token: string): Promise<void> {\n try {\n if (!(await this.stillHolds(row.step_id, token))) {\n this.onError(\n new Error(\n `[DbTransport] lost the claim on task ${row.step_id} before running it — another instance took it over; not running it here`,\n ),\n );\n return;\n }\n const task: RemoteTask = {\n runId: row.run_id,\n seq: Number(row.seq),\n stepId: row.step_id,\n name: row.name,\n group,\n input: row.input == null ? undefined : JSON.parse(row.input),\n attempt: Number(row.attempt),\n };\n const result = await runStepHandler(task, this.handlers.get(task.name));\n if (!(await this.settleTask(task.stepId, token, result))) {\n this.onError(\n new Error(\n `[DbTransport] lost the claim on task ${task.stepId} while running it (this instance went silent past leaseMs) — another instance took it over and may run it too; this run's result was dropped. Raise leaseMs if steps block the event loop`,\n ),\n );\n }\n } catch (err) {\n // A database error settling the row (or a malformed row): it stays claimed, stops being\n // renewed, and is reclaimed after the lease — at-least-once, like a crash.\n this.onError(err);\n }\n }\n\n /** Whether the claim on `stepId` is still `token`'s (re-stamping it if so). */\n private async stillHolds(stepId: string, token: string): Promise<boolean> {\n const t = this.q(this.tasksTable);\n const rows = await this.exec.transaction(async (tx) => {\n const held = await tx.query<{ step_id: string }>(\n `SELECT ${this.q('step_id')} FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)} FOR UPDATE`,\n [stepId, token],\n );\n if (held.length > 0) {\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_at')} = ${this.ph(1)} WHERE ${this.q('step_id')} = ${this.ph(2)} AND ${this.q('claimed_by')} = ${this.ph(3)}`,\n [this.now(), stepId, token],\n );\n }\n return held;\n });\n return rows.length > 0;\n }\n\n /** Delete the task row and publish its result in ONE transaction, only while `token` holds it. */\n private async settleTask(stepId: string, token: string, result: StepResult): Promise<boolean> {\n const t = this.q(this.tasksTable);\n return this.exec.transaction(async (tx) => {\n const held = await tx.query<{ step_id: string }>(\n `SELECT ${this.q('step_id')} FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)} FOR UPDATE`,\n [stepId, token],\n );\n if (held.length === 0) return false;\n await tx.query(\n `DELETE FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)}`,\n [stepId, token],\n );\n await this.insertResult(result, tx);\n return true;\n });\n }\n\n /**\n * Claim a batch of results, deliver each to the engine, and delete it — only after its handler ran\n * (at-least-once), and only while this round still holds the claim (a newer result for the same\n * step that replaced the row resets the claim, so it is delivered next instead of deleted). The\n * batch's claim is renewed until it is done. A throwing handler is reported and its row left for\n * re-delivery after the lease; the rest of the batch continues.\n */\n private async drainResults(handler: (result: StepResult) => Promise<void>): Promise<number> {\n const { rows, token } = await this.claim<ResultRow>(\n this.resultsTable,\n this.batchSize,\n '1 = 1',\n [],\n );\n if (rows.length === 0) return 0;\n this.hold(this.resultsTable, token);\n try {\n for (const row of rows) {\n if (!this.running) break;\n try {\n const result: StepResult = {\n runId: row.run_id,\n seq: Number(row.seq),\n stepId: row.step_id,\n status: row.status as StepResult['status'],\n output: row.output == null ? undefined : JSON.parse(row.output),\n error: row.error == null ? undefined : JSON.parse(row.error),\n startedAt: row.started_at == null ? undefined : Number(row.started_at),\n };\n await handler(result);\n await this.exec.query(\n `DELETE FROM ${this.q(this.resultsTable)} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)}`,\n [row.step_id, token],\n );\n } catch (err) {\n this.onError(err);\n }\n }\n } finally {\n this.release(this.resultsTable, token);\n }\n return rows.length;\n }\n\n /**\n * Atomically claim up to `limit` un-leased rows matching `where` and stamp them with a claim token\n * unique to this round (`<instanceId>:<uuid>`). `SELECT … FOR UPDATE SKIP LOCKED` inside the txn\n * means concurrent instances skip each other's locked rows instead of blocking, so no row is\n * claimed twice; the token is what every later delete/settle is conditional on.\n */\n private async claim<T extends { step_id: string }>(\n table: string,\n limit: number,\n where: string,\n whereParams: unknown[],\n ): Promise<{ rows: T[]; token: string }> {\n const t = this.q(table);\n const staleBefore = this.now() - this.leaseMs;\n const token = `${this.instanceId}:${randomUUID()}`;\n const rows = await this.exec.transaction(async (tx) => {\n const leaseClause = `(${this.q('claimed_at')} IS NULL OR ${this.q('claimed_at')} < ${this.ph(whereParams.length + 1)})`;\n const found = await tx.query<T>(\n `SELECT * FROM ${t} WHERE ${where} AND ${leaseClause}\n ORDER BY ${this.q('created_at')} ASC LIMIT ${Math.max(1, Math.floor(limit))} FOR UPDATE SKIP LOCKED`,\n [...whereParams, staleBefore],\n );\n if (found.length > 0) {\n const ids = found.map((r) => r.step_id);\n const placeholders = ids.map((_, i) => this.ph(i + 3)).join(', ');\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_by')} = ${this.ph(1)}, ${this.q('claimed_at')} = ${this.ph(2)}\n WHERE ${this.q('step_id')} IN (${placeholders})`,\n [token, this.now(), ...ids],\n );\n }\n return found;\n });\n return { rows, token };\n }\n\n // ── claim renewal: every claim held, not only the row being run ─────────────────────────────\n private hold(table: string, token: string): void {\n let tokens = this.held.get(table);\n if (!tokens) {\n tokens = new Set();\n this.held.set(table, tokens);\n }\n tokens.add(token);\n if (this.renewTimer) return;\n const intervalMs = Math.max(10, Math.floor(this.leaseMs / 3));\n this.renewTimer = setInterval(() => {\n if (this.renewal) return; // a slow database never stacks renewal rounds\n const round = this.renewHeld()\n .catch((err) => this.onError(err))\n .finally(() => {\n if (this.renewal === round) this.renewal = undefined;\n });\n this.renewal = round;\n }, intervalMs);\n this.renewTimer.unref?.();\n }\n\n private release(table: string, token: string): void {\n const tokens = this.held.get(table);\n tokens?.delete(token);\n if (tokens?.size === 0) this.held.delete(table);\n if (this.held.size === 0 && this.renewTimer) {\n clearInterval(this.renewTimer);\n this.renewTimer = undefined;\n }\n }\n\n /** Re-stamp `claimed_at` on every row still claimed under a token this instance holds. */\n private async renewHeld(): Promise<void> {\n for (const [table, tokens] of this.held) {\n if (tokens.size === 0) continue;\n const list = [...tokens];\n const placeholders = list.map((_, i) => this.ph(i + 2)).join(', ');\n await this.exec.query(\n `UPDATE ${this.q(table)} SET ${this.q('claimed_at')} = ${this.ph(1)} WHERE ${this.q('claimed_by')} IN (${placeholders})`,\n [this.now(), ...list],\n );\n }\n }\n\n /**\n * Write a result row. A result already waiting for the same step (an earlier attempt's, not yet\n * deleted by the engine) is REPLACED and its claim reset, never kept: `step_id` is stable across\n * attempts, so keeping the old row would silently drop a retry's result.\n */\n private async insertResult(result: StepResult, tx: SqlTx = this.exec): Promise<void> {\n const t = this.q(this.resultsTable);\n const cols = [\n 'step_id',\n 'run_id',\n 'seq',\n 'status',\n 'output',\n 'error',\n 'started_at',\n 'created_at',\n ];\n const replace = ['run_id', 'seq', 'status', 'output', 'error', 'started_at', 'created_at'];\n const values = `(${cols.map((c) => this.q(c)).join(', ')}) VALUES (${cols.map((_, i) => this.ph(i + 1)).join(', ')})`;\n const sql = this.isPg\n ? `INSERT INTO ${t} ${values} ON CONFLICT (${this.q('step_id')}) DO UPDATE SET ${[\n ...replace.map((c) => `${this.q(c)} = EXCLUDED.${this.q(c)}`),\n `${this.q('claimed_by')} = NULL`,\n `${this.q('claimed_at')} = NULL`,\n ].join(', ')}`\n : `INSERT INTO ${t} ${values} ON DUPLICATE KEY UPDATE ${[\n ...replace.map((c) => `${this.q(c)} = VALUES(${this.q(c)})`),\n `${this.q('claimed_by')} = NULL`,\n `${this.q('claimed_at')} = NULL`,\n ].join(', ')}`;\n await tx.query(sql, [\n result.stepId,\n result.runId,\n result.seq,\n result.status,\n result.output === undefined ? null : JSON.stringify(result.output),\n result.error === undefined ? null : JSON.stringify(result.error),\n result.startedAt ?? null,\n this.now(),\n ]);\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n }\n\n /** Stop the pollers and wait for the current ticks to settle. Does not close the shared DataSource. */\n async close(): Promise<void> {\n this.running = false;\n await Promise.allSettled([this.taskLoop, this.resultLoop]);\n // Let running tasks settle (their claims keep being renewed until they do).\n await Promise.allSettled([...this.runningTasks]);\n if (this.renewTimer) clearInterval(this.renewTimer);\n this.renewTimer = undefined;\n await this.renewal;\n }\n}\n","/**\n * The tiny SQL surface `DbTransport` needs, so it rides **whatever ORM/connection the app already\n * has** instead of forcing a specific one. Implement it for your ORM (adapters for TypeORM and\n * MikroORM ship below) and hand it to `new DbTransport({ executor })`. Mirrors how the durable\n * *store* is ORM-pluggable (store-typeorm / store-mikro-orm / …).\n */\nexport interface SqlExecutor {\n /** Drives placeholder style (`$n` vs `?`) and a couple of DDL type choices. */\n readonly dialect: 'mysql' | 'postgres';\n /** Quote/escape an identifier (table/column name) for this dialect. */\n escapeId(id: string): string;\n /** Run a statement outside a transaction. */\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n /** Run `fn` inside a transaction — the claim uses `FOR UPDATE SKIP LOCKED` within it. */\n transaction<T>(fn: (tx: SqlTx) => Promise<T>): Promise<T>;\n}\n\nexport interface SqlTx {\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n}\n\n// ── TypeORM ──────────────────────────────────────────────────────────────────────────────────────\n\n/** Structural slice of a TypeORM `DataSource` — avoids a hard dependency on typeorm. */\ninterface TypeOrmDataSourceLike {\n options: { type: string };\n driver: { escape(id: string): string };\n query(sql: string, params?: unknown[]): Promise<unknown>;\n createQueryRunner(): {\n connect(): Promise<void>;\n startTransaction(): Promise<void>;\n commitTransaction(): Promise<void>;\n rollbackTransaction(): Promise<void>;\n release(): Promise<void>;\n query(sql: string, params?: unknown[]): Promise<unknown>;\n };\n}\n\n/** Build an executor from a TypeORM `DataSource` (e.g. the one the durable store already uses). */\nexport function typeOrmExecutor(ds: TypeOrmDataSourceLike): SqlExecutor {\n return {\n dialect: /postgres/.test(String(ds.options.type)) ? 'postgres' : 'mysql',\n escapeId: (id) => ds.driver.escape(id),\n query: <T>(sql: string, params?: unknown[]) => ds.query(sql, params) as Promise<T[]>,\n transaction: async <T>(fn: (tx: SqlTx) => Promise<T>) => {\n const qr = ds.createQueryRunner();\n await qr.connect();\n await qr.startTransaction();\n try {\n const result = await fn({\n query: <U>(sql: string, params?: unknown[]) => qr.query(sql, params) as Promise<U[]>,\n });\n await qr.commitTransaction();\n return result;\n } catch (err) {\n await qr.rollbackTransaction();\n throw err;\n } finally {\n await qr.release();\n }\n },\n };\n}\n\n// ── MikroORM ─────────────────────────────────────────────────────────────────────────────────────\n\n/** Structural slice of a MikroORM `EntityManager` — avoids a hard dependency on @mikro-orm/core. */\ninterface MikroOrmEmLike {\n getPlatform(): { constructor: { name: string }; quoteIdentifier(id: string): string };\n getConnection(): {\n execute(sql: string, params?: unknown[], method?: 'all', ctx?: unknown): Promise<unknown>;\n };\n getTransactionContext?(): unknown;\n transactional<T>(cb: (em: MikroOrmEmLike) => Promise<T>): Promise<T>;\n}\n\n/**\n * Build an executor from a MikroORM `EntityManager` — i.e. **the app's own configured ORM**. Runs\n * raw SQL through `em.getConnection().execute(...)` and wraps the claim in `em.transactional(...)`,\n * threading the transaction context so `FOR UPDATE SKIP LOCKED` locks within the tx.\n */\nexport function mikroOrmExecutor(em: MikroOrmEmLike): SqlExecutor {\n const platform = em.getPlatform();\n return {\n dialect: /postgre/i.test(platform.constructor.name) ? 'postgres' : 'mysql',\n escapeId: (id) => platform.quoteIdentifier(id),\n query: <T>(sql: string, params?: unknown[]) =>\n em.getConnection().execute(sql, params ?? [], 'all') as Promise<T[]>,\n transaction: <T>(fn: (tx: SqlTx) => Promise<T>) =>\n em.transactional((txEm) =>\n fn({\n query: <U>(sql: string, params?: unknown[]) =>\n txEm\n .getConnection()\n .execute(sql, params ?? [], 'all', txEm.getTransactionContext?.()) as Promise<U[]>,\n }),\n ),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACAA,yBAA2B;AAC3B,iCAOO;;;AC+BA,SAASA,gBAAgBC,IAAyB;AACvD,SAAO;IACLC,SAAS,WAAWC,KAAKC,OAAOH,GAAGI,QAAQC,IAAI,CAAA,IAAK,aAAa;IACjEC,UAAU,wBAACC,OAAOP,GAAGQ,OAAOC,OAAOF,EAAAA,GAAzB;IACVG,OAAO,wBAAIC,KAAaC,WAAuBZ,GAAGU,MAAMC,KAAK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A;EAC1C;;EAGA,MAAME,QAAuB;AAC3B,SAAK1H,UAAU;AACf,UAAMsE,QAAQqD,WAAW;MAAC,KAAKzH;MAAU,KAAKC;KAAW;AAEzD,UAAMmE,QAAQqD,WAAW;SAAI,KAAKvH;KAAa;AAC/C,QAAI,KAAKG,WAAY8G,eAAc,KAAK9G,UAAU;AAClD,SAAKA,aAAazB;AAClB,UAAM,KAAK0B;EACb;AACF;","names":["typeOrmExecutor","ds","dialect","test","String","options","type","escapeId","id","driver","escape","query","sql","params","transaction","fn","qr","createQueryRunner","connect","startTransaction","result","commitTransaction","err","rollbackTransaction","release","mikroOrmExecutor","em","platform","getPlatform","name","quoteIdentifier","getConnection","execute","transactional","txEm","getTransactionContext","numberOption","value","fallback","min","undefined","Number","isFinite","DbTransport","exec","group","tasksTable","resultsTable","pollMs","leaseMs","batchSize","concurrency","onError","autoCreate","instanceId","isPg","handlers","Map","running","schemaReady","taskLoop","resultLoop","runningTasks","Set","held","renewTimer","renewal","options","executor","prefix","Math","floor","err","console","error","randomUUID","dialect","ph","i","q","id","escapeId","now","Date","ensureSchema","createTables","catch","createIfMissing","sql","query","str","txt","tasks","results","dispatch","task","t","ignore","cols","replace","map","c","join","_","stepId","runId","seq","name","JSON","stringify","input","attempt","handle","fn","Error","set","loop","drainTasks","onResult","handler","drainResults","onHeartbeat","_handler","tick","processed","sleep","free","size","Promise","race","rows","token","claim","length","hold","left","row","run","runTask","finally","delete","release","add","stillHolds","step_id","run_id","parse","result","runStepHandler","get","settleTask","transaction","tx","insertResult","status","output","startedAt","started_at","table","limit","where","whereParams","staleBefore","leaseClause","found","max","ids","r","placeholders","tokens","intervalMs","setInterval","round","renewHeld","unref","clearInterval","list","values","ms","setTimeout","close","allSettled"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/db-transport.ts","../src/executors.ts"],"sourcesContent":["export * from './db-transport';\n","import { randomUUID } from 'node:crypto';\nimport {\n type Heartbeat,\n type RemoteTask,\n type RunConsumerOptions,\n type RunDispatch,\n type RunQueueOptions,\n type StepHandler,\n type StepResult,\n type Transport,\n runStepHandler,\n} from '@dudousxd/nestjs-durable-core';\nimport type { SqlExecutor, SqlTx } from './executors';\n\nexport { mikroOrmExecutor, type SqlExecutor, type SqlTx, typeOrmExecutor } from './executors';\n\n/** Raw row shapes returned by `SELECT *` (declared fields, so they're not `| undefined` under noUncheckedIndexedAccess). */\ninterface TaskRow {\n step_id: string;\n run_id: string;\n seq: string | number;\n name: string;\n input: string | null;\n attempt: string | number;\n}\ninterface RunRow {\n run_id: string;\n wake: number | string;\n}\n\n/** A claimed run row: its run id and the token of this claim. */\ninterface ClaimedRun {\n run: RunDispatch;\n token: string;\n}\n\n/** Most rows one {@link DbTransport.dispatchRuns} insert writes. */\nconst RUNS_INSERT_CHUNK = 500;\n/** Most run rows one consumer poll claims. */\nconst RUNS_CLAIM_MAX = 50;\n\n/** A run-queue consumer started by {@link DbTransport.onDispatchedRun}. */\ninterface RunConsumer {\n stopped: boolean;\n /** Claim tokens of the rows whose runs are in flight. */\n inflight: Set<string>;\n slotFreed: (() => void) | undefined;\n loop: Promise<void>;\n}\n\ninterface ResultRow {\n step_id: string;\n run_id: string;\n seq: string | number;\n status: string;\n output: string | null;\n error: string | null;\n started_at: string | number | null;\n}\n\nexport interface DbTransportOptions {\n /**\n * How to run SQL — built from the app's **own** ORM/connection (no broker, no extra connection).\n * Use `mikroOrmExecutor(em)` to ride the app's MikroORM, `typeOrmExecutor(dataSource)` for TypeORM,\n * `drizzlePgExecutor(db)` (from `@dudousxd/nestjs-durable-store-drizzle/pg`) for Drizzle on\n * Postgres, or implement `SqlExecutor` for anything else.\n */\n executor: SqlExecutor;\n /** The worker group this instance serves. Required to register `handle()` consumers. */\n group?: string;\n /**\n * Table-name prefix. Tables: `${prefix}_transport_tasks` / `${prefix}_transport_results`, and\n * `${prefix}_transport_runs` for the run queue. Default `durable`.\n */\n prefix?: string;\n /** Poll interval in ms when a queue is empty. Default 500. */\n pollMs?: number;\n /**\n * How long a claimed row is owned before it's reclaimable (crash recovery), in ms. Default 30_000.\n * Every claim this instance holds is renewed every `leaseMs / 3` while it is waiting or running, so\n * a step may run longer than `leaseMs`; only a crashed (or event-loop-blocked) instance loses it.\n */\n leaseMs?: number;\n /**\n * Max rows claimed per poll. Default 10. The task loop claims only as many rows as it has free\n * {@link concurrency} slots (capped by this); the results loop claims up to this many.\n */\n batchSize?: number;\n /**\n * How many tasks this instance runs at once (worker side). Default 1. A row is claimed only when a\n * slot is free to run it, so rows never wait claimed behind a slow task while a sibling sits idle.\n */\n concurrency?: number;\n /**\n * Where a transport failure is reported: a failing poll, a throwing result handler (the result is\n * re-delivered after the lease), a lost claim. Default `console.error`.\n */\n onError?: (err: unknown) => void;\n /** Create the tables on first use if missing. Default true. */\n autoCreate?: boolean;\n /** Identifies this instance in `claimed_by` (for debugging). Defaults to a random id. */\n instanceId?: string;\n}\n\n/**\n * A numeric option: `fallback` unless `value` is a finite number of at least `min`. `Math.max(1, NaN)`\n * is `NaN`, so a clamp alone would let a `NaN` through (to `LIMIT NaN`, or a `NaN` timer).\n */\nfunction numberOption(value: number | undefined, fallback: number, min: number): number {\n return value !== undefined && Number.isFinite(value) && value >= min ? value : fallback;\n}\n\n/**\n * A SQL-backed `Transport` — DBOS-style. Instead of a broker (Redis/SQS), remote steps are **rows**\n * in the same database the durable store already uses: `dispatch` inserts a task row, a worker\n * claims it with `SELECT … FOR UPDATE SKIP LOCKED` (so instances never double-claim), runs it, and\n * writes a result row the engine polls. Zero new infrastructure — the DB you already have IS the\n * queue.\n *\n * Trade-off vs a real broker: throughput is bounded by polling + row contention. Great for\n * workflow/pipeline scale (modest rate, long steps); not for high-fanout firehoses.\n *\n * Requires `FOR UPDATE SKIP LOCKED` — **MySQL 8+** or **Postgres 9.5+** (not SQLite). Run one\n * instance engine-side (`onResult`, dispatches) and one per worker process (`handle()` for its group).\n */\nexport class DbTransport implements Transport {\n private readonly exec: SqlExecutor;\n private readonly group?: string | undefined;\n private readonly tasksTable: string;\n private readonly resultsTable: string;\n private readonly runsTable: string;\n private readonly runConsumers = new Set<RunConsumer>();\n private readonly pollMs: number;\n private readonly leaseMs: number;\n private readonly batchSize: number;\n private readonly concurrency: number;\n private readonly onError: (err: unknown) => void;\n private readonly autoCreate: boolean;\n private readonly instanceId: string;\n private readonly isPg: boolean;\n\n private readonly handlers = new Map<string, StepHandler>();\n private running = true;\n private schemaReady?: Promise<void> | undefined;\n private taskLoop?: Promise<void>;\n private resultLoop?: Promise<void>;\n /** Tasks running on this instance (at most `concurrency`). */\n private readonly runningTasks = new Set<Promise<void>>();\n /** Claim tokens this instance holds, by table — every one is renewed on `renewTimer`. */\n private readonly held = new Map<string, Set<string>>();\n private renewTimer?: ReturnType<typeof setInterval> | undefined;\n private renewal?: Promise<void> | undefined;\n\n constructor(options: DbTransportOptions) {\n this.exec = options.executor;\n this.group = options.group;\n const prefix = options.prefix ?? 'durable';\n this.tasksTable = `${prefix}_transport_tasks`;\n this.resultsTable = `${prefix}_transport_results`;\n this.runsTable = `${prefix}_transport_runs`;\n this.pollMs = numberOption(options.pollMs, 500, 0);\n this.leaseMs = numberOption(options.leaseMs, 30_000, 1);\n this.batchSize = Math.floor(numberOption(options.batchSize, 10, 1));\n this.concurrency = Math.floor(numberOption(options.concurrency, 1, 1));\n this.onError = options.onError ?? ((err) => console.error('[DbTransport]', err));\n this.autoCreate = options.autoCreate ?? true;\n // Random, not time-based: two instances booted in the same millisecond must not share an id.\n this.instanceId = options.instanceId ?? `db-${randomUUID()}`;\n this.isPg = this.exec.dialect === 'postgres';\n }\n\n // ── dialect helpers ──────────────────────────────────────────────────────────────────────────\n /** Positional placeholder for param `i` (1-based): `$i` on Postgres, `?` elsewhere. */\n private ph(i: number): string {\n return this.isPg ? `$${i}` : '?';\n }\n private q(id: string): string {\n return this.exec.escapeId(id);\n }\n private now(): number {\n return Math.floor(Date.now());\n }\n\n // ── schema ───────────────────────────────────────────────────────────────────────────────────\n private ensureSchema(): Promise<void> {\n if (!this.schemaReady) {\n // A failed attempt is not cached: the next call tries again instead of failing forever.\n this.schemaReady = this.createTables().catch((err) => {\n this.schemaReady = undefined;\n throw err;\n });\n }\n return this.schemaReady;\n }\n\n /**\n * Run one `CREATE … IF NOT EXISTS`. Two instances booting on a fresh database race it, and Postgres\n * can reject the loser with a unique violation on its catalog even with `IF NOT EXISTS`; the\n * statement is simply re-run, by which point the table exists and it is a no-op.\n */\n private async createIfMissing(sql: string): Promise<void> {\n try {\n await this.exec.query(sql);\n } catch {\n await this.exec.query(sql);\n }\n }\n\n private async createTables(): Promise<void> {\n if (!this.autoCreate) return;\n const str = 'varchar(191)';\n const txt = this.isPg ? 'text' : 'longtext';\n const tasks = this.q(this.tasksTable);\n const results = this.q(this.resultsTable);\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${tasks} (\n ${this.q('step_id')} ${str} PRIMARY KEY,\n ${this.q('run_id')} ${str} NOT NULL,\n ${this.q('seq')} integer NOT NULL,\n ${this.q('name')} ${str} NOT NULL,\n ${this.q('grp')} ${str} NOT NULL,\n ${this.q('input')} ${txt},\n ${this.q('attempt')} integer NOT NULL,\n ${this.q('status')} varchar(32) NOT NULL,\n ${this.q('claimed_by')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${results} (\n ${this.q('step_id')} ${str} PRIMARY KEY,\n ${this.q('run_id')} ${str} NOT NULL,\n ${this.q('seq')} integer NOT NULL,\n ${this.q('status')} varchar(32) NOT NULL,\n ${this.q('output')} ${txt},\n ${this.q('error')} ${txt},\n ${this.q('started_at')} bigint,\n ${this.q('claimed_by')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${this.q(this.runsTable)} (\n ${this.q('run_id')} ${str} PRIMARY KEY,\n ${this.q('ns')} ${str} NOT NULL,\n ${this.q('priority')} integer NOT NULL,\n ${this.q('wake')} integer NOT NULL,\n ${this.q('claimed_by')} ${str},\n ${this.q('claim_token')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n await this.exec\n .query(\n `CREATE INDEX ${this.q(`${this.runsTable}_ns_idx`)} ON ${this.q(this.runsTable)} (${this.q('ns')}, ${this.q('priority')}, ${this.q('created_at')})`,\n )\n .catch(() => {});\n // Best-effort index for the group poll (MySQL has no CREATE INDEX IF NOT EXISTS < 8.0.13).\n await this.exec\n .query(\n `CREATE INDEX ${this.q(`${this.tasksTable}_grp_idx`)} ON ${tasks} (${this.q('grp')}, ${this.q('status')}, ${this.q('created_at')})`,\n )\n .catch(() => {});\n }\n\n // ── engine → worker ────────────────────────────────────────────────────────────────────────\n async dispatch(task: RemoteTask): Promise<void> {\n await this.ensureSchema();\n const t = this.q(this.tasksTable);\n // Idempotent: a redelivered dispatch for the same step_id is ignored (the row already exists).\n const ignore = this.isPg\n ? `INSERT INTO ${t} (...) ON CONFLICT (${this.q('step_id')}) DO NOTHING`\n : `INSERT IGNORE INTO ${t} (...)`;\n const cols = [\n 'step_id',\n 'run_id',\n 'seq',\n 'name',\n 'grp',\n 'input',\n 'attempt',\n 'status',\n 'created_at',\n ];\n const sql = ignore.replace(\n '(...)',\n `(${cols.map((c) => this.q(c)).join(', ')}) VALUES (${cols.map((_, i) => this.ph(i + 1)).join(', ')})`,\n );\n await this.exec.query(sql, [\n task.stepId,\n task.runId,\n task.seq,\n task.name,\n task.group,\n JSON.stringify(task.input ?? null),\n task.attempt,\n 'pending',\n this.now(),\n ]);\n }\n\n // ── worker → engine ────────────────────────────────────────────────────────────────────────\n handle(name: string, fn: StepHandler): void {\n if (!this.group) throw new Error('DbTransport needs a `group` to register handlers');\n this.handlers.set(name, fn);\n if (!this.taskLoop) this.taskLoop = this.loop(() => this.drainTasks(this.group as string));\n }\n\n onResult(handler: (result: StepResult) => Promise<void>): void {\n if (!this.resultLoop) this.resultLoop = this.loop(() => this.drainResults(handler));\n }\n\n onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void {\n // Not modelled; the lease/reclaim on `claimed_at` is the liveness mechanism.\n }\n\n // ── run queue (engine ↔ engine) ─────────────────────────────────────────────────────────────\n /**\n * Queue `pending` runs for whichever engine instance polls the run queue first: one row per run,\n * keyed by run id, so a run already waiting is not queued twice. A run whose row an instance holds\n * right now is released for another take, so a dispatch landing while the run's previous entry is\n * being handled is not lost when that entry is deleted. Up to {@link RUNS_INSERT_CHUNK} rows per\n * insert.\n */\n async dispatchRuns(runs: readonly RunDispatch[], opts?: RunQueueOptions): Promise<void> {\n if (runs.length === 0) return;\n await this.ensureSchema();\n // One row per run (an upsert may not touch the same row twice in one statement); a wake among\n // a run's dispatches makes its row a wake.\n const byRun = new Map<string, RunDispatch>();\n for (const run of runs) {\n if (!byRun.has(run.runId) || run.reason === 'wake') byRun.set(run.runId, run);\n }\n const unique = [...byRun.values()];\n const t = this.q(this.runsTable);\n const cols = ['run_id', 'ns', 'priority', 'wake', 'created_at'];\n const now = this.now();\n for (let at = 0; at < unique.length; at += RUNS_INSERT_CHUNK) {\n const chunk = unique.slice(at, at + RUNS_INSERT_CHUNK);\n const values = chunk\n .map((_, r) => `(${cols.map((__, c) => this.ph(r * cols.length + c + 1)).join(', ')})`)\n .join(', ');\n const insert = `INTO ${t} (${cols.map((c) => this.q(c)).join(', ')}) VALUES ${values}`;\n const release = ['claimed_by', 'claim_token', 'claimed_at']\n .map((c) => `${this.q(c)} = NULL`)\n .join(', ');\n const wake = this.q('wake');\n const sql = this.isPg\n ? `INSERT ${insert} ON CONFLICT (${this.q('run_id')}) DO UPDATE SET ${release}, ${wake} = GREATEST(${t}.${wake}, EXCLUDED.${wake})`\n : `INSERT ${insert} ON DUPLICATE KEY UPDATE ${release}, ${wake} = GREATEST(${wake}, VALUES(${wake}))`;\n await this.exec.query(\n sql,\n chunk.flatMap((run, r) => [\n run.runId,\n opts?.namespace ?? '',\n run.priority ?? 0,\n run.reason === 'wake' ? 1 : 0,\n now + r,\n ]),\n );\n }\n }\n\n /**\n * Poll the run queue, at most `opts.concurrency` runs in flight on this instance. Rows are claimed\n * with `FOR UPDATE SKIP LOCKED` (instances never take the same run), highest priority then oldest\n * first; a row is deleted once its handler settles, and its lease is renewed meanwhile, so a row is\n * re-taken only after the instance holding it went down. The returned stop takes no more rows and\n * resolves once the runs in flight settled.\n */\n onDispatchedRun(\n handler: (run: RunDispatch) => Promise<void>,\n opts: RunConsumerOptions,\n ): () => Promise<void> {\n const consumer: RunConsumer = {\n stopped: false,\n inflight: new Set(),\n slotFreed: undefined,\n loop: Promise.resolve(),\n };\n const concurrency = Math.max(1, Math.floor(opts.concurrency));\n const ns = opts.namespace ?? '';\n consumer.loop = this.consumeRuns(consumer, handler, concurrency, ns).catch((err) => {\n this.onError(err);\n });\n this.runConsumers.add(consumer);\n return () => this.stopRunConsumer(consumer);\n }\n\n private async stopRunConsumer(consumer: RunConsumer): Promise<void> {\n consumer.stopped = true;\n consumer.slotFreed?.();\n await consumer.loop;\n this.runConsumers.delete(consumer);\n }\n\n private async consumeRuns(\n consumer: RunConsumer,\n handler: (run: RunDispatch) => Promise<void>,\n concurrency: number,\n ns: string,\n ): Promise<void> {\n const renew = setInterval(\n () => void this.renewRunLeases(consumer).catch(() => undefined),\n Math.max(1_000, Math.floor(this.leaseMs / 3)),\n );\n renew.unref?.();\n const settled = new Set<Promise<unknown>>();\n try {\n while (this.running && !consumer.stopped) {\n const free = concurrency - consumer.inflight.size;\n if (free <= 0) {\n await new Promise<void>((resolve) => {\n consumer.slotFreed = resolve;\n });\n consumer.slotFreed = undefined;\n continue;\n }\n let rows: ClaimedRun[] = [];\n try {\n await this.ensureSchema();\n rows = await this.claimRuns(ns, Math.min(free, RUNS_CLAIM_MAX));\n } catch (err) {\n if (this.running && !consumer.stopped) this.onError(err);\n }\n for (const { run, token } of rows) {\n consumer.inflight.add(token);\n const done = handler(run)\n .catch(() => undefined)\n .then(() =>\n this.exec\n .query(\n `DELETE FROM ${this.q(this.runsTable)} WHERE ${this.q('claim_token')} = ${this.ph(1)}`,\n [token],\n )\n .catch(() => undefined),\n )\n .finally(() => {\n consumer.inflight.delete(token);\n settled.delete(done);\n consumer.slotFreed?.();\n });\n settled.add(done);\n }\n if (rows.length === 0) await this.sleep(this.pollMs);\n }\n await Promise.allSettled([...settled]);\n } finally {\n clearInterval(renew);\n }\n }\n\n private async claimRuns(ns: string, limit: number): Promise<ClaimedRun[]> {\n const t = this.q(this.runsTable);\n const staleBefore = this.now() - this.leaseMs;\n return this.exec.transaction(async (tx) => {\n const rows = await tx.query<RunRow>(\n `SELECT ${this.q('run_id')}, ${this.q('wake')} FROM ${t}\n WHERE ${this.q('ns')} = ${this.ph(1)}\n AND (${this.q('claimed_at')} IS NULL OR ${this.q('claimed_at')} < ${this.ph(2)})\n ORDER BY ${this.q('priority')} DESC, ${this.q('created_at')} ASC\n LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED`,\n [ns, staleBefore],\n );\n const claimed = rows.map((r) => ({\n run: {\n runId: r.run_id,\n reason: Number(r.wake) === 1 ? ('wake' as const) : ('start' as const),\n },\n token: globalThis.crypto.randomUUID(),\n }));\n const now = this.now();\n for (const {\n run: { runId },\n token,\n } of claimed) {\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_by')} = ${this.ph(1)}, ${this.q('claim_token')} = ${this.ph(2)}, ${this.q('claimed_at')} = ${this.ph(3)}\n WHERE ${this.q('run_id')} = ${this.ph(4)}`,\n [this.instanceId, token, now, runId],\n );\n }\n return claimed;\n });\n }\n\n /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */\n private async renewRunLeases(consumer: RunConsumer): Promise<void> {\n const tokens = [...consumer.inflight];\n if (tokens.length === 0) return;\n await this.exec.query(\n `UPDATE ${this.q(this.runsTable)} SET ${this.q('claimed_at')} = ${this.ph(1)}\n WHERE ${this.q('claim_token')} IN (${tokens.map((_, i) => this.ph(i + 2)).join(', ')})`,\n [this.now(), ...tokens],\n );\n }\n\n // ── polling ──────────────────────────────────────────────────────────────────────────────────\n /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */\n private async loop(tick: () => Promise<number>): Promise<void> {\n while (this.running) {\n let processed = 0;\n try {\n await this.ensureSchema();\n processed = await tick();\n } catch (err) {\n if (this.running) this.onError(err);\n }\n if (processed === 0 && this.running) await this.sleep(this.pollMs);\n }\n }\n\n /**\n * One task-loop round: claim as many rows as there are free slots (never more — a claimed row that\n * isn't running is one an idle sibling can't run), and start each. With every slot busy, wait for\n * one to free instead of polling.\n */\n private async drainTasks(group: string): Promise<number> {\n const free = this.concurrency - this.runningTasks.size;\n if (free <= 0) {\n await Promise.race(this.runningTasks);\n return 1;\n }\n const { rows, token } = await this.claim<TaskRow>(\n this.tasksTable,\n Math.min(free, this.batchSize),\n `${this.q('grp')} = ${this.ph(1)}`,\n [group],\n );\n if (rows.length === 0) return 0;\n this.hold(this.tasksTable, token);\n let left = rows.length;\n for (const row of rows) {\n const run = this.runTask(row, group, token).finally(() => {\n this.runningTasks.delete(run);\n left -= 1;\n if (left === 0) this.release(this.tasksTable, token);\n });\n this.runningTasks.add(run);\n }\n return rows.length;\n }\n\n /**\n * Run one claimed task and settle it — only while this instance still holds the claim: the claim is\n * re-checked before running, and the task row is deleted and its result written in ONE transaction,\n * conditional on the claim token, so an instance whose claim was taken over neither deletes the new\n * holder's row nor publishes a second result.\n */\n private async runTask(row: TaskRow, group: string, token: string): Promise<void> {\n try {\n if (!(await this.stillHolds(row.step_id, token))) {\n this.onError(\n new Error(\n `[DbTransport] lost the claim on task ${row.step_id} before running it — another instance took it over; not running it here`,\n ),\n );\n return;\n }\n const task: RemoteTask = {\n runId: row.run_id,\n seq: Number(row.seq),\n stepId: row.step_id,\n name: row.name,\n group,\n input: row.input == null ? undefined : JSON.parse(row.input),\n attempt: Number(row.attempt),\n };\n const result = await runStepHandler(task, this.handlers.get(task.name));\n if (!(await this.settleTask(task.stepId, token, result))) {\n this.onError(\n new Error(\n `[DbTransport] lost the claim on task ${task.stepId} while running it (this instance went silent past leaseMs) — another instance took it over and may run it too; this run's result was dropped. Raise leaseMs if steps block the event loop`,\n ),\n );\n }\n } catch (err) {\n // A database error settling the row (or a malformed row): it stays claimed, stops being\n // renewed, and is reclaimed after the lease — at-least-once, like a crash.\n this.onError(err);\n }\n }\n\n /** Whether the claim on `stepId` is still `token`'s (re-stamping it if so). */\n private async stillHolds(stepId: string, token: string): Promise<boolean> {\n const t = this.q(this.tasksTable);\n const rows = await this.exec.transaction(async (tx) => {\n const held = await tx.query<{ step_id: string }>(\n `SELECT ${this.q('step_id')} FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)} FOR UPDATE`,\n [stepId, token],\n );\n if (held.length > 0) {\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_at')} = ${this.ph(1)} WHERE ${this.q('step_id')} = ${this.ph(2)} AND ${this.q('claimed_by')} = ${this.ph(3)}`,\n [this.now(), stepId, token],\n );\n }\n return held;\n });\n return rows.length > 0;\n }\n\n /** Delete the task row and publish its result in ONE transaction, only while `token` holds it. */\n private async settleTask(stepId: string, token: string, result: StepResult): Promise<boolean> {\n const t = this.q(this.tasksTable);\n return this.exec.transaction(async (tx) => {\n const held = await tx.query<{ step_id: string }>(\n `SELECT ${this.q('step_id')} FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)} FOR UPDATE`,\n [stepId, token],\n );\n if (held.length === 0) return false;\n await tx.query(\n `DELETE FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)}`,\n [stepId, token],\n );\n await this.insertResult(result, tx);\n return true;\n });\n }\n\n /**\n * Claim a batch of results, deliver each to the engine, and delete it — only after its handler ran\n * (at-least-once), and only while this round still holds the claim (a newer result for the same\n * step that replaced the row resets the claim, so it is delivered next instead of deleted). The\n * batch's claim is renewed until it is done. A throwing handler is reported and its row left for\n * re-delivery after the lease; the rest of the batch continues.\n */\n private async drainResults(handler: (result: StepResult) => Promise<void>): Promise<number> {\n const { rows, token } = await this.claim<ResultRow>(\n this.resultsTable,\n this.batchSize,\n '1 = 1',\n [],\n );\n if (rows.length === 0) return 0;\n this.hold(this.resultsTable, token);\n try {\n for (const row of rows) {\n if (!this.running) break;\n try {\n const result: StepResult = {\n runId: row.run_id,\n seq: Number(row.seq),\n stepId: row.step_id,\n status: row.status as StepResult['status'],\n output: row.output == null ? undefined : JSON.parse(row.output),\n error: row.error == null ? undefined : JSON.parse(row.error),\n startedAt: row.started_at == null ? undefined : Number(row.started_at),\n };\n await handler(result);\n await this.exec.query(\n `DELETE FROM ${this.q(this.resultsTable)} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)}`,\n [row.step_id, token],\n );\n } catch (err) {\n this.onError(err);\n }\n }\n } finally {\n this.release(this.resultsTable, token);\n }\n return rows.length;\n }\n\n /**\n * Atomically claim up to `limit` un-leased rows matching `where` and stamp them with a claim token\n * unique to this round (`<instanceId>:<uuid>`). `SELECT … FOR UPDATE SKIP LOCKED` inside the txn\n * means concurrent instances skip each other's locked rows instead of blocking, so no row is\n * claimed twice; the token is what every later delete/settle is conditional on.\n */\n private async claim<T extends { step_id: string }>(\n table: string,\n limit: number,\n where: string,\n whereParams: unknown[],\n ): Promise<{ rows: T[]; token: string }> {\n const t = this.q(table);\n const staleBefore = this.now() - this.leaseMs;\n const token = `${this.instanceId}:${randomUUID()}`;\n const rows = await this.exec.transaction(async (tx) => {\n const leaseClause = `(${this.q('claimed_at')} IS NULL OR ${this.q('claimed_at')} < ${this.ph(whereParams.length + 1)})`;\n const found = await tx.query<T>(\n `SELECT * FROM ${t} WHERE ${where} AND ${leaseClause}\n ORDER BY ${this.q('created_at')} ASC LIMIT ${Math.max(1, Math.floor(limit))} FOR UPDATE SKIP LOCKED`,\n [...whereParams, staleBefore],\n );\n if (found.length > 0) {\n const ids = found.map((r) => r.step_id);\n const placeholders = ids.map((_, i) => this.ph(i + 3)).join(', ');\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_by')} = ${this.ph(1)}, ${this.q('claimed_at')} = ${this.ph(2)}\n WHERE ${this.q('step_id')} IN (${placeholders})`,\n [token, this.now(), ...ids],\n );\n }\n return found;\n });\n return { rows, token };\n }\n\n // ── claim renewal: every claim held, not only the row being run ─────────────────────────────\n private hold(table: string, token: string): void {\n let tokens = this.held.get(table);\n if (!tokens) {\n tokens = new Set();\n this.held.set(table, tokens);\n }\n tokens.add(token);\n if (this.renewTimer) return;\n const intervalMs = Math.max(10, Math.floor(this.leaseMs / 3));\n this.renewTimer = setInterval(() => {\n if (this.renewal) return; // a slow database never stacks renewal rounds\n const round = this.renewHeld()\n .catch((err) => this.onError(err))\n .finally(() => {\n if (this.renewal === round) this.renewal = undefined;\n });\n this.renewal = round;\n }, intervalMs);\n this.renewTimer.unref?.();\n }\n\n private release(table: string, token: string): void {\n const tokens = this.held.get(table);\n tokens?.delete(token);\n if (tokens?.size === 0) this.held.delete(table);\n if (this.held.size === 0 && this.renewTimer) {\n clearInterval(this.renewTimer);\n this.renewTimer = undefined;\n }\n }\n\n /** Re-stamp `claimed_at` on every row still claimed under a token this instance holds. */\n private async renewHeld(): Promise<void> {\n for (const [table, tokens] of this.held) {\n if (tokens.size === 0) continue;\n const list = [...tokens];\n const placeholders = list.map((_, i) => this.ph(i + 2)).join(', ');\n await this.exec.query(\n `UPDATE ${this.q(table)} SET ${this.q('claimed_at')} = ${this.ph(1)} WHERE ${this.q('claimed_by')} IN (${placeholders})`,\n [this.now(), ...list],\n );\n }\n }\n\n /**\n * Write a result row. A result already waiting for the same step (an earlier attempt's, not yet\n * deleted by the engine) is REPLACED and its claim reset, never kept: `step_id` is stable across\n * attempts, so keeping the old row would silently drop a retry's result.\n */\n private async insertResult(result: StepResult, tx: SqlTx = this.exec): Promise<void> {\n const t = this.q(this.resultsTable);\n const cols = [\n 'step_id',\n 'run_id',\n 'seq',\n 'status',\n 'output',\n 'error',\n 'started_at',\n 'created_at',\n ];\n const replace = ['run_id', 'seq', 'status', 'output', 'error', 'started_at', 'created_at'];\n const values = `(${cols.map((c) => this.q(c)).join(', ')}) VALUES (${cols.map((_, i) => this.ph(i + 1)).join(', ')})`;\n const sql = this.isPg\n ? `INSERT INTO ${t} ${values} ON CONFLICT (${this.q('step_id')}) DO UPDATE SET ${[\n ...replace.map((c) => `${this.q(c)} = EXCLUDED.${this.q(c)}`),\n `${this.q('claimed_by')} = NULL`,\n `${this.q('claimed_at')} = NULL`,\n ].join(', ')}`\n : `INSERT INTO ${t} ${values} ON DUPLICATE KEY UPDATE ${[\n ...replace.map((c) => `${this.q(c)} = VALUES(${this.q(c)})`),\n `${this.q('claimed_by')} = NULL`,\n `${this.q('claimed_at')} = NULL`,\n ].join(', ')}`;\n await tx.query(sql, [\n result.stepId,\n result.runId,\n result.seq,\n result.status,\n result.output === undefined ? null : JSON.stringify(result.output),\n result.error === undefined ? null : JSON.stringify(result.error),\n result.startedAt ?? null,\n this.now(),\n ]);\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n }\n\n /** Stop the pollers and wait for the current ticks to settle. Does not close the shared DataSource. */\n async close(): Promise<void> {\n this.running = false;\n await Promise.allSettled([\n this.taskLoop,\n this.resultLoop,\n ...[...this.runConsumers].map((c) => this.stopRunConsumer(c)),\n ]);\n // Let running tasks settle (their claims keep being renewed until they do).\n await Promise.allSettled([...this.runningTasks]);\n if (this.renewTimer) clearInterval(this.renewTimer);\n this.renewTimer = undefined;\n await this.renewal;\n }\n}\n","/**\n * The tiny SQL surface `DbTransport` needs, so it rides **whatever ORM/connection the app already\n * has** instead of forcing a specific one. Implement it for your ORM (adapters for TypeORM and\n * MikroORM ship below) and hand it to `new DbTransport({ executor })`. Mirrors how the durable\n * *store* is ORM-pluggable (store-typeorm / store-mikro-orm / …).\n */\nexport interface SqlExecutor {\n /** Drives placeholder style (`$n` vs `?`) and a couple of DDL type choices. */\n readonly dialect: 'mysql' | 'postgres';\n /** Quote/escape an identifier (table/column name) for this dialect. */\n escapeId(id: string): string;\n /** Run a statement outside a transaction. */\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n /** Run `fn` inside a transaction — the claim uses `FOR UPDATE SKIP LOCKED` within it. */\n transaction<T>(fn: (tx: SqlTx) => Promise<T>): Promise<T>;\n}\n\nexport interface SqlTx {\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n}\n\n// ── TypeORM ──────────────────────────────────────────────────────────────────────────────────────\n\n/** Structural slice of a TypeORM `DataSource` — avoids a hard dependency on typeorm. */\ninterface TypeOrmDataSourceLike {\n options: { type: string };\n driver: { escape(id: string): string };\n query(sql: string, params?: unknown[]): Promise<unknown>;\n createQueryRunner(): {\n connect(): Promise<void>;\n startTransaction(): Promise<void>;\n commitTransaction(): Promise<void>;\n rollbackTransaction(): Promise<void>;\n release(): Promise<void>;\n query(sql: string, params?: unknown[]): Promise<unknown>;\n };\n}\n\n/** Build an executor from a TypeORM `DataSource` (e.g. the one the durable store already uses). */\nexport function typeOrmExecutor(ds: TypeOrmDataSourceLike): SqlExecutor {\n return {\n dialect: /postgres/.test(String(ds.options.type)) ? 'postgres' : 'mysql',\n escapeId: (id) => ds.driver.escape(id),\n query: <T>(sql: string, params?: unknown[]) => ds.query(sql, params) as Promise<T[]>,\n transaction: async <T>(fn: (tx: SqlTx) => Promise<T>) => {\n const qr = ds.createQueryRunner();\n await qr.connect();\n await qr.startTransaction();\n try {\n const result = await fn({\n query: <U>(sql: string, params?: unknown[]) => qr.query(sql, params) as Promise<U[]>,\n });\n await qr.commitTransaction();\n return result;\n } catch (err) {\n await qr.rollbackTransaction();\n throw err;\n } finally {\n await qr.release();\n }\n },\n };\n}\n\n// ── MikroORM ─────────────────────────────────────────────────────────────────────────────────────\n\n/** Structural slice of a MikroORM `EntityManager` — avoids a hard dependency on @mikro-orm/core. */\ninterface MikroOrmEmLike {\n getPlatform(): { constructor: { name: string }; quoteIdentifier(id: string): string };\n getConnection(): {\n execute(sql: string, params?: unknown[], method?: 'all', ctx?: unknown): Promise<unknown>;\n };\n getTransactionContext?(): unknown;\n transactional<T>(cb: (em: MikroOrmEmLike) => Promise<T>): Promise<T>;\n}\n\n/**\n * Build an executor from a MikroORM `EntityManager` — i.e. **the app's own configured ORM**. Runs\n * raw SQL through `em.getConnection().execute(...)` and wraps the claim in `em.transactional(...)`,\n * threading the transaction context so `FOR UPDATE SKIP LOCKED` locks within the tx.\n */\nexport function mikroOrmExecutor(em: MikroOrmEmLike): SqlExecutor {\n const platform = em.getPlatform();\n return {\n dialect: /postgre/i.test(platform.constructor.name) ? 'postgres' : 'mysql',\n escapeId: (id) => platform.quoteIdentifier(id),\n query: <T>(sql: string, params?: unknown[]) =>\n em.getConnection().execute(sql, params ?? [], 'all') as Promise<T[]>,\n transaction: <T>(fn: (tx: SqlTx) => Promise<T>) =>\n em.transactional((txEm) =>\n fn({\n query: <U>(sql: string, params?: unknown[]) =>\n txEm\n .getConnection()\n .execute(sql, params ?? [], 'all', txEm.getTransactionContext?.()) as Promise<U[]>,\n }),\n ),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACAA,yBAA2B;AAC3B,iCAUO;;;AC4BA,SAASA,gBAAgBC,IAAyB;AACvD,SAAO;IACLC,SAAS,WAAWC,KAAKC,OAAOH,GAAGI,QAAQC,IAAI,CAAA,IAAK,aAAa;IACjEC,UAAU,wBAACC,OAAOP,GAAGQ,OAAOC,OAAOF,EAAAA,GAAzB;IACVG,OAAO,wBAAIC,KAAaC,WAAuBZ,GAAGU,MAAMC,KAAKC,MAAAA,GAAtD;IACPC,aAAa,8BAAUC,OAAAA;AACrB,YAAMC,KAAKf,GAAGgB,kBAAiB;AAC/B,YAAMD,GAAG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AKf;QAAcqD,IAAI,CAACC,MAAM,KAAKsD,gBAAgBtD,CAAAA,CAAAA;KAC3D;AAED,UAAMgD,QAAQsB,WAAW;SAAI,KAAK5G;KAAa;AAC/C,QAAI,KAAKE,WAAY2G,eAAc,KAAK3G,UAAU;AAClD,SAAKA,aAAa3B;AAClB,UAAM,KAAK4B;EACb;AACF;","names":["typeOrmExecutor","ds","dialect","test","String","options","type","escapeId","id","driver","escape","query","sql","params","transaction","fn","qr","createQueryRunner","connect","startTransaction","result","commitTransaction","err","rollbackTransaction","release","mikroOrmExecutor","em","platform","getPlatform","name","quoteIdentifier","getConnection","execute","transactional","txEm","getTransactionContext","RUNS_INSERT_CHUNK","RUNS_CLAIM_MAX","numberOption","value","fallback","min","undefined","Number","isFinite","DbTransport","exec","group","tasksTable","resultsTable","runsTable","runConsumers","Set","pollMs","leaseMs","batchSize","concurrency","onError","autoCreate","instanceId","isPg","handlers","Map","running","schemaReady","taskLoop","resultLoop","runningTasks","held","renewTimer","renewal","options","executor","prefix","Math","floor","err","console","error","randomUUID","dialect","ph","i","q","id","escapeId","now","Date","ensureSchema","createTables","catch","createIfMissing","sql","query","str","txt","tasks","results","dispatch","task","t","ignore","cols","replace","map","c","join","_","stepId","runId","seq","name","JSON","stringify","input","attempt","handle","fn","Error","set","loop","drainTasks","onResult","handler","drainResults","onHeartbeat","_handler","dispatchRuns","runs","opts","length","byRun","run","has","reason","unique","values","at","chunk","slice","r","__","insert","release","wake","flatMap","namespace","priority","onDispatchedRun","consumer","stopped","inflight","slotFreed","Promise","resolve","max","ns","consumeRuns","add","stopRunConsumer","delete","renew","setInterval","renewRunLeases","unref","settled","free","size","rows","claimRuns","token","done","then","finally","sleep","allSettled","clearInterval","limit","staleBefore","transaction","tx","claimed","run_id","globalThis","crypto","tokens","tick","processed","race","claim","hold","left","row","runTask","stillHolds","step_id","parse","result","runStepHandler","get","settleTask","insertResult","status","output","startedAt","started_at","table","where","whereParams","leaseClause","found","ids","placeholders","intervalMs","round","renewHeld","list","ms","setTimeout","close"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Transport, RemoteTask, StepHandler, StepResult, Heartbeat } from '@dudousxd/nestjs-durable-core';
1
+ import { Transport, RemoteTask, StepHandler, StepResult, Heartbeat, RunDispatch, RunQueueOptions, RunConsumerOptions } from '@dudousxd/nestjs-durable-core';
2
2
 
3
3
  /**
4
4
  * The tiny SQL surface `DbTransport` needs, so it rides **whatever ORM/connection the app already
@@ -70,7 +70,10 @@ interface DbTransportOptions {
70
70
  executor: SqlExecutor;
71
71
  /** The worker group this instance serves. Required to register `handle()` consumers. */
72
72
  group?: string;
73
- /** Table-name prefix. Tables: `${prefix}_transport_tasks` / `${prefix}_transport_results`. Default `durable`. */
73
+ /**
74
+ * Table-name prefix. Tables: `${prefix}_transport_tasks` / `${prefix}_transport_results`, and
75
+ * `${prefix}_transport_runs` for the run queue. Default `durable`.
76
+ */
74
77
  prefix?: string;
75
78
  /** Poll interval in ms when a queue is empty. Default 500. */
76
79
  pollMs?: number;
@@ -95,7 +98,7 @@ interface DbTransportOptions {
95
98
  * re-delivered after the lease), a lost claim. Default `console.error`.
96
99
  */
97
100
  onError?: (err: unknown) => void;
98
- /** Create the two tables on first use if missing. Default true. */
101
+ /** Create the tables on first use if missing. Default true. */
99
102
  autoCreate?: boolean;
100
103
  /** Identifies this instance in `claimed_by` (for debugging). Defaults to a random id. */
101
104
  instanceId?: string;
@@ -118,6 +121,8 @@ declare class DbTransport implements Transport {
118
121
  private readonly group?;
119
122
  private readonly tasksTable;
120
123
  private readonly resultsTable;
124
+ private readonly runsTable;
125
+ private readonly runConsumers;
121
126
  private readonly pollMs;
122
127
  private readonly leaseMs;
123
128
  private readonly batchSize;
@@ -154,6 +159,27 @@ declare class DbTransport implements Transport {
154
159
  handle(name: string, fn: StepHandler): void;
155
160
  onResult(handler: (result: StepResult) => Promise<void>): void;
156
161
  onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void;
162
+ /**
163
+ * Queue `pending` runs for whichever engine instance polls the run queue first: one row per run,
164
+ * keyed by run id, so a run already waiting is not queued twice. A run whose row an instance holds
165
+ * right now is released for another take, so a dispatch landing while the run's previous entry is
166
+ * being handled is not lost when that entry is deleted. Up to {@link RUNS_INSERT_CHUNK} rows per
167
+ * insert.
168
+ */
169
+ dispatchRuns(runs: readonly RunDispatch[], opts?: RunQueueOptions): Promise<void>;
170
+ /**
171
+ * Poll the run queue, at most `opts.concurrency` runs in flight on this instance. Rows are claimed
172
+ * with `FOR UPDATE SKIP LOCKED` (instances never take the same run), highest priority then oldest
173
+ * first; a row is deleted once its handler settles, and its lease is renewed meanwhile, so a row is
174
+ * re-taken only after the instance holding it went down. The returned stop takes no more rows and
175
+ * resolves once the runs in flight settled.
176
+ */
177
+ onDispatchedRun(handler: (run: RunDispatch) => Promise<void>, opts: RunConsumerOptions): () => Promise<void>;
178
+ private stopRunConsumer;
179
+ private consumeRuns;
180
+ private claimRuns;
181
+ /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */
182
+ private renewRunLeases;
157
183
  /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */
158
184
  private loop;
159
185
  /**
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Transport, RemoteTask, StepHandler, StepResult, Heartbeat } from '@dudousxd/nestjs-durable-core';
1
+ import { Transport, RemoteTask, StepHandler, StepResult, Heartbeat, RunDispatch, RunQueueOptions, RunConsumerOptions } from '@dudousxd/nestjs-durable-core';
2
2
 
3
3
  /**
4
4
  * The tiny SQL surface `DbTransport` needs, so it rides **whatever ORM/connection the app already
@@ -70,7 +70,10 @@ interface DbTransportOptions {
70
70
  executor: SqlExecutor;
71
71
  /** The worker group this instance serves. Required to register `handle()` consumers. */
72
72
  group?: string;
73
- /** Table-name prefix. Tables: `${prefix}_transport_tasks` / `${prefix}_transport_results`. Default `durable`. */
73
+ /**
74
+ * Table-name prefix. Tables: `${prefix}_transport_tasks` / `${prefix}_transport_results`, and
75
+ * `${prefix}_transport_runs` for the run queue. Default `durable`.
76
+ */
74
77
  prefix?: string;
75
78
  /** Poll interval in ms when a queue is empty. Default 500. */
76
79
  pollMs?: number;
@@ -95,7 +98,7 @@ interface DbTransportOptions {
95
98
  * re-delivered after the lease), a lost claim. Default `console.error`.
96
99
  */
97
100
  onError?: (err: unknown) => void;
98
- /** Create the two tables on first use if missing. Default true. */
101
+ /** Create the tables on first use if missing. Default true. */
99
102
  autoCreate?: boolean;
100
103
  /** Identifies this instance in `claimed_by` (for debugging). Defaults to a random id. */
101
104
  instanceId?: string;
@@ -118,6 +121,8 @@ declare class DbTransport implements Transport {
118
121
  private readonly group?;
119
122
  private readonly tasksTable;
120
123
  private readonly resultsTable;
124
+ private readonly runsTable;
125
+ private readonly runConsumers;
121
126
  private readonly pollMs;
122
127
  private readonly leaseMs;
123
128
  private readonly batchSize;
@@ -154,6 +159,27 @@ declare class DbTransport implements Transport {
154
159
  handle(name: string, fn: StepHandler): void;
155
160
  onResult(handler: (result: StepResult) => Promise<void>): void;
156
161
  onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void;
162
+ /**
163
+ * Queue `pending` runs for whichever engine instance polls the run queue first: one row per run,
164
+ * keyed by run id, so a run already waiting is not queued twice. A run whose row an instance holds
165
+ * right now is released for another take, so a dispatch landing while the run's previous entry is
166
+ * being handled is not lost when that entry is deleted. Up to {@link RUNS_INSERT_CHUNK} rows per
167
+ * insert.
168
+ */
169
+ dispatchRuns(runs: readonly RunDispatch[], opts?: RunQueueOptions): Promise<void>;
170
+ /**
171
+ * Poll the run queue, at most `opts.concurrency` runs in flight on this instance. Rows are claimed
172
+ * with `FOR UPDATE SKIP LOCKED` (instances never take the same run), highest priority then oldest
173
+ * first; a row is deleted once its handler settles, and its lease is renewed meanwhile, so a row is
174
+ * re-taken only after the instance holding it went down. The returned stop takes no more rows and
175
+ * resolves once the runs in flight settled.
176
+ */
177
+ onDispatchedRun(handler: (run: RunDispatch) => Promise<void>, opts: RunConsumerOptions): () => Promise<void>;
178
+ private stopRunConsumer;
179
+ private consumeRuns;
180
+ private claimRuns;
181
+ /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */
182
+ private renewRunLeases;
157
183
  /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */
158
184
  private loop;
159
185
  /**
package/dist/index.js CHANGED
@@ -45,6 +45,8 @@ function mikroOrmExecutor(em) {
45
45
  __name(mikroOrmExecutor, "mikroOrmExecutor");
46
46
 
47
47
  // src/db-transport.ts
48
+ var RUNS_INSERT_CHUNK = 500;
49
+ var RUNS_CLAIM_MAX = 50;
48
50
  function numberOption(value, fallback, min) {
49
51
  return value !== void 0 && Number.isFinite(value) && value >= min ? value : fallback;
50
52
  }
@@ -57,6 +59,8 @@ var DbTransport = class {
57
59
  group;
58
60
  tasksTable;
59
61
  resultsTable;
62
+ runsTable;
63
+ runConsumers = /* @__PURE__ */ new Set();
60
64
  pollMs;
61
65
  leaseMs;
62
66
  batchSize;
@@ -82,6 +86,7 @@ var DbTransport = class {
82
86
  const prefix = options.prefix ?? "durable";
83
87
  this.tasksTable = `${prefix}_transport_tasks`;
84
88
  this.resultsTable = `${prefix}_transport_results`;
89
+ this.runsTable = `${prefix}_transport_runs`;
85
90
  this.pollMs = numberOption(options.pollMs, 500, 0);
86
91
  this.leaseMs = numberOption(options.leaseMs, 3e4, 1);
87
92
  this.batchSize = Math.floor(numberOption(options.batchSize, 10, 1));
@@ -155,6 +160,18 @@ var DbTransport = class {
155
160
  ${this.q("claimed_at")} bigint,
156
161
  ${this.q("created_at")} bigint NOT NULL
157
162
  )`);
163
+ await this.createIfMissing(`CREATE TABLE IF NOT EXISTS ${this.q(this.runsTable)} (
164
+ ${this.q("run_id")} ${str} PRIMARY KEY,
165
+ ${this.q("ns")} ${str} NOT NULL,
166
+ ${this.q("priority")} integer NOT NULL,
167
+ ${this.q("wake")} integer NOT NULL,
168
+ ${this.q("claimed_by")} ${str},
169
+ ${this.q("claim_token")} ${str},
170
+ ${this.q("claimed_at")} bigint,
171
+ ${this.q("created_at")} bigint NOT NULL
172
+ )`);
173
+ await this.exec.query(`CREATE INDEX ${this.q(`${this.runsTable}_ns_idx`)} ON ${this.q(this.runsTable)} (${this.q("ns")}, ${this.q("priority")}, ${this.q("created_at")})`).catch(() => {
174
+ });
158
175
  await this.exec.query(`CREATE INDEX ${this.q(`${this.tasksTable}_grp_idx`)} ON ${tasks} (${this.q("grp")}, ${this.q("status")}, ${this.q("created_at")})`).catch(() => {
159
176
  });
160
177
  }
@@ -198,6 +215,166 @@ var DbTransport = class {
198
215
  }
199
216
  onHeartbeat(_handler) {
200
217
  }
218
+ // ── run queue (engine ↔ engine) ─────────────────────────────────────────────────────────────
219
+ /**
220
+ * Queue `pending` runs for whichever engine instance polls the run queue first: one row per run,
221
+ * keyed by run id, so a run already waiting is not queued twice. A run whose row an instance holds
222
+ * right now is released for another take, so a dispatch landing while the run's previous entry is
223
+ * being handled is not lost when that entry is deleted. Up to {@link RUNS_INSERT_CHUNK} rows per
224
+ * insert.
225
+ */
226
+ async dispatchRuns(runs, opts) {
227
+ if (runs.length === 0) return;
228
+ await this.ensureSchema();
229
+ const byRun = /* @__PURE__ */ new Map();
230
+ for (const run of runs) {
231
+ if (!byRun.has(run.runId) || run.reason === "wake") byRun.set(run.runId, run);
232
+ }
233
+ const unique = [
234
+ ...byRun.values()
235
+ ];
236
+ const t = this.q(this.runsTable);
237
+ const cols = [
238
+ "run_id",
239
+ "ns",
240
+ "priority",
241
+ "wake",
242
+ "created_at"
243
+ ];
244
+ const now = this.now();
245
+ for (let at = 0; at < unique.length; at += RUNS_INSERT_CHUNK) {
246
+ const chunk = unique.slice(at, at + RUNS_INSERT_CHUNK);
247
+ const values = chunk.map((_, r) => `(${cols.map((__, c) => this.ph(r * cols.length + c + 1)).join(", ")})`).join(", ");
248
+ const insert = `INTO ${t} (${cols.map((c) => this.q(c)).join(", ")}) VALUES ${values}`;
249
+ const release = [
250
+ "claimed_by",
251
+ "claim_token",
252
+ "claimed_at"
253
+ ].map((c) => `${this.q(c)} = NULL`).join(", ");
254
+ const wake = this.q("wake");
255
+ const sql = this.isPg ? `INSERT ${insert} ON CONFLICT (${this.q("run_id")}) DO UPDATE SET ${release}, ${wake} = GREATEST(${t}.${wake}, EXCLUDED.${wake})` : `INSERT ${insert} ON DUPLICATE KEY UPDATE ${release}, ${wake} = GREATEST(${wake}, VALUES(${wake}))`;
256
+ await this.exec.query(sql, chunk.flatMap((run, r) => [
257
+ run.runId,
258
+ opts?.namespace ?? "",
259
+ run.priority ?? 0,
260
+ run.reason === "wake" ? 1 : 0,
261
+ now + r
262
+ ]));
263
+ }
264
+ }
265
+ /**
266
+ * Poll the run queue, at most `opts.concurrency` runs in flight on this instance. Rows are claimed
267
+ * with `FOR UPDATE SKIP LOCKED` (instances never take the same run), highest priority then oldest
268
+ * first; a row is deleted once its handler settles, and its lease is renewed meanwhile, so a row is
269
+ * re-taken only after the instance holding it went down. The returned stop takes no more rows and
270
+ * resolves once the runs in flight settled.
271
+ */
272
+ onDispatchedRun(handler, opts) {
273
+ const consumer = {
274
+ stopped: false,
275
+ inflight: /* @__PURE__ */ new Set(),
276
+ slotFreed: void 0,
277
+ loop: Promise.resolve()
278
+ };
279
+ const concurrency = Math.max(1, Math.floor(opts.concurrency));
280
+ const ns = opts.namespace ?? "";
281
+ consumer.loop = this.consumeRuns(consumer, handler, concurrency, ns).catch((err) => {
282
+ this.onError(err);
283
+ });
284
+ this.runConsumers.add(consumer);
285
+ return () => this.stopRunConsumer(consumer);
286
+ }
287
+ async stopRunConsumer(consumer) {
288
+ consumer.stopped = true;
289
+ consumer.slotFreed?.();
290
+ await consumer.loop;
291
+ this.runConsumers.delete(consumer);
292
+ }
293
+ async consumeRuns(consumer, handler, concurrency, ns) {
294
+ const renew = setInterval(() => void this.renewRunLeases(consumer).catch(() => void 0), Math.max(1e3, Math.floor(this.leaseMs / 3)));
295
+ renew.unref?.();
296
+ const settled = /* @__PURE__ */ new Set();
297
+ try {
298
+ while (this.running && !consumer.stopped) {
299
+ const free = concurrency - consumer.inflight.size;
300
+ if (free <= 0) {
301
+ await new Promise((resolve) => {
302
+ consumer.slotFreed = resolve;
303
+ });
304
+ consumer.slotFreed = void 0;
305
+ continue;
306
+ }
307
+ let rows = [];
308
+ try {
309
+ await this.ensureSchema();
310
+ rows = await this.claimRuns(ns, Math.min(free, RUNS_CLAIM_MAX));
311
+ } catch (err) {
312
+ if (this.running && !consumer.stopped) this.onError(err);
313
+ }
314
+ for (const { run, token } of rows) {
315
+ consumer.inflight.add(token);
316
+ const done = handler(run).catch(() => void 0).then(() => this.exec.query(`DELETE FROM ${this.q(this.runsTable)} WHERE ${this.q("claim_token")} = ${this.ph(1)}`, [
317
+ token
318
+ ]).catch(() => void 0)).finally(() => {
319
+ consumer.inflight.delete(token);
320
+ settled.delete(done);
321
+ consumer.slotFreed?.();
322
+ });
323
+ settled.add(done);
324
+ }
325
+ if (rows.length === 0) await this.sleep(this.pollMs);
326
+ }
327
+ await Promise.allSettled([
328
+ ...settled
329
+ ]);
330
+ } finally {
331
+ clearInterval(renew);
332
+ }
333
+ }
334
+ async claimRuns(ns, limit) {
335
+ const t = this.q(this.runsTable);
336
+ const staleBefore = this.now() - this.leaseMs;
337
+ return this.exec.transaction(async (tx) => {
338
+ const rows = await tx.query(`SELECT ${this.q("run_id")}, ${this.q("wake")} FROM ${t}
339
+ WHERE ${this.q("ns")} = ${this.ph(1)}
340
+ AND (${this.q("claimed_at")} IS NULL OR ${this.q("claimed_at")} < ${this.ph(2)})
341
+ ORDER BY ${this.q("priority")} DESC, ${this.q("created_at")} ASC
342
+ LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED`, [
343
+ ns,
344
+ staleBefore
345
+ ]);
346
+ const claimed = rows.map((r) => ({
347
+ run: {
348
+ runId: r.run_id,
349
+ reason: Number(r.wake) === 1 ? "wake" : "start"
350
+ },
351
+ token: globalThis.crypto.randomUUID()
352
+ }));
353
+ const now = this.now();
354
+ for (const { run: { runId }, token } of claimed) {
355
+ await tx.query(`UPDATE ${t} SET ${this.q("claimed_by")} = ${this.ph(1)}, ${this.q("claim_token")} = ${this.ph(2)}, ${this.q("claimed_at")} = ${this.ph(3)}
356
+ WHERE ${this.q("run_id")} = ${this.ph(4)}`, [
357
+ this.instanceId,
358
+ token,
359
+ now,
360
+ runId
361
+ ]);
362
+ }
363
+ return claimed;
364
+ });
365
+ }
366
+ /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */
367
+ async renewRunLeases(consumer) {
368
+ const tokens = [
369
+ ...consumer.inflight
370
+ ];
371
+ if (tokens.length === 0) return;
372
+ await this.exec.query(`UPDATE ${this.q(this.runsTable)} SET ${this.q("claimed_at")} = ${this.ph(1)}
373
+ WHERE ${this.q("claim_token")} IN (${tokens.map((_, i) => this.ph(i + 2)).join(", ")})`, [
374
+ this.now(),
375
+ ...tokens
376
+ ]);
377
+ }
201
378
  // ── polling ──────────────────────────────────────────────────────────────────────────────────
202
379
  /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */
203
380
  async loop(tick) {
@@ -473,7 +650,10 @@ var DbTransport = class {
473
650
  this.running = false;
474
651
  await Promise.allSettled([
475
652
  this.taskLoop,
476
- this.resultLoop
653
+ this.resultLoop,
654
+ ...[
655
+ ...this.runConsumers
656
+ ].map((c) => this.stopRunConsumer(c))
477
657
  ]);
478
658
  await Promise.allSettled([
479
659
  ...this.runningTasks
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/db-transport.ts","../src/executors.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport {\n type Heartbeat,\n type RemoteTask,\n type StepHandler,\n type StepResult,\n type Transport,\n runStepHandler,\n} from '@dudousxd/nestjs-durable-core';\nimport type { SqlExecutor, SqlTx } from './executors';\n\nexport { mikroOrmExecutor, type SqlExecutor, type SqlTx, typeOrmExecutor } from './executors';\n\n/** Raw row shapes returned by `SELECT *` (declared fields, so they're not `| undefined` under noUncheckedIndexedAccess). */\ninterface TaskRow {\n step_id: string;\n run_id: string;\n seq: string | number;\n name: string;\n input: string | null;\n attempt: string | number;\n}\ninterface ResultRow {\n step_id: string;\n run_id: string;\n seq: string | number;\n status: string;\n output: string | null;\n error: string | null;\n started_at: string | number | null;\n}\n\nexport interface DbTransportOptions {\n /**\n * How to run SQL — built from the app's **own** ORM/connection (no broker, no extra connection).\n * Use `mikroOrmExecutor(em)` to ride the app's MikroORM, `typeOrmExecutor(dataSource)` for TypeORM,\n * `drizzlePgExecutor(db)` (from `@dudousxd/nestjs-durable-store-drizzle/pg`) for Drizzle on\n * Postgres, or implement `SqlExecutor` for anything else.\n */\n executor: SqlExecutor;\n /** The worker group this instance serves. Required to register `handle()` consumers. */\n group?: string;\n /** Table-name prefix. Tables: `${prefix}_transport_tasks` / `${prefix}_transport_results`. Default `durable`. */\n prefix?: string;\n /** Poll interval in ms when a queue is empty. Default 500. */\n pollMs?: number;\n /**\n * How long a claimed row is owned before it's reclaimable (crash recovery), in ms. Default 30_000.\n * Every claim this instance holds is renewed every `leaseMs / 3` while it is waiting or running, so\n * a step may run longer than `leaseMs`; only a crashed (or event-loop-blocked) instance loses it.\n */\n leaseMs?: number;\n /**\n * Max rows claimed per poll. Default 10. The task loop claims only as many rows as it has free\n * {@link concurrency} slots (capped by this); the results loop claims up to this many.\n */\n batchSize?: number;\n /**\n * How many tasks this instance runs at once (worker side). Default 1. A row is claimed only when a\n * slot is free to run it, so rows never wait claimed behind a slow task while a sibling sits idle.\n */\n concurrency?: number;\n /**\n * Where a transport failure is reported: a failing poll, a throwing result handler (the result is\n * re-delivered after the lease), a lost claim. Default `console.error`.\n */\n onError?: (err: unknown) => void;\n /** Create the two tables on first use if missing. Default true. */\n autoCreate?: boolean;\n /** Identifies this instance in `claimed_by` (for debugging). Defaults to a random id. */\n instanceId?: string;\n}\n\n/**\n * A numeric option: `fallback` unless `value` is a finite number of at least `min`. `Math.max(1, NaN)`\n * is `NaN`, so a clamp alone would let a `NaN` through (to `LIMIT NaN`, or a `NaN` timer).\n */\nfunction numberOption(value: number | undefined, fallback: number, min: number): number {\n return value !== undefined && Number.isFinite(value) && value >= min ? value : fallback;\n}\n\n/**\n * A SQL-backed `Transport` — DBOS-style. Instead of a broker (Redis/SQS), remote steps are **rows**\n * in the same database the durable store already uses: `dispatch` inserts a task row, a worker\n * claims it with `SELECT … FOR UPDATE SKIP LOCKED` (so instances never double-claim), runs it, and\n * writes a result row the engine polls. Zero new infrastructure — the DB you already have IS the\n * queue.\n *\n * Trade-off vs a real broker: throughput is bounded by polling + row contention. Great for\n * workflow/pipeline scale (modest rate, long steps); not for high-fanout firehoses.\n *\n * Requires `FOR UPDATE SKIP LOCKED` — **MySQL 8+** or **Postgres 9.5+** (not SQLite). Run one\n * instance engine-side (`onResult`, dispatches) and one per worker process (`handle()` for its group).\n */\nexport class DbTransport implements Transport {\n private readonly exec: SqlExecutor;\n private readonly group?: string | undefined;\n private readonly tasksTable: string;\n private readonly resultsTable: string;\n private readonly pollMs: number;\n private readonly leaseMs: number;\n private readonly batchSize: number;\n private readonly concurrency: number;\n private readonly onError: (err: unknown) => void;\n private readonly autoCreate: boolean;\n private readonly instanceId: string;\n private readonly isPg: boolean;\n\n private readonly handlers = new Map<string, StepHandler>();\n private running = true;\n private schemaReady?: Promise<void> | undefined;\n private taskLoop?: Promise<void>;\n private resultLoop?: Promise<void>;\n /** Tasks running on this instance (at most `concurrency`). */\n private readonly runningTasks = new Set<Promise<void>>();\n /** Claim tokens this instance holds, by table — every one is renewed on `renewTimer`. */\n private readonly held = new Map<string, Set<string>>();\n private renewTimer?: ReturnType<typeof setInterval> | undefined;\n private renewal?: Promise<void> | undefined;\n\n constructor(options: DbTransportOptions) {\n this.exec = options.executor;\n this.group = options.group;\n const prefix = options.prefix ?? 'durable';\n this.tasksTable = `${prefix}_transport_tasks`;\n this.resultsTable = `${prefix}_transport_results`;\n this.pollMs = numberOption(options.pollMs, 500, 0);\n this.leaseMs = numberOption(options.leaseMs, 30_000, 1);\n this.batchSize = Math.floor(numberOption(options.batchSize, 10, 1));\n this.concurrency = Math.floor(numberOption(options.concurrency, 1, 1));\n this.onError = options.onError ?? ((err) => console.error('[DbTransport]', err));\n this.autoCreate = options.autoCreate ?? true;\n // Random, not time-based: two instances booted in the same millisecond must not share an id.\n this.instanceId = options.instanceId ?? `db-${randomUUID()}`;\n this.isPg = this.exec.dialect === 'postgres';\n }\n\n // ── dialect helpers ──────────────────────────────────────────────────────────────────────────\n /** Positional placeholder for param `i` (1-based): `$i` on Postgres, `?` elsewhere. */\n private ph(i: number): string {\n return this.isPg ? `$${i}` : '?';\n }\n private q(id: string): string {\n return this.exec.escapeId(id);\n }\n private now(): number {\n return Math.floor(Date.now());\n }\n\n // ── schema ───────────────────────────────────────────────────────────────────────────────────\n private ensureSchema(): Promise<void> {\n if (!this.schemaReady) {\n // A failed attempt is not cached: the next call tries again instead of failing forever.\n this.schemaReady = this.createTables().catch((err) => {\n this.schemaReady = undefined;\n throw err;\n });\n }\n return this.schemaReady;\n }\n\n /**\n * Run one `CREATE … IF NOT EXISTS`. Two instances booting on a fresh database race it, and Postgres\n * can reject the loser with a unique violation on its catalog even with `IF NOT EXISTS`; the\n * statement is simply re-run, by which point the table exists and it is a no-op.\n */\n private async createIfMissing(sql: string): Promise<void> {\n try {\n await this.exec.query(sql);\n } catch {\n await this.exec.query(sql);\n }\n }\n\n private async createTables(): Promise<void> {\n if (!this.autoCreate) return;\n const str = 'varchar(191)';\n const txt = this.isPg ? 'text' : 'longtext';\n const tasks = this.q(this.tasksTable);\n const results = this.q(this.resultsTable);\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${tasks} (\n ${this.q('step_id')} ${str} PRIMARY KEY,\n ${this.q('run_id')} ${str} NOT NULL,\n ${this.q('seq')} integer NOT NULL,\n ${this.q('name')} ${str} NOT NULL,\n ${this.q('grp')} ${str} NOT NULL,\n ${this.q('input')} ${txt},\n ${this.q('attempt')} integer NOT NULL,\n ${this.q('status')} varchar(32) NOT NULL,\n ${this.q('claimed_by')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${results} (\n ${this.q('step_id')} ${str} PRIMARY KEY,\n ${this.q('run_id')} ${str} NOT NULL,\n ${this.q('seq')} integer NOT NULL,\n ${this.q('status')} varchar(32) NOT NULL,\n ${this.q('output')} ${txt},\n ${this.q('error')} ${txt},\n ${this.q('started_at')} bigint,\n ${this.q('claimed_by')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n // Best-effort index for the group poll (MySQL has no CREATE INDEX IF NOT EXISTS < 8.0.13).\n await this.exec\n .query(\n `CREATE INDEX ${this.q(`${this.tasksTable}_grp_idx`)} ON ${tasks} (${this.q('grp')}, ${this.q('status')}, ${this.q('created_at')})`,\n )\n .catch(() => {});\n }\n\n // ── engine → worker ────────────────────────────────────────────────────────────────────────\n async dispatch(task: RemoteTask): Promise<void> {\n await this.ensureSchema();\n const t = this.q(this.tasksTable);\n // Idempotent: a redelivered dispatch for the same step_id is ignored (the row already exists).\n const ignore = this.isPg\n ? `INSERT INTO ${t} (...) ON CONFLICT (${this.q('step_id')}) DO NOTHING`\n : `INSERT IGNORE INTO ${t} (...)`;\n const cols = [\n 'step_id',\n 'run_id',\n 'seq',\n 'name',\n 'grp',\n 'input',\n 'attempt',\n 'status',\n 'created_at',\n ];\n const sql = ignore.replace(\n '(...)',\n `(${cols.map((c) => this.q(c)).join(', ')}) VALUES (${cols.map((_, i) => this.ph(i + 1)).join(', ')})`,\n );\n await this.exec.query(sql, [\n task.stepId,\n task.runId,\n task.seq,\n task.name,\n task.group,\n JSON.stringify(task.input ?? null),\n task.attempt,\n 'pending',\n this.now(),\n ]);\n }\n\n // ── worker → engine ────────────────────────────────────────────────────────────────────────\n handle(name: string, fn: StepHandler): void {\n if (!this.group) throw new Error('DbTransport needs a `group` to register handlers');\n this.handlers.set(name, fn);\n if (!this.taskLoop) this.taskLoop = this.loop(() => this.drainTasks(this.group as string));\n }\n\n onResult(handler: (result: StepResult) => Promise<void>): void {\n if (!this.resultLoop) this.resultLoop = this.loop(() => this.drainResults(handler));\n }\n\n onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void {\n // Not modelled; the lease/reclaim on `claimed_at` is the liveness mechanism.\n }\n\n // ── polling ──────────────────────────────────────────────────────────────────────────────────\n /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */\n private async loop(tick: () => Promise<number>): Promise<void> {\n while (this.running) {\n let processed = 0;\n try {\n await this.ensureSchema();\n processed = await tick();\n } catch (err) {\n if (this.running) this.onError(err);\n }\n if (processed === 0 && this.running) await this.sleep(this.pollMs);\n }\n }\n\n /**\n * One task-loop round: claim as many rows as there are free slots (never more — a claimed row that\n * isn't running is one an idle sibling can't run), and start each. With every slot busy, wait for\n * one to free instead of polling.\n */\n private async drainTasks(group: string): Promise<number> {\n const free = this.concurrency - this.runningTasks.size;\n if (free <= 0) {\n await Promise.race(this.runningTasks);\n return 1;\n }\n const { rows, token } = await this.claim<TaskRow>(\n this.tasksTable,\n Math.min(free, this.batchSize),\n `${this.q('grp')} = ${this.ph(1)}`,\n [group],\n );\n if (rows.length === 0) return 0;\n this.hold(this.tasksTable, token);\n let left = rows.length;\n for (const row of rows) {\n const run = this.runTask(row, group, token).finally(() => {\n this.runningTasks.delete(run);\n left -= 1;\n if (left === 0) this.release(this.tasksTable, token);\n });\n this.runningTasks.add(run);\n }\n return rows.length;\n }\n\n /**\n * Run one claimed task and settle it — only while this instance still holds the claim: the claim is\n * re-checked before running, and the task row is deleted and its result written in ONE transaction,\n * conditional on the claim token, so an instance whose claim was taken over neither deletes the new\n * holder's row nor publishes a second result.\n */\n private async runTask(row: TaskRow, group: string, token: string): Promise<void> {\n try {\n if (!(await this.stillHolds(row.step_id, token))) {\n this.onError(\n new Error(\n `[DbTransport] lost the claim on task ${row.step_id} before running it — another instance took it over; not running it here`,\n ),\n );\n return;\n }\n const task: RemoteTask = {\n runId: row.run_id,\n seq: Number(row.seq),\n stepId: row.step_id,\n name: row.name,\n group,\n input: row.input == null ? undefined : JSON.parse(row.input),\n attempt: Number(row.attempt),\n };\n const result = await runStepHandler(task, this.handlers.get(task.name));\n if (!(await this.settleTask(task.stepId, token, result))) {\n this.onError(\n new Error(\n `[DbTransport] lost the claim on task ${task.stepId} while running it (this instance went silent past leaseMs) — another instance took it over and may run it too; this run's result was dropped. Raise leaseMs if steps block the event loop`,\n ),\n );\n }\n } catch (err) {\n // A database error settling the row (or a malformed row): it stays claimed, stops being\n // renewed, and is reclaimed after the lease — at-least-once, like a crash.\n this.onError(err);\n }\n }\n\n /** Whether the claim on `stepId` is still `token`'s (re-stamping it if so). */\n private async stillHolds(stepId: string, token: string): Promise<boolean> {\n const t = this.q(this.tasksTable);\n const rows = await this.exec.transaction(async (tx) => {\n const held = await tx.query<{ step_id: string }>(\n `SELECT ${this.q('step_id')} FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)} FOR UPDATE`,\n [stepId, token],\n );\n if (held.length > 0) {\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_at')} = ${this.ph(1)} WHERE ${this.q('step_id')} = ${this.ph(2)} AND ${this.q('claimed_by')} = ${this.ph(3)}`,\n [this.now(), stepId, token],\n );\n }\n return held;\n });\n return rows.length > 0;\n }\n\n /** Delete the task row and publish its result in ONE transaction, only while `token` holds it. */\n private async settleTask(stepId: string, token: string, result: StepResult): Promise<boolean> {\n const t = this.q(this.tasksTable);\n return this.exec.transaction(async (tx) => {\n const held = await tx.query<{ step_id: string }>(\n `SELECT ${this.q('step_id')} FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)} FOR UPDATE`,\n [stepId, token],\n );\n if (held.length === 0) return false;\n await tx.query(\n `DELETE FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)}`,\n [stepId, token],\n );\n await this.insertResult(result, tx);\n return true;\n });\n }\n\n /**\n * Claim a batch of results, deliver each to the engine, and delete it — only after its handler ran\n * (at-least-once), and only while this round still holds the claim (a newer result for the same\n * step that replaced the row resets the claim, so it is delivered next instead of deleted). The\n * batch's claim is renewed until it is done. A throwing handler is reported and its row left for\n * re-delivery after the lease; the rest of the batch continues.\n */\n private async drainResults(handler: (result: StepResult) => Promise<void>): Promise<number> {\n const { rows, token } = await this.claim<ResultRow>(\n this.resultsTable,\n this.batchSize,\n '1 = 1',\n [],\n );\n if (rows.length === 0) return 0;\n this.hold(this.resultsTable, token);\n try {\n for (const row of rows) {\n if (!this.running) break;\n try {\n const result: StepResult = {\n runId: row.run_id,\n seq: Number(row.seq),\n stepId: row.step_id,\n status: row.status as StepResult['status'],\n output: row.output == null ? undefined : JSON.parse(row.output),\n error: row.error == null ? undefined : JSON.parse(row.error),\n startedAt: row.started_at == null ? undefined : Number(row.started_at),\n };\n await handler(result);\n await this.exec.query(\n `DELETE FROM ${this.q(this.resultsTable)} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)}`,\n [row.step_id, token],\n );\n } catch (err) {\n this.onError(err);\n }\n }\n } finally {\n this.release(this.resultsTable, token);\n }\n return rows.length;\n }\n\n /**\n * Atomically claim up to `limit` un-leased rows matching `where` and stamp them with a claim token\n * unique to this round (`<instanceId>:<uuid>`). `SELECT … FOR UPDATE SKIP LOCKED` inside the txn\n * means concurrent instances skip each other's locked rows instead of blocking, so no row is\n * claimed twice; the token is what every later delete/settle is conditional on.\n */\n private async claim<T extends { step_id: string }>(\n table: string,\n limit: number,\n where: string,\n whereParams: unknown[],\n ): Promise<{ rows: T[]; token: string }> {\n const t = this.q(table);\n const staleBefore = this.now() - this.leaseMs;\n const token = `${this.instanceId}:${randomUUID()}`;\n const rows = await this.exec.transaction(async (tx) => {\n const leaseClause = `(${this.q('claimed_at')} IS NULL OR ${this.q('claimed_at')} < ${this.ph(whereParams.length + 1)})`;\n const found = await tx.query<T>(\n `SELECT * FROM ${t} WHERE ${where} AND ${leaseClause}\n ORDER BY ${this.q('created_at')} ASC LIMIT ${Math.max(1, Math.floor(limit))} FOR UPDATE SKIP LOCKED`,\n [...whereParams, staleBefore],\n );\n if (found.length > 0) {\n const ids = found.map((r) => r.step_id);\n const placeholders = ids.map((_, i) => this.ph(i + 3)).join(', ');\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_by')} = ${this.ph(1)}, ${this.q('claimed_at')} = ${this.ph(2)}\n WHERE ${this.q('step_id')} IN (${placeholders})`,\n [token, this.now(), ...ids],\n );\n }\n return found;\n });\n return { rows, token };\n }\n\n // ── claim renewal: every claim held, not only the row being run ─────────────────────────────\n private hold(table: string, token: string): void {\n let tokens = this.held.get(table);\n if (!tokens) {\n tokens = new Set();\n this.held.set(table, tokens);\n }\n tokens.add(token);\n if (this.renewTimer) return;\n const intervalMs = Math.max(10, Math.floor(this.leaseMs / 3));\n this.renewTimer = setInterval(() => {\n if (this.renewal) return; // a slow database never stacks renewal rounds\n const round = this.renewHeld()\n .catch((err) => this.onError(err))\n .finally(() => {\n if (this.renewal === round) this.renewal = undefined;\n });\n this.renewal = round;\n }, intervalMs);\n this.renewTimer.unref?.();\n }\n\n private release(table: string, token: string): void {\n const tokens = this.held.get(table);\n tokens?.delete(token);\n if (tokens?.size === 0) this.held.delete(table);\n if (this.held.size === 0 && this.renewTimer) {\n clearInterval(this.renewTimer);\n this.renewTimer = undefined;\n }\n }\n\n /** Re-stamp `claimed_at` on every row still claimed under a token this instance holds. */\n private async renewHeld(): Promise<void> {\n for (const [table, tokens] of this.held) {\n if (tokens.size === 0) continue;\n const list = [...tokens];\n const placeholders = list.map((_, i) => this.ph(i + 2)).join(', ');\n await this.exec.query(\n `UPDATE ${this.q(table)} SET ${this.q('claimed_at')} = ${this.ph(1)} WHERE ${this.q('claimed_by')} IN (${placeholders})`,\n [this.now(), ...list],\n );\n }\n }\n\n /**\n * Write a result row. A result already waiting for the same step (an earlier attempt's, not yet\n * deleted by the engine) is REPLACED and its claim reset, never kept: `step_id` is stable across\n * attempts, so keeping the old row would silently drop a retry's result.\n */\n private async insertResult(result: StepResult, tx: SqlTx = this.exec): Promise<void> {\n const t = this.q(this.resultsTable);\n const cols = [\n 'step_id',\n 'run_id',\n 'seq',\n 'status',\n 'output',\n 'error',\n 'started_at',\n 'created_at',\n ];\n const replace = ['run_id', 'seq', 'status', 'output', 'error', 'started_at', 'created_at'];\n const values = `(${cols.map((c) => this.q(c)).join(', ')}) VALUES (${cols.map((_, i) => this.ph(i + 1)).join(', ')})`;\n const sql = this.isPg\n ? `INSERT INTO ${t} ${values} ON CONFLICT (${this.q('step_id')}) DO UPDATE SET ${[\n ...replace.map((c) => `${this.q(c)} = EXCLUDED.${this.q(c)}`),\n `${this.q('claimed_by')} = NULL`,\n `${this.q('claimed_at')} = NULL`,\n ].join(', ')}`\n : `INSERT INTO ${t} ${values} ON DUPLICATE KEY UPDATE ${[\n ...replace.map((c) => `${this.q(c)} = VALUES(${this.q(c)})`),\n `${this.q('claimed_by')} = NULL`,\n `${this.q('claimed_at')} = NULL`,\n ].join(', ')}`;\n await tx.query(sql, [\n result.stepId,\n result.runId,\n result.seq,\n result.status,\n result.output === undefined ? null : JSON.stringify(result.output),\n result.error === undefined ? null : JSON.stringify(result.error),\n result.startedAt ?? null,\n this.now(),\n ]);\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n }\n\n /** Stop the pollers and wait for the current ticks to settle. Does not close the shared DataSource. */\n async close(): Promise<void> {\n this.running = false;\n await Promise.allSettled([this.taskLoop, this.resultLoop]);\n // Let running tasks settle (their claims keep being renewed until they do).\n await Promise.allSettled([...this.runningTasks]);\n if (this.renewTimer) clearInterval(this.renewTimer);\n this.renewTimer = undefined;\n await this.renewal;\n }\n}\n","/**\n * The tiny SQL surface `DbTransport` needs, so it rides **whatever ORM/connection the app already\n * has** instead of forcing a specific one. Implement it for your ORM (adapters for TypeORM and\n * MikroORM ship below) and hand it to `new DbTransport({ executor })`. Mirrors how the durable\n * *store* is ORM-pluggable (store-typeorm / store-mikro-orm / …).\n */\nexport interface SqlExecutor {\n /** Drives placeholder style (`$n` vs `?`) and a couple of DDL type choices. */\n readonly dialect: 'mysql' | 'postgres';\n /** Quote/escape an identifier (table/column name) for this dialect. */\n escapeId(id: string): string;\n /** Run a statement outside a transaction. */\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n /** Run `fn` inside a transaction — the claim uses `FOR UPDATE SKIP LOCKED` within it. */\n transaction<T>(fn: (tx: SqlTx) => Promise<T>): Promise<T>;\n}\n\nexport interface SqlTx {\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n}\n\n// ── TypeORM ──────────────────────────────────────────────────────────────────────────────────────\n\n/** Structural slice of a TypeORM `DataSource` — avoids a hard dependency on typeorm. */\ninterface TypeOrmDataSourceLike {\n options: { type: string };\n driver: { escape(id: string): string };\n query(sql: string, params?: unknown[]): Promise<unknown>;\n createQueryRunner(): {\n connect(): Promise<void>;\n startTransaction(): Promise<void>;\n commitTransaction(): Promise<void>;\n rollbackTransaction(): Promise<void>;\n release(): Promise<void>;\n query(sql: string, params?: unknown[]): Promise<unknown>;\n };\n}\n\n/** Build an executor from a TypeORM `DataSource` (e.g. the one the durable store already uses). */\nexport function typeOrmExecutor(ds: TypeOrmDataSourceLike): SqlExecutor {\n return {\n dialect: /postgres/.test(String(ds.options.type)) ? 'postgres' : 'mysql',\n escapeId: (id) => ds.driver.escape(id),\n query: <T>(sql: string, params?: unknown[]) => ds.query(sql, params) as Promise<T[]>,\n transaction: async <T>(fn: (tx: SqlTx) => Promise<T>) => {\n const qr = ds.createQueryRunner();\n await qr.connect();\n await qr.startTransaction();\n try {\n const result = await fn({\n query: <U>(sql: string, params?: unknown[]) => qr.query(sql, params) as Promise<U[]>,\n });\n await qr.commitTransaction();\n return result;\n } catch (err) {\n await qr.rollbackTransaction();\n throw err;\n } finally {\n await qr.release();\n }\n },\n };\n}\n\n// ── MikroORM ─────────────────────────────────────────────────────────────────────────────────────\n\n/** Structural slice of a MikroORM `EntityManager` — avoids a hard dependency on @mikro-orm/core. */\ninterface MikroOrmEmLike {\n getPlatform(): { constructor: { name: string }; quoteIdentifier(id: string): string };\n getConnection(): {\n execute(sql: string, params?: unknown[], method?: 'all', ctx?: unknown): Promise<unknown>;\n };\n getTransactionContext?(): unknown;\n transactional<T>(cb: (em: MikroOrmEmLike) => Promise<T>): Promise<T>;\n}\n\n/**\n * Build an executor from a MikroORM `EntityManager` — i.e. **the app's own configured ORM**. Runs\n * raw SQL through `em.getConnection().execute(...)` and wraps the claim in `em.transactional(...)`,\n * threading the transaction context so `FOR UPDATE SKIP LOCKED` locks within the tx.\n */\nexport function mikroOrmExecutor(em: MikroOrmEmLike): SqlExecutor {\n const platform = em.getPlatform();\n return {\n dialect: /postgre/i.test(platform.constructor.name) ? 'postgres' : 'mysql',\n escapeId: (id) => platform.quoteIdentifier(id),\n query: <T>(sql: string, params?: unknown[]) =>\n em.getConnection().execute(sql, params ?? [], 'all') as Promise<T[]>,\n transaction: <T>(fn: (tx: SqlTx) => Promise<T>) =>\n em.transactional((txEm) =>\n fn({\n query: <U>(sql: string, params?: unknown[]) =>\n txEm\n .getConnection()\n .execute(sql, params ?? [], 'all', txEm.getTransactionContext?.()) as Promise<U[]>,\n }),\n ),\n };\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;AAC3B,SAMEC,sBACK;;;AC+BA,SAASC,gBAAgBC,IAAyB;AACvD,SAAO;IACLC,SAAS,WAAWC,KAAKC,OAAOH,GAAGI,QAAQC,IAAI,CAAA,IAAK,aAAa;IACjEC,UAAU,wBAACC,OAAOP,GAAGQ,OAAO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IAA2B;AACvC,WAAO,IAAIlD,QAAQ,CAACuC,MAAMY,WAAWZ,GAAGW,EAAAA,CAAAA;EAC1C;;EAGA,MAAME,QAAuB;AAC3B,SAAK1H,UAAU;AACf,UAAMsE,QAAQqD,WAAW;MAAC,KAAKzH;MAAU,KAAKC;KAAW;AAEzD,UAAMmE,QAAQqD,WAAW;SAAI,KAAKvH;KAAa;AAC/C,QAAI,KAAKG,WAAY8G,eAAc,KAAK9G,UAAU;AAClD,SAAKA,aAAazB;AAClB,UAAM,KAAK0B;EACb;AACF;","names":["randomUUID","runStepHandler","typeOrmExecutor","ds","dialect","test","String","options","type","escapeId","id","driver","escape","query","sql","params","transaction","fn","qr","createQueryRunner","connect","startTransaction","result","commitTransaction","err","rollbackTransaction","release","mikroOrmExecutor","em","platform","getPlatform","name","quoteIdentifier","getConnection","execute","transactional","txEm","getTransactionContext","numberOption","value","fallback","min","undefined","Number","isFinite","DbTransport","exec","group","tasksTable","resultsTable","pollMs","leaseMs","batchSize","concurrency","onError","autoCreate","instanceId","isPg","handlers","Map","running","schemaReady","taskLoop","resultLoop","runningTasks","Set","held","renewTimer","renewal","options","executor","prefix","Math","floor","err","console","error","randomUUID","dialect","ph","i","q","id","escapeId","now","Date","ensureSchema","createTables","catch","createIfMissing","sql","query","str","txt","tasks","results","dispatch","task","t","ignore","cols","replace","map","c","join","_","stepId","runId","seq","name","JSON","stringify","input","attempt","handle","fn","Error","set","loop","drainTasks","onResult","handler","drainResults","onHeartbeat","_handler","tick","processed","sleep","free","size","Promise","race","rows","token","claim","length","hold","left","row","run","runTask","finally","delete","release","add","stillHolds","step_id","run_id","parse","result","runStepHandler","get","settleTask","transaction","tx","insertResult","status","output","startedAt","started_at","table","limit","where","whereParams","staleBefore","leaseClause","found","max","ids","r","placeholders","tokens","intervalMs","setInterval","round","renewHeld","unref","clearInterval","list","values","ms","setTimeout","close","allSettled"]}
1
+ {"version":3,"sources":["../src/db-transport.ts","../src/executors.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport {\n type Heartbeat,\n type RemoteTask,\n type RunConsumerOptions,\n type RunDispatch,\n type RunQueueOptions,\n type StepHandler,\n type StepResult,\n type Transport,\n runStepHandler,\n} from '@dudousxd/nestjs-durable-core';\nimport type { SqlExecutor, SqlTx } from './executors';\n\nexport { mikroOrmExecutor, type SqlExecutor, type SqlTx, typeOrmExecutor } from './executors';\n\n/** Raw row shapes returned by `SELECT *` (declared fields, so they're not `| undefined` under noUncheckedIndexedAccess). */\ninterface TaskRow {\n step_id: string;\n run_id: string;\n seq: string | number;\n name: string;\n input: string | null;\n attempt: string | number;\n}\ninterface RunRow {\n run_id: string;\n wake: number | string;\n}\n\n/** A claimed run row: its run id and the token of this claim. */\ninterface ClaimedRun {\n run: RunDispatch;\n token: string;\n}\n\n/** Most rows one {@link DbTransport.dispatchRuns} insert writes. */\nconst RUNS_INSERT_CHUNK = 500;\n/** Most run rows one consumer poll claims. */\nconst RUNS_CLAIM_MAX = 50;\n\n/** A run-queue consumer started by {@link DbTransport.onDispatchedRun}. */\ninterface RunConsumer {\n stopped: boolean;\n /** Claim tokens of the rows whose runs are in flight. */\n inflight: Set<string>;\n slotFreed: (() => void) | undefined;\n loop: Promise<void>;\n}\n\ninterface ResultRow {\n step_id: string;\n run_id: string;\n seq: string | number;\n status: string;\n output: string | null;\n error: string | null;\n started_at: string | number | null;\n}\n\nexport interface DbTransportOptions {\n /**\n * How to run SQL — built from the app's **own** ORM/connection (no broker, no extra connection).\n * Use `mikroOrmExecutor(em)` to ride the app's MikroORM, `typeOrmExecutor(dataSource)` for TypeORM,\n * `drizzlePgExecutor(db)` (from `@dudousxd/nestjs-durable-store-drizzle/pg`) for Drizzle on\n * Postgres, or implement `SqlExecutor` for anything else.\n */\n executor: SqlExecutor;\n /** The worker group this instance serves. Required to register `handle()` consumers. */\n group?: string;\n /**\n * Table-name prefix. Tables: `${prefix}_transport_tasks` / `${prefix}_transport_results`, and\n * `${prefix}_transport_runs` for the run queue. Default `durable`.\n */\n prefix?: string;\n /** Poll interval in ms when a queue is empty. Default 500. */\n pollMs?: number;\n /**\n * How long a claimed row is owned before it's reclaimable (crash recovery), in ms. Default 30_000.\n * Every claim this instance holds is renewed every `leaseMs / 3` while it is waiting or running, so\n * a step may run longer than `leaseMs`; only a crashed (or event-loop-blocked) instance loses it.\n */\n leaseMs?: number;\n /**\n * Max rows claimed per poll. Default 10. The task loop claims only as many rows as it has free\n * {@link concurrency} slots (capped by this); the results loop claims up to this many.\n */\n batchSize?: number;\n /**\n * How many tasks this instance runs at once (worker side). Default 1. A row is claimed only when a\n * slot is free to run it, so rows never wait claimed behind a slow task while a sibling sits idle.\n */\n concurrency?: number;\n /**\n * Where a transport failure is reported: a failing poll, a throwing result handler (the result is\n * re-delivered after the lease), a lost claim. Default `console.error`.\n */\n onError?: (err: unknown) => void;\n /** Create the tables on first use if missing. Default true. */\n autoCreate?: boolean;\n /** Identifies this instance in `claimed_by` (for debugging). Defaults to a random id. */\n instanceId?: string;\n}\n\n/**\n * A numeric option: `fallback` unless `value` is a finite number of at least `min`. `Math.max(1, NaN)`\n * is `NaN`, so a clamp alone would let a `NaN` through (to `LIMIT NaN`, or a `NaN` timer).\n */\nfunction numberOption(value: number | undefined, fallback: number, min: number): number {\n return value !== undefined && Number.isFinite(value) && value >= min ? value : fallback;\n}\n\n/**\n * A SQL-backed `Transport` — DBOS-style. Instead of a broker (Redis/SQS), remote steps are **rows**\n * in the same database the durable store already uses: `dispatch` inserts a task row, a worker\n * claims it with `SELECT … FOR UPDATE SKIP LOCKED` (so instances never double-claim), runs it, and\n * writes a result row the engine polls. Zero new infrastructure — the DB you already have IS the\n * queue.\n *\n * Trade-off vs a real broker: throughput is bounded by polling + row contention. Great for\n * workflow/pipeline scale (modest rate, long steps); not for high-fanout firehoses.\n *\n * Requires `FOR UPDATE SKIP LOCKED` — **MySQL 8+** or **Postgres 9.5+** (not SQLite). Run one\n * instance engine-side (`onResult`, dispatches) and one per worker process (`handle()` for its group).\n */\nexport class DbTransport implements Transport {\n private readonly exec: SqlExecutor;\n private readonly group?: string | undefined;\n private readonly tasksTable: string;\n private readonly resultsTable: string;\n private readonly runsTable: string;\n private readonly runConsumers = new Set<RunConsumer>();\n private readonly pollMs: number;\n private readonly leaseMs: number;\n private readonly batchSize: number;\n private readonly concurrency: number;\n private readonly onError: (err: unknown) => void;\n private readonly autoCreate: boolean;\n private readonly instanceId: string;\n private readonly isPg: boolean;\n\n private readonly handlers = new Map<string, StepHandler>();\n private running = true;\n private schemaReady?: Promise<void> | undefined;\n private taskLoop?: Promise<void>;\n private resultLoop?: Promise<void>;\n /** Tasks running on this instance (at most `concurrency`). */\n private readonly runningTasks = new Set<Promise<void>>();\n /** Claim tokens this instance holds, by table — every one is renewed on `renewTimer`. */\n private readonly held = new Map<string, Set<string>>();\n private renewTimer?: ReturnType<typeof setInterval> | undefined;\n private renewal?: Promise<void> | undefined;\n\n constructor(options: DbTransportOptions) {\n this.exec = options.executor;\n this.group = options.group;\n const prefix = options.prefix ?? 'durable';\n this.tasksTable = `${prefix}_transport_tasks`;\n this.resultsTable = `${prefix}_transport_results`;\n this.runsTable = `${prefix}_transport_runs`;\n this.pollMs = numberOption(options.pollMs, 500, 0);\n this.leaseMs = numberOption(options.leaseMs, 30_000, 1);\n this.batchSize = Math.floor(numberOption(options.batchSize, 10, 1));\n this.concurrency = Math.floor(numberOption(options.concurrency, 1, 1));\n this.onError = options.onError ?? ((err) => console.error('[DbTransport]', err));\n this.autoCreate = options.autoCreate ?? true;\n // Random, not time-based: two instances booted in the same millisecond must not share an id.\n this.instanceId = options.instanceId ?? `db-${randomUUID()}`;\n this.isPg = this.exec.dialect === 'postgres';\n }\n\n // ── dialect helpers ──────────────────────────────────────────────────────────────────────────\n /** Positional placeholder for param `i` (1-based): `$i` on Postgres, `?` elsewhere. */\n private ph(i: number): string {\n return this.isPg ? `$${i}` : '?';\n }\n private q(id: string): string {\n return this.exec.escapeId(id);\n }\n private now(): number {\n return Math.floor(Date.now());\n }\n\n // ── schema ───────────────────────────────────────────────────────────────────────────────────\n private ensureSchema(): Promise<void> {\n if (!this.schemaReady) {\n // A failed attempt is not cached: the next call tries again instead of failing forever.\n this.schemaReady = this.createTables().catch((err) => {\n this.schemaReady = undefined;\n throw err;\n });\n }\n return this.schemaReady;\n }\n\n /**\n * Run one `CREATE … IF NOT EXISTS`. Two instances booting on a fresh database race it, and Postgres\n * can reject the loser with a unique violation on its catalog even with `IF NOT EXISTS`; the\n * statement is simply re-run, by which point the table exists and it is a no-op.\n */\n private async createIfMissing(sql: string): Promise<void> {\n try {\n await this.exec.query(sql);\n } catch {\n await this.exec.query(sql);\n }\n }\n\n private async createTables(): Promise<void> {\n if (!this.autoCreate) return;\n const str = 'varchar(191)';\n const txt = this.isPg ? 'text' : 'longtext';\n const tasks = this.q(this.tasksTable);\n const results = this.q(this.resultsTable);\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${tasks} (\n ${this.q('step_id')} ${str} PRIMARY KEY,\n ${this.q('run_id')} ${str} NOT NULL,\n ${this.q('seq')} integer NOT NULL,\n ${this.q('name')} ${str} NOT NULL,\n ${this.q('grp')} ${str} NOT NULL,\n ${this.q('input')} ${txt},\n ${this.q('attempt')} integer NOT NULL,\n ${this.q('status')} varchar(32) NOT NULL,\n ${this.q('claimed_by')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${results} (\n ${this.q('step_id')} ${str} PRIMARY KEY,\n ${this.q('run_id')} ${str} NOT NULL,\n ${this.q('seq')} integer NOT NULL,\n ${this.q('status')} varchar(32) NOT NULL,\n ${this.q('output')} ${txt},\n ${this.q('error')} ${txt},\n ${this.q('started_at')} bigint,\n ${this.q('claimed_by')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n await this.createIfMissing(\n `CREATE TABLE IF NOT EXISTS ${this.q(this.runsTable)} (\n ${this.q('run_id')} ${str} PRIMARY KEY,\n ${this.q('ns')} ${str} NOT NULL,\n ${this.q('priority')} integer NOT NULL,\n ${this.q('wake')} integer NOT NULL,\n ${this.q('claimed_by')} ${str},\n ${this.q('claim_token')} ${str},\n ${this.q('claimed_at')} bigint,\n ${this.q('created_at')} bigint NOT NULL\n )`,\n );\n await this.exec\n .query(\n `CREATE INDEX ${this.q(`${this.runsTable}_ns_idx`)} ON ${this.q(this.runsTable)} (${this.q('ns')}, ${this.q('priority')}, ${this.q('created_at')})`,\n )\n .catch(() => {});\n // Best-effort index for the group poll (MySQL has no CREATE INDEX IF NOT EXISTS < 8.0.13).\n await this.exec\n .query(\n `CREATE INDEX ${this.q(`${this.tasksTable}_grp_idx`)} ON ${tasks} (${this.q('grp')}, ${this.q('status')}, ${this.q('created_at')})`,\n )\n .catch(() => {});\n }\n\n // ── engine → worker ────────────────────────────────────────────────────────────────────────\n async dispatch(task: RemoteTask): Promise<void> {\n await this.ensureSchema();\n const t = this.q(this.tasksTable);\n // Idempotent: a redelivered dispatch for the same step_id is ignored (the row already exists).\n const ignore = this.isPg\n ? `INSERT INTO ${t} (...) ON CONFLICT (${this.q('step_id')}) DO NOTHING`\n : `INSERT IGNORE INTO ${t} (...)`;\n const cols = [\n 'step_id',\n 'run_id',\n 'seq',\n 'name',\n 'grp',\n 'input',\n 'attempt',\n 'status',\n 'created_at',\n ];\n const sql = ignore.replace(\n '(...)',\n `(${cols.map((c) => this.q(c)).join(', ')}) VALUES (${cols.map((_, i) => this.ph(i + 1)).join(', ')})`,\n );\n await this.exec.query(sql, [\n task.stepId,\n task.runId,\n task.seq,\n task.name,\n task.group,\n JSON.stringify(task.input ?? null),\n task.attempt,\n 'pending',\n this.now(),\n ]);\n }\n\n // ── worker → engine ────────────────────────────────────────────────────────────────────────\n handle(name: string, fn: StepHandler): void {\n if (!this.group) throw new Error('DbTransport needs a `group` to register handlers');\n this.handlers.set(name, fn);\n if (!this.taskLoop) this.taskLoop = this.loop(() => this.drainTasks(this.group as string));\n }\n\n onResult(handler: (result: StepResult) => Promise<void>): void {\n if (!this.resultLoop) this.resultLoop = this.loop(() => this.drainResults(handler));\n }\n\n onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void {\n // Not modelled; the lease/reclaim on `claimed_at` is the liveness mechanism.\n }\n\n // ── run queue (engine ↔ engine) ─────────────────────────────────────────────────────────────\n /**\n * Queue `pending` runs for whichever engine instance polls the run queue first: one row per run,\n * keyed by run id, so a run already waiting is not queued twice. A run whose row an instance holds\n * right now is released for another take, so a dispatch landing while the run's previous entry is\n * being handled is not lost when that entry is deleted. Up to {@link RUNS_INSERT_CHUNK} rows per\n * insert.\n */\n async dispatchRuns(runs: readonly RunDispatch[], opts?: RunQueueOptions): Promise<void> {\n if (runs.length === 0) return;\n await this.ensureSchema();\n // One row per run (an upsert may not touch the same row twice in one statement); a wake among\n // a run's dispatches makes its row a wake.\n const byRun = new Map<string, RunDispatch>();\n for (const run of runs) {\n if (!byRun.has(run.runId) || run.reason === 'wake') byRun.set(run.runId, run);\n }\n const unique = [...byRun.values()];\n const t = this.q(this.runsTable);\n const cols = ['run_id', 'ns', 'priority', 'wake', 'created_at'];\n const now = this.now();\n for (let at = 0; at < unique.length; at += RUNS_INSERT_CHUNK) {\n const chunk = unique.slice(at, at + RUNS_INSERT_CHUNK);\n const values = chunk\n .map((_, r) => `(${cols.map((__, c) => this.ph(r * cols.length + c + 1)).join(', ')})`)\n .join(', ');\n const insert = `INTO ${t} (${cols.map((c) => this.q(c)).join(', ')}) VALUES ${values}`;\n const release = ['claimed_by', 'claim_token', 'claimed_at']\n .map((c) => `${this.q(c)} = NULL`)\n .join(', ');\n const wake = this.q('wake');\n const sql = this.isPg\n ? `INSERT ${insert} ON CONFLICT (${this.q('run_id')}) DO UPDATE SET ${release}, ${wake} = GREATEST(${t}.${wake}, EXCLUDED.${wake})`\n : `INSERT ${insert} ON DUPLICATE KEY UPDATE ${release}, ${wake} = GREATEST(${wake}, VALUES(${wake}))`;\n await this.exec.query(\n sql,\n chunk.flatMap((run, r) => [\n run.runId,\n opts?.namespace ?? '',\n run.priority ?? 0,\n run.reason === 'wake' ? 1 : 0,\n now + r,\n ]),\n );\n }\n }\n\n /**\n * Poll the run queue, at most `opts.concurrency` runs in flight on this instance. Rows are claimed\n * with `FOR UPDATE SKIP LOCKED` (instances never take the same run), highest priority then oldest\n * first; a row is deleted once its handler settles, and its lease is renewed meanwhile, so a row is\n * re-taken only after the instance holding it went down. The returned stop takes no more rows and\n * resolves once the runs in flight settled.\n */\n onDispatchedRun(\n handler: (run: RunDispatch) => Promise<void>,\n opts: RunConsumerOptions,\n ): () => Promise<void> {\n const consumer: RunConsumer = {\n stopped: false,\n inflight: new Set(),\n slotFreed: undefined,\n loop: Promise.resolve(),\n };\n const concurrency = Math.max(1, Math.floor(opts.concurrency));\n const ns = opts.namespace ?? '';\n consumer.loop = this.consumeRuns(consumer, handler, concurrency, ns).catch((err) => {\n this.onError(err);\n });\n this.runConsumers.add(consumer);\n return () => this.stopRunConsumer(consumer);\n }\n\n private async stopRunConsumer(consumer: RunConsumer): Promise<void> {\n consumer.stopped = true;\n consumer.slotFreed?.();\n await consumer.loop;\n this.runConsumers.delete(consumer);\n }\n\n private async consumeRuns(\n consumer: RunConsumer,\n handler: (run: RunDispatch) => Promise<void>,\n concurrency: number,\n ns: string,\n ): Promise<void> {\n const renew = setInterval(\n () => void this.renewRunLeases(consumer).catch(() => undefined),\n Math.max(1_000, Math.floor(this.leaseMs / 3)),\n );\n renew.unref?.();\n const settled = new Set<Promise<unknown>>();\n try {\n while (this.running && !consumer.stopped) {\n const free = concurrency - consumer.inflight.size;\n if (free <= 0) {\n await new Promise<void>((resolve) => {\n consumer.slotFreed = resolve;\n });\n consumer.slotFreed = undefined;\n continue;\n }\n let rows: ClaimedRun[] = [];\n try {\n await this.ensureSchema();\n rows = await this.claimRuns(ns, Math.min(free, RUNS_CLAIM_MAX));\n } catch (err) {\n if (this.running && !consumer.stopped) this.onError(err);\n }\n for (const { run, token } of rows) {\n consumer.inflight.add(token);\n const done = handler(run)\n .catch(() => undefined)\n .then(() =>\n this.exec\n .query(\n `DELETE FROM ${this.q(this.runsTable)} WHERE ${this.q('claim_token')} = ${this.ph(1)}`,\n [token],\n )\n .catch(() => undefined),\n )\n .finally(() => {\n consumer.inflight.delete(token);\n settled.delete(done);\n consumer.slotFreed?.();\n });\n settled.add(done);\n }\n if (rows.length === 0) await this.sleep(this.pollMs);\n }\n await Promise.allSettled([...settled]);\n } finally {\n clearInterval(renew);\n }\n }\n\n private async claimRuns(ns: string, limit: number): Promise<ClaimedRun[]> {\n const t = this.q(this.runsTable);\n const staleBefore = this.now() - this.leaseMs;\n return this.exec.transaction(async (tx) => {\n const rows = await tx.query<RunRow>(\n `SELECT ${this.q('run_id')}, ${this.q('wake')} FROM ${t}\n WHERE ${this.q('ns')} = ${this.ph(1)}\n AND (${this.q('claimed_at')} IS NULL OR ${this.q('claimed_at')} < ${this.ph(2)})\n ORDER BY ${this.q('priority')} DESC, ${this.q('created_at')} ASC\n LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED`,\n [ns, staleBefore],\n );\n const claimed = rows.map((r) => ({\n run: {\n runId: r.run_id,\n reason: Number(r.wake) === 1 ? ('wake' as const) : ('start' as const),\n },\n token: globalThis.crypto.randomUUID(),\n }));\n const now = this.now();\n for (const {\n run: { runId },\n token,\n } of claimed) {\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_by')} = ${this.ph(1)}, ${this.q('claim_token')} = ${this.ph(2)}, ${this.q('claimed_at')} = ${this.ph(3)}\n WHERE ${this.q('run_id')} = ${this.ph(4)}`,\n [this.instanceId, token, now, runId],\n );\n }\n return claimed;\n });\n }\n\n /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */\n private async renewRunLeases(consumer: RunConsumer): Promise<void> {\n const tokens = [...consumer.inflight];\n if (tokens.length === 0) return;\n await this.exec.query(\n `UPDATE ${this.q(this.runsTable)} SET ${this.q('claimed_at')} = ${this.ph(1)}\n WHERE ${this.q('claim_token')} IN (${tokens.map((_, i) => this.ph(i + 2)).join(', ')})`,\n [this.now(), ...tokens],\n );\n }\n\n // ── polling ──────────────────────────────────────────────────────────────────────────────────\n /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */\n private async loop(tick: () => Promise<number>): Promise<void> {\n while (this.running) {\n let processed = 0;\n try {\n await this.ensureSchema();\n processed = await tick();\n } catch (err) {\n if (this.running) this.onError(err);\n }\n if (processed === 0 && this.running) await this.sleep(this.pollMs);\n }\n }\n\n /**\n * One task-loop round: claim as many rows as there are free slots (never more — a claimed row that\n * isn't running is one an idle sibling can't run), and start each. With every slot busy, wait for\n * one to free instead of polling.\n */\n private async drainTasks(group: string): Promise<number> {\n const free = this.concurrency - this.runningTasks.size;\n if (free <= 0) {\n await Promise.race(this.runningTasks);\n return 1;\n }\n const { rows, token } = await this.claim<TaskRow>(\n this.tasksTable,\n Math.min(free, this.batchSize),\n `${this.q('grp')} = ${this.ph(1)}`,\n [group],\n );\n if (rows.length === 0) return 0;\n this.hold(this.tasksTable, token);\n let left = rows.length;\n for (const row of rows) {\n const run = this.runTask(row, group, token).finally(() => {\n this.runningTasks.delete(run);\n left -= 1;\n if (left === 0) this.release(this.tasksTable, token);\n });\n this.runningTasks.add(run);\n }\n return rows.length;\n }\n\n /**\n * Run one claimed task and settle it — only while this instance still holds the claim: the claim is\n * re-checked before running, and the task row is deleted and its result written in ONE transaction,\n * conditional on the claim token, so an instance whose claim was taken over neither deletes the new\n * holder's row nor publishes a second result.\n */\n private async runTask(row: TaskRow, group: string, token: string): Promise<void> {\n try {\n if (!(await this.stillHolds(row.step_id, token))) {\n this.onError(\n new Error(\n `[DbTransport] lost the claim on task ${row.step_id} before running it — another instance took it over; not running it here`,\n ),\n );\n return;\n }\n const task: RemoteTask = {\n runId: row.run_id,\n seq: Number(row.seq),\n stepId: row.step_id,\n name: row.name,\n group,\n input: row.input == null ? undefined : JSON.parse(row.input),\n attempt: Number(row.attempt),\n };\n const result = await runStepHandler(task, this.handlers.get(task.name));\n if (!(await this.settleTask(task.stepId, token, result))) {\n this.onError(\n new Error(\n `[DbTransport] lost the claim on task ${task.stepId} while running it (this instance went silent past leaseMs) — another instance took it over and may run it too; this run's result was dropped. Raise leaseMs if steps block the event loop`,\n ),\n );\n }\n } catch (err) {\n // A database error settling the row (or a malformed row): it stays claimed, stops being\n // renewed, and is reclaimed after the lease — at-least-once, like a crash.\n this.onError(err);\n }\n }\n\n /** Whether the claim on `stepId` is still `token`'s (re-stamping it if so). */\n private async stillHolds(stepId: string, token: string): Promise<boolean> {\n const t = this.q(this.tasksTable);\n const rows = await this.exec.transaction(async (tx) => {\n const held = await tx.query<{ step_id: string }>(\n `SELECT ${this.q('step_id')} FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)} FOR UPDATE`,\n [stepId, token],\n );\n if (held.length > 0) {\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_at')} = ${this.ph(1)} WHERE ${this.q('step_id')} = ${this.ph(2)} AND ${this.q('claimed_by')} = ${this.ph(3)}`,\n [this.now(), stepId, token],\n );\n }\n return held;\n });\n return rows.length > 0;\n }\n\n /** Delete the task row and publish its result in ONE transaction, only while `token` holds it. */\n private async settleTask(stepId: string, token: string, result: StepResult): Promise<boolean> {\n const t = this.q(this.tasksTable);\n return this.exec.transaction(async (tx) => {\n const held = await tx.query<{ step_id: string }>(\n `SELECT ${this.q('step_id')} FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)} FOR UPDATE`,\n [stepId, token],\n );\n if (held.length === 0) return false;\n await tx.query(\n `DELETE FROM ${t} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)}`,\n [stepId, token],\n );\n await this.insertResult(result, tx);\n return true;\n });\n }\n\n /**\n * Claim a batch of results, deliver each to the engine, and delete it — only after its handler ran\n * (at-least-once), and only while this round still holds the claim (a newer result for the same\n * step that replaced the row resets the claim, so it is delivered next instead of deleted). The\n * batch's claim is renewed until it is done. A throwing handler is reported and its row left for\n * re-delivery after the lease; the rest of the batch continues.\n */\n private async drainResults(handler: (result: StepResult) => Promise<void>): Promise<number> {\n const { rows, token } = await this.claim<ResultRow>(\n this.resultsTable,\n this.batchSize,\n '1 = 1',\n [],\n );\n if (rows.length === 0) return 0;\n this.hold(this.resultsTable, token);\n try {\n for (const row of rows) {\n if (!this.running) break;\n try {\n const result: StepResult = {\n runId: row.run_id,\n seq: Number(row.seq),\n stepId: row.step_id,\n status: row.status as StepResult['status'],\n output: row.output == null ? undefined : JSON.parse(row.output),\n error: row.error == null ? undefined : JSON.parse(row.error),\n startedAt: row.started_at == null ? undefined : Number(row.started_at),\n };\n await handler(result);\n await this.exec.query(\n `DELETE FROM ${this.q(this.resultsTable)} WHERE ${this.q('step_id')} = ${this.ph(1)} AND ${this.q('claimed_by')} = ${this.ph(2)}`,\n [row.step_id, token],\n );\n } catch (err) {\n this.onError(err);\n }\n }\n } finally {\n this.release(this.resultsTable, token);\n }\n return rows.length;\n }\n\n /**\n * Atomically claim up to `limit` un-leased rows matching `where` and stamp them with a claim token\n * unique to this round (`<instanceId>:<uuid>`). `SELECT … FOR UPDATE SKIP LOCKED` inside the txn\n * means concurrent instances skip each other's locked rows instead of blocking, so no row is\n * claimed twice; the token is what every later delete/settle is conditional on.\n */\n private async claim<T extends { step_id: string }>(\n table: string,\n limit: number,\n where: string,\n whereParams: unknown[],\n ): Promise<{ rows: T[]; token: string }> {\n const t = this.q(table);\n const staleBefore = this.now() - this.leaseMs;\n const token = `${this.instanceId}:${randomUUID()}`;\n const rows = await this.exec.transaction(async (tx) => {\n const leaseClause = `(${this.q('claimed_at')} IS NULL OR ${this.q('claimed_at')} < ${this.ph(whereParams.length + 1)})`;\n const found = await tx.query<T>(\n `SELECT * FROM ${t} WHERE ${where} AND ${leaseClause}\n ORDER BY ${this.q('created_at')} ASC LIMIT ${Math.max(1, Math.floor(limit))} FOR UPDATE SKIP LOCKED`,\n [...whereParams, staleBefore],\n );\n if (found.length > 0) {\n const ids = found.map((r) => r.step_id);\n const placeholders = ids.map((_, i) => this.ph(i + 3)).join(', ');\n await tx.query(\n `UPDATE ${t} SET ${this.q('claimed_by')} = ${this.ph(1)}, ${this.q('claimed_at')} = ${this.ph(2)}\n WHERE ${this.q('step_id')} IN (${placeholders})`,\n [token, this.now(), ...ids],\n );\n }\n return found;\n });\n return { rows, token };\n }\n\n // ── claim renewal: every claim held, not only the row being run ─────────────────────────────\n private hold(table: string, token: string): void {\n let tokens = this.held.get(table);\n if (!tokens) {\n tokens = new Set();\n this.held.set(table, tokens);\n }\n tokens.add(token);\n if (this.renewTimer) return;\n const intervalMs = Math.max(10, Math.floor(this.leaseMs / 3));\n this.renewTimer = setInterval(() => {\n if (this.renewal) return; // a slow database never stacks renewal rounds\n const round = this.renewHeld()\n .catch((err) => this.onError(err))\n .finally(() => {\n if (this.renewal === round) this.renewal = undefined;\n });\n this.renewal = round;\n }, intervalMs);\n this.renewTimer.unref?.();\n }\n\n private release(table: string, token: string): void {\n const tokens = this.held.get(table);\n tokens?.delete(token);\n if (tokens?.size === 0) this.held.delete(table);\n if (this.held.size === 0 && this.renewTimer) {\n clearInterval(this.renewTimer);\n this.renewTimer = undefined;\n }\n }\n\n /** Re-stamp `claimed_at` on every row still claimed under a token this instance holds. */\n private async renewHeld(): Promise<void> {\n for (const [table, tokens] of this.held) {\n if (tokens.size === 0) continue;\n const list = [...tokens];\n const placeholders = list.map((_, i) => this.ph(i + 2)).join(', ');\n await this.exec.query(\n `UPDATE ${this.q(table)} SET ${this.q('claimed_at')} = ${this.ph(1)} WHERE ${this.q('claimed_by')} IN (${placeholders})`,\n [this.now(), ...list],\n );\n }\n }\n\n /**\n * Write a result row. A result already waiting for the same step (an earlier attempt's, not yet\n * deleted by the engine) is REPLACED and its claim reset, never kept: `step_id` is stable across\n * attempts, so keeping the old row would silently drop a retry's result.\n */\n private async insertResult(result: StepResult, tx: SqlTx = this.exec): Promise<void> {\n const t = this.q(this.resultsTable);\n const cols = [\n 'step_id',\n 'run_id',\n 'seq',\n 'status',\n 'output',\n 'error',\n 'started_at',\n 'created_at',\n ];\n const replace = ['run_id', 'seq', 'status', 'output', 'error', 'started_at', 'created_at'];\n const values = `(${cols.map((c) => this.q(c)).join(', ')}) VALUES (${cols.map((_, i) => this.ph(i + 1)).join(', ')})`;\n const sql = this.isPg\n ? `INSERT INTO ${t} ${values} ON CONFLICT (${this.q('step_id')}) DO UPDATE SET ${[\n ...replace.map((c) => `${this.q(c)} = EXCLUDED.${this.q(c)}`),\n `${this.q('claimed_by')} = NULL`,\n `${this.q('claimed_at')} = NULL`,\n ].join(', ')}`\n : `INSERT INTO ${t} ${values} ON DUPLICATE KEY UPDATE ${[\n ...replace.map((c) => `${this.q(c)} = VALUES(${this.q(c)})`),\n `${this.q('claimed_by')} = NULL`,\n `${this.q('claimed_at')} = NULL`,\n ].join(', ')}`;\n await tx.query(sql, [\n result.stepId,\n result.runId,\n result.seq,\n result.status,\n result.output === undefined ? null : JSON.stringify(result.output),\n result.error === undefined ? null : JSON.stringify(result.error),\n result.startedAt ?? null,\n this.now(),\n ]);\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n }\n\n /** Stop the pollers and wait for the current ticks to settle. Does not close the shared DataSource. */\n async close(): Promise<void> {\n this.running = false;\n await Promise.allSettled([\n this.taskLoop,\n this.resultLoop,\n ...[...this.runConsumers].map((c) => this.stopRunConsumer(c)),\n ]);\n // Let running tasks settle (their claims keep being renewed until they do).\n await Promise.allSettled([...this.runningTasks]);\n if (this.renewTimer) clearInterval(this.renewTimer);\n this.renewTimer = undefined;\n await this.renewal;\n }\n}\n","/**\n * The tiny SQL surface `DbTransport` needs, so it rides **whatever ORM/connection the app already\n * has** instead of forcing a specific one. Implement it for your ORM (adapters for TypeORM and\n * MikroORM ship below) and hand it to `new DbTransport({ executor })`. Mirrors how the durable\n * *store* is ORM-pluggable (store-typeorm / store-mikro-orm / …).\n */\nexport interface SqlExecutor {\n /** Drives placeholder style (`$n` vs `?`) and a couple of DDL type choices. */\n readonly dialect: 'mysql' | 'postgres';\n /** Quote/escape an identifier (table/column name) for this dialect. */\n escapeId(id: string): string;\n /** Run a statement outside a transaction. */\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n /** Run `fn` inside a transaction — the claim uses `FOR UPDATE SKIP LOCKED` within it. */\n transaction<T>(fn: (tx: SqlTx) => Promise<T>): Promise<T>;\n}\n\nexport interface SqlTx {\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\n}\n\n// ── TypeORM ──────────────────────────────────────────────────────────────────────────────────────\n\n/** Structural slice of a TypeORM `DataSource` — avoids a hard dependency on typeorm. */\ninterface TypeOrmDataSourceLike {\n options: { type: string };\n driver: { escape(id: string): string };\n query(sql: string, params?: unknown[]): Promise<unknown>;\n createQueryRunner(): {\n connect(): Promise<void>;\n startTransaction(): Promise<void>;\n commitTransaction(): Promise<void>;\n rollbackTransaction(): Promise<void>;\n release(): Promise<void>;\n query(sql: string, params?: unknown[]): Promise<unknown>;\n };\n}\n\n/** Build an executor from a TypeORM `DataSource` (e.g. the one the durable store already uses). */\nexport function typeOrmExecutor(ds: TypeOrmDataSourceLike): SqlExecutor {\n return {\n dialect: /postgres/.test(String(ds.options.type)) ? 'postgres' : 'mysql',\n escapeId: (id) => ds.driver.escape(id),\n query: <T>(sql: string, params?: unknown[]) => ds.query(sql, params) as Promise<T[]>,\n transaction: async <T>(fn: (tx: SqlTx) => Promise<T>) => {\n const qr = ds.createQueryRunner();\n await qr.connect();\n await qr.startTransaction();\n try {\n const result = await fn({\n query: <U>(sql: string, params?: unknown[]) => qr.query(sql, params) as Promise<U[]>,\n });\n await qr.commitTransaction();\n return result;\n } catch (err) {\n await qr.rollbackTransaction();\n throw err;\n } finally {\n await qr.release();\n }\n },\n };\n}\n\n// ── MikroORM ─────────────────────────────────────────────────────────────────────────────────────\n\n/** Structural slice of a MikroORM `EntityManager` — avoids a hard dependency on @mikro-orm/core. */\ninterface MikroOrmEmLike {\n getPlatform(): { constructor: { name: string }; quoteIdentifier(id: string): string };\n getConnection(): {\n execute(sql: string, params?: unknown[], method?: 'all', ctx?: unknown): Promise<unknown>;\n };\n getTransactionContext?(): unknown;\n transactional<T>(cb: (em: MikroOrmEmLike) => Promise<T>): Promise<T>;\n}\n\n/**\n * Build an executor from a MikroORM `EntityManager` — i.e. **the app's own configured ORM**. Runs\n * raw SQL through `em.getConnection().execute(...)` and wraps the claim in `em.transactional(...)`,\n * threading the transaction context so `FOR UPDATE SKIP LOCKED` locks within the tx.\n */\nexport function mikroOrmExecutor(em: MikroOrmEmLike): SqlExecutor {\n const platform = em.getPlatform();\n return {\n dialect: /postgre/i.test(platform.constructor.name) ? 'postgres' : 'mysql',\n escapeId: (id) => platform.quoteIdentifier(id),\n query: <T>(sql: string, params?: unknown[]) =>\n em.getConnection().execute(sql, params ?? [], 'all') as Promise<T[]>,\n transaction: <T>(fn: (tx: SqlTx) => Promise<T>) =>\n em.transactional((txEm) =>\n fn({\n query: <U>(sql: string, params?: unknown[]) =>\n txEm\n .getConnection()\n .execute(sql, params ?? [], 'all', txEm.getTransactionContext?.()) as Promise<U[]>,\n }),\n ),\n };\n}\n"],"mappings":";;;;AAAA,SAASA,kBAAkB;AAC3B,SASEC,sBACK;;;AC4BA,SAASC,gBAAgBC,IAAyB;AACvD,SAAO;IACLC,SAAS,WAAWC,KAAKC,OAAOH,GAAGI,QAAQC,IAAI,CAAA,IAAK,aAAa;IACjEC,UAAU,wBAACC,OAAOP,GAAGQ,OAAOC,OAAOF,EAAAA,GAAzB;IACVG,OAAO,wBAAIC,KAAaC,WAAuBZ,GAAGU,MAAMC,KAAKC,MAAAA,GAAtD;IACPC,aAAa,8BAAUC,OAAAA;AACrB,YAAMC,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MACvB,KAAK9G;MACL,KAAKC;SACF;WAAI,KAAKf;QAAcqD,IAAI,CAACC,MAAM,KAAKsD,gBAAgBtD,CAAAA,CAAAA;KAC3D;AAED,UAAMgD,QAAQsB,WAAW;SAAI,KAAK5G;KAAa;AAC/C,QAAI,KAAKE,WAAY2G,eAAc,KAAK3G,UAAU;AAClD,SAAKA,aAAa3B;AAClB,UAAM,KAAK4B;EACb;AACF;","names":["randomUUID","runStepHandler","typeOrmExecutor","ds","dialect","test","String","options","type","escapeId","id","driver","escape","query","sql","params","transaction","fn","qr","createQueryRunner","connect","startTransaction","result","commitTransaction","err","rollbackTransaction","release","mikroOrmExecutor","em","platform","getPlatform","name","quoteIdentifier","getConnection","execute","transactional","txEm","getTransactionContext","RUNS_INSERT_CHUNK","RUNS_CLAIM_MAX","numberOption","value","fallback","min","undefined","Number","isFinite","DbTransport","exec","group","tasksTable","resultsTable","runsTable","runConsumers","Set","pollMs","leaseMs","batchSize","concurrency","onError","autoCreate","instanceId","isPg","handlers","Map","running","schemaReady","taskLoop","resultLoop","runningTasks","held","renewTimer","renewal","options","executor","prefix","Math","floor","err","console","error","randomUUID","dialect","ph","i","q","id","escapeId","now","Date","ensureSchema","createTables","catch","createIfMissing","sql","query","str","txt","tasks","results","dispatch","task","t","ignore","cols","replace","map","c","join","_","stepId","runId","seq","name","JSON","stringify","input","attempt","handle","fn","Error","set","loop","drainTasks","onResult","handler","drainResults","onHeartbeat","_handler","dispatchRuns","runs","opts","length","byRun","run","has","reason","unique","values","at","chunk","slice","r","__","insert","release","wake","flatMap","namespace","priority","onDispatchedRun","consumer","stopped","inflight","slotFreed","Promise","resolve","max","ns","consumeRuns","add","stopRunConsumer","delete","renew","setInterval","renewRunLeases","unref","settled","free","size","rows","claimRuns","token","done","then","finally","sleep","allSettled","clearInterval","limit","staleBefore","transaction","tx","claimed","run_id","globalThis","crypto","tokens","tick","processed","race","claim","hold","left","row","runTask","stillHolds","step_id","parse","result","runStepHandler","get","settleTask","insertResult","status","output","startedAt","started_at","table","where","whereParams","leaseClause","found","ids","placeholders","intervalMs","round","renewHeld","list","ms","setTimeout","close"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudousxd/nestjs-durable-transport-db",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Database (SQL) Transport for nestjs-durable — DBOS-style: dispatch remote steps as rows in the durable DB, no broker",
5
5
  "license": "MIT",
6
6
  "author": "Davide Carvalho",
@@ -35,15 +35,16 @@
35
35
  }
36
36
  },
37
37
  "devDependencies": {
38
+ "@testcontainers/mysql": "10.18.0",
38
39
  "@testcontainers/postgresql": "10.18.0",
39
40
  "mysql2": "3.11.5",
40
41
  "pg": "8.13.1",
41
42
  "reflect-metadata": "0.2.2",
43
+ "tsup": "8.3.5",
42
44
  "typeorm": "0.3.31",
43
45
  "typescript": "5.9.3",
44
46
  "zod": "3.25.76",
45
- "tsup": "8.3.5",
46
- "@dudousxd/nestjs-durable-core": "^0.80.0"
47
+ "@dudousxd/nestjs-durable-core": "^0.85.0"
47
48
  },
48
49
  "module": "./dist/index.js",
49
50
  "exports": {