@dudousxd/nestjs-durable-store-typeorm 0.16.1 → 0.18.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 +75 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -1
- package/dist/index.d.ts +14 -1
- package/dist/index.js +76 -11
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -979,17 +979,36 @@ var TypeOrmStateStore = class {
|
|
|
979
979
|
}).execute();
|
|
980
980
|
return result.affected === 1;
|
|
981
981
|
}
|
|
982
|
-
|
|
982
|
+
/** A query builder (root alias `r`) carrying the predicates every run query shares —
|
|
983
|
+
* {@link listRuns} orders + pages it, {@link runFacets} groups it, so a facet count and the page
|
|
984
|
+
* it labels are always taken over the same set. */
|
|
985
|
+
runQueryBuilder(query) {
|
|
983
986
|
const qb = this.runs().createQueryBuilder("r");
|
|
984
987
|
if (query.workflow) qb.andWhere("r.workflow = :workflow", {
|
|
985
988
|
workflow: query.workflow
|
|
986
989
|
});
|
|
990
|
+
if (query.workflows) qb.andWhere(query.workflows.length ? "r.workflow IN (:...workflows)" : "1 = 0", query.workflows.length ? {
|
|
991
|
+
workflows: query.workflows
|
|
992
|
+
} : {});
|
|
987
993
|
if (query.namespace !== void 0) qb.andWhere("r.namespace = :namespace", {
|
|
988
994
|
namespace: query.namespace
|
|
989
995
|
});
|
|
990
|
-
if (query.
|
|
996
|
+
if (query.namespaces) qb.andWhere(query.namespaces.length ? "r.namespace IN (:...namespaces)" : "1 = 0", query.namespaces.length ? {
|
|
997
|
+
namespaces: query.namespaces
|
|
998
|
+
} : {});
|
|
999
|
+
if (query.origin === null) qb.andWhere("r.origin IS NULL");
|
|
1000
|
+
else if (query.origin !== void 0) qb.andWhere("r.origin = :origin", {
|
|
991
1001
|
origin: query.origin
|
|
992
1002
|
});
|
|
1003
|
+
if (query.origins) {
|
|
1004
|
+
const named = query.origins.filter((o) => o !== null);
|
|
1005
|
+
const branches = [];
|
|
1006
|
+
if (named.length) branches.push("r.origin IN (:...origins)");
|
|
1007
|
+
if (query.origins.some((o) => o === null)) branches.push("r.origin IS NULL");
|
|
1008
|
+
qb.andWhere(branches.length ? `(${branches.join(" OR ")})` : "1 = 0", named.length ? {
|
|
1009
|
+
origins: named
|
|
1010
|
+
} : {});
|
|
1011
|
+
}
|
|
993
1012
|
if (query.status) qb.andWhere("r.status = :status", {
|
|
994
1013
|
status: query.status
|
|
995
1014
|
});
|
|
@@ -999,36 +1018,82 @@ var TypeOrmStateStore = class {
|
|
|
999
1018
|
if (query.tag) qb.andWhere("r.tags LIKE :tagPattern", {
|
|
1000
1019
|
tagPattern: `%"${query.tag}"%`
|
|
1001
1020
|
});
|
|
1021
|
+
if (query.tags) {
|
|
1022
|
+
const branches = query.tags.map((_, i) => `r.tags LIKE :tagPattern${i}`);
|
|
1023
|
+
qb.andWhere(branches.length ? `(${branches.join(" OR ")})` : "1 = 0", Object.fromEntries(query.tags.map((t, i) => [
|
|
1024
|
+
`tagPattern${i}`,
|
|
1025
|
+
`%"${t}"%`
|
|
1026
|
+
])));
|
|
1027
|
+
}
|
|
1002
1028
|
if (query.attributes?.length) {
|
|
1003
1029
|
query.attributes.forEach((f, i) => this.applyAttributeExists(qb, f, i));
|
|
1004
1030
|
}
|
|
1031
|
+
return qb;
|
|
1032
|
+
}
|
|
1033
|
+
async listRuns(query) {
|
|
1034
|
+
const qb = this.runQueryBuilder(query);
|
|
1005
1035
|
qb.orderBy("r.createdAt", "DESC");
|
|
1006
1036
|
if (query.limit != null) qb.take(query.limit);
|
|
1007
1037
|
if (query.offset != null) qb.skip(query.offset);
|
|
1008
1038
|
const rows = await qb.getMany();
|
|
1009
1039
|
return rows.map(fromRunEntity);
|
|
1010
1040
|
}
|
|
1041
|
+
/** `GROUP BY status, origin` over the same predicates {@link listRuns} pages — one aggregate, so a
|
|
1042
|
+
* console can show whole-set counts next to a bounded page instead of downloading every run to
|
|
1043
|
+
* count them in the browser. */
|
|
1044
|
+
async runFacets(query) {
|
|
1045
|
+
const rows = await this.runQueryBuilder(query).select("r.status", "status").addSelect("r.origin", "origin").addSelect("COUNT(*)", "count").groupBy("r.status").addGroupBy("r.origin").getRawMany();
|
|
1046
|
+
return (0, import_nestjs_durable_core.mergeRunFacetRows)(rows.map((r) => ({
|
|
1047
|
+
...r,
|
|
1048
|
+
count: Number(r.count)
|
|
1049
|
+
})));
|
|
1050
|
+
}
|
|
1051
|
+
/** Distinct values of one filter axis over the same predicates {@link listRuns} pages. A run-table
|
|
1052
|
+
* column is a `GROUP BY` like {@link runFacets}, exact over the whole matching set; the tag and
|
|
1053
|
+
* attribute axes live outside the row (json text / side table) and are counted from a bounded page
|
|
1054
|
+
* of runs instead — see `RunValueFacetOptions.scan`. */
|
|
1055
|
+
async runValueFacets(axis, query, opts) {
|
|
1056
|
+
if (!(0, import_nestjs_durable_core.axisIsRunColumn)(axis)) {
|
|
1057
|
+
const runs = await this.listRuns({
|
|
1058
|
+
...query,
|
|
1059
|
+
limit: opts?.scan ?? import_nestjs_durable_core.RUN_VALUE_FACET_SCAN
|
|
1060
|
+
});
|
|
1061
|
+
return (0, import_nestjs_durable_core.runValueFacetsFromRuns)(runs, axis, opts);
|
|
1062
|
+
}
|
|
1063
|
+
const rows = await this.runQueryBuilder(query).select(`r.${axis.field}`, "value").addSelect("COUNT(*)", "count").groupBy(`r.${axis.field}`).getRawMany();
|
|
1064
|
+
return (0, import_nestjs_durable_core.mergeRunValueFacetRows)(rows.map((r) => ({
|
|
1065
|
+
value: r.value ?? null,
|
|
1066
|
+
count: Number(r.count)
|
|
1067
|
+
})), opts);
|
|
1068
|
+
}
|
|
1011
1069
|
/** Add one attribute predicate to `qb` as an EXISTS subquery on the side-table. `i` namespaces the
|
|
1012
1070
|
* bind params so multiple ANDed filters don't collide. */
|
|
1013
1071
|
applyAttributeExists(qb, f, i) {
|
|
1014
|
-
const
|
|
1015
|
-
const cmp = (0, import_nestjs_durable_core.sqlComparator)(f.op);
|
|
1072
|
+
const comparisons = (0, import_nestjs_durable_core.attributePredicateOperands)(f);
|
|
1016
1073
|
const keyParam = `attrKey${i}`;
|
|
1017
|
-
const valParam = `attrVal${i}`;
|
|
1018
1074
|
const resolve = durableColumnResolver(this.dataSource);
|
|
1019
1075
|
const q = this.idQuote();
|
|
1020
1076
|
const wrap = /* @__PURE__ */ __name((name) => `${q}${name}${q}`, "wrap");
|
|
1021
1077
|
const runIdCol = wrap(resolve("durable_run_attributes", "runId"));
|
|
1022
1078
|
const keyCol = wrap(resolve("durable_run_attributes", "key"));
|
|
1023
|
-
const valueCol = wrap(resolve("durable_run_attributes", valueProperty));
|
|
1024
1079
|
const runPkCol = wrap(resolve("durable_workflow_runs", "id"));
|
|
1025
1080
|
const table = wrap("durable_run_attributes");
|
|
1026
1081
|
const a = `a${i}`;
|
|
1027
|
-
const
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1082
|
+
const params = {
|
|
1083
|
+
[keyParam]: f.key
|
|
1084
|
+
};
|
|
1085
|
+
const branches = comparisons.map(({ column, comparator, operand }, j) => {
|
|
1086
|
+
const valParam = `attrVal${i}_${j}`;
|
|
1087
|
+
params[valParam] = operand;
|
|
1088
|
+
return `${a}.${wrap(resolve("durable_run_attributes", column))} ${comparator} :${valParam}`;
|
|
1031
1089
|
});
|
|
1090
|
+
if (branches.length === 0) {
|
|
1091
|
+
qb.andWhere("1 = 0");
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
const match = branches.length === 1 ? branches[0] : `(${branches.join(" OR ")})`;
|
|
1095
|
+
const sql = `EXISTS (SELECT 1 FROM ${table} ${a} WHERE ${a}.${runIdCol} = r.${runPkCol} AND ${a}.${keyCol} = :${keyParam} AND ${match})`;
|
|
1096
|
+
qb.andWhere(sql, params);
|
|
1032
1097
|
}
|
|
1033
1098
|
/** The identifier quote char for the active driver (MySQL backtick, others double-quote). */
|
|
1034
1099
|
idQuote() {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/entities.ts","../src/schema.ts","../src/typeorm-state-store.ts"],"sourcesContent":["export * from './entities';\nexport * from './schema';\nexport * from './typeorm-state-store';\n","import type { RunStatus, StepKind } from '@dudousxd/nestjs-durable-core';\nimport { EntitySchema, type ValueTransformer } from 'typeorm';\n\n/**\n * Safely deserialize a JSON-text column back to an object on READ.\n *\n * A column truncated by the old MySQL `text` 64KB limit (or otherwise corrupt) makes `JSON.parse`\n * throw \"Unterminated string in JSON\" — which, without this guard, would 500 the *entire* run-detail\n * read just because one blob is damaged. Instead, log once and degrade the bad field to `undefined`\n * so the rest of the run still renders. Valid JSON is unchanged.\n */\nexport function parseJsonColumn<T = unknown>(raw: unknown, field: string): T | undefined {\n if (raw == null) return undefined;\n // Some drivers (e.g. a native `json` column) already hand back a parsed object.\n if (typeof raw !== 'string') return raw as T;\n try {\n return JSON.parse(raw) as T;\n } catch (err) {\n console.warn(\n `durable store: failed to parse ${field} column, degrading to undefined: ${\n (err as Error).message\n }`,\n );\n return undefined;\n }\n}\n\n/**\n * TypeORM transformer for the free-form JSON-blob columns. Mirrors the built-in `simple-json`\n * serialization on WRITE (`JSON.stringify`, SQL NULL stays NULL) but uses {@link parseJsonColumn}\n * on READ so a single corrupt/truncated row degrades to `undefined` instead of throwing.\n */\nfunction jsonColumnTransformer(field: string): ValueTransformer {\n return {\n to: (value: unknown) => (value == null ? null : JSON.stringify(value)),\n from: (value: unknown) => parseJsonColumn(value, field),\n };\n}\n\n/**\n * How property names map to physical column names. The durable tables are adapter-agnostic: a run\n * written by one store adapter must be readable by another, so every adapter has to agree on the\n * physical column names. The default is `'snake_case'` (the canonical, matched by the MikroORM,\n * Prisma and Drizzle adapters). `'preserve'` keeps the camelCase property name verbatim (what the\n * old TypeORM/Prisma adapters produced before they were pinned). A function lets you supply any\n * custom mapping.\n *\n * The choice is pinned EXPLICITLY onto the entity schema rather than left to the host ORM's naming\n * strategy — depending on the host strategy is what silently diverged the adapters and broke a store\n * swap against an existing table.\n */\nexport type DurableColumnNaming = 'snake_case' | 'preserve' | ((property: string) => string);\n\nfunction snakeCase(property: string): string {\n return property.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);\n}\n\n/** Resolve a `DurableColumnNaming` to a `(property) => columnName` function. */\nexport function columnNamer(naming: DurableColumnNaming): (property: string) => string {\n if (naming === 'snake_case') return snakeCase;\n if (naming === 'preserve') return (property) => property;\n return naming;\n}\n\n// Plain classes (no decorators): the schema/column mapping lives on the EntitySchema built by\n// `durableEntities`, so the same class can be registered under different column names. The store\n// still references these classes for `getRepository`/`getMetadata`.\n\nexport class WorkflowRunEntity {\n id!: string;\n workflow!: string;\n workflowVersion!: string;\n status!: RunStatus;\n input?: unknown;\n output?: unknown;\n error?: unknown;\n wakeAt?: Date;\n lockedBy?: string | null;\n lockedUntil?: Date;\n awaitingDecisionTaskId?: string | null;\n recoveryAttempts?: number;\n tags?: string[] | null;\n searchAttributes?: Record<string, string | number | boolean> | null;\n priority?: number | null;\n namespace!: string;\n origin?: string | null;\n createdAt!: Date;\n updatedAt!: Date;\n}\n\nexport class StepCheckpointEntity {\n runId!: string;\n seq!: number;\n name!: string;\n kind!: StepKind;\n stepId!: string;\n status!: 'pending' | 'running' | 'completed' | 'failed';\n input?: unknown;\n output?: unknown;\n error?: unknown;\n events?: unknown;\n attempts!: number;\n workerGroup?: string | null;\n parallelGroup?: string | null;\n wakeAt?: Date;\n enqueuedAt?: Date;\n startedAt!: Date;\n finishedAt!: Date;\n}\n\n/**\n * Normalized side-table for search attributes: one row per (run, key), so range/equality predicates\n * push DOWN into SQL (an EXISTS join indexed on `(key, numValue)` / `(key, strValue)`) instead of a\n * coarse scan + in-process filter. Maintained on every `createRun`/`updateRun`. Numbers land in\n * `numValue`, strings/booleans in `strValue` (booleans as `\"true\"`/`\"false\"`); see `normalizeAttributeRows`.\n */\nexport class RunAttributeEntity {\n runId!: string;\n key!: string;\n strValue?: string | null;\n numValue?: number | null;\n}\n\nexport class SignalWaiterEntity {\n token!: string;\n runId!: string;\n seq!: number;\n parallelGroup?: string | null;\n}\n\nexport class BufferedSignalEntity {\n id!: number;\n token!: string;\n payload?: unknown;\n}\n\n/** A published event that matched no live waiter (see `engine.publishEvent`'s buffering). Keyed by a\n * caller-minted `id` (a uuid, not autoincrement — `removeBufferedEvent` targets it directly), not by\n * `runId`: events are name-based pub/sub, not tied to any one run. */\nexport class BufferedEventEntity {\n id!: string;\n name!: string;\n payload?: unknown;\n publishedAt!: Date;\n}\n\n/**\n * Build the durable TypeORM entity schemas with column names pinned per `naming` (default\n * `'snake_case'`). Register the result in your `DataSource`/`TypeOrmModule.forFeature`. The JSON-blob\n * columns keep the `jsonColumnTransformer` (corruption-tolerant read), the primary keys / auto-\n * increment / nullability are preserved, and the `id` of `durable_buffered_signals` stays a driver-\n * native auto-increment column.\n *\n * ```ts\n * entities: durableEntities({ naming: 'snake_case' })\n * ```\n */\nexport function durableEntities(options: { naming?: DurableColumnNaming } = {}): EntitySchema[] {\n const col = columnNamer(options.naming ?? 'snake_case');\n\n const workflowRuns = new EntitySchema<WorkflowRunEntity>({\n name: 'WorkflowRunEntity',\n target: WorkflowRunEntity,\n tableName: 'durable_workflow_runs',\n columns: {\n id: { type: 'text', primary: true, name: col('id') },\n workflow: { type: 'text', name: col('workflow') },\n workflowVersion: { type: 'text', name: col('workflowVersion') },\n status: { type: 'text', name: col('status') },\n input: {\n type: 'text',\n nullable: true,\n name: col('input'),\n transformer: jsonColumnTransformer('runs.input'),\n },\n output: {\n type: 'text',\n nullable: true,\n name: col('output'),\n transformer: jsonColumnTransformer('runs.output'),\n },\n error: {\n type: 'text',\n nullable: true,\n name: col('error'),\n transformer: jsonColumnTransformer('runs.error'),\n },\n wakeAt: { type: Date, nullable: true, name: col('wakeAt') },\n lockedBy: { type: 'text', nullable: true, name: col('lockedBy') },\n lockedUntil: { type: Date, nullable: true, name: col('lockedUntil') },\n // REMOTE turn the engine suspended on awaiting a decision; matched by completeRemoteDecision so\n // only the currently-awaited turn's decision is applied. Nullable: cleared when a decision lands.\n awaitingDecisionTaskId: {\n type: 'text',\n nullable: true,\n name: col('awaitingDecisionTaskId'),\n },\n recoveryAttempts: { type: 'integer', nullable: true, name: col('recoveryAttempts') },\n tags: {\n type: 'text',\n nullable: true,\n name: col('tags'),\n transformer: jsonColumnTransformer('runs.tags'),\n },\n searchAttributes: {\n type: 'text',\n nullable: true,\n name: col('searchAttributes'),\n transformer: jsonColumnTransformer('runs.searchAttributes'),\n },\n priority: { type: 'integer', nullable: true, name: col('priority') },\n // The worker-pool partition that owns the run. This is the tenant isolation boundary, not a\n // label: a worker only picks up (`listPendingRuns`), recovers (`listIncompleteRuns`), resumes\n // timers for (`listDueTimers`) and times out (`listRuns` with `namespace`) runs in its own\n // namespace, so an unfiltered predicate here hands one tenant's runs to another tenant's worker.\n //\n // NOT NULL DEFAULT `'default'`, deliberately unlike `origin` below. A run written before this\n // column existed DID execute in a namespace — the unscoped one — so `'default'` states a fact\n // rather than guesses one, and the DDL default (see the `additive` map in ./schema) back-fills\n // every pre-existing row with it. That back-fill is what makes the plain-equality predicates\n // safe: a NULL here would match no namespace at all, so a worker asking for `'default'` would\n // silently skip every run that predates the column.\n namespace: { type: 'text', name: col('namespace'), default: 'default' },\n // Which library/module registered the workflow this run belongs to (e.g.\n // `@dudousxd/nestjs-catalog-pipeline`), derived at registration time — never caller input.\n // Nullable with NO default: an origin cannot be reconstructed for a row written before this\n // column existed, so it stays NULL and reads back as `undefined` = \"unknown\". Defaulting it to\n // a real-looking string would be indistinguishable from a genuine registration in the\n // dashboard's facet. `ensureTypeOrmDurableSchema` back-fills the COLUMN onto pre-existing\n // tables (see the `additive` map in ./schema), never its value.\n origin: { type: 'text', nullable: true, name: col('origin') },\n createdAt: { type: Date, name: col('createdAt') },\n updatedAt: { type: Date, name: col('updatedAt') },\n },\n });\n\n const stepCheckpoints = new EntitySchema<StepCheckpointEntity>({\n name: 'StepCheckpointEntity',\n target: StepCheckpointEntity,\n tableName: 'durable_step_checkpoints',\n columns: {\n runId: { type: 'text', primary: true, name: col('runId') },\n seq: { type: 'integer', primary: true, name: col('seq') },\n name: { type: 'text', name: col('name') },\n kind: { type: 'text', name: col('kind') },\n stepId: { type: 'text', name: col('stepId') },\n status: { type: 'text', name: col('status') },\n input: {\n type: 'text',\n nullable: true,\n name: col('input'),\n transformer: jsonColumnTransformer('checkpoints.input'),\n },\n output: {\n type: 'text',\n nullable: true,\n name: col('output'),\n transformer: jsonColumnTransformer('checkpoints.output'),\n },\n error: {\n type: 'text',\n nullable: true,\n name: col('error'),\n transformer: jsonColumnTransformer('checkpoints.error'),\n },\n events: {\n type: 'text',\n nullable: true,\n name: col('events'),\n transformer: jsonColumnTransformer('checkpoints.events'),\n },\n attempts: { type: 'integer', name: col('attempts') },\n workerGroup: { type: 'text', nullable: true, name: col('workerGroup') },\n // A ctx.gather/ctx.all fan tags every sibling step with the same group so the dashboard renders\n // them as one parallel group; the core engine sets it (incl. from a remote worker's recordStep).\n parallelGroup: { type: 'text', nullable: true, name: col('parallelGroup') },\n wakeAt: { type: Date, nullable: true, name: col('wakeAt') },\n enqueuedAt: { type: Date, nullable: true, name: col('enqueuedAt') },\n startedAt: { type: Date, name: col('startedAt') },\n finishedAt: { type: Date, name: col('finishedAt') },\n },\n });\n\n const runAttributes = new EntitySchema<RunAttributeEntity>({\n name: 'RunAttributeEntity',\n target: RunAttributeEntity,\n tableName: 'durable_run_attributes',\n columns: {\n runId: { type: 'text', primary: true, name: col('runId') },\n key: { type: 'text', primary: true, name: col('key') },\n strValue: { type: 'text', nullable: true, name: col('strValue') },\n // `float`/`double` portable across SQLite/MySQL/Postgres for numeric range scans.\n numValue: { type: 'float', nullable: true, name: col('numValue') },\n },\n });\n\n const signalWaiters = new EntitySchema<SignalWaiterEntity>({\n name: 'SignalWaiterEntity',\n target: SignalWaiterEntity,\n tableName: 'durable_signal_waiters',\n columns: {\n token: { type: 'text', primary: true, name: col('token') },\n runId: { type: 'text', name: col('runId') },\n seq: { type: 'integer', name: col('seq') },\n // A ctx.gather_children/ctx.all child fan-out tags every awaited child with the same group; the\n // engine threads it onto the waiter so the resolving `signal:child:` checkpoint carries it and the\n // dashboard renders the fan as one parallel group. Nullable: only fan-out child waiters carry it.\n parallelGroup: { type: 'text', nullable: true, name: col('parallelGroup') },\n },\n });\n\n const bufferedSignals = new EntitySchema<BufferedSignalEntity>({\n name: 'BufferedSignalEntity',\n target: BufferedSignalEntity,\n tableName: 'durable_buffered_signals',\n columns: {\n // Auto-increment PK for FIFO ordering. Left as TypeORM's default increment generation so it\n // maps to the driver-native auto-increment column (INTEGER on SQLite, BIGINT/SERIAL elsewhere).\n id: { type: Number, primary: true, generated: 'increment', name: col('id') },\n token: { type: 'text', name: col('token') },\n payload: {\n type: 'text',\n nullable: true,\n name: col('payload'),\n transformer: jsonColumnTransformer('buffered.payload'),\n },\n },\n });\n\n const bufferedEvents = new EntitySchema<BufferedEventEntity>({\n name: 'BufferedEventEntity',\n target: BufferedEventEntity,\n tableName: 'durable_buffered_events',\n // No `indices` here (unlike MikroORM's EntitySchema, which does declare one): this store manages\n // its DDL — including the `(name, publishedAt)` index — via raw SQL in `schema.ts`'s\n // `ensureTypeOrmDurableSchema`, the same as every other durable_* table's indexes.\n columns: {\n // Caller-minted uuid (engine.publishEvent), not autoincrement — removeBufferedEvent targets it\n // directly and needs to be handed the SAME id it was buffered with.\n id: { type: 'text', primary: true, name: col('id') },\n name: { type: 'text', name: col('name') },\n payload: {\n type: 'text',\n nullable: true,\n name: col('payload'),\n transformer: jsonColumnTransformer('buffered.eventPayload'),\n },\n publishedAt: { type: Date, name: col('publishedAt') },\n },\n });\n\n return [\n workflowRuns,\n stepCheckpoints,\n runAttributes,\n signalWaiters,\n bufferedSignals,\n bufferedEvents,\n ];\n}\n\n/** Durable entity schemas with the canonical `'snake_case'` column names. */\nexport const ENTITIES = durableEntities();\n","import type { DataSource } from 'typeorm';\nimport {\n BufferedEventEntity,\n BufferedSignalEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n StepCheckpointEntity,\n WorkflowRunEntity,\n} from './entities';\n\n/** The JSON-blob columns per table (keyed by table name) that hold free-form payloads and so must\n * be the unbounded text type — `longtext` on MySQL, `text` elsewhere. Keyed by entity PROPERTY name;\n * the physical column is resolved from the DataSource metadata so it tracks the configured naming. */\nexport const JSON_BLOB_COLUMNS: Record<string, string[]> = {\n durable_workflow_runs: ['input', 'output', 'error', 'tags', 'searchAttributes'],\n durable_step_checkpoints: ['input', 'output', 'error', 'events'],\n // NOTE: durable_buffered_signals/durable_buffered_events intentionally omitted here, same as the\n // existing buffered-signals table — their `payload` column is created with the widened `txt` type\n // (see `${bufCol('payload')} ${txt}` / the new table's `${bevCol('payload')} ${txt}` below) directly\n // at CREATE TABLE time on a fresh install, so there's no pre-existing narrower column to widen.\n};\n\n/** Each durable table → its backing entity class, so a column resolver can look up the physical\n * column for any (table, property) from the DataSource metadata (which reflects the configured\n * `DurableColumnNaming`). Keeps the raw DDL/SQL in lock-step with the entity column mapping. */\nconst TABLE_TO_ENTITY = {\n durable_workflow_runs: WorkflowRunEntity,\n durable_step_checkpoints: StepCheckpointEntity,\n durable_run_attributes: RunAttributeEntity,\n durable_signal_waiters: SignalWaiterEntity,\n durable_buffered_signals: BufferedSignalEntity,\n durable_buffered_events: BufferedEventEntity,\n} as const;\n\n/**\n * Tables this store creates and manages at boot (autoSchema, see {@link ensureTypeOrmDurableSchema}).\n * Feed to your ORM's migration differ exclude/skipTables so it never tries to drop them.\n *\n * ```ts\n * // MikroORM-flavoured example (TypeORM has no built-in equivalent option); adapt to whichever\n * // migration tool generates your diffs — e.g. exclude these names from a typeorm-generated\n * // migration, or filter them out of `SELECT table_name FROM information_schema.tables` before\n * // diffing against your own entities.\n * const skipTables = new Set(durableManagedTables());\n * ```\n *\n * Derived from the same {@link TABLE_TO_ENTITY} map the raw-SQL heal keys its column resolution off\n * — one list, so a consumer's denylist can never drift from what this store actually owns.\n */\nexport function durableManagedTables(): string[] {\n return Object.keys(TABLE_TO_ENTITY);\n}\n\n/**\n * Resolve `(table, property) => physical column name` from the DataSource's entity metadata. The\n * column names are NOT hardcoded here: they come from whatever the registered `durableEntities`\n * mapped (canonical `snake_case` by default, `'preserve'` for the legacy camelCase, or a custom\n * mapping), so the raw `CREATE TABLE`/index/EXISTS SQL always matches the entities and can never\n * silently diverge.\n */\nexport function durableColumnResolver(\n dataSource: DataSource,\n): (table: string, property: string) => string {\n return (table, property) => {\n const entity = TABLE_TO_ENTITY[table as keyof typeof TABLE_TO_ENTITY];\n if (!entity) throw new Error(`durable store: unknown table \"${table}\"`);\n const meta = dataSource.getMetadata(entity);\n const column = meta.findColumnWithPropertyName(property);\n if (!column) {\n throw new Error(`durable store: no column for ${table}.${property} in entity metadata`);\n }\n return column.databaseName;\n };\n}\n\n/** The SQL type for free-form JSON-blob columns. MySQL `text` caps at 64KB and silently truncates,\n * so use `longtext` (4GB) there; Postgres/SQLite `text` is already unbounded. */\nexport function jsonBlobColumnType(isMysql: boolean): 'longtext' | 'text' {\n return isMysql ? 'longtext' : 'text';\n}\n\n/** Idempotent `MODIFY COLUMN ... longtext` statements that widen pre-existing MySQL `text` JSON-blob\n * columns. Returns `[]` on non-MySQL dialects (their `text` is already unbounded — nothing to do).\n * `quote` quotes an identifier per the active driver; `col` resolves a property to its physical\n * column name so the widen tracks the configured naming. */\nexport function buildWidenStatements(\n isMysql: boolean,\n quote: (id: string) => string,\n col: (table: string, property: string) => string,\n): string[] {\n if (!isMysql) return [];\n const out: string[] = [];\n for (const [table, props] of Object.entries(JSON_BLOB_COLUMNS)) {\n for (const prop of props) {\n out.push(`ALTER TABLE ${quote(table)} MODIFY COLUMN ${quote(col(table, prop))} longtext`);\n }\n }\n return out;\n}\n\n/**\n * Idempotently create the durable tables. Safe to run on every boot (auto-schema) and the\n * exact function to call from your own TypeORM migration when you disable auto-schema:\n *\n * ```ts\n * export class AddDurableTables implements MigrationInterface {\n * async up(q: QueryRunner) { await ensureTypeOrmDurableSchema(q.connection); }\n * }\n * ```\n *\n * Dialect-aware (MySQL / MariaDB / Postgres / SQLite): identifiers are quoted per driver, keyed\n * string columns are `varchar` (MySQL can't key a `text` column), and the index is best-effort.\n * Only ever adds the three durable tables — it never touches your other tables.\n */\nexport async function ensureTypeOrmDurableSchema(dataSource: DataSource): Promise<void> {\n const q = (id: string) => dataSource.driver.escape(id);\n // Physical column names come from the entity metadata (canonical snake_case by default), so this\n // raw DDL always matches the registered `durableEntities` instead of hardcoding camelCase.\n const resolve = durableColumnResolver(dataSource);\n const type = String(dataSource.options.type);\n const isPg = type === 'postgres' || type === 'aurora-postgres';\n const isMysql = type === 'mysql' || type === 'mariadb' || type === 'aurora-mysql';\n const isSqlite = type === 'sqlite' || type === 'better-sqlite3' || type === 'expo';\n\n // Keyed/short strings must be varchar on MySQL (a `text` PK/index needs a key length); `text`\n // for the free-form JSON payloads. Dates use the dialect's native timestamp type.\n const str = 'varchar(191)';\n // Free-form JSON payloads (`input`/`output`/`error`/`events`/`tags`/`searchAttributes`). MySQL's\n // `text` caps at 64KB and *silently truncates* — a large fan-out step's `events` then fails to\n // parse on read (\"Unterminated string in JSON\"). Use `longtext` (4GB) on MySQL; Postgres `text`\n // is already unbounded and SQLite `text` has no length limit.\n const txt = jsonBlobColumnType(isMysql);\n const int = isMysql ? 'int' : 'integer';\n const ts = isPg ? 'timestamptz' : 'datetime';\n // The tenant partition every poll predicate filters on. NOT NULL with a literal default so that\n // adding it to a table that predates it back-fills each existing row with `'default'` — the\n // namespace those runs actually executed in — instead of leaving NULLs that would match no\n // namespace and so be invisible to every worker. Postgres (11+) and SQLite fill the existing rows\n // from the default without rewriting the table; MySQL 8.0.12+ does it instantly, older MySQL\n // rewrites the table once, so a very large `durable_workflow_runs` there should take the ALTER in a\n // maintenance window rather than at boot.\n const nsCol = `${str} NOT NULL DEFAULT 'default'`;\n\n const runs = q('durable_workflow_runs');\n const checkpoints = q('durable_step_checkpoints');\n const runAttributes = q('durable_run_attributes');\n const waiters = q('durable_signal_waiters');\n const buffered = q('durable_buffered_signals');\n const bufferedEvents = q('durable_buffered_events');\n // Per-table quoted-column helpers: resolve an entity property to its physical column then quote it.\n const runsCol = (property: string) => q(resolve('durable_workflow_runs', property));\n const cpCol = (property: string) => q(resolve('durable_step_checkpoints', property));\n const attrCol = (property: string) => q(resolve('durable_run_attributes', property));\n const waiterCol = (property: string) => q(resolve('durable_signal_waiters', property));\n const bufCol = (property: string) => q(resolve('durable_buffered_signals', property));\n const bevCol = (property: string) => q(resolve('durable_buffered_events', property));\n // Numeric side-table column for attribute range scans. `double precision` on Postgres, `double` on\n // MySQL, `real` on SQLite (all hold JS numbers without precision loss for the typical attribute).\n const num = isPg ? 'double precision' : isMysql ? 'double' : 'real';\n\n // Auto-increment PK syntax differs per dialect: SQLite wants `INTEGER PRIMARY KEY AUTOINCREMENT`,\n // MySQL `BIGINT AUTO_INCREMENT PRIMARY KEY`, Postgres `BIGSERIAL PRIMARY KEY`.\n const bufferedId = isSqlite\n ? `${bufCol('id')} integer PRIMARY KEY AUTOINCREMENT`\n : isMysql\n ? `${bufCol('id')} bigint NOT NULL AUTO_INCREMENT PRIMARY KEY`\n : isPg\n ? `${bufCol('id')} bigserial PRIMARY KEY`\n : `${bufCol('id')} bigint NOT NULL AUTO_INCREMENT PRIMARY KEY`;\n\n const tables = [\n `CREATE TABLE IF NOT EXISTS ${runs} (\n ${runsCol('id')} ${str} PRIMARY KEY,\n ${runsCol('workflow')} ${str} NOT NULL,\n ${runsCol('workflowVersion')} ${str} NOT NULL,\n ${runsCol('status')} ${str} NOT NULL,\n ${runsCol('input')} ${txt}, ${runsCol('output')} ${txt}, ${runsCol('error')} ${txt},\n ${runsCol('wakeAt')} ${ts}, ${runsCol('lockedBy')} ${str}, ${runsCol('lockedUntil')} ${ts},\n ${runsCol('awaitingDecisionTaskId')} ${str},\n ${runsCol('recoveryAttempts')} ${int}, ${runsCol('tags')} ${txt}, ${runsCol('searchAttributes')} ${txt},\n ${runsCol('priority')} ${int}, ${runsCol('namespace')} ${nsCol}, ${runsCol('origin')} ${str},\n ${runsCol('createdAt')} ${ts} NOT NULL, ${runsCol('updatedAt')} ${ts} NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS ${checkpoints} (\n ${cpCol('runId')} ${str} NOT NULL, ${cpCol('seq')} ${int} NOT NULL,\n ${cpCol('name')} ${str} NOT NULL, ${cpCol('kind')} ${str} NOT NULL, ${cpCol('stepId')} ${str} NOT NULL,\n ${cpCol('status')} ${str} NOT NULL, ${cpCol('input')} ${txt}, ${cpCol('output')} ${txt}, ${cpCol('error')} ${txt}, ${cpCol('events')} ${txt},\n ${cpCol('attempts')} ${int} NOT NULL, ${cpCol('workerGroup')} ${str}, ${cpCol('parallelGroup')} ${str},\n ${cpCol('wakeAt')} ${ts}, ${cpCol('enqueuedAt')} ${ts},\n ${cpCol('startedAt')} ${ts} NOT NULL, ${cpCol('finishedAt')} ${ts} NOT NULL,\n PRIMARY KEY (${cpCol('runId')}, ${cpCol('seq')})\n )`,\n // Normalized search-attribute side-table: one row per (run, key) so attribute predicates push\n // DOWN into SQL via an EXISTS join (indexed below). `key` is keyed → must be varchar on MySQL.\n `CREATE TABLE IF NOT EXISTS ${runAttributes} (\n ${attrCol('runId')} ${str} NOT NULL, ${attrCol('key')} ${str} NOT NULL,\n ${attrCol('strValue')} ${str}, ${attrCol('numValue')} ${num},\n PRIMARY KEY (${attrCol('runId')}, ${attrCol('key')})\n )`,\n `CREATE TABLE IF NOT EXISTS ${waiters} (\n ${waiterCol('token')} ${str} PRIMARY KEY, ${waiterCol('runId')} ${str} NOT NULL, ${waiterCol('seq')} ${int} NOT NULL,\n ${waiterCol('parallelGroup')} ${str}\n )`,\n `CREATE TABLE IF NOT EXISTS ${buffered} (\n ${bufferedId}, ${bufCol('token')} ${str} NOT NULL, ${bufCol('payload')} ${txt}\n )`,\n // Caller-minted uuid PK (engine.publishEvent), not auto-increment — unlike durable_buffered_signals\n // above, removeBufferedEvent needs to target the EXACT id it was buffered with.\n `CREATE TABLE IF NOT EXISTS ${bufferedEvents} (\n ${bevCol('id')} ${str} PRIMARY KEY, ${bevCol('name')} ${str} NOT NULL,\n ${bevCol('payload')} ${txt}, ${bevCol('publishedAt')} ${ts} NOT NULL\n )`,\n ];\n\n // Additive nullable columns gained across versions (e.g. `input`, `events`, `enqueuedAt`). On a\n // table that predates them, `CREATE TABLE IF NOT EXISTS` above is a no-op, so back-fill the ones\n // that are actually missing — the auto-schema self-heals instead of needing a manual migration.\n // We check the live columns first (rather than ALTER-and-ignore) so a *real* ALTER failure\n // surfaces instead of being swallowed as a presumed \"column already exists\".\n // Keyed by entity PROPERTY name; the physical column is resolved per-table so the ADD COLUMN\n // tracks the configured naming.\n const additive: Record<string, Array<[string, string]>> = {\n durable_workflow_runs: [\n ['input', txt],\n ['output', txt],\n ['error', txt],\n ['awaitingDecisionTaskId', str],\n ['recoveryAttempts', int],\n ['tags', txt],\n ['searchAttributes', txt],\n ['priority', int],\n // Back-filled WITH a value, unlike `origin` below: the DDL default writes `'default'` onto\n // every pre-existing row, because a run created before this column existed really did execute\n // in the unscoped `'default'` namespace. Leaving those rows NULL would make them invisible to\n // the worker that owns them — the list predicates are plain equality, so `NULL <> 'default'`.\n ['namespace', nsCol],\n // Nullable and NOT back-filled with a value: every row that predates the column keeps a NULL\n // origin, which the store reads as `undefined` = \"unknown origin\". There is no honest value to\n // back-fill — the origin is derived from the registration that created the run, which is long\n // gone by the time this ALTER runs.\n ['origin', str],\n ],\n durable_step_checkpoints: [\n ['input', txt],\n ['output', txt],\n ['error', txt],\n ['events', txt],\n ['workerGroup', str],\n ['parallelGroup', str],\n ['enqueuedAt', ts],\n ],\n // Back-fill the child-await fan group onto signal-waiter tables that predate it (a remote\n // `gather_children` fan-out threads its group here so the resolved `signal:child:` checkpoint carries it).\n durable_signal_waiters: [['parallelGroup', str]],\n };\n\n const runner = dataSource.createQueryRunner();\n try {\n for (const sql of tables) await runner.query(sql);\n for (const [table, props] of Object.entries(additive)) {\n const have = await existingColumns(runner, table, { isSqlite, isMysql });\n for (const [property, colType] of props) {\n const column = resolve(table, property);\n if (!have.has(column)) {\n await runner.query(`ALTER TABLE ${q(table)} ADD COLUMN ${q(column)} ${colType}`);\n }\n }\n }\n // Widen pre-existing MySQL `text` JSON-blob columns to `longtext`. A table created before this\n // fix has these as `text` (64KB) and silently truncates large `events`/`output` payloads. MODIFY\n // to `longtext` is idempotent (no-op if already longtext), so it's safe to run on every boot.\n // MySQL-only: Postgres/SQLite `text` is already unbounded, so there's nothing to widen.\n for (const sql of buildWidenStatements(isMysql, q, resolve)) {\n try {\n await runner.query(sql);\n } catch {\n /* column already longtext, or table/column not present on this deploy */\n }\n }\n // MySQL has no `CREATE INDEX IF NOT EXISTS`; create each best-effort and ignore \"already exists\".\n // - status/wakeAt: the timer poller (listDueTimers) and recovery (listIncompleteRuns) scans.\n // - workflow/status: the dashboard's listRuns filters. (Checkpoints are keyed by the PK prefix\n // `(runId, seq)`, so listCheckpoints/getEvent already hit an index — no extra one needed.)\n const indexes: Array<[string, string]> = [\n ['durable_runs_status_idx', `${runs} (${runsCol('status')}, ${runsCol('wakeAt')})`],\n [\n 'durable_runs_workflow_status_idx',\n `${runs} (${runsCol('workflow')}, ${runsCol('status')})`,\n ],\n // namespace/status/createdAt: every poll tick of a namespaced worker filters on `namespace`\n // ANDed with `status` (and `listPendingRuns` orders by `createdAt`), so without this the two\n // indexes above degrade to a scan of the WHOLE table — including every other tenant's rows —\n // on each tick. Created best-effort on every boot like the others, so a deployment whose table\n // already exists picks it up as soon as it runs this version.\n [\n 'durable_runs_namespace_status_idx',\n `${runs} (${runsCol('namespace')}, ${runsCol('status')}, ${runsCol('createdAt')})`,\n ],\n // buffered signals are taken FIFO per token (smallest id) — index the token for the scan.\n ['durable_buffered_signals_token_idx', `${buffered} (${bufCol('token')})`],\n // buffered events are scanned oldest-first per name — one composite index serves both.\n [\n 'durable_buffered_events_name_published_at_idx',\n `${bufferedEvents} (${bevCol('name')}, ${bevCol('publishedAt')})`,\n ],\n // Search-attribute pushdown: equality + range predicates probe by (key, value). Two composite\n // indexes — one per typed column — so a numeric range or a string equality is an index scan.\n [\n 'durable_run_attributes_num_idx',\n `${runAttributes} (${attrCol('key')}, ${attrCol('numValue')})`,\n ],\n [\n 'durable_run_attributes_str_idx',\n `${runAttributes} (${attrCol('key')}, ${attrCol('strValue')})`,\n ],\n ];\n for (const [name, target] of indexes) {\n try {\n await runner.query(`CREATE INDEX ${q(name)} ON ${target}`);\n } catch {\n /* index already exists */\n }\n }\n } finally {\n await runner.release();\n }\n}\n\n/** The columns that currently exist on `table`, so the schema can add only the missing ones\n * (instead of ALTER-and-swallow, which would also hide a genuine ALTER failure). */\nasync function existingColumns(\n runner: { query: (sql: string, params?: unknown[]) => Promise<unknown> },\n table: string,\n d: { isSqlite: boolean; isMysql: boolean },\n): Promise<Set<string>> {\n if (d.isSqlite) {\n const rows = (await runner.query(`PRAGMA table_info(\"${table}\")`)) as Array<{ name: string }>;\n return new Set(rows.map((r) => r.name));\n }\n // Postgres + MySQL both expose information_schema; scope to the connection's own schema/db.\n // Bind-param placeholder differs: Postgres uses `$1`, MySQL uses `?` (TypeORM only rewrites `?`\n // inside the query builder, not for these raw `runner.query` calls), so pick per dialect.\n const scope = d.isMysql ? 'TABLE_SCHEMA = DATABASE()' : 'table_schema = current_schema()';\n const placeholder = d.isMysql ? '?' : '$1';\n const rows = (await runner.query(\n `SELECT column_name AS name FROM information_schema.columns WHERE table_name = ${placeholder} AND ${scope}`,\n [table],\n )) as Array<{ name?: string; COLUMN_NAME?: string }>;\n return new Set(rows.map((r) => (r.name ?? r.COLUMN_NAME) as string));\n}\n","import {\n type AttributeFilter,\n type RunQuery,\n type SignalWaiter,\n type StateStore,\n type StepCheckpoint,\n type StepError,\n type StepEvent,\n type WorkflowRun,\n attributeColumnFor,\n attributeOperand,\n normalizeAttributeRows,\n sqlComparator,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Brackets,\n type DataSource,\n type EntityManager,\n In,\n IsNull,\n LessThanOrEqual,\n Like,\n type SelectQueryBuilder,\n} from 'typeorm';\nimport type { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';\nimport {\n BufferedEventEntity,\n BufferedSignalEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n StepCheckpointEntity,\n WorkflowRunEntity,\n} from './entities';\nimport { durableColumnResolver, ensureTypeOrmDurableSchema } from './schema';\n\n/**\n * TypeORM-backed `StateStore`. Works on any TypeORM driver — Postgres, MySQL, SQLite (tested);\n * timestamps use native datetime columns and `wakeAt` is stored as a datetime too.\n */\nexport class TypeOrmStateStore implements StateStore {\n constructor(private readonly dataSource: DataSource) {}\n\n async ensureSchema(): Promise<void> {\n await ensureTypeOrmDurableSchema(this.dataSource);\n }\n\n private runs() {\n return this.dataSource.getRepository(WorkflowRunEntity);\n }\n private checkpoints() {\n return this.dataSource.getRepository(StepCheckpointEntity);\n }\n private waiters() {\n return this.dataSource.getRepository(SignalWaiterEntity);\n }\n private buffered() {\n return this.dataSource.getRepository(BufferedSignalEntity);\n }\n private bufferedEvents() {\n return this.dataSource.getRepository(BufferedEventEntity);\n }\n private attributes() {\n return this.dataSource.getRepository(RunAttributeEntity);\n }\n\n /** Rewrite a run's normalized attribute rows: delete the old set, insert the current one. Mirrors\n * the in-memory store's reindex so the side-table always reflects the run's live searchAttributes. */\n private async reindexAttributes(\n runId: string,\n attributes: WorkflowRun['searchAttributes'],\n em?: EntityManager,\n ): Promise<void> {\n const repo = em ? em.getRepository(RunAttributeEntity) : this.attributes();\n await repo.delete({ runId });\n const rows = normalizeAttributeRows(runId, attributes);\n if (rows.length) await repo.insert(rows);\n }\n\n async createRun(run: WorkflowRun): Promise<void> {\n await this.runs().save(toRunEntity(run));\n await this.reindexAttributes(run.id, run.searchAttributes);\n }\n\n async updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n // Single UPDATE (no pre-SELECT + save round-trips): map only the patched fields. The query\n // builder still applies the entities' JSON column transformers to the `set` values (as in\n // listRuns/tryLockRun). Preserve the not-found throw any caller may rely on.\n const update: Record<string, unknown> = {};\n if ('workflow' in patch) update.workflow = patch.workflow;\n if ('workflowVersion' in patch) update.workflowVersion = patch.workflowVersion;\n if ('status' in patch) update.status = patch.status;\n if ('input' in patch) update.input = patch.input ?? null;\n if ('output' in patch) update.output = patch.output ?? null;\n if ('error' in patch) update.error = patch.error ?? null;\n if ('wakeAt' in patch) update.wakeAt = patch.wakeAt == null ? null : new Date(patch.wakeAt);\n if ('lockedBy' in patch) update.lockedBy = patch.lockedBy ?? null;\n if ('lockedUntil' in patch)\n update.lockedUntil = patch.lockedUntil == null ? null : new Date(patch.lockedUntil);\n if ('awaitingDecisionTaskId' in patch)\n update.awaitingDecisionTaskId = patch.awaitingDecisionTaskId ?? null;\n if ('recoveryAttempts' in patch) update.recoveryAttempts = patch.recoveryAttempts;\n if ('tags' in patch) update.tags = patch.tags ?? null;\n if ('searchAttributes' in patch) update.searchAttributes = patch.searchAttributes ?? null;\n if ('priority' in patch) update.priority = patch.priority ?? null;\n // A patch that clears the namespace still lands on `'default'`, never NULL — the column is the\n // isolation predicate, and a NULL there would match no worker's namespace at all.\n if ('namespace' in patch) update.namespace = patch.namespace ?? 'default';\n if ('origin' in patch) update.origin = patch.origin ?? null;\n if ('createdAt' in patch) update.createdAt = patch.createdAt;\n if ('updatedAt' in patch) update.updatedAt = patch.updatedAt;\n const result = await this.runs()\n .createQueryBuilder()\n .update()\n .set(update)\n .where({ id: runId })\n .execute();\n if (!result.affected) throw new Error(`run ${runId} not found`);\n // Keep the side-table in step with the run's attributes whenever they're patched.\n if ('searchAttributes' in patch) await this.reindexAttributes(runId, patch.searchAttributes);\n }\n\n async getRun(runId: string): Promise<WorkflowRun | null> {\n const e = await this.runs().findOneBy({ id: runId });\n return e ? fromRunEntity(e) : null;\n }\n\n async deleteRun(runId: string): Promise<void> {\n // Child rows first, then the run — checkpoints, signal waiters, attribute rows.\n await this.checkpoints().delete({ runId });\n await this.waiters().delete({ runId });\n await this.attributes().delete({ runId });\n await this.runs().delete({ id: runId });\n }\n\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n const e = await this.checkpoints().findOneBy({ runId, seq });\n return e ? fromCheckpointEntity(e) : null;\n }\n\n async saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n // upsert = INSERT ... ON CONFLICT DO UPDATE on the (runId, seq) key — drops the pre-SELECT that\n // `.save()` does on each write. JSON column transformers still apply for upsert.\n const entity = toCheckpointEntity(checkpoint) as QueryDeepPartialEntity<StepCheckpointEntity>;\n await this.checkpoints().upsert(entity, ['runId', 'seq']);\n }\n\n async transaction<T>(\n work: (tx: {\n raw: unknown;\n saveCheckpoint: (cp: StepCheckpoint) => Promise<void>;\n }) => Promise<T>,\n ): Promise<T> {\n return this.dataSource.transaction(async (em) =>\n work({\n raw: em,\n saveCheckpoint: async (cp) => {\n await em.getRepository(StepCheckpointEntity).save(toCheckpointEntity(cp));\n },\n }),\n );\n }\n\n /**\n * The three worker-poll predicates below (recover / pick up / resume timers) each AND in\n * `namespace` when one is given, and omit the predicate entirely when it is `undefined`. Omitting\n * is NOT the same as `namespace IS NULL`: `undefined` means \"no restriction\" — the operator /\n * control-plane view that legitimately sees every tenant — whereas a NULL-matching predicate would\n * hide every real run behind an empty result while looking correct in a single-tenant test.\n */\n async listIncompleteRuns(namespace?: string): Promise<WorkflowRun[]> {\n const rows = await this.runs().findBy({\n status: In(['running', 'cancelling']),\n ...(namespace !== undefined ? { namespace } : {}),\n });\n return rows.map(fromRunEntity);\n }\n\n async listPendingRuns(limit: number, namespace?: string): Promise<WorkflowRun[]> {\n const rows = await this.runs().find({\n where: { status: 'pending', ...(namespace !== undefined ? { namespace } : {}) },\n order: { createdAt: 'ASC' }, // FIFO dispatch\n take: limit,\n });\n return rows.map(fromRunEntity);\n }\n\n async listDueTimers(nowMs: number, namespace?: string): Promise<WorkflowRun[]> {\n const rows = await this.runs().findBy({\n status: 'suspended',\n wakeAt: LessThanOrEqual(new Date(nowMs)),\n ...(namespace !== undefined ? { namespace } : {}),\n });\n return rows.map(fromRunEntity);\n }\n\n async tryLockRun(\n runId: string,\n owner: string,\n leaseUntilMs: number,\n nowMs: number,\n ): Promise<boolean> {\n const result = await this.runs()\n .createQueryBuilder()\n .update()\n .set({ lockedBy: owner, lockedUntil: new Date(leaseUntilMs) })\n .where({ id: runId })\n .andWhere(\n new Brackets((qb) =>\n qb\n .where({ lockedUntil: IsNull() })\n .orWhere({ lockedUntil: LessThanOrEqual(new Date(nowMs)) }),\n ),\n )\n .execute();\n return result.affected === 1;\n }\n\n async releaseRunLock(runId: string): Promise<void> {\n await this.runs().update({ id: runId }, { lockedBy: null, lockedUntil: () => 'NULL' });\n }\n\n async renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n const result = await this.runs()\n .createQueryBuilder()\n .update()\n .set({ lockedUntil: new Date(leaseUntilMs) })\n .where({ id: runId, lockedBy: owner })\n .execute();\n return result.affected === 1;\n }\n\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n // `tags` carries a custom JSON transformer, and TypeORM applies a column transformer's `to()` to\n // FindOperator values too — so a `Like('%\"etl\"%')` in a plain `where` would be JSON-stringified\n // and corrupt the LIKE pattern. Use the query builder with a raw parameter to bypass that.\n const qb = this.runs().createQueryBuilder('r');\n if (query.workflow) qb.andWhere('r.workflow = :workflow', { workflow: query.workflow });\n // The tenant partition. This is not only a dashboard facet: the engine's execution-timeout sweep\n // finds its in-flight runs through `listRuns({ workflow, status, namespace })`, so without this\n // predicate a namespaced worker would cancel ANOTHER tenant's long-running runs. `undefined`\n // leaves the predicate off = every namespace (the operator view), exactly as in the list methods.\n if (query.namespace !== undefined)\n qb.andWhere('r.namespace = :namespace', { namespace: query.namespace });\n // Which library registered the workflow. Plain equality, so a run whose origin is NULL (created\n // before the column existed, or registered through a path the derivation could not classify)\n // matches NO origin value — it is never folded into a bucket to make the facet look complete.\n // Unknown-origin runs are reachable only with the filter OFF, so \"all origins\" must stay the\n // default view; a dashboard that filtered by default would make those runs look deleted.\n if (query.origin !== undefined) qb.andWhere('r.origin = :origin', { origin: query.origin });\n if (query.status) qb.andWhere('r.status = :status', { status: query.status });\n if (query.statuses)\n qb.andWhere(\n query.statuses.length ? 'r.status IN (:...statuses)' : '1 = 0',\n query.statuses.length ? { statuses: query.statuses } : {},\n );\n // `tags` is a JSON-text column; match the quoted token so `etl` doesn't match `etl-foo`. NOTE: a\n // leading-wildcard LIKE on JSON text is NOT index-friendly (no B-tree index can serve `%\"x\"%`), so\n // tag-filtered scans (e.g. singleton admission) are sequential over `durable_runs_workflow_status_idx`'s\n // result set. The `statuses`/`workflow` predicates above bound that scan; if tag scans ever dominate,\n // promote tags to a normalized join table or a JSON/GIN index — a schema change, intentionally not done here.\n if (query.tag) qb.andWhere('r.tags LIKE :tagPattern', { tagPattern: `%\"${query.tag}\"%` });\n // Typed/range attribute predicates push DOWN into SQL: each filter becomes an EXISTS against the\n // normalized `durable_run_attributes` side-table (indexed on (key, numValue)/(key, strValue)), so\n // the DB does the filtering AND the LIMIT/OFFSET — no full scan + in-process filter. ANDed: a run\n // must satisfy every filter, so one EXISTS per filter.\n if (query.attributes?.length) {\n query.attributes.forEach((f, i) => this.applyAttributeExists(qb, f, i));\n }\n qb.orderBy('r.createdAt', 'DESC'); // newest first — recent runs on top in the dashboard\n if (query.limit != null) qb.take(query.limit);\n if (query.offset != null) qb.skip(query.offset);\n const rows = await qb.getMany();\n return rows.map(fromRunEntity);\n }\n\n /** Add one attribute predicate to `qb` as an EXISTS subquery on the side-table. `i` namespaces the\n * bind params so multiple ANDed filters don't collide. */\n private applyAttributeExists(\n qb: SelectQueryBuilder<WorkflowRunEntity>,\n f: AttributeFilter,\n i: number,\n ): void {\n const valueProperty = attributeColumnFor(f); // 'numValue' | 'strValue' (entity property)\n const cmp = sqlComparator(f.op);\n const keyParam = `attrKey${i}`;\n const valParam = `attrVal${i}`;\n // Resolve the PHYSICAL column names from the entity metadata so this raw subquery tracks the\n // configured naming (canonical snake_case by default) instead of hardcoding camelCase — which\n // would break the EXISTS pushdown the moment the table is snake_case.\n const resolve = durableColumnResolver(this.dataSource);\n const q = this.idQuote();\n const wrap = (name: string) => `${q}${name}${q}`;\n const runIdCol = wrap(resolve('durable_run_attributes', 'runId'));\n const keyCol = wrap(resolve('durable_run_attributes', 'key'));\n const valueCol = wrap(resolve('durable_run_attributes', valueProperty));\n const runPkCol = wrap(resolve('durable_workflow_runs', 'id'));\n const table = wrap('durable_run_attributes');\n // `<>` (ne) must also exclude rows where the attribute is absent: the missing-key-never-matches\n // contract (see core matchesAttributes). EXISTS already requires the key row to be present, and a\n // row only exists when the value is non-null, so EXISTS(... <> ...) gives exactly ne-with-present.\n const a = `a${i}`;\n const sql = `EXISTS (SELECT 1 FROM ${table} ${a} WHERE ${a}.${runIdCol} = r.${runPkCol} AND ${a}.${keyCol} = :${keyParam} AND ${a}.${valueCol} ${cmp} :${valParam})`;\n qb.andWhere(sql, {\n [keyParam]: f.key,\n [valParam]: attributeOperand(f),\n });\n }\n\n /** The identifier quote char for the active driver (MySQL backtick, others double-quote). */\n private idQuote(): string {\n const type = String(this.dataSource.options.type);\n return type === 'mysql' || type === 'mariadb' || type === 'aurora-mysql' ? '`' : '\"';\n }\n\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n const rows = await this.checkpoints().find({ where: { runId }, order: { seq: 'ASC' } });\n return rows.map(fromCheckpointEntity);\n }\n\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n const e = await this.checkpoints().findOne({ where: { runId, name }, order: { seq: 'DESC' } });\n return e ? fromCheckpointEntity(e) : undefined;\n }\n\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n if (prefixes.length === 0) return [];\n const rows = await this.checkpoints().find({\n where: prefixes.map((p) => ({ runId, name: Like(`${p}%`) })),\n order: { seq: 'ASC' },\n });\n return rows.map(fromCheckpointEntity);\n }\n\n async putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n await this.waiters().save({\n token: waiter.token,\n runId: waiter.runId,\n seq: waiter.seq,\n parallelGroup: waiter.parallelGroup ?? null,\n });\n }\n\n async listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n const rows = await this.waiters().find({ where: { token: Like(`${prefix}%`) } });\n return rows.map((e) => ({\n token: e.token,\n runId: e.runId,\n seq: e.seq,\n parallelGroup: e.parallelGroup ?? undefined,\n }));\n }\n\n async takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n const e = await this.waiters().findOneBy({ token });\n if (!e) return null;\n const waiter: SignalWaiter = {\n token: e.token,\n runId: e.runId,\n seq: e.seq,\n parallelGroup: e.parallelGroup ?? undefined,\n };\n await this.waiters().delete({ token });\n return waiter;\n }\n\n async removeSignalWaiter(waiter: SignalWaiter): Promise<void> {\n // Exact-match delete (token AND runId AND seq) — a plain `delete({ token })` would remove\n // whatever row currently owns the token, even if a different run has since claimed it.\n await this.waiters().delete({ token: waiter.token, runId: waiter.runId, seq: waiter.seq });\n }\n\n async bufferSignal(token: string, payload: unknown): Promise<void> {\n await this.buffered().save({ token, payload: payload ?? null });\n }\n\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const e = await this.buffered().findOne({ where: { token }, order: { id: 'ASC' } });\n if (!e) return null;\n await this.buffered().delete({ id: e.id });\n return { payload: e.payload ?? undefined };\n }\n\n async bufferEvent(input: {\n name: string;\n payload: unknown;\n id: string;\n publishedAt: number;\n }): Promise<void> {\n await this.bufferedEvents().save({\n id: input.id,\n name: input.name,\n payload: input.payload ?? null,\n publishedAt: new Date(input.publishedAt),\n });\n }\n\n async listBufferedEvents(\n name: string,\n limit: number,\n ): Promise<Array<{ id: string; payload: unknown; publishedAt: number }>> {\n const rows = await this.bufferedEvents().find({\n where: { name },\n order: { publishedAt: 'ASC' }, // oldest first\n take: limit,\n });\n return rows.map((e) => ({\n id: e.id,\n payload: e.payload ?? undefined,\n publishedAt: e.publishedAt.getTime(),\n }));\n }\n\n async removeBufferedEvent(id: string): Promise<boolean> {\n const result = await this.bufferedEvents().delete({ id });\n return result.affected === 1;\n }\n}\n\nfunction toRunEntity(run: WorkflowRun): WorkflowRunEntity {\n return {\n id: run.id,\n workflow: run.workflow,\n workflowVersion: run.workflowVersion,\n status: run.status,\n input: run.input ?? null,\n output: run.output ?? null,\n error: run.error ?? null,\n ...(run.wakeAt == null ? {} : { wakeAt: new Date(run.wakeAt) }),\n lockedBy: run.lockedBy ?? null,\n ...(run.lockedUntil == null ? {} : { lockedUntil: new Date(run.lockedUntil) }),\n awaitingDecisionTaskId: run.awaitingDecisionTaskId ?? null,\n ...(run.recoveryAttempts === undefined ? {} : { recoveryAttempts: run.recoveryAttempts }),\n tags: run.tags ?? null,\n searchAttributes: run.searchAttributes ?? null,\n priority: run.priority ?? null,\n // An absent namespace is persisted as `'default'` (what the core `WorkflowRun.namespace` docblock\n // promises), so the column is always a value a worker can match on — the opposite of `origin`\n // below, where NULL is the only honest answer.\n namespace: run.namespace ?? 'default',\n // Absent origin stays SQL NULL — \"unknown\", never coerced into a real-looking library name.\n origin: run.origin ?? null,\n createdAt: run.createdAt,\n updatedAt: run.updatedAt,\n };\n}\n\nfunction fromRunEntity(e: WorkflowRunEntity): WorkflowRun {\n return {\n id: e.id,\n workflow: e.workflow,\n workflowVersion: e.workflowVersion,\n status: e.status,\n input: e.input ?? undefined,\n output: e.output ?? undefined,\n error: (e.error ?? undefined) as StepError | undefined,\n wakeAt: e.wakeAt == null ? undefined : e.wakeAt.getTime(),\n lockedBy: e.lockedBy ?? undefined,\n lockedUntil: e.lockedUntil == null ? undefined : e.lockedUntil.getTime(),\n awaitingDecisionTaskId: e.awaitingDecisionTaskId ?? undefined,\n recoveryAttempts: e.recoveryAttempts ?? undefined,\n tags: e.tags ?? undefined,\n searchAttributes: e.searchAttributes ?? undefined,\n priority: e.priority ?? undefined,\n // Reported verbatim. A row can only be NULL here if the column was added by hand without the\n // `'default'` back-fill the schema helper applies, and reading it back as `'default'` would then\n // LIE: the row would claim a namespace that its own SQL predicate does not match.\n namespace: e.namespace,\n // NULL (a row written before the column existed) surfaces as `undefined` = unknown origin.\n origin: e.origin ?? undefined,\n createdAt: e.createdAt,\n updatedAt: e.updatedAt,\n };\n}\n\nfunction toCheckpointEntity(cp: StepCheckpoint): StepCheckpointEntity {\n return {\n runId: cp.runId,\n seq: cp.seq,\n name: cp.name,\n kind: cp.kind,\n stepId: cp.stepId,\n status: cp.status,\n input: cp.input ?? null,\n output: cp.output ?? null,\n error: cp.error ?? null,\n events: cp.events ?? null,\n attempts: cp.attempts,\n workerGroup: cp.workerGroup ?? null,\n parallelGroup: cp.parallelGroup ?? null,\n ...(cp.wakeAt == null ? {} : { wakeAt: new Date(cp.wakeAt) }),\n enqueuedAt: cp.enqueuedAt,\n startedAt: cp.startedAt,\n finishedAt: cp.finishedAt,\n };\n}\n\nfunction fromCheckpointEntity(e: StepCheckpointEntity): StepCheckpoint {\n return {\n runId: e.runId,\n seq: e.seq,\n name: e.name,\n kind: e.kind,\n stepId: e.stepId,\n status: e.status,\n input: e.input ?? undefined,\n output: e.output ?? undefined,\n error: (e.error ?? undefined) as StepError | undefined,\n events: (e.events ?? undefined) as StepEvent[] | undefined,\n attempts: e.attempts,\n workerGroup: e.workerGroup ?? undefined,\n parallelGroup: e.parallelGroup ?? undefined,\n wakeAt: e.wakeAt == null ? undefined : e.wakeAt.getTime(),\n // Older rows predate enqueuedAt; treat the worker start as enqueue time (queue-wait reads zero).\n enqueuedAt: e.enqueuedAt ?? e.startedAt,\n startedAt: e.startedAt,\n finishedAt: e.finishedAt,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;ACCA,qBAAoD;AAU7C,SAASA,gB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,GAAIxE,GAAGnC,UAAU,OAAO,CAAC,IAAI;MAAEA,QAAQ,IAAIC,KAAKkC,GAAGnC,MAAM;IAAE;IAC3D6H,YAAY1F,GAAG0F;IACfC,WAAW3F,GAAG2F;IACdC,YAAY5F,GAAG4F;EACjB;AACF;AApBSjG;AAsBT,SAASJ,qBAAqBN,GAAuB;AACnD,SAAO;IACL3C,OAAO2C,EAAE3C;IACTgD,KAAKL,EAAEK;IACP2D,MAAMhE,EAAEgE;IACRoC,MAAMpG,EAAEoG;IACRC,QAAQrG,EAAEqG;IACV7H,QAAQwB,EAAExB;IACVC,OAAOuB,EAAEvB,SAAS0C;IAClBzC,QAAQsB,EAAEtB,UAAUyC;IACpBxC,OAAQqB,EAAErB,SAASwC;IACnBmF,QAAStG,EAAEsG,UAAUnF;IACrBoF,UAAUvG,EAAEuG;IACZC,aAAaxG,EAAEwG,eAAerF;IAC9BoE,eAAevF,EAAEuF,iBAAiBpE;IAClCvC,QAAQoB,EAAEpB,UAAU,OAAOuC,SAAYnB,EAAEpB,OAAOsH,QAAO;;IAEvDO,YAAYzG,EAAEyG,cAAczG,EAAE0G;IAC9BA,WAAW1G,EAAE0G;IACbC,YAAY3G,EAAE2G;EAChB;AACF;AArBSrG;","names":["parseJsonColumn","raw","field","undefined","JSON","parse","err","console","warn","message","jsonColumnTransformer","to","value","stringify","from","snakeCase","property","replace","c","toLowerCase","columnNamer","naming","WorkflowRunEntity","id","workflow","workflowVersion","status","input","output","error","wakeAt","lockedBy","lockedUntil","awaitingDecisionTaskId","recoveryAttempts","tags","searchAttributes","priority","namespace","origin","createdAt","updatedAt","StepCheckpointEntity","runId","seq","name","kind","stepId","events","attempts","workerGroup","parallelGroup","enqueuedAt","startedAt","finishedAt","RunAttributeEntity","key","strValue","numValue","SignalWaiterEntity","token","BufferedSignalEntity","payload","BufferedEventEntity","publishedAt","durableEntities","options","col","workflowRuns","EntitySchema","target","tableName","columns","type","primary","nullable","transformer","Date","default","stepCheckpoints","runAttributes","signalWaiters","bufferedSignals","Number","generated","bufferedEvents","ENTITIES","JSON_BLOB_COLUMNS","durable_workflow_runs","durable_step_checkpoints","TABLE_TO_ENTITY","WorkflowRunEntity","StepCheckpointEntity","durable_run_attributes","RunAttributeEntity","durable_signal_waiters","SignalWaiterEntity","durable_buffered_signals","BufferedSignalEntity","durable_buffered_events","BufferedEventEntity","durableManagedTables","Object","keys","durableColumnResolver","dataSource","table","property","entity","Error","meta","getMetadata","column","findColumnWithPropertyName","databaseName","jsonBlobColumnType","isMysql","buildWidenStatements","quote","col","out","props","entries","prop","push","ensureTypeOrmDurableSchema","q","id","driver","escape","resolve","type","String","options","isPg","isSqlite","str","txt","int","ts","nsCol","runs","checkpoints","runAttributes","waiters","buffered","bufferedEvents","runsCol","cpCol","attrCol","waiterCol","bufCol","bevCol","num","bufferedId","tables","additive","runner","createQueryRunner","sql","query","have","existingColumns","colType","has","indexes","name","target","release","d","rows","Set","map","r","scope","placeholder","COLUMN_NAME","import_typeorm","TypeOrmStateStore","dataSource","ensureSchema","ensureTypeOrmDurableSchema","runs","getRepository","WorkflowRunEntity","checkpoints","StepCheckpointEntity","waiters","SignalWaiterEntity","buffered","BufferedSignalEntity","bufferedEvents","BufferedEventEntity","attributes","RunAttributeEntity","reindexAttributes","runId","em","repo","delete","rows","normalizeAttributeRows","length","insert","createRun","run","save","toRunEntity","id","searchAttributes","updateRun","patch","update","workflow","workflowVersion","status","input","output","error","wakeAt","Date","lockedBy","lockedUntil","awaitingDecisionTaskId","recoveryAttempts","tags","priority","namespace","origin","createdAt","updatedAt","result","createQueryBuilder","set","where","execute","affected","Error","getRun","e","findOneBy","fromRunEntity","deleteRun","getCheckpoint","seq","fromCheckpointEntity","saveCheckpoint","checkpoint","entity","toCheckpointEntity","upsert","transaction","work","raw","cp","listIncompleteRuns","findBy","In","undefined","map","listPendingRuns","limit","find","order","take","listDueTimers","nowMs","LessThanOrEqual","tryLockRun","owner","leaseUntilMs","andWhere","Brackets","qb","IsNull","orWhere","releaseRunLock","renewRunLock","listRuns","query","statuses","tag","tagPattern","forEach","f","i","applyAttributeExists","orderBy","offset","skip","getMany","valueProperty","attributeColumnFor","cmp","sqlComparator","op","keyParam","valParam","resolve","durableColumnResolver","q","idQuote","wrap","name","runIdCol","keyCol","valueCol","runPkCol","table","a","sql","key","attributeOperand","type","String","options","listCheckpoints","getLatestCheckpointByName","findOne","listCheckpointsByNamePrefix","prefixes","p","Like","putSignalWaiter","waiter","token","parallelGroup","listSignalWaiters","prefix","takeSignalWaiter","removeSignalWaiter","bufferSignal","payload","takeBufferedSignal","bufferEvent","publishedAt","listBufferedEvents","getTime","removeBufferedEvent","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/entities.ts","../src/schema.ts","../src/typeorm-state-store.ts"],"sourcesContent":["export * from './entities';\nexport * from './schema';\nexport * from './typeorm-state-store';\n","import type { RunStatus, StepKind } from '@dudousxd/nestjs-durable-core';\nimport { EntitySchema, type ValueTransformer } from 'typeorm';\n\n/**\n * Safely deserialize a JSON-text column back to an object on READ.\n *\n * A column truncated by the old MySQL `text` 64KB limit (or otherwise corrupt) makes `JSON.parse`\n * throw \"Unterminated string in JSON\" — which, without this guard, would 500 the *entire* run-detail\n * read just because one blob is damaged. Instead, log once and degrade the bad field to `undefined`\n * so the rest of the run still renders. Valid JSON is unchanged.\n */\nexport function parseJsonColumn<T = unknown>(raw: unknown, field: string): T | undefined {\n if (raw == null) return undefined;\n // Some drivers (e.g. a native `json` column) already hand back a parsed object.\n if (typeof raw !== 'string') return raw as T;\n try {\n return JSON.parse(raw) as T;\n } catch (err) {\n console.warn(\n `durable store: failed to parse ${field} column, degrading to undefined: ${\n (err as Error).message\n }`,\n );\n return undefined;\n }\n}\n\n/**\n * TypeORM transformer for the free-form JSON-blob columns. Mirrors the built-in `simple-json`\n * serialization on WRITE (`JSON.stringify`, SQL NULL stays NULL) but uses {@link parseJsonColumn}\n * on READ so a single corrupt/truncated row degrades to `undefined` instead of throwing.\n */\nfunction jsonColumnTransformer(field: string): ValueTransformer {\n return {\n to: (value: unknown) => (value == null ? null : JSON.stringify(value)),\n from: (value: unknown) => parseJsonColumn(value, field),\n };\n}\n\n/**\n * How property names map to physical column names. The durable tables are adapter-agnostic: a run\n * written by one store adapter must be readable by another, so every adapter has to agree on the\n * physical column names. The default is `'snake_case'` (the canonical, matched by the MikroORM,\n * Prisma and Drizzle adapters). `'preserve'` keeps the camelCase property name verbatim (what the\n * old TypeORM/Prisma adapters produced before they were pinned). A function lets you supply any\n * custom mapping.\n *\n * The choice is pinned EXPLICITLY onto the entity schema rather than left to the host ORM's naming\n * strategy — depending on the host strategy is what silently diverged the adapters and broke a store\n * swap against an existing table.\n */\nexport type DurableColumnNaming = 'snake_case' | 'preserve' | ((property: string) => string);\n\nfunction snakeCase(property: string): string {\n return property.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);\n}\n\n/** Resolve a `DurableColumnNaming` to a `(property) => columnName` function. */\nexport function columnNamer(naming: DurableColumnNaming): (property: string) => string {\n if (naming === 'snake_case') return snakeCase;\n if (naming === 'preserve') return (property) => property;\n return naming;\n}\n\n// Plain classes (no decorators): the schema/column mapping lives on the EntitySchema built by\n// `durableEntities`, so the same class can be registered under different column names. The store\n// still references these classes for `getRepository`/`getMetadata`.\n\nexport class WorkflowRunEntity {\n id!: string;\n workflow!: string;\n workflowVersion!: string;\n status!: RunStatus;\n input?: unknown;\n output?: unknown;\n error?: unknown;\n wakeAt?: Date;\n lockedBy?: string | null;\n lockedUntil?: Date;\n awaitingDecisionTaskId?: string | null;\n recoveryAttempts?: number;\n tags?: string[] | null;\n searchAttributes?: Record<string, string | number | boolean> | null;\n priority?: number | null;\n namespace!: string;\n origin?: string | null;\n createdAt!: Date;\n updatedAt!: Date;\n}\n\nexport class StepCheckpointEntity {\n runId!: string;\n seq!: number;\n name!: string;\n kind!: StepKind;\n stepId!: string;\n status!: 'pending' | 'running' | 'completed' | 'failed';\n input?: unknown;\n output?: unknown;\n error?: unknown;\n events?: unknown;\n attempts!: number;\n workerGroup?: string | null;\n parallelGroup?: string | null;\n wakeAt?: Date;\n enqueuedAt?: Date;\n startedAt!: Date;\n finishedAt!: Date;\n}\n\n/**\n * Normalized side-table for search attributes: one row per (run, key), so range/equality predicates\n * push DOWN into SQL (an EXISTS join indexed on `(key, numValue)` / `(key, strValue)`) instead of a\n * coarse scan + in-process filter. Maintained on every `createRun`/`updateRun`. Numbers land in\n * `numValue`, strings/booleans in `strValue` (booleans as `\"true\"`/`\"false\"`); see `normalizeAttributeRows`.\n */\nexport class RunAttributeEntity {\n runId!: string;\n key!: string;\n strValue?: string | null;\n numValue?: number | null;\n}\n\nexport class SignalWaiterEntity {\n token!: string;\n runId!: string;\n seq!: number;\n parallelGroup?: string | null;\n}\n\nexport class BufferedSignalEntity {\n id!: number;\n token!: string;\n payload?: unknown;\n}\n\n/** A published event that matched no live waiter (see `engine.publishEvent`'s buffering). Keyed by a\n * caller-minted `id` (a uuid, not autoincrement — `removeBufferedEvent` targets it directly), not by\n * `runId`: events are name-based pub/sub, not tied to any one run. */\nexport class BufferedEventEntity {\n id!: string;\n name!: string;\n payload?: unknown;\n publishedAt!: Date;\n}\n\n/**\n * Build the durable TypeORM entity schemas with column names pinned per `naming` (default\n * `'snake_case'`). Register the result in your `DataSource`/`TypeOrmModule.forFeature`. The JSON-blob\n * columns keep the `jsonColumnTransformer` (corruption-tolerant read), the primary keys / auto-\n * increment / nullability are preserved, and the `id` of `durable_buffered_signals` stays a driver-\n * native auto-increment column.\n *\n * ```ts\n * entities: durableEntities({ naming: 'snake_case' })\n * ```\n */\nexport function durableEntities(options: { naming?: DurableColumnNaming } = {}): EntitySchema[] {\n const col = columnNamer(options.naming ?? 'snake_case');\n\n const workflowRuns = new EntitySchema<WorkflowRunEntity>({\n name: 'WorkflowRunEntity',\n target: WorkflowRunEntity,\n tableName: 'durable_workflow_runs',\n columns: {\n id: { type: 'text', primary: true, name: col('id') },\n workflow: { type: 'text', name: col('workflow') },\n workflowVersion: { type: 'text', name: col('workflowVersion') },\n status: { type: 'text', name: col('status') },\n input: {\n type: 'text',\n nullable: true,\n name: col('input'),\n transformer: jsonColumnTransformer('runs.input'),\n },\n output: {\n type: 'text',\n nullable: true,\n name: col('output'),\n transformer: jsonColumnTransformer('runs.output'),\n },\n error: {\n type: 'text',\n nullable: true,\n name: col('error'),\n transformer: jsonColumnTransformer('runs.error'),\n },\n wakeAt: { type: Date, nullable: true, name: col('wakeAt') },\n lockedBy: { type: 'text', nullable: true, name: col('lockedBy') },\n lockedUntil: { type: Date, nullable: true, name: col('lockedUntil') },\n // REMOTE turn the engine suspended on awaiting a decision; matched by completeRemoteDecision so\n // only the currently-awaited turn's decision is applied. Nullable: cleared when a decision lands.\n awaitingDecisionTaskId: {\n type: 'text',\n nullable: true,\n name: col('awaitingDecisionTaskId'),\n },\n recoveryAttempts: { type: 'integer', nullable: true, name: col('recoveryAttempts') },\n tags: {\n type: 'text',\n nullable: true,\n name: col('tags'),\n transformer: jsonColumnTransformer('runs.tags'),\n },\n searchAttributes: {\n type: 'text',\n nullable: true,\n name: col('searchAttributes'),\n transformer: jsonColumnTransformer('runs.searchAttributes'),\n },\n priority: { type: 'integer', nullable: true, name: col('priority') },\n // The worker-pool partition that owns the run. This is the tenant isolation boundary, not a\n // label: a worker only picks up (`listPendingRuns`), recovers (`listIncompleteRuns`), resumes\n // timers for (`listDueTimers`) and times out (`listRuns` with `namespace`) runs in its own\n // namespace, so an unfiltered predicate here hands one tenant's runs to another tenant's worker.\n //\n // NOT NULL DEFAULT `'default'`, deliberately unlike `origin` below. A run written before this\n // column existed DID execute in a namespace — the unscoped one — so `'default'` states a fact\n // rather than guesses one, and the DDL default (see the `additive` map in ./schema) back-fills\n // every pre-existing row with it. That back-fill is what makes the plain-equality predicates\n // safe: a NULL here would match no namespace at all, so a worker asking for `'default'` would\n // silently skip every run that predates the column.\n namespace: { type: 'text', name: col('namespace'), default: 'default' },\n // Which library/module registered the workflow this run belongs to (e.g.\n // `@dudousxd/nestjs-catalog-pipeline`), derived at registration time — never caller input.\n // Nullable with NO default: an origin cannot be reconstructed for a row written before this\n // column existed, so it stays NULL and reads back as `undefined` = \"unknown\". Defaulting it to\n // a real-looking string would be indistinguishable from a genuine registration in the\n // dashboard's facet. `ensureTypeOrmDurableSchema` back-fills the COLUMN onto pre-existing\n // tables (see the `additive` map in ./schema), never its value.\n origin: { type: 'text', nullable: true, name: col('origin') },\n createdAt: { type: Date, name: col('createdAt') },\n updatedAt: { type: Date, name: col('updatedAt') },\n },\n });\n\n const stepCheckpoints = new EntitySchema<StepCheckpointEntity>({\n name: 'StepCheckpointEntity',\n target: StepCheckpointEntity,\n tableName: 'durable_step_checkpoints',\n columns: {\n runId: { type: 'text', primary: true, name: col('runId') },\n seq: { type: 'integer', primary: true, name: col('seq') },\n name: { type: 'text', name: col('name') },\n kind: { type: 'text', name: col('kind') },\n stepId: { type: 'text', name: col('stepId') },\n status: { type: 'text', name: col('status') },\n input: {\n type: 'text',\n nullable: true,\n name: col('input'),\n transformer: jsonColumnTransformer('checkpoints.input'),\n },\n output: {\n type: 'text',\n nullable: true,\n name: col('output'),\n transformer: jsonColumnTransformer('checkpoints.output'),\n },\n error: {\n type: 'text',\n nullable: true,\n name: col('error'),\n transformer: jsonColumnTransformer('checkpoints.error'),\n },\n events: {\n type: 'text',\n nullable: true,\n name: col('events'),\n transformer: jsonColumnTransformer('checkpoints.events'),\n },\n attempts: { type: 'integer', name: col('attempts') },\n workerGroup: { type: 'text', nullable: true, name: col('workerGroup') },\n // A ctx.gather/ctx.all fan tags every sibling step with the same group so the dashboard renders\n // them as one parallel group; the core engine sets it (incl. from a remote worker's recordStep).\n parallelGroup: { type: 'text', nullable: true, name: col('parallelGroup') },\n wakeAt: { type: Date, nullable: true, name: col('wakeAt') },\n enqueuedAt: { type: Date, nullable: true, name: col('enqueuedAt') },\n startedAt: { type: Date, name: col('startedAt') },\n finishedAt: { type: Date, name: col('finishedAt') },\n },\n });\n\n const runAttributes = new EntitySchema<RunAttributeEntity>({\n name: 'RunAttributeEntity',\n target: RunAttributeEntity,\n tableName: 'durable_run_attributes',\n columns: {\n runId: { type: 'text', primary: true, name: col('runId') },\n key: { type: 'text', primary: true, name: col('key') },\n strValue: { type: 'text', nullable: true, name: col('strValue') },\n // `float`/`double` portable across SQLite/MySQL/Postgres for numeric range scans.\n numValue: { type: 'float', nullable: true, name: col('numValue') },\n },\n });\n\n const signalWaiters = new EntitySchema<SignalWaiterEntity>({\n name: 'SignalWaiterEntity',\n target: SignalWaiterEntity,\n tableName: 'durable_signal_waiters',\n columns: {\n token: { type: 'text', primary: true, name: col('token') },\n runId: { type: 'text', name: col('runId') },\n seq: { type: 'integer', name: col('seq') },\n // A ctx.gather_children/ctx.all child fan-out tags every awaited child with the same group; the\n // engine threads it onto the waiter so the resolving `signal:child:` checkpoint carries it and the\n // dashboard renders the fan as one parallel group. Nullable: only fan-out child waiters carry it.\n parallelGroup: { type: 'text', nullable: true, name: col('parallelGroup') },\n },\n });\n\n const bufferedSignals = new EntitySchema<BufferedSignalEntity>({\n name: 'BufferedSignalEntity',\n target: BufferedSignalEntity,\n tableName: 'durable_buffered_signals',\n columns: {\n // Auto-increment PK for FIFO ordering. Left as TypeORM's default increment generation so it\n // maps to the driver-native auto-increment column (INTEGER on SQLite, BIGINT/SERIAL elsewhere).\n id: { type: Number, primary: true, generated: 'increment', name: col('id') },\n token: { type: 'text', name: col('token') },\n payload: {\n type: 'text',\n nullable: true,\n name: col('payload'),\n transformer: jsonColumnTransformer('buffered.payload'),\n },\n },\n });\n\n const bufferedEvents = new EntitySchema<BufferedEventEntity>({\n name: 'BufferedEventEntity',\n target: BufferedEventEntity,\n tableName: 'durable_buffered_events',\n // No `indices` here (unlike MikroORM's EntitySchema, which does declare one): this store manages\n // its DDL — including the `(name, publishedAt)` index — via raw SQL in `schema.ts`'s\n // `ensureTypeOrmDurableSchema`, the same as every other durable_* table's indexes.\n columns: {\n // Caller-minted uuid (engine.publishEvent), not autoincrement — removeBufferedEvent targets it\n // directly and needs to be handed the SAME id it was buffered with.\n id: { type: 'text', primary: true, name: col('id') },\n name: { type: 'text', name: col('name') },\n payload: {\n type: 'text',\n nullable: true,\n name: col('payload'),\n transformer: jsonColumnTransformer('buffered.eventPayload'),\n },\n publishedAt: { type: Date, name: col('publishedAt') },\n },\n });\n\n return [\n workflowRuns,\n stepCheckpoints,\n runAttributes,\n signalWaiters,\n bufferedSignals,\n bufferedEvents,\n ];\n}\n\n/** Durable entity schemas with the canonical `'snake_case'` column names. */\nexport const ENTITIES = durableEntities();\n","import type { DataSource } from 'typeorm';\nimport {\n BufferedEventEntity,\n BufferedSignalEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n StepCheckpointEntity,\n WorkflowRunEntity,\n} from './entities';\n\n/** The JSON-blob columns per table (keyed by table name) that hold free-form payloads and so must\n * be the unbounded text type — `longtext` on MySQL, `text` elsewhere. Keyed by entity PROPERTY name;\n * the physical column is resolved from the DataSource metadata so it tracks the configured naming. */\nexport const JSON_BLOB_COLUMNS: Record<string, string[]> = {\n durable_workflow_runs: ['input', 'output', 'error', 'tags', 'searchAttributes'],\n durable_step_checkpoints: ['input', 'output', 'error', 'events'],\n // NOTE: durable_buffered_signals/durable_buffered_events intentionally omitted here, same as the\n // existing buffered-signals table — their `payload` column is created with the widened `txt` type\n // (see `${bufCol('payload')} ${txt}` / the new table's `${bevCol('payload')} ${txt}` below) directly\n // at CREATE TABLE time on a fresh install, so there's no pre-existing narrower column to widen.\n};\n\n/** Each durable table → its backing entity class, so a column resolver can look up the physical\n * column for any (table, property) from the DataSource metadata (which reflects the configured\n * `DurableColumnNaming`). Keeps the raw DDL/SQL in lock-step with the entity column mapping. */\nconst TABLE_TO_ENTITY = {\n durable_workflow_runs: WorkflowRunEntity,\n durable_step_checkpoints: StepCheckpointEntity,\n durable_run_attributes: RunAttributeEntity,\n durable_signal_waiters: SignalWaiterEntity,\n durable_buffered_signals: BufferedSignalEntity,\n durable_buffered_events: BufferedEventEntity,\n} as const;\n\n/**\n * Tables this store creates and manages at boot (autoSchema, see {@link ensureTypeOrmDurableSchema}).\n * Feed to your ORM's migration differ exclude/skipTables so it never tries to drop them.\n *\n * ```ts\n * // MikroORM-flavoured example (TypeORM has no built-in equivalent option); adapt to whichever\n * // migration tool generates your diffs — e.g. exclude these names from a typeorm-generated\n * // migration, or filter them out of `SELECT table_name FROM information_schema.tables` before\n * // diffing against your own entities.\n * const skipTables = new Set(durableManagedTables());\n * ```\n *\n * Derived from the same {@link TABLE_TO_ENTITY} map the raw-SQL heal keys its column resolution off\n * — one list, so a consumer's denylist can never drift from what this store actually owns.\n */\nexport function durableManagedTables(): string[] {\n return Object.keys(TABLE_TO_ENTITY);\n}\n\n/**\n * Resolve `(table, property) => physical column name` from the DataSource's entity metadata. The\n * column names are NOT hardcoded here: they come from whatever the registered `durableEntities`\n * mapped (canonical `snake_case` by default, `'preserve'` for the legacy camelCase, or a custom\n * mapping), so the raw `CREATE TABLE`/index/EXISTS SQL always matches the entities and can never\n * silently diverge.\n */\nexport function durableColumnResolver(\n dataSource: DataSource,\n): (table: string, property: string) => string {\n return (table, property) => {\n const entity = TABLE_TO_ENTITY[table as keyof typeof TABLE_TO_ENTITY];\n if (!entity) throw new Error(`durable store: unknown table \"${table}\"`);\n const meta = dataSource.getMetadata(entity);\n const column = meta.findColumnWithPropertyName(property);\n if (!column) {\n throw new Error(`durable store: no column for ${table}.${property} in entity metadata`);\n }\n return column.databaseName;\n };\n}\n\n/** The SQL type for free-form JSON-blob columns. MySQL `text` caps at 64KB and silently truncates,\n * so use `longtext` (4GB) there; Postgres/SQLite `text` is already unbounded. */\nexport function jsonBlobColumnType(isMysql: boolean): 'longtext' | 'text' {\n return isMysql ? 'longtext' : 'text';\n}\n\n/** Idempotent `MODIFY COLUMN ... longtext` statements that widen pre-existing MySQL `text` JSON-blob\n * columns. Returns `[]` on non-MySQL dialects (their `text` is already unbounded — nothing to do).\n * `quote` quotes an identifier per the active driver; `col` resolves a property to its physical\n * column name so the widen tracks the configured naming. */\nexport function buildWidenStatements(\n isMysql: boolean,\n quote: (id: string) => string,\n col: (table: string, property: string) => string,\n): string[] {\n if (!isMysql) return [];\n const out: string[] = [];\n for (const [table, props] of Object.entries(JSON_BLOB_COLUMNS)) {\n for (const prop of props) {\n out.push(`ALTER TABLE ${quote(table)} MODIFY COLUMN ${quote(col(table, prop))} longtext`);\n }\n }\n return out;\n}\n\n/**\n * Idempotently create the durable tables. Safe to run on every boot (auto-schema) and the\n * exact function to call from your own TypeORM migration when you disable auto-schema:\n *\n * ```ts\n * export class AddDurableTables implements MigrationInterface {\n * async up(q: QueryRunner) { await ensureTypeOrmDurableSchema(q.connection); }\n * }\n * ```\n *\n * Dialect-aware (MySQL / MariaDB / Postgres / SQLite): identifiers are quoted per driver, keyed\n * string columns are `varchar` (MySQL can't key a `text` column), and the index is best-effort.\n * Only ever adds the three durable tables — it never touches your other tables.\n */\nexport async function ensureTypeOrmDurableSchema(dataSource: DataSource): Promise<void> {\n const q = (id: string) => dataSource.driver.escape(id);\n // Physical column names come from the entity metadata (canonical snake_case by default), so this\n // raw DDL always matches the registered `durableEntities` instead of hardcoding camelCase.\n const resolve = durableColumnResolver(dataSource);\n const type = String(dataSource.options.type);\n const isPg = type === 'postgres' || type === 'aurora-postgres';\n const isMysql = type === 'mysql' || type === 'mariadb' || type === 'aurora-mysql';\n const isSqlite = type === 'sqlite' || type === 'better-sqlite3' || type === 'expo';\n\n // Keyed/short strings must be varchar on MySQL (a `text` PK/index needs a key length); `text`\n // for the free-form JSON payloads. Dates use the dialect's native timestamp type.\n const str = 'varchar(191)';\n // Free-form JSON payloads (`input`/`output`/`error`/`events`/`tags`/`searchAttributes`). MySQL's\n // `text` caps at 64KB and *silently truncates* — a large fan-out step's `events` then fails to\n // parse on read (\"Unterminated string in JSON\"). Use `longtext` (4GB) on MySQL; Postgres `text`\n // is already unbounded and SQLite `text` has no length limit.\n const txt = jsonBlobColumnType(isMysql);\n const int = isMysql ? 'int' : 'integer';\n const ts = isPg ? 'timestamptz' : 'datetime';\n // The tenant partition every poll predicate filters on. NOT NULL with a literal default so that\n // adding it to a table that predates it back-fills each existing row with `'default'` — the\n // namespace those runs actually executed in — instead of leaving NULLs that would match no\n // namespace and so be invisible to every worker. Postgres (11+) and SQLite fill the existing rows\n // from the default without rewriting the table; MySQL 8.0.12+ does it instantly, older MySQL\n // rewrites the table once, so a very large `durable_workflow_runs` there should take the ALTER in a\n // maintenance window rather than at boot.\n const nsCol = `${str} NOT NULL DEFAULT 'default'`;\n\n const runs = q('durable_workflow_runs');\n const checkpoints = q('durable_step_checkpoints');\n const runAttributes = q('durable_run_attributes');\n const waiters = q('durable_signal_waiters');\n const buffered = q('durable_buffered_signals');\n const bufferedEvents = q('durable_buffered_events');\n // Per-table quoted-column helpers: resolve an entity property to its physical column then quote it.\n const runsCol = (property: string) => q(resolve('durable_workflow_runs', property));\n const cpCol = (property: string) => q(resolve('durable_step_checkpoints', property));\n const attrCol = (property: string) => q(resolve('durable_run_attributes', property));\n const waiterCol = (property: string) => q(resolve('durable_signal_waiters', property));\n const bufCol = (property: string) => q(resolve('durable_buffered_signals', property));\n const bevCol = (property: string) => q(resolve('durable_buffered_events', property));\n // Numeric side-table column for attribute range scans. `double precision` on Postgres, `double` on\n // MySQL, `real` on SQLite (all hold JS numbers without precision loss for the typical attribute).\n const num = isPg ? 'double precision' : isMysql ? 'double' : 'real';\n\n // Auto-increment PK syntax differs per dialect: SQLite wants `INTEGER PRIMARY KEY AUTOINCREMENT`,\n // MySQL `BIGINT AUTO_INCREMENT PRIMARY KEY`, Postgres `BIGSERIAL PRIMARY KEY`.\n const bufferedId = isSqlite\n ? `${bufCol('id')} integer PRIMARY KEY AUTOINCREMENT`\n : isMysql\n ? `${bufCol('id')} bigint NOT NULL AUTO_INCREMENT PRIMARY KEY`\n : isPg\n ? `${bufCol('id')} bigserial PRIMARY KEY`\n : `${bufCol('id')} bigint NOT NULL AUTO_INCREMENT PRIMARY KEY`;\n\n const tables = [\n `CREATE TABLE IF NOT EXISTS ${runs} (\n ${runsCol('id')} ${str} PRIMARY KEY,\n ${runsCol('workflow')} ${str} NOT NULL,\n ${runsCol('workflowVersion')} ${str} NOT NULL,\n ${runsCol('status')} ${str} NOT NULL,\n ${runsCol('input')} ${txt}, ${runsCol('output')} ${txt}, ${runsCol('error')} ${txt},\n ${runsCol('wakeAt')} ${ts}, ${runsCol('lockedBy')} ${str}, ${runsCol('lockedUntil')} ${ts},\n ${runsCol('awaitingDecisionTaskId')} ${str},\n ${runsCol('recoveryAttempts')} ${int}, ${runsCol('tags')} ${txt}, ${runsCol('searchAttributes')} ${txt},\n ${runsCol('priority')} ${int}, ${runsCol('namespace')} ${nsCol}, ${runsCol('origin')} ${str},\n ${runsCol('createdAt')} ${ts} NOT NULL, ${runsCol('updatedAt')} ${ts} NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS ${checkpoints} (\n ${cpCol('runId')} ${str} NOT NULL, ${cpCol('seq')} ${int} NOT NULL,\n ${cpCol('name')} ${str} NOT NULL, ${cpCol('kind')} ${str} NOT NULL, ${cpCol('stepId')} ${str} NOT NULL,\n ${cpCol('status')} ${str} NOT NULL, ${cpCol('input')} ${txt}, ${cpCol('output')} ${txt}, ${cpCol('error')} ${txt}, ${cpCol('events')} ${txt},\n ${cpCol('attempts')} ${int} NOT NULL, ${cpCol('workerGroup')} ${str}, ${cpCol('parallelGroup')} ${str},\n ${cpCol('wakeAt')} ${ts}, ${cpCol('enqueuedAt')} ${ts},\n ${cpCol('startedAt')} ${ts} NOT NULL, ${cpCol('finishedAt')} ${ts} NOT NULL,\n PRIMARY KEY (${cpCol('runId')}, ${cpCol('seq')})\n )`,\n // Normalized search-attribute side-table: one row per (run, key) so attribute predicates push\n // DOWN into SQL via an EXISTS join (indexed below). `key` is keyed → must be varchar on MySQL.\n `CREATE TABLE IF NOT EXISTS ${runAttributes} (\n ${attrCol('runId')} ${str} NOT NULL, ${attrCol('key')} ${str} NOT NULL,\n ${attrCol('strValue')} ${str}, ${attrCol('numValue')} ${num},\n PRIMARY KEY (${attrCol('runId')}, ${attrCol('key')})\n )`,\n `CREATE TABLE IF NOT EXISTS ${waiters} (\n ${waiterCol('token')} ${str} PRIMARY KEY, ${waiterCol('runId')} ${str} NOT NULL, ${waiterCol('seq')} ${int} NOT NULL,\n ${waiterCol('parallelGroup')} ${str}\n )`,\n `CREATE TABLE IF NOT EXISTS ${buffered} (\n ${bufferedId}, ${bufCol('token')} ${str} NOT NULL, ${bufCol('payload')} ${txt}\n )`,\n // Caller-minted uuid PK (engine.publishEvent), not auto-increment — unlike durable_buffered_signals\n // above, removeBufferedEvent needs to target the EXACT id it was buffered with.\n `CREATE TABLE IF NOT EXISTS ${bufferedEvents} (\n ${bevCol('id')} ${str} PRIMARY KEY, ${bevCol('name')} ${str} NOT NULL,\n ${bevCol('payload')} ${txt}, ${bevCol('publishedAt')} ${ts} NOT NULL\n )`,\n ];\n\n // Additive nullable columns gained across versions (e.g. `input`, `events`, `enqueuedAt`). On a\n // table that predates them, `CREATE TABLE IF NOT EXISTS` above is a no-op, so back-fill the ones\n // that are actually missing — the auto-schema self-heals instead of needing a manual migration.\n // We check the live columns first (rather than ALTER-and-ignore) so a *real* ALTER failure\n // surfaces instead of being swallowed as a presumed \"column already exists\".\n // Keyed by entity PROPERTY name; the physical column is resolved per-table so the ADD COLUMN\n // tracks the configured naming.\n const additive: Record<string, Array<[string, string]>> = {\n durable_workflow_runs: [\n ['input', txt],\n ['output', txt],\n ['error', txt],\n ['awaitingDecisionTaskId', str],\n ['recoveryAttempts', int],\n ['tags', txt],\n ['searchAttributes', txt],\n ['priority', int],\n // Back-filled WITH a value, unlike `origin` below: the DDL default writes `'default'` onto\n // every pre-existing row, because a run created before this column existed really did execute\n // in the unscoped `'default'` namespace. Leaving those rows NULL would make them invisible to\n // the worker that owns them — the list predicates are plain equality, so `NULL <> 'default'`.\n ['namespace', nsCol],\n // Nullable and NOT back-filled with a value: every row that predates the column keeps a NULL\n // origin, which the store reads as `undefined` = \"unknown origin\". There is no honest value to\n // back-fill — the origin is derived from the registration that created the run, which is long\n // gone by the time this ALTER runs.\n ['origin', str],\n ],\n durable_step_checkpoints: [\n ['input', txt],\n ['output', txt],\n ['error', txt],\n ['events', txt],\n ['workerGroup', str],\n ['parallelGroup', str],\n ['enqueuedAt', ts],\n ],\n // Back-fill the child-await fan group onto signal-waiter tables that predate it (a remote\n // `gather_children` fan-out threads its group here so the resolved `signal:child:` checkpoint carries it).\n durable_signal_waiters: [['parallelGroup', str]],\n };\n\n const runner = dataSource.createQueryRunner();\n try {\n for (const sql of tables) await runner.query(sql);\n for (const [table, props] of Object.entries(additive)) {\n const have = await existingColumns(runner, table, { isSqlite, isMysql });\n for (const [property, colType] of props) {\n const column = resolve(table, property);\n if (!have.has(column)) {\n await runner.query(`ALTER TABLE ${q(table)} ADD COLUMN ${q(column)} ${colType}`);\n }\n }\n }\n // Widen pre-existing MySQL `text` JSON-blob columns to `longtext`. A table created before this\n // fix has these as `text` (64KB) and silently truncates large `events`/`output` payloads. MODIFY\n // to `longtext` is idempotent (no-op if already longtext), so it's safe to run on every boot.\n // MySQL-only: Postgres/SQLite `text` is already unbounded, so there's nothing to widen.\n for (const sql of buildWidenStatements(isMysql, q, resolve)) {\n try {\n await runner.query(sql);\n } catch {\n /* column already longtext, or table/column not present on this deploy */\n }\n }\n // MySQL has no `CREATE INDEX IF NOT EXISTS`; create each best-effort and ignore \"already exists\".\n // - status/wakeAt: the timer poller (listDueTimers) and recovery (listIncompleteRuns) scans.\n // - workflow/status: the dashboard's listRuns filters. (Checkpoints are keyed by the PK prefix\n // `(runId, seq)`, so listCheckpoints/getEvent already hit an index — no extra one needed.)\n const indexes: Array<[string, string]> = [\n ['durable_runs_status_idx', `${runs} (${runsCol('status')}, ${runsCol('wakeAt')})`],\n [\n 'durable_runs_workflow_status_idx',\n `${runs} (${runsCol('workflow')}, ${runsCol('status')})`,\n ],\n // namespace/status/createdAt: every poll tick of a namespaced worker filters on `namespace`\n // ANDed with `status` (and `listPendingRuns` orders by `createdAt`), so without this the two\n // indexes above degrade to a scan of the WHOLE table — including every other tenant's rows —\n // on each tick. Created best-effort on every boot like the others, so a deployment whose table\n // already exists picks it up as soon as it runs this version.\n [\n 'durable_runs_namespace_status_idx',\n `${runs} (${runsCol('namespace')}, ${runsCol('status')}, ${runsCol('createdAt')})`,\n ],\n // buffered signals are taken FIFO per token (smallest id) — index the token for the scan.\n ['durable_buffered_signals_token_idx', `${buffered} (${bufCol('token')})`],\n // buffered events are scanned oldest-first per name — one composite index serves both.\n [\n 'durable_buffered_events_name_published_at_idx',\n `${bufferedEvents} (${bevCol('name')}, ${bevCol('publishedAt')})`,\n ],\n // Search-attribute pushdown: equality + range predicates probe by (key, value). Two composite\n // indexes — one per typed column — so a numeric range or a string equality is an index scan.\n [\n 'durable_run_attributes_num_idx',\n `${runAttributes} (${attrCol('key')}, ${attrCol('numValue')})`,\n ],\n [\n 'durable_run_attributes_str_idx',\n `${runAttributes} (${attrCol('key')}, ${attrCol('strValue')})`,\n ],\n ];\n for (const [name, target] of indexes) {\n try {\n await runner.query(`CREATE INDEX ${q(name)} ON ${target}`);\n } catch {\n /* index already exists */\n }\n }\n } finally {\n await runner.release();\n }\n}\n\n/** The columns that currently exist on `table`, so the schema can add only the missing ones\n * (instead of ALTER-and-swallow, which would also hide a genuine ALTER failure). */\nasync function existingColumns(\n runner: { query: (sql: string, params?: unknown[]) => Promise<unknown> },\n table: string,\n d: { isSqlite: boolean; isMysql: boolean },\n): Promise<Set<string>> {\n if (d.isSqlite) {\n const rows = (await runner.query(`PRAGMA table_info(\"${table}\")`)) as Array<{ name: string }>;\n return new Set(rows.map((r) => r.name));\n }\n // Postgres + MySQL both expose information_schema; scope to the connection's own schema/db.\n // Bind-param placeholder differs: Postgres uses `$1`, MySQL uses `?` (TypeORM only rewrites `?`\n // inside the query builder, not for these raw `runner.query` calls), so pick per dialect.\n const scope = d.isMysql ? 'TABLE_SCHEMA = DATABASE()' : 'table_schema = current_schema()';\n const placeholder = d.isMysql ? '?' : '$1';\n const rows = (await runner.query(\n `SELECT column_name AS name FROM information_schema.columns WHERE table_name = ${placeholder} AND ${scope}`,\n [table],\n )) as Array<{ name?: string; COLUMN_NAME?: string }>;\n return new Set(rows.map((r) => (r.name ?? r.COLUMN_NAME) as string));\n}\n","import {\n type AttributeFilter,\n RUN_VALUE_FACET_SCAN,\n type RunFacetQuery,\n type RunFacetRow,\n type RunQuery,\n type RunStatus,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type SignalWaiter,\n type StateStore,\n type StepCheckpoint,\n type StepError,\n type StepEvent,\n type WorkflowRun,\n attributePredicateOperands,\n axisIsRunColumn,\n mergeRunFacetRows,\n mergeRunValueFacetRows,\n normalizeAttributeRows,\n runValueFacetsFromRuns,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Brackets,\n type DataSource,\n type EntityManager,\n In,\n IsNull,\n LessThanOrEqual,\n Like,\n type SelectQueryBuilder,\n} from 'typeorm';\nimport type { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';\nimport {\n BufferedEventEntity,\n BufferedSignalEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n StepCheckpointEntity,\n WorkflowRunEntity,\n} from './entities';\nimport { durableColumnResolver, ensureTypeOrmDurableSchema } from './schema';\n\n/**\n * TypeORM-backed `StateStore`. Works on any TypeORM driver — Postgres, MySQL, SQLite (tested);\n * timestamps use native datetime columns and `wakeAt` is stored as a datetime too.\n */\nexport class TypeOrmStateStore implements StateStore {\n constructor(private readonly dataSource: DataSource) {}\n\n async ensureSchema(): Promise<void> {\n await ensureTypeOrmDurableSchema(this.dataSource);\n }\n\n private runs() {\n return this.dataSource.getRepository(WorkflowRunEntity);\n }\n private checkpoints() {\n return this.dataSource.getRepository(StepCheckpointEntity);\n }\n private waiters() {\n return this.dataSource.getRepository(SignalWaiterEntity);\n }\n private buffered() {\n return this.dataSource.getRepository(BufferedSignalEntity);\n }\n private bufferedEvents() {\n return this.dataSource.getRepository(BufferedEventEntity);\n }\n private attributes() {\n return this.dataSource.getRepository(RunAttributeEntity);\n }\n\n /** Rewrite a run's normalized attribute rows: delete the old set, insert the current one. Mirrors\n * the in-memory store's reindex so the side-table always reflects the run's live searchAttributes. */\n private async reindexAttributes(\n runId: string,\n attributes: WorkflowRun['searchAttributes'],\n em?: EntityManager,\n ): Promise<void> {\n const repo = em ? em.getRepository(RunAttributeEntity) : this.attributes();\n await repo.delete({ runId });\n const rows = normalizeAttributeRows(runId, attributes);\n if (rows.length) await repo.insert(rows);\n }\n\n async createRun(run: WorkflowRun): Promise<void> {\n await this.runs().save(toRunEntity(run));\n await this.reindexAttributes(run.id, run.searchAttributes);\n }\n\n async updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n // Single UPDATE (no pre-SELECT + save round-trips): map only the patched fields. The query\n // builder still applies the entities' JSON column transformers to the `set` values (as in\n // listRuns/tryLockRun). Preserve the not-found throw any caller may rely on.\n const update: Record<string, unknown> = {};\n if ('workflow' in patch) update.workflow = patch.workflow;\n if ('workflowVersion' in patch) update.workflowVersion = patch.workflowVersion;\n if ('status' in patch) update.status = patch.status;\n if ('input' in patch) update.input = patch.input ?? null;\n if ('output' in patch) update.output = patch.output ?? null;\n if ('error' in patch) update.error = patch.error ?? null;\n if ('wakeAt' in patch) update.wakeAt = patch.wakeAt == null ? null : new Date(patch.wakeAt);\n if ('lockedBy' in patch) update.lockedBy = patch.lockedBy ?? null;\n if ('lockedUntil' in patch)\n update.lockedUntil = patch.lockedUntil == null ? null : new Date(patch.lockedUntil);\n if ('awaitingDecisionTaskId' in patch)\n update.awaitingDecisionTaskId = patch.awaitingDecisionTaskId ?? null;\n if ('recoveryAttempts' in patch) update.recoveryAttempts = patch.recoveryAttempts;\n if ('tags' in patch) update.tags = patch.tags ?? null;\n if ('searchAttributes' in patch) update.searchAttributes = patch.searchAttributes ?? null;\n if ('priority' in patch) update.priority = patch.priority ?? null;\n // A patch that clears the namespace still lands on `'default'`, never NULL — the column is the\n // isolation predicate, and a NULL there would match no worker's namespace at all.\n if ('namespace' in patch) update.namespace = patch.namespace ?? 'default';\n if ('origin' in patch) update.origin = patch.origin ?? null;\n if ('createdAt' in patch) update.createdAt = patch.createdAt;\n if ('updatedAt' in patch) update.updatedAt = patch.updatedAt;\n const result = await this.runs()\n .createQueryBuilder()\n .update()\n .set(update)\n .where({ id: runId })\n .execute();\n if (!result.affected) throw new Error(`run ${runId} not found`);\n // Keep the side-table in step with the run's attributes whenever they're patched.\n if ('searchAttributes' in patch) await this.reindexAttributes(runId, patch.searchAttributes);\n }\n\n async getRun(runId: string): Promise<WorkflowRun | null> {\n const e = await this.runs().findOneBy({ id: runId });\n return e ? fromRunEntity(e) : null;\n }\n\n async deleteRun(runId: string): Promise<void> {\n // Child rows first, then the run — checkpoints, signal waiters, attribute rows.\n await this.checkpoints().delete({ runId });\n await this.waiters().delete({ runId });\n await this.attributes().delete({ runId });\n await this.runs().delete({ id: runId });\n }\n\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n const e = await this.checkpoints().findOneBy({ runId, seq });\n return e ? fromCheckpointEntity(e) : null;\n }\n\n async saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n // upsert = INSERT ... ON CONFLICT DO UPDATE on the (runId, seq) key — drops the pre-SELECT that\n // `.save()` does on each write. JSON column transformers still apply for upsert.\n const entity = toCheckpointEntity(checkpoint) as QueryDeepPartialEntity<StepCheckpointEntity>;\n await this.checkpoints().upsert(entity, ['runId', 'seq']);\n }\n\n async transaction<T>(\n work: (tx: {\n raw: unknown;\n saveCheckpoint: (cp: StepCheckpoint) => Promise<void>;\n }) => Promise<T>,\n ): Promise<T> {\n return this.dataSource.transaction(async (em) =>\n work({\n raw: em,\n saveCheckpoint: async (cp) => {\n await em.getRepository(StepCheckpointEntity).save(toCheckpointEntity(cp));\n },\n }),\n );\n }\n\n /**\n * The three worker-poll predicates below (recover / pick up / resume timers) each AND in\n * `namespace` when one is given, and omit the predicate entirely when it is `undefined`. Omitting\n * is NOT the same as `namespace IS NULL`: `undefined` means \"no restriction\" — the operator /\n * control-plane view that legitimately sees every tenant — whereas a NULL-matching predicate would\n * hide every real run behind an empty result while looking correct in a single-tenant test.\n */\n async listIncompleteRuns(namespace?: string): Promise<WorkflowRun[]> {\n const rows = await this.runs().findBy({\n status: In(['running', 'cancelling']),\n ...(namespace !== undefined ? { namespace } : {}),\n });\n return rows.map(fromRunEntity);\n }\n\n async listPendingRuns(limit: number, namespace?: string): Promise<WorkflowRun[]> {\n const rows = await this.runs().find({\n where: { status: 'pending', ...(namespace !== undefined ? { namespace } : {}) },\n order: { createdAt: 'ASC' }, // FIFO dispatch\n take: limit,\n });\n return rows.map(fromRunEntity);\n }\n\n async listDueTimers(nowMs: number, namespace?: string): Promise<WorkflowRun[]> {\n const rows = await this.runs().findBy({\n status: 'suspended',\n wakeAt: LessThanOrEqual(new Date(nowMs)),\n ...(namespace !== undefined ? { namespace } : {}),\n });\n return rows.map(fromRunEntity);\n }\n\n async tryLockRun(\n runId: string,\n owner: string,\n leaseUntilMs: number,\n nowMs: number,\n ): Promise<boolean> {\n const result = await this.runs()\n .createQueryBuilder()\n .update()\n .set({ lockedBy: owner, lockedUntil: new Date(leaseUntilMs) })\n .where({ id: runId })\n .andWhere(\n new Brackets((qb) =>\n qb\n .where({ lockedUntil: IsNull() })\n .orWhere({ lockedUntil: LessThanOrEqual(new Date(nowMs)) }),\n ),\n )\n .execute();\n return result.affected === 1;\n }\n\n async releaseRunLock(runId: string): Promise<void> {\n await this.runs().update({ id: runId }, { lockedBy: null, lockedUntil: () => 'NULL' });\n }\n\n async renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n const result = await this.runs()\n .createQueryBuilder()\n .update()\n .set({ lockedUntil: new Date(leaseUntilMs) })\n .where({ id: runId, lockedBy: owner })\n .execute();\n return result.affected === 1;\n }\n\n /** A query builder (root alias `r`) carrying the predicates every run query shares —\n * {@link listRuns} orders + pages it, {@link runFacets} groups it, so a facet count and the page\n * it labels are always taken over the same set. */\n private runQueryBuilder(query: RunQuery): SelectQueryBuilder<WorkflowRunEntity> {\n // `tags` carries a custom JSON transformer, and TypeORM applies a column transformer's `to()` to\n // FindOperator values too — so a `Like('%\"etl\"%')` in a plain `where` would be JSON-stringified\n // and corrupt the LIKE pattern. Use the query builder with a raw parameter to bypass that.\n const qb = this.runs().createQueryBuilder('r');\n if (query.workflow) qb.andWhere('r.workflow = :workflow', { workflow: query.workflow });\n // The plural form of each axis: ORed within itself, ANDed with everything else, and an empty set\n // matches nothing — the contract `statuses` already had, spelled the same way (`1 = 0`).\n if (query.workflows)\n qb.andWhere(\n query.workflows.length ? 'r.workflow IN (:...workflows)' : '1 = 0',\n query.workflows.length ? { workflows: query.workflows } : {},\n );\n // The tenant partition. This is not only a dashboard facet: the engine's execution-timeout sweep\n // finds its in-flight runs through `listRuns({ workflow, status, namespace })`, so without this\n // predicate a namespaced worker would cancel ANOTHER tenant's long-running runs. `undefined`\n // leaves the predicate off = every namespace (the operator view), exactly as in the list methods.\n if (query.namespace !== undefined)\n qb.andWhere('r.namespace = :namespace', { namespace: query.namespace });\n if (query.namespaces)\n qb.andWhere(\n query.namespaces.length ? 'r.namespace IN (:...namespaces)' : '1 = 0',\n query.namespaces.length ? { namespaces: query.namespaces } : {},\n );\n // Which library registered the workflow. Plain equality, so a run whose origin is NULL (created\n // before the column existed, or registered through a path the derivation could not classify)\n // matches NO origin value — it is never folded into a bucket to make the facet look complete.\n // Unknown-origin runs are reachable only with the filter OFF, so \"all origins\" must stay the\n // default view; a dashboard that filtered by default would make those runs look deleted.\n // `null` asks for exactly that absent bucket, which is how a paginated console offers an\n // \"unknown\" chip without holding every run in the browser to find them.\n if (query.origin === null) qb.andWhere('r.origin IS NULL');\n else if (query.origin !== undefined)\n qb.andWhere('r.origin = :origin', { origin: query.origin });\n // A set of origins may include `null` (the unattributed bucket), which `IN` cannot carry —\n // `IN (NULL)` is never true — so it becomes its own ORed `IS NULL` branch.\n if (query.origins) {\n const named = query.origins.filter((o): o is string => o !== null);\n const branches: string[] = [];\n if (named.length) branches.push('r.origin IN (:...origins)');\n if (query.origins.some((o) => o === null)) branches.push('r.origin IS NULL');\n qb.andWhere(\n branches.length ? `(${branches.join(' OR ')})` : '1 = 0',\n named.length ? { origins: named } : {},\n );\n }\n if (query.status) qb.andWhere('r.status = :status', { status: query.status });\n if (query.statuses)\n qb.andWhere(\n query.statuses.length ? 'r.status IN (:...statuses)' : '1 = 0',\n query.statuses.length ? { statuses: query.statuses } : {},\n );\n // `tags` is a JSON-text column; match the quoted token so `etl` doesn't match `etl-foo`. NOTE: a\n // leading-wildcard LIKE on JSON text is NOT index-friendly (no B-tree index can serve `%\"x\"%`), so\n // tag-filtered scans (e.g. singleton admission) are sequential over `durable_runs_workflow_status_idx`'s\n // result set. The `statuses`/`workflow` predicates above bound that scan; if tag scans ever dominate,\n // promote tags to a normalized join table or a JSON/GIN index — a schema change, intentionally not done here.\n if (query.tag) qb.andWhere('r.tags LIKE :tagPattern', { tagPattern: `%\"${query.tag}\"%` });\n if (query.tags) {\n const branches = query.tags.map((_, i) => `r.tags LIKE :tagPattern${i}`);\n qb.andWhere(\n branches.length ? `(${branches.join(' OR ')})` : '1 = 0',\n Object.fromEntries(query.tags.map((t, i) => [`tagPattern${i}`, `%\"${t}\"%`])),\n );\n }\n // Typed/range attribute predicates push DOWN into SQL: each filter becomes an EXISTS against the\n // normalized `durable_run_attributes` side-table (indexed on (key, numValue)/(key, strValue)), so\n // the DB does the filtering AND the LIMIT/OFFSET — no full scan + in-process filter. ANDed: a run\n // must satisfy every filter, so one EXISTS per filter.\n if (query.attributes?.length) {\n query.attributes.forEach((f, i) => this.applyAttributeExists(qb, f, i));\n }\n return qb;\n }\n\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n const qb = this.runQueryBuilder(query);\n qb.orderBy('r.createdAt', 'DESC'); // newest first — recent runs on top in the dashboard\n if (query.limit != null) qb.take(query.limit);\n if (query.offset != null) qb.skip(query.offset);\n const rows = await qb.getMany();\n return rows.map(fromRunEntity);\n }\n\n /** `GROUP BY status, origin` over the same predicates {@link listRuns} pages — one aggregate, so a\n * console can show whole-set counts next to a bounded page instead of downloading every run to\n * count them in the browser. */\n async runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n const rows = await this.runQueryBuilder(query)\n .select('r.status', 'status')\n .addSelect('r.origin', 'origin')\n .addSelect('COUNT(*)', 'count')\n .groupBy('r.status')\n .addGroupBy('r.origin')\n .getRawMany<{ status: RunStatus; origin: string | null; count: number | string }>();\n // Most drivers hand `COUNT(*)` back as a string through `getRawMany`; normalise before merging.\n return mergeRunFacetRows(rows.map((r) => ({ ...r, count: Number(r.count) })));\n }\n\n /** Distinct values of one filter axis over the same predicates {@link listRuns} pages. A run-table\n * column is a `GROUP BY` like {@link runFacets}, exact over the whole matching set; the tag and\n * attribute axes live outside the row (json text / side table) and are counted from a bounded page\n * of runs instead — see `RunValueFacetOptions.scan`. */\n async runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n if (!axisIsRunColumn(axis)) {\n const runs = await this.listRuns({ ...query, limit: opts?.scan ?? RUN_VALUE_FACET_SCAN });\n return runValueFacetsFromRuns(runs, axis, opts);\n }\n const rows = await this.runQueryBuilder(query)\n .select(`r.${axis.field}`, 'value')\n .addSelect('COUNT(*)', 'count')\n .groupBy(`r.${axis.field}`)\n .getRawMany<{ value: string | null; count: number | string }>();\n return mergeRunValueFacetRows(\n rows.map((r) => ({ value: r.value ?? null, count: Number(r.count) })),\n opts,\n );\n }\n\n /** Add one attribute predicate to `qb` as an EXISTS subquery on the side-table. `i` namespaces the\n * bind params so multiple ANDed filters don't collide. */\n private applyAttributeExists(\n qb: SelectQueryBuilder<WorkflowRunEntity>,\n f: AttributeFilter,\n i: number,\n ): void {\n // One comparison for a scalar op, one per member for `in` — ORed inside the single EXISTS, since\n // `in`'s operands may be of mixed types and so land in different typed columns.\n const comparisons = attributePredicateOperands(f);\n const keyParam = `attrKey${i}`;\n // Resolve the PHYSICAL column names from the entity metadata so this raw subquery tracks the\n // configured naming (canonical snake_case by default) instead of hardcoding camelCase — which\n // would break the EXISTS pushdown the moment the table is snake_case.\n const resolve = durableColumnResolver(this.dataSource);\n const q = this.idQuote();\n const wrap = (name: string) => `${q}${name}${q}`;\n const runIdCol = wrap(resolve('durable_run_attributes', 'runId'));\n const keyCol = wrap(resolve('durable_run_attributes', 'key'));\n const runPkCol = wrap(resolve('durable_workflow_runs', 'id'));\n const table = wrap('durable_run_attributes');\n // `<>` (ne) must also exclude rows where the attribute is absent: the missing-key-never-matches\n // contract (see core matchesAttributes). EXISTS already requires the key row to be present, and a\n // row only exists when the value is non-null, so EXISTS(... <> ...) gives exactly ne-with-present.\n const a = `a${i}`;\n const params: Record<string, unknown> = { [keyParam]: f.key };\n const branches = comparisons.map(({ column, comparator, operand }, j) => {\n const valParam = `attrVal${i}_${j}`;\n params[valParam] = operand;\n return `${a}.${wrap(resolve('durable_run_attributes', column))} ${comparator} :${valParam}`;\n });\n if (branches.length === 0) {\n qb.andWhere('1 = 0');\n return;\n }\n const match = branches.length === 1 ? branches[0] : `(${branches.join(' OR ')})`;\n const sql = `EXISTS (SELECT 1 FROM ${table} ${a} WHERE ${a}.${runIdCol} = r.${runPkCol} AND ${a}.${keyCol} = :${keyParam} AND ${match})`;\n qb.andWhere(sql, params);\n }\n\n /** The identifier quote char for the active driver (MySQL backtick, others double-quote). */\n private idQuote(): string {\n const type = String(this.dataSource.options.type);\n return type === 'mysql' || type === 'mariadb' || type === 'aurora-mysql' ? '`' : '\"';\n }\n\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n const rows = await this.checkpoints().find({ where: { runId }, order: { seq: 'ASC' } });\n return rows.map(fromCheckpointEntity);\n }\n\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n const e = await this.checkpoints().findOne({ where: { runId, name }, order: { seq: 'DESC' } });\n return e ? fromCheckpointEntity(e) : undefined;\n }\n\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n if (prefixes.length === 0) return [];\n const rows = await this.checkpoints().find({\n where: prefixes.map((p) => ({ runId, name: Like(`${p}%`) })),\n order: { seq: 'ASC' },\n });\n return rows.map(fromCheckpointEntity);\n }\n\n async putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n await this.waiters().save({\n token: waiter.token,\n runId: waiter.runId,\n seq: waiter.seq,\n parallelGroup: waiter.parallelGroup ?? null,\n });\n }\n\n async listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n const rows = await this.waiters().find({ where: { token: Like(`${prefix}%`) } });\n return rows.map((e) => ({\n token: e.token,\n runId: e.runId,\n seq: e.seq,\n parallelGroup: e.parallelGroup ?? undefined,\n }));\n }\n\n async takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n const e = await this.waiters().findOneBy({ token });\n if (!e) return null;\n const waiter: SignalWaiter = {\n token: e.token,\n runId: e.runId,\n seq: e.seq,\n parallelGroup: e.parallelGroup ?? undefined,\n };\n await this.waiters().delete({ token });\n return waiter;\n }\n\n async removeSignalWaiter(waiter: SignalWaiter): Promise<void> {\n // Exact-match delete (token AND runId AND seq) — a plain `delete({ token })` would remove\n // whatever row currently owns the token, even if a different run has since claimed it.\n await this.waiters().delete({ token: waiter.token, runId: waiter.runId, seq: waiter.seq });\n }\n\n async bufferSignal(token: string, payload: unknown): Promise<void> {\n await this.buffered().save({ token, payload: payload ?? null });\n }\n\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const e = await this.buffered().findOne({ where: { token }, order: { id: 'ASC' } });\n if (!e) return null;\n await this.buffered().delete({ id: e.id });\n return { payload: e.payload ?? undefined };\n }\n\n async bufferEvent(input: {\n name: string;\n payload: unknown;\n id: string;\n publishedAt: number;\n }): Promise<void> {\n await this.bufferedEvents().save({\n id: input.id,\n name: input.name,\n payload: input.payload ?? null,\n publishedAt: new Date(input.publishedAt),\n });\n }\n\n async listBufferedEvents(\n name: string,\n limit: number,\n ): Promise<Array<{ id: string; payload: unknown; publishedAt: number }>> {\n const rows = await this.bufferedEvents().find({\n where: { name },\n order: { publishedAt: 'ASC' }, // oldest first\n take: limit,\n });\n return rows.map((e) => ({\n id: e.id,\n payload: e.payload ?? undefined,\n publishedAt: e.publishedAt.getTime(),\n }));\n }\n\n async removeBufferedEvent(id: string): Promise<boolean> {\n const result = await this.bufferedEvents().delete({ id });\n return result.affected === 1;\n }\n}\n\nfunction toRunEntity(run: WorkflowRun): WorkflowRunEntity {\n return {\n id: run.id,\n workflow: run.workflow,\n workflowVersion: run.workflowVersion,\n status: run.status,\n input: run.input ?? null,\n output: run.output ?? null,\n error: run.error ?? null,\n ...(run.wakeAt == null ? {} : { wakeAt: new Date(run.wakeAt) }),\n lockedBy: run.lockedBy ?? null,\n ...(run.lockedUntil == null ? {} : { lockedUntil: new Date(run.lockedUntil) }),\n awaitingDecisionTaskId: run.awaitingDecisionTaskId ?? null,\n ...(run.recoveryAttempts === undefined ? {} : { recoveryAttempts: run.recoveryAttempts }),\n tags: run.tags ?? null,\n searchAttributes: run.searchAttributes ?? null,\n priority: run.priority ?? null,\n // An absent namespace is persisted as `'default'` (what the core `WorkflowRun.namespace` docblock\n // promises), so the column is always a value a worker can match on — the opposite of `origin`\n // below, where NULL is the only honest answer.\n namespace: run.namespace ?? 'default',\n // Absent origin stays SQL NULL — \"unknown\", never coerced into a real-looking library name.\n origin: run.origin ?? null,\n createdAt: run.createdAt,\n updatedAt: run.updatedAt,\n };\n}\n\nfunction fromRunEntity(e: WorkflowRunEntity): WorkflowRun {\n return {\n id: e.id,\n workflow: e.workflow,\n workflowVersion: e.workflowVersion,\n status: e.status,\n input: e.input ?? undefined,\n output: e.output ?? undefined,\n error: (e.error ?? undefined) as StepError | undefined,\n wakeAt: e.wakeAt == null ? undefined : e.wakeAt.getTime(),\n lockedBy: e.lockedBy ?? undefined,\n lockedUntil: e.lockedUntil == null ? undefined : e.lockedUntil.getTime(),\n awaitingDecisionTaskId: e.awaitingDecisionTaskId ?? undefined,\n recoveryAttempts: e.recoveryAttempts ?? undefined,\n tags: e.tags ?? undefined,\n searchAttributes: e.searchAttributes ?? undefined,\n priority: e.priority ?? undefined,\n // Reported verbatim. A row can only be NULL here if the column was added by hand without the\n // `'default'` back-fill the schema helper applies, and reading it back as `'default'` would then\n // LIE: the row would claim a namespace that its own SQL predicate does not match.\n namespace: e.namespace,\n // NULL (a row written before the column existed) surfaces as `undefined` = unknown origin.\n origin: e.origin ?? undefined,\n createdAt: e.createdAt,\n updatedAt: e.updatedAt,\n };\n}\n\nfunction toCheckpointEntity(cp: StepCheckpoint): StepCheckpointEntity {\n return {\n runId: cp.runId,\n seq: cp.seq,\n name: cp.name,\n kind: cp.kind,\n stepId: cp.stepId,\n status: cp.status,\n input: cp.input ?? null,\n output: cp.output ?? null,\n error: cp.error ?? null,\n events: cp.events ?? null,\n attempts: cp.attempts,\n workerGroup: cp.workerGroup ?? null,\n parallelGroup: cp.parallelGroup ?? null,\n ...(cp.wakeAt == null ? {} : { wakeAt: new Date(cp.wakeAt) }),\n enqueuedAt: cp.enqueuedAt,\n startedAt: cp.startedAt,\n finishedAt: cp.finishedAt,\n };\n}\n\nfunction fromCheckpointEntity(e: StepCheckpointEntity): StepCheckpoint {\n return {\n runId: e.runId,\n seq: e.seq,\n name: e.name,\n kind: e.kind,\n stepId: e.stepId,\n status: e.status,\n input: e.input ?? undefined,\n output: e.output ?? undefined,\n error: (e.error ?? undefined) as StepError | undefined,\n events: (e.events ?? undefined) as StepEvent[] | undefined,\n attempts: e.attempts,\n workerGroup: e.workerGroup ?? undefined,\n parallelGroup: e.parallelGroup ?? undefined,\n wakeAt: e.wakeAt == null ? undefined : e.wakeAt.getTime(),\n // Older rows predate enqueuedAt; treat the worker start as enqueue time (queue-wait reads zero).\n enqueuedAt: e.enqueuedAt ?? e.startedAt,\n startedAt: e.startedAt,\n finishedAt: e.finishedAt,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;ACCA,qBAAoD;AAU7C,SAASA,gBAA6BC,KAAcC,OAAa;AACtE,MAAID,OAAO,KAAM,QAAOE;AAExB,MAAI,OAAOF,QAAQ,SAAU,QAAOA;AACpC,MAAI;AACF,WAAOG,KAAKC,MAAMJ,GAAAA;EACpB,SAASK,KAAK;AACZC,YAAQC,KACN,kCAAkCN,KAAAA,oCAC/BI,IAAcG,OAAO,EACtB;AAEJ,WAAON;EACT;AACF;AAdgBH;AAqBhB,SAASU,sBAAsBR,OAAa;AAC1C,SAAO;IACLS,IAAI,wBAACC,UAAoBA,SAAS,OAAO,OAAOR,KAAKS,UAAUD,KAAAA,GAA3D;IACJE,MAAM,wBAACF,UAAmBZ,gBAAgBY,OAAOV,KAAAA,GAA3C;EACR;AACF;AALSQ;AAqBT,SAASK,UAAUC,UAAgB;AACjC,SAAOA,SAASC,QAAQ,UAAU,CAACC,MAAM,IAAIA,EAAEC,YAAW,CAAA,EAAI;AAChE;AAFSJ;AAKF,SAASK,YAAYC,QAA2B;AACrD,MAAIA,WAAW,aAAc,QAAON;AACpC,MAAIM,WAAW,WAAY,QAAO,CAACL,aAAaA;AAChD,SAAOK;AACT;AAJgBD;AAUT,IAAME,oBAAN,MAAMA;EAnEb,OAmEaA;;;EACXC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;AACF;AAEO,IAAMC,uBAAN,MAAMA;EAzFb,OAyFaA;;;EACXC;EACAC;EACAC;EACAC;EACAC;EACArB;EACAC;EACAC;EACAC;EACAmB;EACAC;EACAC;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BC,OAAOoC,GAAGpC,SAAS;IACnB+J,QAAQ3H,GAAG2H,UAAU;IACrBC,UAAU5H,GAAG4H;IACbC,aAAa7H,GAAG6H,eAAe;IAC/BjB,eAAe5G,GAAG4G,iBAAiB;IACnC,GAAI5G,GAAGnC,UAAU,OAAO,CAAC,IAAI;MAAEA,QAAQ,IAAIC,KAAKkC,GAAGnC,MAAM;IAAE;IAC3DiK,YAAY9H,GAAG8H;IACfC,WAAW/H,GAAG+H;IACdC,YAAYhI,GAAGgI;EACjB;AACF;AApBSrI;AAsBT,SAASJ,qBAAqBN,GAAuB;AACnD,SAAO;IACL3C,OAAO2C,EAAE3C;IACTgD,KAAKL,EAAEK;IACP0F,MAAM/F,EAAE+F;IACRyC,MAAMxI,EAAEwI;IACRC,QAAQzI,EAAEyI;IACVjK,QAAQwB,EAAExB;IACVC,OAAOuB,EAAEvB,SAAS0C;IAClBzC,QAAQsB,EAAEtB,UAAUyC;IACpBxC,OAAQqB,EAAErB,SAASwC;IACnBuH,QAAS1I,EAAE0I,UAAUvH;IACrBwH,UAAU3I,EAAE2I;IACZC,aAAa5I,EAAE4I,eAAezH;IAC9BwG,eAAe3H,EAAE2H,iBAAiBxG;IAClCvC,QAAQoB,EAAEpB,UAAU,OAAOuC,SAAYnB,EAAEpB,OAAO0J,QAAO;;IAEvDO,YAAY7I,EAAE6I,cAAc7I,EAAE8I;IAC9BA,WAAW9I,EAAE8I;IACbC,YAAY/I,EAAE+I;EAChB;AACF;AArBSzI;","names":["parseJsonColumn","raw","field","undefined","JSON","parse","err","console","warn","message","jsonColumnTransformer","to","value","stringify","from","snakeCase","property","replace","c","toLowerCase","columnNamer","naming","WorkflowRunEntity","id","workflow","workflowVersion","status","input","output","error","wakeAt","lockedBy","lockedUntil","awaitingDecisionTaskId","recoveryAttempts","tags","searchAttributes","priority","namespace","origin","createdAt","updatedAt","StepCheckpointEntity","runId","seq","name","kind","stepId","events","attempts","workerGroup","parallelGroup","enqueuedAt","startedAt","finishedAt","RunAttributeEntity","key","strValue","numValue","SignalWaiterEntity","token","BufferedSignalEntity","payload","BufferedEventEntity","publishedAt","durableEntities","options","col","workflowRuns","EntitySchema","target","tableName","columns","type","primary","nullable","transformer","Date","default","stepCheckpoints","runAttributes","signalWaiters","bufferedSignals","Number","generated","bufferedEvents","ENTITIES","JSON_BLOB_COLUMNS","durable_workflow_runs","durable_step_checkpoints","TABLE_TO_ENTITY","WorkflowRunEntity","StepCheckpointEntity","durable_run_attributes","RunAttributeEntity","durable_signal_waiters","SignalWaiterEntity","durable_buffered_signals","BufferedSignalEntity","durable_buffered_events","BufferedEventEntity","durableManagedTables","Object","keys","durableColumnResolver","dataSource","table","property","entity","Error","meta","getMetadata","column","findColumnWithPropertyName","databaseName","jsonBlobColumnType","isMysql","buildWidenStatements","quote","col","out","props","entries","prop","push","ensureTypeOrmDurableSchema","q","id","driver","escape","resolve","type","String","options","isPg","isSqlite","str","txt","int","ts","nsCol","runs","checkpoints","runAttributes","waiters","buffered","bufferedEvents","runsCol","cpCol","attrCol","waiterCol","bufCol","bevCol","num","bufferedId","tables","additive","runner","createQueryRunner","sql","query","have","existingColumns","colType","has","indexes","name","target","release","d","rows","Set","map","r","scope","placeholder","COLUMN_NAME","import_typeorm","TypeOrmStateStore","dataSource","ensureSchema","ensureTypeOrmDurableSchema","runs","getRepository","WorkflowRunEntity","checkpoints","StepCheckpointEntity","waiters","SignalWaiterEntity","buffered","BufferedSignalEntity","bufferedEvents","BufferedEventEntity","attributes","RunAttributeEntity","reindexAttributes","runId","em","repo","delete","rows","normalizeAttributeRows","length","insert","createRun","run","save","toRunEntity","id","searchAttributes","updateRun","patch","update","workflow","workflowVersion","status","input","output","error","wakeAt","Date","lockedBy","lockedUntil","awaitingDecisionTaskId","recoveryAttempts","tags","priority","namespace","origin","createdAt","updatedAt","result","createQueryBuilder","set","where","execute","affected","Error","getRun","e","findOneBy","fromRunEntity","deleteRun","getCheckpoint","seq","fromCheckpointEntity","saveCheckpoint","checkpoint","entity","toCheckpointEntity","upsert","transaction","work","raw","cp","listIncompleteRuns","findBy","In","undefined","map","listPendingRuns","limit","find","order","take","listDueTimers","nowMs","LessThanOrEqual","tryLockRun","owner","leaseUntilMs","andWhere","Brackets","qb","IsNull","orWhere","releaseRunLock","renewRunLock","runQueryBuilder","query","workflows","namespaces","origins","named","filter","o","branches","push","some","join","statuses","tag","tagPattern","_","i","Object","fromEntries","t","forEach","f","applyAttributeExists","listRuns","orderBy","offset","skip","getMany","runFacets","select","addSelect","groupBy","addGroupBy","getRawMany","mergeRunFacetRows","r","count","Number","runValueFacets","axis","opts","axisIsRunColumn","scan","RUN_VALUE_FACET_SCAN","runValueFacetsFromRuns","field","mergeRunValueFacetRows","value","comparisons","attributePredicateOperands","keyParam","resolve","durableColumnResolver","q","idQuote","wrap","name","runIdCol","keyCol","runPkCol","table","a","params","key","column","comparator","operand","j","valParam","match","sql","type","String","options","listCheckpoints","getLatestCheckpointByName","findOne","listCheckpointsByNamePrefix","prefixes","p","Like","putSignalWaiter","waiter","token","parallelGroup","listSignalWaiters","prefix","takeSignalWaiter","removeSignalWaiter","bufferSignal","payload","takeBufferedSignal","bufferEvent","publishedAt","listBufferedEvents","getTime","removeBufferedEvent","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { StepKind, RunStatus, StateStore, WorkflowRun, StepCheckpoint, RunQuery, SignalWaiter } from '@dudousxd/nestjs-durable-core';
|
|
1
|
+
import { StepKind, RunStatus, StateStore, WorkflowRun, StepCheckpoint, RunQuery, RunFacetQuery, RunFacetRow, RunValueAxis, RunValueFacetOptions, RunValueFacetRow, SignalWaiter } from '@dudousxd/nestjs-durable-core';
|
|
2
2
|
import { EntitySchema, DataSource } from 'typeorm';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -206,7 +206,20 @@ declare class TypeOrmStateStore implements StateStore {
|
|
|
206
206
|
tryLockRun(runId: string, owner: string, leaseUntilMs: number, nowMs: number): Promise<boolean>;
|
|
207
207
|
releaseRunLock(runId: string): Promise<void>;
|
|
208
208
|
renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean>;
|
|
209
|
+
/** A query builder (root alias `r`) carrying the predicates every run query shares —
|
|
210
|
+
* {@link listRuns} orders + pages it, {@link runFacets} groups it, so a facet count and the page
|
|
211
|
+
* it labels are always taken over the same set. */
|
|
212
|
+
private runQueryBuilder;
|
|
209
213
|
listRuns(query: RunQuery): Promise<WorkflowRun[]>;
|
|
214
|
+
/** `GROUP BY status, origin` over the same predicates {@link listRuns} pages — one aggregate, so a
|
|
215
|
+
* console can show whole-set counts next to a bounded page instead of downloading every run to
|
|
216
|
+
* count them in the browser. */
|
|
217
|
+
runFacets(query: RunFacetQuery): Promise<RunFacetRow[]>;
|
|
218
|
+
/** Distinct values of one filter axis over the same predicates {@link listRuns} pages. A run-table
|
|
219
|
+
* column is a `GROUP BY` like {@link runFacets}, exact over the whole matching set; the tag and
|
|
220
|
+
* attribute axes live outside the row (json text / side table) and are counted from a bounded page
|
|
221
|
+
* of runs instead — see `RunValueFacetOptions.scan`. */
|
|
222
|
+
runValueFacets(axis: RunValueAxis, query: RunFacetQuery, opts?: RunValueFacetOptions): Promise<RunValueFacetRow[]>;
|
|
210
223
|
/** Add one attribute predicate to `qb` as an EXISTS subquery on the side-table. `i` namespaces the
|
|
211
224
|
* bind params so multiple ANDed filters don't collide. */
|
|
212
225
|
private applyAttributeExists;
|