@dudousxd/nestjs-durable-store-mikro-orm 0.7.0 → 0.9.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.
@@ -0,0 +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 { Entity, PrimaryKey, Property } from '@mikro-orm/core';\n\n@Entity({ tableName: 'durable_workflow_runs' })\nexport class WorkflowRunEntity {\n @PrimaryKey()\n id!: string;\n\n @Property()\n workflow!: string;\n\n @Property()\n workflowVersion!: string;\n\n @Property()\n status!: RunStatus;\n\n @Property({ type: 'json', nullable: true })\n input?: unknown;\n\n @Property({ type: 'json', nullable: true })\n output?: unknown;\n\n @Property({ type: 'json', nullable: true })\n error?: unknown;\n\n @Property({ nullable: true })\n wakeAt?: Date;\n\n @Property({ nullable: true })\n lockedBy?: string;\n\n @Property({ nullable: true })\n lockedUntil?: Date;\n\n @Property({ type: 'integer', nullable: true })\n recoveryAttempts?: number;\n\n @Property({ type: 'json', nullable: true })\n tags?: string[] | null;\n\n @Property({ type: 'json', nullable: true })\n searchAttributes?: Record<string, string | number | boolean> | null;\n\n @Property()\n createdAt!: Date;\n\n @Property()\n updatedAt!: Date;\n}\n\n@Entity({ tableName: 'durable_step_checkpoints' })\nexport class StepCheckpointEntity {\n @PrimaryKey()\n runId!: string;\n\n @PrimaryKey()\n seq!: number;\n\n @Property()\n name!: string;\n\n @Property()\n kind!: StepKind;\n\n @Property()\n stepId!: string;\n\n @Property()\n status!: 'pending' | 'running' | 'completed' | 'failed';\n\n @Property({ type: 'json', nullable: true })\n input?: unknown;\n\n @Property({ type: 'json', nullable: true })\n output?: unknown;\n\n @Property({ type: 'json', nullable: true })\n error?: unknown;\n\n @Property({ type: 'json', nullable: true })\n events?: unknown;\n\n @Property()\n attempts!: number;\n\n @Property({ nullable: true })\n workerGroup?: string;\n\n @Property({ nullable: true })\n wakeAt?: Date;\n\n @Property({ nullable: true })\n enqueuedAt?: Date;\n\n @Property()\n startedAt!: Date;\n\n @Property()\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 */\n@Entity({ tableName: 'durable_run_attributes' })\nexport class RunAttributeEntity {\n @PrimaryKey()\n runId!: string;\n\n @PrimaryKey()\n key!: string;\n\n @Property({ type: 'string', nullable: true })\n strValue?: string | null;\n\n // `float`/`double` is portable across SQLite/MySQL/Postgres for numeric range scans.\n @Property({ type: 'float', nullable: true })\n numValue?: number | null;\n}\n\n@Entity({ tableName: 'durable_signal_waiters' })\nexport class SignalWaiterEntity {\n @PrimaryKey()\n token!: string;\n\n @Property()\n runId!: string;\n\n @Property()\n seq!: number;\n}\n\n@Entity({ tableName: 'durable_buffered_signals' })\nexport class BufferedSignalEntity {\n @PrimaryKey({ autoincrement: true })\n id!: number;\n\n @Property({ index: true })\n token!: string;\n\n @Property({ type: 'json', nullable: true })\n payload?: unknown;\n}\n\nexport const ENTITIES = [\n WorkflowRunEntity,\n StepCheckpointEntity,\n RunAttributeEntity,\n SignalWaiterEntity,\n BufferedSignalEntity,\n] as const;\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 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: 'running' });\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.name);\n const field = (prop: string) => meta.properties[prop]?.fieldNames?.[0] ?? prop;\n const runMeta = em.getMetadata().get(WorkflowRunEntity.name);\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.name);\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 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.removeAndFlush(entity);\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.removeAndFlush(entity);\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.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 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 * Idempotently create/extend the durable tables (additive, never drops). Safe to run on every\n * boot (auto-schema) and the function to call from a MikroORM migration when you disable\n * auto-schema:\n *\n * ```ts\n * export class AddDurableTables extends Migration {\n * async up() { await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm()); }\n * }\n * ```\n */\nexport async function ensureMikroOrmDurableSchema(orm: MikroORM): Promise<void> {\n await orm.schema.updateSchema({ safe: true });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;ACCA,kBAA6C;;;;;;;;;;;;AAGtC,IAAMA,oBAAN,MAAMA;SAAAA;;;EAEXC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;EAGAC;AACF;;;;;;;;;;;;;;;;;;;IAhCcC,MAAM;IAAQC,UAAU;;;;;;IAGxBD,MAAM;IAAQC,UAAU;;;;;;IAGxBD,MAAM;IAAQC,UAAU;;;;;;IAGxBA,UAAU;;;;;;IAGVA,UAAU;;;;;;IAGVA,UAAU;;;;;;IAGVD,MAAM;IAAWC,UAAU;;;;;;IAG3BD,MAAM;IAAQC,UAAU;;;;;;IAGxBD,MAAM;IAAQC,UAAU;;;;;;;;;;;;;;IAtC5BC,WAAW;;;AAiDd,IAAMC,uBAAN,MAAMA;SAAAA;;;EAEXC;EAGAC;EAGAC;EAGAC;EAGAC;EAGApB;EAGAC;EAGAC;EAGAC;EAGAkB;EAGAC;EAGAC;EAGAnB;EAGAoB;EAGAC;EAGAC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;IA7Bcd,MAAM;IAAQC,UAAU;;;;;;IAGxBD,MAAM;IAAQC,UAAU;;;;;;IAGxBD,MAA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zG,GAAGyG,UAAU;AACxBT,IAAEU,QAAQ1G,GAAG0G,SAAS;AACtBV,IAAEgB,SAAShH,GAAGgH,UAAU;AACxBhB,IAAEiB,WAAWjH,GAAGiH;AAChB,MAAIjH,GAAGkH,gBAAgBZ,OAAWN,GAAEkB,cAAclH,GAAGkH;AACrD,MAAIlH,GAAGW,UAAU,KAAMqF,GAAErF,SAAS,IAAIG,KAAKd,GAAGW,MAAM;AACpDqF,IAAEmB,aAAanH,GAAGmH;AAClBnB,IAAEoB,YAAYpH,GAAGoH;AACjBpB,IAAEqB,aAAarH,GAAGqH;AAClB,SAAOrB;AACT;AAnBSrG;AAqBT,SAASJ,qBAAqByG,GAAuB;AACnD,SAAO;IACL7H,OAAO6H,EAAE7H;IACTkB,KAAK2G,EAAE3G;IACPkF,MAAMyB,EAAEzB;IACRuC,MAAMd,EAAEc;IACRC,QAAQf,EAAEe;IACV5G,QAAQ6F,EAAE7F;IACVqG,OAAOR,EAAEQ,SAASF;IAClBG,QAAQT,EAAES,UAAUH;IACpBI,OAAQV,EAAEU,SAASJ;IACnBU,QAAShB,EAAEgB,UAAUV;IACrBW,UAAUjB,EAAEiB;IACZC,aAAalB,EAAEkB,eAAeZ;IAC9B3F,QAAQqF,EAAErF,QAAQkG,QAAAA;IAClBM,YAAYnB,EAAEmB,cAAcnB,EAAEoB;IAC9BA,WAAWpB,EAAEoB;IACbC,YAAYrB,EAAEqB;EAChB;AACF;AAnBS9H;","names":["WorkflowRunEntity","id","workflow","workflowVersion","status","input","output","error","wakeAt","lockedBy","lockedUntil","recoveryAttempts","tags","searchAttributes","createdAt","updatedAt","type","nullable","tableName","StepCheckpointEntity","runId","seq","name","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt","RunAttributeEntity","key","strValue","numValue","SignalWaiterEntity","token","BufferedSignalEntity","payload","autoincrement","index","ENTITIES","ensureMikroOrmDurableSchema","orm","schema","updateSchema","safe","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","getCheckpoint","seq","StepCheckpointEntity","fromCheckpointEntity","saveCheckpoint","checkpoint","upsert","toCheckpointEntity","transaction","work","transactional","raw","cp","listIncompleteRuns","find","status","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","$in","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","name","field","prop","properties","fieldNames","runMeta","tableName","tags","colRef","platform","getPlatform","toLowerCase","includes","isMysql","ch","listCheckpoints","putSignalWaiter","waiter","SignalWaiterEntity","takeSignalWaiter","token","removeAndFlush","listSignalWaiters","prefix","$like","e","bufferSignal","payload","BufferedSignalEntity","persist","takeBufferedSignal","undefined","workflowVersion","input","output","error","recoveryAttempts","updatedAt","getTime","kind","stepId","events","attempts","workerGroup","enqueuedAt","startedAt","finishedAt"]}
@@ -0,0 +1,132 @@
1
+ import { RunStatus, StepKind, StateStore, WorkflowRun, StepCheckpoint, RunQuery, SignalWaiter } from '@dudousxd/nestjs-durable-core';
2
+ import { MikroORM } from '@mikro-orm/core';
3
+
4
+ declare class WorkflowRunEntity {
5
+ id: string;
6
+ workflow: string;
7
+ workflowVersion: string;
8
+ status: RunStatus;
9
+ input?: unknown;
10
+ output?: unknown;
11
+ error?: unknown;
12
+ wakeAt?: Date;
13
+ lockedBy?: string;
14
+ lockedUntil?: Date;
15
+ recoveryAttempts?: number;
16
+ tags?: string[] | null;
17
+ searchAttributes?: Record<string, string | number | boolean> | null;
18
+ createdAt: Date;
19
+ updatedAt: Date;
20
+ }
21
+ declare class StepCheckpointEntity {
22
+ runId: string;
23
+ seq: number;
24
+ name: string;
25
+ kind: StepKind;
26
+ stepId: string;
27
+ status: 'pending' | 'running' | 'completed' | 'failed';
28
+ input?: unknown;
29
+ output?: unknown;
30
+ error?: unknown;
31
+ events?: unknown;
32
+ attempts: number;
33
+ workerGroup?: string;
34
+ wakeAt?: Date;
35
+ enqueuedAt?: Date;
36
+ startedAt: Date;
37
+ finishedAt: Date;
38
+ }
39
+ /**
40
+ * Normalized side-table for search attributes: one row per (run, key), so range/equality predicates
41
+ * push DOWN into SQL (an EXISTS join indexed on `(key, numValue)` / `(key, strValue)`) instead of a
42
+ * coarse scan + in-process filter. Maintained on every createRun/updateRun. Numbers land in
43
+ * `numValue`, strings/booleans in `strValue` (booleans as "true"/"false"); see normalizeAttributeRows.
44
+ */
45
+ declare class RunAttributeEntity {
46
+ runId: string;
47
+ key: string;
48
+ strValue?: string | null;
49
+ numValue?: number | null;
50
+ }
51
+ declare class SignalWaiterEntity {
52
+ token: string;
53
+ runId: string;
54
+ seq: number;
55
+ }
56
+ declare class BufferedSignalEntity {
57
+ id: number;
58
+ token: string;
59
+ payload?: unknown;
60
+ }
61
+ declare const ENTITIES: readonly [typeof WorkflowRunEntity, typeof StepCheckpointEntity, typeof RunAttributeEntity, typeof SignalWaiterEntity, typeof BufferedSignalEntity];
62
+
63
+ /**
64
+ * MikroORM-backed `StateStore`. Works on any MikroORM driver — Postgres, MySQL, SQLite (tested);
65
+ * timestamps and `wakeAt` use native datetime columns. Each operation runs on a forked
66
+ * EntityManager so it owns its unit of work.
67
+ */
68
+ declare class MikroOrmStateStore implements StateStore {
69
+ private readonly orm;
70
+ constructor(orm: MikroORM);
71
+ ensureSchema(): Promise<void>;
72
+ createRun(run: WorkflowRun): Promise<void>;
73
+ updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void>;
74
+ /** Rewrite a run's normalized attribute rows: delete the old set, insert the current one. Mirrors
75
+ * the in-memory store's reindex so the side-table always reflects the run's live searchAttributes. */
76
+ private reindexAttributes;
77
+ getRun(runId: string): Promise<WorkflowRun | null>;
78
+ getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null>;
79
+ saveCheckpoint(checkpoint: StepCheckpoint): Promise<void>;
80
+ transaction<T>(work: (tx: {
81
+ raw: unknown;
82
+ saveCheckpoint: (cp: StepCheckpoint) => Promise<void>;
83
+ }) => Promise<T>): Promise<T>;
84
+ listIncompleteRuns(): Promise<WorkflowRun[]>;
85
+ listPendingRuns(limit: number): Promise<WorkflowRun[]>;
86
+ listDueTimers(nowMs: number): Promise<WorkflowRun[]>;
87
+ tryLockRun(runId: string, owner: string, leaseUntilMs: number, nowMs: number): Promise<boolean>;
88
+ releaseRunLock(runId: string): Promise<void>;
89
+ renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean>;
90
+ listRuns(query: RunQuery): Promise<WorkflowRun[]>;
91
+ /** One attribute predicate as a raw EXISTS subquery on the side-table, correlated to the outer run
92
+ * alias. `<>` (ne) also excludes runs where the attribute is absent (missing-key-never-matches):
93
+ * EXISTS already requires a present row, so EXISTS(... <> ...) is exactly ne-with-present. Numeric
94
+ * operands compare the num column, everything else the str column. Identifiers are quoted per
95
+ * driver and operands are inlined as literals (string operands are escaped by doubling quotes). */
96
+ private attributeExistsSql;
97
+ /** Resolve the side-table's actual column names from MikroORM metadata, so the raw EXISTS matches
98
+ * the active naming strategy (underscore vs camelCase) rather than guessing. The run PK column is
99
+ * reused for BOTH the outer correlation and the side-table FK (they share the same fieldName). */
100
+ private attributeColumns;
101
+ /** Resolve the `tags` column name from metadata (per the active naming strategy), for the raw LIKE. */
102
+ private tagsColumn;
103
+ /** Wrap a JSON column reference so it can be `LIKE`d as text. Postgres `jsonb`/`json` rejects `LIKE`
104
+ * directly (`operator does not exist: jsonb ~~ unknown`) — cast to `text`; MySQL JSON needs an
105
+ * explicit `CHAR` cast; SQLite stores JSON as text already, so no cast. */
106
+ private jsonAsText;
107
+ /** Quote an identifier per the active SQL driver (MySQL/MariaDB backtick, others double-quote). */
108
+ private idQuote;
109
+ listCheckpoints(runId: string): Promise<StepCheckpoint[]>;
110
+ putSignalWaiter(waiter: SignalWaiter): Promise<void>;
111
+ takeSignalWaiter(token: string): Promise<SignalWaiter | null>;
112
+ listSignalWaiters(prefix: string): Promise<SignalWaiter[]>;
113
+ bufferSignal(token: string, payload: unknown): Promise<void>;
114
+ takeBufferedSignal(token: string): Promise<{
115
+ payload: unknown;
116
+ } | null>;
117
+ }
118
+
119
+ /**
120
+ * Idempotently create/extend the durable tables (additive, never drops). Safe to run on every
121
+ * boot (auto-schema) and the function to call from a MikroORM migration when you disable
122
+ * auto-schema:
123
+ *
124
+ * ```ts
125
+ * export class AddDurableTables extends Migration {
126
+ * async up() { await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm()); }
127
+ * }
128
+ * ```
129
+ */
130
+ declare function ensureMikroOrmDurableSchema(orm: MikroORM): Promise<void>;
131
+
132
+ export { BufferedSignalEntity, ENTITIES, MikroOrmStateStore, RunAttributeEntity, SignalWaiterEntity, StepCheckpointEntity, WorkflowRunEntity, ensureMikroOrmDurableSchema };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,132 @@
1
- export * from './entities';
2
- export * from './mikro-orm-state-store';
3
- export * from './schema';
4
- //# sourceMappingURL=index.d.ts.map
1
+ import { RunStatus, StepKind, StateStore, WorkflowRun, StepCheckpoint, RunQuery, SignalWaiter } from '@dudousxd/nestjs-durable-core';
2
+ import { MikroORM } from '@mikro-orm/core';
3
+
4
+ declare class WorkflowRunEntity {
5
+ id: string;
6
+ workflow: string;
7
+ workflowVersion: string;
8
+ status: RunStatus;
9
+ input?: unknown;
10
+ output?: unknown;
11
+ error?: unknown;
12
+ wakeAt?: Date;
13
+ lockedBy?: string;
14
+ lockedUntil?: Date;
15
+ recoveryAttempts?: number;
16
+ tags?: string[] | null;
17
+ searchAttributes?: Record<string, string | number | boolean> | null;
18
+ createdAt: Date;
19
+ updatedAt: Date;
20
+ }
21
+ declare class StepCheckpointEntity {
22
+ runId: string;
23
+ seq: number;
24
+ name: string;
25
+ kind: StepKind;
26
+ stepId: string;
27
+ status: 'pending' | 'running' | 'completed' | 'failed';
28
+ input?: unknown;
29
+ output?: unknown;
30
+ error?: unknown;
31
+ events?: unknown;
32
+ attempts: number;
33
+ workerGroup?: string;
34
+ wakeAt?: Date;
35
+ enqueuedAt?: Date;
36
+ startedAt: Date;
37
+ finishedAt: Date;
38
+ }
39
+ /**
40
+ * Normalized side-table for search attributes: one row per (run, key), so range/equality predicates
41
+ * push DOWN into SQL (an EXISTS join indexed on `(key, numValue)` / `(key, strValue)`) instead of a
42
+ * coarse scan + in-process filter. Maintained on every createRun/updateRun. Numbers land in
43
+ * `numValue`, strings/booleans in `strValue` (booleans as "true"/"false"); see normalizeAttributeRows.
44
+ */
45
+ declare class RunAttributeEntity {
46
+ runId: string;
47
+ key: string;
48
+ strValue?: string | null;
49
+ numValue?: number | null;
50
+ }
51
+ declare class SignalWaiterEntity {
52
+ token: string;
53
+ runId: string;
54
+ seq: number;
55
+ }
56
+ declare class BufferedSignalEntity {
57
+ id: number;
58
+ token: string;
59
+ payload?: unknown;
60
+ }
61
+ declare const ENTITIES: readonly [typeof WorkflowRunEntity, typeof StepCheckpointEntity, typeof RunAttributeEntity, typeof SignalWaiterEntity, typeof BufferedSignalEntity];
62
+
63
+ /**
64
+ * MikroORM-backed `StateStore`. Works on any MikroORM driver — Postgres, MySQL, SQLite (tested);
65
+ * timestamps and `wakeAt` use native datetime columns. Each operation runs on a forked
66
+ * EntityManager so it owns its unit of work.
67
+ */
68
+ declare class MikroOrmStateStore implements StateStore {
69
+ private readonly orm;
70
+ constructor(orm: MikroORM);
71
+ ensureSchema(): Promise<void>;
72
+ createRun(run: WorkflowRun): Promise<void>;
73
+ updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void>;
74
+ /** Rewrite a run's normalized attribute rows: delete the old set, insert the current one. Mirrors
75
+ * the in-memory store's reindex so the side-table always reflects the run's live searchAttributes. */
76
+ private reindexAttributes;
77
+ getRun(runId: string): Promise<WorkflowRun | null>;
78
+ getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null>;
79
+ saveCheckpoint(checkpoint: StepCheckpoint): Promise<void>;
80
+ transaction<T>(work: (tx: {
81
+ raw: unknown;
82
+ saveCheckpoint: (cp: StepCheckpoint) => Promise<void>;
83
+ }) => Promise<T>): Promise<T>;
84
+ listIncompleteRuns(): Promise<WorkflowRun[]>;
85
+ listPendingRuns(limit: number): Promise<WorkflowRun[]>;
86
+ listDueTimers(nowMs: number): Promise<WorkflowRun[]>;
87
+ tryLockRun(runId: string, owner: string, leaseUntilMs: number, nowMs: number): Promise<boolean>;
88
+ releaseRunLock(runId: string): Promise<void>;
89
+ renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean>;
90
+ listRuns(query: RunQuery): Promise<WorkflowRun[]>;
91
+ /** One attribute predicate as a raw EXISTS subquery on the side-table, correlated to the outer run
92
+ * alias. `<>` (ne) also excludes runs where the attribute is absent (missing-key-never-matches):
93
+ * EXISTS already requires a present row, so EXISTS(... <> ...) is exactly ne-with-present. Numeric
94
+ * operands compare the num column, everything else the str column. Identifiers are quoted per
95
+ * driver and operands are inlined as literals (string operands are escaped by doubling quotes). */
96
+ private attributeExistsSql;
97
+ /** Resolve the side-table's actual column names from MikroORM metadata, so the raw EXISTS matches
98
+ * the active naming strategy (underscore vs camelCase) rather than guessing. The run PK column is
99
+ * reused for BOTH the outer correlation and the side-table FK (they share the same fieldName). */
100
+ private attributeColumns;
101
+ /** Resolve the `tags` column name from metadata (per the active naming strategy), for the raw LIKE. */
102
+ private tagsColumn;
103
+ /** Wrap a JSON column reference so it can be `LIKE`d as text. Postgres `jsonb`/`json` rejects `LIKE`
104
+ * directly (`operator does not exist: jsonb ~~ unknown`) — cast to `text`; MySQL JSON needs an
105
+ * explicit `CHAR` cast; SQLite stores JSON as text already, so no cast. */
106
+ private jsonAsText;
107
+ /** Quote an identifier per the active SQL driver (MySQL/MariaDB backtick, others double-quote). */
108
+ private idQuote;
109
+ listCheckpoints(runId: string): Promise<StepCheckpoint[]>;
110
+ putSignalWaiter(waiter: SignalWaiter): Promise<void>;
111
+ takeSignalWaiter(token: string): Promise<SignalWaiter | null>;
112
+ listSignalWaiters(prefix: string): Promise<SignalWaiter[]>;
113
+ bufferSignal(token: string, payload: unknown): Promise<void>;
114
+ takeBufferedSignal(token: string): Promise<{
115
+ payload: unknown;
116
+ } | null>;
117
+ }
118
+
119
+ /**
120
+ * Idempotently create/extend the durable tables (additive, never drops). Safe to run on every
121
+ * boot (auto-schema) and the function to call from a MikroORM migration when you disable
122
+ * auto-schema:
123
+ *
124
+ * ```ts
125
+ * export class AddDurableTables extends Migration {
126
+ * async up() { await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm()); }
127
+ * }
128
+ * ```
129
+ */
130
+ declare function ensureMikroOrmDurableSchema(orm: MikroORM): Promise<void>;
131
+
132
+ export { BufferedSignalEntity, ENTITIES, MikroOrmStateStore, RunAttributeEntity, SignalWaiterEntity, StepCheckpointEntity, WorkflowRunEntity, ensureMikroOrmDurableSchema };