@dudousxd/nestjs-durable-store-drizzle 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 +190 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +300 -1
- package/dist/index.d.ts +300 -1
- package/dist/index.js +189 -8
- package/dist/index.js.map +1 -1
- package/dist/pg/index.cjs +832 -122
- package/dist/pg/index.cjs.map +1 -1
- package/dist/pg/index.d.cts +295 -2
- package/dist/pg/index.d.ts +295 -2
- package/dist/pg/index.js +714 -15
- package/dist/pg/index.js.map +1 -1
- package/package.json +3 -3
package/dist/pg/index.js
CHANGED
|
@@ -56,6 +56,8 @@ var DURABLE_PG_DDL = [
|
|
|
56
56
|
"priority" integer,
|
|
57
57
|
"namespace" text DEFAULT 'default' NOT NULL,
|
|
58
58
|
"origin" text,
|
|
59
|
+
"tenant_id" text,
|
|
60
|
+
"tenant_kind" text,
|
|
59
61
|
"created_at" timestamp with time zone NOT NULL,
|
|
60
62
|
"updated_at" timestamp with time zone NOT NULL
|
|
61
63
|
)`,
|
|
@@ -102,6 +104,12 @@ var DURABLE_PG_DDL = [
|
|
|
102
104
|
"name" text NOT NULL,
|
|
103
105
|
"payload" jsonb,
|
|
104
106
|
"published_at" timestamp with time zone NOT NULL
|
|
107
|
+
)`,
|
|
108
|
+
`CREATE TABLE IF NOT EXISTS "durable_signal_ids" (
|
|
109
|
+
"token" text NOT NULL,
|
|
110
|
+
"signal_id" text NOT NULL,
|
|
111
|
+
"expires_at" timestamp with time zone NOT NULL,
|
|
112
|
+
CONSTRAINT "durable_signal_ids_token_signal_id_pk" PRIMARY KEY("token","signal_id")
|
|
105
113
|
)`,
|
|
106
114
|
`CREATE TABLE IF NOT EXISTS "durable_schedules" (
|
|
107
115
|
"id" text PRIMARY KEY NOT NULL,
|
|
@@ -112,9 +120,16 @@ var DURABLE_PG_DDL = [
|
|
|
112
120
|
"tags" jsonb,
|
|
113
121
|
"spec" jsonb NOT NULL,
|
|
114
122
|
"state" jsonb NOT NULL,
|
|
123
|
+
"tenant_id" text,
|
|
124
|
+
"tenant_kind" text,
|
|
115
125
|
"created_at" timestamp with time zone NOT NULL,
|
|
116
126
|
"updated_at" timestamp with time zone NOT NULL
|
|
117
127
|
)`,
|
|
128
|
+
// Tenancy columns (the customer a run / schedule belongs to): added in place on an existing database.
|
|
129
|
+
`ALTER TABLE "durable_workflow_runs" ADD COLUMN IF NOT EXISTS "tenant_id" text`,
|
|
130
|
+
`ALTER TABLE "durable_workflow_runs" ADD COLUMN IF NOT EXISTS "tenant_kind" text`,
|
|
131
|
+
`ALTER TABLE "durable_schedules" ADD COLUMN IF NOT EXISTS "tenant_id" text`,
|
|
132
|
+
`ALTER TABLE "durable_schedules" ADD COLUMN IF NOT EXISTS "tenant_kind" text`,
|
|
118
133
|
`CREATE INDEX IF NOT EXISTS "durable_runs_status_idx" ON "durable_workflow_runs" USING btree ("status","wake_at")`,
|
|
119
134
|
`CREATE INDEX IF NOT EXISTS "durable_runs_workflow_status_idx" ON "durable_workflow_runs" USING btree ("workflow","status")`,
|
|
120
135
|
`CREATE INDEX IF NOT EXISTS "durable_workflow_runs_namespace_status_idx" ON "durable_workflow_runs" USING btree ("namespace","status","created_at")`,
|
|
@@ -126,7 +141,10 @@ var DURABLE_PG_DDL = [
|
|
|
126
141
|
`CREATE INDEX IF NOT EXISTS "durable_signal_waiters_run_id_idx" ON "durable_signal_waiters" USING btree ("run_id")`,
|
|
127
142
|
`CREATE INDEX IF NOT EXISTS "durable_buffered_signals_token_idx" ON "durable_buffered_signals" USING btree ("token","id")`,
|
|
128
143
|
`CREATE INDEX IF NOT EXISTS "durable_buffered_events_name_published_at_idx" ON "durable_buffered_events" USING btree ("name","published_at")`,
|
|
129
|
-
`CREATE INDEX IF NOT EXISTS "durable_schedules_due_idx" ON "durable_schedules" USING btree ("paused","next_fire_at")
|
|
144
|
+
`CREATE INDEX IF NOT EXISTS "durable_schedules_due_idx" ON "durable_schedules" USING btree ("paused","next_fire_at")`,
|
|
145
|
+
`CREATE INDEX IF NOT EXISTS "durable_workflow_runs_tenant_idx" ON "durable_workflow_runs" USING btree ("tenant_id","created_at")`,
|
|
146
|
+
`CREATE INDEX IF NOT EXISTS "durable_schedules_tenant_idx" ON "durable_schedules" USING btree ("tenant_id")`,
|
|
147
|
+
`CREATE INDEX IF NOT EXISTS "durable_signal_ids_expires_at_idx" ON "durable_signal_ids" USING btree ("expires_at")`
|
|
130
148
|
];
|
|
131
149
|
var SCHEMA_LOCK_KEY = "durable_schema";
|
|
132
150
|
function drizzlePgSchemaRepairWarning(repairs) {
|
|
@@ -199,7 +217,187 @@ __name(ensureDrizzlePgDurableSchema, "ensureDrizzlePgDurableSchema");
|
|
|
199
217
|
|
|
200
218
|
// src/pg/drizzle-pg-state-store.ts
|
|
201
219
|
import { LIFECYCLE_REGISTRY_WORKFLOW, RUN_VALUE_FACET_SCAN, SINGLETON_ACTIVE_STATUSES, TERMINAL_RUN_STATUSES, attributePredicateOperands, axisIsRunColumn, clearTerminalSingletonAdmission, mergeRunFacetRows, mergeRunValueFacetRows, normalizeAttributeRows, parseDuration, retentionKeeps, runValueFacetsFromRuns, singletonAdmissionDenialPatch, singletonAdmissionTags } from "@dudousxd/nestjs-durable-core";
|
|
202
|
-
import { and, asc, desc, eq, exists, getTableColumns, gt, gte, inArray, isNotNull, isNull, like, lt, lte, notInArray, or, sql as sql3 } from "drizzle-orm";
|
|
220
|
+
import { and, asc, desc, eq, exists, getTableColumns as getTableColumns2, getTableName as getTableName2, gt, gte, inArray, isNotNull, isNull, like, lt, lte, notInArray, or, sql as sql3 } from "drizzle-orm";
|
|
221
|
+
|
|
222
|
+
// src/tenant-columns.ts
|
|
223
|
+
var PG_STATEMENTS = [
|
|
224
|
+
'ALTER TABLE "durable_workflow_runs" ADD COLUMN IF NOT EXISTS "tenant_id" text;',
|
|
225
|
+
'ALTER TABLE "durable_workflow_runs" ADD COLUMN IF NOT EXISTS "tenant_kind" text;',
|
|
226
|
+
'ALTER TABLE "durable_schedules" ADD COLUMN IF NOT EXISTS "tenant_id" text;',
|
|
227
|
+
'ALTER TABLE "durable_schedules" ADD COLUMN IF NOT EXISTS "tenant_kind" text;',
|
|
228
|
+
'CREATE INDEX IF NOT EXISTS "durable_workflow_runs_tenant_idx" ON "durable_workflow_runs" USING btree ("tenant_id","created_at");',
|
|
229
|
+
'CREATE INDEX IF NOT EXISTS "durable_schedules_tenant_idx" ON "durable_schedules" USING btree ("tenant_id");'
|
|
230
|
+
];
|
|
231
|
+
var SQLITE_STATEMENTS = [
|
|
232
|
+
"ALTER TABLE durable_workflow_runs ADD COLUMN tenant_id TEXT;",
|
|
233
|
+
"ALTER TABLE durable_workflow_runs ADD COLUMN tenant_kind TEXT;",
|
|
234
|
+
"ALTER TABLE durable_schedules ADD COLUMN tenant_id TEXT;",
|
|
235
|
+
"ALTER TABLE durable_schedules ADD COLUMN tenant_kind TEXT;",
|
|
236
|
+
"CREATE INDEX IF NOT EXISTS durable_workflow_runs_tenant_idx ON durable_workflow_runs (tenant_id, created_at);",
|
|
237
|
+
"CREATE INDEX IF NOT EXISTS durable_schedules_tenant_idx ON durable_schedules (tenant_id);"
|
|
238
|
+
];
|
|
239
|
+
var TENANT_COLUMN = /tenant_(id|kind)/;
|
|
240
|
+
function isMissingTenantColumn(err) {
|
|
241
|
+
let cur = err;
|
|
242
|
+
for (let depth = 0; cur && depth < 5; depth += 1) {
|
|
243
|
+
const e = cur;
|
|
244
|
+
const message = typeof e.message === "string" ? e.message : "";
|
|
245
|
+
if (TENANT_COLUMN.test(message)) {
|
|
246
|
+
if (e.code === "42703" || /does not exist/.test(message) || /no such column/i.test(message)) {
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
cur = e.cause;
|
|
251
|
+
}
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
__name(isMissingTenantColumn, "isMissingTenantColumn");
|
|
255
|
+
var MissingTenantColumnsError = class extends Error {
|
|
256
|
+
static {
|
|
257
|
+
__name(this, "MissingTenantColumnsError");
|
|
258
|
+
}
|
|
259
|
+
constructor(dialect, cause) {
|
|
260
|
+
const statements = dialect === "pg" ? PG_STATEMENTS : SQLITE_STATEMENTS;
|
|
261
|
+
const fix = dialect === "pg" ? "Generate a migration with drizzle-kit (`drizzle-kit generate`) from the store schema and apply it, or turn on the module's `autoSchema`, which adds them on boot." : "Generate a migration with drizzle-kit (`drizzle-kit generate`) from the store schema and apply it.";
|
|
262
|
+
super([
|
|
263
|
+
"[nestjs-durable] The durable tables are missing the tenancy columns (tenant_id, tenant_kind).",
|
|
264
|
+
"This version of the Drizzle store reads them on every run and schedule query, even with tenancy off.",
|
|
265
|
+
fix,
|
|
266
|
+
"The migration must contain:",
|
|
267
|
+
...statements.map((s) => ` ${s}`)
|
|
268
|
+
].join("\n"), {
|
|
269
|
+
cause
|
|
270
|
+
});
|
|
271
|
+
this.name = "MissingTenantColumnsError";
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
function tenantColumnsHint(dialect) {
|
|
275
|
+
return (err) => {
|
|
276
|
+
if (isMissingTenantColumn(err)) throw new MissingTenantColumnsError(dialect, err);
|
|
277
|
+
throw err;
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
__name(tenantColumnsHint, "tenantColumnsHint");
|
|
281
|
+
async function withTenantColumnsHint(dialect, query) {
|
|
282
|
+
try {
|
|
283
|
+
return await query;
|
|
284
|
+
} catch (err) {
|
|
285
|
+
return tenantColumnsHint(dialect)(err);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
__name(withTenantColumnsHint, "withTenantColumnsHint");
|
|
289
|
+
|
|
290
|
+
// src/pg/hot-path.ts
|
|
291
|
+
import * as drizzleOrm from "drizzle-orm";
|
|
292
|
+
import { getTableColumns } from "drizzle-orm";
|
|
293
|
+
function nodePgClient(db) {
|
|
294
|
+
const client = db.$client;
|
|
295
|
+
if (!client || typeof client !== "object") return void 0;
|
|
296
|
+
if (typeof client.query !== "function") return void 0;
|
|
297
|
+
const isPool = "totalCount" in client && "idleCount" in client;
|
|
298
|
+
const isClient = "connectionParameters" in client;
|
|
299
|
+
return isPool || isClient ? client : void 0;
|
|
300
|
+
}
|
|
301
|
+
__name(nodePgClient, "nodePgClient");
|
|
302
|
+
function drizzleLogger(db) {
|
|
303
|
+
const logger = db.session?.logger;
|
|
304
|
+
if (!logger || typeof logger.logQuery !== "function") return void 0;
|
|
305
|
+
if (logger.constructor?.name === "NoopLogger") {
|
|
306
|
+
return void 0;
|
|
307
|
+
}
|
|
308
|
+
return logger;
|
|
309
|
+
}
|
|
310
|
+
__name(drizzleLogger, "drizzleLogger");
|
|
311
|
+
var QueryError = drizzleOrm.DrizzleQueryError;
|
|
312
|
+
function hash(text2) {
|
|
313
|
+
let h = 2166136261;
|
|
314
|
+
for (let i = 0; i < text2.length; i += 1) {
|
|
315
|
+
h ^= text2.charCodeAt(i);
|
|
316
|
+
h = Math.imul(h, 16777619);
|
|
317
|
+
}
|
|
318
|
+
return (h >>> 0).toString(36);
|
|
319
|
+
}
|
|
320
|
+
__name(hash, "hash");
|
|
321
|
+
var PgHotPath = class _PgHotPath {
|
|
322
|
+
static {
|
|
323
|
+
__name(this, "PgHotPath");
|
|
324
|
+
}
|
|
325
|
+
client;
|
|
326
|
+
logger;
|
|
327
|
+
prepared;
|
|
328
|
+
constructor(client, logger, prepared) {
|
|
329
|
+
this.client = client;
|
|
330
|
+
this.logger = logger;
|
|
331
|
+
this.prepared = prepared;
|
|
332
|
+
}
|
|
333
|
+
/** The hot path for `db`, or `undefined` when `db` does not run on node-postgres. */
|
|
334
|
+
static for(db, options = {}) {
|
|
335
|
+
const client = nodePgClient(db);
|
|
336
|
+
if (!client) return void 0;
|
|
337
|
+
return new _PgHotPath(client, drizzleLogger(db), options.preparedStatements !== false);
|
|
338
|
+
}
|
|
339
|
+
/** Run one statement; resolves its rows as the driver decoded them (column names as stored). */
|
|
340
|
+
async query(text2, values) {
|
|
341
|
+
this.logger?.logQuery(text2, values);
|
|
342
|
+
const config = {
|
|
343
|
+
text: text2,
|
|
344
|
+
values
|
|
345
|
+
};
|
|
346
|
+
if (this.prepared) config.name = `durable_${hash(text2)}`;
|
|
347
|
+
try {
|
|
348
|
+
return (await this.client.query(config)).rows;
|
|
349
|
+
} catch (err) {
|
|
350
|
+
throw QueryError ? new QueryError(text2, values, err) : err;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
var TableCodec = class {
|
|
355
|
+
static {
|
|
356
|
+
__name(this, "TableCodec");
|
|
357
|
+
}
|
|
358
|
+
columns;
|
|
359
|
+
/** `"a", "b", …` in column order. */
|
|
360
|
+
list;
|
|
361
|
+
constructor(table, omit = []) {
|
|
362
|
+
this.columns = Object.entries(getTableColumns(table)).filter(([key]) => !omit.includes(key));
|
|
363
|
+
this.list = this.columns.map(([, c]) => quote(c.name)).join(", ");
|
|
364
|
+
}
|
|
365
|
+
/** The quoted column name of `property`. */
|
|
366
|
+
name(property) {
|
|
367
|
+
const found = this.columns.find(([key]) => key === property);
|
|
368
|
+
if (!found) throw new Error(`no column for ${property}`);
|
|
369
|
+
return quote(found[1].name);
|
|
370
|
+
}
|
|
371
|
+
/** A value of `property` as drizzle's builder would bind it. */
|
|
372
|
+
encode(property, value) {
|
|
373
|
+
if (value == null) return null;
|
|
374
|
+
const found = this.columns.find(([key]) => key === property);
|
|
375
|
+
return found ? found[1].mapToDriverValue(value) : value;
|
|
376
|
+
}
|
|
377
|
+
/** A row's values, in column order, as drizzle's builder would bind them. */
|
|
378
|
+
encodeRow(row) {
|
|
379
|
+
return this.columns.map(([key, column]) => {
|
|
380
|
+
const value = row[key];
|
|
381
|
+
return value == null ? null : column.mapToDriverValue(value);
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
/** A row a statement returned, as drizzle would map it (absent / omitted columns read `null`). */
|
|
385
|
+
decode(raw) {
|
|
386
|
+
const row = {};
|
|
387
|
+
for (const [key, column] of this.columns) {
|
|
388
|
+
const value = raw[column.name];
|
|
389
|
+
row[key] = value == null ? null : column.mapFromDriverValue(value);
|
|
390
|
+
}
|
|
391
|
+
return row;
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
var quote = /* @__PURE__ */ __name((name) => `"${name.replace(/"/g, '""')}"`, "quote");
|
|
395
|
+
function placeholders(from, count) {
|
|
396
|
+
return Array.from({
|
|
397
|
+
length: count
|
|
398
|
+
}, (_, i) => `$${from + i}`).join(", ");
|
|
399
|
+
}
|
|
400
|
+
__name(placeholders, "placeholders");
|
|
203
401
|
|
|
204
402
|
// src/pg/schema.ts
|
|
205
403
|
import { getTableName } from "drizzle-orm";
|
|
@@ -232,9 +430,14 @@ var durableWorkflowRuns = pgTable("durable_workflow_runs", {
|
|
|
232
430
|
namespace: text("namespace").notNull().default(DEFAULT_NAMESPACE),
|
|
233
431
|
// Which package declared the workflow. Nullable, no default: NULL = unknown, never guessed.
|
|
234
432
|
origin: text("origin"),
|
|
433
|
+
// The customer (tenancy) the run belongs to — not the worker-pool `namespace`. NULL = none.
|
|
434
|
+
tenantId: text("tenant_id"),
|
|
435
|
+
tenantKind: text("tenant_kind"),
|
|
235
436
|
createdAt: tstz("created_at").notNull(),
|
|
236
437
|
updatedAt: tstz("updated_at").notNull()
|
|
237
438
|
}, (t) => [
|
|
439
|
+
// App-facing reads with tenancy on: `tenant_id = $1 ORDER BY created_at DESC`.
|
|
440
|
+
index("durable_workflow_runs_tenant_idx").on(t.tenantId, t.createdAt),
|
|
238
441
|
// Timer poller (`listDueTimers`) + recovery (`listIncompleteRuns`). Same name as the TypeORM DDL.
|
|
239
442
|
index("durable_runs_status_idx").on(t.status, t.wakeAt),
|
|
240
443
|
// Dashboard `listRuns({ workflow, status })` and the singleton gate's per-workflow scans.
|
|
@@ -332,6 +535,19 @@ var durableBufferedEvents = pgTable("durable_buffered_events", {
|
|
|
332
535
|
}, (t) => [
|
|
333
536
|
index("durable_buffered_events_name_published_at_idx").on(t.name, t.publishedAt)
|
|
334
537
|
]);
|
|
538
|
+
var durableSignalIds = pgTable("durable_signal_ids", {
|
|
539
|
+
token: text("token").notNull(),
|
|
540
|
+
signalId: text("signal_id").notNull(),
|
|
541
|
+
expiresAt: tstz("expires_at").notNull()
|
|
542
|
+
}, (t) => [
|
|
543
|
+
primaryKey({
|
|
544
|
+
columns: [
|
|
545
|
+
t.token,
|
|
546
|
+
t.signalId
|
|
547
|
+
]
|
|
548
|
+
}),
|
|
549
|
+
index("durable_signal_ids_expires_at_idx").on(t.expiresAt)
|
|
550
|
+
]);
|
|
335
551
|
var durableSchedules = pgTable(
|
|
336
552
|
"durable_schedules",
|
|
337
553
|
{
|
|
@@ -343,12 +559,16 @@ var durableSchedules = pgTable(
|
|
|
343
559
|
tags: jsonb("tags").$type(),
|
|
344
560
|
spec: jsonb("spec").$type().notNull(),
|
|
345
561
|
state: jsonb("state").$type().notNull(),
|
|
562
|
+
// The customer the schedule (and every run it starts) belongs to. NULL = none.
|
|
563
|
+
tenantId: text("tenant_id"),
|
|
564
|
+
tenantKind: text("tenant_kind"),
|
|
346
565
|
createdAt: tstz("created_at").notNull(),
|
|
347
566
|
updatedAt: tstz("updated_at").notNull()
|
|
348
567
|
},
|
|
349
568
|
// The poll's "due by T" scan: `paused = false AND next_fire_at <= T ORDER BY next_fire_at`.
|
|
350
569
|
(t) => [
|
|
351
|
-
index("durable_schedules_due_idx").on(t.paused, t.nextFireAt)
|
|
570
|
+
index("durable_schedules_due_idx").on(t.paused, t.nextFireAt),
|
|
571
|
+
index("durable_schedules_tenant_idx").on(t.tenantId)
|
|
352
572
|
]
|
|
353
573
|
);
|
|
354
574
|
var durablePgSchema = {
|
|
@@ -358,6 +578,7 @@ var durablePgSchema = {
|
|
|
358
578
|
durableSignalWaiters,
|
|
359
579
|
durableBufferedSignals,
|
|
360
580
|
durableBufferedEvents,
|
|
581
|
+
durableSignalIds,
|
|
361
582
|
durableSchedules
|
|
362
583
|
};
|
|
363
584
|
function durablePgManagedTables() {
|
|
@@ -374,6 +595,14 @@ function anyOf(conditions) {
|
|
|
374
595
|
return present.length ? or(...present) : sql3`1 = 0`;
|
|
375
596
|
}
|
|
376
597
|
__name(anyOf, "anyOf");
|
|
598
|
+
function tenantFilters(column, query) {
|
|
599
|
+
const one = /* @__PURE__ */ __name((id) => id === null ? isNull(column) : eq(column, id), "one");
|
|
600
|
+
return [
|
|
601
|
+
query.tenantId !== void 0 ? one(query.tenantId) : void 0,
|
|
602
|
+
query.tenantIds ? anyOf(query.tenantIds.map(one)) : void 0
|
|
603
|
+
];
|
|
604
|
+
}
|
|
605
|
+
__name(tenantFilters, "tenantFilters");
|
|
377
606
|
function namespaceFilter(namespace) {
|
|
378
607
|
if (namespace === void 0) return void 0;
|
|
379
608
|
if (namespace === DEFAULT_NAMESPACE || namespace === "") {
|
|
@@ -400,10 +629,59 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
400
629
|
db;
|
|
401
630
|
options;
|
|
402
631
|
scopeNamespace;
|
|
632
|
+
/** Constant-SQL path for the per-step statements, on node-postgres (see `hot-path.ts`). */
|
|
633
|
+
hot;
|
|
634
|
+
/** The run read-scope predicate as SQL text from `$2` on, and its values (hot path). */
|
|
635
|
+
hotScope;
|
|
636
|
+
/** Hot-path UPDATE texts by patch shape. */
|
|
637
|
+
hotUpdates = /* @__PURE__ */ new Map();
|
|
403
638
|
constructor(db, options = {}) {
|
|
404
639
|
this.db = db;
|
|
405
640
|
this.options = options;
|
|
406
641
|
this.scopeNamespace = options.scope?.namespace;
|
|
642
|
+
this.hot = PgHotPath.for(db, {
|
|
643
|
+
preparedStatements: options.preparedStatements
|
|
644
|
+
});
|
|
645
|
+
const ns = this.scopeNamespace;
|
|
646
|
+
this.hotScope = ns === void 0 ? {
|
|
647
|
+
text: "",
|
|
648
|
+
values: []
|
|
649
|
+
} : ns === DEFAULT_NAMESPACE || ns === "" ? {
|
|
650
|
+
text: ' AND "namespace" IN ($2, $3)',
|
|
651
|
+
values: [
|
|
652
|
+
DEFAULT_NAMESPACE,
|
|
653
|
+
""
|
|
654
|
+
]
|
|
655
|
+
} : {
|
|
656
|
+
text: ' AND "namespace" = $2',
|
|
657
|
+
values: [
|
|
658
|
+
ns
|
|
659
|
+
]
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* A hot-path `UPDATE` of the runs table setting `row`'s columns on run `$n`, optionally only while
|
|
664
|
+
* its status is one of `expected` (then `RETURNING "id"`). Text cached per shape.
|
|
665
|
+
*/
|
|
666
|
+
hotRunUpdate(runId, row, expected) {
|
|
667
|
+
const keys = Object.keys(row);
|
|
668
|
+
const shape = `${keys.join(",")}|${expected?.length ?? -1}`;
|
|
669
|
+
let text2 = this.hotUpdates.get(shape);
|
|
670
|
+
if (text2 === void 0) {
|
|
671
|
+
const set = keys.map((key, i) => `${RUNS.name(key)} = $${i + 1}`).join(", ");
|
|
672
|
+
const id = keys.length + 1;
|
|
673
|
+
text2 = `UPDATE ${T_RUNS} SET ${set} WHERE "id" = $${id}`;
|
|
674
|
+
if (expected) {
|
|
675
|
+
text2 += ` AND "status" IN (${placeholders(id + 1, expected.length)}) RETURNING "id"`;
|
|
676
|
+
}
|
|
677
|
+
this.hotUpdates.set(shape, text2);
|
|
678
|
+
}
|
|
679
|
+
const values = keys.map((key) => RUNS.encode(key, row[key]));
|
|
680
|
+
values.push(runId, ...expected ?? []);
|
|
681
|
+
return {
|
|
682
|
+
text: text2,
|
|
683
|
+
values
|
|
684
|
+
};
|
|
407
685
|
}
|
|
408
686
|
/** A store confined to `scope.namespace`, sharing this store's db (no new connection). Used by the
|
|
409
687
|
* NestJS module's `scopeReads`; `{ namespace: undefined }` is the unscoped operator view. */
|
|
@@ -446,6 +724,13 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
446
724
|
}
|
|
447
725
|
async createRun(run) {
|
|
448
726
|
if (normalizeAttributeRows(run.id, run.searchAttributes).length === 0) {
|
|
727
|
+
if (this.hot) {
|
|
728
|
+
await this.hot.query(INSERT_RUN, RUNS.encodeRow(toRunRow(run)));
|
|
729
|
+
await this.hot.query(DELETE_ATTRIBUTES, [
|
|
730
|
+
run.id
|
|
731
|
+
]);
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
449
734
|
await this.db.insert(durableWorkflowRuns).values(toRunRow(run));
|
|
450
735
|
await this.db.delete(durableRunAttributes).where(eq(durableRunAttributes.runId, run.id));
|
|
451
736
|
return;
|
|
@@ -461,6 +746,11 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
461
746
|
const reindex = "searchAttributes" in patch;
|
|
462
747
|
if (!Object.keys(row).length && !reindex) return;
|
|
463
748
|
if (!reindex) {
|
|
749
|
+
if (this.hot) {
|
|
750
|
+
const { text: text2, values } = this.hotRunUpdate(runId, row);
|
|
751
|
+
await this.hot.query(text2, values);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
464
754
|
await this.db.update(durableWorkflowRuns).set(row).where(eq(durableWorkflowRuns.id, runId));
|
|
465
755
|
return;
|
|
466
756
|
}
|
|
@@ -475,6 +765,16 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
475
765
|
const row = toRunPatch(patch);
|
|
476
766
|
const reindex = "searchAttributes" in patch;
|
|
477
767
|
const matches = and(eq(durableWorkflowRuns.id, runId), inArray(durableWorkflowRuns.status, expectedStatuses));
|
|
768
|
+
if (!reindex && Object.keys(row).length) {
|
|
769
|
+
if (this.hot) {
|
|
770
|
+
const { text: text2, values } = this.hotRunUpdate(runId, row, expectedStatuses);
|
|
771
|
+
return (await this.hot.query(text2, values)).length === 1;
|
|
772
|
+
}
|
|
773
|
+
const applied = await this.db.update(durableWorkflowRuns).set(row).where(matches).returning({
|
|
774
|
+
id: durableWorkflowRuns.id
|
|
775
|
+
});
|
|
776
|
+
return applied.length === 1;
|
|
777
|
+
}
|
|
478
778
|
return this.db.transaction(async (tx) => {
|
|
479
779
|
const applied = Object.keys(row).length ? (await tx.update(durableWorkflowRuns).set(row).where(matches).returning({
|
|
480
780
|
id: durableWorkflowRuns.id
|
|
@@ -486,6 +786,13 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
486
786
|
});
|
|
487
787
|
}
|
|
488
788
|
async getRun(runId) {
|
|
789
|
+
if (this.hot) {
|
|
790
|
+
const rows2 = await this.hot.query(`${SELECT_RUN}${this.hotScope.text} LIMIT 1`, [
|
|
791
|
+
runId,
|
|
792
|
+
...this.hotScope.values
|
|
793
|
+
]);
|
|
794
|
+
return rows2[0] ? fromRunRow(RUNS.decode(rows2[0])) : null;
|
|
795
|
+
}
|
|
489
796
|
const rows = await this.db.select().from(durableWorkflowRuns).where(and(eq(durableWorkflowRuns.id, runId), this.scope())).limit(1);
|
|
490
797
|
return rows[0] ? fromRunRow(rows[0]) : null;
|
|
491
798
|
}
|
|
@@ -551,6 +858,13 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
551
858
|
});
|
|
552
859
|
}
|
|
553
860
|
async getCheckpoint(runId, seq) {
|
|
861
|
+
if (this.hot) {
|
|
862
|
+
const rows2 = await this.hot.query(SELECT_CHECKPOINT, [
|
|
863
|
+
runId,
|
|
864
|
+
seq
|
|
865
|
+
]);
|
|
866
|
+
return rows2[0] ? fromCheckpointRow(CPS.decode(rows2[0])) : null;
|
|
867
|
+
}
|
|
554
868
|
const rows = await this.db.select().from(durableStepCheckpoints).where(and(eq(durableStepCheckpoints.runId, runId), eq(durableStepCheckpoints.seq, seq))).limit(1);
|
|
555
869
|
return rows[0] ? fromCheckpointRow(rows[0]) : null;
|
|
556
870
|
}
|
|
@@ -568,7 +882,15 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
568
882
|
const unique = [
|
|
569
883
|
...new Set(seqs)
|
|
570
884
|
];
|
|
571
|
-
|
|
885
|
+
if (this.hot) {
|
|
886
|
+
if (unique.length === 0) return [];
|
|
887
|
+
const rows2 = await this.hot.query(SELECT_CHECKPOINTS_FOR_SETTLE, [
|
|
888
|
+
runId,
|
|
889
|
+
unique
|
|
890
|
+
]);
|
|
891
|
+
return rows2.map((raw) => fromCheckpointRow(CPS_NO_INPUT.decode(raw)));
|
|
892
|
+
}
|
|
893
|
+
const { input: _input, ...columns } = getTableColumns2(durableStepCheckpoints);
|
|
572
894
|
const rows = [];
|
|
573
895
|
for (let at = 0; at < unique.length; at += 500) {
|
|
574
896
|
rows.push(...await this.db.select(columns).from(durableStepCheckpoints).where(and(eq(durableStepCheckpoints.runId, runId), inArray(durableStepCheckpoints.seq, unique.slice(at, at + 500)))));
|
|
@@ -579,6 +901,10 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
579
901
|
}));
|
|
580
902
|
}
|
|
581
903
|
async saveCheckpoint(checkpoint) {
|
|
904
|
+
if (this.hot) {
|
|
905
|
+
await this.hot.query(UPSERT_CHECKPOINT, CPS.encodeRow(toCheckpointRow(checkpoint)));
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
582
908
|
await upsertCheckpoint(this.db, checkpoint);
|
|
583
909
|
}
|
|
584
910
|
async saveCheckpoints(checkpoints) {
|
|
@@ -605,7 +931,7 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
605
931
|
async saveCheckpointsIfPending(checkpoints) {
|
|
606
932
|
const wrote = checkpoints.map(() => false);
|
|
607
933
|
if (checkpoints.length === 0) return wrote;
|
|
608
|
-
await this.
|
|
934
|
+
await this.inTransactionIf(oneStatement(checkpoints), async (tx) => {
|
|
609
935
|
for (const round of distinctRounds(checkpoints)) {
|
|
610
936
|
for (let at = 0; at < round.length; at += CHECKPOINT_BATCH_ROWS) {
|
|
611
937
|
const chunk = round.slice(at, at + CHECKPOINT_BATCH_ROWS);
|
|
@@ -629,7 +955,7 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
629
955
|
async settleCheckpointsIfPending(settlements) {
|
|
630
956
|
const wrote = settlements.map(() => false);
|
|
631
957
|
if (settlements.length === 0) return wrote;
|
|
632
|
-
await this.
|
|
958
|
+
await this.inTransactionIf(oneStatement(settlements), async (tx) => {
|
|
633
959
|
for (const round of distinctRounds(settlements)) {
|
|
634
960
|
for (let at = 0; at < round.length; at += CHECKPOINT_BATCH_ROWS) {
|
|
635
961
|
const chunk = round.slice(at, at + CHECKPOINT_BATCH_ROWS);
|
|
@@ -650,6 +976,84 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
650
976
|
});
|
|
651
977
|
return wrote;
|
|
652
978
|
}
|
|
979
|
+
async settleResultsIfPending(results) {
|
|
980
|
+
const out = results.map(() => null);
|
|
981
|
+
const seen = /* @__PURE__ */ new Set();
|
|
982
|
+
const sent = results.flatMap((r, i) => {
|
|
983
|
+
const key = rowKey(r);
|
|
984
|
+
if (seen.has(key)) return [];
|
|
985
|
+
seen.add(key);
|
|
986
|
+
return [
|
|
987
|
+
i
|
|
988
|
+
];
|
|
989
|
+
});
|
|
990
|
+
if (sent.length === 0) return out;
|
|
991
|
+
if (this.hot && sent.length <= HOT_SETTLE_MAX_ROWS) {
|
|
992
|
+
const rows = await this.hot.query(settleResultsText(sent.length), sent.flatMap((i) => settleResultValues(results[i])));
|
|
993
|
+
const byKey = new Map(sent.map((i) => [
|
|
994
|
+
rowKey(results[i]),
|
|
995
|
+
i
|
|
996
|
+
]));
|
|
997
|
+
for (const raw of rows) {
|
|
998
|
+
const cp = fromCheckpointRow(CPS_NO_INPUT.decode(raw));
|
|
999
|
+
const i = byKey.get(rowKey(cp));
|
|
1000
|
+
if (i !== void 0) out[i] = cp;
|
|
1001
|
+
}
|
|
1002
|
+
return out;
|
|
1003
|
+
}
|
|
1004
|
+
await this.inTransactionIf(sent.length <= CHECKPOINT_BATCH_ROWS, async (tx) => {
|
|
1005
|
+
for (let at = 0; at < sent.length; at += CHECKPOINT_BATCH_ROWS) {
|
|
1006
|
+
const chunk = sent.slice(at, at + CHECKPOINT_BATCH_ROWS);
|
|
1007
|
+
const rows = rowsOf(await tx.execute(settleResultsFrom(chunk.map((i) => results[i]))));
|
|
1008
|
+
const byKey = new Map(chunk.map((i) => [
|
|
1009
|
+
rowKey(results[i]),
|
|
1010
|
+
i
|
|
1011
|
+
]));
|
|
1012
|
+
for (const raw of rows) {
|
|
1013
|
+
const cp = fromCheckpointRow(settledRowFromDriver(raw));
|
|
1014
|
+
const i = byKey.get(rowKey(cp));
|
|
1015
|
+
if (i !== void 0) out[i] = cp;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
return out;
|
|
1020
|
+
}
|
|
1021
|
+
async insertCheckpointIfAbsent(checkpoint) {
|
|
1022
|
+
if (this.hot) {
|
|
1023
|
+
const values = CPS.encodeRow(toCheckpointRow(checkpoint));
|
|
1024
|
+
return (await this.hot.query(INSERT_CHECKPOINT_IF_ABSENT, values)).length === 1;
|
|
1025
|
+
}
|
|
1026
|
+
const rows = await this.db.insert(durableStepCheckpoints).values(toCheckpointRow(checkpoint)).onConflictDoNothing({
|
|
1027
|
+
target: [
|
|
1028
|
+
durableStepCheckpoints.runId,
|
|
1029
|
+
durableStepCheckpoints.seq
|
|
1030
|
+
]
|
|
1031
|
+
}).returning({
|
|
1032
|
+
seq: durableStepCheckpoints.seq
|
|
1033
|
+
});
|
|
1034
|
+
return rows.length === 1;
|
|
1035
|
+
}
|
|
1036
|
+
async tryLockRunAndGet(runId, owner, leaseUntilMs, nowMs) {
|
|
1037
|
+
if (this.hot) {
|
|
1038
|
+
const rows2 = await this.hot.query(`${LOCK_RUN}${this.hotScope.text.replace(/\$(\d+)/g, (_, n) => `$${Number(n) + 3}`)} RETURNING ${RUNS.list}`, [
|
|
1039
|
+
runId,
|
|
1040
|
+
owner,
|
|
1041
|
+
lockTime(leaseUntilMs),
|
|
1042
|
+
lockTime(nowMs),
|
|
1043
|
+
...this.hotScope.values
|
|
1044
|
+
]);
|
|
1045
|
+
return rows2[0] ? fromRunRow(RUNS.decode(rows2[0])) : null;
|
|
1046
|
+
}
|
|
1047
|
+
const rows = await this.db.update(durableWorkflowRuns).set({
|
|
1048
|
+
lockedBy: owner,
|
|
1049
|
+
lockedUntil: new Date(leaseUntilMs)
|
|
1050
|
+
}).where(and(eq(durableWorkflowRuns.id, runId), or(isNull(durableWorkflowRuns.lockedUntil), lte(durableWorkflowRuns.lockedUntil, new Date(nowMs))), this.scope())).returning();
|
|
1051
|
+
return rows[0] ? fromRunRow(rows[0]) : null;
|
|
1052
|
+
}
|
|
1053
|
+
/** Run `work` on the db as is when it is one statement (atomic by itself), else in a transaction. */
|
|
1054
|
+
inTransactionIf(single, work) {
|
|
1055
|
+
return single ? work(this.db) : this.db.transaction((tx) => work(tx));
|
|
1056
|
+
}
|
|
653
1057
|
async transaction(work) {
|
|
654
1058
|
return this.db.transaction(async (tx) => work({
|
|
655
1059
|
raw: tx,
|
|
@@ -658,15 +1062,15 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
658
1062
|
}
|
|
659
1063
|
/** Crash recovery. Namespace-scoped: a worker re-drives only its own tenant's runs. */
|
|
660
1064
|
async listIncompleteRuns(namespace) {
|
|
661
|
-
const rows = await this.db.select().from(durableWorkflowRuns).where(and(inArray(durableWorkflowRuns.status, [
|
|
1065
|
+
const rows = await withTenantColumnsHint("pg", this.db.select().from(durableWorkflowRuns).where(and(inArray(durableWorkflowRuns.status, [
|
|
662
1066
|
"running",
|
|
663
1067
|
"cancelling"
|
|
664
|
-
]), namespaceFilter(namespace), this.scope()));
|
|
1068
|
+
]), namespaceFilter(namespace), this.scope())));
|
|
665
1069
|
return rows.map(fromRunRow);
|
|
666
1070
|
}
|
|
667
1071
|
async listOrphanedRuns(nowMs, limit, namespace, ownedBy) {
|
|
668
1072
|
if (limit <= 0) return [];
|
|
669
|
-
const
|
|
1073
|
+
const query = this.db.select().from(durableWorkflowRuns).where(and(inArray(durableWorkflowRuns.status, [
|
|
670
1074
|
"running",
|
|
671
1075
|
"cancelling"
|
|
672
1076
|
]), or(
|
|
@@ -675,20 +1079,54 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
675
1079
|
// A live lease left by a previous process with the caller's own instance id.
|
|
676
1080
|
ownedBy ? and(eq(durableWorkflowRuns.lockedBy, ownedBy.owner), lt(durableWorkflowRuns.lockedUntil, new Date(ownedBy.lockedBefore))) : void 0
|
|
677
1081
|
), namespaceFilter(namespace), this.scope())).orderBy(asc(durableWorkflowRuns.createdAt)).limit(limit);
|
|
1082
|
+
const rows = await withTenantColumnsHint("pg", query);
|
|
678
1083
|
return rows.map(fromRunRow);
|
|
679
1084
|
}
|
|
680
1085
|
/** FIFO pick-up, served by `durable_workflow_runs_namespace_status_idx`. The engine then leases
|
|
681
1086
|
* each run with {@link tryLockRun}; the listing itself takes no locks (it runs outside a tx). */
|
|
682
1087
|
async listPendingRuns(limit, namespace) {
|
|
683
|
-
const rows = await this.db.select().from(durableWorkflowRuns).where(and(eq(durableWorkflowRuns.status, "pending"), namespaceFilter(namespace), this.scope())).orderBy(asc(durableWorkflowRuns.createdAt)).limit(limit);
|
|
1088
|
+
const rows = await withTenantColumnsHint("pg", this.db.select().from(durableWorkflowRuns).where(and(eq(durableWorkflowRuns.status, "pending"), namespaceFilter(namespace), this.scope())).orderBy(asc(durableWorkflowRuns.createdAt)).limit(limit));
|
|
684
1089
|
return rows.map(fromRunRow);
|
|
685
1090
|
}
|
|
1091
|
+
async claimPendingRuns(limit, owner, leaseUntilMs, nowMs, namespace) {
|
|
1092
|
+
if (limit <= 0) return [];
|
|
1093
|
+
const filters = and(eq(durableWorkflowRuns.status, "pending"), or(isNull(durableWorkflowRuns.lockedUntil), lte(durableWorkflowRuns.lockedUntil, new Date(nowMs))), namespaceFilter(namespace), this.scope());
|
|
1094
|
+
const returning = sql3.join(RUNS.columns.map(([, column]) => sql3`r.${sql3.identifier(column.name)}`), sql3`, `);
|
|
1095
|
+
const rows = rowsOf(
|
|
1096
|
+
// A CTE, MATERIALIZED, picks the rows once. As a subquery in UPDATE ... FROM, Postgres may
|
|
1097
|
+
// rescan it, and each rescan skips the rows this statement already updated and takes the
|
|
1098
|
+
// next ones, so a claim of `limit` rows could lease every free pending run.
|
|
1099
|
+
await withTenantColumnsHint("pg", this.db.execute(sql3`WITH c AS MATERIALIZED (
|
|
1100
|
+
SELECT ${durableWorkflowRuns.id} AS claimed_id FROM ${durableWorkflowRuns}
|
|
1101
|
+
WHERE ${filters}
|
|
1102
|
+
ORDER BY ${durableWorkflowRuns.createdAt}, ${durableWorkflowRuns.id}
|
|
1103
|
+
LIMIT ${limit}
|
|
1104
|
+
FOR UPDATE SKIP LOCKED
|
|
1105
|
+
)
|
|
1106
|
+
UPDATE ${durableWorkflowRuns} AS r
|
|
1107
|
+
SET ${sql3.identifier(getTableColumns2(durableWorkflowRuns).lockedBy.name)} = ${owner},
|
|
1108
|
+
${sql3.identifier(getTableColumns2(durableWorkflowRuns).lockedUntil.name)} = ${new Date(leaseUntilMs).toISOString()}::timestamptz
|
|
1109
|
+
FROM c
|
|
1110
|
+
WHERE r.${sql3.identifier(getTableColumns2(durableWorkflowRuns).id.name)} = c.claimed_id
|
|
1111
|
+
RETURNING ${returning}`))
|
|
1112
|
+
);
|
|
1113
|
+
return rows.map((raw) => fromRunRow(RUNS.decode(raw))).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));
|
|
1114
|
+
}
|
|
686
1115
|
async listDueTimers(nowMs, namespace, limit) {
|
|
687
1116
|
const query = this.db.select().from(durableWorkflowRuns).where(and(eq(durableWorkflowRuns.status, "suspended"), isNotNull(durableWorkflowRuns.wakeAt), lte(durableWorkflowRuns.wakeAt, new Date(nowMs)), namespaceFilter(namespace), this.scope())).orderBy(asc(durableWorkflowRuns.wakeAt));
|
|
688
|
-
const rows = limit !== void 0 ?
|
|
1117
|
+
const rows = await withTenantColumnsHint("pg", limit !== void 0 ? query.limit(limit) : query);
|
|
689
1118
|
return rows.map(fromRunRow);
|
|
690
1119
|
}
|
|
691
1120
|
async tryLockRun(runId, owner, leaseUntilMs, nowMs) {
|
|
1121
|
+
if (this.hot) {
|
|
1122
|
+
const rows2 = await this.hot.query(`${LOCK_RUN} RETURNING "id"`, [
|
|
1123
|
+
runId,
|
|
1124
|
+
owner,
|
|
1125
|
+
lockTime(leaseUntilMs),
|
|
1126
|
+
lockTime(nowMs)
|
|
1127
|
+
]);
|
|
1128
|
+
return rows2.length === 1;
|
|
1129
|
+
}
|
|
692
1130
|
const rows = await this.db.update(durableWorkflowRuns).set({
|
|
693
1131
|
lockedBy: owner,
|
|
694
1132
|
lockedUntil: new Date(leaseUntilMs)
|
|
@@ -698,12 +1136,29 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
698
1136
|
return rows.length === 1;
|
|
699
1137
|
}
|
|
700
1138
|
async releaseRunLock(runId, owner) {
|
|
1139
|
+
if (this.hot) {
|
|
1140
|
+
await (owner === void 0 ? this.hot.query(RELEASE_LOCK, [
|
|
1141
|
+
runId
|
|
1142
|
+
]) : this.hot.query(`${RELEASE_LOCK} AND "locked_by" = $2`, [
|
|
1143
|
+
runId,
|
|
1144
|
+
owner
|
|
1145
|
+
]));
|
|
1146
|
+
return;
|
|
1147
|
+
}
|
|
701
1148
|
await this.db.update(durableWorkflowRuns).set({
|
|
702
1149
|
lockedBy: null,
|
|
703
1150
|
lockedUntil: null
|
|
704
1151
|
}).where(owner === void 0 ? eq(durableWorkflowRuns.id, runId) : and(eq(durableWorkflowRuns.id, runId), eq(durableWorkflowRuns.lockedBy, owner)));
|
|
705
1152
|
}
|
|
706
1153
|
async renewRunLock(runId, owner, leaseUntilMs) {
|
|
1154
|
+
if (this.hot) {
|
|
1155
|
+
const rows2 = await this.hot.query(RENEW_LOCK, [
|
|
1156
|
+
runId,
|
|
1157
|
+
owner,
|
|
1158
|
+
lockTime(leaseUntilMs)
|
|
1159
|
+
]);
|
|
1160
|
+
return rows2.length === 1;
|
|
1161
|
+
}
|
|
707
1162
|
const rows = await this.db.update(durableWorkflowRuns).set({
|
|
708
1163
|
lockedUntil: new Date(leaseUntilMs)
|
|
709
1164
|
}).where(and(eq(durableWorkflowRuns.id, runId), eq(durableWorkflowRuns.lockedBy, owner))).returning({
|
|
@@ -726,6 +1181,8 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
726
1181
|
// `null` selects the unattributed bucket; a value never matches a NULL origin.
|
|
727
1182
|
query.origin === null ? isNull(durableWorkflowRuns.origin) : query.origin !== void 0 ? eq(durableWorkflowRuns.origin, query.origin) : void 0,
|
|
728
1183
|
query.origins ? anyOf(query.origins.map((o) => o === null ? isNull(durableWorkflowRuns.origin) : eq(durableWorkflowRuns.origin, o))) : void 0,
|
|
1184
|
+
// The customer (tenancy matching rule): `null` = runs with no tenant.
|
|
1185
|
+
...tenantFilters(durableWorkflowRuns.tenantId, query),
|
|
729
1186
|
query.status ? eq(durableWorkflowRuns.status, query.status) : void 0,
|
|
730
1187
|
query.statuses ? query.statuses.length ? inArray(durableWorkflowRuns.status, query.statuses) : sql3`1 = 0` : void 0,
|
|
731
1188
|
query.tag ? hasTag(query.tag) : void 0,
|
|
@@ -822,17 +1279,36 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
822
1279
|
async listSchedules(query) {
|
|
823
1280
|
const base = this.db.select().from(durableSchedules).where(and(query.namespace !== void 0 ? eq(durableSchedules.namespace, query.namespace) : void 0, query.workflow !== void 0 ? eq(durableSchedules.workflow, query.workflow) : void 0, query.paused !== void 0 ? eq(durableSchedules.paused, query.paused) : void 0, query.tag !== void 0 ? sql3`${durableSchedules.tags} @> ${JSON.stringify([
|
|
824
1281
|
query.tag
|
|
825
|
-
])}::jsonb` : void 0, query.dueBy !== void 0 ? and(eq(durableSchedules.paused, false), lte(durableSchedules.nextFireAt, new Date(query.dueBy))) : void 0)).orderBy(sql3`${durableSchedules.nextFireAt} ASC NULLS LAST`, asc(durableSchedules.id)).$dynamic();
|
|
1282
|
+
])}::jsonb` : void 0, ...tenantFilters(durableSchedules.tenantId, query), query.dueBy !== void 0 ? and(eq(durableSchedules.paused, false), lte(durableSchedules.nextFireAt, new Date(query.dueBy))) : void 0)).orderBy(sql3`${durableSchedules.nextFireAt} ASC NULLS LAST`, asc(durableSchedules.id)).$dynamic();
|
|
826
1283
|
if (query.limit != null) base.limit(query.limit);
|
|
827
1284
|
if (query.offset != null) base.offset(query.offset);
|
|
828
|
-
return (await base).map(fromScheduleRow);
|
|
1285
|
+
return (await withTenantColumnsHint("pg", base)).map(fromScheduleRow);
|
|
829
1286
|
}
|
|
830
1287
|
async listCheckpoints(runId) {
|
|
831
1288
|
const rows = await this.db.select().from(durableStepCheckpoints).where(eq(durableStepCheckpoints.runId, runId)).orderBy(asc(durableStepCheckpoints.seq));
|
|
832
1289
|
return rows.map(fromCheckpointRow);
|
|
833
1290
|
}
|
|
834
1291
|
async listCheckpointsForReplay(runId) {
|
|
835
|
-
|
|
1292
|
+
if (this.hot) {
|
|
1293
|
+
const rows2 = (await this.hot.query(SELECT_REPLAY, [
|
|
1294
|
+
runId
|
|
1295
|
+
])).map((raw) => CPS_NO_INPUT.decode(raw));
|
|
1296
|
+
const open2 = rows2.filter((row) => row.status !== "completed").map((row) => row.seq);
|
|
1297
|
+
const inputs2 = /* @__PURE__ */ new Map();
|
|
1298
|
+
if (open2.length > 0) {
|
|
1299
|
+
for (const raw of await this.hot.query(SELECT_INPUTS, [
|
|
1300
|
+
runId,
|
|
1301
|
+
open2
|
|
1302
|
+
])) {
|
|
1303
|
+
inputs2.set(Number(raw.seq), CPS.decode(raw).input);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
return rows2.map((row) => fromCheckpointRow({
|
|
1307
|
+
...row,
|
|
1308
|
+
input: inputs2.get(row.seq) ?? null
|
|
1309
|
+
}));
|
|
1310
|
+
}
|
|
1311
|
+
const { input: _input, ...columns } = getTableColumns2(durableStepCheckpoints);
|
|
836
1312
|
const rows = await this.db.select(columns).from(durableStepCheckpoints).where(eq(durableStepCheckpoints.runId, runId)).orderBy(asc(durableStepCheckpoints.seq));
|
|
837
1313
|
const open = rows.filter((row) => row.status !== "completed").map((row) => row.seq);
|
|
838
1314
|
const inputs = /* @__PURE__ */ new Map();
|
|
@@ -854,6 +1330,15 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
854
1330
|
}
|
|
855
1331
|
async hasCheckpoints(runId, fromSeq, toSeq, statuses) {
|
|
856
1332
|
if (statuses.length === 0) return false;
|
|
1333
|
+
if (this.hot) {
|
|
1334
|
+
const rows2 = await this.hot.query(HAS_CHECKPOINTS, [
|
|
1335
|
+
runId,
|
|
1336
|
+
fromSeq,
|
|
1337
|
+
toSeq,
|
|
1338
|
+
statuses
|
|
1339
|
+
]);
|
|
1340
|
+
return rows2.length > 0;
|
|
1341
|
+
}
|
|
857
1342
|
const rows = await this.db.select({
|
|
858
1343
|
seq: durableStepCheckpoints.seq
|
|
859
1344
|
}).from(durableStepCheckpoints).where(and(eq(durableStepCheckpoints.runId, runId), gte(durableStepCheckpoints.seq, fromSeq), lte(durableStepCheckpoints.seq, toSeq), inArray(durableStepCheckpoints.status, statuses))).orderBy(desc(durableStepCheckpoints.seq)).limit(1);
|
|
@@ -861,6 +1346,15 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
861
1346
|
}
|
|
862
1347
|
async countCheckpoints(runId, fromSeq, toSeq, statuses) {
|
|
863
1348
|
if (statuses.length === 0) return 0;
|
|
1349
|
+
if (this.hot) {
|
|
1350
|
+
const rows2 = await this.hot.query(COUNT_CHECKPOINTS, [
|
|
1351
|
+
runId,
|
|
1352
|
+
fromSeq,
|
|
1353
|
+
toSeq,
|
|
1354
|
+
statuses
|
|
1355
|
+
]);
|
|
1356
|
+
return Number(rows2[0]?.n ?? 0);
|
|
1357
|
+
}
|
|
864
1358
|
const rows = await this.db.select({
|
|
865
1359
|
count: sql3`count(*)`.mapWith(Number)
|
|
866
1360
|
}).from(durableStepCheckpoints).where(and(eq(durableStepCheckpoints.runId, runId), gte(durableStepCheckpoints.seq, fromSeq), lte(durableStepCheckpoints.seq, toSeq), inArray(durableStepCheckpoints.status, statuses)));
|
|
@@ -993,6 +1487,16 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
993
1487
|
});
|
|
994
1488
|
}
|
|
995
1489
|
async takeBufferedSignal(token) {
|
|
1490
|
+
if (this.hot) {
|
|
1491
|
+
const [row2] = await this.hot.query(TAKE_BUFFERED_SIGNAL, [
|
|
1492
|
+
token
|
|
1493
|
+
]);
|
|
1494
|
+
if (!row2) return null;
|
|
1495
|
+
const payload = row2.payload == null ? null : SIGNAL_PAYLOAD.mapFromDriverValue(row2.payload);
|
|
1496
|
+
return {
|
|
1497
|
+
payload: payload ?? void 0
|
|
1498
|
+
};
|
|
1499
|
+
}
|
|
996
1500
|
const oldest = this.db.select({
|
|
997
1501
|
id: durableBufferedSignals.id
|
|
998
1502
|
}).from(durableBufferedSignals).where(eq(durableBufferedSignals.token, token)).orderBy(asc(durableBufferedSignals.id)).limit(1).for("update", {
|
|
@@ -1006,6 +1510,59 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
1006
1510
|
payload: row.payload ?? void 0
|
|
1007
1511
|
} : null;
|
|
1008
1512
|
}
|
|
1513
|
+
async takeOldestBufferedSignal(tokens) {
|
|
1514
|
+
if (tokens.length === 0) return null;
|
|
1515
|
+
const oldest = this.db.select({
|
|
1516
|
+
id: durableBufferedSignals.id
|
|
1517
|
+
}).from(durableBufferedSignals).where(inArray(durableBufferedSignals.token, [
|
|
1518
|
+
...new Set(tokens)
|
|
1519
|
+
])).orderBy(asc(durableBufferedSignals.id)).limit(1).for("update", {
|
|
1520
|
+
skipLocked: true
|
|
1521
|
+
});
|
|
1522
|
+
const rows = await this.db.delete(durableBufferedSignals).where(inArray(durableBufferedSignals.id, oldest)).returning({
|
|
1523
|
+
token: durableBufferedSignals.token,
|
|
1524
|
+
payload: durableBufferedSignals.payload
|
|
1525
|
+
});
|
|
1526
|
+
const row = rows[0];
|
|
1527
|
+
return row ? {
|
|
1528
|
+
token: row.token,
|
|
1529
|
+
payload: row.payload ?? void 0
|
|
1530
|
+
} : null;
|
|
1531
|
+
}
|
|
1532
|
+
async claimSignalId(token, id, expiresAt, nowMs) {
|
|
1533
|
+
const rows = await this.db.insert(durableSignalIds).values({
|
|
1534
|
+
token,
|
|
1535
|
+
signalId: id,
|
|
1536
|
+
expiresAt: new Date(expiresAt)
|
|
1537
|
+
}).onConflictDoUpdate({
|
|
1538
|
+
target: [
|
|
1539
|
+
durableSignalIds.token,
|
|
1540
|
+
durableSignalIds.signalId
|
|
1541
|
+
],
|
|
1542
|
+
set: {
|
|
1543
|
+
expiresAt: new Date(expiresAt)
|
|
1544
|
+
},
|
|
1545
|
+
setWhere: lte(durableSignalIds.expiresAt, new Date(nowMs))
|
|
1546
|
+
}).returning({
|
|
1547
|
+
token: durableSignalIds.token
|
|
1548
|
+
});
|
|
1549
|
+
return rows.length > 0;
|
|
1550
|
+
}
|
|
1551
|
+
async releaseSignalId(token, id) {
|
|
1552
|
+
await this.db.delete(durableSignalIds).where(and(eq(durableSignalIds.token, token), eq(durableSignalIds.signalId, id)));
|
|
1553
|
+
}
|
|
1554
|
+
async deleteExpiredSignalIds(nowMs, limit) {
|
|
1555
|
+
const expired = this.db.select({
|
|
1556
|
+
token: durableSignalIds.token,
|
|
1557
|
+
signalId: durableSignalIds.signalId
|
|
1558
|
+
}).from(durableSignalIds).where(lte(durableSignalIds.expiresAt, new Date(nowMs))).limit(limit).for("update", {
|
|
1559
|
+
skipLocked: true
|
|
1560
|
+
});
|
|
1561
|
+
const rows = await this.db.delete(durableSignalIds).where(sql3`(${durableSignalIds.token}, ${durableSignalIds.signalId}) in (${expired})`).returning({
|
|
1562
|
+
token: durableSignalIds.token
|
|
1563
|
+
});
|
|
1564
|
+
return rows.length;
|
|
1565
|
+
}
|
|
1009
1566
|
async listBufferedSignals(tokenPrefix, afterId, limit) {
|
|
1010
1567
|
const rows = await this.db.select().from(durableBufferedSignals).where(and(like(durableBufferedSignals.token, `${escapeLike(tokenPrefix)}%`), afterId !== void 0 ? gt(durableBufferedSignals.id, Number(afterId)) : void 0)).orderBy(asc(durableBufferedSignals.id)).limit(limit);
|
|
1011
1568
|
return rows.filter((r) => r.token.startsWith(tokenPrefix)).map((r) => ({
|
|
@@ -1027,6 +1584,19 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
1027
1584
|
});
|
|
1028
1585
|
}
|
|
1029
1586
|
async listBufferedEvents(name, limit) {
|
|
1587
|
+
if (this.hot) {
|
|
1588
|
+
return (await this.hot.query(LIST_BUFFERED_EVENTS, [
|
|
1589
|
+
name,
|
|
1590
|
+
limit
|
|
1591
|
+
])).map((raw) => {
|
|
1592
|
+
const r = EVENTS.decode(raw);
|
|
1593
|
+
return {
|
|
1594
|
+
id: r.id,
|
|
1595
|
+
payload: r.payload ?? void 0,
|
|
1596
|
+
publishedAt: r.publishedAt.getTime()
|
|
1597
|
+
};
|
|
1598
|
+
});
|
|
1599
|
+
}
|
|
1030
1600
|
const rows = await this.db.select().from(durableBufferedEvents).where(eq(durableBufferedEvents.name, name)).orderBy(asc(durableBufferedEvents.publishedAt), asc(durableBufferedEvents.id)).limit(limit);
|
|
1031
1601
|
return rows.map((r) => ({
|
|
1032
1602
|
id: r.id,
|
|
@@ -1035,6 +1605,9 @@ var DrizzlePgStateStore = class _DrizzlePgStateStore {
|
|
|
1035
1605
|
}));
|
|
1036
1606
|
}
|
|
1037
1607
|
async removeBufferedEvent(id) {
|
|
1608
|
+
if (this.hot) return (await this.hot.query(REMOVE_BUFFERED_EVENT, [
|
|
1609
|
+
id
|
|
1610
|
+
])).length === 1;
|
|
1038
1611
|
const rows = await this.db.delete(durableBufferedEvents).where(eq(durableBufferedEvents.id, id)).returning({
|
|
1039
1612
|
id: durableBufferedEvents.id
|
|
1040
1613
|
});
|
|
@@ -1046,6 +1619,68 @@ function escapeLike(value) {
|
|
|
1046
1619
|
}
|
|
1047
1620
|
__name(escapeLike, "escapeLike");
|
|
1048
1621
|
var CHECKPOINT_BATCH_ROWS = 500;
|
|
1622
|
+
var RUNS = new TableCodec(durableWorkflowRuns);
|
|
1623
|
+
var CPS = new TableCodec(durableStepCheckpoints);
|
|
1624
|
+
var CPS_NO_INPUT = new TableCodec(durableStepCheckpoints, [
|
|
1625
|
+
"input"
|
|
1626
|
+
]);
|
|
1627
|
+
var EVENTS = new TableCodec(durableBufferedEvents);
|
|
1628
|
+
var SIGNAL_PAYLOAD = getTableColumns2(durableBufferedSignals).payload;
|
|
1629
|
+
var T_RUNS = quote(getTableName2(durableWorkflowRuns));
|
|
1630
|
+
var T_CPS = quote(getTableName2(durableStepCheckpoints));
|
|
1631
|
+
var T_EVENTS = quote(getTableName2(durableBufferedEvents));
|
|
1632
|
+
var T_SIGNALS = quote(getTableName2(durableBufferedSignals));
|
|
1633
|
+
var T_ATTRIBUTES = quote(getTableName2(durableRunAttributes));
|
|
1634
|
+
var SELECT_RUN = `SELECT ${RUNS.list} FROM ${T_RUNS} WHERE "id" = $1`;
|
|
1635
|
+
var INSERT_RUN = `INSERT INTO ${T_RUNS} (${RUNS.list}) VALUES (${placeholders(1, RUNS.columns.length)})`;
|
|
1636
|
+
var DELETE_ATTRIBUTES = `DELETE FROM ${T_ATTRIBUTES} WHERE "run_id" = $1`;
|
|
1637
|
+
var LOCK_RUN = `UPDATE ${T_RUNS} SET "locked_by" = $2, "locked_until" = $3 WHERE "id" = $1 AND ("locked_until" IS NULL OR "locked_until" <= $4)`;
|
|
1638
|
+
var RELEASE_LOCK = `UPDATE ${T_RUNS} SET "locked_by" = NULL, "locked_until" = NULL WHERE "id" = $1`;
|
|
1639
|
+
var RENEW_LOCK = `UPDATE ${T_RUNS} SET "locked_until" = $3 WHERE "id" = $1 AND "locked_by" = $2 RETURNING "id"`;
|
|
1640
|
+
var SELECT_CHECKPOINT = `SELECT ${CPS.list} FROM ${T_CPS} WHERE "run_id" = $1 AND "seq" = $2 LIMIT 1`;
|
|
1641
|
+
var SELECT_CHECKPOINTS_FOR_SETTLE = `SELECT ${CPS_NO_INPUT.list} FROM ${T_CPS} WHERE "run_id" = $1 AND "seq" = ANY($2::integer[]) ORDER BY "seq"`;
|
|
1642
|
+
var SELECT_REPLAY = `SELECT ${CPS_NO_INPUT.list} FROM ${T_CPS} WHERE "run_id" = $1 ORDER BY "seq"`;
|
|
1643
|
+
var SELECT_INPUTS = `SELECT "seq", "input" FROM ${T_CPS} WHERE "run_id" = $1 AND "seq" = ANY($2::integer[])`;
|
|
1644
|
+
var CHECKPOINT_VALUES = `(${CPS.list}) VALUES (${placeholders(1, CPS.columns.length)})`;
|
|
1645
|
+
var UPSERT_CHECKPOINT = `INSERT INTO ${T_CPS} ${CHECKPOINT_VALUES} ON CONFLICT ("run_id", "seq") DO UPDATE SET ${CPS.columns.map(([, c]) => `${quote(c.name)} = EXCLUDED.${quote(c.name)}`).join(", ")}`;
|
|
1646
|
+
var INSERT_CHECKPOINT_IF_ABSENT = `INSERT INTO ${T_CPS} ${CHECKPOINT_VALUES} ON CONFLICT ("run_id", "seq") DO NOTHING RETURNING "seq"`;
|
|
1647
|
+
var CHECKPOINT_RANGE = `FROM ${T_CPS} WHERE "run_id" = $1 AND "seq" >= $2 AND "seq" <= $3 AND "status" = ANY($4::text[])`;
|
|
1648
|
+
var HAS_CHECKPOINTS = `SELECT "seq" ${CHECKPOINT_RANGE} ORDER BY "seq" DESC LIMIT 1`;
|
|
1649
|
+
var COUNT_CHECKPOINTS = `SELECT count(*)::integer AS "n" ${CHECKPOINT_RANGE}`;
|
|
1650
|
+
var LIST_BUFFERED_EVENTS = `SELECT ${EVENTS.list} FROM ${T_EVENTS} WHERE "name" = $1 ORDER BY "published_at", "id" LIMIT $2`;
|
|
1651
|
+
var REMOVE_BUFFERED_EVENT = `DELETE FROM ${T_EVENTS} WHERE "id" = $1 RETURNING "id"`;
|
|
1652
|
+
var TAKE_BUFFERED_SIGNAL = `WITH taken AS MATERIALIZED (SELECT "id" FROM ${T_SIGNALS} WHERE "token" = $1 ORDER BY "id" LIMIT 1 FOR UPDATE SKIP LOCKED) DELETE FROM ${T_SIGNALS} WHERE "id" IN (SELECT "id" FROM taken) RETURNING "payload"`;
|
|
1653
|
+
var HOT_SETTLE_MAX_ROWS = 64;
|
|
1654
|
+
var settleTexts = /* @__PURE__ */ new Map();
|
|
1655
|
+
var lockTime = /* @__PURE__ */ __name((ms2) => RUNS.encode("lockedUntil", new Date(ms2)), "lockTime");
|
|
1656
|
+
function settleResultsText(n) {
|
|
1657
|
+
let text2 = settleTexts.get(n);
|
|
1658
|
+
if (text2 !== void 0) return text2;
|
|
1659
|
+
const rows = Array.from({
|
|
1660
|
+
length: n
|
|
1661
|
+
}, (_, r) => {
|
|
1662
|
+
const p = /* @__PURE__ */ __name((k) => `$${r * 8 + k}`, "p");
|
|
1663
|
+
return `(${p(1)}::text, ${p(2)}::integer, ${p(3)}::text, ${p(4)}::jsonb, ${p(5)}::jsonb, ${p(6)}::jsonb, ${p(7)}::timestamptz, ${p(8)}::timestamptz)`;
|
|
1664
|
+
});
|
|
1665
|
+
text2 = `UPDATE ${T_CPS} 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 NOT EXISTS (SELECT 1 FROM ${T_RUNS} AS r WHERE r.id = c.run_id AND r.status IN ('cancelled', 'completed')) RETURNING ${CPS_NO_INPUT.columns.map(([, c]) => `c.${quote(c.name)}`).join(", ")}`;
|
|
1666
|
+
settleTexts.set(n, text2);
|
|
1667
|
+
return text2;
|
|
1668
|
+
}
|
|
1669
|
+
__name(settleResultsText, "settleResultsText");
|
|
1670
|
+
function settleResultValues(r) {
|
|
1671
|
+
const json = /* @__PURE__ */ __name((v) => v == null ? null : JSON.stringify(v), "json");
|
|
1672
|
+
return [
|
|
1673
|
+
r.runId,
|
|
1674
|
+
r.seq,
|
|
1675
|
+
r.status,
|
|
1676
|
+
json(r.status === "completed" ? r.output : null),
|
|
1677
|
+
json(r.error),
|
|
1678
|
+
json(r.events),
|
|
1679
|
+
r.startedAt ? r.startedAt.toISOString() : null,
|
|
1680
|
+
r.finishedAt.toISOString()
|
|
1681
|
+
];
|
|
1682
|
+
}
|
|
1683
|
+
__name(settleResultValues, "settleResultValues");
|
|
1049
1684
|
var rowKey = /* @__PURE__ */ __name((cp) => `${cp.seq}:${cp.runId}`, "rowKey");
|
|
1050
1685
|
function distinctRounds(checkpoints) {
|
|
1051
1686
|
const rounds = [];
|
|
@@ -1092,6 +1727,48 @@ function settleIfPendingFrom(settlements) {
|
|
|
1092
1727
|
RETURNING c.run_id, c.seq`;
|
|
1093
1728
|
}
|
|
1094
1729
|
__name(settleIfPendingFrom, "settleIfPendingFrom");
|
|
1730
|
+
function oneStatement(rows) {
|
|
1731
|
+
if (rows.length > CHECKPOINT_BATCH_ROWS) return false;
|
|
1732
|
+
const keys = new Set(rows.map(rowKey));
|
|
1733
|
+
return keys.size === rows.length;
|
|
1734
|
+
}
|
|
1735
|
+
__name(oneStatement, "oneStatement");
|
|
1736
|
+
var SETTLED_COLUMNS = (() => {
|
|
1737
|
+
const { input: _input, ...columns } = getTableColumns2(durableStepCheckpoints);
|
|
1738
|
+
return columns;
|
|
1739
|
+
})();
|
|
1740
|
+
function settledRowFromDriver(raw) {
|
|
1741
|
+
const row = {
|
|
1742
|
+
input: null
|
|
1743
|
+
};
|
|
1744
|
+
for (const [key, column] of Object.entries(SETTLED_COLUMNS)) {
|
|
1745
|
+
const value = raw[column.name];
|
|
1746
|
+
row[key] = value == null ? null : column.mapFromDriverValue(value);
|
|
1747
|
+
}
|
|
1748
|
+
return row;
|
|
1749
|
+
}
|
|
1750
|
+
__name(settledRowFromDriver, "settledRowFromDriver");
|
|
1751
|
+
function settleResultsFrom(results) {
|
|
1752
|
+
const json = /* @__PURE__ */ __name((v) => v == null ? null : JSON.stringify(v), "json");
|
|
1753
|
+
const values = results.map((r) => sql3`(${r.runId}::text, ${r.seq}::integer, ${r.status}::text, ${json(r.status === "completed" ? r.output : null)}::jsonb, ${json(r.error)}::jsonb, ${json(r.events)}::jsonb, ${r.startedAt ? r.startedAt.toISOString() : null}::timestamptz, ${r.finishedAt.toISOString()}::timestamptz)`);
|
|
1754
|
+
const returning = sql3.join(Object.values(SETTLED_COLUMNS).map((column) => sql3`c.${sql3.identifier(column.name)}`), sql3`, `);
|
|
1755
|
+
return sql3`UPDATE ${durableStepCheckpoints} AS c SET
|
|
1756
|
+
status = v.status,
|
|
1757
|
+
output = CASE WHEN v.status = 'completed' THEN v.output ELSE c.output END,
|
|
1758
|
+
error = v.error,
|
|
1759
|
+
events = COALESCE(v.events, c.events),
|
|
1760
|
+
started_at = COALESCE(v.started_at, c.started_at),
|
|
1761
|
+
finished_at = v.finished_at
|
|
1762
|
+
FROM (VALUES ${sql3.join(values, sql3`, `)}) AS v(run_id, seq, status, output, error, events,
|
|
1763
|
+
started_at, finished_at)
|
|
1764
|
+
WHERE c.run_id = v.run_id AND c.seq = v.seq AND c.status = 'pending'
|
|
1765
|
+
AND NOT EXISTS (
|
|
1766
|
+
SELECT 1 FROM ${durableWorkflowRuns} AS r
|
|
1767
|
+
WHERE r.id = c.run_id AND r.status IN ('cancelled', 'completed')
|
|
1768
|
+
)
|
|
1769
|
+
RETURNING ${returning}`;
|
|
1770
|
+
}
|
|
1771
|
+
__name(settleResultsFrom, "settleResultsFrom");
|
|
1095
1772
|
async function upsertCheckpoint(db, cp) {
|
|
1096
1773
|
const row = toCheckpointRow(cp);
|
|
1097
1774
|
await db.insert(durableStepCheckpoints).values(row).onConflictDoUpdate({
|
|
@@ -1147,6 +1824,8 @@ function toRunRow(run) {
|
|
|
1147
1824
|
priority: run.priority ?? null,
|
|
1148
1825
|
namespace: run.namespace || DEFAULT_NAMESPACE,
|
|
1149
1826
|
origin: run.origin ?? null,
|
|
1827
|
+
tenantId: run.tenantId ?? null,
|
|
1828
|
+
tenantKind: run.tenantKind ?? null,
|
|
1150
1829
|
createdAt: run.createdAt,
|
|
1151
1830
|
updatedAt: run.updatedAt
|
|
1152
1831
|
};
|
|
@@ -1170,6 +1849,8 @@ function toRunPatch(patch) {
|
|
|
1170
1849
|
if ("priority" in patch) row.priority = patch.priority ?? null;
|
|
1171
1850
|
if ("namespace" in patch) row.namespace = patch.namespace || DEFAULT_NAMESPACE;
|
|
1172
1851
|
if ("origin" in patch) row.origin = patch.origin ?? null;
|
|
1852
|
+
if ("tenantId" in patch) row.tenantId = patch.tenantId ?? null;
|
|
1853
|
+
if ("tenantKind" in patch) row.tenantKind = patch.tenantKind ?? null;
|
|
1173
1854
|
if (patch.createdAt != null) row.createdAt = patch.createdAt;
|
|
1174
1855
|
if (patch.updatedAt != null) row.updatedAt = patch.updatedAt;
|
|
1175
1856
|
return row;
|
|
@@ -1194,6 +1875,13 @@ function fromRunRow(row) {
|
|
|
1194
1875
|
priority: row.priority ?? void 0,
|
|
1195
1876
|
namespace: row.namespace || DEFAULT_NAMESPACE,
|
|
1196
1877
|
origin: row.origin ?? void 0,
|
|
1878
|
+
// NULL = no tenant; left off entirely so a tenancy-off run reads back unchanged.
|
|
1879
|
+
...row.tenantId != null ? {
|
|
1880
|
+
tenantId: row.tenantId
|
|
1881
|
+
} : {},
|
|
1882
|
+
...row.tenantKind != null ? {
|
|
1883
|
+
tenantKind: row.tenantKind
|
|
1884
|
+
} : {},
|
|
1197
1885
|
createdAt: row.createdAt,
|
|
1198
1886
|
updatedAt: row.updatedAt
|
|
1199
1887
|
};
|
|
@@ -1254,6 +1942,8 @@ function toScheduleRow(r) {
|
|
|
1254
1942
|
tags: r.tags ?? null,
|
|
1255
1943
|
spec: r.spec,
|
|
1256
1944
|
state: r.state,
|
|
1945
|
+
tenantId: r.tenantId ?? null,
|
|
1946
|
+
tenantKind: r.tenantKind ?? null,
|
|
1257
1947
|
createdAt: r.createdAt,
|
|
1258
1948
|
updatedAt: r.updatedAt
|
|
1259
1949
|
};
|
|
@@ -1268,6 +1958,8 @@ function toSchedulePatch(patch) {
|
|
|
1268
1958
|
if ("tags" in patch) set.tags = patch.tags ?? null;
|
|
1269
1959
|
if (patch.spec !== void 0) set.spec = patch.spec;
|
|
1270
1960
|
if (patch.state !== void 0) set.state = patch.state;
|
|
1961
|
+
if ("tenantId" in patch) set.tenantId = patch.tenantId ?? null;
|
|
1962
|
+
if ("tenantKind" in patch) set.tenantKind = patch.tenantKind ?? null;
|
|
1271
1963
|
if (patch.updatedAt !== void 0) set.updatedAt = patch.updatedAt;
|
|
1272
1964
|
return set;
|
|
1273
1965
|
}
|
|
@@ -1284,13 +1976,19 @@ function fromScheduleRow(row) {
|
|
|
1284
1976
|
} : {},
|
|
1285
1977
|
spec: row.spec ?? {},
|
|
1286
1978
|
state: row.state ?? {},
|
|
1979
|
+
...row.tenantId != null ? {
|
|
1980
|
+
tenantId: row.tenantId
|
|
1981
|
+
} : {},
|
|
1982
|
+
...row.tenantKind != null ? {
|
|
1983
|
+
tenantKind: row.tenantKind
|
|
1984
|
+
} : {},
|
|
1287
1985
|
createdAt: row.createdAt,
|
|
1288
1986
|
updatedAt: row.updatedAt
|
|
1289
1987
|
};
|
|
1290
1988
|
}
|
|
1291
1989
|
__name(fromScheduleRow, "fromScheduleRow");
|
|
1292
1990
|
function excludedSet(table, only) {
|
|
1293
|
-
return Object.fromEntries(Object.entries(
|
|
1991
|
+
return Object.fromEntries(Object.entries(getTableColumns2(table)).filter(([key]) => !only || only.includes(key)).map(([key, column]) => [
|
|
1294
1992
|
key,
|
|
1295
1993
|
sql3.raw(`excluded."${column.name}"`)
|
|
1296
1994
|
]));
|
|
@@ -1308,6 +2006,7 @@ export {
|
|
|
1308
2006
|
durablePgSchema,
|
|
1309
2007
|
durableRunAttributes,
|
|
1310
2008
|
durableSchedules,
|
|
2009
|
+
durableSignalIds,
|
|
1311
2010
|
durableSignalWaiters,
|
|
1312
2011
|
durableStepCheckpoints,
|
|
1313
2012
|
durableWorkflowRuns,
|