@dudousxd/nestjs-durable-transport-db 0.2.2 → 0.3.1

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,19 @@ function mikroOrmExecutor(em) {
71
71
  __name(mikroOrmExecutor, "mikroOrmExecutor");
72
72
 
73
73
  // src/db-transport.ts
74
+ var RUNS_INSERT_CHUNK = 500;
75
+ var DEADLOCK_RETRIES = 5;
76
+ function isDeadlock(err) {
77
+ const codes = [
78
+ err.code,
79
+ err.errno,
80
+ err.driverError?.code,
81
+ err.driverError?.errno
82
+ ];
83
+ return codes.some((c) => c === "ER_LOCK_DEADLOCK" || c === 1213 || c === "40P01");
84
+ }
85
+ __name(isDeadlock, "isDeadlock");
86
+ var RUNS_CLAIM_MAX = 50;
74
87
  function numberOption(value, fallback, min) {
75
88
  return value !== void 0 && Number.isFinite(value) && value >= min ? value : fallback;
76
89
  }
@@ -83,6 +96,8 @@ var DbTransport = class {
83
96
  group;
84
97
  tasksTable;
85
98
  resultsTable;
99
+ runsTable;
100
+ runConsumers = /* @__PURE__ */ new Set();
86
101
  pollMs;
87
102
  leaseMs;
88
103
  batchSize;
@@ -108,6 +123,7 @@ var DbTransport = class {
108
123
  const prefix = options.prefix ?? "durable";
109
124
  this.tasksTable = `${prefix}_transport_tasks`;
110
125
  this.resultsTable = `${prefix}_transport_results`;
126
+ this.runsTable = `${prefix}_transport_runs`;
111
127
  this.pollMs = numberOption(options.pollMs, 500, 0);
112
128
  this.leaseMs = numberOption(options.leaseMs, 3e4, 1);
113
129
  this.batchSize = Math.floor(numberOption(options.batchSize, 10, 1));
@@ -181,6 +197,18 @@ var DbTransport = class {
181
197
  ${this.q("claimed_at")} bigint,
182
198
  ${this.q("created_at")} bigint NOT NULL
183
199
  )`);
200
+ await this.createIfMissing(`CREATE TABLE IF NOT EXISTS ${this.q(this.runsTable)} (
201
+ ${this.q("run_id")} ${str} PRIMARY KEY,
202
+ ${this.q("ns")} ${str} NOT NULL,
203
+ ${this.q("priority")} integer NOT NULL,
204
+ ${this.q("wake")} integer NOT NULL,
205
+ ${this.q("claimed_by")} ${str},
206
+ ${this.q("claim_token")} ${str},
207
+ ${this.q("claimed_at")} bigint,
208
+ ${this.q("created_at")} bigint NOT NULL
209
+ )`);
210
+ 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(() => {
211
+ });
184
212
  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
213
  });
186
214
  }
@@ -224,6 +252,181 @@ var DbTransport = class {
224
252
  }
225
253
  onHeartbeat(_handler) {
226
254
  }
255
+ // ── run queue (engine ↔ engine) ─────────────────────────────────────────────────────────────
256
+ /**
257
+ * Queue `pending` runs for whichever engine instance polls the run queue first: one row per run,
258
+ * keyed by run id, so a run already waiting is not queued twice. A run whose row an instance holds
259
+ * right now is released for another take, so a dispatch landing while the run's previous entry is
260
+ * being handled is not lost when that entry is deleted. Up to {@link RUNS_INSERT_CHUNK} rows per
261
+ * insert.
262
+ */
263
+ async dispatchRuns(runs, opts) {
264
+ if (runs.length === 0) return;
265
+ await this.ensureSchema();
266
+ const byRun = /* @__PURE__ */ new Map();
267
+ for (const run of runs) {
268
+ if (!byRun.has(run.runId) || run.reason === "wake") byRun.set(run.runId, run);
269
+ }
270
+ const unique = [
271
+ ...byRun.values()
272
+ ].sort((a, b) => a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0);
273
+ const t = this.q(this.runsTable);
274
+ const cols = [
275
+ "run_id",
276
+ "ns",
277
+ "priority",
278
+ "wake",
279
+ "created_at"
280
+ ];
281
+ const now = this.now();
282
+ for (let at = 0; at < unique.length; at += RUNS_INSERT_CHUNK) {
283
+ const chunk = unique.slice(at, at + RUNS_INSERT_CHUNK);
284
+ const values = chunk.map((_, r) => `(${cols.map((__, c) => this.ph(r * cols.length + c + 1)).join(", ")})`).join(", ");
285
+ const insert = `INTO ${t} (${cols.map((c) => this.q(c)).join(", ")}) VALUES ${values}`;
286
+ const release = [
287
+ "claimed_by",
288
+ "claim_token",
289
+ "claimed_at"
290
+ ].map((c) => `${this.q(c)} = NULL`).join(", ");
291
+ const wake = this.q("wake");
292
+ 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}))`;
293
+ await this.retryOnDeadlock(() => this.exec.query(sql, chunk.flatMap((run, r) => [
294
+ run.runId,
295
+ opts?.namespace ?? "",
296
+ run.priority ?? 0,
297
+ run.reason === "wake" ? 1 : 0,
298
+ now + r
299
+ ])));
300
+ }
301
+ }
302
+ /**
303
+ * Poll the run queue, at most `opts.concurrency` runs in flight on this instance. Rows are claimed
304
+ * with `FOR UPDATE SKIP LOCKED` (instances never take the same run), highest priority then oldest
305
+ * first; a row is deleted once its handler settles, and its lease is renewed meanwhile, so a row is
306
+ * re-taken only after the instance holding it went down. The returned stop takes no more rows and
307
+ * resolves once the runs in flight settled.
308
+ */
309
+ onDispatchedRun(handler, opts) {
310
+ const consumer = {
311
+ stopped: false,
312
+ inflight: /* @__PURE__ */ new Set(),
313
+ slotFreed: void 0,
314
+ loop: Promise.resolve()
315
+ };
316
+ const concurrency = Math.max(1, Math.floor(opts.concurrency));
317
+ const ns = opts.namespace ?? "";
318
+ consumer.loop = this.consumeRuns(consumer, handler, concurrency, ns).catch((err) => {
319
+ this.onError(err);
320
+ });
321
+ this.runConsumers.add(consumer);
322
+ return () => this.stopRunConsumer(consumer);
323
+ }
324
+ async stopRunConsumer(consumer) {
325
+ consumer.stopped = true;
326
+ consumer.slotFreed?.();
327
+ await consumer.loop;
328
+ this.runConsumers.delete(consumer);
329
+ }
330
+ async consumeRuns(consumer, handler, concurrency, ns) {
331
+ const renew = setInterval(() => void this.renewRunLeases(consumer).catch(() => void 0), Math.max(1e3, Math.floor(this.leaseMs / 3)));
332
+ renew.unref?.();
333
+ const settled = /* @__PURE__ */ new Set();
334
+ try {
335
+ while (this.running && !consumer.stopped) {
336
+ const free = concurrency - consumer.inflight.size;
337
+ if (free <= 0) {
338
+ await new Promise((resolve) => {
339
+ consumer.slotFreed = resolve;
340
+ });
341
+ consumer.slotFreed = void 0;
342
+ continue;
343
+ }
344
+ let rows = [];
345
+ try {
346
+ await this.ensureSchema();
347
+ rows = await this.retryOnDeadlock(() => this.claimRuns(ns, Math.min(free, RUNS_CLAIM_MAX)));
348
+ } catch (err) {
349
+ if (this.running && !consumer.stopped) this.onError(err);
350
+ }
351
+ for (const { run, token } of rows) {
352
+ consumer.inflight.add(token);
353
+ const done = handler(run).catch(() => void 0).then(() => this.retryOnDeadlock(() => this.exec.query(`DELETE FROM ${this.q(this.runsTable)} WHERE ${this.q("claim_token")} = ${this.ph(1)}`, [
354
+ token
355
+ ])).catch(() => void 0)).finally(() => {
356
+ consumer.inflight.delete(token);
357
+ settled.delete(done);
358
+ consumer.slotFreed?.();
359
+ });
360
+ settled.add(done);
361
+ }
362
+ if (rows.length === 0) await this.sleep(this.pollMs);
363
+ }
364
+ await Promise.allSettled([
365
+ ...settled
366
+ ]);
367
+ } finally {
368
+ clearInterval(renew);
369
+ }
370
+ }
371
+ /**
372
+ * Run `statement`, again on a deadlock: queueing a run (an upsert), taking one (`SKIP LOCKED`)
373
+ * and deleting a handled one touch the same rows from different instances, and the database then
374
+ * rolls one of them back rather than wait (InnoDB reports `ER_LOCK_DEADLOCK`, Postgres `40P01`).
375
+ */
376
+ async retryOnDeadlock(statement) {
377
+ for (let attempt = 1; ; attempt += 1) {
378
+ try {
379
+ return await statement();
380
+ } catch (err) {
381
+ if (attempt >= DEADLOCK_RETRIES || !isDeadlock(err)) throw err;
382
+ await this.sleep(10 * attempt + Math.floor(Math.random() * 10));
383
+ }
384
+ }
385
+ }
386
+ async claimRuns(ns, limit) {
387
+ const t = this.q(this.runsTable);
388
+ const staleBefore = this.now() - this.leaseMs;
389
+ return this.exec.transaction(async (tx) => {
390
+ const rows = await tx.query(`SELECT ${this.q("run_id")}, ${this.q("wake")} FROM ${t}
391
+ WHERE ${this.q("ns")} = ${this.ph(1)}
392
+ AND (${this.q("claimed_at")} IS NULL OR ${this.q("claimed_at")} < ${this.ph(2)})
393
+ ORDER BY ${this.q("priority")} DESC, ${this.q("created_at")} ASC
394
+ LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED`, [
395
+ ns,
396
+ staleBefore
397
+ ]);
398
+ const claimed = rows.map((r) => ({
399
+ run: {
400
+ runId: r.run_id,
401
+ reason: Number(r.wake) === 1 ? "wake" : "start"
402
+ },
403
+ token: globalThis.crypto.randomUUID()
404
+ }));
405
+ const now = this.now();
406
+ for (const { run: { runId }, token } of claimed) {
407
+ 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)}
408
+ WHERE ${this.q("run_id")} = ${this.ph(4)}`, [
409
+ this.instanceId,
410
+ token,
411
+ now,
412
+ runId
413
+ ]);
414
+ }
415
+ return claimed;
416
+ });
417
+ }
418
+ /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */
419
+ async renewRunLeases(consumer) {
420
+ const tokens = [
421
+ ...consumer.inflight
422
+ ];
423
+ if (tokens.length === 0) return;
424
+ await this.exec.query(`UPDATE ${this.q(this.runsTable)} SET ${this.q("claimed_at")} = ${this.ph(1)}
425
+ WHERE ${this.q("claim_token")} IN (${tokens.map((_, i) => this.ph(i + 2)).join(", ")})`, [
426
+ this.now(),
427
+ ...tokens
428
+ ]);
429
+ }
227
430
  // ── polling ──────────────────────────────────────────────────────────────────────────────────
228
431
  /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */
229
432
  async loop(tick) {
@@ -499,7 +702,10 @@ var DbTransport = class {
499
702
  this.running = false;
500
703
  await Promise.allSettled([
501
704
  this.taskLoop,
502
- this.resultLoop
705
+ this.resultLoop,
706
+ ...[
707
+ ...this.runConsumers
708
+ ].map((c) => this.stopRunConsumer(c))
503
709
  ]);
504
710
  await Promise.allSettled([
505
711
  ...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,KAAKC,MAAAA,GAAtD;IACPC,aAAa,8BAAUC,OAAAA;AACrB,YAAMC,KAAKf,GAAGgB,kBAAiB;AAC/B,YAAMD,GAAGE,QAAO;AAChB,YAAMF,GAAGG,iBAAgB;AACzB,UAAI;AACF,cAAMC,SAAS,MAAML,GAAG;UACtBJ,OAAO,wBAAIC,KAAaC,WAAuBG,GAAGL,MAAMC,KAAKC,MAAAA,GAAtD;QACT,CAAA;AACA,cAAMG,GAAGK,kBAAiB;AAC1B,eAAOD;MACT,SAASE,KAAK;AACZ,cAAMN,GAAGO,oBAAmB;AAC5B,cAAMD;MACR,UAAA;AACE,cAAMN,GAAGQ,QAAO;MAClB;IACF,GAhBa;EAiBf;AACF;AAvBgBxB;AA0CT,SAASyB,iBAAiBC,IAAkB;AACjD,QAAMC,WAAWD,GAAGE,YAAW;AAC/B,SAAO;IACL1B,SAAS,WA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G,KAAKA,EAAE,YAAA,CAAA;MACVuB,KAAK,IAAA,CAAA,KACP,eAAeN,CAAAA,IAAKiF,MAAAA,4BAAkC;SACjD9E,QAAQC,IAAI,CAACC,MAAM,GAAG,KAAKtB,EAAEsB,CAAAA,CAAAA,aAAe,KAAKtB,EAAEsB,CAAAA,CAAAA,GAAK;MAC3D,GAAG,KAAKtB,EAAE,YAAA,CAAA;MACV,GAAG,KAAKA,EAAE,YAAA,CAAA;MACVuB,KAAK,IAAA,CAAA;AACX,UAAMkD,GAAG/D,MAAMD,KAAK;MAClB2D,OAAO3C;MACP2C,OAAO1C;MACP0C,OAAOzC;MACPyC,OAAOO;MACPP,OAAOQ,WAAWnH,SAAY,OAAOoE,KAAKC,UAAUsC,OAAOQ,MAAM;MACjER,OAAOzE,UAAUlC,SAAY,OAAOoE,KAAKC,UAAUsC,OAAOzE,KAAK;MAC/DyE,OAAOS,aAAa;MACpB,KAAK1E,IAAG;KACT;EACH;EAEQ2C,MAAMqD,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":["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/** Tries for a statement the database rolled back as a deadlock (see `retryOnDeadlock`). */\nconst DEADLOCK_RETRIES = 5;\n\n/** Whether `err` is the database rolling a statement back to break a deadlock. */\nfunction isDeadlock(err: unknown): boolean {\n const codes = [\n (err as { code?: unknown }).code,\n (err as { errno?: unknown }).errno,\n (err as { driverError?: { code?: unknown; errno?: unknown } }).driverError?.code,\n (err as { driverError?: { code?: unknown; errno?: unknown } }).driverError?.errno,\n ];\n return codes.some((c) => c === 'ER_LOCK_DEADLOCK' || c === 1213 || c === '40P01');\n}\n\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 // In run-id order: two dispatches touching overlapping rows lock them in the same order.\n const unique = [...byRun.values()].sort((a, b) =>\n a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0,\n );\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.retryOnDeadlock(() =>\n 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 /**\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.retryOnDeadlock(() =>\n this.claimRuns(ns, Math.min(free, RUNS_CLAIM_MAX)),\n );\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.retryOnDeadlock(() =>\n this.exec.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 /**\n * Run `statement`, again on a deadlock: queueing a run (an upsert), taking one (`SKIP LOCKED`)\n * and deleting a handled one touch the same rows from different instances, and the database then\n * rolls one of them back rather than wait (InnoDB reports `ER_LOCK_DEADLOCK`, Postgres `40P01`).\n */\n private async retryOnDeadlock<T>(statement: () => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await statement();\n } catch (err) {\n if (attempt >= DEADLOCK_RETRIES || !isDeadlock(err)) throw err;\n await this.sleep(10 * attempt + Math.floor(Math.random() * 10));\n }\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;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C,QAAI,KAAKE,WAAY6G,eAAc,KAAK7G,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","DEADLOCK_RETRIES","isDeadlock","err","codes","code","errno","driverError","some","c","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","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","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","sort","a","b","at","chunk","slice","r","__","insert","release","wake","retryOnDeadlock","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","statement","random","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,33 @@ 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
+ /**
181
+ * Run `statement`, again on a deadlock: queueing a run (an upsert), taking one (`SKIP LOCKED`)
182
+ * and deleting a handled one touch the same rows from different instances, and the database then
183
+ * rolls one of them back rather than wait (InnoDB reports `ER_LOCK_DEADLOCK`, Postgres `40P01`).
184
+ */
185
+ private retryOnDeadlock;
186
+ private claimRuns;
187
+ /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */
188
+ private renewRunLeases;
157
189
  /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */
158
190
  private loop;
159
191
  /**
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,33 @@ 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
+ /**
181
+ * Run `statement`, again on a deadlock: queueing a run (an upsert), taking one (`SKIP LOCKED`)
182
+ * and deleting a handled one touch the same rows from different instances, and the database then
183
+ * rolls one of them back rather than wait (InnoDB reports `ER_LOCK_DEADLOCK`, Postgres `40P01`).
184
+ */
185
+ private retryOnDeadlock;
186
+ private claimRuns;
187
+ /** Keep the rows of the runs in flight leased, so a long turn is not re-taken by another instance. */
188
+ private renewRunLeases;
157
189
  /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */
158
190
  private loop;
159
191
  /**
package/dist/index.js CHANGED
@@ -45,6 +45,19 @@ function mikroOrmExecutor(em) {
45
45
  __name(mikroOrmExecutor, "mikroOrmExecutor");
46
46
 
47
47
  // src/db-transport.ts
48
+ var RUNS_INSERT_CHUNK = 500;
49
+ var DEADLOCK_RETRIES = 5;
50
+ function isDeadlock(err) {
51
+ const codes = [
52
+ err.code,
53
+ err.errno,
54
+ err.driverError?.code,
55
+ err.driverError?.errno
56
+ ];
57
+ return codes.some((c) => c === "ER_LOCK_DEADLOCK" || c === 1213 || c === "40P01");
58
+ }
59
+ __name(isDeadlock, "isDeadlock");
60
+ var RUNS_CLAIM_MAX = 50;
48
61
  function numberOption(value, fallback, min) {
49
62
  return value !== void 0 && Number.isFinite(value) && value >= min ? value : fallback;
50
63
  }
@@ -57,6 +70,8 @@ var DbTransport = class {
57
70
  group;
58
71
  tasksTable;
59
72
  resultsTable;
73
+ runsTable;
74
+ runConsumers = /* @__PURE__ */ new Set();
60
75
  pollMs;
61
76
  leaseMs;
62
77
  batchSize;
@@ -82,6 +97,7 @@ var DbTransport = class {
82
97
  const prefix = options.prefix ?? "durable";
83
98
  this.tasksTable = `${prefix}_transport_tasks`;
84
99
  this.resultsTable = `${prefix}_transport_results`;
100
+ this.runsTable = `${prefix}_transport_runs`;
85
101
  this.pollMs = numberOption(options.pollMs, 500, 0);
86
102
  this.leaseMs = numberOption(options.leaseMs, 3e4, 1);
87
103
  this.batchSize = Math.floor(numberOption(options.batchSize, 10, 1));
@@ -155,6 +171,18 @@ var DbTransport = class {
155
171
  ${this.q("claimed_at")} bigint,
156
172
  ${this.q("created_at")} bigint NOT NULL
157
173
  )`);
174
+ await this.createIfMissing(`CREATE TABLE IF NOT EXISTS ${this.q(this.runsTable)} (
175
+ ${this.q("run_id")} ${str} PRIMARY KEY,
176
+ ${this.q("ns")} ${str} NOT NULL,
177
+ ${this.q("priority")} integer NOT NULL,
178
+ ${this.q("wake")} integer NOT NULL,
179
+ ${this.q("claimed_by")} ${str},
180
+ ${this.q("claim_token")} ${str},
181
+ ${this.q("claimed_at")} bigint,
182
+ ${this.q("created_at")} bigint NOT NULL
183
+ )`);
184
+ 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(() => {
185
+ });
158
186
  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
187
  });
160
188
  }
@@ -198,6 +226,181 @@ var DbTransport = class {
198
226
  }
199
227
  onHeartbeat(_handler) {
200
228
  }
229
+ // ── run queue (engine ↔ engine) ─────────────────────────────────────────────────────────────
230
+ /**
231
+ * Queue `pending` runs for whichever engine instance polls the run queue first: one row per run,
232
+ * keyed by run id, so a run already waiting is not queued twice. A run whose row an instance holds
233
+ * right now is released for another take, so a dispatch landing while the run's previous entry is
234
+ * being handled is not lost when that entry is deleted. Up to {@link RUNS_INSERT_CHUNK} rows per
235
+ * insert.
236
+ */
237
+ async dispatchRuns(runs, opts) {
238
+ if (runs.length === 0) return;
239
+ await this.ensureSchema();
240
+ const byRun = /* @__PURE__ */ new Map();
241
+ for (const run of runs) {
242
+ if (!byRun.has(run.runId) || run.reason === "wake") byRun.set(run.runId, run);
243
+ }
244
+ const unique = [
245
+ ...byRun.values()
246
+ ].sort((a, b) => a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0);
247
+ const t = this.q(this.runsTable);
248
+ const cols = [
249
+ "run_id",
250
+ "ns",
251
+ "priority",
252
+ "wake",
253
+ "created_at"
254
+ ];
255
+ const now = this.now();
256
+ for (let at = 0; at < unique.length; at += RUNS_INSERT_CHUNK) {
257
+ const chunk = unique.slice(at, at + RUNS_INSERT_CHUNK);
258
+ const values = chunk.map((_, r) => `(${cols.map((__, c) => this.ph(r * cols.length + c + 1)).join(", ")})`).join(", ");
259
+ const insert = `INTO ${t} (${cols.map((c) => this.q(c)).join(", ")}) VALUES ${values}`;
260
+ const release = [
261
+ "claimed_by",
262
+ "claim_token",
263
+ "claimed_at"
264
+ ].map((c) => `${this.q(c)} = NULL`).join(", ");
265
+ const wake = this.q("wake");
266
+ 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}))`;
267
+ await this.retryOnDeadlock(() => this.exec.query(sql, chunk.flatMap((run, r) => [
268
+ run.runId,
269
+ opts?.namespace ?? "",
270
+ run.priority ?? 0,
271
+ run.reason === "wake" ? 1 : 0,
272
+ now + r
273
+ ])));
274
+ }
275
+ }
276
+ /**
277
+ * Poll the run queue, at most `opts.concurrency` runs in flight on this instance. Rows are claimed
278
+ * with `FOR UPDATE SKIP LOCKED` (instances never take the same run), highest priority then oldest
279
+ * first; a row is deleted once its handler settles, and its lease is renewed meanwhile, so a row is
280
+ * re-taken only after the instance holding it went down. The returned stop takes no more rows and
281
+ * resolves once the runs in flight settled.
282
+ */
283
+ onDispatchedRun(handler, opts) {
284
+ const consumer = {
285
+ stopped: false,
286
+ inflight: /* @__PURE__ */ new Set(),
287
+ slotFreed: void 0,
288
+ loop: Promise.resolve()
289
+ };
290
+ const concurrency = Math.max(1, Math.floor(opts.concurrency));
291
+ const ns = opts.namespace ?? "";
292
+ consumer.loop = this.consumeRuns(consumer, handler, concurrency, ns).catch((err) => {
293
+ this.onError(err);
294
+ });
295
+ this.runConsumers.add(consumer);
296
+ return () => this.stopRunConsumer(consumer);
297
+ }
298
+ async stopRunConsumer(consumer) {
299
+ consumer.stopped = true;
300
+ consumer.slotFreed?.();
301
+ await consumer.loop;
302
+ this.runConsumers.delete(consumer);
303
+ }
304
+ async consumeRuns(consumer, handler, concurrency, ns) {
305
+ const renew = setInterval(() => void this.renewRunLeases(consumer).catch(() => void 0), Math.max(1e3, Math.floor(this.leaseMs / 3)));
306
+ renew.unref?.();
307
+ const settled = /* @__PURE__ */ new Set();
308
+ try {
309
+ while (this.running && !consumer.stopped) {
310
+ const free = concurrency - consumer.inflight.size;
311
+ if (free <= 0) {
312
+ await new Promise((resolve) => {
313
+ consumer.slotFreed = resolve;
314
+ });
315
+ consumer.slotFreed = void 0;
316
+ continue;
317
+ }
318
+ let rows = [];
319
+ try {
320
+ await this.ensureSchema();
321
+ rows = await this.retryOnDeadlock(() => this.claimRuns(ns, Math.min(free, RUNS_CLAIM_MAX)));
322
+ } catch (err) {
323
+ if (this.running && !consumer.stopped) this.onError(err);
324
+ }
325
+ for (const { run, token } of rows) {
326
+ consumer.inflight.add(token);
327
+ const done = handler(run).catch(() => void 0).then(() => this.retryOnDeadlock(() => this.exec.query(`DELETE FROM ${this.q(this.runsTable)} WHERE ${this.q("claim_token")} = ${this.ph(1)}`, [
328
+ token
329
+ ])).catch(() => void 0)).finally(() => {
330
+ consumer.inflight.delete(token);
331
+ settled.delete(done);
332
+ consumer.slotFreed?.();
333
+ });
334
+ settled.add(done);
335
+ }
336
+ if (rows.length === 0) await this.sleep(this.pollMs);
337
+ }
338
+ await Promise.allSettled([
339
+ ...settled
340
+ ]);
341
+ } finally {
342
+ clearInterval(renew);
343
+ }
344
+ }
345
+ /**
346
+ * Run `statement`, again on a deadlock: queueing a run (an upsert), taking one (`SKIP LOCKED`)
347
+ * and deleting a handled one touch the same rows from different instances, and the database then
348
+ * rolls one of them back rather than wait (InnoDB reports `ER_LOCK_DEADLOCK`, Postgres `40P01`).
349
+ */
350
+ async retryOnDeadlock(statement) {
351
+ for (let attempt = 1; ; attempt += 1) {
352
+ try {
353
+ return await statement();
354
+ } catch (err) {
355
+ if (attempt >= DEADLOCK_RETRIES || !isDeadlock(err)) throw err;
356
+ await this.sleep(10 * attempt + Math.floor(Math.random() * 10));
357
+ }
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
+ }
201
404
  // ── polling ──────────────────────────────────────────────────────────────────────────────────
202
405
  /** Run `tick` repeatedly; sleep `pollMs` when it reports an empty queue. Stops on `close()`. */
203
406
  async loop(tick) {
@@ -473,7 +676,10 @@ var DbTransport = class {
473
676
  this.running = false;
474
677
  await Promise.allSettled([
475
678
  this.taskLoop,
476
- this.resultLoop
679
+ this.resultLoop,
680
+ ...[
681
+ ...this.runConsumers
682
+ ].map((c) => this.stopRunConsumer(c))
477
683
  ]);
478
684
  await Promise.allSettled([
479
685
  ...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,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,GAAGE,QAAO;AAChB,YAAMF,GAAGG,i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D,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/** Tries for a statement the database rolled back as a deadlock (see `retryOnDeadlock`). */\nconst DEADLOCK_RETRIES = 5;\n\n/** Whether `err` is the database rolling a statement back to break a deadlock. */\nfunction isDeadlock(err: unknown): boolean {\n const codes = [\n (err as { code?: unknown }).code,\n (err as { errno?: unknown }).errno,\n (err as { driverError?: { code?: unknown; errno?: unknown } }).driverError?.code,\n (err as { driverError?: { code?: unknown; errno?: unknown } }).driverError?.errno,\n ];\n return codes.some((c) => c === 'ER_LOCK_DEADLOCK' || c === 1213 || c === '40P01');\n}\n\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 // In run-id order: two dispatches touching overlapping rows lock them in the same order.\n const unique = [...byRun.values()].sort((a, b) =>\n a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0,\n );\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.retryOnDeadlock(() =>\n 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 /**\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.retryOnDeadlock(() =>\n this.claimRuns(ns, Math.min(free, RUNS_CLAIM_MAX)),\n );\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.retryOnDeadlock(() =>\n this.exec.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 /**\n * Run `statement`, again on a deadlock: queueing a run (an upsert), taking one (`SKIP LOCKED`)\n * and deleting a handled one touch the same rows from different instances, and the database then\n * rolls one of them back rather than wait (InnoDB reports `ER_LOCK_DEADLOCK`, Postgres `40P01`).\n */\n private async retryOnDeadlock<T>(statement: () => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await statement();\n } catch (err) {\n if (attempt >= DEADLOCK_RETRIES || !isDeadlock(err)) throw err;\n await this.sleep(10 * attempt + Math.floor(Math.random() * 10));\n }\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,KAAKf,GAAGgB,kBAAiB;AAC/B,YAAMD,GAAGE,QAAO;AAChB,YAAMF,GAAGG,iBAAgB;AACzB,UAAI;AACF,cAAMC,SAAS,MAAML,GAAG;UACtBJ,OAAO,wBAAIC,KAAaC,WAAuBG,GAAGL,MAAMC,KAAKC,MAAAA,GAAtD;QACT,CAAA;AACA,cAAMG,GAAGK,kBAAiB;AAC1B,eAAOD;MACT,SAASE,KAAK;AACZ,cAAMN,GAAGO,oBAAmB;AAC5B,cAAMD;MACR,UAAA;AACE,cAAMN,GAAGQ,QAAO;MAClB;IACF,GAhBa;EAiBf;AACF;AAvBgBxB;AA0CT,SAASyB,iBAAiBC,IAAkB;AACjD,QAAMC,WAAWD,GAAGE,YAAW;AAC/B,SAAO;IACL1B,SAAS,WAAWC,KAAKwB,SAAS,YAAYE,IAAI,IAAI,aAAa;IACnEtB,UAAU,wBAACC,OAAOmB,SAASG,gBAAgBtB,EAAAA,GAAjC;IACVG,OA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B,KAAK3H,IAAG;KACT;EACH;EAEQ2F,MAAM6C,IAA2B;AACvC,WAAO,IAAIlE,QAAQ,CAACd,MAAMiF,WAAWjF,GAAGgF,EAAAA,CAAAA;EAC1C;;EAGA,MAAME,QAAuB;AAC3B,SAAKhK,UAAU;AACf,UAAM4F,QAAQsB,WAAW;MACvB,KAAKhH;MACL,KAAKC;SACF;WAAI,KAAKf;QAAcoD,IAAI,CAACnE,MAAM,KAAK6H,gBAAgB7H,CAAAA,CAAAA;KAC3D;AAED,UAAMuH,QAAQsB,WAAW;SAAI,KAAK9G;KAAa;AAC/C,QAAI,KAAKE,WAAY6G,eAAc,KAAK7G,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","DEADLOCK_RETRIES","isDeadlock","err","codes","code","errno","driverError","some","c","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","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","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","sort","a","b","at","chunk","slice","r","__","insert","release","wake","retryOnDeadlock","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","statement","random","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.1",
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.3"
47
48
  },
48
49
  "module": "./dist/index.js",
49
50
  "exports": {