@dudousxd/nestjs-durable-store-typeorm 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -29,6 +29,7 @@ __export(index_exports, {
29
29
  MYSQL_DATETIME_TYPE: () => MYSQL_DATETIME_TYPE,
30
30
  RunAttributeEntity: () => RunAttributeEntity,
31
31
  ScheduleEntity: () => ScheduleEntity,
32
+ SignalIdEntity: () => SignalIdEntity,
32
33
  SignalWaiterEntity: () => SignalWaiterEntity,
33
34
  StepCheckpointEntity: () => StepCheckpointEntity,
34
35
  TypeOrmStateStore: () => TypeOrmStateStore,
@@ -97,6 +98,8 @@ var WorkflowRunEntity = class {
97
98
  priority;
98
99
  namespace;
99
100
  origin;
101
+ tenantId;
102
+ tenantKind;
100
103
  createdAt;
101
104
  updatedAt;
102
105
  };
@@ -157,6 +160,15 @@ var BufferedEventEntity = class {
157
160
  payload;
158
161
  publishedAt;
159
162
  };
163
+ var SignalIdEntity = class {
164
+ static {
165
+ __name(this, "SignalIdEntity");
166
+ }
167
+ token;
168
+ signalId;
169
+ /** Epoch ms as a `bigint` (drivers hand it back as a string): exact, unlike a DATETIME. */
170
+ expiresAt;
171
+ };
160
172
  var ScheduleEntity = class {
161
173
  static {
162
174
  __name(this, "ScheduleEntity");
@@ -171,6 +183,8 @@ var ScheduleEntity = class {
171
183
  tags;
172
184
  spec;
173
185
  state;
186
+ tenantId;
187
+ tenantKind;
174
188
  createdAt;
175
189
  updatedAt;
176
190
  };
@@ -288,6 +302,18 @@ function durableEntities(options = {}) {
288
302
  nullable: true,
289
303
  name: col("origin")
290
304
  },
305
+ // The CUSTOMER (tenancy) the run belongs to — not the worker-pool `namespace`. Nullable, no
306
+ // default: NULL = no tenant. `ensureTypeOrmDurableSchema` adds the columns in place.
307
+ tenantId: {
308
+ type: "text",
309
+ nullable: true,
310
+ name: col("tenantId")
311
+ },
312
+ tenantKind: {
313
+ type: "text",
314
+ nullable: true,
315
+ name: col("tenantKind")
316
+ },
291
317
  createdAt: {
292
318
  type: Date,
293
319
  name: col("createdAt")
@@ -521,6 +547,29 @@ function durableEntities(options = {}) {
521
547
  }
522
548
  }
523
549
  });
550
+ const signalIds = new import_typeorm.EntitySchema({
551
+ name: "SignalIdEntity",
552
+ target: SignalIdEntity,
553
+ tableName: "durable_signal_ids",
554
+ // Its `(token, signal_id)` key and `expires_at` index are raw DDL in `schema.ts`, like every
555
+ // other durable table's.
556
+ columns: {
557
+ token: {
558
+ type: "text",
559
+ primary: true,
560
+ name: col("token")
561
+ },
562
+ signalId: {
563
+ type: "text",
564
+ primary: true,
565
+ name: col("signalId")
566
+ },
567
+ expiresAt: {
568
+ type: "bigint",
569
+ name: col("expiresAt")
570
+ }
571
+ }
572
+ });
524
573
  const schedules = new import_typeorm.EntitySchema({
525
574
  name: "ScheduleEntity",
526
575
  target: ScheduleEntity,
@@ -566,6 +615,17 @@ function durableEntities(options = {}) {
566
615
  name: col("state"),
567
616
  transformer: jsonColumnTransformer("schedules.state")
568
617
  },
618
+ // The customer the schedule (and every run it starts) belongs to. NULL = none.
619
+ tenantId: {
620
+ type: "text",
621
+ nullable: true,
622
+ name: col("tenantId")
623
+ },
624
+ tenantKind: {
625
+ type: "text",
626
+ nullable: true,
627
+ name: col("tenantKind")
628
+ },
569
629
  createdAt: {
570
630
  type: Date,
571
631
  name: col("createdAt")
@@ -583,6 +643,7 @@ function durableEntities(options = {}) {
583
643
  signalWaiters,
584
644
  bufferedSignals,
585
645
  bufferedEvents,
646
+ signalIds,
586
647
  schedules
587
648
  ];
588
649
  }
@@ -635,6 +696,7 @@ var TABLE_TO_ENTITY = {
635
696
  durable_signal_waiters: SignalWaiterEntity,
636
697
  durable_buffered_signals: BufferedSignalEntity,
637
698
  durable_buffered_events: BufferedEventEntity,
699
+ durable_signal_ids: SignalIdEntity,
638
700
  durable_schedules: ScheduleEntity
639
701
  };
640
702
  function durableManagedTables() {
@@ -717,6 +779,8 @@ async function ensureTypeOrmDurableSchema(dataSource, options = {}) {
717
779
  const bevCol = /* @__PURE__ */ __name((property) => q(resolve("durable_buffered_events", property)), "bevCol");
718
780
  const schedules = q("durable_schedules");
719
781
  const schCol = /* @__PURE__ */ __name((property) => q(resolve("durable_schedules", property)), "schCol");
782
+ const signalIds = q("durable_signal_ids");
783
+ const sidCol = /* @__PURE__ */ __name((property) => q(resolve("durable_signal_ids", property)), "sidCol");
720
784
  const num = isPg ? "double precision" : isMysql ? "double" : "real";
721
785
  const bufferedId = isSqlite ? `${bufCol("id")} integer PRIMARY KEY AUTOINCREMENT` : isMysql ? `${bufCol("id")} bigint NOT NULL AUTO_INCREMENT PRIMARY KEY` : isPg ? `${bufCol("id")} bigserial PRIMARY KEY` : `${bufCol("id")} bigint NOT NULL AUTO_INCREMENT PRIMARY KEY`;
722
786
  const tables = [
@@ -732,6 +796,7 @@ async function ensureTypeOrmDurableSchema(dataSource, options = {}) {
732
796
  ${runsCol("awaitingDecisionTaskId")} ${str},
733
797
  ${runsCol("recoveryAttempts")} ${int}, ${runsCol("tags")} ${txt}, ${runsCol("searchAttributes")} ${txt},
734
798
  ${runsCol("priority")} ${int}, ${runsCol("namespace")} ${nsCol}, ${runsCol("origin")} ${str},
799
+ ${runsCol("tenantId")} ${str}, ${runsCol("tenantKind")} ${str},
735
800
  ${runsCol("createdAt")} ${ts} NOT NULL, ${runsCol("updatedAt")} ${ts} NOT NULL
736
801
  )`
737
802
  ],
@@ -779,6 +844,16 @@ async function ensureTypeOrmDurableSchema(dataSource, options = {}) {
779
844
  ${bevCol("payload")} ${txt}, ${bevCol("publishedAt")} ${ts} NOT NULL
780
845
  )`
781
846
  ],
847
+ // Signal dedupe ids (`signal(..., { id })`): one row per (token, id) until `expires_at` (epoch
848
+ // ms as a bigint — exact, unlike a MySQL DATETIME).
849
+ [
850
+ "durable_signal_ids",
851
+ `CREATE TABLE IF NOT EXISTS ${signalIds} (
852
+ ${sidCol("token")} ${str} NOT NULL, ${sidCol("signalId")} ${str} NOT NULL,
853
+ ${sidCol("expiresAt")} bigint NOT NULL,
854
+ PRIMARY KEY (${sidCol("token")}, ${sidCol("signalId")})
855
+ )`
856
+ ],
782
857
  // Persisted schedules. `next_fire_at` is epoch ms as a bigint (exact, so the compare-and-set on
783
858
  // it survives MySQL's DATETIME millisecond truncation); `spec`/`state` are engine-owned JSON.
784
859
  [
@@ -789,6 +864,7 @@ async function ensureTypeOrmDurableSchema(dataSource, options = {}) {
789
864
  ${schCol("paused")} boolean NOT NULL DEFAULT ${isPg ? "false" : "0"},
790
865
  ${schCol("nextFireAt")} bigint, ${schCol("tags")} ${txt},
791
866
  ${schCol("spec")} ${txt} NOT NULL, ${schCol("state")} ${txt} NOT NULL,
867
+ ${schCol("tenantId")} ${str}, ${schCol("tenantKind")} ${str},
792
868
  ${schCol("createdAt")} ${ts} NOT NULL, ${schCol("updatedAt")} ${ts} NOT NULL
793
869
  )`
794
870
  ]
@@ -842,6 +918,15 @@ async function ensureTypeOrmDurableSchema(dataSource, options = {}) {
842
918
  [
843
919
  "origin",
844
920
  str
921
+ ],
922
+ // The customer (tenancy). Nullable, never back-filled: a run written before it has no tenant.
923
+ [
924
+ "tenantId",
925
+ str
926
+ ],
927
+ [
928
+ "tenantKind",
929
+ str
845
930
  ]
846
931
  ],
847
932
  durable_step_checkpoints: [
@@ -881,6 +966,16 @@ async function ensureTypeOrmDurableSchema(dataSource, options = {}) {
881
966
  "parallelGroup",
882
967
  str
883
968
  ]
969
+ ],
970
+ durable_schedules: [
971
+ [
972
+ "tenantId",
973
+ str
974
+ ],
975
+ [
976
+ "tenantKind",
977
+ str
978
+ ]
884
979
  ]
885
980
  };
886
981
  const repairs = [];
@@ -998,6 +1093,12 @@ async function ensureTypeOrmDurableSchema(dataSource, options = {}) {
998
1093
  `${bufferedEvents} (${bevCol("name")}, ${bevCol("publishedAt")})`,
999
1094
  "durable_buffered_events"
1000
1095
  ],
1096
+ // The expired-signal-id sweep (`expires_at <= now`).
1097
+ [
1098
+ "durable_signal_ids_expires_at_idx",
1099
+ `${signalIds} (${sidCol("expiresAt")})`,
1100
+ "durable_signal_ids"
1101
+ ],
1001
1102
  // Search-attribute pushdown: equality + range predicates probe by (key, value). Two composite
1002
1103
  // indexes — one per typed column — so a numeric range or a string equality is an index scan.
1003
1104
  // Persisted schedules: the poll's "due by T" scan (`paused = false AND next_fire_at <= T`).
@@ -1006,6 +1107,17 @@ async function ensureTypeOrmDurableSchema(dataSource, options = {}) {
1006
1107
  `${schedules} (${schCol("paused")}, ${schCol("nextFireAt")})`,
1007
1108
  "durable_schedules"
1008
1109
  ],
1110
+ // Tenancy: app-facing reads filter by the customer and page newest first.
1111
+ [
1112
+ "durable_workflow_runs_tenant_idx",
1113
+ `${runs} (${runsCol("tenantId")}, ${runsCol("createdAt")})`,
1114
+ "durable_workflow_runs"
1115
+ ],
1116
+ [
1117
+ "durable_schedules_tenant_idx",
1118
+ `${schedules} (${schCol("tenantId")})`,
1119
+ "durable_schedules"
1120
+ ],
1009
1121
  [
1010
1122
  "durable_run_attributes_num_idx",
1011
1123
  `${runAttributes} (${attrCol("key")}, ${attrCol("numValue")})`,
@@ -1101,9 +1213,25 @@ var TypeOrmStateStore = class {
1101
1213
  }
1102
1214
  dataSource;
1103
1215
  options;
1216
+ // The round-trip-saving optional methods, bound per dialect where they save a statement (see
1217
+ // `TypeOrmRoundTrips`); absent on SQLite, where the engine's read-then-write calls are used.
1218
+ settleResultsIfPending;
1219
+ insertCheckpointIfAbsent;
1220
+ tryLockRunAndGet;
1221
+ claimPendingRuns;
1104
1222
  constructor(dataSource, options = {}) {
1105
1223
  this.dataSource = dataSource;
1106
1224
  this.options = options;
1225
+ const type = String(dataSource.options.type);
1226
+ const dialect = type === "postgres" ? "postgres" : type === "mysql" ? "mysql" : void 0;
1227
+ if (!dialect) return;
1228
+ const fast = new TypeOrmRoundTrips(dataSource, dialect, this);
1229
+ this.insertCheckpointIfAbsent = (cp) => fast.insertCheckpointIfAbsent(cp);
1230
+ this.settleResultsIfPending = (results) => fast.settleResultsIfPending(results);
1231
+ this.claimPendingRuns = (limit, owner, until, now, ns) => fast.claimPendingRuns(limit, owner, until, now, ns);
1232
+ if (dialect === "postgres") {
1233
+ this.tryLockRunAndGet = (runId, owner, until, now) => fast.tryLockRunAndGet(runId, owner, until, now);
1234
+ }
1107
1235
  }
1108
1236
  async ensureSchema() {
1109
1237
  await ensureTypeOrmDurableSchema(this.dataSource, {
@@ -1126,6 +1254,9 @@ var TypeOrmStateStore = class {
1126
1254
  bufferedEvents() {
1127
1255
  return this.dataSource.getRepository(BufferedEventEntity);
1128
1256
  }
1257
+ signalIds() {
1258
+ return this.dataSource.getRepository(SignalIdEntity);
1259
+ }
1129
1260
  attributes() {
1130
1261
  return this.dataSource.getRepository(RunAttributeEntity);
1131
1262
  }
@@ -1408,6 +1539,24 @@ var TypeOrmStateStore = class {
1408
1539
  }
1409
1540
  async settleCheckpointsIfPending(settlements) {
1410
1541
  if (settlements.length === 0) return [];
1542
+ if (settlements.length === 1) {
1543
+ const s = settlements[0];
1544
+ const result = await this.checkpoints().createQueryBuilder().update().set({
1545
+ status: s.status,
1546
+ output: s.output ?? null,
1547
+ error: s.error ?? null,
1548
+ events: s.events ?? null,
1549
+ startedAt: s.startedAt,
1550
+ finishedAt: s.finishedAt
1551
+ }).where({
1552
+ runId: s.runId,
1553
+ seq: s.seq,
1554
+ status: "pending"
1555
+ }).execute();
1556
+ return [
1557
+ result.affected === 1
1558
+ ];
1559
+ }
1411
1560
  return this.dataSource.transaction(async (em) => {
1412
1561
  const repo = em.getRepository(StepCheckpointEntity);
1413
1562
  const pending = await this.lockPendingCheckpoints(repo, settlements, [
@@ -1660,6 +1809,7 @@ var TypeOrmStateStore = class {
1660
1809
  origins: named
1661
1810
  } : {});
1662
1811
  }
1812
+ applyTenantWhere(qb, "r", query);
1663
1813
  if (query.status) qb.andWhere("r.status = :status", {
1664
1814
  status: query.status
1665
1815
  });
@@ -1774,6 +1924,8 @@ var TypeOrmStateStore = class {
1774
1924
  if ("tags" in patch) set.tags = patch.tags ?? null;
1775
1925
  if (patch.spec !== void 0) set.spec = patch.spec;
1776
1926
  if (patch.state !== void 0) set.state = patch.state;
1927
+ if ("tenantId" in patch) set.tenantId = patch.tenantId ?? null;
1928
+ if ("tenantKind" in patch) set.tenantKind = patch.tenantKind ?? null;
1777
1929
  if (patch.updatedAt !== void 0) set.updatedAt = patch.updatedAt;
1778
1930
  if (!Object.keys(set).length) return await this.getSchedule(id) !== null;
1779
1931
  const qb = this.schedules().createQueryBuilder().update().set(set).where({
@@ -1808,6 +1960,7 @@ var TypeOrmStateStore = class {
1808
1960
  if (query.tag !== void 0) qb.andWhere("s.tags LIKE :tag", {
1809
1961
  tag: `%"${query.tag}"%`
1810
1962
  });
1963
+ applyTenantWhere(qb, "s", query);
1811
1964
  if (query.dueBy !== void 0) qb.andWhere("s.paused = :notPaused AND s.nextFireAt <= :dueBy", {
1812
1965
  notPaused: false,
1813
1966
  dueBy: query.dueBy
@@ -2098,6 +2251,87 @@ var TypeOrmStateStore = class {
2098
2251
  payload: e.payload ?? void 0
2099
2252
  };
2100
2253
  }
2254
+ async takeOldestBufferedSignal(tokens) {
2255
+ if (tokens.length === 0) return null;
2256
+ const unique = [
2257
+ ...new Set(tokens)
2258
+ ];
2259
+ for (; ; ) {
2260
+ const e = await this.buffered().findOne({
2261
+ where: {
2262
+ token: (0, import_typeorm2.In)(unique)
2263
+ },
2264
+ order: {
2265
+ id: "ASC"
2266
+ }
2267
+ });
2268
+ if (!e) return null;
2269
+ const deleted = await this.buffered().delete({
2270
+ id: e.id
2271
+ });
2272
+ if (deleted.affected === 1) return {
2273
+ token: e.token,
2274
+ payload: e.payload ?? void 0
2275
+ };
2276
+ }
2277
+ }
2278
+ async claimSignalId(token, id, expiresAt, nowMs) {
2279
+ for (; ; ) {
2280
+ try {
2281
+ await this.signalIds().insert({
2282
+ token,
2283
+ signalId: id,
2284
+ expiresAt
2285
+ });
2286
+ return true;
2287
+ } catch (err) {
2288
+ if (!isUniqueViolation(err)) throw err;
2289
+ }
2290
+ const taken = await this.signalIds().update({
2291
+ token,
2292
+ signalId: id,
2293
+ expiresAt: (0, import_typeorm2.LessThanOrEqual)(nowMs)
2294
+ }, {
2295
+ expiresAt
2296
+ });
2297
+ if (taken.affected === 1) return true;
2298
+ if (await this.signalIds().exists({
2299
+ where: {
2300
+ token,
2301
+ signalId: id
2302
+ }
2303
+ })) return false;
2304
+ }
2305
+ }
2306
+ async releaseSignalId(token, id) {
2307
+ await this.signalIds().delete({
2308
+ token,
2309
+ signalId: id
2310
+ });
2311
+ }
2312
+ async deleteExpiredSignalIds(nowMs, limit) {
2313
+ const rows = await this.signalIds().find({
2314
+ select: {
2315
+ token: true,
2316
+ signalId: true
2317
+ },
2318
+ where: {
2319
+ expiresAt: (0, import_typeorm2.LessThanOrEqual)(nowMs)
2320
+ },
2321
+ take: limit
2322
+ });
2323
+ if (rows.length === 0) return 0;
2324
+ const result = await this.signalIds().delete({
2325
+ token: (0, import_typeorm2.In)([
2326
+ ...new Set(rows.map((r) => r.token))
2327
+ ]),
2328
+ signalId: (0, import_typeorm2.In)([
2329
+ ...new Set(rows.map((r) => r.signalId))
2330
+ ]),
2331
+ expiresAt: (0, import_typeorm2.LessThanOrEqual)(nowMs)
2332
+ });
2333
+ return result.affected ?? rows.length;
2334
+ }
2101
2335
  async listBufferedSignals(tokenPrefix, afterId, limit) {
2102
2336
  const rows = await this.buffered().find({
2103
2337
  where: {
@@ -2183,6 +2417,8 @@ function toRunEntity(run) {
2183
2417
  namespace: run.namespace || "default",
2184
2418
  // Absent origin stays SQL NULL — "unknown", never coerced into a real-looking library name.
2185
2419
  origin: run.origin ?? null,
2420
+ tenantId: run.tenantId ?? null,
2421
+ tenantKind: run.tenantKind ?? null,
2186
2422
  createdAt: run.createdAt,
2187
2423
  updatedAt: run.updatedAt
2188
2424
  };
@@ -2211,6 +2447,13 @@ function fromRunEntity(e) {
2211
2447
  namespace: e.namespace,
2212
2448
  // NULL (a row written before the column existed) surfaces as `undefined` = unknown origin.
2213
2449
  origin: e.origin ?? void 0,
2450
+ // NULL = no tenant; left off entirely so a tenancy-off run reads back unchanged.
2451
+ ...e.tenantId != null ? {
2452
+ tenantId: e.tenantId
2453
+ } : {},
2454
+ ...e.tenantKind != null ? {
2455
+ tenantKind: e.tenantKind
2456
+ } : {},
2214
2457
  createdAt: e.createdAt,
2215
2458
  updatedAt: e.updatedAt
2216
2459
  };
@@ -2263,6 +2506,22 @@ function fromCheckpointEntity(e) {
2263
2506
  };
2264
2507
  }
2265
2508
  __name(fromCheckpointEntity, "fromCheckpointEntity");
2509
+ function applyTenantWhere(qb, alias, query) {
2510
+ if (query.tenantId === null) qb.andWhere(`${alias}.tenantId IS NULL`);
2511
+ else if (query.tenantId !== void 0) qb.andWhere(`${alias}.tenantId = :tenantId`, {
2512
+ tenantId: query.tenantId
2513
+ });
2514
+ if (query.tenantIds) {
2515
+ const named = query.tenantIds.filter((t) => t !== null);
2516
+ const branches = [];
2517
+ if (named.length) branches.push(`${alias}.tenantId IN (:...tenantIds)`);
2518
+ if (query.tenantIds.some((t) => t === null)) branches.push(`${alias}.tenantId IS NULL`);
2519
+ qb.andWhere(branches.length ? `(${branches.join(" OR ")})` : "1 = 0", named.length ? {
2520
+ tenantIds: named
2521
+ } : {});
2522
+ }
2523
+ }
2524
+ __name(applyTenantWhere, "applyTenantWhere");
2266
2525
  function toScheduleEntity(r) {
2267
2526
  const e = new ScheduleEntity();
2268
2527
  e.id = r.id;
@@ -2273,6 +2532,8 @@ function toScheduleEntity(r) {
2273
2532
  e.tags = r.tags ?? null;
2274
2533
  e.spec = r.spec;
2275
2534
  e.state = r.state;
2535
+ e.tenantId = r.tenantId ?? null;
2536
+ e.tenantKind = r.tenantKind ?? null;
2276
2537
  e.createdAt = r.createdAt;
2277
2538
  e.updatedAt = r.updatedAt;
2278
2539
  return e;
@@ -2291,6 +2552,12 @@ function fromScheduleEntity(e) {
2291
2552
  } : {},
2292
2553
  spec: e.spec ?? {},
2293
2554
  state: e.state ?? {},
2555
+ ...e.tenantId != null ? {
2556
+ tenantId: e.tenantId
2557
+ } : {},
2558
+ ...e.tenantKind != null ? {
2559
+ tenantKind: e.tenantKind
2560
+ } : {},
2294
2561
  createdAt: e.createdAt,
2295
2562
  updatedAt: e.updatedAt
2296
2563
  };
@@ -2314,6 +2581,8 @@ function runUpdateSet(patch) {
2314
2581
  if ("priority" in patch) update.priority = patch.priority ?? null;
2315
2582
  if ("namespace" in patch) update.namespace = patch.namespace || "default";
2316
2583
  if ("origin" in patch) update.origin = patch.origin ?? null;
2584
+ if ("tenantId" in patch) update.tenantId = patch.tenantId ?? null;
2585
+ if ("tenantKind" in patch) update.tenantKind = patch.tenantKind ?? null;
2317
2586
  if ("createdAt" in patch) update.createdAt = patch.createdAt;
2318
2587
  if ("updatedAt" in patch) update.updatedAt = patch.updatedAt;
2319
2588
  return update;
@@ -2383,6 +2652,251 @@ async function updateIfPending(repo, checkpoint) {
2383
2652
  return (result.affected ?? 0) > 0;
2384
2653
  }
2385
2654
  __name(updateIfPending, "updateIfPending");
2655
+ function isUniqueViolation(err) {
2656
+ const driverError = err?.driverError ?? err;
2657
+ const e = driverError;
2658
+ const code = String(e?.code ?? "");
2659
+ return code === "23505" || code === "ER_DUP_ENTRY" || e?.errno === 1062 || code.startsWith("SQLITE_CONSTRAINT");
2660
+ }
2661
+ __name(isUniqueViolation, "isUniqueViolation");
2662
+ var TypeOrmRoundTrips = class TypeOrmRoundTrips2 {
2663
+ static {
2664
+ __name(this, "TypeOrmRoundTrips");
2665
+ }
2666
+ ds;
2667
+ store;
2668
+ pg;
2669
+ /** The checkpoint columns' actual Postgres types (what the schema created), read once. */
2670
+ cpTypes;
2671
+ constructor(ds, dialect, store) {
2672
+ this.ds = ds;
2673
+ this.store = store;
2674
+ this.pg = dialect === "postgres";
2675
+ }
2676
+ get runs() {
2677
+ return this.ds.getMetadata(WorkflowRunEntity);
2678
+ }
2679
+ get cps() {
2680
+ return this.ds.getMetadata(StepCheckpointEntity);
2681
+ }
2682
+ /**
2683
+ * The Postgres type to cast a `VALUES` parameter of checkpoint `property` to: the column's actual
2684
+ * type in the database (a `timestamptz` the schema helper created, or a `timestamp` from
2685
+ * `synchronize`), so the value converts exactly as the repository's own writes convert it.
2686
+ */
2687
+ async cpType(property) {
2688
+ this.cpTypes ??= this.ds.query("SELECT column_name AS name, data_type AS type FROM information_schema.columns WHERE table_name = $1 AND table_schema = current_schema()", [
2689
+ this.cps.tableName
2690
+ ]).then((rows) => new Map(rows.map((r) => [
2691
+ r.name,
2692
+ r.type
2693
+ ])));
2694
+ const column = this.col(this.cps, property);
2695
+ return (await this.cpTypes).get(column.databaseName) ?? this.ds.driver.normalizeType(column);
2696
+ }
2697
+ q(name) {
2698
+ return this.pg ? `"${name.replace(/"/g, '""')}"` : `\`${name.replace(/`/g, "``")}\``;
2699
+ }
2700
+ p(i) {
2701
+ return this.pg ? `$${i}` : "?";
2702
+ }
2703
+ col(meta, property) {
2704
+ const column = meta.findColumnWithPropertyName(property);
2705
+ if (!column) throw new Error(`no column for ${property}`);
2706
+ return column;
2707
+ }
2708
+ c(meta, property) {
2709
+ return this.q(this.col(meta, property).databaseName);
2710
+ }
2711
+ table(meta) {
2712
+ return this.q(meta.tableName);
2713
+ }
2714
+ /** `value` as the driver binds it for `property` (transformers and type conversion included). */
2715
+ bind(meta, property, value) {
2716
+ if (value == null) return null;
2717
+ return this.ds.driver.preparePersistentValue(value, this.col(meta, property));
2718
+ }
2719
+ /** A raw row as the repository would hydrate it; a column the row lacks reads `null`. */
2720
+ hydrate(meta, raw) {
2721
+ const entity = {};
2722
+ for (const column of meta.columns) {
2723
+ const value = raw[column.databaseName];
2724
+ entity[column.propertyName] = value === void 0 ? null : this.ds.driver.prepareHydratedValue(value, column);
2725
+ }
2726
+ return entity;
2727
+ }
2728
+ /** Rows of a statement: Postgres `UPDATE … RETURNING` comes back as `[rows, count]`. */
2729
+ rows(out) {
2730
+ if (Array.isArray(out) && Array.isArray(out[0])) return out[0];
2731
+ return Array.isArray(out) ? out : [];
2732
+ }
2733
+ cpColumns(withInput) {
2734
+ return this.cps.columns.filter((c) => withInput || c.propertyName !== "input");
2735
+ }
2736
+ async tryLockRunAndGet(runId, owner, leaseUntilMs, nowMs) {
2737
+ const r = this.runs;
2738
+ const until = this.c(r, "lockedUntil");
2739
+ const out = await this.ds.query(`UPDATE ${this.table(r)} SET ${this.c(r, "lockedBy")} = $1, ${until} = $2 WHERE ${this.c(r, "id")} = $3 AND (${until} IS NULL OR ${until} <= $4) RETURNING *`, [
2740
+ owner,
2741
+ this.bind(r, "lockedUntil", new Date(leaseUntilMs)),
2742
+ runId,
2743
+ this.bind(r, "lockedUntil", new Date(nowMs))
2744
+ ]);
2745
+ const [row] = this.rows(out);
2746
+ return row ? fromRunEntity(this.hydrate(r, row)) : null;
2747
+ }
2748
+ async insertCheckpointIfAbsent(checkpoint) {
2749
+ const entity = toCheckpointEntity(checkpoint);
2750
+ const columns = this.cps.columns;
2751
+ const names = columns.map((c) => this.q(c.databaseName)).join(", ");
2752
+ const values = columns.map((c) => this.bind(this.cps, c.propertyName, entity[c.propertyName]));
2753
+ const marks = columns.map((_, i) => this.p(i + 1)).join(", ");
2754
+ const insert = `INSERT INTO ${this.table(this.cps)} (${names}) VALUES (${marks})`;
2755
+ if (this.pg) {
2756
+ const key = `${this.c(this.cps, "runId")}, ${this.c(this.cps, "seq")}`;
2757
+ const out = await this.ds.query(`${insert} ON CONFLICT (${key}) DO NOTHING RETURNING ${this.c(this.cps, "seq")}`, values);
2758
+ return this.rows(out).length === 1;
2759
+ }
2760
+ try {
2761
+ await this.ds.query(insert, values);
2762
+ return true;
2763
+ } catch (err) {
2764
+ const driver = err.driverError;
2765
+ if (driver?.errno === 1062 || driver?.code === "ER_DUP_ENTRY") return false;
2766
+ throw err;
2767
+ }
2768
+ }
2769
+ async settleResultsIfPending(results) {
2770
+ const out = results.map(() => null);
2771
+ const seen = /* @__PURE__ */ new Set();
2772
+ const sent = results.flatMap((r2, i) => {
2773
+ const key = checkpointKey(r2.runId, r2.seq);
2774
+ if (seen.has(key)) return [];
2775
+ seen.add(key);
2776
+ return [
2777
+ i
2778
+ ];
2779
+ });
2780
+ if (sent.length === 0) return out;
2781
+ if (!this.pg) {
2782
+ if (sent.length > 1) return (0, import_nestjs_durable_core.settleResultsWithPlainCalls)(this.store, results);
2783
+ const only = sent[0];
2784
+ out[only] = await this.settleOneMysql(results[only]);
2785
+ return out;
2786
+ }
2787
+ const k = this.cps;
2788
+ const r = this.runs;
2789
+ const props = [
2790
+ "runId",
2791
+ "seq",
2792
+ "status",
2793
+ "output",
2794
+ "error",
2795
+ "events",
2796
+ "startedAt",
2797
+ "finishedAt"
2798
+ ];
2799
+ const types = new Map(await Promise.all(props.map(async (prop) => [
2800
+ prop,
2801
+ await this.cpType(prop)
2802
+ ])));
2803
+ const type = /* @__PURE__ */ __name((property) => types.get(property), "type");
2804
+ for (let at = 0; at < sent.length; at += 500) {
2805
+ const chunk = sent.slice(at, at + 500);
2806
+ const values = [];
2807
+ const rows = chunk.map((i) => {
2808
+ const s = results[i];
2809
+ const n = values.length;
2810
+ values.push(s.runId, s.seq, s.status, this.bind(k, "output", s.status === "completed" ? s.output : null), this.bind(k, "error", s.error), this.bind(k, "events", s.events), this.bind(k, "startedAt", s.startedAt), this.bind(k, "finishedAt", s.finishedAt));
2811
+ const p = /* @__PURE__ */ __name((j) => `$${n + j}`, "p");
2812
+ return `(${p(1)}::${type("runId")}, ${p(2)}::${type("seq")}, ${p(3)}::${type("status")}, ${p(4)}::${type("output")}, ${p(5)}::${type("error")}, ${p(6)}::${type("events")}, ${p(7)}::${type("startedAt")}, ${p(8)}::${type("finishedAt")})`;
2813
+ });
2814
+ const c = /* @__PURE__ */ __name((prop) => this.c(k, prop), "c");
2815
+ const returning = this.cpColumns(false).map((col) => `c.${this.q(col.databaseName)}`).join(", ");
2816
+ const settled = this.rows(await this.ds.query(`UPDATE ${this.table(k)} AS c SET ${c("status")} = v.status, ${c("output")} = CASE WHEN v.status = 'completed' THEN v.output ELSE c.${c("output")} END, ${c("error")} = v.error, ${c("events")} = COALESCE(v.events, c.${c("events")}), ${c("startedAt")} = COALESCE(v.started_at, c.${c("startedAt")}), ${c("finishedAt")} = v.finished_at FROM (VALUES ${rows.join(", ")}) AS v(run_id, seq, status, output, error, events, started_at, finished_at) WHERE c.${c("runId")} = v.run_id AND c.${c("seq")} = v.seq AND c.${c("status")} = 'pending' AND NOT EXISTS (SELECT 1 FROM ${this.table(r)} AS r WHERE r.${this.c(r, "id")} = c.${c("runId")} AND r.${this.c(r, "status")} IN ('cancelled', 'completed')) RETURNING ${returning}`, values));
2817
+ const byKey = new Map(chunk.map((i) => {
2818
+ const s = results[i];
2819
+ return [
2820
+ checkpointKey(s.runId, s.seq),
2821
+ i
2822
+ ];
2823
+ }));
2824
+ for (const raw of settled) {
2825
+ const cp = fromCheckpointEntity(this.hydrate(k, raw));
2826
+ const i = byKey.get(checkpointKey(cp.runId, cp.seq));
2827
+ if (i !== void 0) out[i] = cp;
2828
+ }
2829
+ }
2830
+ return out;
2831
+ }
2832
+ async settleOneMysql(s) {
2833
+ const k = this.cps;
2834
+ const r = this.runs;
2835
+ const c = /* @__PURE__ */ __name((prop) => `c.${this.c(k, prop)}`, "c");
2836
+ const done = s.status === "completed";
2837
+ const result = await this.ds.query(`UPDATE ${this.table(k)} AS c SET ${c("status")} = ?, ${c("output")} = ${done ? "?" : c("output")}, ${c("error")} = ?, ${c("events")} = COALESCE(?, ${c("events")}), ${c("startedAt")} = COALESCE(?, ${c("startedAt")}), ${c("finishedAt")} = ? WHERE ${c("runId")} = ? AND ${c("seq")} = ? AND ${c("status")} = 'pending' AND NOT EXISTS (SELECT 1 FROM ${this.table(r)} AS r WHERE r.${this.c(r, "id")} = ${c("runId")} AND r.${this.c(r, "status")} IN ('cancelled', 'completed'))`, [
2838
+ s.status,
2839
+ ...done ? [
2840
+ this.bind(k, "output", s.output)
2841
+ ] : [],
2842
+ this.bind(k, "error", s.error),
2843
+ this.bind(k, "events", s.events),
2844
+ this.bind(k, "startedAt", s.startedAt),
2845
+ this.bind(k, "finishedAt", s.finishedAt),
2846
+ s.runId,
2847
+ s.seq
2848
+ ]);
2849
+ if (!result?.affectedRows) return null;
2850
+ const list = this.cpColumns(false).map((col) => this.q(col.databaseName)).join(", ");
2851
+ const [row] = this.rows(await this.ds.query(`SELECT ${list} FROM ${this.table(k)} WHERE ${this.c(k, "runId")} = ? AND ${this.c(k, "seq")} = ?`, [
2852
+ s.runId,
2853
+ s.seq
2854
+ ]));
2855
+ return row ? fromCheckpointEntity(this.hydrate(k, row)) : null;
2856
+ }
2857
+ async claimPendingRuns(limit, owner, leaseUntilMs, nowMs, namespace) {
2858
+ if (limit <= 0) return [];
2859
+ const r = this.runs;
2860
+ const c = /* @__PURE__ */ __name((prop) => this.c(r, prop), "c");
2861
+ const until = this.bind(r, "lockedUntil", new Date(leaseUntilMs));
2862
+ const now = this.bind(r, "lockedUntil", new Date(nowMs));
2863
+ const sort = /* @__PURE__ */ __name((runs) => runs.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id)), "sort");
2864
+ if (this.pg) {
2865
+ const ns = namespace !== void 0 ? ` AND ${c("namespace")} = $5` : "";
2866
+ const out = await this.ds.query(`WITH claimed AS MATERIALIZED (SELECT ${c("id")} AS claimed_id FROM ${this.table(r)} WHERE ${c("status")} = 'pending' AND (${c("lockedUntil")} IS NULL OR ${c("lockedUntil")} <= $3)${ns} ORDER BY ${c("createdAt")}, ${c("id")} LIMIT $4 FOR UPDATE SKIP LOCKED) UPDATE ${this.table(r)} AS r SET ${c("lockedBy")} = $1, ${c("lockedUntil")} = $2 FROM claimed WHERE r.${c("id")} = claimed.claimed_id RETURNING r.*`, [
2867
+ owner,
2868
+ until,
2869
+ now,
2870
+ limit,
2871
+ ...namespace !== void 0 ? [
2872
+ namespace
2873
+ ] : []
2874
+ ]);
2875
+ return sort(this.rows(out).map((raw) => fromRunEntity(this.hydrate(r, raw))));
2876
+ }
2877
+ return this.ds.transaction(async (em) => {
2878
+ const ns = namespace !== void 0 ? ` AND ${c("namespace")} = ?` : "";
2879
+ const picked = this.rows(await em.query(`SELECT * FROM ${this.table(r)} WHERE ${c("status")} = 'pending' AND (${c("lockedUntil")} IS NULL OR ${c("lockedUntil")} <= ?)${ns} ORDER BY ${c("createdAt")}, ${c("id")} LIMIT ? FOR UPDATE SKIP LOCKED`, [
2880
+ now,
2881
+ ...namespace !== void 0 ? [
2882
+ namespace
2883
+ ] : [],
2884
+ limit
2885
+ ])).map((raw) => fromRunEntity(this.hydrate(r, raw)));
2886
+ if (picked.length === 0) return [];
2887
+ await em.query(`UPDATE ${this.table(r)} SET ${c("lockedBy")} = ?, ${c("lockedUntil")} = ? WHERE ${c("id")} IN (${picked.map(() => "?").join(", ")})`, [
2888
+ owner,
2889
+ until,
2890
+ ...picked.map((run) => run.id)
2891
+ ]);
2892
+ return sort(picked.map((run) => ({
2893
+ ...run,
2894
+ lockedBy: owner,
2895
+ lockedUntil: leaseUntilMs
2896
+ })));
2897
+ });
2898
+ }
2899
+ };
2386
2900
  // Annotate the CommonJS export names for ESM import in node:
2387
2901
  0 && (module.exports = {
2388
2902
  BufferedEventEntity,
@@ -2393,6 +2907,7 @@ __name(updateIfPending, "updateIfPending");
2393
2907
  MYSQL_DATETIME_TYPE,
2394
2908
  RunAttributeEntity,
2395
2909
  ScheduleEntity,
2910
+ SignalIdEntity,
2396
2911
  SignalWaiterEntity,
2397
2912
  StepCheckpointEntity,
2398
2913
  TypeOrmStateStore,