@dudousxd/nestjs-durable-store-prisma 0.25.0 → 0.27.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
@@ -43,8 +43,28 @@ var PrismaStateStore = class {
43
43
  __name(this, "PrismaStateStore");
44
44
  }
45
45
  db;
46
+ // The round-trip-saving optional methods, bound on Postgres and MySQL (see `PrismaRoundTrips`);
47
+ // absent on SQLite, where the engine's read-then-write calls are used.
48
+ settleResultsIfPending;
49
+ insertCheckpointIfAbsent;
50
+ tryLockRunAndGet;
51
+ claimPendingRuns;
52
+ /** Raw single-statement writes on Postgres/MySQL (Prisma wraps `updateMany` in a transaction). */
53
+ fast;
46
54
  constructor(db) {
47
55
  this.db = db;
56
+ const provider = db._activeProvider;
57
+ const raw = typeof db.$queryRawUnsafe === "function";
58
+ const dialect = raw && provider === "postgresql" ? "postgres" : raw && provider === "mysql" ? "mysql" : void 0;
59
+ if (!dialect) return;
60
+ const fast = new PrismaRoundTrips(db, dialect, this);
61
+ this.fast = fast;
62
+ this.insertCheckpointIfAbsent = (cp) => fast.insertCheckpointIfAbsent(cp);
63
+ this.settleResultsIfPending = (results) => fast.settleResultsIfPending(results);
64
+ this.claimPendingRuns = (limit, owner, until, now, ns) => fast.claimPendingRuns(limit, owner, until, now, ns);
65
+ if (dialect === "postgres") {
66
+ this.tryLockRunAndGet = (runId, owner, until, now) => fast.tryLockRunAndGet(runId, owner, until, now);
67
+ }
48
68
  }
49
69
  async tryAdmitSingleton(runId, tag, workflow, limit, retryWakeAt) {
50
70
  const where = {
@@ -142,7 +162,8 @@ var PrismaStateStore = class {
142
162
  }
143
163
  };
144
164
  const data = toRunPatch(patch);
145
- const count = Object.keys(data).length ? (await this.db.durableWorkflowRun.updateMany({
165
+ const raw = Object.keys(data).length ? this.fast?.updateRunWhere(runId, expectedStatuses, patch) : void 0;
166
+ const count = raw ? await raw : Object.keys(data).length ? (await this.db.durableWorkflowRun.updateMany({
146
167
  where,
147
168
  data
148
169
  })).count : await this.db.durableWorkflowRun.count({
@@ -437,7 +458,7 @@ var PrismaStateStore = class {
437
458
  seen.add(key);
438
459
  firsts.push(i);
439
460
  });
440
- const dialect = rawSettleDialect(this.db);
461
+ const dialect = firsts.length === 1 ? void 0 : rawSettleDialect(this.db);
441
462
  if (!dialect) {
442
463
  const settle = /* @__PURE__ */ __name(async (db) => {
443
464
  for (const i of firsts) {
@@ -606,6 +627,10 @@ var PrismaStateStore = class {
606
627
  return result.count === 1;
607
628
  }
608
629
  async releaseRunLock(runId, owner) {
630
+ if (this.fast) {
631
+ await this.fast.releaseRunLock(runId, owner);
632
+ return;
633
+ }
609
634
  await this.db.durableWorkflowRun.updateMany({
610
635
  where: owner === void 0 ? {
611
636
  id: runId
@@ -660,6 +685,12 @@ var PrismaStateStore = class {
660
685
  if (query.origins) and.push(anyOf(query.origins.map((o) => ({
661
686
  origin: o
662
687
  }))));
688
+ if (query.tenantId !== void 0) and.push({
689
+ tenantId: query.tenantId
690
+ });
691
+ if (query.tenantIds) and.push(anyOf(query.tenantIds.map((t) => ({
692
+ tenantId: t
693
+ }))));
663
694
  if (query.status && query.statuses) {
664
695
  and.push({
665
696
  status: query.status
@@ -786,6 +817,8 @@ var PrismaStateStore = class {
786
817
  if ("tags" in patch) data.tags = jsonOrNull(patch.tags);
787
818
  if (patch.spec !== void 0) data.spec = patch.spec;
788
819
  if (patch.state !== void 0) data.state = patch.state;
820
+ if ("tenantId" in patch) data.tenantId = patch.tenantId ?? null;
821
+ if ("tenantKind" in patch) data.tenantKind = patch.tenantKind ?? null;
789
822
  if (patch.updatedAt !== void 0) data.updatedAt = patch.updatedAt;
790
823
  if (!Object.keys(data).length) return await this.getSchedule(id) !== null;
791
824
  const where = {
@@ -814,18 +847,23 @@ var PrismaStateStore = class {
814
847
  if (query.tag !== void 0) where.tags = {
815
848
  array_contains: query.tag
816
849
  };
850
+ const and = [];
851
+ if (query.tenantId !== void 0) and.push({
852
+ tenantId: query.tenantId
853
+ });
854
+ if (query.tenantIds) and.push(anyOf(query.tenantIds.map((t) => ({
855
+ tenantId: t
856
+ }))));
817
857
  if (query.dueBy !== void 0) {
818
- where.AND = [
819
- {
820
- paused: false
821
- },
822
- {
823
- nextFireAt: {
824
- lte: BigInt(query.dueBy)
825
- }
858
+ and.push({
859
+ paused: false
860
+ }, {
861
+ nextFireAt: {
862
+ lte: BigInt(query.dueBy)
826
863
  }
827
- ];
864
+ });
828
865
  }
866
+ if (and.length) where.AND = and;
829
867
  const rows = await this.schedules().findMany({
830
868
  where,
831
869
  // Soonest-due first, never-firing (NULL) last, id as the stable tie-break.
@@ -1260,6 +1298,112 @@ var PrismaStateStore = class {
1260
1298
  payload: row.payload ?? void 0
1261
1299
  };
1262
1300
  }
1301
+ async takeOldestBufferedSignal(tokens) {
1302
+ if (tokens.length === 0) return null;
1303
+ const unique = [
1304
+ ...new Set(tokens)
1305
+ ];
1306
+ for (; ; ) {
1307
+ const row = await this.db.durableBufferedSignal.findFirst({
1308
+ where: {
1309
+ token: {
1310
+ in: unique
1311
+ }
1312
+ },
1313
+ orderBy: {
1314
+ id: "asc"
1315
+ }
1316
+ });
1317
+ if (!row) return null;
1318
+ const { count } = await this.db.durableBufferedSignal.deleteMany({
1319
+ where: {
1320
+ id: row.id
1321
+ }
1322
+ });
1323
+ if (count === 1) return {
1324
+ token: row.token,
1325
+ payload: row.payload ?? void 0
1326
+ };
1327
+ }
1328
+ }
1329
+ signalIds() {
1330
+ const delegate = this.db.durableSignalId;
1331
+ if (!delegate) {
1332
+ throw new Error("signal dedupe (`signal(..., { id })`) needs the DurableSignalId model \u2014 copy it from prisma/schema.prisma into your schema and re-run `prisma generate`");
1333
+ }
1334
+ return delegate;
1335
+ }
1336
+ async claimSignalId(token, id, expiresAt, nowMs) {
1337
+ const ids = this.signalIds();
1338
+ for (; ; ) {
1339
+ try {
1340
+ await ids.create({
1341
+ data: {
1342
+ token,
1343
+ signalId: id,
1344
+ expiresAt: BigInt(expiresAt)
1345
+ }
1346
+ });
1347
+ return true;
1348
+ } catch (err) {
1349
+ if (err?.code !== "P2002") throw err;
1350
+ }
1351
+ const { count } = await ids.updateMany({
1352
+ where: {
1353
+ token,
1354
+ signalId: id,
1355
+ expiresAt: {
1356
+ lte: BigInt(nowMs)
1357
+ }
1358
+ },
1359
+ data: {
1360
+ expiresAt: BigInt(expiresAt)
1361
+ }
1362
+ });
1363
+ if (count === 1) return true;
1364
+ if (await ids.count({
1365
+ where: {
1366
+ token,
1367
+ signalId: id
1368
+ }
1369
+ }) > 0) return false;
1370
+ }
1371
+ }
1372
+ async releaseSignalId(token, id) {
1373
+ await this.signalIds().deleteMany({
1374
+ where: {
1375
+ token,
1376
+ signalId: id
1377
+ }
1378
+ });
1379
+ }
1380
+ async deleteExpiredSignalIds(nowMs, limit) {
1381
+ const ids = this.signalIds();
1382
+ const expired = {
1383
+ lte: BigInt(nowMs)
1384
+ };
1385
+ const rows = await ids.findMany({
1386
+ where: {
1387
+ expiresAt: expired
1388
+ },
1389
+ select: {
1390
+ token: true,
1391
+ signalId: true
1392
+ },
1393
+ take: limit
1394
+ });
1395
+ if (rows.length === 0) return 0;
1396
+ const { count } = await ids.deleteMany({
1397
+ where: {
1398
+ expiresAt: expired,
1399
+ OR: rows.map((r) => ({
1400
+ token: r.token,
1401
+ signalId: r.signalId
1402
+ }))
1403
+ }
1404
+ });
1405
+ return count;
1406
+ }
1263
1407
  async listBufferedSignals(tokenPrefix, afterId, limit) {
1264
1408
  const rows = await this.db.durableBufferedSignal.findMany({
1265
1409
  where: {
@@ -1384,6 +1528,8 @@ function toRunData(run) {
1384
1528
  namespace: run.namespace || "default",
1385
1529
  // Absent origin stays SQL NULL — "unknown", never coerced into a real-looking library name.
1386
1530
  origin: run.origin ?? null,
1531
+ tenantId: run.tenantId ?? null,
1532
+ tenantKind: run.tenantKind ?? null,
1387
1533
  createdAt: run.createdAt,
1388
1534
  updatedAt: run.updatedAt
1389
1535
  };
@@ -1407,6 +1553,8 @@ function toRunPatch(patch) {
1407
1553
  if ("priority" in patch) data.priority = patch.priority ?? null;
1408
1554
  if ("namespace" in patch) data.namespace = patch.namespace || "default";
1409
1555
  if ("origin" in patch) data.origin = patch.origin ?? null;
1556
+ if ("tenantId" in patch) data.tenantId = patch.tenantId ?? null;
1557
+ if ("tenantKind" in patch) data.tenantKind = patch.tenantKind ?? null;
1410
1558
  if (patch.createdAt != null) data.createdAt = patch.createdAt;
1411
1559
  if (patch.updatedAt != null) data.updatedAt = patch.updatedAt;
1412
1560
  return data;
@@ -1437,6 +1585,13 @@ function fromRunRow(row) {
1437
1585
  namespace: row.namespace,
1438
1586
  // NULL (a row written before the column existed) surfaces as `undefined` = unknown origin.
1439
1587
  origin: row.origin ?? void 0,
1588
+ // NULL = no tenant; left off entirely so a tenancy-off run reads back unchanged.
1589
+ ...row.tenantId != null ? {
1590
+ tenantId: row.tenantId
1591
+ } : {},
1592
+ ...row.tenantKind != null ? {
1593
+ tenantKind: row.tenantKind
1594
+ } : {},
1440
1595
  createdAt: row.createdAt,
1441
1596
  updatedAt: row.updatedAt
1442
1597
  };
@@ -1718,6 +1873,8 @@ function toScheduleData(r) {
1718
1873
  tags: jsonOrNull(r.tags),
1719
1874
  spec: r.spec,
1720
1875
  state: r.state,
1876
+ tenantId: r.tenantId ?? null,
1877
+ tenantKind: r.tenantKind ?? null,
1721
1878
  createdAt: r.createdAt,
1722
1879
  updatedAt: r.updatedAt
1723
1880
  };
@@ -1736,11 +1893,365 @@ function fromScheduleRow(row) {
1736
1893
  } : {},
1737
1894
  spec: row.spec ?? {},
1738
1895
  state: row.state ?? {},
1896
+ ...row.tenantId != null ? {
1897
+ tenantId: row.tenantId
1898
+ } : {},
1899
+ ...row.tenantKind != null ? {
1900
+ tenantKind: row.tenantKind
1901
+ } : {},
1739
1902
  createdAt: row.createdAt,
1740
1903
  updatedAt: row.updatedAt
1741
1904
  };
1742
1905
  }
1743
1906
  __name(fromScheduleRow, "fromScheduleRow");
1907
+ function fromRawRow(raw) {
1908
+ const row = {};
1909
+ for (const [key, value] of Object.entries(raw)) {
1910
+ row[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = value;
1911
+ }
1912
+ return row;
1913
+ }
1914
+ __name(fromRawRow, "fromRawRow");
1915
+ var SETTLED_CHECKPOINT_COLUMNS = "run_id, seq, name, kind, step_id, status, output, error, events, attempts, worker_group, parallel_group, wake_at, enqueued_at, started_at, finished_at";
1916
+ var PrismaRoundTrips = class PrismaRoundTrips2 {
1917
+ static {
1918
+ __name(this, "PrismaRoundTrips");
1919
+ }
1920
+ db;
1921
+ store;
1922
+ pg;
1923
+ constructor(db, dialect, store) {
1924
+ this.db = db;
1925
+ this.store = store;
1926
+ this.pg = dialect === "postgres";
1927
+ }
1928
+ get raw() {
1929
+ return this.db;
1930
+ }
1931
+ async tryLockRunAndGet(runId, owner, leaseUntilMs, nowMs) {
1932
+ const rows = await this.raw.$queryRawUnsafe(`UPDATE "durable_workflow_runs" SET locked_by = $1, locked_until = ($2::timestamptz AT TIME ZONE 'UTC') WHERE id = $3 AND (locked_until IS NULL OR locked_until <= ($4::timestamptz AT TIME ZONE 'UTC')) RETURNING *`, owner, new Date(leaseUntilMs).toISOString(), runId, new Date(nowMs).toISOString());
1933
+ const [row] = rows;
1934
+ return row ? fromRunRow(fromRawRow(row)) : null;
1935
+ }
1936
+ /** A parameter placeholder for `kind` at position `n` (1-based), in this dialect. */
1937
+ param(kind, n) {
1938
+ if (this.pg) {
1939
+ const p = `$${n}`;
1940
+ if (kind === "json") return `${p}::jsonb`;
1941
+ if (kind === "date") return `(${p}::timestamptz AT TIME ZONE 'UTC')`;
1942
+ if (kind === "bigint") return `${p}::bigint`;
1943
+ if (kind === "int") return `${p}::integer`;
1944
+ return p;
1945
+ }
1946
+ return kind === "json" ? "CAST(? AS JSON)" : "?";
1947
+ }
1948
+ /** A value of `kind` as the raw statement binds it (dates as UTC, JSON as text). */
1949
+ value(kind, v) {
1950
+ if (v == null) return null;
1951
+ if (kind === "json") return JSON.stringify(v);
1952
+ if (kind === "date") {
1953
+ const iso = (v instanceof Date ? v : new Date(v)).toISOString();
1954
+ return this.pg ? iso : iso.replace("T", " ").replace("Z", "");
1955
+ }
1956
+ return v;
1957
+ }
1958
+ q(name) {
1959
+ return this.pg ? `"${name}"` : `\`${name}\``;
1960
+ }
1961
+ async insertCheckpointIfAbsent(checkpoint) {
1962
+ const columns = [
1963
+ [
1964
+ "run_id",
1965
+ "text",
1966
+ checkpoint.runId
1967
+ ],
1968
+ [
1969
+ "seq",
1970
+ "int",
1971
+ checkpoint.seq
1972
+ ],
1973
+ [
1974
+ "name",
1975
+ "text",
1976
+ checkpoint.name
1977
+ ],
1978
+ [
1979
+ "kind",
1980
+ "text",
1981
+ checkpoint.kind
1982
+ ],
1983
+ [
1984
+ "step_id",
1985
+ "text",
1986
+ checkpoint.stepId
1987
+ ],
1988
+ [
1989
+ "status",
1990
+ "text",
1991
+ checkpoint.status
1992
+ ],
1993
+ [
1994
+ "input",
1995
+ "json",
1996
+ checkpoint.input
1997
+ ],
1998
+ [
1999
+ "output",
2000
+ "json",
2001
+ checkpoint.output
2002
+ ],
2003
+ [
2004
+ "error",
2005
+ "json",
2006
+ checkpoint.error
2007
+ ],
2008
+ [
2009
+ "events",
2010
+ "json",
2011
+ checkpoint.events
2012
+ ],
2013
+ [
2014
+ "attempts",
2015
+ "int",
2016
+ checkpoint.attempts
2017
+ ],
2018
+ [
2019
+ "worker_group",
2020
+ "text",
2021
+ checkpoint.workerGroup
2022
+ ],
2023
+ [
2024
+ "parallel_group",
2025
+ "text",
2026
+ checkpoint.parallelGroup
2027
+ ],
2028
+ [
2029
+ "wake_at",
2030
+ "bigint",
2031
+ checkpoint.wakeAt
2032
+ ],
2033
+ [
2034
+ "enqueued_at",
2035
+ "date",
2036
+ checkpoint.enqueuedAt ?? checkpoint.startedAt
2037
+ ],
2038
+ [
2039
+ "started_at",
2040
+ "date",
2041
+ checkpoint.startedAt
2042
+ ],
2043
+ [
2044
+ "finished_at",
2045
+ "date",
2046
+ checkpoint.finishedAt
2047
+ ]
2048
+ ];
2049
+ const names = columns.map(([name]) => this.q(name)).join(", ");
2050
+ const marks = columns.map(([, kind], i) => this.param(kind, i + 1)).join(", ");
2051
+ const values = columns.map(([, kind, v]) => this.value(kind, v));
2052
+ const insert = `INSERT INTO ${this.q("durable_step_checkpoints")} (${names}) VALUES (${marks})`;
2053
+ if (this.pg) {
2054
+ const rows = await this.raw.$queryRawUnsafe(`${insert} ON CONFLICT (run_id, seq) DO NOTHING RETURNING seq`, ...values);
2055
+ return rows.length === 1;
2056
+ }
2057
+ try {
2058
+ await this.raw.$executeRawUnsafe(insert, ...values);
2059
+ return true;
2060
+ } catch (err) {
2061
+ const code = String(err.meta?.code ?? "");
2062
+ if (code === "1062" || /Duplicate entry/i.test(String(err.message))) return false;
2063
+ throw err;
2064
+ }
2065
+ }
2066
+ /** The run columns a raw patch may write, with their kinds; any other goes through `updateMany`. */
2067
+ static RUN_COLUMNS = {
2068
+ workflow: [
2069
+ "workflow",
2070
+ "text"
2071
+ ],
2072
+ workflowVersion: [
2073
+ "workflow_version",
2074
+ "text"
2075
+ ],
2076
+ status: [
2077
+ "status",
2078
+ "text"
2079
+ ],
2080
+ input: [
2081
+ "input",
2082
+ "json"
2083
+ ],
2084
+ output: [
2085
+ "output",
2086
+ "json"
2087
+ ],
2088
+ error: [
2089
+ "error",
2090
+ "json"
2091
+ ],
2092
+ wakeAt: [
2093
+ "wake_at",
2094
+ "bigint"
2095
+ ],
2096
+ lockedBy: [
2097
+ "locked_by",
2098
+ "text"
2099
+ ],
2100
+ lockedUntil: [
2101
+ "locked_until",
2102
+ "date"
2103
+ ],
2104
+ awaitingDecisionTaskId: [
2105
+ "awaiting_decision_task_id",
2106
+ "text"
2107
+ ],
2108
+ recoveryAttempts: [
2109
+ "recovery_attempts",
2110
+ "int"
2111
+ ],
2112
+ tags: [
2113
+ "tags",
2114
+ "json"
2115
+ ],
2116
+ priority: [
2117
+ "priority",
2118
+ "int"
2119
+ ],
2120
+ origin: [
2121
+ "origin",
2122
+ "text"
2123
+ ],
2124
+ tenantId: [
2125
+ "tenant_id",
2126
+ "text"
2127
+ ],
2128
+ tenantKind: [
2129
+ "tenant_kind",
2130
+ "text"
2131
+ ],
2132
+ updatedAt: [
2133
+ "updated_at",
2134
+ "date"
2135
+ ]
2136
+ };
2137
+ /**
2138
+ * `updateRunIf`'s compare-and-set as one raw UPDATE (Prisma's `updateMany` opens a transaction
2139
+ * around it), resolving the rows it changed; `undefined` for a patch left to `updateMany` (search
2140
+ * attributes, which reindex a side table, namespace, createdAt).
2141
+ */
2142
+ updateRunWhere(runId, expected, patch) {
2143
+ const keys = Object.keys(patch).filter(
2144
+ // A non-null date field left undefined is left alone, as toRunPatch does.
2145
+ (k) => !(k === "updatedAt" && patch.updatedAt == null)
2146
+ );
2147
+ if (keys.length === 0 || keys.some((k) => !PrismaRoundTrips2.RUN_COLUMNS[k])) return void 0;
2148
+ const values = [];
2149
+ const set = keys.map((k) => {
2150
+ const [column, kind] = PrismaRoundTrips2.RUN_COLUMNS[k];
2151
+ values.push(this.value(kind, patch[k]));
2152
+ return `${this.q(column)} = ${this.param(kind, values.length)}`;
2153
+ });
2154
+ values.push(runId);
2155
+ const id = this.param("text", values.length);
2156
+ const statuses = expected.map((status) => {
2157
+ values.push(status);
2158
+ return this.param("text", values.length);
2159
+ });
2160
+ return this.raw.$executeRawUnsafe(`UPDATE ${this.q("durable_workflow_runs")} SET ${set.join(", ")} WHERE id = ${id} AND status IN (${statuses.join(", ")})`, ...values);
2161
+ }
2162
+ /** `releaseRunLock` as one raw UPDATE (no transaction around it). */
2163
+ async releaseRunLock(runId, owner) {
2164
+ const where = owner === void 0 ? "" : ` AND locked_by = ${this.param("text", 2)}`;
2165
+ await this.raw.$executeRawUnsafe(`UPDATE ${this.q("durable_workflow_runs")} SET locked_by = NULL, locked_until = NULL WHERE id = ${this.param("text", 1)}${where}`, runId, ...owner === void 0 ? [] : [
2166
+ owner
2167
+ ]);
2168
+ }
2169
+ async settleResultsIfPending(results) {
2170
+ const out = results.map(() => null);
2171
+ const seen = /* @__PURE__ */ new Set();
2172
+ const sent = results.flatMap((r, i) => {
2173
+ const key = checkpointKey(r.runId, r.seq);
2174
+ if (seen.has(key)) return [];
2175
+ seen.add(key);
2176
+ return [
2177
+ i
2178
+ ];
2179
+ });
2180
+ if (sent.length === 0) return out;
2181
+ const finished = `NOT EXISTS (SELECT 1 FROM durable_workflow_runs r WHERE r.id = c.run_id AND r.status IN ('cancelled', 'completed'))`;
2182
+ if (!this.pg) {
2183
+ if (sent.length > 1) return (0, import_nestjs_durable_core.settleResultsWithPlainCalls)(this.store, results);
2184
+ const i = sent[0];
2185
+ const s = results[i];
2186
+ const done = s.status === "completed";
2187
+ const at = /* @__PURE__ */ __name((d) => d.toISOString().replace("T", " ").replace("Z", ""), "at");
2188
+ const wrote = await this.raw.$executeRawUnsafe(`UPDATE durable_step_checkpoints c SET c.status = ?, c.output = ${done ? "CAST(? AS JSON)" : "c.output"}, c.error = CAST(? AS JSON), c.events = COALESCE(CAST(? AS JSON), c.events), c.started_at = COALESCE(?, c.started_at), c.finished_at = ? WHERE c.run_id = ? AND c.seq = ? AND c.status = 'pending' AND ${finished}`, s.status, ...done ? [
2189
+ jsonText(s.output)
2190
+ ] : [], jsonText(s.error), jsonText(s.events), s.startedAt ? at(s.startedAt) : null, at(s.finishedAt), s.runId, s.seq);
2191
+ if (wrote !== 1) return out;
2192
+ const [row] = await this.raw.$queryRawUnsafe(`SELECT ${SETTLED_CHECKPOINT_COLUMNS} FROM durable_step_checkpoints WHERE run_id = ? AND seq = ?`, s.runId, s.seq);
2193
+ out[i] = row ? fromCheckpointRow(fromRawRow({
2194
+ ...row,
2195
+ input: null
2196
+ })) : null;
2197
+ return out;
2198
+ }
2199
+ for (let at = 0; at < sent.length; at += 500) {
2200
+ const chunk = sent.slice(at, at + 500);
2201
+ const values = [];
2202
+ const rows = chunk.map((i) => {
2203
+ const s = results[i];
2204
+ const n = values.length;
2205
+ values.push(s.runId, s.seq, s.status, jsonText(s.status === "completed" ? s.output : null), jsonText(s.error), jsonText(s.events), s.startedAt ? s.startedAt.toISOString() : null, s.finishedAt.toISOString());
2206
+ const p = /* @__PURE__ */ __name((k) => `$${n + k}`, "p");
2207
+ return `(${p(1)}::text, ${p(2)}::integer, ${p(3)}::text, ${p(4)}::jsonb, ${p(5)}::jsonb, ${p(6)}::jsonb, (${p(7)}::timestamptz AT TIME ZONE 'UTC'), (${p(8)}::timestamptz AT TIME ZONE 'UTC'))`;
2208
+ });
2209
+ const settled = await this.raw.$queryRawUnsafe(`UPDATE "durable_step_checkpoints" AS c SET status = v.status, output = CASE WHEN v.status = 'completed' THEN v.output ELSE c.output END, error = v.error, events = COALESCE(v.events, c.events), started_at = COALESCE(v.started_at, c.started_at), finished_at = v.finished_at FROM (VALUES ${rows.join(", ")}) AS v(run_id, seq, status, output, error, events, started_at, finished_at) WHERE c.run_id = v.run_id AND c.seq = v.seq AND c.status = 'pending' AND ${finished} RETURNING ${SETTLED_CHECKPOINT_COLUMNS.split(", ").map((col) => `c.${col}`).join(", ")}`, ...values);
2210
+ const byKey = new Map(chunk.map((i) => {
2211
+ const s = results[i];
2212
+ return [
2213
+ checkpointKey(s.runId, s.seq),
2214
+ i
2215
+ ];
2216
+ }));
2217
+ for (const raw of settled) {
2218
+ const cp = fromCheckpointRow(fromRawRow({
2219
+ ...raw,
2220
+ input: null
2221
+ }));
2222
+ const i = byKey.get(checkpointKey(cp.runId, cp.seq));
2223
+ if (i !== void 0) out[i] = cp;
2224
+ }
2225
+ }
2226
+ return out;
2227
+ }
2228
+ async claimPendingRuns(limit, owner, leaseUntilMs, nowMs, namespace) {
2229
+ if (limit <= 0) return [];
2230
+ const sort = /* @__PURE__ */ __name((runs) => runs.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id)), "sort");
2231
+ if (this.pg) {
2232
+ const ns = namespace !== void 0 ? " AND namespace = $5" : "";
2233
+ const rows = await this.raw.$queryRawUnsafe(`WITH claimed AS MATERIALIZED (SELECT id AS claimed_id FROM "durable_workflow_runs" WHERE status = 'pending' AND (locked_until IS NULL OR locked_until <= ($3::timestamptz AT TIME ZONE 'UTC'))${ns} ORDER BY created_at, id LIMIT $4 FOR UPDATE SKIP LOCKED) UPDATE "durable_workflow_runs" AS r SET locked_by = $1, locked_until = ($2::timestamptz AT TIME ZONE 'UTC') FROM claimed WHERE r.id = claimed.claimed_id RETURNING r.*`, owner, new Date(leaseUntilMs).toISOString(), new Date(nowMs).toISOString(), limit, ...namespace !== void 0 ? [
2234
+ namespace
2235
+ ] : []);
2236
+ return sort(rows.map((raw) => fromRunRow(fromRawRow(raw))));
2237
+ }
2238
+ return this.db.$transaction(async (tx) => {
2239
+ const raw = tx;
2240
+ const at = /* @__PURE__ */ __name((ms) => new Date(ms).toISOString().replace("T", " ").replace("Z", ""), "at");
2241
+ const ns = namespace !== void 0 ? " AND namespace = ?" : "";
2242
+ const picked = (await raw.$queryRawUnsafe(`SELECT * FROM durable_workflow_runs WHERE status = 'pending' AND (locked_until IS NULL OR locked_until <= ?)${ns} ORDER BY created_at, id LIMIT ? FOR UPDATE SKIP LOCKED`, at(nowMs), ...namespace !== void 0 ? [
2243
+ namespace
2244
+ ] : [], limit)).map((row) => fromRunRow(fromRawRow(row)));
2245
+ if (picked.length === 0) return [];
2246
+ await raw.$executeRawUnsafe(`UPDATE durable_workflow_runs SET locked_by = ?, locked_until = ? WHERE id IN (${picked.map(() => "?").join(", ")})`, owner, at(leaseUntilMs), ...picked.map((run) => run.id));
2247
+ return sort(picked.map((run) => ({
2248
+ ...run,
2249
+ lockedBy: owner,
2250
+ lockedUntil: leaseUntilMs
2251
+ })));
2252
+ });
2253
+ }
2254
+ };
1744
2255
 
1745
2256
  // src/schema.ts
1746
2257
  function durableManagedTables() {
@@ -1751,6 +2262,7 @@ function durableManagedTables() {
1751
2262
  "durable_signal_waiters",
1752
2263
  "durable_buffered_signals",
1753
2264
  "durable_buffered_events",
2265
+ "durable_signal_ids",
1754
2266
  "durable_schedules"
1755
2267
  ];
1756
2268
  }