@dudousxd/nestjs-durable-store-mikro-orm 0.13.3 → 0.15.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 +107 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +108 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -117,6 +117,26 @@ function durableEntities(options = {}) {
|
|
|
117
117
|
const workflowRuns = new import_core.EntitySchema({
|
|
118
118
|
class: WorkflowRunEntity,
|
|
119
119
|
tableName: "durable_workflow_runs",
|
|
120
|
+
// Indexes mirror the Prisma adapter so a store swap keeps the same plan. The poller hits these
|
|
121
|
+
// every tick: `(status, wakeAt)` serves both the due-timer scan (status='suspended' AND wakeAt<=now)
|
|
122
|
+
// and, via its `status` prefix, the pending/incomplete status lookups; `(workflow, status)` serves
|
|
123
|
+
// the per-workflow timeout sweep. Without them every poll is a full scan of a table that only grows.
|
|
124
|
+
indexes: [
|
|
125
|
+
{
|
|
126
|
+
name: "durable_workflow_runs_status_wake_at_idx",
|
|
127
|
+
properties: [
|
|
128
|
+
"status",
|
|
129
|
+
"wakeAt"
|
|
130
|
+
]
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
name: "durable_workflow_runs_workflow_status_idx",
|
|
134
|
+
properties: [
|
|
135
|
+
"workflow",
|
|
136
|
+
"status"
|
|
137
|
+
]
|
|
138
|
+
}
|
|
139
|
+
],
|
|
120
140
|
properties: {
|
|
121
141
|
id: {
|
|
122
142
|
type: "string",
|
|
@@ -277,6 +297,24 @@ function durableEntities(options = {}) {
|
|
|
277
297
|
const runAttributes = new import_core.EntitySchema({
|
|
278
298
|
class: RunAttributeEntity,
|
|
279
299
|
tableName: "durable_run_attributes",
|
|
300
|
+
// The search-attribute EXISTS join (see the class docstring) pushes equality/range predicates down
|
|
301
|
+
// onto `(key, numValue)` / `(key, strValue)`; mirror the Prisma adapter so those scans stay indexed.
|
|
302
|
+
indexes: [
|
|
303
|
+
{
|
|
304
|
+
name: "durable_run_attributes_key_num_idx",
|
|
305
|
+
properties: [
|
|
306
|
+
"key",
|
|
307
|
+
"numValue"
|
|
308
|
+
]
|
|
309
|
+
},
|
|
310
|
+
{
|
|
311
|
+
name: "durable_run_attributes_key_str_idx",
|
|
312
|
+
properties: [
|
|
313
|
+
"key",
|
|
314
|
+
"strValue"
|
|
315
|
+
]
|
|
316
|
+
}
|
|
317
|
+
],
|
|
280
318
|
properties: {
|
|
281
319
|
runId: {
|
|
282
320
|
type: "string",
|
|
@@ -365,12 +403,12 @@ var DURABLE_TABLE_NAMES = /* @__PURE__ */ new Set([
|
|
|
365
403
|
"durable_buffered_signals"
|
|
366
404
|
]);
|
|
367
405
|
function targetTable(statement) {
|
|
368
|
-
const match = statement.match(/^(?:create|alter)\s+table\s+(?:if\s+not\s+exists\s+)?[`"']?([\w$]+)[`"']?/i);
|
|
406
|
+
const match = statement.match(/^(?:create\s+(?:unique\s+)?index\s+.+?\s+on\s+|(?:create|alter)\s+table\s+(?:if\s+not\s+exists\s+)?)[`"']?([\w$]+)[`"']?/i);
|
|
369
407
|
return match?.[1]?.toLowerCase();
|
|
370
408
|
}
|
|
371
409
|
__name(targetTable, "targetTable");
|
|
372
410
|
function isRequiredStructure(statement) {
|
|
373
|
-
return /\b(?:create\s+table|add\s+(?:column|index|constraint|key|unique|fulltext))\b/i.test(statement);
|
|
411
|
+
return /\b(?:create\s+table|create\s+(?:unique\s+)?index|add\s+(?:column|index|constraint|key|unique|fulltext))\b/i.test(statement);
|
|
374
412
|
}
|
|
375
413
|
__name(isRequiredStructure, "isRequiredStructure");
|
|
376
414
|
async function ensureMikroOrmDurableSchema(orm) {
|
|
@@ -494,6 +532,73 @@ var MikroOrmStateStore = class {
|
|
|
494
532
|
id: runId
|
|
495
533
|
});
|
|
496
534
|
}
|
|
535
|
+
async pruneTerminalRuns(policy, nowMs, limit) {
|
|
536
|
+
if (policy.statuses.length === 0 || limit <= 0) return 0;
|
|
537
|
+
const em = this.orm.em.fork();
|
|
538
|
+
const status = {
|
|
539
|
+
$in: policy.statuses
|
|
540
|
+
};
|
|
541
|
+
const ids = /* @__PURE__ */ new Set();
|
|
542
|
+
if (policy.maxAge != null) {
|
|
543
|
+
const cutoff = new Date(nowMs - (0, import_nestjs_durable_core.parseDuration)(policy.maxAge));
|
|
544
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
545
|
+
status,
|
|
546
|
+
updatedAt: {
|
|
547
|
+
$lt: cutoff
|
|
548
|
+
}
|
|
549
|
+
}, {
|
|
550
|
+
fields: [
|
|
551
|
+
"id"
|
|
552
|
+
],
|
|
553
|
+
orderBy: {
|
|
554
|
+
updatedAt: "asc"
|
|
555
|
+
},
|
|
556
|
+
limit
|
|
557
|
+
});
|
|
558
|
+
for (const r of rows) ids.add(r.id);
|
|
559
|
+
}
|
|
560
|
+
if (policy.maxCount != null && ids.size < limit) {
|
|
561
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
562
|
+
status
|
|
563
|
+
}, {
|
|
564
|
+
fields: [
|
|
565
|
+
"id"
|
|
566
|
+
],
|
|
567
|
+
orderBy: {
|
|
568
|
+
updatedAt: "desc",
|
|
569
|
+
id: "desc"
|
|
570
|
+
},
|
|
571
|
+
limit,
|
|
572
|
+
offset: policy.maxCount
|
|
573
|
+
});
|
|
574
|
+
for (const r of rows) {
|
|
575
|
+
ids.add(r.id);
|
|
576
|
+
if (ids.size >= limit) break;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
if (ids.size === 0) return 0;
|
|
580
|
+
const idList = [
|
|
581
|
+
...ids
|
|
582
|
+
].slice(0, limit);
|
|
583
|
+
const runId = {
|
|
584
|
+
$in: idList
|
|
585
|
+
};
|
|
586
|
+
await em.transactional(async (tem) => {
|
|
587
|
+
await tem.nativeDelete(StepCheckpointEntity, {
|
|
588
|
+
runId
|
|
589
|
+
});
|
|
590
|
+
await tem.nativeDelete(SignalWaiterEntity, {
|
|
591
|
+
runId
|
|
592
|
+
});
|
|
593
|
+
await tem.nativeDelete(RunAttributeEntity, {
|
|
594
|
+
runId
|
|
595
|
+
});
|
|
596
|
+
await tem.nativeDelete(WorkflowRunEntity, {
|
|
597
|
+
id: runId
|
|
598
|
+
});
|
|
599
|
+
});
|
|
600
|
+
return idList.length;
|
|
601
|
+
}
|
|
497
602
|
async getCheckpoint(runId, seq) {
|
|
498
603
|
const em = this.orm.em.fork();
|
|
499
604
|
const entity = await em.findOne(StepCheckpointEntity, {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/entities.ts","../src/mikro-orm-state-store.ts","../src/schema.ts"],"sourcesContent":["export * from './entities';\nexport * from './mikro-orm-state-store';\nexport * from './schema';\n","import type { RunStatus, StepKind } from '@dudousxd/nestjs-durable-core';\nimport { EntitySchema } from '@mikro-orm/core';\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 TypeORM,\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\nfunction 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 `em.create`/`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;\n lockedUntil?: Date;\n recoveryAttempts?: number;\n tags?: string[] | null;\n searchAttributes?: Record<string, string | number | boolean> | null;\n priority?: number | 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;\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}\n\nexport class BufferedSignalEntity {\n id!: number;\n token!: string;\n payload?: unknown;\n}\n\n/**\n * Build the durable MikroORM entity schemas with column names pinned per `naming` (default\n * `'snake_case'`). Register the result in your MikroORM config / `MikroOrmModule.forFeature`.\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 class: WorkflowRunEntity,\n tableName: 'durable_workflow_runs',\n properties: {\n id: { type: 'string', primary: true, fieldName: col('id') },\n workflow: { type: 'string', fieldName: col('workflow') },\n workflowVersion: { type: 'string', fieldName: col('workflowVersion') },\n status: { type: 'string', fieldName: col('status') },\n input: { type: 'json', nullable: true, fieldName: col('input') },\n output: { type: 'json', nullable: true, fieldName: col('output') },\n error: { type: 'json', nullable: true, fieldName: col('error') },\n wakeAt: { type: 'Date', nullable: true, fieldName: col('wakeAt') },\n lockedBy: { type: 'string', nullable: true, fieldName: col('lockedBy') },\n lockedUntil: { type: 'Date', nullable: true, fieldName: col('lockedUntil') },\n recoveryAttempts: { type: 'integer', nullable: true, fieldName: col('recoveryAttempts') },\n tags: { type: 'json', nullable: true, fieldName: col('tags') },\n searchAttributes: { type: 'json', nullable: true, fieldName: col('searchAttributes') },\n priority: { type: 'integer', nullable: true, fieldName: col('priority') },\n createdAt: { type: 'Date', fieldName: col('createdAt') },\n updatedAt: { type: 'Date', fieldName: col('updatedAt') },\n },\n });\n\n const stepCheckpoints = new EntitySchema<StepCheckpointEntity>({\n class: StepCheckpointEntity,\n tableName: 'durable_step_checkpoints',\n properties: {\n runId: { type: 'string', primary: true, fieldName: col('runId') },\n seq: { type: 'integer', primary: true, fieldName: col('seq') },\n name: { type: 'string', fieldName: col('name') },\n kind: { type: 'string', fieldName: col('kind') },\n stepId: { type: 'string', fieldName: col('stepId') },\n status: { type: 'string', fieldName: col('status') },\n input: { type: 'json', nullable: true, fieldName: col('input') },\n output: { type: 'json', nullable: true, fieldName: col('output') },\n error: { type: 'json', nullable: true, fieldName: col('error') },\n events: { type: 'json', nullable: true, fieldName: col('events') },\n attempts: { type: 'integer', fieldName: col('attempts') },\n workerGroup: { type: 'string', nullable: true, fieldName: col('workerGroup') },\n wakeAt: { type: 'Date', nullable: true, fieldName: col('wakeAt') },\n enqueuedAt: { type: 'Date', nullable: true, fieldName: col('enqueuedAt') },\n startedAt: { type: 'Date', fieldName: col('startedAt') },\n finishedAt: { type: 'Date', fieldName: col('finishedAt') },\n },\n });\n\n const runAttributes = new EntitySchema<RunAttributeEntity>({\n class: RunAttributeEntity,\n tableName: 'durable_run_attributes',\n properties: {\n runId: { type: 'string', primary: true, fieldName: col('runId') },\n key: { type: 'string', primary: true, fieldName: col('key') },\n strValue: { type: 'string', nullable: true, fieldName: col('strValue') },\n // `float`/`double` is portable across SQLite/MySQL/Postgres for numeric range scans.\n numValue: { type: 'float', nullable: true, fieldName: col('numValue') },\n },\n });\n\n const signalWaiters = new EntitySchema<SignalWaiterEntity>({\n class: SignalWaiterEntity,\n tableName: 'durable_signal_waiters',\n properties: {\n token: { type: 'string', primary: true, fieldName: col('token') },\n runId: { type: 'string', fieldName: col('runId') },\n seq: { type: 'integer', fieldName: col('seq') },\n },\n });\n\n const bufferedSignals = new EntitySchema<BufferedSignalEntity>({\n class: BufferedSignalEntity,\n tableName: 'durable_buffered_signals',\n properties: {\n id: { type: 'integer', primary: true, autoincrement: true, fieldName: col('id') },\n token: { type: 'string', index: true, fieldName: col('token') },\n payload: { type: 'json', nullable: true, fieldName: col('payload') },\n },\n });\n\n return [workflowRuns, stepCheckpoints, runAttributes, signalWaiters, bufferedSignals];\n}\n\n/** Durable entity schemas with the canonical `'snake_case'` column names. */\nexport const ENTITIES = durableEntities();\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 type { EntityManager, MikroORM } from '@mikro-orm/core';\n\n/** Minimal structural surface of the SQL EntityManager's QueryBuilder (from `@mikro-orm/knex`),\n * typed here so the adapter needn't add a hard dependency on the knex types — a real SQL-driver EM\n * satisfies it at runtime. */\ninterface DurableQueryBuilder<T> {\n where(cond: Record<string, unknown>): DurableQueryBuilder<T>;\n andWhere(cond: string): DurableQueryBuilder<T>;\n orderBy(cond: Record<string, unknown>): DurableQueryBuilder<T>;\n limit(n: number): DurableQueryBuilder<T>;\n offset(n: number): DurableQueryBuilder<T>;\n getResultList(): Promise<T[]>;\n}\ntype SqlEm = EntityManager & {\n createQueryBuilder<T>(entity: unknown, alias: string): DurableQueryBuilder<T>;\n};\n\n/** Resolved side-table column names (per the active naming strategy) for the raw EXISTS pushdown. */\ninterface AttributeColumns {\n table: string;\n /** Side-table FK column (the run id on `durable_run_attributes`). */\n runId: string;\n /** Run table PK column (the `id` on `durable_workflow_runs`) used for the outer correlation. */\n runPk: string;\n key: string;\n strValue: string;\n numValue: string;\n}\nimport {\n BufferedSignalEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n StepCheckpointEntity,\n WorkflowRunEntity,\n} from './entities';\nimport { ensureMikroOrmDurableSchema } from './schema';\n\n/**\n * MikroORM-backed `StateStore`. Works on any MikroORM driver — Postgres, MySQL, SQLite (tested);\n * timestamps and `wakeAt` use native datetime columns. Each operation runs on a forked\n * EntityManager so it owns its unit of work.\n */\nexport class MikroOrmStateStore implements StateStore {\n constructor(private readonly orm: MikroORM) {}\n\n async ensureSchema(): Promise<void> {\n await ensureMikroOrmDurableSchema(this.orm);\n }\n\n async createRun(run: WorkflowRun): Promise<void> {\n const em = this.orm.em.fork();\n em.create(WorkflowRunEntity, toRunEntity(run));\n await em.flush();\n await this.reindexAttributes(run.id, run.searchAttributes);\n }\n\n async updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n const em = this.orm.em.fork();\n const entity = await em.findOneOrFail(WorkflowRunEntity, { id: runId });\n Object.assign(entity, toRunEntity({ ...fromRunEntity(entity), ...patch } as WorkflowRun));\n await em.flush();\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 /** 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 forked?: EntityManager,\n ): Promise<void> {\n const em = forked ?? this.orm.em.fork();\n await em.nativeDelete(RunAttributeEntity, { runId });\n const rows = normalizeAttributeRows(runId, attributes);\n if (rows.length) await em.insertMany(RunAttributeEntity, rows);\n }\n\n async getRun(runId: string): Promise<WorkflowRun | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(WorkflowRunEntity, { id: runId });\n return entity ? fromRunEntity(entity) : null;\n }\n\n async deleteRun(runId: string): Promise<void> {\n const em = this.orm.em.fork();\n // Children first, then the run row — checkpoints, signal waiters, and the normalized\n // attribute side-table, so nothing dangles after the run is gone.\n await em.nativeDelete(StepCheckpointEntity, { runId });\n await em.nativeDelete(SignalWaiterEntity, { runId });\n await em.nativeDelete(RunAttributeEntity, { runId });\n await em.nativeDelete(WorkflowRunEntity, { id: runId });\n }\n\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(StepCheckpointEntity, { runId, seq });\n return entity ? fromCheckpointEntity(entity) : null;\n }\n\n async saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n const em = this.orm.em.fork();\n await em.upsert(StepCheckpointEntity, toCheckpointEntity(checkpoint));\n await em.flush();\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.orm.em.fork().transactional(async (em) =>\n work({\n raw: em,\n saveCheckpoint: async (cp) => {\n await em.upsert(StepCheckpointEntity, toCheckpointEntity(cp));\n },\n }),\n );\n }\n\n async listIncompleteRuns(): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(WorkflowRunEntity, { status: { $in: ['running', 'cancelling'] } });\n return rows.map(fromRunEntity);\n }\n\n async listPendingRuns(limit: number): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(\n WorkflowRunEntity,\n { status: 'pending' },\n { orderBy: { createdAt: 'asc' }, limit }, // FIFO dispatch\n );\n return rows.map(fromRunEntity);\n }\n\n async listDueTimers(nowMs: number): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(WorkflowRunEntity, {\n status: 'suspended',\n wakeAt: { $ne: null, $lte: new Date(nowMs) },\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 em = this.orm.em.fork();\n const affected = await em.nativeUpdate(\n WorkflowRunEntity,\n { id: runId, $or: [{ lockedUntil: null }, { lockedUntil: { $lte: new Date(nowMs) } }] },\n { lockedBy: owner, lockedUntil: new Date(leaseUntilMs) },\n );\n return affected === 1;\n }\n\n async releaseRunLock(runId: string): Promise<void> {\n const em = this.orm.em.fork();\n await em.nativeUpdate(WorkflowRunEntity, { id: runId }, { lockedBy: null, lockedUntil: null });\n }\n\n async renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n const em = this.orm.em.fork();\n const affected = await em.nativeUpdate(\n WorkflowRunEntity,\n { id: runId, lockedBy: owner },\n { lockedUntil: new Date(leaseUntilMs) },\n );\n return affected === 1;\n }\n\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const where: Record<string, unknown> = {};\n if (query.workflow) where.workflow = query.workflow;\n // `status IN (...)`; an empty set matches nothing (mirrors the in-memory store). When both the\n // single `status` and `statuses` are set, AND them so the narrower set wins.\n if (query.status && query.statuses) {\n where.$and = [{ status: query.status }, { status: { $in: query.statuses } }];\n } else if (query.status) {\n where.status = query.status;\n } else if (query.statuses) {\n where.status = { $in: query.statuses };\n }\n const orderBy = { createdAt: 'desc' as const }; // newest first — recent runs on top in the dashboard\n // `tags`/attributes need raw SQL pushed through the QueryBuilder:\n // - tag: `tags` is a JSON column (native json/jsonb on PG/MySQL), and MikroORM JSON-serializes a\n // `{ $like }` operand (wrapping/escaping the LIKE pattern) so a plain where corrupts it to no\n // matches. A raw LIKE on the column-as-text matches the quoted token so `etl` doesn't match\n // `etl-foo`. Postgres `jsonb` rejects `LIKE` directly, so cast to text per dialect.\n // - attributes: each filter becomes a raw EXISTS against the normalized side-table, so the DB\n // filters AND paginates — no full scan + in-process filter (ANDed: one EXISTS per filter).\n // Use a QueryBuilder with a fixed root alias `r` so the raw correlations are stable across drivers.\n if (query.tag || query.attributes?.length) {\n const quote = this.idQuote(em);\n const cols = this.attributeColumns(em);\n const qb = (em as SqlEm)\n .createQueryBuilder<WorkflowRunEntity>(WorkflowRunEntity, 'r')\n .where(where)\n .orderBy(orderBy);\n if (query.tag) {\n const tagsCol = this.tagsColumn(em);\n const pattern = `%\"${query.tag.replace(/'/g, \"''\")}\"%`;\n const colExpr = this.jsonAsText(em, `${quote('r')}.${quote(tagsCol)}`);\n qb.andWhere(`${colExpr} LIKE '${pattern}'`);\n }\n for (const f of query.attributes ?? []) {\n qb.andWhere(this.attributeExistsSql(f, quote, 'r', cols));\n }\n if (query.limit != null) qb.limit(query.limit);\n if (query.offset != null) qb.offset(query.offset);\n const rows = await qb.getResultList();\n return rows.map(fromRunEntity);\n }\n const rows = await em.find(WorkflowRunEntity, where, {\n ...(query.limit != null ? { limit: query.limit } : {}),\n ...(query.offset != null ? { offset: query.offset } : {}),\n orderBy,\n });\n return rows.map(fromRunEntity);\n }\n\n /** One attribute predicate as a raw EXISTS subquery on the side-table, correlated to the outer run\n * alias. `<>` (ne) also excludes runs where the attribute is absent (missing-key-never-matches):\n * EXISTS already requires a present row, so EXISTS(... <> ...) is exactly ne-with-present. Numeric\n * operands compare the num column, everything else the str column. Identifiers are quoted per\n * driver and operands are inlined as literals (string operands are escaped by doubling quotes). */\n private attributeExistsSql(\n f: AttributeFilter,\n quote: (id: string) => string,\n alias: string,\n cols: AttributeColumns,\n ): string {\n const col = attributeColumnFor(f) === 'numValue' ? cols.numValue : cols.strValue;\n const cmp = sqlComparator(f.op);\n const operand = attributeOperand(f);\n const literal =\n typeof operand === 'number' ? String(operand) : `'${String(operand).replace(/'/g, \"''\")}'`;\n const a = quote(cols.table);\n const sub = quote('a');\n const outerId = `${quote(alias)}.${quote(cols.runPk)}`; // run PK column on the outer alias\n return `EXISTS (SELECT 1 FROM ${a} ${sub} WHERE ${sub}.${quote(cols.runId)} = ${outerId} AND ${sub}.${quote(cols.key)} = '${f.key.replace(/'/g, \"''\")}' AND ${sub}.${quote(col)} ${cmp} ${literal})`;\n }\n\n /** Resolve the side-table's actual column names from MikroORM metadata, so the raw EXISTS matches\n * the active naming strategy (underscore vs camelCase) rather than guessing. The run PK column is\n * reused for BOTH the outer correlation and the side-table FK (they share the same fieldName). */\n private attributeColumns(em: EntityManager): AttributeColumns {\n const meta = em.getMetadata().get(RunAttributeEntity);\n const field = (prop: string) =>\n meta.props.find((p) => p.name === prop)?.fieldNames?.[0] ?? prop;\n const runMeta = em.getMetadata().get(WorkflowRunEntity);\n const runPk = runMeta.properties.id?.fieldNames?.[0] ?? 'id';\n return {\n table: meta.tableName,\n runId: field('runId'),\n runPk,\n key: field('key'),\n strValue: field('strValue'),\n numValue: field('numValue'),\n };\n }\n\n /** Resolve the `tags` column name from metadata (per the active naming strategy), for the raw LIKE. */\n private tagsColumn(em: EntityManager): string {\n const runMeta = em.getMetadata().get(WorkflowRunEntity);\n return runMeta.properties.tags?.fieldNames?.[0] ?? 'tags';\n }\n\n /** Wrap a JSON column reference so it can be `LIKE`d as text. Postgres `jsonb`/`json` rejects `LIKE`\n * directly (`operator does not exist: jsonb ~~ unknown`) — cast to `text`; MySQL JSON needs an\n * explicit `CHAR` cast; SQLite stores JSON as text already, so no cast. */\n private jsonAsText(em: EntityManager, colRef: string): string {\n const platform = String(em.getPlatform().constructor.name).toLowerCase();\n if (platform.includes('postgre')) return `${colRef}::text`;\n if (platform.includes('mysql') || platform.includes('mariadb'))\n return `CAST(${colRef} AS CHAR)`;\n return colRef;\n }\n\n /** Quote an identifier per the active SQL driver (MySQL/MariaDB backtick, others double-quote). */\n private idQuote(em: EntityManager): (id: string) => string {\n const platform = String(em.getPlatform().constructor.name).toLowerCase();\n const isMysql = platform.includes('mysql') || platform.includes('mariadb');\n const ch = isMysql ? '`' : '\"';\n return (id: string) => `${ch}${id}${ch}`;\n }\n\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(StepCheckpointEntity, { runId }, { orderBy: { seq: 'asc' } });\n return rows.map(fromCheckpointEntity);\n }\n\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(\n StepCheckpointEntity,\n { runId, name },\n { orderBy: { seq: 'desc' } },\n );\n return entity ? fromCheckpointEntity(entity) : undefined;\n }\n\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n if (prefixes.length === 0) return [];\n const em = this.orm.em.fork();\n const rows = await em.find(\n StepCheckpointEntity,\n { runId, $or: prefixes.map((p) => ({ name: { $like: `${p}%` } })) },\n { orderBy: { seq: 'asc' } },\n );\n return rows.map(fromCheckpointEntity);\n }\n\n async putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n const em = this.orm.em.fork();\n await em.upsert(SignalWaiterEntity, { ...waiter });\n await em.flush();\n }\n\n async takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(SignalWaiterEntity, { token });\n if (!entity) return null;\n const waiter: SignalWaiter = { token: entity.token, runId: entity.runId, seq: entity.seq };\n await em.remove(entity).flush();\n return waiter;\n }\n\n async listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(SignalWaiterEntity, { token: { $like: `${prefix}%` } });\n return rows.map((e) => ({ token: e.token, runId: e.runId, seq: e.seq }));\n }\n\n async bufferSignal(token: string, payload: unknown): Promise<void> {\n const em = this.orm.em.fork();\n const e = new BufferedSignalEntity();\n e.token = token;\n e.payload = payload ?? null;\n em.persist(e);\n await em.flush();\n }\n\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(BufferedSignalEntity, { token }, { orderBy: { id: 'asc' } });\n if (!entity) return null;\n const payload = entity.payload ?? undefined;\n await em.remove(entity).flush();\n return { payload };\n }\n}\n\nfunction toRunEntity(run: WorkflowRun): WorkflowRunEntity {\n const e = new WorkflowRunEntity();\n e.id = run.id;\n e.workflow = run.workflow;\n e.workflowVersion = run.workflowVersion;\n e.status = run.status;\n e.input = run.input ?? null;\n e.output = run.output ?? null;\n e.error = run.error ?? null;\n if (run.wakeAt != null) e.wakeAt = new Date(run.wakeAt);\n if (run.lockedBy !== undefined) e.lockedBy = run.lockedBy;\n if (run.lockedUntil != null) e.lockedUntil = new Date(run.lockedUntil);\n if (run.recoveryAttempts !== undefined) e.recoveryAttempts = run.recoveryAttempts;\n e.tags = run.tags ?? null;\n e.searchAttributes = run.searchAttributes ?? null;\n e.priority = run.priority ?? null;\n e.createdAt = run.createdAt;\n e.updatedAt = run.updatedAt;\n return e;\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?.getTime(),\n lockedBy: e.lockedBy ?? undefined,\n lockedUntil: e.lockedUntil?.getTime(),\n recoveryAttempts: e.recoveryAttempts ?? undefined,\n tags: e.tags ?? undefined,\n searchAttributes: e.searchAttributes ?? undefined,\n priority: e.priority ?? undefined,\n createdAt: e.createdAt,\n updatedAt: e.updatedAt,\n };\n}\n\nfunction toCheckpointEntity(cp: StepCheckpoint): StepCheckpointEntity {\n const e = new StepCheckpointEntity();\n e.runId = cp.runId;\n e.seq = cp.seq;\n e.name = cp.name;\n e.kind = cp.kind;\n e.stepId = cp.stepId;\n e.status = cp.status;\n e.input = cp.input ?? null;\n e.output = cp.output ?? null;\n e.error = cp.error ?? null;\n e.events = cp.events ?? null;\n e.attempts = cp.attempts;\n if (cp.workerGroup !== undefined) e.workerGroup = cp.workerGroup;\n if (cp.wakeAt != null) e.wakeAt = new Date(cp.wakeAt);\n e.enqueuedAt = cp.enqueuedAt;\n e.startedAt = cp.startedAt;\n e.finishedAt = cp.finishedAt;\n return e;\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 wakeAt: e.wakeAt?.getTime(),\n enqueuedAt: e.enqueuedAt ?? e.startedAt,\n startedAt: e.startedAt,\n finishedAt: e.finishedAt,\n };\n}\n","import type { MikroORM } from '@mikro-orm/core';\n\n/**\n * The tables this store owns. Kept in sync with the `tableName`s in `./entities`. Used to scope\n * schema management to our own tables (see {@link ensureMikroOrmDurableSchema}).\n */\nconst DURABLE_TABLE_NAMES = new Set([\n 'durable_workflow_runs',\n 'durable_step_checkpoints',\n 'durable_run_attributes',\n 'durable_signal_waiters',\n 'durable_buffered_signals',\n]);\n\n/** The table a `create table` / `alter table` statement targets, lower-cased; undefined otherwise. */\nfunction targetTable(statement: string): string | undefined {\n const match = statement.match(\n /^(?:create|alter)\\s+table\\s+(?:if\\s+not\\s+exists\\s+)?[`\"']?([\\w$]+)[`\"']?/i,\n );\n return match?.[1]?.toLowerCase();\n}\n\n/**\n * Whether a statement adds structure the store REQUIRES — a failure here is fatal (the store can't\n * run without the table/column/index). A column TYPE alignment (`modify`/`alter column ... type`)\n * is best-effort: the column already holds the data (the store serializes JSON to/from it regardless\n * of the declared type), so failing to converge its type — e.g. a legacy `longtext` value that won't\n * cast to `json` because it was truncated under an older `text` column — must NOT crash boot.\n */\nfunction isRequiredStructure(statement: string): boolean {\n return /\\b(?:create\\s+table|add\\s+(?:column|index|constraint|key|unique|fulltext))\\b/i.test(\n statement,\n );\n}\n\n/**\n * Idempotently create/extend ONLY the durable tables (additive — never drops). Safe to run on every\n * boot (auto-schema) and from a MikroORM migration when you disable auto-schema:\n *\n * ```ts\n * export class AddDurableTables extends Migration {\n * async up() { await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm()); }\n * }\n * ```\n *\n * It does NOT run a whole-ORM `schema.update()`. When the store shares the host app's ORM (the\n * recommended setup — a single ORM avoids MikroORM's global-metadata clobber between instances),\n * a full `schema.update()` would try to reconcile EVERY app table to the entity metadata: on a\n * migration-managed schema that means recreating the migrations table and dropping app foreign keys.\n * Instead we compute the safe additive diff and execute only the statements that target our own\n * `durable_*` tables. `getUpdateSchemaSQL` already emits a `create table` only for a missing table\n * and `alter table ... add` only for missing columns, so existing tables — and the entire rest of\n * the host schema — are left untouched.\n */\nexport async function ensureMikroOrmDurableSchema(orm: MikroORM): Promise<void> {\n const sql = await orm.schema.getUpdateSchemaSQL({ safe: true });\n const ours = sql\n .split(';')\n .map((statement) => statement.trim())\n .filter((statement) => {\n const table = targetTable(statement);\n return table !== undefined && DURABLE_TABLE_NAMES.has(table);\n });\n const connection = orm.em.getConnection();\n for (const statement of ours) {\n try {\n await connection.execute(statement);\n } catch (err) {\n // Required structure (create table / add column / add index) must succeed — rethrow.\n if (isRequiredStructure(statement)) {\n throw err;\n }\n // A best-effort type alignment (e.g. legacy `longtext` → `json`) failed, typically because an\n // existing column holds a value that can't cast to the target type (a relic of an older column\n // type). The column already stores the data and the store reads/writes it via serialization, so\n // leave it as-is and continue rather than crashing boot. Surfaced so the data can be repaired\n // out of band (e.g. `UPDATE … SET col = NULL WHERE JSON_VALID(col) = 0` for a disposable column).\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `[nestjs-durable-store-mikro-orm] skipped a non-structural durable-schema statement that failed; the column is left as-is (functional) — repair the data out of band to converge its type. Statement: ${statement} — ${message}`,\n );\n }\n }\n\n // Converge collation last, once the tables exist (whether just created above or pre-existing).\n await alignDurableCollation(orm);\n}\n\n/** A MySQL identifier we are willing to interpolate into DDL (charset / collation names). */\nfunction isSafeSqlIdentifier(value: string): boolean {\n return /^[A-Za-z0-9_]+$/.test(value);\n}\n\n/**\n * Align each durable table's collation to the ORM's configured `collate` (MySQL/MariaDB only).\n *\n * MikroORM's auto-schema (`getUpdateSchemaSQL`) creates tables with the server's DEFAULT collation —\n * on MySQL 8.4 that's `utf8mb4_0900_ai_ci` — and ignores the `collate` config option. When the host\n * app pins a different collation on its own tables (commonly `utf8mb4_unicode_ci` via migrations), a\n * JOIN between a durable table and an app table throws \"Illegal mix of collations\". We converge it\n * here: read the configured collation and `CONVERT` only the durable tables whose collation differs.\n *\n * Idempotent (matching tables are skipped), non-fatal (a CONVERT failure is warned, never crashes\n * boot), and a no-op when no `collate` is configured or the platform isn't MySQL/MariaDB.\n */\nasync function alignDurableCollation(orm: MikroORM): Promise<void> {\n const platform = String(orm.em.getPlatform().constructor.name).toLowerCase();\n if (!platform.includes('mysql') && !platform.includes('maria')) {\n return;\n }\n const collate = orm.config.get('collate');\n if (typeof collate !== 'string' || !isSafeSqlIdentifier(collate)) {\n return;\n }\n // utf8mb4_unicode_ci → utf8mb4. CONVERT TO needs the charset that owns the collation.\n const charset = collate.split('_')[0];\n if (!charset || !isSafeSqlIdentifier(charset)) {\n return;\n }\n const connection = orm.em.getConnection();\n for (const table of DURABLE_TABLE_NAMES) {\n try {\n const rows = (await connection.execute(\n 'select table_collation as collation from information_schema.tables where table_schema = database() and table_name = ? limit 1',\n [table],\n )) as Array<{ collation?: string | null }>;\n const current = rows[0]?.collation;\n // Table absent (nothing to align) or already at the target collation — skip.\n if (current == null || current === collate) {\n continue;\n }\n await connection.execute(\n `alter table \\`${table}\\` convert to character set ${charset} collate ${collate}`,\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `[nestjs-durable-store-mikro-orm] could not align collation for \\`${table}\\` to ${collate} (left as-is): ${message}`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;ACCA,kBAA6B;AAgB7B,SAASA,UAAUC,UAAgB;AACjC,SAAOA,SAASC,QAAQ,UAAU,CAACC,MAAM,IAAIA,EAAEC,YAAW,CAAA,EAAI;AAChE;AAFSJ;AAIT,SAASK,YAAYC,QAA2B;AAC9C,MAAIA,WAAW,aAAc,QAAON;AACpC,MAAIM,WAAW,WAAY,QAAO,CAACL,aAAaA;AAChD,SAAOK;AACT;AAJSD;AAUF,IAAME,oBAAN,MAAMA;EA9Bb,OA8BaA;;;EACXC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;AACF;AAEO,IAAMC,uBAAN,MAAMA;EAjDb,OAiDaA;;;EACXC;EACAC;EACAC;EACAC;EACAC;EACAlB;EACAC;EACAC;EACAC;EACAgB;EACAC;EACAC;EACAjB;EACAkB;EACAC;EACAC;AACF;AAQO,IAAMC,qBAAN,MAAMA;EA1Eb,OA0EaA;;;EACXX;EACAY;EACAC;EACAC;AACF;AAEO,IAAMC,qBAAN,MAAMA;EAjFb,OAiFaA;;;EACXC;EACAhB;EACAC;AACF;AAEO,IAAMgB,uBAAN,MAAMA;EAvFb,OAuFaA;;;EACXlC;EACAiC;EACAE;AACF;AAUO,SAASC,gBAAgBC,UAA4C,CAAC,GAAC;AAC5E,QAAMC,MAAMzC,YAAYwC,QAAQvC,UAAU,YAAA;AAE1C,QAAMyC,eAAe,IAAIC,yBAAgC;IACvDC,OAAO1C;IACP2C,WAAW;IACXC,YAAY;MACV3C,IAAI;QAAE4C,MAAM;QAAUC,SAAS;QAAMC,WAAWR,IAAI,IAAA;MAAM;MAC1DrC,UAAU;QAAE2C,MAAM;QAAUE,WAAWR,IAAI,UA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AAqB8G,GAAuB;AACnD,SAAO;IACLpI,OAAOoI,EAAEpI;IACTqB,KAAK+G,EAAE/G;IACPqF,MAAM0B,EAAE1B;IACRwC,MAAMd,EAAEc;IACRC,QAAQf,EAAEe;IACVjH,QAAQkG,EAAElG;IACVyG,OAAOP,EAAEO,SAASlB;IAClBmB,QAAQR,EAAEQ,UAAUnB;IACpBoB,OAAQT,EAAES,SAASpB;IACnB2B,QAAShB,EAAEgB,UAAU3B;IACrB4B,UAAUjB,EAAEiB;IACZC,aAAalB,EAAEkB,eAAe7B;IAC9B9E,QAAQyF,EAAEzF,QAAQsG,QAAAA;IAClBM,YAAYnB,EAAEmB,cAAcnB,EAAEoB;IAC9BA,WAAWpB,EAAEoB;IACbC,YAAYrB,EAAEqB;EAChB;AACF;AAnBSnI;","names":["snakeCase","property","replace","c","toLowerCase","columnNamer","naming","WorkflowRunEntity","id","workflow","workflowVersion","status","input","output","error","wakeAt","lockedBy","lockedUntil","recoveryAttempts","tags","searchAttributes","priority","createdAt","updatedAt","StepCheckpointEntity","runId","seq","name","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt","RunAttributeEntity","key","strValue","numValue","SignalWaiterEntity","token","BufferedSignalEntity","payload","durableEntities","options","col","workflowRuns","EntitySchema","class","tableName","properties","type","primary","fieldName","nullable","stepCheckpoints","runAttributes","signalWaiters","bufferedSignals","autoincrement","index","ENTITIES","DURABLE_TABLE_NAMES","Set","targetTable","statement","match","toLowerCase","isRequiredStructure","test","ensureMikroOrmDurableSchema","orm","sql","schema","getUpdateSchemaSQL","safe","ours","split","map","trim","filter","table","undefined","has","connection","em","getConnection","execute","err","message","Error","String","console","warn","alignDurableCollation","isSafeSqlIdentifier","value","platform","getPlatform","name","includes","collate","config","get","charset","rows","current","collation","MikroOrmStateStore","orm","ensureSchema","ensureMikroOrmDurableSchema","createRun","run","em","fork","create","WorkflowRunEntity","toRunEntity","flush","reindexAttributes","id","searchAttributes","updateRun","runId","patch","entity","findOneOrFail","Object","assign","fromRunEntity","attributes","forked","nativeDelete","RunAttributeEntity","rows","normalizeAttributeRows","length","insertMany","getRun","findOne","deleteRun","StepCheckpointEntity","SignalWaiterEntity","getCheckpoint","seq","fromCheckpointEntity","saveCheckpoint","checkpoint","upsert","toCheckpointEntity","transaction","work","transactional","raw","cp","listIncompleteRuns","find","status","$in","map","listPendingRuns","limit","orderBy","createdAt","listDueTimers","nowMs","wakeAt","$ne","$lte","Date","tryLockRun","owner","leaseUntilMs","affected","nativeUpdate","$or","lockedUntil","lockedBy","releaseRunLock","renewRunLock","listRuns","query","where","workflow","statuses","$and","tag","quote","idQuote","cols","attributeColumns","qb","createQueryBuilder","tagsCol","tagsColumn","pattern","replace","colExpr","jsonAsText","andWhere","f","attributeExistsSql","offset","getResultList","alias","col","attributeColumnFor","numValue","strValue","cmp","sqlComparator","op","operand","attributeOperand","literal","String","a","table","sub","outerId","runPk","key","meta","getMetadata","get","field","prop","props","p","name","fieldNames","runMeta","properties","tableName","tags","colRef","platform","getPlatform","toLowerCase","includes","isMysql","ch","listCheckpoints","getLatestCheckpointByName","undefined","listCheckpointsByNamePrefix","prefixes","$like","putSignalWaiter","waiter","takeSignalWaiter","token","remove","listSignalWaiters","prefix","e","bufferSignal","payload","BufferedSignalEntity","persist","takeBufferedSignal","workflowVersion","input","output","error","recoveryAttempts","priority","updatedAt","getTime","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/entities.ts","../src/mikro-orm-state-store.ts","../src/schema.ts"],"sourcesContent":["export * from './entities';\nexport * from './mikro-orm-state-store';\nexport * from './schema';\n","import type { RunStatus, StepKind } from '@dudousxd/nestjs-durable-core';\nimport { EntitySchema } from '@mikro-orm/core';\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 TypeORM,\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\nfunction 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 `em.create`/`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;\n lockedUntil?: Date;\n recoveryAttempts?: number;\n tags?: string[] | null;\n searchAttributes?: Record<string, string | number | boolean> | null;\n priority?: number | 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;\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}\n\nexport class BufferedSignalEntity {\n id!: number;\n token!: string;\n payload?: unknown;\n}\n\n/**\n * Build the durable MikroORM entity schemas with column names pinned per `naming` (default\n * `'snake_case'`). Register the result in your MikroORM config / `MikroOrmModule.forFeature`.\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 class: WorkflowRunEntity,\n tableName: 'durable_workflow_runs',\n // Indexes mirror the Prisma adapter so a store swap keeps the same plan. The poller hits these\n // every tick: `(status, wakeAt)` serves both the due-timer scan (status='suspended' AND wakeAt<=now)\n // and, via its `status` prefix, the pending/incomplete status lookups; `(workflow, status)` serves\n // the per-workflow timeout sweep. Without them every poll is a full scan of a table that only grows.\n indexes: [\n { name: 'durable_workflow_runs_status_wake_at_idx', properties: ['status', 'wakeAt'] },\n { name: 'durable_workflow_runs_workflow_status_idx', properties: ['workflow', 'status'] },\n ],\n properties: {\n id: { type: 'string', primary: true, fieldName: col('id') },\n workflow: { type: 'string', fieldName: col('workflow') },\n workflowVersion: { type: 'string', fieldName: col('workflowVersion') },\n status: { type: 'string', fieldName: col('status') },\n input: { type: 'json', nullable: true, fieldName: col('input') },\n output: { type: 'json', nullable: true, fieldName: col('output') },\n error: { type: 'json', nullable: true, fieldName: col('error') },\n wakeAt: { type: 'Date', nullable: true, fieldName: col('wakeAt') },\n lockedBy: { type: 'string', nullable: true, fieldName: col('lockedBy') },\n lockedUntil: { type: 'Date', nullable: true, fieldName: col('lockedUntil') },\n recoveryAttempts: { type: 'integer', nullable: true, fieldName: col('recoveryAttempts') },\n tags: { type: 'json', nullable: true, fieldName: col('tags') },\n searchAttributes: { type: 'json', nullable: true, fieldName: col('searchAttributes') },\n priority: { type: 'integer', nullable: true, fieldName: col('priority') },\n createdAt: { type: 'Date', fieldName: col('createdAt') },\n updatedAt: { type: 'Date', fieldName: col('updatedAt') },\n },\n });\n\n const stepCheckpoints = new EntitySchema<StepCheckpointEntity>({\n class: StepCheckpointEntity,\n tableName: 'durable_step_checkpoints',\n properties: {\n runId: { type: 'string', primary: true, fieldName: col('runId') },\n seq: { type: 'integer', primary: true, fieldName: col('seq') },\n name: { type: 'string', fieldName: col('name') },\n kind: { type: 'string', fieldName: col('kind') },\n stepId: { type: 'string', fieldName: col('stepId') },\n status: { type: 'string', fieldName: col('status') },\n input: { type: 'json', nullable: true, fieldName: col('input') },\n output: { type: 'json', nullable: true, fieldName: col('output') },\n error: { type: 'json', nullable: true, fieldName: col('error') },\n events: { type: 'json', nullable: true, fieldName: col('events') },\n attempts: { type: 'integer', fieldName: col('attempts') },\n workerGroup: { type: 'string', nullable: true, fieldName: col('workerGroup') },\n wakeAt: { type: 'Date', nullable: true, fieldName: col('wakeAt') },\n enqueuedAt: { type: 'Date', nullable: true, fieldName: col('enqueuedAt') },\n startedAt: { type: 'Date', fieldName: col('startedAt') },\n finishedAt: { type: 'Date', fieldName: col('finishedAt') },\n },\n });\n\n const runAttributes = new EntitySchema<RunAttributeEntity>({\n class: RunAttributeEntity,\n tableName: 'durable_run_attributes',\n // The search-attribute EXISTS join (see the class docstring) pushes equality/range predicates down\n // onto `(key, numValue)` / `(key, strValue)`; mirror the Prisma adapter so those scans stay indexed.\n indexes: [\n { name: 'durable_run_attributes_key_num_idx', properties: ['key', 'numValue'] },\n { name: 'durable_run_attributes_key_str_idx', properties: ['key', 'strValue'] },\n ],\n properties: {\n runId: { type: 'string', primary: true, fieldName: col('runId') },\n key: { type: 'string', primary: true, fieldName: col('key') },\n strValue: { type: 'string', nullable: true, fieldName: col('strValue') },\n // `float`/`double` is portable across SQLite/MySQL/Postgres for numeric range scans.\n numValue: { type: 'float', nullable: true, fieldName: col('numValue') },\n },\n });\n\n const signalWaiters = new EntitySchema<SignalWaiterEntity>({\n class: SignalWaiterEntity,\n tableName: 'durable_signal_waiters',\n properties: {\n token: { type: 'string', primary: true, fieldName: col('token') },\n runId: { type: 'string', fieldName: col('runId') },\n seq: { type: 'integer', fieldName: col('seq') },\n },\n });\n\n const bufferedSignals = new EntitySchema<BufferedSignalEntity>({\n class: BufferedSignalEntity,\n tableName: 'durable_buffered_signals',\n properties: {\n id: { type: 'integer', primary: true, autoincrement: true, fieldName: col('id') },\n token: { type: 'string', index: true, fieldName: col('token') },\n payload: { type: 'json', nullable: true, fieldName: col('payload') },\n },\n });\n\n return [workflowRuns, stepCheckpoints, runAttributes, signalWaiters, bufferedSignals];\n}\n\n/** Durable entity schemas with the canonical `'snake_case'` column names. */\nexport const ENTITIES = durableEntities();\n","import {\n type AttributeFilter,\n type RetentionPolicy,\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 parseDuration,\n sqlComparator,\n} from '@dudousxd/nestjs-durable-core';\nimport type { EntityManager, MikroORM } from '@mikro-orm/core';\n\n/** Minimal structural surface of the SQL EntityManager's QueryBuilder (from `@mikro-orm/knex`),\n * typed here so the adapter needn't add a hard dependency on the knex types — a real SQL-driver EM\n * satisfies it at runtime. */\ninterface DurableQueryBuilder<T> {\n where(cond: Record<string, unknown>): DurableQueryBuilder<T>;\n andWhere(cond: string): DurableQueryBuilder<T>;\n orderBy(cond: Record<string, unknown>): DurableQueryBuilder<T>;\n limit(n: number): DurableQueryBuilder<T>;\n offset(n: number): DurableQueryBuilder<T>;\n getResultList(): Promise<T[]>;\n}\ntype SqlEm = EntityManager & {\n createQueryBuilder<T>(entity: unknown, alias: string): DurableQueryBuilder<T>;\n};\n\n/** Resolved side-table column names (per the active naming strategy) for the raw EXISTS pushdown. */\ninterface AttributeColumns {\n table: string;\n /** Side-table FK column (the run id on `durable_run_attributes`). */\n runId: string;\n /** Run table PK column (the `id` on `durable_workflow_runs`) used for the outer correlation. */\n runPk: string;\n key: string;\n strValue: string;\n numValue: string;\n}\nimport {\n BufferedSignalEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n StepCheckpointEntity,\n WorkflowRunEntity,\n} from './entities';\nimport { ensureMikroOrmDurableSchema } from './schema';\n\n/**\n * MikroORM-backed `StateStore`. Works on any MikroORM driver — Postgres, MySQL, SQLite (tested);\n * timestamps and `wakeAt` use native datetime columns. Each operation runs on a forked\n * EntityManager so it owns its unit of work.\n */\nexport class MikroOrmStateStore implements StateStore {\n constructor(private readonly orm: MikroORM) {}\n\n async ensureSchema(): Promise<void> {\n await ensureMikroOrmDurableSchema(this.orm);\n }\n\n async createRun(run: WorkflowRun): Promise<void> {\n const em = this.orm.em.fork();\n em.create(WorkflowRunEntity, toRunEntity(run));\n await em.flush();\n await this.reindexAttributes(run.id, run.searchAttributes);\n }\n\n async updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n const em = this.orm.em.fork();\n const entity = await em.findOneOrFail(WorkflowRunEntity, { id: runId });\n Object.assign(entity, toRunEntity({ ...fromRunEntity(entity), ...patch } as WorkflowRun));\n await em.flush();\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 /** 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 forked?: EntityManager,\n ): Promise<void> {\n const em = forked ?? this.orm.em.fork();\n await em.nativeDelete(RunAttributeEntity, { runId });\n const rows = normalizeAttributeRows(runId, attributes);\n if (rows.length) await em.insertMany(RunAttributeEntity, rows);\n }\n\n async getRun(runId: string): Promise<WorkflowRun | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(WorkflowRunEntity, { id: runId });\n return entity ? fromRunEntity(entity) : null;\n }\n\n async deleteRun(runId: string): Promise<void> {\n const em = this.orm.em.fork();\n // Children first, then the run row — checkpoints, signal waiters, and the normalized\n // attribute side-table, so nothing dangles after the run is gone.\n await em.nativeDelete(StepCheckpointEntity, { runId });\n await em.nativeDelete(SignalWaiterEntity, { runId });\n await em.nativeDelete(RunAttributeEntity, { runId });\n await em.nativeDelete(WorkflowRunEntity, { id: runId });\n }\n\n async pruneTerminalRuns(policy: RetentionPolicy, nowMs: number, limit: number): Promise<number> {\n if (policy.statuses.length === 0 || limit <= 0) return 0;\n const em = this.orm.em.fork();\n const status = { $in: policy.statuses };\n // Collect ids that violate EITHER bound (most-restrictive keep): too old, or past the count cap.\n const ids = new Set<string>();\n\n if (policy.maxAge != null) {\n const cutoff = new Date(nowMs - parseDuration(policy.maxAge));\n const rows = await em.find(\n WorkflowRunEntity,\n { status, updatedAt: { $lt: cutoff } },\n { fields: ['id'], orderBy: { updatedAt: 'asc' }, limit }, // oldest first\n );\n for (const r of rows) ids.add(r.id);\n }\n\n if (policy.maxCount != null && ids.size < limit) {\n // Everything beyond the newest `maxCount` rows in the status set — skip the kept window via offset.\n const rows = await em.find(\n WorkflowRunEntity,\n { status },\n {\n fields: ['id'],\n orderBy: { updatedAt: 'desc', id: 'desc' },\n limit,\n offset: policy.maxCount,\n },\n );\n for (const r of rows) {\n ids.add(r.id);\n if (ids.size >= limit) break;\n }\n }\n\n if (ids.size === 0) return 0;\n const idList = [...ids].slice(0, limit);\n const runId = { $in: idList };\n // Cascade children then runs (mirrors deleteRun) in one transaction so a pruned run never dangles.\n await em.transactional(async (tem) => {\n await tem.nativeDelete(StepCheckpointEntity, { runId });\n await tem.nativeDelete(SignalWaiterEntity, { runId });\n await tem.nativeDelete(RunAttributeEntity, { runId });\n await tem.nativeDelete(WorkflowRunEntity, { id: runId });\n });\n return idList.length;\n }\n\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(StepCheckpointEntity, { runId, seq });\n return entity ? fromCheckpointEntity(entity) : null;\n }\n\n async saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n const em = this.orm.em.fork();\n await em.upsert(StepCheckpointEntity, toCheckpointEntity(checkpoint));\n await em.flush();\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.orm.em.fork().transactional(async (em) =>\n work({\n raw: em,\n saveCheckpoint: async (cp) => {\n await em.upsert(StepCheckpointEntity, toCheckpointEntity(cp));\n },\n }),\n );\n }\n\n async listIncompleteRuns(): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(WorkflowRunEntity, { status: { $in: ['running', 'cancelling'] } });\n return rows.map(fromRunEntity);\n }\n\n async listPendingRuns(limit: number): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(\n WorkflowRunEntity,\n { status: 'pending' },\n { orderBy: { createdAt: 'asc' }, limit }, // FIFO dispatch\n );\n return rows.map(fromRunEntity);\n }\n\n async listDueTimers(nowMs: number): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(WorkflowRunEntity, {\n status: 'suspended',\n wakeAt: { $ne: null, $lte: new Date(nowMs) },\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 em = this.orm.em.fork();\n const affected = await em.nativeUpdate(\n WorkflowRunEntity,\n { id: runId, $or: [{ lockedUntil: null }, { lockedUntil: { $lte: new Date(nowMs) } }] },\n { lockedBy: owner, lockedUntil: new Date(leaseUntilMs) },\n );\n return affected === 1;\n }\n\n async releaseRunLock(runId: string): Promise<void> {\n const em = this.orm.em.fork();\n await em.nativeUpdate(WorkflowRunEntity, { id: runId }, { lockedBy: null, lockedUntil: null });\n }\n\n async renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n const em = this.orm.em.fork();\n const affected = await em.nativeUpdate(\n WorkflowRunEntity,\n { id: runId, lockedBy: owner },\n { lockedUntil: new Date(leaseUntilMs) },\n );\n return affected === 1;\n }\n\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const where: Record<string, unknown> = {};\n if (query.workflow) where.workflow = query.workflow;\n // `status IN (...)`; an empty set matches nothing (mirrors the in-memory store). When both the\n // single `status` and `statuses` are set, AND them so the narrower set wins.\n if (query.status && query.statuses) {\n where.$and = [{ status: query.status }, { status: { $in: query.statuses } }];\n } else if (query.status) {\n where.status = query.status;\n } else if (query.statuses) {\n where.status = { $in: query.statuses };\n }\n const orderBy = { createdAt: 'desc' as const }; // newest first — recent runs on top in the dashboard\n // `tags`/attributes need raw SQL pushed through the QueryBuilder:\n // - tag: `tags` is a JSON column (native json/jsonb on PG/MySQL), and MikroORM JSON-serializes a\n // `{ $like }` operand (wrapping/escaping the LIKE pattern) so a plain where corrupts it to no\n // matches. A raw LIKE on the column-as-text matches the quoted token so `etl` doesn't match\n // `etl-foo`. Postgres `jsonb` rejects `LIKE` directly, so cast to text per dialect.\n // - attributes: each filter becomes a raw EXISTS against the normalized side-table, so the DB\n // filters AND paginates — no full scan + in-process filter (ANDed: one EXISTS per filter).\n // Use a QueryBuilder with a fixed root alias `r` so the raw correlations are stable across drivers.\n if (query.tag || query.attributes?.length) {\n const quote = this.idQuote(em);\n const cols = this.attributeColumns(em);\n const qb = (em as SqlEm)\n .createQueryBuilder<WorkflowRunEntity>(WorkflowRunEntity, 'r')\n .where(where)\n .orderBy(orderBy);\n if (query.tag) {\n const tagsCol = this.tagsColumn(em);\n const pattern = `%\"${query.tag.replace(/'/g, \"''\")}\"%`;\n const colExpr = this.jsonAsText(em, `${quote('r')}.${quote(tagsCol)}`);\n qb.andWhere(`${colExpr} LIKE '${pattern}'`);\n }\n for (const f of query.attributes ?? []) {\n qb.andWhere(this.attributeExistsSql(f, quote, 'r', cols));\n }\n if (query.limit != null) qb.limit(query.limit);\n if (query.offset != null) qb.offset(query.offset);\n const rows = await qb.getResultList();\n return rows.map(fromRunEntity);\n }\n const rows = await em.find(WorkflowRunEntity, where, {\n ...(query.limit != null ? { limit: query.limit } : {}),\n ...(query.offset != null ? { offset: query.offset } : {}),\n orderBy,\n });\n return rows.map(fromRunEntity);\n }\n\n /** One attribute predicate as a raw EXISTS subquery on the side-table, correlated to the outer run\n * alias. `<>` (ne) also excludes runs where the attribute is absent (missing-key-never-matches):\n * EXISTS already requires a present row, so EXISTS(... <> ...) is exactly ne-with-present. Numeric\n * operands compare the num column, everything else the str column. Identifiers are quoted per\n * driver and operands are inlined as literals (string operands are escaped by doubling quotes). */\n private attributeExistsSql(\n f: AttributeFilter,\n quote: (id: string) => string,\n alias: string,\n cols: AttributeColumns,\n ): string {\n const col = attributeColumnFor(f) === 'numValue' ? cols.numValue : cols.strValue;\n const cmp = sqlComparator(f.op);\n const operand = attributeOperand(f);\n const literal =\n typeof operand === 'number' ? String(operand) : `'${String(operand).replace(/'/g, \"''\")}'`;\n const a = quote(cols.table);\n const sub = quote('a');\n const outerId = `${quote(alias)}.${quote(cols.runPk)}`; // run PK column on the outer alias\n return `EXISTS (SELECT 1 FROM ${a} ${sub} WHERE ${sub}.${quote(cols.runId)} = ${outerId} AND ${sub}.${quote(cols.key)} = '${f.key.replace(/'/g, \"''\")}' AND ${sub}.${quote(col)} ${cmp} ${literal})`;\n }\n\n /** Resolve the side-table's actual column names from MikroORM metadata, so the raw EXISTS matches\n * the active naming strategy (underscore vs camelCase) rather than guessing. The run PK column is\n * reused for BOTH the outer correlation and the side-table FK (they share the same fieldName). */\n private attributeColumns(em: EntityManager): AttributeColumns {\n const meta = em.getMetadata().get(RunAttributeEntity);\n const field = (prop: string) =>\n meta.props.find((p) => p.name === prop)?.fieldNames?.[0] ?? prop;\n const runMeta = em.getMetadata().get(WorkflowRunEntity);\n const runPk = runMeta.properties.id?.fieldNames?.[0] ?? 'id';\n return {\n table: meta.tableName,\n runId: field('runId'),\n runPk,\n key: field('key'),\n strValue: field('strValue'),\n numValue: field('numValue'),\n };\n }\n\n /** Resolve the `tags` column name from metadata (per the active naming strategy), for the raw LIKE. */\n private tagsColumn(em: EntityManager): string {\n const runMeta = em.getMetadata().get(WorkflowRunEntity);\n return runMeta.properties.tags?.fieldNames?.[0] ?? 'tags';\n }\n\n /** Wrap a JSON column reference so it can be `LIKE`d as text. Postgres `jsonb`/`json` rejects `LIKE`\n * directly (`operator does not exist: jsonb ~~ unknown`) — cast to `text`; MySQL JSON needs an\n * explicit `CHAR` cast; SQLite stores JSON as text already, so no cast. */\n private jsonAsText(em: EntityManager, colRef: string): string {\n const platform = String(em.getPlatform().constructor.name).toLowerCase();\n if (platform.includes('postgre')) return `${colRef}::text`;\n if (platform.includes('mysql') || platform.includes('mariadb'))\n return `CAST(${colRef} AS CHAR)`;\n return colRef;\n }\n\n /** Quote an identifier per the active SQL driver (MySQL/MariaDB backtick, others double-quote). */\n private idQuote(em: EntityManager): (id: string) => string {\n const platform = String(em.getPlatform().constructor.name).toLowerCase();\n const isMysql = platform.includes('mysql') || platform.includes('mariadb');\n const ch = isMysql ? '`' : '\"';\n return (id: string) => `${ch}${id}${ch}`;\n }\n\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(StepCheckpointEntity, { runId }, { orderBy: { seq: 'asc' } });\n return rows.map(fromCheckpointEntity);\n }\n\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(\n StepCheckpointEntity,\n { runId, name },\n { orderBy: { seq: 'desc' } },\n );\n return entity ? fromCheckpointEntity(entity) : undefined;\n }\n\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n if (prefixes.length === 0) return [];\n const em = this.orm.em.fork();\n const rows = await em.find(\n StepCheckpointEntity,\n { runId, $or: prefixes.map((p) => ({ name: { $like: `${p}%` } })) },\n { orderBy: { seq: 'asc' } },\n );\n return rows.map(fromCheckpointEntity);\n }\n\n async putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n const em = this.orm.em.fork();\n await em.upsert(SignalWaiterEntity, { ...waiter });\n await em.flush();\n }\n\n async takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(SignalWaiterEntity, { token });\n if (!entity) return null;\n const waiter: SignalWaiter = { token: entity.token, runId: entity.runId, seq: entity.seq };\n await em.remove(entity).flush();\n return waiter;\n }\n\n async listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(SignalWaiterEntity, { token: { $like: `${prefix}%` } });\n return rows.map((e) => ({ token: e.token, runId: e.runId, seq: e.seq }));\n }\n\n async bufferSignal(token: string, payload: unknown): Promise<void> {\n const em = this.orm.em.fork();\n const e = new BufferedSignalEntity();\n e.token = token;\n e.payload = payload ?? null;\n em.persist(e);\n await em.flush();\n }\n\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(BufferedSignalEntity, { token }, { orderBy: { id: 'asc' } });\n if (!entity) return null;\n const payload = entity.payload ?? undefined;\n await em.remove(entity).flush();\n return { payload };\n }\n}\n\nfunction toRunEntity(run: WorkflowRun): WorkflowRunEntity {\n const e = new WorkflowRunEntity();\n e.id = run.id;\n e.workflow = run.workflow;\n e.workflowVersion = run.workflowVersion;\n e.status = run.status;\n e.input = run.input ?? null;\n e.output = run.output ?? null;\n e.error = run.error ?? null;\n if (run.wakeAt != null) e.wakeAt = new Date(run.wakeAt);\n if (run.lockedBy !== undefined) e.lockedBy = run.lockedBy;\n if (run.lockedUntil != null) e.lockedUntil = new Date(run.lockedUntil);\n if (run.recoveryAttempts !== undefined) e.recoveryAttempts = run.recoveryAttempts;\n e.tags = run.tags ?? null;\n e.searchAttributes = run.searchAttributes ?? null;\n e.priority = run.priority ?? null;\n e.createdAt = run.createdAt;\n e.updatedAt = run.updatedAt;\n return e;\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?.getTime(),\n lockedBy: e.lockedBy ?? undefined,\n lockedUntil: e.lockedUntil?.getTime(),\n recoveryAttempts: e.recoveryAttempts ?? undefined,\n tags: e.tags ?? undefined,\n searchAttributes: e.searchAttributes ?? undefined,\n priority: e.priority ?? undefined,\n createdAt: e.createdAt,\n updatedAt: e.updatedAt,\n };\n}\n\nfunction toCheckpointEntity(cp: StepCheckpoint): StepCheckpointEntity {\n const e = new StepCheckpointEntity();\n e.runId = cp.runId;\n e.seq = cp.seq;\n e.name = cp.name;\n e.kind = cp.kind;\n e.stepId = cp.stepId;\n e.status = cp.status;\n e.input = cp.input ?? null;\n e.output = cp.output ?? null;\n e.error = cp.error ?? null;\n e.events = cp.events ?? null;\n e.attempts = cp.attempts;\n if (cp.workerGroup !== undefined) e.workerGroup = cp.workerGroup;\n if (cp.wakeAt != null) e.wakeAt = new Date(cp.wakeAt);\n e.enqueuedAt = cp.enqueuedAt;\n e.startedAt = cp.startedAt;\n e.finishedAt = cp.finishedAt;\n return e;\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 wakeAt: e.wakeAt?.getTime(),\n enqueuedAt: e.enqueuedAt ?? e.startedAt,\n startedAt: e.startedAt,\n finishedAt: e.finishedAt,\n };\n}\n","import type { MikroORM } from '@mikro-orm/core';\n\n/**\n * The tables this store owns. Kept in sync with the `tableName`s in `./entities`. Used to scope\n * schema management to our own tables (see {@link ensureMikroOrmDurableSchema}).\n */\nconst DURABLE_TABLE_NAMES = new Set([\n 'durable_workflow_runs',\n 'durable_step_checkpoints',\n 'durable_run_attributes',\n 'durable_signal_waiters',\n 'durable_buffered_signals',\n]);\n\n/**\n * The table a DDL statement targets, lower-cased; undefined otherwise. Recognizes `create table` /\n * `alter table` (the table name follows immediately) and standalone `create [unique] index ... on\n * <table>` (the table follows `on`). MikroORM adds an index to an EXISTING table as `alter table ...\n * add index` on MySQL but as a standalone `create index ... on ...` on Postgres/SQLite — without the\n * second form those index statements would be dropped by the durable-table filter and never applied.\n */\nfunction targetTable(statement: string): string | undefined {\n const match = statement.match(\n /^(?:create\\s+(?:unique\\s+)?index\\s+.+?\\s+on\\s+|(?:create|alter)\\s+table\\s+(?:if\\s+not\\s+exists\\s+)?)[`\"']?([\\w$]+)[`\"']?/i,\n );\n return match?.[1]?.toLowerCase();\n}\n\n/**\n * Whether a statement adds structure the store REQUIRES — a failure here is fatal (the store can't\n * run without the table/column/index). A column TYPE alignment (`modify`/`alter column ... type`)\n * is best-effort: the column already holds the data (the store serializes JSON to/from it regardless\n * of the declared type), so failing to converge its type — e.g. a legacy `longtext` value that won't\n * cast to `json` because it was truncated under an older `text` column — must NOT crash boot.\n */\nfunction isRequiredStructure(statement: string): boolean {\n return /\\b(?:create\\s+table|create\\s+(?:unique\\s+)?index|add\\s+(?:column|index|constraint|key|unique|fulltext))\\b/i.test(\n statement,\n );\n}\n\n/**\n * Idempotently create/extend ONLY the durable tables (additive — never drops). Safe to run on every\n * boot (auto-schema) and from a MikroORM migration when you disable auto-schema:\n *\n * ```ts\n * export class AddDurableTables extends Migration {\n * async up() { await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm()); }\n * }\n * ```\n *\n * It does NOT run a whole-ORM `schema.update()`. When the store shares the host app's ORM (the\n * recommended setup — a single ORM avoids MikroORM's global-metadata clobber between instances),\n * a full `schema.update()` would try to reconcile EVERY app table to the entity metadata: on a\n * migration-managed schema that means recreating the migrations table and dropping app foreign keys.\n * Instead we compute the safe additive diff and execute only the statements that target our own\n * `durable_*` tables. `getUpdateSchemaSQL` already emits a `create table` only for a missing table\n * and `alter table ... add` only for missing columns, so existing tables — and the entire rest of\n * the host schema — are left untouched.\n */\nexport async function ensureMikroOrmDurableSchema(orm: MikroORM): Promise<void> {\n const sql = await orm.schema.getUpdateSchemaSQL({ safe: true });\n const ours = sql\n .split(';')\n .map((statement) => statement.trim())\n .filter((statement) => {\n const table = targetTable(statement);\n return table !== undefined && DURABLE_TABLE_NAMES.has(table);\n });\n const connection = orm.em.getConnection();\n for (const statement of ours) {\n try {\n await connection.execute(statement);\n } catch (err) {\n // Required structure (create table / add column / add index) must succeed — rethrow.\n if (isRequiredStructure(statement)) {\n throw err;\n }\n // A best-effort type alignment (e.g. legacy `longtext` → `json`) failed, typically because an\n // existing column holds a value that can't cast to the target type (a relic of an older column\n // type). The column already stores the data and the store reads/writes it via serialization, so\n // leave it as-is and continue rather than crashing boot. Surfaced so the data can be repaired\n // out of band (e.g. `UPDATE … SET col = NULL WHERE JSON_VALID(col) = 0` for a disposable column).\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `[nestjs-durable-store-mikro-orm] skipped a non-structural durable-schema statement that failed; the column is left as-is (functional) — repair the data out of band to converge its type. Statement: ${statement} — ${message}`,\n );\n }\n }\n\n // Converge collation last, once the tables exist (whether just created above or pre-existing).\n await alignDurableCollation(orm);\n}\n\n/** A MySQL identifier we are willing to interpolate into DDL (charset / collation names). */\nfunction isSafeSqlIdentifier(value: string): boolean {\n return /^[A-Za-z0-9_]+$/.test(value);\n}\n\n/**\n * Align each durable table's collation to the ORM's configured `collate` (MySQL/MariaDB only).\n *\n * MikroORM's auto-schema (`getUpdateSchemaSQL`) creates tables with the server's DEFAULT collation —\n * on MySQL 8.4 that's `utf8mb4_0900_ai_ci` — and ignores the `collate` config option. When the host\n * app pins a different collation on its own tables (commonly `utf8mb4_unicode_ci` via migrations), a\n * JOIN between a durable table and an app table throws \"Illegal mix of collations\". We converge it\n * here: read the configured collation and `CONVERT` only the durable tables whose collation differs.\n *\n * Idempotent (matching tables are skipped), non-fatal (a CONVERT failure is warned, never crashes\n * boot), and a no-op when no `collate` is configured or the platform isn't MySQL/MariaDB.\n */\nasync function alignDurableCollation(orm: MikroORM): Promise<void> {\n const platform = String(orm.em.getPlatform().constructor.name).toLowerCase();\n if (!platform.includes('mysql') && !platform.includes('maria')) {\n return;\n }\n const collate = orm.config.get('collate');\n if (typeof collate !== 'string' || !isSafeSqlIdentifier(collate)) {\n return;\n }\n // utf8mb4_unicode_ci → utf8mb4. CONVERT TO needs the charset that owns the collation.\n const charset = collate.split('_')[0];\n if (!charset || !isSafeSqlIdentifier(charset)) {\n return;\n }\n const connection = orm.em.getConnection();\n for (const table of DURABLE_TABLE_NAMES) {\n try {\n const rows = (await connection.execute(\n 'select table_collation as collation from information_schema.tables where table_schema = database() and table_name = ? limit 1',\n [table],\n )) as Array<{ collation?: string | null }>;\n const current = rows[0]?.collation;\n // Table absent (nothing to align) or already at the target collation — skip.\n if (current == null || current === collate) {\n continue;\n }\n await connection.execute(\n `alter table \\`${table}\\` convert to character set ${charset} collate ${collate}`,\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `[nestjs-durable-store-mikro-orm] could not align collation for \\`${table}\\` to ${collate} (left as-is): ${message}`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;ACCA,kBAA6B;AAgB7B,SAASA,UAAUC,UAAgB;AACjC,SAAOA,SAASC,QAAQ,UAAU,CAACC,MAAM,IAAIA,EAAEC,YAAW,CAAA,EAAI;AAChE;AAFSJ;AAIT,SAASK,YAAYC,QAA2B;AAC9C,MAA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GAAGM,MAAM;AACpDsF,IAAEkB,aAAa9G,GAAG8G;AAClBlB,IAAEmB,YAAY/G,GAAG+G;AACjBnB,IAAEoB,aAAahH,GAAGgH;AAClB,SAAOpB;AACT;AAnBShG;AAqBT,SAASJ,qBAAqBoG,GAAuB;AACnD,SAAO;IACLrJ,OAAOqJ,EAAErJ;IACTgD,KAAKqG,EAAErG;IACP2E,MAAM0B,EAAE1B;IACRuC,MAAMb,EAAEa;IACRC,QAAQd,EAAEc;IACV1I,QAAQ4H,EAAE5H;IACVmI,OAAOP,EAAEO,SAASlB;IAClBmB,QAAQR,EAAEQ,UAAUnB;IACpBoB,OAAQT,EAAES,SAASpB;IACnB0B,QAASf,EAAEe,UAAU1B;IACrB2B,UAAUhB,EAAEgB;IACZC,aAAajB,EAAEiB,eAAe5B;IAC9B3E,QAAQsF,EAAEtF,QAAQkG,QAAAA;IAClBM,YAAYlB,EAAEkB,cAAclB,EAAEmB;IAC9BA,WAAWnB,EAAEmB;IACbC,YAAYpB,EAAEoB;EAChB;AACF;AAnBSxH;","names":["snakeCase","property","replace","c","toLowerCase","columnNamer","naming","WorkflowRunEntity","id","workflow","workflowVersion","status","input","output","error","wakeAt","lockedBy","lockedUntil","recoveryAttempts","tags","searchAttributes","priority","createdAt","updatedAt","StepCheckpointEntity","runId","seq","name","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt","RunAttributeEntity","key","strValue","numValue","SignalWaiterEntity","token","BufferedSignalEntity","payload","durableEntities","options","col","workflowRuns","EntitySchema","class","tableName","indexes","properties","type","primary","fieldName","nullable","stepCheckpoints","runAttributes","signalWaiters","bufferedSignals","autoincrement","index","ENTITIES","DURABLE_TABLE_NAMES","Set","targetTable","statement","match","toLowerCase","isRequiredStructure","test","ensureMikroOrmDurableSchema","orm","sql","schema","getUpdateSchemaSQL","safe","ours","split","map","trim","filter","table","undefined","has","connection","em","getConnection","execute","err","message","Error","String","console","warn","alignDurableCollation","isSafeSqlIdentifier","value","platform","getPlatform","name","includes","collate","config","get","charset","rows","current","collation","MikroOrmStateStore","orm","ensureSchema","ensureMikroOrmDurableSchema","createRun","run","em","fork","create","WorkflowRunEntity","toRunEntity","flush","reindexAttributes","id","searchAttributes","updateRun","runId","patch","entity","findOneOrFail","Object","assign","fromRunEntity","attributes","forked","nativeDelete","RunAttributeEntity","rows","normalizeAttributeRows","length","insertMany","getRun","findOne","deleteRun","StepCheckpointEntity","SignalWaiterEntity","pruneTerminalRuns","policy","nowMs","limit","statuses","status","$in","ids","Set","maxAge","cutoff","Date","parseDuration","find","updatedAt","$lt","fields","orderBy","r","add","maxCount","size","offset","idList","slice","transactional","tem","getCheckpoint","seq","fromCheckpointEntity","saveCheckpoint","checkpoint","upsert","toCheckpointEntity","transaction","work","raw","cp","listIncompleteRuns","map","listPendingRuns","createdAt","listDueTimers","wakeAt","$ne","$lte","tryLockRun","owner","leaseUntilMs","affected","nativeUpdate","$or","lockedUntil","lockedBy","releaseRunLock","renewRunLock","listRuns","query","where","workflow","$and","tag","quote","idQuote","cols","attributeColumns","qb","createQueryBuilder","tagsCol","tagsColumn","pattern","replace","colExpr","jsonAsText","andWhere","f","attributeExistsSql","getResultList","alias","col","attributeColumnFor","numValue","strValue","cmp","sqlComparator","op","operand","attributeOperand","literal","String","a","table","sub","outerId","runPk","key","meta","getMetadata","get","field","prop","props","p","name","fieldNames","runMeta","properties","tableName","tags","colRef","platform","getPlatform","toLowerCase","includes","isMysql","ch","listCheckpoints","getLatestCheckpointByName","undefined","listCheckpointsByNamePrefix","prefixes","$like","putSignalWaiter","waiter","takeSignalWaiter","token","remove","listSignalWaiters","prefix","e","bufferSignal","payload","BufferedSignalEntity","persist","takeBufferedSignal","workflowVersion","input","output","error","recoveryAttempts","priority","getTime","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _mikro_orm_core from '@mikro-orm/core';
|
|
2
2
|
import { EntitySchema, MikroORM } from '@mikro-orm/core';
|
|
3
|
-
import { StepKind, RunStatus, StateStore, WorkflowRun, StepCheckpoint, RunQuery, SignalWaiter } from '@dudousxd/nestjs-durable-core';
|
|
3
|
+
import { StepKind, RunStatus, StateStore, WorkflowRun, RetentionPolicy, StepCheckpoint, RunQuery, SignalWaiter } from '@dudousxd/nestjs-durable-core';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* How property names map to physical column names. The durable tables are adapter-agnostic: a run
|
|
@@ -103,6 +103,7 @@ declare class MikroOrmStateStore implements StateStore {
|
|
|
103
103
|
private reindexAttributes;
|
|
104
104
|
getRun(runId: string): Promise<WorkflowRun | null>;
|
|
105
105
|
deleteRun(runId: string): Promise<void>;
|
|
106
|
+
pruneTerminalRuns(policy: RetentionPolicy, nowMs: number, limit: number): Promise<number>;
|
|
106
107
|
getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null>;
|
|
107
108
|
saveCheckpoint(checkpoint: StepCheckpoint): Promise<void>;
|
|
108
109
|
transaction<T>(work: (tx: {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _mikro_orm_core from '@mikro-orm/core';
|
|
2
2
|
import { EntitySchema, MikroORM } from '@mikro-orm/core';
|
|
3
|
-
import { StepKind, RunStatus, StateStore, WorkflowRun, StepCheckpoint, RunQuery, SignalWaiter } from '@dudousxd/nestjs-durable-core';
|
|
3
|
+
import { StepKind, RunStatus, StateStore, WorkflowRun, RetentionPolicy, StepCheckpoint, RunQuery, SignalWaiter } from '@dudousxd/nestjs-durable-core';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* How property names map to physical column names. The durable tables are adapter-agnostic: a run
|
|
@@ -103,6 +103,7 @@ declare class MikroOrmStateStore implements StateStore {
|
|
|
103
103
|
private reindexAttributes;
|
|
104
104
|
getRun(runId: string): Promise<WorkflowRun | null>;
|
|
105
105
|
deleteRun(runId: string): Promise<void>;
|
|
106
|
+
pruneTerminalRuns(policy: RetentionPolicy, nowMs: number, limit: number): Promise<number>;
|
|
106
107
|
getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null>;
|
|
107
108
|
saveCheckpoint(checkpoint: StepCheckpoint): Promise<void>;
|
|
108
109
|
transaction<T>(work: (tx: {
|
package/dist/index.js
CHANGED
|
@@ -85,6 +85,26 @@ function durableEntities(options = {}) {
|
|
|
85
85
|
const workflowRuns = new EntitySchema({
|
|
86
86
|
class: WorkflowRunEntity,
|
|
87
87
|
tableName: "durable_workflow_runs",
|
|
88
|
+
// Indexes mirror the Prisma adapter so a store swap keeps the same plan. The poller hits these
|
|
89
|
+
// every tick: `(status, wakeAt)` serves both the due-timer scan (status='suspended' AND wakeAt<=now)
|
|
90
|
+
// and, via its `status` prefix, the pending/incomplete status lookups; `(workflow, status)` serves
|
|
91
|
+
// the per-workflow timeout sweep. Without them every poll is a full scan of a table that only grows.
|
|
92
|
+
indexes: [
|
|
93
|
+
{
|
|
94
|
+
name: "durable_workflow_runs_status_wake_at_idx",
|
|
95
|
+
properties: [
|
|
96
|
+
"status",
|
|
97
|
+
"wakeAt"
|
|
98
|
+
]
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
name: "durable_workflow_runs_workflow_status_idx",
|
|
102
|
+
properties: [
|
|
103
|
+
"workflow",
|
|
104
|
+
"status"
|
|
105
|
+
]
|
|
106
|
+
}
|
|
107
|
+
],
|
|
88
108
|
properties: {
|
|
89
109
|
id: {
|
|
90
110
|
type: "string",
|
|
@@ -245,6 +265,24 @@ function durableEntities(options = {}) {
|
|
|
245
265
|
const runAttributes = new EntitySchema({
|
|
246
266
|
class: RunAttributeEntity,
|
|
247
267
|
tableName: "durable_run_attributes",
|
|
268
|
+
// The search-attribute EXISTS join (see the class docstring) pushes equality/range predicates down
|
|
269
|
+
// onto `(key, numValue)` / `(key, strValue)`; mirror the Prisma adapter so those scans stay indexed.
|
|
270
|
+
indexes: [
|
|
271
|
+
{
|
|
272
|
+
name: "durable_run_attributes_key_num_idx",
|
|
273
|
+
properties: [
|
|
274
|
+
"key",
|
|
275
|
+
"numValue"
|
|
276
|
+
]
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
name: "durable_run_attributes_key_str_idx",
|
|
280
|
+
properties: [
|
|
281
|
+
"key",
|
|
282
|
+
"strValue"
|
|
283
|
+
]
|
|
284
|
+
}
|
|
285
|
+
],
|
|
248
286
|
properties: {
|
|
249
287
|
runId: {
|
|
250
288
|
type: "string",
|
|
@@ -322,7 +360,7 @@ __name(durableEntities, "durableEntities");
|
|
|
322
360
|
var ENTITIES = durableEntities();
|
|
323
361
|
|
|
324
362
|
// src/mikro-orm-state-store.ts
|
|
325
|
-
import { attributeColumnFor, attributeOperand, normalizeAttributeRows, sqlComparator } from "@dudousxd/nestjs-durable-core";
|
|
363
|
+
import { attributeColumnFor, attributeOperand, normalizeAttributeRows, parseDuration, sqlComparator } from "@dudousxd/nestjs-durable-core";
|
|
326
364
|
|
|
327
365
|
// src/schema.ts
|
|
328
366
|
var DURABLE_TABLE_NAMES = /* @__PURE__ */ new Set([
|
|
@@ -333,12 +371,12 @@ var DURABLE_TABLE_NAMES = /* @__PURE__ */ new Set([
|
|
|
333
371
|
"durable_buffered_signals"
|
|
334
372
|
]);
|
|
335
373
|
function targetTable(statement) {
|
|
336
|
-
const match = statement.match(/^(?:create|alter)\s+table\s+(?:if\s+not\s+exists\s+)?[`"']?([\w$]+)[`"']?/i);
|
|
374
|
+
const match = statement.match(/^(?:create\s+(?:unique\s+)?index\s+.+?\s+on\s+|(?:create|alter)\s+table\s+(?:if\s+not\s+exists\s+)?)[`"']?([\w$]+)[`"']?/i);
|
|
337
375
|
return match?.[1]?.toLowerCase();
|
|
338
376
|
}
|
|
339
377
|
__name(targetTable, "targetTable");
|
|
340
378
|
function isRequiredStructure(statement) {
|
|
341
|
-
return /\b(?:create\s+table|add\s+(?:column|index|constraint|key|unique|fulltext))\b/i.test(statement);
|
|
379
|
+
return /\b(?:create\s+table|create\s+(?:unique\s+)?index|add\s+(?:column|index|constraint|key|unique|fulltext))\b/i.test(statement);
|
|
342
380
|
}
|
|
343
381
|
__name(isRequiredStructure, "isRequiredStructure");
|
|
344
382
|
async function ensureMikroOrmDurableSchema(orm) {
|
|
@@ -462,6 +500,73 @@ var MikroOrmStateStore = class {
|
|
|
462
500
|
id: runId
|
|
463
501
|
});
|
|
464
502
|
}
|
|
503
|
+
async pruneTerminalRuns(policy, nowMs, limit) {
|
|
504
|
+
if (policy.statuses.length === 0 || limit <= 0) return 0;
|
|
505
|
+
const em = this.orm.em.fork();
|
|
506
|
+
const status = {
|
|
507
|
+
$in: policy.statuses
|
|
508
|
+
};
|
|
509
|
+
const ids = /* @__PURE__ */ new Set();
|
|
510
|
+
if (policy.maxAge != null) {
|
|
511
|
+
const cutoff = new Date(nowMs - parseDuration(policy.maxAge));
|
|
512
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
513
|
+
status,
|
|
514
|
+
updatedAt: {
|
|
515
|
+
$lt: cutoff
|
|
516
|
+
}
|
|
517
|
+
}, {
|
|
518
|
+
fields: [
|
|
519
|
+
"id"
|
|
520
|
+
],
|
|
521
|
+
orderBy: {
|
|
522
|
+
updatedAt: "asc"
|
|
523
|
+
},
|
|
524
|
+
limit
|
|
525
|
+
});
|
|
526
|
+
for (const r of rows) ids.add(r.id);
|
|
527
|
+
}
|
|
528
|
+
if (policy.maxCount != null && ids.size < limit) {
|
|
529
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
530
|
+
status
|
|
531
|
+
}, {
|
|
532
|
+
fields: [
|
|
533
|
+
"id"
|
|
534
|
+
],
|
|
535
|
+
orderBy: {
|
|
536
|
+
updatedAt: "desc",
|
|
537
|
+
id: "desc"
|
|
538
|
+
},
|
|
539
|
+
limit,
|
|
540
|
+
offset: policy.maxCount
|
|
541
|
+
});
|
|
542
|
+
for (const r of rows) {
|
|
543
|
+
ids.add(r.id);
|
|
544
|
+
if (ids.size >= limit) break;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
if (ids.size === 0) return 0;
|
|
548
|
+
const idList = [
|
|
549
|
+
...ids
|
|
550
|
+
].slice(0, limit);
|
|
551
|
+
const runId = {
|
|
552
|
+
$in: idList
|
|
553
|
+
};
|
|
554
|
+
await em.transactional(async (tem) => {
|
|
555
|
+
await tem.nativeDelete(StepCheckpointEntity, {
|
|
556
|
+
runId
|
|
557
|
+
});
|
|
558
|
+
await tem.nativeDelete(SignalWaiterEntity, {
|
|
559
|
+
runId
|
|
560
|
+
});
|
|
561
|
+
await tem.nativeDelete(RunAttributeEntity, {
|
|
562
|
+
runId
|
|
563
|
+
});
|
|
564
|
+
await tem.nativeDelete(WorkflowRunEntity, {
|
|
565
|
+
id: runId
|
|
566
|
+
});
|
|
567
|
+
});
|
|
568
|
+
return idList.length;
|
|
569
|
+
}
|
|
465
570
|
async getCheckpoint(runId, seq) {
|
|
466
571
|
const em = this.orm.em.fork();
|
|
467
572
|
const entity = await em.findOne(StepCheckpointEntity, {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/entities.ts","../src/mikro-orm-state-store.ts","../src/schema.ts"],"sourcesContent":["import type { RunStatus, StepKind } from '@dudousxd/nestjs-durable-core';\nimport { EntitySchema } from '@mikro-orm/core';\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 TypeORM,\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\nfunction 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 `em.create`/`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;\n lockedUntil?: Date;\n recoveryAttempts?: number;\n tags?: string[] | null;\n searchAttributes?: Record<string, string | number | boolean> | null;\n priority?: number | 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;\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}\n\nexport class BufferedSignalEntity {\n id!: number;\n token!: string;\n payload?: unknown;\n}\n\n/**\n * Build the durable MikroORM entity schemas with column names pinned per `naming` (default\n * `'snake_case'`). Register the result in your MikroORM config / `MikroOrmModule.forFeature`.\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 class: WorkflowRunEntity,\n tableName: 'durable_workflow_runs',\n properties: {\n id: { type: 'string', primary: true, fieldName: col('id') },\n workflow: { type: 'string', fieldName: col('workflow') },\n workflowVersion: { type: 'string', fieldName: col('workflowVersion') },\n status: { type: 'string', fieldName: col('status') },\n input: { type: 'json', nullable: true, fieldName: col('input') },\n output: { type: 'json', nullable: true, fieldName: col('output') },\n error: { type: 'json', nullable: true, fieldName: col('error') },\n wakeAt: { type: 'Date', nullable: true, fieldName: col('wakeAt') },\n lockedBy: { type: 'string', nullable: true, fieldName: col('lockedBy') },\n lockedUntil: { type: 'Date', nullable: true, fieldName: col('lockedUntil') },\n recoveryAttempts: { type: 'integer', nullable: true, fieldName: col('recoveryAttempts') },\n tags: { type: 'json', nullable: true, fieldName: col('tags') },\n searchAttributes: { type: 'json', nullable: true, fieldName: col('searchAttributes') },\n priority: { type: 'integer', nullable: true, fieldName: col('priority') },\n createdAt: { type: 'Date', fieldName: col('createdAt') },\n updatedAt: { type: 'Date', fieldName: col('updatedAt') },\n },\n });\n\n const stepCheckpoints = new EntitySchema<StepCheckpointEntity>({\n class: StepCheckpointEntity,\n tableName: 'durable_step_checkpoints',\n properties: {\n runId: { type: 'string', primary: true, fieldName: col('runId') },\n seq: { type: 'integer', primary: true, fieldName: col('seq') },\n name: { type: 'string', fieldName: col('name') },\n kind: { type: 'string', fieldName: col('kind') },\n stepId: { type: 'string', fieldName: col('stepId') },\n status: { type: 'string', fieldName: col('status') },\n input: { type: 'json', nullable: true, fieldName: col('input') },\n output: { type: 'json', nullable: true, fieldName: col('output') },\n error: { type: 'json', nullable: true, fieldName: col('error') },\n events: { type: 'json', nullable: true, fieldName: col('events') },\n attempts: { type: 'integer', fieldName: col('attempts') },\n workerGroup: { type: 'string', nullable: true, fieldName: col('workerGroup') },\n wakeAt: { type: 'Date', nullable: true, fieldName: col('wakeAt') },\n enqueuedAt: { type: 'Date', nullable: true, fieldName: col('enqueuedAt') },\n startedAt: { type: 'Date', fieldName: col('startedAt') },\n finishedAt: { type: 'Date', fieldName: col('finishedAt') },\n },\n });\n\n const runAttributes = new EntitySchema<RunAttributeEntity>({\n class: RunAttributeEntity,\n tableName: 'durable_run_attributes',\n properties: {\n runId: { type: 'string', primary: true, fieldName: col('runId') },\n key: { type: 'string', primary: true, fieldName: col('key') },\n strValue: { type: 'string', nullable: true, fieldName: col('strValue') },\n // `float`/`double` is portable across SQLite/MySQL/Postgres for numeric range scans.\n numValue: { type: 'float', nullable: true, fieldName: col('numValue') },\n },\n });\n\n const signalWaiters = new EntitySchema<SignalWaiterEntity>({\n class: SignalWaiterEntity,\n tableName: 'durable_signal_waiters',\n properties: {\n token: { type: 'string', primary: true, fieldName: col('token') },\n runId: { type: 'string', fieldName: col('runId') },\n seq: { type: 'integer', fieldName: col('seq') },\n },\n });\n\n const bufferedSignals = new EntitySchema<BufferedSignalEntity>({\n class: BufferedSignalEntity,\n tableName: 'durable_buffered_signals',\n properties: {\n id: { type: 'integer', primary: true, autoincrement: true, fieldName: col('id') },\n token: { type: 'string', index: true, fieldName: col('token') },\n payload: { type: 'json', nullable: true, fieldName: col('payload') },\n },\n });\n\n return [workflowRuns, stepCheckpoints, runAttributes, signalWaiters, bufferedSignals];\n}\n\n/** Durable entity schemas with the canonical `'snake_case'` column names. */\nexport const ENTITIES = durableEntities();\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 type { EntityManager, MikroORM } from '@mikro-orm/core';\n\n/** Minimal structural surface of the SQL EntityManager's QueryBuilder (from `@mikro-orm/knex`),\n * typed here so the adapter needn't add a hard dependency on the knex types — a real SQL-driver EM\n * satisfies it at runtime. */\ninterface DurableQueryBuilder<T> {\n where(cond: Record<string, unknown>): DurableQueryBuilder<T>;\n andWhere(cond: string): DurableQueryBuilder<T>;\n orderBy(cond: Record<string, unknown>): DurableQueryBuilder<T>;\n limit(n: number): DurableQueryBuilder<T>;\n offset(n: number): DurableQueryBuilder<T>;\n getResultList(): Promise<T[]>;\n}\ntype SqlEm = EntityManager & {\n createQueryBuilder<T>(entity: unknown, alias: string): DurableQueryBuilder<T>;\n};\n\n/** Resolved side-table column names (per the active naming strategy) for the raw EXISTS pushdown. */\ninterface AttributeColumns {\n table: string;\n /** Side-table FK column (the run id on `durable_run_attributes`). */\n runId: string;\n /** Run table PK column (the `id` on `durable_workflow_runs`) used for the outer correlation. */\n runPk: string;\n key: string;\n strValue: string;\n numValue: string;\n}\nimport {\n BufferedSignalEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n StepCheckpointEntity,\n WorkflowRunEntity,\n} from './entities';\nimport { ensureMikroOrmDurableSchema } from './schema';\n\n/**\n * MikroORM-backed `StateStore`. Works on any MikroORM driver — Postgres, MySQL, SQLite (tested);\n * timestamps and `wakeAt` use native datetime columns. Each operation runs on a forked\n * EntityManager so it owns its unit of work.\n */\nexport class MikroOrmStateStore implements StateStore {\n constructor(private readonly orm: MikroORM) {}\n\n async ensureSchema(): Promise<void> {\n await ensureMikroOrmDurableSchema(this.orm);\n }\n\n async createRun(run: WorkflowRun): Promise<void> {\n const em = this.orm.em.fork();\n em.create(WorkflowRunEntity, toRunEntity(run));\n await em.flush();\n await this.reindexAttributes(run.id, run.searchAttributes);\n }\n\n async updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n const em = this.orm.em.fork();\n const entity = await em.findOneOrFail(WorkflowRunEntity, { id: runId });\n Object.assign(entity, toRunEntity({ ...fromRunEntity(entity), ...patch } as WorkflowRun));\n await em.flush();\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 /** 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 forked?: EntityManager,\n ): Promise<void> {\n const em = forked ?? this.orm.em.fork();\n await em.nativeDelete(RunAttributeEntity, { runId });\n const rows = normalizeAttributeRows(runId, attributes);\n if (rows.length) await em.insertMany(RunAttributeEntity, rows);\n }\n\n async getRun(runId: string): Promise<WorkflowRun | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(WorkflowRunEntity, { id: runId });\n return entity ? fromRunEntity(entity) : null;\n }\n\n async deleteRun(runId: string): Promise<void> {\n const em = this.orm.em.fork();\n // Children first, then the run row — checkpoints, signal waiters, and the normalized\n // attribute side-table, so nothing dangles after the run is gone.\n await em.nativeDelete(StepCheckpointEntity, { runId });\n await em.nativeDelete(SignalWaiterEntity, { runId });\n await em.nativeDelete(RunAttributeEntity, { runId });\n await em.nativeDelete(WorkflowRunEntity, { id: runId });\n }\n\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(StepCheckpointEntity, { runId, seq });\n return entity ? fromCheckpointEntity(entity) : null;\n }\n\n async saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n const em = this.orm.em.fork();\n await em.upsert(StepCheckpointEntity, toCheckpointEntity(checkpoint));\n await em.flush();\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.orm.em.fork().transactional(async (em) =>\n work({\n raw: em,\n saveCheckpoint: async (cp) => {\n await em.upsert(StepCheckpointEntity, toCheckpointEntity(cp));\n },\n }),\n );\n }\n\n async listIncompleteRuns(): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(WorkflowRunEntity, { status: { $in: ['running', 'cancelling'] } });\n return rows.map(fromRunEntity);\n }\n\n async listPendingRuns(limit: number): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(\n WorkflowRunEntity,\n { status: 'pending' },\n { orderBy: { createdAt: 'asc' }, limit }, // FIFO dispatch\n );\n return rows.map(fromRunEntity);\n }\n\n async listDueTimers(nowMs: number): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(WorkflowRunEntity, {\n status: 'suspended',\n wakeAt: { $ne: null, $lte: new Date(nowMs) },\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 em = this.orm.em.fork();\n const affected = await em.nativeUpdate(\n WorkflowRunEntity,\n { id: runId, $or: [{ lockedUntil: null }, { lockedUntil: { $lte: new Date(nowMs) } }] },\n { lockedBy: owner, lockedUntil: new Date(leaseUntilMs) },\n );\n return affected === 1;\n }\n\n async releaseRunLock(runId: string): Promise<void> {\n const em = this.orm.em.fork();\n await em.nativeUpdate(WorkflowRunEntity, { id: runId }, { lockedBy: null, lockedUntil: null });\n }\n\n async renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n const em = this.orm.em.fork();\n const affected = await em.nativeUpdate(\n WorkflowRunEntity,\n { id: runId, lockedBy: owner },\n { lockedUntil: new Date(leaseUntilMs) },\n );\n return affected === 1;\n }\n\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const where: Record<string, unknown> = {};\n if (query.workflow) where.workflow = query.workflow;\n // `status IN (...)`; an empty set matches nothing (mirrors the in-memory store). When both the\n // single `status` and `statuses` are set, AND them so the narrower set wins.\n if (query.status && query.statuses) {\n where.$and = [{ status: query.status }, { status: { $in: query.statuses } }];\n } else if (query.status) {\n where.status = query.status;\n } else if (query.statuses) {\n where.status = { $in: query.statuses };\n }\n const orderBy = { createdAt: 'desc' as const }; // newest first — recent runs on top in the dashboard\n // `tags`/attributes need raw SQL pushed through the QueryBuilder:\n // - tag: `tags` is a JSON column (native json/jsonb on PG/MySQL), and MikroORM JSON-serializes a\n // `{ $like }` operand (wrapping/escaping the LIKE pattern) so a plain where corrupts it to no\n // matches. A raw LIKE on the column-as-text matches the quoted token so `etl` doesn't match\n // `etl-foo`. Postgres `jsonb` rejects `LIKE` directly, so cast to text per dialect.\n // - attributes: each filter becomes a raw EXISTS against the normalized side-table, so the DB\n // filters AND paginates — no full scan + in-process filter (ANDed: one EXISTS per filter).\n // Use a QueryBuilder with a fixed root alias `r` so the raw correlations are stable across drivers.\n if (query.tag || query.attributes?.length) {\n const quote = this.idQuote(em);\n const cols = this.attributeColumns(em);\n const qb = (em as SqlEm)\n .createQueryBuilder<WorkflowRunEntity>(WorkflowRunEntity, 'r')\n .where(where)\n .orderBy(orderBy);\n if (query.tag) {\n const tagsCol = this.tagsColumn(em);\n const pattern = `%\"${query.tag.replace(/'/g, \"''\")}\"%`;\n const colExpr = this.jsonAsText(em, `${quote('r')}.${quote(tagsCol)}`);\n qb.andWhere(`${colExpr} LIKE '${pattern}'`);\n }\n for (const f of query.attributes ?? []) {\n qb.andWhere(this.attributeExistsSql(f, quote, 'r', cols));\n }\n if (query.limit != null) qb.limit(query.limit);\n if (query.offset != null) qb.offset(query.offset);\n const rows = await qb.getResultList();\n return rows.map(fromRunEntity);\n }\n const rows = await em.find(WorkflowRunEntity, where, {\n ...(query.limit != null ? { limit: query.limit } : {}),\n ...(query.offset != null ? { offset: query.offset } : {}),\n orderBy,\n });\n return rows.map(fromRunEntity);\n }\n\n /** One attribute predicate as a raw EXISTS subquery on the side-table, correlated to the outer run\n * alias. `<>` (ne) also excludes runs where the attribute is absent (missing-key-never-matches):\n * EXISTS already requires a present row, so EXISTS(... <> ...) is exactly ne-with-present. Numeric\n * operands compare the num column, everything else the str column. Identifiers are quoted per\n * driver and operands are inlined as literals (string operands are escaped by doubling quotes). */\n private attributeExistsSql(\n f: AttributeFilter,\n quote: (id: string) => string,\n alias: string,\n cols: AttributeColumns,\n ): string {\n const col = attributeColumnFor(f) === 'numValue' ? cols.numValue : cols.strValue;\n const cmp = sqlComparator(f.op);\n const operand = attributeOperand(f);\n const literal =\n typeof operand === 'number' ? String(operand) : `'${String(operand).replace(/'/g, \"''\")}'`;\n const a = quote(cols.table);\n const sub = quote('a');\n const outerId = `${quote(alias)}.${quote(cols.runPk)}`; // run PK column on the outer alias\n return `EXISTS (SELECT 1 FROM ${a} ${sub} WHERE ${sub}.${quote(cols.runId)} = ${outerId} AND ${sub}.${quote(cols.key)} = '${f.key.replace(/'/g, \"''\")}' AND ${sub}.${quote(col)} ${cmp} ${literal})`;\n }\n\n /** Resolve the side-table's actual column names from MikroORM metadata, so the raw EXISTS matches\n * the active naming strategy (underscore vs camelCase) rather than guessing. The run PK column is\n * reused for BOTH the outer correlation and the side-table FK (they share the same fieldName). */\n private attributeColumns(em: EntityManager): AttributeColumns {\n const meta = em.getMetadata().get(RunAttributeEntity);\n const field = (prop: string) =>\n meta.props.find((p) => p.name === prop)?.fieldNames?.[0] ?? prop;\n const runMeta = em.getMetadata().get(WorkflowRunEntity);\n const runPk = runMeta.properties.id?.fieldNames?.[0] ?? 'id';\n return {\n table: meta.tableName,\n runId: field('runId'),\n runPk,\n key: field('key'),\n strValue: field('strValue'),\n numValue: field('numValue'),\n };\n }\n\n /** Resolve the `tags` column name from metadata (per the active naming strategy), for the raw LIKE. */\n private tagsColumn(em: EntityManager): string {\n const runMeta = em.getMetadata().get(WorkflowRunEntity);\n return runMeta.properties.tags?.fieldNames?.[0] ?? 'tags';\n }\n\n /** Wrap a JSON column reference so it can be `LIKE`d as text. Postgres `jsonb`/`json` rejects `LIKE`\n * directly (`operator does not exist: jsonb ~~ unknown`) — cast to `text`; MySQL JSON needs an\n * explicit `CHAR` cast; SQLite stores JSON as text already, so no cast. */\n private jsonAsText(em: EntityManager, colRef: string): string {\n const platform = String(em.getPlatform().constructor.name).toLowerCase();\n if (platform.includes('postgre')) return `${colRef}::text`;\n if (platform.includes('mysql') || platform.includes('mariadb'))\n return `CAST(${colRef} AS CHAR)`;\n return colRef;\n }\n\n /** Quote an identifier per the active SQL driver (MySQL/MariaDB backtick, others double-quote). */\n private idQuote(em: EntityManager): (id: string) => string {\n const platform = String(em.getPlatform().constructor.name).toLowerCase();\n const isMysql = platform.includes('mysql') || platform.includes('mariadb');\n const ch = isMysql ? '`' : '\"';\n return (id: string) => `${ch}${id}${ch}`;\n }\n\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(StepCheckpointEntity, { runId }, { orderBy: { seq: 'asc' } });\n return rows.map(fromCheckpointEntity);\n }\n\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(\n StepCheckpointEntity,\n { runId, name },\n { orderBy: { seq: 'desc' } },\n );\n return entity ? fromCheckpointEntity(entity) : undefined;\n }\n\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n if (prefixes.length === 0) return [];\n const em = this.orm.em.fork();\n const rows = await em.find(\n StepCheckpointEntity,\n { runId, $or: prefixes.map((p) => ({ name: { $like: `${p}%` } })) },\n { orderBy: { seq: 'asc' } },\n );\n return rows.map(fromCheckpointEntity);\n }\n\n async putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n const em = this.orm.em.fork();\n await em.upsert(SignalWaiterEntity, { ...waiter });\n await em.flush();\n }\n\n async takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(SignalWaiterEntity, { token });\n if (!entity) return null;\n const waiter: SignalWaiter = { token: entity.token, runId: entity.runId, seq: entity.seq };\n await em.remove(entity).flush();\n return waiter;\n }\n\n async listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(SignalWaiterEntity, { token: { $like: `${prefix}%` } });\n return rows.map((e) => ({ token: e.token, runId: e.runId, seq: e.seq }));\n }\n\n async bufferSignal(token: string, payload: unknown): Promise<void> {\n const em = this.orm.em.fork();\n const e = new BufferedSignalEntity();\n e.token = token;\n e.payload = payload ?? null;\n em.persist(e);\n await em.flush();\n }\n\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(BufferedSignalEntity, { token }, { orderBy: { id: 'asc' } });\n if (!entity) return null;\n const payload = entity.payload ?? undefined;\n await em.remove(entity).flush();\n return { payload };\n }\n}\n\nfunction toRunEntity(run: WorkflowRun): WorkflowRunEntity {\n const e = new WorkflowRunEntity();\n e.id = run.id;\n e.workflow = run.workflow;\n e.workflowVersion = run.workflowVersion;\n e.status = run.status;\n e.input = run.input ?? null;\n e.output = run.output ?? null;\n e.error = run.error ?? null;\n if (run.wakeAt != null) e.wakeAt = new Date(run.wakeAt);\n if (run.lockedBy !== undefined) e.lockedBy = run.lockedBy;\n if (run.lockedUntil != null) e.lockedUntil = new Date(run.lockedUntil);\n if (run.recoveryAttempts !== undefined) e.recoveryAttempts = run.recoveryAttempts;\n e.tags = run.tags ?? null;\n e.searchAttributes = run.searchAttributes ?? null;\n e.priority = run.priority ?? null;\n e.createdAt = run.createdAt;\n e.updatedAt = run.updatedAt;\n return e;\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?.getTime(),\n lockedBy: e.lockedBy ?? undefined,\n lockedUntil: e.lockedUntil?.getTime(),\n recoveryAttempts: e.recoveryAttempts ?? undefined,\n tags: e.tags ?? undefined,\n searchAttributes: e.searchAttributes ?? undefined,\n priority: e.priority ?? undefined,\n createdAt: e.createdAt,\n updatedAt: e.updatedAt,\n };\n}\n\nfunction toCheckpointEntity(cp: StepCheckpoint): StepCheckpointEntity {\n const e = new StepCheckpointEntity();\n e.runId = cp.runId;\n e.seq = cp.seq;\n e.name = cp.name;\n e.kind = cp.kind;\n e.stepId = cp.stepId;\n e.status = cp.status;\n e.input = cp.input ?? null;\n e.output = cp.output ?? null;\n e.error = cp.error ?? null;\n e.events = cp.events ?? null;\n e.attempts = cp.attempts;\n if (cp.workerGroup !== undefined) e.workerGroup = cp.workerGroup;\n if (cp.wakeAt != null) e.wakeAt = new Date(cp.wakeAt);\n e.enqueuedAt = cp.enqueuedAt;\n e.startedAt = cp.startedAt;\n e.finishedAt = cp.finishedAt;\n return e;\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 wakeAt: e.wakeAt?.getTime(),\n enqueuedAt: e.enqueuedAt ?? e.startedAt,\n startedAt: e.startedAt,\n finishedAt: e.finishedAt,\n };\n}\n","import type { MikroORM } from '@mikro-orm/core';\n\n/**\n * The tables this store owns. Kept in sync with the `tableName`s in `./entities`. Used to scope\n * schema management to our own tables (see {@link ensureMikroOrmDurableSchema}).\n */\nconst DURABLE_TABLE_NAMES = new Set([\n 'durable_workflow_runs',\n 'durable_step_checkpoints',\n 'durable_run_attributes',\n 'durable_signal_waiters',\n 'durable_buffered_signals',\n]);\n\n/** The table a `create table` / `alter table` statement targets, lower-cased; undefined otherwise. */\nfunction targetTable(statement: string): string | undefined {\n const match = statement.match(\n /^(?:create|alter)\\s+table\\s+(?:if\\s+not\\s+exists\\s+)?[`\"']?([\\w$]+)[`\"']?/i,\n );\n return match?.[1]?.toLowerCase();\n}\n\n/**\n * Whether a statement adds structure the store REQUIRES — a failure here is fatal (the store can't\n * run without the table/column/index). A column TYPE alignment (`modify`/`alter column ... type`)\n * is best-effort: the column already holds the data (the store serializes JSON to/from it regardless\n * of the declared type), so failing to converge its type — e.g. a legacy `longtext` value that won't\n * cast to `json` because it was truncated under an older `text` column — must NOT crash boot.\n */\nfunction isRequiredStructure(statement: string): boolean {\n return /\\b(?:create\\s+table|add\\s+(?:column|index|constraint|key|unique|fulltext))\\b/i.test(\n statement,\n );\n}\n\n/**\n * Idempotently create/extend ONLY the durable tables (additive — never drops). Safe to run on every\n * boot (auto-schema) and from a MikroORM migration when you disable auto-schema:\n *\n * ```ts\n * export class AddDurableTables extends Migration {\n * async up() { await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm()); }\n * }\n * ```\n *\n * It does NOT run a whole-ORM `schema.update()`. When the store shares the host app's ORM (the\n * recommended setup — a single ORM avoids MikroORM's global-metadata clobber between instances),\n * a full `schema.update()` would try to reconcile EVERY app table to the entity metadata: on a\n * migration-managed schema that means recreating the migrations table and dropping app foreign keys.\n * Instead we compute the safe additive diff and execute only the statements that target our own\n * `durable_*` tables. `getUpdateSchemaSQL` already emits a `create table` only for a missing table\n * and `alter table ... add` only for missing columns, so existing tables — and the entire rest of\n * the host schema — are left untouched.\n */\nexport async function ensureMikroOrmDurableSchema(orm: MikroORM): Promise<void> {\n const sql = await orm.schema.getUpdateSchemaSQL({ safe: true });\n const ours = sql\n .split(';')\n .map((statement) => statement.trim())\n .filter((statement) => {\n const table = targetTable(statement);\n return table !== undefined && DURABLE_TABLE_NAMES.has(table);\n });\n const connection = orm.em.getConnection();\n for (const statement of ours) {\n try {\n await connection.execute(statement);\n } catch (err) {\n // Required structure (create table / add column / add index) must succeed — rethrow.\n if (isRequiredStructure(statement)) {\n throw err;\n }\n // A best-effort type alignment (e.g. legacy `longtext` → `json`) failed, typically because an\n // existing column holds a value that can't cast to the target type (a relic of an older column\n // type). The column already stores the data and the store reads/writes it via serialization, so\n // leave it as-is and continue rather than crashing boot. Surfaced so the data can be repaired\n // out of band (e.g. `UPDATE … SET col = NULL WHERE JSON_VALID(col) = 0` for a disposable column).\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `[nestjs-durable-store-mikro-orm] skipped a non-structural durable-schema statement that failed; the column is left as-is (functional) — repair the data out of band to converge its type. Statement: ${statement} — ${message}`,\n );\n }\n }\n\n // Converge collation last, once the tables exist (whether just created above or pre-existing).\n await alignDurableCollation(orm);\n}\n\n/** A MySQL identifier we are willing to interpolate into DDL (charset / collation names). */\nfunction isSafeSqlIdentifier(value: string): boolean {\n return /^[A-Za-z0-9_]+$/.test(value);\n}\n\n/**\n * Align each durable table's collation to the ORM's configured `collate` (MySQL/MariaDB only).\n *\n * MikroORM's auto-schema (`getUpdateSchemaSQL`) creates tables with the server's DEFAULT collation —\n * on MySQL 8.4 that's `utf8mb4_0900_ai_ci` — and ignores the `collate` config option. When the host\n * app pins a different collation on its own tables (commonly `utf8mb4_unicode_ci` via migrations), a\n * JOIN between a durable table and an app table throws \"Illegal mix of collations\". We converge it\n * here: read the configured collation and `CONVERT` only the durable tables whose collation differs.\n *\n * Idempotent (matching tables are skipped), non-fatal (a CONVERT failure is warned, never crashes\n * boot), and a no-op when no `collate` is configured or the platform isn't MySQL/MariaDB.\n */\nasync function alignDurableCollation(orm: MikroORM): Promise<void> {\n const platform = String(orm.em.getPlatform().constructor.name).toLowerCase();\n if (!platform.includes('mysql') && !platform.includes('maria')) {\n return;\n }\n const collate = orm.config.get('collate');\n if (typeof collate !== 'string' || !isSafeSqlIdentifier(collate)) {\n return;\n }\n // utf8mb4_unicode_ci → utf8mb4. CONVERT TO needs the charset that owns the collation.\n const charset = collate.split('_')[0];\n if (!charset || !isSafeSqlIdentifier(charset)) {\n return;\n }\n const connection = orm.em.getConnection();\n for (const table of DURABLE_TABLE_NAMES) {\n try {\n const rows = (await connection.execute(\n 'select table_collation as collation from information_schema.tables where table_schema = database() and table_name = ? limit 1',\n [table],\n )) as Array<{ collation?: string | null }>;\n const current = rows[0]?.collation;\n // Table absent (nothing to align) or already at the target collation — skip.\n if (current == null || current === collate) {\n continue;\n }\n await connection.execute(\n `alter table \\`${table}\\` convert to character set ${charset} collate ${collate}`,\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `[nestjs-durable-store-mikro-orm] could not align collation for \\`${table}\\` to ${collate} (left as-is): ${message}`,\n );\n }\n }\n}\n"],"mappings":";;;;AACA,SAASA,oBAAoB;AAgB7B,SAASC,UAAUC,UAAgB;AACjC,SAAOA,SAASC,QAAQ,UAAU,CAACC,MAAM,IAAIA,EAAEC,YAAW,CAAA,EAAI;AAChE;AAFSJ;AAIT,SAASK,YAAYC,QAA2B;AAC9C,MAAIA,WAAW,aAAc,QAAON;AACpC,MAAIM,WAAW,WAAY,QAAO,CAACL,aAAaA;AAChD,SAAOK;AACT;AAJSD;AAUF,IAAME,oBAAN,MAAMA;EA9Bb,OA8BaA;;;EACXC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;AACF;AAEO,IAAMC,uBAAN,MAAMA;EAjDb,OAiDaA;;;EACXC;EACAC;EACAC;EACAC;EACAC;EACAlB;EACAC;EACAC;EACAC;EACAgB;EACAC;EACAC;EACAjB;EACAkB;EACAC;EACAC;AACF;AAQO,IAAMC,qBAAN,MAAMA;EA1Eb,OA0EaA;;;EACXX;EACAY;EACAC;EACAC;AACF;AAEO,IAAMC,qBAAN,MAAMA;EAjFb,OAiFaA;;;EACXC;EACAhB;EACAC;AACF;AAEO,IAAMgB,uBAAN,MAAMA;EAvFb,OAuFaA;;;EACXlC;EACAiC;EACAE;AACF;AAUO,SAASC,gBAAgBC,UAA4C,CAAC,GAAC;AAC5E,QAAMC,MAAMzC,YAAYwC,QAAQvC,UAAU,YAAA;AAE1C,QAAMyC,eAAe,IAAIC,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AMyF,GAAEzF,SAAS,IAAIG,KAAKf,GAAGY,MAAM;AACpDyF,IAAEmB,aAAaxH,GAAGwH;AAClBnB,IAAEoB,YAAYzH,GAAGyH;AACjBpB,IAAEqB,aAAa1H,GAAG0H;AAClB,SAAOrB;AACT;AAnBS1G;AAqBT,SAASJ,qBAAqB8G,GAAuB;AACnD,SAAO;IACLpI,OAAOoI,EAAEpI;IACTqB,KAAK+G,EAAE/G;IACPqF,MAAM0B,EAAE1B;IACRwC,MAAMd,EAAEc;IACRC,QAAQf,EAAEe;IACVjH,QAAQkG,EAAElG;IACVyG,OAAOP,EAAEO,SAASlB;IAClBmB,QAAQR,EAAEQ,UAAUnB;IACpBoB,OAAQT,EAAES,SAASpB;IACnB2B,QAAShB,EAAEgB,UAAU3B;IACrB4B,UAAUjB,EAAEiB;IACZC,aAAalB,EAAEkB,eAAe7B;IAC9B9E,QAAQyF,EAAEzF,QAAQsG,QAAAA;IAClBM,YAAYnB,EAAEmB,cAAcnB,EAAEoB;IAC9BA,WAAWpB,EAAEoB;IACbC,YAAYrB,EAAEqB;EAChB;AACF;AAnBSnI;","names":["EntitySchema","snakeCase","property","replace","c","toLowerCase","columnNamer","naming","WorkflowRunEntity","id","workflow","workflowVersion","status","input","output","error","wakeAt","lockedBy","lockedUntil","recoveryAttempts","tags","searchAttributes","priority","createdAt","updatedAt","StepCheckpointEntity","runId","seq","name","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt","RunAttributeEntity","key","strValue","numValue","SignalWaiterEntity","token","BufferedSignalEntity","payload","durableEntities","options","col","workflowRuns","EntitySchema","class","tableName","properties","type","primary","fieldName","nullable","stepCheckpoints","runAttributes","signalWaiters","bufferedSignals","autoincrement","index","ENTITIES","attributeColumnFor","attributeOperand","normalizeAttributeRows","sqlComparator","DURABLE_TABLE_NAMES","Set","targetTable","statement","match","toLowerCase","isRequiredStructure","test","ensureMikroOrmDurableSchema","orm","sql","schema","getUpdateSchemaSQL","safe","ours","split","map","trim","filter","table","undefined","has","connection","em","getConnection","execute","err","message","Error","String","console","warn","alignDurableCollation","isSafeSqlIdentifier","value","platform","getPlatform","name","includes","collate","config","get","charset","rows","current","collation","MikroOrmStateStore","orm","ensureSchema","ensureMikroOrmDurableSchema","createRun","run","em","fork","create","WorkflowRunEntity","toRunEntity","flush","reindexAttributes","id","searchAttributes","updateRun","runId","patch","entity","findOneOrFail","Object","assign","fromRunEntity","attributes","forked","nativeDelete","RunAttributeEntity","rows","normalizeAttributeRows","length","insertMany","getRun","findOne","deleteRun","StepCheckpointEntity","SignalWaiterEntity","getCheckpoint","seq","fromCheckpointEntity","saveCheckpoint","checkpoint","upsert","toCheckpointEntity","transaction","work","transactional","raw","cp","listIncompleteRuns","find","status","$in","map","listPendingRuns","limit","orderBy","createdAt","listDueTimers","nowMs","wakeAt","$ne","$lte","Date","tryLockRun","owner","leaseUntilMs","affected","nativeUpdate","$or","lockedUntil","lockedBy","releaseRunLock","renewRunLock","listRuns","query","where","workflow","statuses","$and","tag","quote","idQuote","cols","attributeColumns","qb","createQueryBuilder","tagsCol","tagsColumn","pattern","replace","colExpr","jsonAsText","andWhere","f","attributeExistsSql","offset","getResultList","alias","col","attributeColumnFor","numValue","strValue","cmp","sqlComparator","op","operand","attributeOperand","literal","String","a","table","sub","outerId","runPk","key","meta","getMetadata","get","field","prop","props","p","name","fieldNames","runMeta","properties","tableName","tags","colRef","platform","getPlatform","toLowerCase","includes","isMysql","ch","listCheckpoints","getLatestCheckpointByName","undefined","listCheckpointsByNamePrefix","prefixes","$like","putSignalWaiter","waiter","takeSignalWaiter","token","remove","listSignalWaiters","prefix","e","bufferSignal","payload","BufferedSignalEntity","persist","takeBufferedSignal","workflowVersion","input","output","error","recoveryAttempts","priority","updatedAt","getTime","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt"]}
|
|
1
|
+
{"version":3,"sources":["../src/entities.ts","../src/mikro-orm-state-store.ts","../src/schema.ts"],"sourcesContent":["import type { RunStatus, StepKind } from '@dudousxd/nestjs-durable-core';\nimport { EntitySchema } from '@mikro-orm/core';\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 TypeORM,\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\nfunction 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 `em.create`/`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;\n lockedUntil?: Date;\n recoveryAttempts?: number;\n tags?: string[] | null;\n searchAttributes?: Record<string, string | number | boolean> | null;\n priority?: number | 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;\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}\n\nexport class BufferedSignalEntity {\n id!: number;\n token!: string;\n payload?: unknown;\n}\n\n/**\n * Build the durable MikroORM entity schemas with column names pinned per `naming` (default\n * `'snake_case'`). Register the result in your MikroORM config / `MikroOrmModule.forFeature`.\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 class: WorkflowRunEntity,\n tableName: 'durable_workflow_runs',\n // Indexes mirror the Prisma adapter so a store swap keeps the same plan. The poller hits these\n // every tick: `(status, wakeAt)` serves both the due-timer scan (status='suspended' AND wakeAt<=now)\n // and, via its `status` prefix, the pending/incomplete status lookups; `(workflow, status)` serves\n // the per-workflow timeout sweep. Without them every poll is a full scan of a table that only grows.\n indexes: [\n { name: 'durable_workflow_runs_status_wake_at_idx', properties: ['status', 'wakeAt'] },\n { name: 'durable_workflow_runs_workflow_status_idx', properties: ['workflow', 'status'] },\n ],\n properties: {\n id: { type: 'string', primary: true, fieldName: col('id') },\n workflow: { type: 'string', fieldName: col('workflow') },\n workflowVersion: { type: 'string', fieldName: col('workflowVersion') },\n status: { type: 'string', fieldName: col('status') },\n input: { type: 'json', nullable: true, fieldName: col('input') },\n output: { type: 'json', nullable: true, fieldName: col('output') },\n error: { type: 'json', nullable: true, fieldName: col('error') },\n wakeAt: { type: 'Date', nullable: true, fieldName: col('wakeAt') },\n lockedBy: { type: 'string', nullable: true, fieldName: col('lockedBy') },\n lockedUntil: { type: 'Date', nullable: true, fieldName: col('lockedUntil') },\n recoveryAttempts: { type: 'integer', nullable: true, fieldName: col('recoveryAttempts') },\n tags: { type: 'json', nullable: true, fieldName: col('tags') },\n searchAttributes: { type: 'json', nullable: true, fieldName: col('searchAttributes') },\n priority: { type: 'integer', nullable: true, fieldName: col('priority') },\n createdAt: { type: 'Date', fieldName: col('createdAt') },\n updatedAt: { type: 'Date', fieldName: col('updatedAt') },\n },\n });\n\n const stepCheckpoints = new EntitySchema<StepCheckpointEntity>({\n class: StepCheckpointEntity,\n tableName: 'durable_step_checkpoints',\n properties: {\n runId: { type: 'string', primary: true, fieldName: col('runId') },\n seq: { type: 'integer', primary: true, fieldName: col('seq') },\n name: { type: 'string', fieldName: col('name') },\n kind: { type: 'string', fieldName: col('kind') },\n stepId: { type: 'string', fieldName: col('stepId') },\n status: { type: 'string', fieldName: col('status') },\n input: { type: 'json', nullable: true, fieldName: col('input') },\n output: { type: 'json', nullable: true, fieldName: col('output') },\n error: { type: 'json', nullable: true, fieldName: col('error') },\n events: { type: 'json', nullable: true, fieldName: col('events') },\n attempts: { type: 'integer', fieldName: col('attempts') },\n workerGroup: { type: 'string', nullable: true, fieldName: col('workerGroup') },\n wakeAt: { type: 'Date', nullable: true, fieldName: col('wakeAt') },\n enqueuedAt: { type: 'Date', nullable: true, fieldName: col('enqueuedAt') },\n startedAt: { type: 'Date', fieldName: col('startedAt') },\n finishedAt: { type: 'Date', fieldName: col('finishedAt') },\n },\n });\n\n const runAttributes = new EntitySchema<RunAttributeEntity>({\n class: RunAttributeEntity,\n tableName: 'durable_run_attributes',\n // The search-attribute EXISTS join (see the class docstring) pushes equality/range predicates down\n // onto `(key, numValue)` / `(key, strValue)`; mirror the Prisma adapter so those scans stay indexed.\n indexes: [\n { name: 'durable_run_attributes_key_num_idx', properties: ['key', 'numValue'] },\n { name: 'durable_run_attributes_key_str_idx', properties: ['key', 'strValue'] },\n ],\n properties: {\n runId: { type: 'string', primary: true, fieldName: col('runId') },\n key: { type: 'string', primary: true, fieldName: col('key') },\n strValue: { type: 'string', nullable: true, fieldName: col('strValue') },\n // `float`/`double` is portable across SQLite/MySQL/Postgres for numeric range scans.\n numValue: { type: 'float', nullable: true, fieldName: col('numValue') },\n },\n });\n\n const signalWaiters = new EntitySchema<SignalWaiterEntity>({\n class: SignalWaiterEntity,\n tableName: 'durable_signal_waiters',\n properties: {\n token: { type: 'string', primary: true, fieldName: col('token') },\n runId: { type: 'string', fieldName: col('runId') },\n seq: { type: 'integer', fieldName: col('seq') },\n },\n });\n\n const bufferedSignals = new EntitySchema<BufferedSignalEntity>({\n class: BufferedSignalEntity,\n tableName: 'durable_buffered_signals',\n properties: {\n id: { type: 'integer', primary: true, autoincrement: true, fieldName: col('id') },\n token: { type: 'string', index: true, fieldName: col('token') },\n payload: { type: 'json', nullable: true, fieldName: col('payload') },\n },\n });\n\n return [workflowRuns, stepCheckpoints, runAttributes, signalWaiters, bufferedSignals];\n}\n\n/** Durable entity schemas with the canonical `'snake_case'` column names. */\nexport const ENTITIES = durableEntities();\n","import {\n type AttributeFilter,\n type RetentionPolicy,\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 parseDuration,\n sqlComparator,\n} from '@dudousxd/nestjs-durable-core';\nimport type { EntityManager, MikroORM } from '@mikro-orm/core';\n\n/** Minimal structural surface of the SQL EntityManager's QueryBuilder (from `@mikro-orm/knex`),\n * typed here so the adapter needn't add a hard dependency on the knex types — a real SQL-driver EM\n * satisfies it at runtime. */\ninterface DurableQueryBuilder<T> {\n where(cond: Record<string, unknown>): DurableQueryBuilder<T>;\n andWhere(cond: string): DurableQueryBuilder<T>;\n orderBy(cond: Record<string, unknown>): DurableQueryBuilder<T>;\n limit(n: number): DurableQueryBuilder<T>;\n offset(n: number): DurableQueryBuilder<T>;\n getResultList(): Promise<T[]>;\n}\ntype SqlEm = EntityManager & {\n createQueryBuilder<T>(entity: unknown, alias: string): DurableQueryBuilder<T>;\n};\n\n/** Resolved side-table column names (per the active naming strategy) for the raw EXISTS pushdown. */\ninterface AttributeColumns {\n table: string;\n /** Side-table FK column (the run id on `durable_run_attributes`). */\n runId: string;\n /** Run table PK column (the `id` on `durable_workflow_runs`) used for the outer correlation. */\n runPk: string;\n key: string;\n strValue: string;\n numValue: string;\n}\nimport {\n BufferedSignalEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n StepCheckpointEntity,\n WorkflowRunEntity,\n} from './entities';\nimport { ensureMikroOrmDurableSchema } from './schema';\n\n/**\n * MikroORM-backed `StateStore`. Works on any MikroORM driver — Postgres, MySQL, SQLite (tested);\n * timestamps and `wakeAt` use native datetime columns. Each operation runs on a forked\n * EntityManager so it owns its unit of work.\n */\nexport class MikroOrmStateStore implements StateStore {\n constructor(private readonly orm: MikroORM) {}\n\n async ensureSchema(): Promise<void> {\n await ensureMikroOrmDurableSchema(this.orm);\n }\n\n async createRun(run: WorkflowRun): Promise<void> {\n const em = this.orm.em.fork();\n em.create(WorkflowRunEntity, toRunEntity(run));\n await em.flush();\n await this.reindexAttributes(run.id, run.searchAttributes);\n }\n\n async updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n const em = this.orm.em.fork();\n const entity = await em.findOneOrFail(WorkflowRunEntity, { id: runId });\n Object.assign(entity, toRunEntity({ ...fromRunEntity(entity), ...patch } as WorkflowRun));\n await em.flush();\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 /** 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 forked?: EntityManager,\n ): Promise<void> {\n const em = forked ?? this.orm.em.fork();\n await em.nativeDelete(RunAttributeEntity, { runId });\n const rows = normalizeAttributeRows(runId, attributes);\n if (rows.length) await em.insertMany(RunAttributeEntity, rows);\n }\n\n async getRun(runId: string): Promise<WorkflowRun | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(WorkflowRunEntity, { id: runId });\n return entity ? fromRunEntity(entity) : null;\n }\n\n async deleteRun(runId: string): Promise<void> {\n const em = this.orm.em.fork();\n // Children first, then the run row — checkpoints, signal waiters, and the normalized\n // attribute side-table, so nothing dangles after the run is gone.\n await em.nativeDelete(StepCheckpointEntity, { runId });\n await em.nativeDelete(SignalWaiterEntity, { runId });\n await em.nativeDelete(RunAttributeEntity, { runId });\n await em.nativeDelete(WorkflowRunEntity, { id: runId });\n }\n\n async pruneTerminalRuns(policy: RetentionPolicy, nowMs: number, limit: number): Promise<number> {\n if (policy.statuses.length === 0 || limit <= 0) return 0;\n const em = this.orm.em.fork();\n const status = { $in: policy.statuses };\n // Collect ids that violate EITHER bound (most-restrictive keep): too old, or past the count cap.\n const ids = new Set<string>();\n\n if (policy.maxAge != null) {\n const cutoff = new Date(nowMs - parseDuration(policy.maxAge));\n const rows = await em.find(\n WorkflowRunEntity,\n { status, updatedAt: { $lt: cutoff } },\n { fields: ['id'], orderBy: { updatedAt: 'asc' }, limit }, // oldest first\n );\n for (const r of rows) ids.add(r.id);\n }\n\n if (policy.maxCount != null && ids.size < limit) {\n // Everything beyond the newest `maxCount` rows in the status set — skip the kept window via offset.\n const rows = await em.find(\n WorkflowRunEntity,\n { status },\n {\n fields: ['id'],\n orderBy: { updatedAt: 'desc', id: 'desc' },\n limit,\n offset: policy.maxCount,\n },\n );\n for (const r of rows) {\n ids.add(r.id);\n if (ids.size >= limit) break;\n }\n }\n\n if (ids.size === 0) return 0;\n const idList = [...ids].slice(0, limit);\n const runId = { $in: idList };\n // Cascade children then runs (mirrors deleteRun) in one transaction so a pruned run never dangles.\n await em.transactional(async (tem) => {\n await tem.nativeDelete(StepCheckpointEntity, { runId });\n await tem.nativeDelete(SignalWaiterEntity, { runId });\n await tem.nativeDelete(RunAttributeEntity, { runId });\n await tem.nativeDelete(WorkflowRunEntity, { id: runId });\n });\n return idList.length;\n }\n\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(StepCheckpointEntity, { runId, seq });\n return entity ? fromCheckpointEntity(entity) : null;\n }\n\n async saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n const em = this.orm.em.fork();\n await em.upsert(StepCheckpointEntity, toCheckpointEntity(checkpoint));\n await em.flush();\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.orm.em.fork().transactional(async (em) =>\n work({\n raw: em,\n saveCheckpoint: async (cp) => {\n await em.upsert(StepCheckpointEntity, toCheckpointEntity(cp));\n },\n }),\n );\n }\n\n async listIncompleteRuns(): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(WorkflowRunEntity, { status: { $in: ['running', 'cancelling'] } });\n return rows.map(fromRunEntity);\n }\n\n async listPendingRuns(limit: number): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(\n WorkflowRunEntity,\n { status: 'pending' },\n { orderBy: { createdAt: 'asc' }, limit }, // FIFO dispatch\n );\n return rows.map(fromRunEntity);\n }\n\n async listDueTimers(nowMs: number): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(WorkflowRunEntity, {\n status: 'suspended',\n wakeAt: { $ne: null, $lte: new Date(nowMs) },\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 em = this.orm.em.fork();\n const affected = await em.nativeUpdate(\n WorkflowRunEntity,\n { id: runId, $or: [{ lockedUntil: null }, { lockedUntil: { $lte: new Date(nowMs) } }] },\n { lockedBy: owner, lockedUntil: new Date(leaseUntilMs) },\n );\n return affected === 1;\n }\n\n async releaseRunLock(runId: string): Promise<void> {\n const em = this.orm.em.fork();\n await em.nativeUpdate(WorkflowRunEntity, { id: runId }, { lockedBy: null, lockedUntil: null });\n }\n\n async renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n const em = this.orm.em.fork();\n const affected = await em.nativeUpdate(\n WorkflowRunEntity,\n { id: runId, lockedBy: owner },\n { lockedUntil: new Date(leaseUntilMs) },\n );\n return affected === 1;\n }\n\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n const em = this.orm.em.fork();\n const where: Record<string, unknown> = {};\n if (query.workflow) where.workflow = query.workflow;\n // `status IN (...)`; an empty set matches nothing (mirrors the in-memory store). When both the\n // single `status` and `statuses` are set, AND them so the narrower set wins.\n if (query.status && query.statuses) {\n where.$and = [{ status: query.status }, { status: { $in: query.statuses } }];\n } else if (query.status) {\n where.status = query.status;\n } else if (query.statuses) {\n where.status = { $in: query.statuses };\n }\n const orderBy = { createdAt: 'desc' as const }; // newest first — recent runs on top in the dashboard\n // `tags`/attributes need raw SQL pushed through the QueryBuilder:\n // - tag: `tags` is a JSON column (native json/jsonb on PG/MySQL), and MikroORM JSON-serializes a\n // `{ $like }` operand (wrapping/escaping the LIKE pattern) so a plain where corrupts it to no\n // matches. A raw LIKE on the column-as-text matches the quoted token so `etl` doesn't match\n // `etl-foo`. Postgres `jsonb` rejects `LIKE` directly, so cast to text per dialect.\n // - attributes: each filter becomes a raw EXISTS against the normalized side-table, so the DB\n // filters AND paginates — no full scan + in-process filter (ANDed: one EXISTS per filter).\n // Use a QueryBuilder with a fixed root alias `r` so the raw correlations are stable across drivers.\n if (query.tag || query.attributes?.length) {\n const quote = this.idQuote(em);\n const cols = this.attributeColumns(em);\n const qb = (em as SqlEm)\n .createQueryBuilder<WorkflowRunEntity>(WorkflowRunEntity, 'r')\n .where(where)\n .orderBy(orderBy);\n if (query.tag) {\n const tagsCol = this.tagsColumn(em);\n const pattern = `%\"${query.tag.replace(/'/g, \"''\")}\"%`;\n const colExpr = this.jsonAsText(em, `${quote('r')}.${quote(tagsCol)}`);\n qb.andWhere(`${colExpr} LIKE '${pattern}'`);\n }\n for (const f of query.attributes ?? []) {\n qb.andWhere(this.attributeExistsSql(f, quote, 'r', cols));\n }\n if (query.limit != null) qb.limit(query.limit);\n if (query.offset != null) qb.offset(query.offset);\n const rows = await qb.getResultList();\n return rows.map(fromRunEntity);\n }\n const rows = await em.find(WorkflowRunEntity, where, {\n ...(query.limit != null ? { limit: query.limit } : {}),\n ...(query.offset != null ? { offset: query.offset } : {}),\n orderBy,\n });\n return rows.map(fromRunEntity);\n }\n\n /** One attribute predicate as a raw EXISTS subquery on the side-table, correlated to the outer run\n * alias. `<>` (ne) also excludes runs where the attribute is absent (missing-key-never-matches):\n * EXISTS already requires a present row, so EXISTS(... <> ...) is exactly ne-with-present. Numeric\n * operands compare the num column, everything else the str column. Identifiers are quoted per\n * driver and operands are inlined as literals (string operands are escaped by doubling quotes). */\n private attributeExistsSql(\n f: AttributeFilter,\n quote: (id: string) => string,\n alias: string,\n cols: AttributeColumns,\n ): string {\n const col = attributeColumnFor(f) === 'numValue' ? cols.numValue : cols.strValue;\n const cmp = sqlComparator(f.op);\n const operand = attributeOperand(f);\n const literal =\n typeof operand === 'number' ? String(operand) : `'${String(operand).replace(/'/g, \"''\")}'`;\n const a = quote(cols.table);\n const sub = quote('a');\n const outerId = `${quote(alias)}.${quote(cols.runPk)}`; // run PK column on the outer alias\n return `EXISTS (SELECT 1 FROM ${a} ${sub} WHERE ${sub}.${quote(cols.runId)} = ${outerId} AND ${sub}.${quote(cols.key)} = '${f.key.replace(/'/g, \"''\")}' AND ${sub}.${quote(col)} ${cmp} ${literal})`;\n }\n\n /** Resolve the side-table's actual column names from MikroORM metadata, so the raw EXISTS matches\n * the active naming strategy (underscore vs camelCase) rather than guessing. The run PK column is\n * reused for BOTH the outer correlation and the side-table FK (they share the same fieldName). */\n private attributeColumns(em: EntityManager): AttributeColumns {\n const meta = em.getMetadata().get(RunAttributeEntity);\n const field = (prop: string) =>\n meta.props.find((p) => p.name === prop)?.fieldNames?.[0] ?? prop;\n const runMeta = em.getMetadata().get(WorkflowRunEntity);\n const runPk = runMeta.properties.id?.fieldNames?.[0] ?? 'id';\n return {\n table: meta.tableName,\n runId: field('runId'),\n runPk,\n key: field('key'),\n strValue: field('strValue'),\n numValue: field('numValue'),\n };\n }\n\n /** Resolve the `tags` column name from metadata (per the active naming strategy), for the raw LIKE. */\n private tagsColumn(em: EntityManager): string {\n const runMeta = em.getMetadata().get(WorkflowRunEntity);\n return runMeta.properties.tags?.fieldNames?.[0] ?? 'tags';\n }\n\n /** Wrap a JSON column reference so it can be `LIKE`d as text. Postgres `jsonb`/`json` rejects `LIKE`\n * directly (`operator does not exist: jsonb ~~ unknown`) — cast to `text`; MySQL JSON needs an\n * explicit `CHAR` cast; SQLite stores JSON as text already, so no cast. */\n private jsonAsText(em: EntityManager, colRef: string): string {\n const platform = String(em.getPlatform().constructor.name).toLowerCase();\n if (platform.includes('postgre')) return `${colRef}::text`;\n if (platform.includes('mysql') || platform.includes('mariadb'))\n return `CAST(${colRef} AS CHAR)`;\n return colRef;\n }\n\n /** Quote an identifier per the active SQL driver (MySQL/MariaDB backtick, others double-quote). */\n private idQuote(em: EntityManager): (id: string) => string {\n const platform = String(em.getPlatform().constructor.name).toLowerCase();\n const isMysql = platform.includes('mysql') || platform.includes('mariadb');\n const ch = isMysql ? '`' : '\"';\n return (id: string) => `${ch}${id}${ch}`;\n }\n\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(StepCheckpointEntity, { runId }, { orderBy: { seq: 'asc' } });\n return rows.map(fromCheckpointEntity);\n }\n\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(\n StepCheckpointEntity,\n { runId, name },\n { orderBy: { seq: 'desc' } },\n );\n return entity ? fromCheckpointEntity(entity) : undefined;\n }\n\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n if (prefixes.length === 0) return [];\n const em = this.orm.em.fork();\n const rows = await em.find(\n StepCheckpointEntity,\n { runId, $or: prefixes.map((p) => ({ name: { $like: `${p}%` } })) },\n { orderBy: { seq: 'asc' } },\n );\n return rows.map(fromCheckpointEntity);\n }\n\n async putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n const em = this.orm.em.fork();\n await em.upsert(SignalWaiterEntity, { ...waiter });\n await em.flush();\n }\n\n async takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(SignalWaiterEntity, { token });\n if (!entity) return null;\n const waiter: SignalWaiter = { token: entity.token, runId: entity.runId, seq: entity.seq };\n await em.remove(entity).flush();\n return waiter;\n }\n\n async listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n const em = this.orm.em.fork();\n const rows = await em.find(SignalWaiterEntity, { token: { $like: `${prefix}%` } });\n return rows.map((e) => ({ token: e.token, runId: e.runId, seq: e.seq }));\n }\n\n async bufferSignal(token: string, payload: unknown): Promise<void> {\n const em = this.orm.em.fork();\n const e = new BufferedSignalEntity();\n e.token = token;\n e.payload = payload ?? null;\n em.persist(e);\n await em.flush();\n }\n\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const em = this.orm.em.fork();\n const entity = await em.findOne(BufferedSignalEntity, { token }, { orderBy: { id: 'asc' } });\n if (!entity) return null;\n const payload = entity.payload ?? undefined;\n await em.remove(entity).flush();\n return { payload };\n }\n}\n\nfunction toRunEntity(run: WorkflowRun): WorkflowRunEntity {\n const e = new WorkflowRunEntity();\n e.id = run.id;\n e.workflow = run.workflow;\n e.workflowVersion = run.workflowVersion;\n e.status = run.status;\n e.input = run.input ?? null;\n e.output = run.output ?? null;\n e.error = run.error ?? null;\n if (run.wakeAt != null) e.wakeAt = new Date(run.wakeAt);\n if (run.lockedBy !== undefined) e.lockedBy = run.lockedBy;\n if (run.lockedUntil != null) e.lockedUntil = new Date(run.lockedUntil);\n if (run.recoveryAttempts !== undefined) e.recoveryAttempts = run.recoveryAttempts;\n e.tags = run.tags ?? null;\n e.searchAttributes = run.searchAttributes ?? null;\n e.priority = run.priority ?? null;\n e.createdAt = run.createdAt;\n e.updatedAt = run.updatedAt;\n return e;\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?.getTime(),\n lockedBy: e.lockedBy ?? undefined,\n lockedUntil: e.lockedUntil?.getTime(),\n recoveryAttempts: e.recoveryAttempts ?? undefined,\n tags: e.tags ?? undefined,\n searchAttributes: e.searchAttributes ?? undefined,\n priority: e.priority ?? undefined,\n createdAt: e.createdAt,\n updatedAt: e.updatedAt,\n };\n}\n\nfunction toCheckpointEntity(cp: StepCheckpoint): StepCheckpointEntity {\n const e = new StepCheckpointEntity();\n e.runId = cp.runId;\n e.seq = cp.seq;\n e.name = cp.name;\n e.kind = cp.kind;\n e.stepId = cp.stepId;\n e.status = cp.status;\n e.input = cp.input ?? null;\n e.output = cp.output ?? null;\n e.error = cp.error ?? null;\n e.events = cp.events ?? null;\n e.attempts = cp.attempts;\n if (cp.workerGroup !== undefined) e.workerGroup = cp.workerGroup;\n if (cp.wakeAt != null) e.wakeAt = new Date(cp.wakeAt);\n e.enqueuedAt = cp.enqueuedAt;\n e.startedAt = cp.startedAt;\n e.finishedAt = cp.finishedAt;\n return e;\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 wakeAt: e.wakeAt?.getTime(),\n enqueuedAt: e.enqueuedAt ?? e.startedAt,\n startedAt: e.startedAt,\n finishedAt: e.finishedAt,\n };\n}\n","import type { MikroORM } from '@mikro-orm/core';\n\n/**\n * The tables this store owns. Kept in sync with the `tableName`s in `./entities`. Used to scope\n * schema management to our own tables (see {@link ensureMikroOrmDurableSchema}).\n */\nconst DURABLE_TABLE_NAMES = new Set([\n 'durable_workflow_runs',\n 'durable_step_checkpoints',\n 'durable_run_attributes',\n 'durable_signal_waiters',\n 'durable_buffered_signals',\n]);\n\n/**\n * The table a DDL statement targets, lower-cased; undefined otherwise. Recognizes `create table` /\n * `alter table` (the table name follows immediately) and standalone `create [unique] index ... on\n * <table>` (the table follows `on`). MikroORM adds an index to an EXISTING table as `alter table ...\n * add index` on MySQL but as a standalone `create index ... on ...` on Postgres/SQLite — without the\n * second form those index statements would be dropped by the durable-table filter and never applied.\n */\nfunction targetTable(statement: string): string | undefined {\n const match = statement.match(\n /^(?:create\\s+(?:unique\\s+)?index\\s+.+?\\s+on\\s+|(?:create|alter)\\s+table\\s+(?:if\\s+not\\s+exists\\s+)?)[`\"']?([\\w$]+)[`\"']?/i,\n );\n return match?.[1]?.toLowerCase();\n}\n\n/**\n * Whether a statement adds structure the store REQUIRES — a failure here is fatal (the store can't\n * run without the table/column/index). A column TYPE alignment (`modify`/`alter column ... type`)\n * is best-effort: the column already holds the data (the store serializes JSON to/from it regardless\n * of the declared type), so failing to converge its type — e.g. a legacy `longtext` value that won't\n * cast to `json` because it was truncated under an older `text` column — must NOT crash boot.\n */\nfunction isRequiredStructure(statement: string): boolean {\n return /\\b(?:create\\s+table|create\\s+(?:unique\\s+)?index|add\\s+(?:column|index|constraint|key|unique|fulltext))\\b/i.test(\n statement,\n );\n}\n\n/**\n * Idempotently create/extend ONLY the durable tables (additive — never drops). Safe to run on every\n * boot (auto-schema) and from a MikroORM migration when you disable auto-schema:\n *\n * ```ts\n * export class AddDurableTables extends Migration {\n * async up() { await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm()); }\n * }\n * ```\n *\n * It does NOT run a whole-ORM `schema.update()`. When the store shares the host app's ORM (the\n * recommended setup — a single ORM avoids MikroORM's global-metadata clobber between instances),\n * a full `schema.update()` would try to reconcile EVERY app table to the entity metadata: on a\n * migration-managed schema that means recreating the migrations table and dropping app foreign keys.\n * Instead we compute the safe additive diff and execute only the statements that target our own\n * `durable_*` tables. `getUpdateSchemaSQL` already emits a `create table` only for a missing table\n * and `alter table ... add` only for missing columns, so existing tables — and the entire rest of\n * the host schema — are left untouched.\n */\nexport async function ensureMikroOrmDurableSchema(orm: MikroORM): Promise<void> {\n const sql = await orm.schema.getUpdateSchemaSQL({ safe: true });\n const ours = sql\n .split(';')\n .map((statement) => statement.trim())\n .filter((statement) => {\n const table = targetTable(statement);\n return table !== undefined && DURABLE_TABLE_NAMES.has(table);\n });\n const connection = orm.em.getConnection();\n for (const statement of ours) {\n try {\n await connection.execute(statement);\n } catch (err) {\n // Required structure (create table / add column / add index) must succeed — rethrow.\n if (isRequiredStructure(statement)) {\n throw err;\n }\n // A best-effort type alignment (e.g. legacy `longtext` → `json`) failed, typically because an\n // existing column holds a value that can't cast to the target type (a relic of an older column\n // type). The column already stores the data and the store reads/writes it via serialization, so\n // leave it as-is and continue rather than crashing boot. Surfaced so the data can be repaired\n // out of band (e.g. `UPDATE … SET col = NULL WHERE JSON_VALID(col) = 0` for a disposable column).\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `[nestjs-durable-store-mikro-orm] skipped a non-structural durable-schema statement that failed; the column is left as-is (functional) — repair the data out of band to converge its type. Statement: ${statement} — ${message}`,\n );\n }\n }\n\n // Converge collation last, once the tables exist (whether just created above or pre-existing).\n await alignDurableCollation(orm);\n}\n\n/** A MySQL identifier we are willing to interpolate into DDL (charset / collation names). */\nfunction isSafeSqlIdentifier(value: string): boolean {\n return /^[A-Za-z0-9_]+$/.test(value);\n}\n\n/**\n * Align each durable table's collation to the ORM's configured `collate` (MySQL/MariaDB only).\n *\n * MikroORM's auto-schema (`getUpdateSchemaSQL`) creates tables with the server's DEFAULT collation —\n * on MySQL 8.4 that's `utf8mb4_0900_ai_ci` — and ignores the `collate` config option. When the host\n * app pins a different collation on its own tables (commonly `utf8mb4_unicode_ci` via migrations), a\n * JOIN between a durable table and an app table throws \"Illegal mix of collations\". We converge it\n * here: read the configured collation and `CONVERT` only the durable tables whose collation differs.\n *\n * Idempotent (matching tables are skipped), non-fatal (a CONVERT failure is warned, never crashes\n * boot), and a no-op when no `collate` is configured or the platform isn't MySQL/MariaDB.\n */\nasync function alignDurableCollation(orm: MikroORM): Promise<void> {\n const platform = String(orm.em.getPlatform().constructor.name).toLowerCase();\n if (!platform.includes('mysql') && !platform.includes('maria')) {\n return;\n }\n const collate = orm.config.get('collate');\n if (typeof collate !== 'string' || !isSafeSqlIdentifier(collate)) {\n return;\n }\n // utf8mb4_unicode_ci → utf8mb4. CONVERT TO needs the charset that owns the collation.\n const charset = collate.split('_')[0];\n if (!charset || !isSafeSqlIdentifier(charset)) {\n return;\n }\n const connection = orm.em.getConnection();\n for (const table of DURABLE_TABLE_NAMES) {\n try {\n const rows = (await connection.execute(\n 'select table_collation as collation from information_schema.tables where table_schema = database() and table_name = ? limit 1',\n [table],\n )) as Array<{ collation?: string | null }>;\n const current = rows[0]?.collation;\n // Table absent (nothing to align) or already at the target collation — skip.\n if (current == null || current === collate) {\n continue;\n }\n await connection.execute(\n `alter table \\`${table}\\` convert to character set ${charset} collate ${collate}`,\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `[nestjs-durable-store-mikro-orm] could not align collation for \\`${table}\\` to ${collate} (left as-is): ${message}`,\n );\n }\n }\n}\n"],"mappings":";;;;AACA,SAASA,oBAAoB;AAgB7B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2G,UAAU;AACxBf,IAAEgB,WAAW5G,GAAG4G;AAChB,MAAI5G,GAAG6G,gBAAgB5B,OAAWW,GAAEiB,cAAc7G,GAAG6G;AACrD,MAAI7G,GAAGM,UAAU,KAAMsF,GAAEtF,SAAS,IAAIhC,KAAK0B,GAAGM,MAAM;AACpDsF,IAAEkB,aAAa9G,GAAG8G;AAClBlB,IAAEmB,YAAY/G,GAAG+G;AACjBnB,IAAEoB,aAAahH,GAAGgH;AAClB,SAAOpB;AACT;AAnBShG;AAqBT,SAASJ,qBAAqBoG,GAAuB;AACnD,SAAO;IACLrJ,OAAOqJ,EAAErJ;IACTgD,KAAKqG,EAAErG;IACP2E,MAAM0B,EAAE1B;IACRuC,MAAMb,EAAEa;IACRC,QAAQd,EAAEc;IACV1I,QAAQ4H,EAAE5H;IACVmI,OAAOP,EAAEO,SAASlB;IAClBmB,QAAQR,EAAEQ,UAAUnB;IACpBoB,OAAQT,EAAES,SAASpB;IACnB0B,QAASf,EAAEe,UAAU1B;IACrB2B,UAAUhB,EAAEgB;IACZC,aAAajB,EAAEiB,eAAe5B;IAC9B3E,QAAQsF,EAAEtF,QAAQkG,QAAAA;IAClBM,YAAYlB,EAAEkB,cAAclB,EAAEmB;IAC9BA,WAAWnB,EAAEmB;IACbC,YAAYpB,EAAEoB;EAChB;AACF;AAnBSxH;","names":["EntitySchema","snakeCase","property","replace","c","toLowerCase","columnNamer","naming","WorkflowRunEntity","id","workflow","workflowVersion","status","input","output","error","wakeAt","lockedBy","lockedUntil","recoveryAttempts","tags","searchAttributes","priority","createdAt","updatedAt","StepCheckpointEntity","runId","seq","name","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt","RunAttributeEntity","key","strValue","numValue","SignalWaiterEntity","token","BufferedSignalEntity","payload","durableEntities","options","col","workflowRuns","EntitySchema","class","tableName","indexes","properties","type","primary","fieldName","nullable","stepCheckpoints","runAttributes","signalWaiters","bufferedSignals","autoincrement","index","ENTITIES","attributeColumnFor","attributeOperand","normalizeAttributeRows","parseDuration","sqlComparator","DURABLE_TABLE_NAMES","Set","targetTable","statement","match","toLowerCase","isRequiredStructure","test","ensureMikroOrmDurableSchema","orm","sql","schema","getUpdateSchemaSQL","safe","ours","split","map","trim","filter","table","undefined","has","connection","em","getConnection","execute","err","message","Error","String","console","warn","alignDurableCollation","isSafeSqlIdentifier","value","platform","getPlatform","name","includes","collate","config","get","charset","rows","current","collation","MikroOrmStateStore","orm","ensureSchema","ensureMikroOrmDurableSchema","createRun","run","em","fork","create","WorkflowRunEntity","toRunEntity","flush","reindexAttributes","id","searchAttributes","updateRun","runId","patch","entity","findOneOrFail","Object","assign","fromRunEntity","attributes","forked","nativeDelete","RunAttributeEntity","rows","normalizeAttributeRows","length","insertMany","getRun","findOne","deleteRun","StepCheckpointEntity","SignalWaiterEntity","pruneTerminalRuns","policy","nowMs","limit","statuses","status","$in","ids","Set","maxAge","cutoff","Date","parseDuration","find","updatedAt","$lt","fields","orderBy","r","add","maxCount","size","offset","idList","slice","transactional","tem","getCheckpoint","seq","fromCheckpointEntity","saveCheckpoint","checkpoint","upsert","toCheckpointEntity","transaction","work","raw","cp","listIncompleteRuns","map","listPendingRuns","createdAt","listDueTimers","wakeAt","$ne","$lte","tryLockRun","owner","leaseUntilMs","affected","nativeUpdate","$or","lockedUntil","lockedBy","releaseRunLock","renewRunLock","listRuns","query","where","workflow","$and","tag","quote","idQuote","cols","attributeColumns","qb","createQueryBuilder","tagsCol","tagsColumn","pattern","replace","colExpr","jsonAsText","andWhere","f","attributeExistsSql","getResultList","alias","col","attributeColumnFor","numValue","strValue","cmp","sqlComparator","op","operand","attributeOperand","literal","String","a","table","sub","outerId","runPk","key","meta","getMetadata","get","field","prop","props","p","name","fieldNames","runMeta","properties","tableName","tags","colRef","platform","getPlatform","toLowerCase","includes","isMysql","ch","listCheckpoints","getLatestCheckpointByName","undefined","listCheckpointsByNamePrefix","prefixes","$like","putSignalWaiter","waiter","takeSignalWaiter","token","remove","listSignalWaiters","prefix","e","bufferSignal","payload","BufferedSignalEntity","persist","takeBufferedSignal","workflowVersion","input","output","error","recoveryAttempts","priority","getTime","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dudousxd/nestjs-durable-store-mikro-orm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "MikroORM adapter for the nestjs-durable StateStore (reference ORM adapter)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Davide Carvalho",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"reflect-metadata": "0.2.2",
|
|
32
32
|
"tsup": "8.3.5",
|
|
33
33
|
"typescript": "5.9.3",
|
|
34
|
-
"@dudousxd/nestjs-durable-core": "^0.
|
|
34
|
+
"@dudousxd/nestjs-durable-core": "^0.37.0",
|
|
35
35
|
"@dudousxd/nestjs-durable-testing": "^0.7.0"
|
|
36
36
|
},
|
|
37
37
|
"module": "./dist/index.js",
|