@dudousxd/nestjs-durable-store-drizzle 0.26.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
@@ -108,9 +108,23 @@ var workflowRuns = (0, import_sqlite_core.sqliteTable)("durable_workflow_runs",
108
108
  // declared here, so until that runs, EVERY run query fails with "no such column: origin" — the same
109
109
  // step `priority` needed before it.
110
110
  origin: (0, import_sqlite_core.text)("origin"),
111
+ // The CUSTOMER (organization, clinic…) the run belongs to — tenancy, not the worker-pool
112
+ // `namespace`. Nullable: NULL = no tenant, which is every run while tenancy is off.
113
+ //
114
+ // MIGRATION (you own this adapter's migrations; until it runs, every run query fails with
115
+ // "no such column: tenant_id"):
116
+ //
117
+ // ALTER TABLE durable_workflow_runs ADD COLUMN tenant_id TEXT;
118
+ // ALTER TABLE durable_workflow_runs ADD COLUMN tenant_kind TEXT;
119
+ // CREATE INDEX IF NOT EXISTS durable_workflow_runs_tenant_idx
120
+ // ON durable_workflow_runs (tenant_id, created_at);
121
+ tenantId: (0, import_sqlite_core.text)("tenant_id"),
122
+ tenantKind: (0, import_sqlite_core.text)("tenant_kind"),
111
123
  createdAt: (0, import_sqlite_core.integer)("created_at").notNull(),
112
124
  updatedAt: (0, import_sqlite_core.integer)("updated_at").notNull()
113
125
  }, (t) => [
126
+ // App-facing reads with tenancy on filter by tenant and page newest first.
127
+ (0, import_sqlite_core.index)("durable_workflow_runs_tenant_idx").on(t.tenantId, t.createdAt),
114
128
  // `namespace` sits on EVERY poll tick's predicate — the pending (FIFO by `created_at`),
115
129
  // incomplete and due-timer scans all filter by it and then by `status` — unlike `origin`, which
116
130
  // only the dashboard's listing touches. Mirrors the MikroORM adapter's
@@ -242,12 +256,19 @@ var durableSchedules = (0, import_sqlite_core.sqliteTable)(
242
256
  state: (0, import_sqlite_core.text)("state", {
243
257
  mode: "json"
244
258
  }).$type().notNull(),
259
+ // The customer the schedule (and every run it starts) belongs to. MIGRATION:
260
+ // ALTER TABLE durable_schedules ADD COLUMN tenant_id TEXT;
261
+ // ALTER TABLE durable_schedules ADD COLUMN tenant_kind TEXT;
262
+ // CREATE INDEX IF NOT EXISTS durable_schedules_tenant_idx ON durable_schedules (tenant_id);
263
+ tenantId: (0, import_sqlite_core.text)("tenant_id"),
264
+ tenantKind: (0, import_sqlite_core.text)("tenant_kind"),
245
265
  createdAt: (0, import_sqlite_core.integer)("created_at").notNull(),
246
266
  updatedAt: (0, import_sqlite_core.integer)("updated_at").notNull()
247
267
  },
248
268
  // The poll's "due by T" scan: `paused = 0 AND next_fire_at <= T ORDER BY next_fire_at`.
249
269
  (t) => [
250
- (0, import_sqlite_core.index)("durable_schedules_due_idx").on(t.paused, t.nextFireAt)
270
+ (0, import_sqlite_core.index)("durable_schedules_due_idx").on(t.paused, t.nextFireAt),
271
+ (0, import_sqlite_core.index)("durable_schedules_tenant_idx").on(t.tenantId)
251
272
  ]
252
273
  );
253
274
  var durableSchema = {
@@ -265,6 +286,74 @@ function durableManagedTables() {
265
286
  }
266
287
  __name(durableManagedTables, "durableManagedTables");
267
288
 
289
+ // src/tenant-columns.ts
290
+ var PG_STATEMENTS = [
291
+ 'ALTER TABLE "durable_workflow_runs" ADD COLUMN IF NOT EXISTS "tenant_id" text;',
292
+ 'ALTER TABLE "durable_workflow_runs" ADD COLUMN IF NOT EXISTS "tenant_kind" text;',
293
+ 'ALTER TABLE "durable_schedules" ADD COLUMN IF NOT EXISTS "tenant_id" text;',
294
+ 'ALTER TABLE "durable_schedules" ADD COLUMN IF NOT EXISTS "tenant_kind" text;',
295
+ 'CREATE INDEX IF NOT EXISTS "durable_workflow_runs_tenant_idx" ON "durable_workflow_runs" USING btree ("tenant_id","created_at");',
296
+ 'CREATE INDEX IF NOT EXISTS "durable_schedules_tenant_idx" ON "durable_schedules" USING btree ("tenant_id");'
297
+ ];
298
+ var SQLITE_STATEMENTS = [
299
+ "ALTER TABLE durable_workflow_runs ADD COLUMN tenant_id TEXT;",
300
+ "ALTER TABLE durable_workflow_runs ADD COLUMN tenant_kind TEXT;",
301
+ "ALTER TABLE durable_schedules ADD COLUMN tenant_id TEXT;",
302
+ "ALTER TABLE durable_schedules ADD COLUMN tenant_kind TEXT;",
303
+ "CREATE INDEX IF NOT EXISTS durable_workflow_runs_tenant_idx ON durable_workflow_runs (tenant_id, created_at);",
304
+ "CREATE INDEX IF NOT EXISTS durable_schedules_tenant_idx ON durable_schedules (tenant_id);"
305
+ ];
306
+ var TENANT_COLUMN = /tenant_(id|kind)/;
307
+ function isMissingTenantColumn(err) {
308
+ let cur = err;
309
+ for (let depth = 0; cur && depth < 5; depth += 1) {
310
+ const e = cur;
311
+ const message = typeof e.message === "string" ? e.message : "";
312
+ if (TENANT_COLUMN.test(message)) {
313
+ if (e.code === "42703" || /does not exist/.test(message) || /no such column/i.test(message)) {
314
+ return true;
315
+ }
316
+ }
317
+ cur = e.cause;
318
+ }
319
+ return false;
320
+ }
321
+ __name(isMissingTenantColumn, "isMissingTenantColumn");
322
+ var MissingTenantColumnsError = class extends Error {
323
+ static {
324
+ __name(this, "MissingTenantColumnsError");
325
+ }
326
+ constructor(dialect, cause) {
327
+ const statements = dialect === "pg" ? PG_STATEMENTS : SQLITE_STATEMENTS;
328
+ 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.";
329
+ super([
330
+ "[nestjs-durable] The durable tables are missing the tenancy columns (tenant_id, tenant_kind).",
331
+ "This version of the Drizzle store reads them on every run and schedule query, even with tenancy off.",
332
+ fix,
333
+ "The migration must contain:",
334
+ ...statements.map((s) => ` ${s}`)
335
+ ].join("\n"), {
336
+ cause
337
+ });
338
+ this.name = "MissingTenantColumnsError";
339
+ }
340
+ };
341
+ function tenantColumnsHint(dialect) {
342
+ return (err) => {
343
+ if (isMissingTenantColumn(err)) throw new MissingTenantColumnsError(dialect, err);
344
+ throw err;
345
+ };
346
+ }
347
+ __name(tenantColumnsHint, "tenantColumnsHint");
348
+ async function withTenantColumnsHint(dialect, query) {
349
+ try {
350
+ return await query;
351
+ } catch (err) {
352
+ return tenantColumnsHint(dialect)(err);
353
+ }
354
+ }
355
+ __name(withTenantColumnsHint, "withTenantColumnsHint");
356
+
268
357
  // src/drizzle-state-store.ts
269
358
  var RETENTION_EXCLUDED = [
270
359
  import_nestjs_durable_core.LIFECYCLE_REGISTRY_WORKFLOW
@@ -274,6 +363,14 @@ function anyOf(conditions) {
274
363
  return present.length ? (0, import_drizzle_orm2.or)(...present) : import_drizzle_orm2.sql`1 = 0`;
275
364
  }
276
365
  __name(anyOf, "anyOf");
366
+ function tenantFilters(column, query) {
367
+ const one = /* @__PURE__ */ __name((id) => id === null ? (0, import_drizzle_orm2.isNull)(column) : (0, import_drizzle_orm2.eq)(column, id), "one");
368
+ return [
369
+ query.tenantId !== void 0 ? one(query.tenantId) : void 0,
370
+ query.tenantIds ? anyOf(query.tenantIds.map(one)) : void 0
371
+ ];
372
+ }
373
+ __name(tenantFilters, "tenantFilters");
277
374
  function namespaceFilter(namespace) {
278
375
  if (namespace === void 0) return void 0;
279
376
  if (namespace === DEFAULT_NAMESPACE || namespace === "") return (0, import_drizzle_orm2.or)((0, import_drizzle_orm2.eq)(workflowRuns.namespace, DEFAULT_NAMESPACE), (0, import_drizzle_orm2.eq)(workflowRuns.namespace, ""), (0, import_drizzle_orm2.isNull)(workflowRuns.namespace));
@@ -587,15 +684,15 @@ var DrizzleStateStore = class {
587
684
  /** Recovery on boot. Namespace-scoped: a worker re-drives only its own tenant's crashed runs.
588
685
  * `and(...)` drops an `undefined` predicate, so an unscoped caller recovers every namespace. */
589
686
  async listIncompleteRuns(namespace) {
590
- const rows = await this.db.select().from(workflowRuns).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.inArray)(workflowRuns.status, [
687
+ const rows = await withTenantColumnsHint("sqlite", this.db.select().from(workflowRuns).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.inArray)(workflowRuns.status, [
591
688
  "running",
592
689
  "cancelling"
593
- ]), namespaceFilter(namespace)));
690
+ ]), namespaceFilter(namespace))));
594
691
  return rows.map(fromRunRow);
595
692
  }
596
693
  async listOrphanedRuns(nowMs, limit, namespace, ownedBy) {
597
694
  if (limit <= 0) return [];
598
- const rows = await this.db.select().from(workflowRuns).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.inArray)(workflowRuns.status, [
695
+ const rows = await withTenantColumnsHint("sqlite", this.db.select().from(workflowRuns).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.inArray)(workflowRuns.status, [
599
696
  "running",
600
697
  "cancelling"
601
698
  ]), (0, import_drizzle_orm2.or)(
@@ -603,19 +700,19 @@ var DrizzleStateStore = class {
603
700
  (0, import_drizzle_orm2.lte)(workflowRuns.lockedUntil, nowMs),
604
701
  // A live lease left by a previous process with the caller's own instance id.
605
702
  ownedBy ? (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(workflowRuns.lockedBy, ownedBy.owner), (0, import_drizzle_orm2.lt)(workflowRuns.lockedUntil, ownedBy.lockedBefore)) : void 0
606
- ), namespaceFilter(namespace))).orderBy((0, import_drizzle_orm2.asc)(workflowRuns.createdAt)).limit(limit);
703
+ ), namespaceFilter(namespace))).orderBy((0, import_drizzle_orm2.asc)(workflowRuns.createdAt)).limit(limit));
607
704
  return rows.map(fromRunRow);
608
705
  }
609
706
  /** Dispatch pick-up. Namespace-scoped — without it a worker serving one tenant drains another
610
707
  * tenant's queue, and the `limit` makes it worse: foreign runs consume the FIFO budget. */
611
708
  async listPendingRuns(limit, namespace) {
612
- const rows = await this.db.select().from(workflowRuns).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(workflowRuns.status, "pending"), namespaceFilter(namespace))).orderBy((0, import_drizzle_orm2.asc)(workflowRuns.createdAt)).limit(limit);
709
+ const rows = await withTenantColumnsHint("sqlite", this.db.select().from(workflowRuns).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(workflowRuns.status, "pending"), namespaceFilter(namespace))).orderBy((0, import_drizzle_orm2.asc)(workflowRuns.createdAt)).limit(limit));
613
710
  return rows.map(fromRunRow);
614
711
  }
615
712
  /** Due durable timers. Namespace-scoped: a worker resumes only its own tenant's suspended runs. */
616
713
  async listDueTimers(nowMs, namespace, limit) {
617
714
  const query = this.db.select().from(workflowRuns).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(workflowRuns.status, "suspended"), (0, import_drizzle_orm2.isNotNull)(workflowRuns.wakeAt), (0, import_drizzle_orm2.lte)(workflowRuns.wakeAt, nowMs), namespaceFilter(namespace))).orderBy((0, import_drizzle_orm2.asc)(workflowRuns.wakeAt));
618
- const rows = limit !== void 0 ? await query.limit(limit) : await query;
715
+ const rows = await withTenantColumnsHint("sqlite", limit !== void 0 ? query.limit(limit) : query);
619
716
  return rows.map(fromRunRow);
620
717
  }
621
718
  async tryLockRun(runId, owner, leaseUntilMs, nowMs) {
@@ -665,6 +762,8 @@ var DrizzleStateStore = class {
665
762
  // A set of origins may include `null` (the unattributed bucket), which `IN` cannot carry —
666
763
  // `IN (NULL)` is never true — so it becomes its own ORed `IS NULL` branch.
667
764
  query.origins ? anyOf(query.origins.map((o) => o === null ? (0, import_drizzle_orm2.isNull)(workflowRuns.origin) : (0, import_drizzle_orm2.eq)(workflowRuns.origin, o))) : void 0,
765
+ // The customer (tenancy matching rule): `null` = runs with no tenant.
766
+ ...tenantFilters(workflowRuns.tenantId, query),
668
767
  query.status ? (0, import_drizzle_orm2.eq)(workflowRuns.status, query.status) : void 0,
669
768
  // `status IN (...)`; an empty set matches nothing (mirrors the in-memory store).
670
769
  query.statuses ? query.statuses.length ? (0, import_drizzle_orm2.inArray)(workflowRuns.status, query.statuses) : import_drizzle_orm2.sql`1 = 0` : void 0,
@@ -765,7 +864,7 @@ var DrizzleStateStore = class {
765
864
  return rows.length > 0;
766
865
  }
767
866
  async listSchedules(query) {
768
- const rows = await this.db.select().from(durableSchedules).where((0, import_drizzle_orm2.and)(query.namespace !== void 0 ? (0, import_drizzle_orm2.eq)(durableSchedules.namespace, query.namespace) : void 0, query.workflow !== void 0 ? (0, import_drizzle_orm2.eq)(durableSchedules.workflow, query.workflow) : void 0, query.paused !== void 0 ? (0, import_drizzle_orm2.eq)(durableSchedules.paused, query.paused) : void 0, query.tag !== void 0 ? (0, import_drizzle_orm2.like)(durableSchedules.tags, `%"${query.tag}"%`) : void 0, query.dueBy !== void 0 ? (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(durableSchedules.paused, false), (0, import_drizzle_orm2.lte)(durableSchedules.nextFireAt, query.dueBy)) : void 0)).orderBy(import_drizzle_orm2.sql`${durableSchedules.nextFireAt} IS NULL`, (0, import_drizzle_orm2.asc)(durableSchedules.nextFireAt), (0, import_drizzle_orm2.asc)(durableSchedules.id)).limit(query.limit ?? -1).offset(query.offset ?? 0);
867
+ const rows = await withTenantColumnsHint("sqlite", this.db.select().from(durableSchedules).where((0, import_drizzle_orm2.and)(query.namespace !== void 0 ? (0, import_drizzle_orm2.eq)(durableSchedules.namespace, query.namespace) : void 0, query.workflow !== void 0 ? (0, import_drizzle_orm2.eq)(durableSchedules.workflow, query.workflow) : void 0, query.paused !== void 0 ? (0, import_drizzle_orm2.eq)(durableSchedules.paused, query.paused) : void 0, query.tag !== void 0 ? (0, import_drizzle_orm2.like)(durableSchedules.tags, `%"${query.tag}"%`) : void 0, ...tenantFilters(durableSchedules.tenantId, query), query.dueBy !== void 0 ? (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(durableSchedules.paused, false), (0, import_drizzle_orm2.lte)(durableSchedules.nextFireAt, query.dueBy)) : void 0)).orderBy(import_drizzle_orm2.sql`${durableSchedules.nextFireAt} IS NULL`, (0, import_drizzle_orm2.asc)(durableSchedules.nextFireAt), (0, import_drizzle_orm2.asc)(durableSchedules.id)).limit(query.limit ?? -1).offset(query.offset ?? 0));
769
868
  return rows.map(fromScheduleRow);
770
869
  }
771
870
  async listCheckpoints(runId) {
@@ -1094,6 +1193,8 @@ function toRunRow(run) {
1094
1193
  namespace: run.namespace || DEFAULT_NAMESPACE,
1095
1194
  // Absent origin stays SQL NULL — "unknown", never coerced into a real-looking library name.
1096
1195
  origin: run.origin ?? null,
1196
+ tenantId: run.tenantId ?? null,
1197
+ tenantKind: run.tenantKind ?? null,
1097
1198
  createdAt: run.createdAt.getTime(),
1098
1199
  updatedAt: run.updatedAt.getTime()
1099
1200
  };
@@ -1117,6 +1218,8 @@ function toRunPatch(patch) {
1117
1218
  if ("priority" in patch) row.priority = patch.priority ?? null;
1118
1219
  if ("namespace" in patch) row.namespace = patch.namespace || DEFAULT_NAMESPACE;
1119
1220
  if ("origin" in patch) row.origin = patch.origin ?? null;
1221
+ if ("tenantId" in patch) row.tenantId = patch.tenantId ?? null;
1222
+ if ("tenantKind" in patch) row.tenantKind = patch.tenantKind ?? null;
1120
1223
  if (patch.createdAt != null) row.createdAt = patch.createdAt.getTime();
1121
1224
  if (patch.updatedAt != null) row.updatedAt = patch.updatedAt.getTime();
1122
1225
  return row;
@@ -1146,6 +1249,13 @@ function fromRunRow(row) {
1146
1249
  namespace: row.namespace || DEFAULT_NAMESPACE,
1147
1250
  // NULL (a row written before the column existed) surfaces as `undefined` = unknown origin.
1148
1251
  origin: row.origin ?? void 0,
1252
+ // NULL = no tenant; left off the object entirely so a tenancy-off run reads back unchanged.
1253
+ ...row.tenantId != null ? {
1254
+ tenantId: row.tenantId
1255
+ } : {},
1256
+ ...row.tenantKind != null ? {
1257
+ tenantKind: row.tenantKind
1258
+ } : {},
1149
1259
  createdAt: new Date(row.createdAt),
1150
1260
  updatedAt: new Date(row.updatedAt)
1151
1261
  };
@@ -1205,6 +1315,8 @@ function toScheduleRow(r) {
1205
1315
  tags: r.tags ?? null,
1206
1316
  spec: r.spec,
1207
1317
  state: r.state,
1318
+ tenantId: r.tenantId ?? null,
1319
+ tenantKind: r.tenantKind ?? null,
1208
1320
  createdAt: r.createdAt.getTime(),
1209
1321
  updatedAt: r.updatedAt.getTime()
1210
1322
  };
@@ -1219,6 +1331,8 @@ function toSchedulePatch(patch) {
1219
1331
  if ("tags" in patch) set.tags = patch.tags ?? null;
1220
1332
  if ("spec" in patch && patch.spec !== void 0) set.spec = patch.spec;
1221
1333
  if ("state" in patch && patch.state !== void 0) set.state = patch.state;
1334
+ if ("tenantId" in patch) set.tenantId = patch.tenantId ?? null;
1335
+ if ("tenantKind" in patch) set.tenantKind = patch.tenantKind ?? null;
1222
1336
  if ("updatedAt" in patch && patch.updatedAt !== void 0) set.updatedAt = patch.updatedAt.getTime();
1223
1337
  return set;
1224
1338
  }
@@ -1235,6 +1349,12 @@ function fromScheduleRow(row) {
1235
1349
  } : {},
1236
1350
  spec: row.spec ?? {},
1237
1351
  state: row.state ?? {},
1352
+ ...row.tenantId != null ? {
1353
+ tenantId: row.tenantId
1354
+ } : {},
1355
+ ...row.tenantKind != null ? {
1356
+ tenantKind: row.tenantKind
1357
+ } : {},
1238
1358
  createdAt: new Date(row.createdAt),
1239
1359
  updatedAt: new Date(row.updatedAt)
1240
1360
  };