@dudousxd/nestjs-durable 0.53.0 → 0.55.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/migrate-from-nestjs-workflows/index.ts","../src/store-run-gateway.ts","../src/migrate-from-nestjs-workflows/combined-run-gateway.ts"],"sourcesContent":["import {\n RunGateway,\n type RunResult,\n type RunStatus,\n STATE_STORE_CANONICAL,\n type StartOptions,\n type StateStore,\n type StepError,\n type WorkflowClass,\n WorkflowEngine,\n type WorkflowInputOf,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport { WorkflowsRunGateway, toWorkflowRun } from '@dudousxd/nestjs-durable-workflows-gateway';\nimport { type DynamicModule, Inject, Injectable, Module } from '@nestjs/common';\nimport { WorkflowClient, WorkflowEvents, type WorkflowStatus } from '@nestjs/workflows';\nimport { StoreRunGateway } from '../store-run-gateway';\nimport { CombinedRunGateway } from './combined-run-gateway';\n\nexport { CombinedRunGateway } from './combined-run-gateway';\n\n/** Which engine owns an instance id during the cutover. */\nexport type MigrationEngine = 'nestjs-durable' | '@nestjs/workflows';\n\n/** An instance's state, in durable's terms, from whichever engine owns it. */\nexport interface MigrationStatus {\n engine: MigrationEngine;\n runId: string;\n workflow: string;\n status: RunStatus;\n output?: unknown;\n error?: StepError | undefined;\n}\n\n/** The official statuses an instance still runs in (what a drain waits for). */\nconst UNFINISHED: WorkflowStatus[] = ['pending', 'running', 'suspended', 'compensating'];\nconst TERMINAL: RunStatus[] = ['completed', 'failed', 'cancelled', 'dead'];\n\n/**\n * Routes a client's calls during a cutover from `@nestjs/workflows` to nestjs-durable, when both\n * run side by side: new starts go to durable; `signal` / `cancel` / `getStatus` / `result` find the\n * instance in whichever engine owns its id, durable first. Instances never move between engines\n * (their journals differ): the official worker keeps finishing what it started.\n *\n * Signals follow the convention the migration codemod uses: the official `signal(name, payload,\n * { key })` is the durable token `<name>:<key>` (or `<name>` without a key).\n */\n@Injectable()\nexport class MigrationClient {\n constructor(\n private readonly engine: WorkflowEngine,\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore,\n private readonly official: WorkflowClient,\n ) {}\n\n /** Start a new instance, always on durable. */\n start<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId?: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n start(workflow: string, input: unknown, runId?: string, opts?: StartOptions): Promise<RunResult>;\n start(\n workflow: string | WorkflowClass,\n input: unknown,\n runId: string = globalThis.crypto.randomUUID(),\n opts?: StartOptions,\n ): Promise<RunResult> {\n return this.engine.start(workflowName(workflow), input, runId, opts);\n }\n\n /** The engine that owns `runId`, or `null` when neither has it. */\n async owner(runId: string): Promise<MigrationEngine | null> {\n if (await this.store.getRun(runId)) return 'nestjs-durable';\n if (await this.official.getStatus(runId)) return '@nestjs/workflows';\n return null;\n }\n\n /**\n * Signal the instance `runId` waits on: durable gets the token `<signal>:<key>` (deduplicated by\n * `id` per token), the official engine `signal(signal, payload, { key, id })`. Resolves the owner, or `null` for an unknown id\n * (nothing is sent: a signal for nobody would be buffered for a later wait).\n */\n async signal(\n runId: string,\n signal: string,\n payload: unknown,\n opts: { key?: string; id?: string } = {},\n ): Promise<MigrationEngine | null> {\n const owner = await this.owner(runId);\n if (owner === 'nestjs-durable') {\n await this.engine.signal(\n opts.key ? `${signal}:${opts.key}` : signal,\n payload,\n opts.id !== undefined ? { id: opts.id } : undefined,\n );\n } else if (owner === '@nestjs/workflows') {\n await this.official.signal(signal, payload as never, {\n ...(opts.key !== undefined ? { key: opts.key } : {}),\n ...(opts.id !== undefined ? { id: opts.id } : {}),\n });\n }\n return owner;\n }\n\n /**\n * Cancel `runId` where it runs. `compensate: true` runs the saga undo (official `cancel`);\n * otherwise it stops without compensating (official `terminate`).\n */\n async cancel(\n runId: string,\n opts: { compensate?: boolean } = {},\n ): Promise<MigrationStatus | null> {\n const owner = await this.owner(runId);\n if (owner === 'nestjs-durable') await this.engine.cancel(runId, opts);\n else if (owner === '@nestjs/workflows') {\n if (opts.compensate) await this.official.cancel(runId);\n else await this.official.terminate(runId);\n }\n return owner ? this.getStatus(runId) : null;\n }\n\n async getStatus(runId: string): Promise<MigrationStatus | null> {\n const run = await this.store.getRun(runId);\n if (run) {\n return {\n engine: 'nestjs-durable',\n runId,\n workflow: run.workflow,\n status: run.status,\n ...(run.output !== undefined ? { output: run.output } : {}),\n ...(run.error ? { error: run.error } : {}),\n };\n }\n const instance = await this.official.getStatus(runId);\n if (!instance) return null;\n const mapped = toWorkflowRun(instance);\n return {\n engine: '@nestjs/workflows',\n runId,\n workflow: instance.workflow,\n status: mapped.status,\n ...(mapped.output !== undefined ? { output: mapped.output } : {}),\n ...(mapped.error ? { error: mapped.error } : {}),\n };\n }\n\n /**\n * Wait for `runId` to finish where it runs and resolve its status (`completed` with `output`, or\n * `failed` / `cancelled` / `dead` with `error`). Never throws for a failed instance.\n */\n async result(runId: string, opts: { timeoutMs?: number } = {}): Promise<MigrationStatus> {\n const owner = await this.owner(runId);\n if (owner === 'nestjs-durable') {\n await this.engine.waitForRun(runId, {\n until: 'terminal',\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n });\n } else if (owner === '@nestjs/workflows') {\n await this.official\n .result(runId, opts.timeoutMs !== undefined ? { timeout: opts.timeoutMs } : {})\n .catch((error: unknown) => {\n // A failed / cancelled instance rejects with WorkflowFailedError: its status says so.\n if ((error as { name?: string })?.name !== 'WorkflowFailedError') throw error;\n });\n } else {\n throw new Error(`no instance ${runId} in nestjs-durable or @nestjs/workflows`);\n }\n const status = await this.getStatus(runId);\n if (!status || !TERMINAL.includes(status.status)) {\n throw new Error(`instance ${runId} did not finish`);\n }\n return status;\n }\n\n /**\n * How many instances the official engine still has to finish. The cutover is over when it is 0:\n * nothing starts there any more, so it only goes down.\n */\n async remainingOnOfficial(): Promise<number> {\n return (await this.official.list({ status: UNFINISHED, limit: 10_000 })).length;\n }\n}\n\n/** One console over both engines: durable's store gateway + the official gateway, combined. */\nfunction combinedGateway(\n store: StateStore,\n engine: WorkflowEngine,\n client: WorkflowClient,\n events: WorkflowEvents,\n): RunGateway {\n return new CombinedRunGateway(\n new StoreRunGateway(store, engine),\n new WorkflowsRunGateway(client, events),\n );\n}\n\n/**\n * The cutover from `@nestjs/workflows`: import next to `DurableModule.forRoot(...)` and\n * `WorkflowsModule.forRoot(...)`.\n *\n * - `forRoot()` provides {@link MigrationClient} (global).\n * - `console()` binds the dashboard to BOTH engines: pass it to the dashboard's `imports`,\n * `DurableDashboardModule.forRoot({ imports: [DurableMigrationModule.console()] })`, where it takes\n * precedence over the durable-only gateway `DurableModule` binds.\n */\n@Module({})\nexport class DurableMigrationModule {\n static forRoot(): DynamicModule {\n return {\n module: DurableMigrationModule,\n global: true,\n providers: [MigrationClient],\n exports: [MigrationClient],\n };\n }\n\n static console(): DynamicModule {\n return {\n module: DurableMigrationConsoleModule,\n providers: [\n {\n provide: RunGateway,\n inject: [STATE_STORE_CANONICAL, WorkflowEngine, WorkflowClient, WorkflowEvents],\n useFactory: combinedGateway,\n },\n ],\n exports: [RunGateway],\n };\n }\n}\n\n@Module({})\nclass DurableMigrationConsoleModule {}\n","import {\n type DurableTopology,\n type EngineEvent,\n type FanPage,\n type FanPageQuery,\n type GroupHealth,\n LIFECYCLE_REGISTRY_WORKFLOW,\n type LifecycleDelivery,\n type LifecycleKind,\n type RepublishLifecycleResult,\n type RepublishLifecycleTarget,\n type RunDetail,\n type RunDetailOptions,\n type RunFacetQuery,\n type RunFacetRow,\n type RunGateway,\n type RunListItem,\n type RunQuery,\n type RunResult,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type RunWaitLink,\n type RunWaiting,\n STATE_STORE_CANONICAL,\n SUMMARY_CHILD_LIMIT,\n type StateStore,\n WorkflowEngine,\n type WorkflowLifecycleLinks,\n type WorkflowRun,\n aggregatesCheckpoints,\n childIdsOf,\n etagMatches,\n extendEtag,\n fanPageEtag,\n indexWaitersByRun,\n lifecycleDeliveriesOf,\n lifecycleKindOf,\n lifecycleSourceOf,\n lifecycleTraceparentOf,\n listSignalWaitersOfRuns,\n mergeRunFacetRows,\n pageFan,\n pageFanFromStore,\n readRunsByIds,\n resolveRunWaiting,\n runDetailEtag,\n runWaitPrefix,\n runWaitTargetOf,\n summarizeRunFromStore,\n summarizeTimeline,\n traceIdOfTraceparent,\n} from '@dudousxd/nestjs-durable-core';\nimport { Inject, Injectable } from '@nestjs/common';\n\n/**\n * What a run detail reads from outside the run row and its checkpoints, folded into its ETag: the\n * subscribers and where each delivery stands, and the status of every run its links point at.\n * Undefined when it has none of them.\n */\nfunction detailExtras(\n links: Pick<\n RunDetail,\n 'lifecycleSubscribers' | 'lifecycleDeliveries' | 'waitsFor' | 'awaitedBy' | 'triggeredBy'\n >,\n): unknown {\n const { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy } = links;\n if (!lifecycleSubscribers && !lifecycleDeliveries && !waitsFor && !awaitedBy && !triggeredBy) {\n return undefined;\n }\n return { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy };\n}\n\n/**\n * `query` without the lifecycle registry's runs, engine bookkeeping that is not a run anyone\n * started, unless the query names that workflow itself.\n */\nfunction withoutRegistry<Q extends RunFacetQuery>(query: Q): Q {\n if (\n query.workflow === LIFECYCLE_REGISTRY_WORKFLOW ||\n query.workflows?.includes(LIFECYCLE_REGISTRY_WORKFLOW)\n ) {\n return query;\n }\n return {\n ...query,\n excludeWorkflows: [...(query.excludeWorkflows ?? []), LIFECYCLE_REGISTRY_WORKFLOW],\n };\n}\n\n/**\n * Store-backed `RunGateway` — the operator-side implementation, bound to {@link RUN_GATEWAY} on\n * worker/drive instances. Reuses `DashboardService`'s six read/control method bodies verbatim\n * (`dashboard.service.ts:76-172`), so a consumer that only needs the bounded `RunGateway` surface\n * (the `RunRequestResponder`, a thin controller) doesn't have to depend on the dashboard package.\n */\n@Injectable()\nexport class StoreRunGateway implements RunGateway {\n constructor(\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore,\n private readonly engine: WorkflowEngine,\n ) {}\n\n topology(): DurableTopology {\n return { role: 'control-plane' };\n }\n\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const links = await this.lifecycleLinks(run);\n const over = options?.summarizeFansOver;\n if (over === undefined) {\n const [timeline, children] = await Promise.all([\n this.store.listCheckpoints(runId),\n this.engine.getRunChildren(runId), // canonical parent→children edge (shared with cancel cascade)\n ]);\n return { run, timeline, children, ...links };\n }\n // Summarized: the children come from the checkpoints, rather than from a read of every\n // child-edge checkpoint plus the waiters. A child whose waiter is written but whose placeholder\n // checkpoint is not yet is missing for that one read; the next one lists it.\n if (aggregatesCheckpoints(this.store)) {\n // The buckets are read before any row, so a write landing mid-read leaves the ETag older than\n // the body: the next poll misses and re-reads, rather than pinning a stale body.\n const stats = await this.store.checkpointStats(runId);\n const etag = extendEtag(runDetailEtag(run, stats, over), detailExtras(links));\n if (etagMatches(options?.ifNoneMatch, etag)) {\n return { run, timeline: [], children: [], notModified: true, etag };\n }\n return {\n run,\n ...(await summarizeRunFromStore(this.store, runId, over, stats)),\n etag,\n ...links,\n };\n }\n const full = await this.store.listCheckpoints(runId);\n const { timeline, fans } = summarizeTimeline(full, over);\n const ids = childIdsOf(full);\n return {\n run,\n timeline,\n children: ids.slice(0, SUMMARY_CHILD_LIMIT),\n fans,\n childCount: ids.length,\n ...links,\n };\n }\n\n /**\n * What a run detail reads beyond the run row and its checkpoints: what this run's settling\n * started, the subscribers its lifecycle event goes to (of its namespace) and where it stands for\n * each, what started it, its workflow's lifecycle links, and the `ctx.waitForRun` waits on either\n * side of it with the other run's status. A few reads per detail: the run's own waiters while it\n * is suspended, the waiters on it (one prefix read), and one batched read of every linked run.\n */\n private async lifecycleLinks(\n run: WorkflowRun,\n ): Promise<\n Pick<\n RunDetail,\n | 'triggered'\n | 'triggeredBy'\n | 'lifecycleSubscribers'\n | 'workflowLifecycle'\n | 'lifecycleDeliveries'\n | 'waitsFor'\n | 'awaitedBy'\n >\n > {\n const triggered = await this.engine.triggeredRuns(run);\n const source = lifecycleSourceOf(run);\n const kind = lifecycleKindOf(run.status);\n const subscribers = kind\n ? await this.engine.lifecycleSubscribers(run.workflow, kind, run.namespace || 'default')\n : [];\n const workflowLifecycle = await this.engine.workflowLifecycle(run.workflow);\n const linked =\n workflowLifecycle.startsOnSettle.length > 0 || workflowLifecycle.startedBy.length > 0;\n const deliveries = kind\n ? lifecycleDeliveriesOf(run, {\n subscribers,\n live: new Set(subscribers),\n coalesced: this.engine.coalescedSubscribers(run),\n })\n : [];\n const [own, onIt] = await Promise.all([\n run.status === 'suspended' ? listSignalWaitersOfRuns(this.store, [run.id]) : [],\n run.workflow.startsWith('__') ? [] : this.store.listSignalWaiters(runWaitPrefix(run.id)),\n ]);\n const waitsFor: RunWaitLink[] = own.flatMap((w) => {\n const target = runWaitTargetOf(w);\n return target !== undefined ? [{ runId: target, seq: w.seq }] : [];\n });\n const awaitedBy: RunWaitLink[] = onIt\n .filter((w) => runWaitTargetOf(w) === run.id)\n .map((w) => ({ runId: w.runId, seq: w.seq }));\n const started = deliveries.flatMap((d) =>\n d.state === 'started' && d.runId !== undefined ? [d.runId] : [],\n );\n const { runs } = await readRunsByIds(this.store, [\n ...(source ? [source.runId] : []),\n ...started,\n ...waitsFor.map((l) => l.runId),\n ...awaitedBy.map((l) => l.runId),\n ]);\n const withRun = <T extends { runId?: string | undefined }>(link: T): T => {\n const other = link.runId !== undefined ? runs.get(link.runId) : undefined;\n return other ? { ...link, status: other.status, namespace: other.namespace } : link;\n };\n const sourceRun = source ? runs.get(source.runId) : undefined;\n const traceId = traceIdOfTraceparent(lifecycleTraceparentOf(sourceRun?.tags));\n return {\n ...(triggered.length > 0 ? { triggered } : {}),\n ...(source\n ? {\n triggeredBy: {\n ...source,\n ...(sourceRun ? { status: sourceRun.status, namespace: sourceRun.namespace } : {}),\n ...(traceId ? { traceId } : {}),\n },\n }\n : {}),\n ...(subscribers.length > 0 ? { lifecycleSubscribers: subscribers } : {}),\n ...(linked ? { workflowLifecycle } : {}),\n ...(deliveries.length > 0\n ? {\n lifecycleDeliveries: deliveries.map(\n (d): LifecycleDelivery => (d.state === 'started' ? withRun(d) : d),\n ),\n }\n : {}),\n ...(waitsFor.length > 0 ? { waitsFor: waitsFor.map(withRun) } : {}),\n ...(awaitedBy.length > 0 ? { awaitedBy: awaitedBy.map(withRun) } : {}),\n };\n }\n\n workflowLifecycle(\n workflow: string,\n opts?: { namespace?: string | undefined },\n ): Promise<WorkflowLifecycleLinks> {\n return this.engine.workflowLifecycle(workflow, opts);\n }\n\n lifecycleSubscribers(\n workflow: string,\n kind: LifecycleKind,\n namespace: string,\n ): Promise<string[]> {\n return this.engine.lifecycleSubscribers(workflow, kind, namespace);\n }\n\n getRun(runId: string): Promise<WorkflowRun | null> {\n return this.store.getRun(runId);\n }\n\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (!(await this.store.getRun(runId))) return null;\n if (aggregatesCheckpoints(this.store)) {\n const stats = await this.store.checkpointStats(runId, { group });\n const etag = fanPageEtag(group, stats, query);\n if (etagMatches(query.ifNoneMatch, etag)) {\n return { items: [], total: 0, notModified: true, etag };\n }\n return { ...(await pageFanFromStore(this.store, runId, group, query, stats)), etag };\n }\n return pageFan(await this.store.listCheckpoints(runId), group, query);\n }\n\n async listRuns(query: RunQuery): Promise<RunListItem[]> {\n const runs = await this.store.listRuns(withoutRegistry(query));\n // One read of the listed suspended runs' signal waiters resolves what each is parked on — signal\n // / webhook / child — with no per-run timeline fetch. A timer wait falls back to the run's own\n // `wakeAt`. Non-suspended (and remote-step-in-flight) runs carry no `waiting`.\n const waiterByRun = indexWaitersByRun(\n await listSignalWaitersOfRuns(\n this.store,\n runs.filter((run) => run.status === 'suspended').map((run) => run.id),\n ),\n );\n return runs.map((run) => {\n const waiting = resolveRunWaiting(run, waiterByRun);\n return waiting ? { ...run, waiting } : run;\n });\n }\n\n /**\n * The `(status, origin)` counts behind a console's chips, straight off the store's aggregate. The\n * console needs this precisely BECAUSE its list is paginated: the page bounds what is rendered,\n * these counts stay whole-set exact. A store with no aggregate falls back to counting a full\n * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.\n */\n async runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n const scoped = withoutRegistry(query);\n if (this.store.runFacets) return this.store.runFacets(scoped);\n const runs = await this.store.listRuns(scoped);\n return mergeRunFacetRows(runs.map((r) => ({ status: r.status, origin: r.origin, count: 1 })));\n }\n\n /**\n * The distinct values behind a console's pickers, straight off the store's enumeration. A store\n * without one answers `[]` rather than falling back to a listing: unlike the facet counts above —\n * where a full listing is at least the RIGHT answer expensively — a picker built from an unbounded\n * scan would be the same unbounded read on every keystroke, for a control whose free-text entry\n * still works without it.\n */\n async runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];\n }\n\n /**\n * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/\n * paginated run listing (e.g. \"which of MY suspended runs are stuck at a breakpoint\") without\n * re-deriving `listRuns`' waiter read or querying `durable_step_checkpoints` directly. Mirrors\n * `listRuns`' waiting computation (the requested runs' signal waiters + `resolveRunWaiting`), but ALSO\n * bulk-fetches the currently-suspended runs to check real status: `engine.cancel` (the non-compensate\n * path) doesn't clear a run's signal waiter row, so a cancelled run can leave an ORPHANED waiter\n * behind — trusting waiter presence alone would wrongly report a terminal run as still waiting.\n * Two bulk reads total (never one query per requested id), same as `listRuns`.\n */\n async waitingFor(runIds: string[]): Promise<Record<string, RunWaiting>> {\n if (runIds.length === 0) return {};\n const idSet = new Set(runIds);\n const [suspended, waiters] = await Promise.all([\n this.store.listRuns({ statuses: ['suspended'] }),\n listSignalWaitersOfRuns(this.store, runIds),\n ]);\n const waiterByRun = indexWaitersByRun(waiters);\n const result: Record<string, RunWaiting> = {};\n for (const run of suspended) {\n if (!idSet.has(run.id)) continue;\n const waiting = resolveRunWaiting(run, waiterByRun);\n if (waiting) result[run.id] = waiting;\n }\n return result;\n }\n\n /** Every group the engine knows about — unscoped. A tenant proxy's request is scoped by the\n * `RunRequestResponder` (to the requester's `@<tenant>` groups); the operator's own UI sees all. */\n workerHealth(): Promise<GroupHealth[]> {\n return this.engine.workerHealth();\n }\n\n cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n return this.engine.cancel(runId, opts);\n }\n\n /** Re-enqueue (dispatch model) instead of resuming inline — a worker picks the run up and replays it. */\n retry(runId: string): Promise<RunResult | null> {\n return this.engine.requeue(runId);\n }\n\n continue(runId: string): Promise<RunResult | null> {\n return this.engine.continue(runId);\n }\n\n retryWithInput(runId: string, input: unknown): Promise<{ runId: string } | null> {\n return this.engine.retryWithInput(runId, input);\n }\n\n redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return this.engine.redispatchPending(runId);\n }\n\n republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n return this.engine.republishLifecycle(target);\n }\n\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n return this.engine.subscribe((event) => {\n if (event.runId === runId) onEvent(event);\n });\n }\n}\n","import {\n type DurableTopology,\n type EngineEvent,\n type GroupHealth,\n type RunDetail,\n type RunDetailOptions,\n type RunFacetQuery,\n type RunFacetRow,\n RunGateway,\n type RunListItem,\n type RunQuery,\n type RunResult,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type RunWaiting,\n type WorkflowRun,\n} from '@dudousxd/nestjs-durable-core';\n\n/**\n * One console over two engines during a cutover: `primary` (nestjs-durable) and `legacy` (the\n * official `@nestjs/workflows`, through `@dudousxd/nestjs-durable-workflows-gateway`). Lists and\n * counts merge both; everything addressed by a run id goes to whichever engine has that id, durable\n * first. The console shows every control (durable runs support them); one a legacy run can't serve\n * answers like a missing run.\n */\nexport class CombinedRunGateway extends RunGateway {\n private readonly primary: RunGateway;\n private readonly legacy: RunGateway;\n // Durable-only features (lifecycle events, fan paging): the primary's, when it has them.\n override getFanMembers?: NonNullable<RunGateway['getFanMembers']>;\n override republishLifecycle?: NonNullable<RunGateway['republishLifecycle']>;\n override workflowLifecycle?: NonNullable<RunGateway['workflowLifecycle']>;\n override lifecycleSubscribers?: NonNullable<RunGateway['lifecycleSubscribers']>;\n\n constructor(primary: RunGateway, legacy: RunGateway) {\n super();\n this.primary = primary;\n this.legacy = legacy;\n if (primary.getFanMembers) this.getFanMembers = primary.getFanMembers.bind(primary);\n if (primary.republishLifecycle)\n this.republishLifecycle = primary.republishLifecycle.bind(primary);\n if (primary.workflowLifecycle) this.workflowLifecycle = primary.workflowLifecycle.bind(primary);\n if (primary.lifecycleSubscribers) {\n this.lifecycleSubscribers = primary.lifecycleSubscribers.bind(primary);\n }\n }\n\n topology(): DurableTopology {\n return { ...this.primary.topology(), engine: 'nestjs-durable + @nestjs/workflows' };\n }\n\n /** The gateway that has `runId`, durable first; `undefined` when neither does. */\n private async owner(runId: string): Promise<RunGateway | undefined> {\n for (const gateway of [this.primary, this.legacy]) {\n const run = gateway.getRun\n ? await gateway.getRun(runId)\n : (await gateway.getRunDetail(runId))?.run;\n if (run) return gateway;\n }\n return undefined;\n }\n\n override async getRun(runId: string): Promise<WorkflowRun | null> {\n return (\n (await this.primary.getRun?.(runId)) ??\n (await this.legacy.getRun?.(runId)) ??\n (await this.getRunDetail(runId))?.run ??\n null\n );\n }\n\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n return (\n (await this.primary.getRunDetail(runId, options)) ?? this.legacy.getRunDetail(runId, options)\n );\n }\n\n /**\n * Both lists, newest first, then the page. The legacy side holds only the rows its gateway can\n * read: the official gateway reads at most `WORKFLOWS_LIST_CAP` (1000) matching instances per list,\n * so legacy rows past that cap are missing here as they are from the legacy console, and deep pages\n * show durable rows only.\n */\n async listRuns(query: RunQuery): Promise<RunListItem[]> {\n const offset = query.offset ?? 0;\n const limit = query.limit ?? 100;\n const window = { ...query, offset: 0, limit: offset + limit };\n const [a, b] = await Promise.all([this.primary.listRuns(window), this.legacy.listRuns(window)]);\n return [...a, ...b]\n .sort((x, y) => y.createdAt.getTime() - x.createdAt.getTime() || y.id.localeCompare(x.id))\n .slice(offset, offset + limit);\n }\n\n async runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n const [a, b] = await Promise.all([this.primary.runFacets(query), this.legacy.runFacets(query)]);\n const cells = new Map<string, RunFacetRow>();\n for (const row of [...a, ...b]) {\n const key = `${row.status}\\u0000${row.origin ?? ''}`;\n const cell = cells.get(key);\n if (cell) cell.count += row.count;\n else cells.set(key, { ...row });\n }\n return [...cells.values()];\n }\n\n async runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n const [a, b] = await Promise.all([\n this.primary.runValueFacets(axis, query, opts),\n this.legacy.runValueFacets(axis, query, opts),\n ]);\n const counts = new Map<string | null, number>();\n for (const row of [...a, ...b]) counts.set(row.value, (counts.get(row.value) ?? 0) + row.count);\n return [...counts]\n .map(([value, count]) => ({ value, count }))\n .sort((x, y) => y.count - x.count);\n }\n\n async waitingFor(runIds: string[]): Promise<Record<string, RunWaiting>> {\n const [a, b] = await Promise.all([\n this.primary.waitingFor(runIds),\n this.legacy.waitingFor(runIds),\n ]);\n return { ...b, ...a };\n }\n\n workerHealth(): Promise<GroupHealth[]> {\n return this.primary.workerHealth();\n }\n\n async cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n return (await this.owner(runId))?.cancel(runId, opts) ?? null;\n }\n\n async retry(runId: string): Promise<RunResult | null> {\n return (await this.owner(runId))?.retry(runId) ?? null;\n }\n\n async continue(runId: string): Promise<RunResult | null> {\n return (await this.owner(runId))?.continue(runId) ?? null;\n }\n\n async redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return (await this.owner(runId))?.redispatchPending(runId) ?? null;\n }\n\n /** Replays on the engine that ran it (a legacy run's workflow may not exist on durable yet). */\n async retryWithInput(runId: string, input: unknown): Promise<{ runId: string } | null> {\n return (await this.owner(runId))?.retryWithInput(runId, input) ?? null;\n }\n\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n const offs = [this.primary.subscribe(runId, onEvent), this.legacy.subscribe(runId, onEvent)];\n return () => {\n for (const off of offs) off();\n };\n }\n}\n"],"mappings":";;;;AAAA,SACEA,cAAAA,aAGAC,yBAAAA,wBAKAC,kBAAAA,iBAEAC,oBACK;AACP,SAASC,qBAAqBC,qBAAqB;AACnD,SAA6BC,UAAAA,SAAQC,cAAAA,aAAYC,cAAc;AAC/D,SAASC,gBAAgBC,sBAA2C;;;ACfpE,SAMEC,6BAkBAC,uBACAC,qBAEAC,gBAGAC,uBACAC,YACAC,aACAC,YACAC,aACAC,mBACAC,uBACAC,iBACAC,mBACAC,wBACAC,yBACAC,mBACAC,SACAC,kBACAC,eACAC,mBACAC,eACAC,eACAC,iBACAC,uBACAC,mBACAC,4BACK;AACP,SAASC,QAAQC,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOnC,SAASC,aACPC,OAGC;AAED,QAAM,EAAEC,sBAAsBC,qBAAqBC,UAAUC,WAAWC,YAAW,IAAKL;AACxF,MAAI,CAACC,wBAAwB,CAACC,uBAAuB,CAACC,YAAY,CAACC,aAAa,CAACC,aAAa;AAC5F,WAAOC;EACT;AACA,SAAO;IAAEL;IAAsBC;IAAqBC;IAAUC;IAAWC;EAAY;AACvF;AAXSN;AAiBT,SAASQ,gBAAyCC,OAAQ;AACxD,MACEA,MAAMC,aAAaC,+BACnBF,MAAMG,WAAWC,SAASF,2BAAAA,GAC1B;AACA,WAAOF;EACT;AACA,SAAO;IACL,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,YAAKA,OAA6BU,SAAS,sBAAuB,OAAMV;MAC1E,CAAA;IACJ,OAAO;AACL,YAAM,IAAIW,MAAM,eAAe/B,KAAAA,yCAA8C;IAC/E;AACA,UAAMkB,SAAS,MAAM,KAAKV,UAAUR,KAAAA;AACpC,QAAI,CAACkB,UAAU,CAAC1B,SAASwC,SAASd,OAAOA,MAAM,GAAG;AAChD,YAAM,IAAIa,MAAM,YAAY/B,KAAAA,iBAAsB;IACpD;AACA,WAAOkB;EACT;;;;;EAMA,MAAMe,sBAAuC;AAC3C,YAAQ,MAAM,KAAKrC,SAASsC,KAAK;MAAEhB,QAAQ3B;MAAY4C,OAAO;IAAO,CAAA,GAAIC;EAC3E;AACF;;;;;;;;;;;AAGA,SAASC,gBACP1C,OACAD,QACA4C,QACAC,QAAsB;AAEtB,SAAO,IAAIC,mBACT,IAAIC,gBAAgB9C,OAAOD,MAAAA,GAC3B,IAAIgD,oBAAoBJ,QAAQC,MAAAA,CAAAA;AAEpC;AAVSF;AAsBF,IAAMM,yBAAN,MAAMA,wBAAAA;SAAAA;;;EACX,OAAOC,UAAyB;AAC9B,WAAO;MACLC,QAAQF;MACRG,QAAQ;MACRC,WAAW;QAACtD;;MACZuD,SAAS;QAACvD;;IACZ;EACF;EAEA,OAAOwD,UAAyB;AAC9B,WAAO;MACLJ,QAAQK;MACRH,WAAW;QACT;UACEI,SAASC;UACTC,QAAQ;YAACC;YAAuBC;YAAgBC;YAAgBC;;UAChEC,YAAYrB;QACd;;MAEFW,SAAS;QAACI;;IACZ;EACF;AACF;;;;AAEA,IACMF,gCADN,MACMA,+BAAAA;SAAAA;;;AAA+B;;;;","names":["RunGateway","STATE_STORE_CANONICAL","WorkflowEngine","workflowName","WorkflowsRunGateway","toWorkflowRun","Inject","Injectable","Module","WorkflowClient","WorkflowEvents","LIFECYCLE_REGISTRY_WORKFLOW","STATE_STORE_CANONICAL","SUMMARY_CHILD_LIMIT","WorkflowEngine","aggregatesCheckpoints","childIdsOf","etagMatches","extendEtag","fanPageEtag","indexWaitersByRun","lifecycleDeliveriesOf","lifecycleKindOf","lifecycleSourceOf","lifecycleTraceparentOf","listSignalWaitersOfRuns","mergeRunFacetRows","pageFan","pageFanFromStore","readRunsByIds","resolveRunWaiting","runDetailEtag","runWaitPrefix","runWaitTargetOf","summarizeRunFromStore","summarizeTimeline","traceIdOfTraceparent","Inject","Injectable","detailExtras","links","lifecycleSubscribers","lifecycleDeliveries","waitsFor","awaitedBy","triggeredBy","undefined","withoutRegistry","query","workflow","LIFECYCLE_REGISTRY_WORKFLOW","workflows","includes","excludeWorkflows","StoreRunGateway","store","engine","topology","role","getRunDetail","runId","options","run","getRun","lifecycleLinks","over","summarizeFansOver","timeline","children","Promise","all","listCheckpoints","getRunChildren","aggregatesCheckpoints","stats","checkpointStats","etag","extendEtag","runDetailEtag","etagMatches","ifNoneMatch","notModified","summarizeRunFromStore","full","fans","summarizeTimeline","ids","childIdsOf","slice","SUMMARY_CHILD_LIMIT","childCount","length","triggered","triggeredRuns","source","lifecycleSourceOf","kind","lifecycleKindOf","status","subscribers","namespace","workflowLifecycle","linked","startsOnSettle","startedBy","deliveries","lifecycleDeliveriesOf","live","Set","coalesced","coalescedSubscribers","own","onIt","listSignalWaitersOfRuns","id","startsWith","listSignalWaiters","runWaitPrefix","flatMap","w","target","runWaitTargetOf","seq","filter","map","started","d","state","runs","readRunsByIds","l","withRun","link","other","get","sourceRun","traceId","traceIdOfTraceparent","lifecycleTraceparentOf","tags","opts","getFanMembers","group","fanPageEtag","items","total","pageFanFromStore","pageFan","listRuns","waiterByRun","indexWaitersByRun","waiting","resolveRunWaiting","runFacets","scoped","mergeRunFacetRows","r","origin","count","runValueFacets","axis","waitingFor","runIds","idSet","suspended","waiters","statuses","result","has","workerHealth","cancel","retry","requeue","continue","retryWithInput","input","redispatchPending","republishLifecycle","subscribe","onEvent","event","RunGateway","CombinedRunGateway","RunGateway","primary","legacy","getFanMembers","republishLifecycle","workflowLifecycle","lifecycleSubscribers","bind","topology","engine","owner","runId","gateway","run","getRun","getRunDetail","undefined","options","listRuns","query","offset","limit","window","a","b","Promise","all","sort","x","y","createdAt","getTime","id","localeCompare","slice","runFacets","cells","Map","row","key","status","origin","cell","get","count","set","values","runValueFacets","axis","opts","counts","value","map","waitingFor","runIds","workerHealth","cancel","retry","continue","redispatchPending","retryWithInput","input","subscribe","onEvent","offs","off","UNFINISHED","TERMINAL","MigrationClient","engine","store","official","start","workflow","input","runId","globalThis","crypto","randomUUID","opts","workflowName","owner","getRun","getStatus","signal","payload","key","id","undefined","cancel","compensate","terminate","run","status","output","error","instance","mapped","toWorkflowRun","result","waitForRun","until","timeoutMs","timeout","catch","name","Error","includes","remainingOnOfficial","list","limit","length","combinedGateway","client","events","CombinedRunGateway","StoreRunGateway","WorkflowsRunGateway","DurableMigrationModule","forRoot","module","global","providers","exports","console","DurableMigrationConsoleModule","provide","RunGateway","inject","STATE_STORE_CANONICAL","WorkflowEngine","WorkflowClient","WorkflowEvents","useFactory"]}
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/outbox/index.ts
22
+ var outbox_exports = {};
23
+ __export(outbox_exports, {
24
+ DURABLE_OUTBOX_CONSUMER: () => DURABLE_OUTBOX_CONSUMER,
25
+ DURABLE_OUTBOX_TOPIC: () => DURABLE_OUTBOX_TOPIC,
26
+ DurableOutbox: () => DurableOutbox,
27
+ DurableOutboxHandler: () => DurableOutboxHandler,
28
+ DurableOutboxModule: () => DurableOutboxModule,
29
+ applyDurableOutboxMessage: () => applyDurableOutboxMessage
30
+ });
31
+ module.exports = __toCommonJS(outbox_exports);
32
+
33
+ // src/outbox/durable-outbox.ts
34
+ var import_node_crypto = require("crypto");
35
+ var import_nestjs_durable_core = require("@dudousxd/nestjs-durable-core");
36
+ var import_common = require("@nestjs/common");
37
+ var import_outbox = require("@nestjs/outbox");
38
+ function _ts_decorate(decorators, target, key, desc) {
39
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
40
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
41
+ r = Reflect.decorate(decorators, target, key, desc);
42
+ } else {
43
+ for (var i = decorators.length - 1; i >= 0; i--) {
44
+ if (d = decorators[i]) {
45
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
46
+ }
47
+ }
48
+ }
49
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
50
+ }
51
+ __name(_ts_decorate, "_ts_decorate");
52
+ function _ts_metadata(metadataKey, metadataValue) {
53
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
54
+ return Reflect.metadata(metadataKey, metadataValue);
55
+ }
56
+ }
57
+ __name(_ts_metadata, "_ts_metadata");
58
+ function _ts_param(paramIndex, decorator) {
59
+ return function(target, key) {
60
+ decorator(target, key, paramIndex);
61
+ };
62
+ }
63
+ __name(_ts_param, "_ts_param");
64
+ var DURABLE_OUTBOX_TOPIC = "nestjs-durable";
65
+ var DURABLE_OUTBOX_CONSUMER = "nestjs-durable";
66
+ var OPTIONS = Symbol("DURABLE_OUTBOX_OPTIONS");
67
+ var DurableOutbox = class {
68
+ static {
69
+ __name(this, "DurableOutbox");
70
+ }
71
+ outbox;
72
+ options;
73
+ constructor(outbox, options) {
74
+ this.outbox = outbox;
75
+ this.options = options;
76
+ }
77
+ async start(tx, workflow, input, opts = {}) {
78
+ const { runId = (0, import_node_crypto.randomUUID)(), key, startAt, ...rest } = opts;
79
+ const wireOpts = {
80
+ ...rest,
81
+ ...startAt !== void 0 ? {
82
+ startAt: startAt instanceof Date ? startAt.getTime() : startAt
83
+ } : {}
84
+ };
85
+ const payload = {
86
+ v: 1,
87
+ kind: "start",
88
+ workflow: (0, import_nestjs_durable_core.workflowName)(workflow),
89
+ input,
90
+ runId,
91
+ ...Object.keys(wireOpts).length > 0 ? {
92
+ opts: wireOpts
93
+ } : {}
94
+ };
95
+ await this.outbox.add(tx, {
96
+ topic: this.options.topic,
97
+ payload,
98
+ key: key ?? null
99
+ });
100
+ return {
101
+ runId
102
+ };
103
+ }
104
+ /**
105
+ * Write a "deliver this signal" message through `tx`: after commit, the payload is delivered to
106
+ * the run waiting on `token` (`ctx.waitForSignal(token)`), or buffered for it like
107
+ * `WorkflowService.signal`.
108
+ */
109
+ async signal(tx, token, payload, opts = {}) {
110
+ const message = {
111
+ v: 1,
112
+ kind: "signal",
113
+ token,
114
+ payload
115
+ };
116
+ await this.outbox.add(tx, {
117
+ topic: this.options.topic,
118
+ payload: message,
119
+ key: opts.key === void 0 ? token : opts.key,
120
+ ...opts.id !== void 0 ? {
121
+ id: opts.id
122
+ } : {}
123
+ });
124
+ }
125
+ /** Poll the relay now (after your transaction commits) instead of waiting for its interval. */
126
+ notify() {
127
+ this.outbox.notify();
128
+ }
129
+ };
130
+ DurableOutbox = _ts_decorate([
131
+ (0, import_common.Injectable)(),
132
+ _ts_param(1, (0, import_common.Inject)(OPTIONS)),
133
+ _ts_metadata("design:type", Function),
134
+ _ts_metadata("design:paramtypes", [
135
+ typeof import_outbox.Outbox === "undefined" ? Object : import_outbox.Outbox,
136
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
137
+ ])
138
+ ], DurableOutbox);
139
+ async function applyDurableOutboxMessage(engine, message) {
140
+ if (!message || message.v !== 1) {
141
+ throw new import_outbox.NonRetryableMessageError(`unsupported durable outbox payload: ${JSON.stringify(message)?.slice(0, 200)}`);
142
+ }
143
+ try {
144
+ if (message.kind === "start") {
145
+ await engine.start(message.workflow, message.input, message.runId, message.opts);
146
+ return;
147
+ }
148
+ if (message.kind === "signal") {
149
+ await engine.signal(message.token, message.payload);
150
+ return;
151
+ }
152
+ } catch (error) {
153
+ if (error instanceof import_nestjs_durable_core.FatalError) {
154
+ throw new import_outbox.NonRetryableMessageError(error.message, {
155
+ cause: error
156
+ });
157
+ }
158
+ throw error;
159
+ }
160
+ throw new import_outbox.NonRetryableMessageError(`unknown durable outbox message kind: ${message.kind}`);
161
+ }
162
+ __name(applyDurableOutboxMessage, "applyDurableOutboxMessage");
163
+ var DurableOutboxHandler = class {
164
+ static {
165
+ __name(this, "DurableOutboxHandler");
166
+ }
167
+ engine;
168
+ constructor(engine) {
169
+ this.engine = engine;
170
+ }
171
+ handle(payload, _ctx) {
172
+ return applyDurableOutboxMessage(this.engine, payload);
173
+ }
174
+ };
175
+ DurableOutboxHandler = _ts_decorate([
176
+ (0, import_common.Injectable)(),
177
+ _ts_metadata("design:type", Function),
178
+ _ts_metadata("design:paramtypes", [
179
+ typeof import_nestjs_durable_core.WorkflowEngine === "undefined" ? Object : import_nestjs_durable_core.WorkflowEngine
180
+ ])
181
+ ], DurableOutboxHandler);
182
+ function handlerFor(options) {
183
+ const derived = class extends DurableOutboxHandler {
184
+ static {
185
+ __name(this, "derived");
186
+ }
187
+ };
188
+ Object.defineProperty(derived, "name", {
189
+ value: DurableOutboxHandler.name
190
+ });
191
+ const handle = /* @__PURE__ */ __name(function(payload, ctx) {
192
+ return DurableOutboxHandler.prototype.handle.call(this, payload, ctx);
193
+ }, "handle");
194
+ const descriptor = {
195
+ value: handle,
196
+ writable: true,
197
+ configurable: true
198
+ };
199
+ (0, import_outbox.OnOutboxMessage)(options.topic, {
200
+ consumer: options.consumer
201
+ })(derived.prototype, "handle", descriptor);
202
+ Object.defineProperty(derived.prototype, "handle", descriptor);
203
+ return derived;
204
+ }
205
+ __name(handlerFor, "handlerFor");
206
+ var DurableOutboxModule = class _DurableOutboxModule {
207
+ static {
208
+ __name(this, "DurableOutboxModule");
209
+ }
210
+ static forRoot(options = {}) {
211
+ const resolved = {
212
+ topic: options.topic ?? DURABLE_OUTBOX_TOPIC,
213
+ consumer: options.consumer ?? DURABLE_OUTBOX_CONSUMER
214
+ };
215
+ return {
216
+ module: _DurableOutboxModule,
217
+ providers: [
218
+ {
219
+ provide: OPTIONS,
220
+ useValue: resolved
221
+ },
222
+ DurableOutbox,
223
+ handlerFor(resolved)
224
+ ],
225
+ exports: [
226
+ DurableOutbox
227
+ ]
228
+ };
229
+ }
230
+ };
231
+ DurableOutboxModule = _ts_decorate([
232
+ (0, import_common.Module)({})
233
+ ], DurableOutboxModule);
234
+ // Annotate the CommonJS export names for ESM import in node:
235
+ 0 && (module.exports = {
236
+ DURABLE_OUTBOX_CONSUMER,
237
+ DURABLE_OUTBOX_TOPIC,
238
+ DurableOutbox,
239
+ DurableOutboxHandler,
240
+ DurableOutboxModule,
241
+ applyDurableOutboxMessage
242
+ });
243
+ //# sourceMappingURL=outbox.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/outbox/index.ts","../src/outbox/durable-outbox.ts"],"sourcesContent":["export {\n applyDurableOutboxMessage,\n DURABLE_OUTBOX_CONSUMER,\n DURABLE_OUTBOX_TOPIC,\n DurableOutbox,\n DurableOutboxHandler,\n DurableOutboxModule,\n type DurableOutboxModuleOptions,\n type DurableOutboxPayload,\n type DurableOutboxSignalOptions,\n type DurableOutboxStartOptions,\n} from './durable-outbox';\n","import { randomUUID } from 'node:crypto';\nimport {\n FatalError,\n type StartOptions,\n type WorkflowClass,\n WorkflowEngine,\n type WorkflowInputOf,\n type WorkflowRef,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport { type DynamicModule, Inject, Injectable, Module } from '@nestjs/common';\nimport {\n NonRetryableMessageError,\n OnOutboxMessage,\n Outbox,\n type OutboxHandlerContext,\n} from '@nestjs/outbox';\n\n/** Default outbox topic the durable messages are written to. */\nexport const DURABLE_OUTBOX_TOPIC = 'nestjs-durable';\n/** Default inbox consumer name of the handler that starts/signals runs. */\nexport const DURABLE_OUTBOX_CONSUMER = 'nestjs-durable';\n\n/** Options for {@link DurableOutboxModule.forRoot}. */\nexport interface DurableOutboxModuleOptions {\n /** The outbox topic durable's messages use. Default {@link DURABLE_OUTBOX_TOPIC}. */\n topic?: string;\n /**\n * The `@OnOutboxMessage` consumer name its inbox entries are recorded under. Keep it stable: a new\n * name makes every past message look new. Default {@link DURABLE_OUTBOX_CONSUMER}.\n */\n consumer?: string;\n}\n\n/** `StartOptions` as they travel in an outbox message: JSON-safe (`startAt` as epoch ms). */\ntype WireStartOptions = Omit<StartOptions, 'startAt'> & { startAt?: number };\n\n/** The payload of a durable outbox message. Versioned so a later shape can coexist. */\nexport type DurableOutboxPayload =\n | {\n v: 1;\n kind: 'start';\n workflow: string;\n input: unknown;\n runId: string;\n opts?: WireStartOptions;\n }\n | { v: 1; kind: 'signal'; token: string; payload: unknown };\n\n/** {@link DurableOutbox.start} options: `StartOptions` plus the run id. */\nexport interface DurableOutboxStartOptions extends StartOptions {\n /**\n * The run's id. Optional: when omitted, a random id is chosen NOW and written into the message,\n * so every redelivery starts the same run (the engine's start is idempotent by run id).\n */\n runId?: string;\n /** Outbox ordering key (messages sharing it publish in order). */\n key?: string;\n}\n\n/** {@link DurableOutbox.signal} options. */\nexport interface DurableOutboxSignalOptions {\n /** Outbox ordering key; defaults to the token, so signals to one token arrive in order. */\n key?: string | null;\n /** The outbox message id (dedupe key of the inbox). Default: the fresh UUIDv7 `Outbox.add` assigns. */\n id?: string;\n}\n\nconst OPTIONS = Symbol('DURABLE_OUTBOX_OPTIONS');\n\ninterface ResolvedOptions {\n topic: string;\n consumer: string;\n}\n\n/**\n * Starts and signals durable runs INSIDE the application's database transaction, through\n * `@nestjs/outbox`: the message commits or rolls back with your business writes, and the relay\n * delivers it to the engine after commit.\n *\n * ```ts\n * await db.transaction(async (tx) => {\n * await tx.insert(orders).values(order);\n * await durableOutbox.start(tx, CheckoutWorkflow, { orderId: order.id }, { runId: `checkout:${order.id}` });\n * });\n * ```\n */\n@Injectable()\nexport class DurableOutbox<Tx = unknown> {\n constructor(\n private readonly outbox: Outbox<Tx>,\n @Inject(OPTIONS) private readonly options: ResolvedOptions,\n ) {}\n\n /**\n * Write a \"start this run\" message through `tx`. Resolves the run id (yours, or the one chosen\n * here). A workflow class is written by its registered NAME, so the message stays serializable\n * and is delivered to whichever instance runs the relay.\n */\n start<C extends WorkflowClass>(\n tx: Tx,\n workflow: C,\n input: WorkflowInputOf<C>,\n opts?: DurableOutboxStartOptions,\n ): Promise<{ runId: string }>;\n start(\n tx: Tx,\n workflow: string,\n input: unknown,\n opts?: DurableOutboxStartOptions,\n ): Promise<{ runId: string }>;\n async start(\n tx: Tx,\n workflow: WorkflowRef,\n input: unknown,\n opts: DurableOutboxStartOptions = {},\n ): Promise<{ runId: string }> {\n const { runId = randomUUID(), key, startAt, ...rest } = opts;\n const wireOpts: WireStartOptions = {\n ...rest,\n ...(startAt !== undefined\n ? { startAt: startAt instanceof Date ? startAt.getTime() : startAt }\n : {}),\n };\n const payload: DurableOutboxPayload = {\n v: 1,\n kind: 'start',\n workflow: workflowName(workflow),\n input,\n runId,\n ...(Object.keys(wireOpts).length > 0 ? { opts: wireOpts } : {}),\n };\n await this.outbox.add(tx, { topic: this.options.topic, payload, key: key ?? null });\n return { runId };\n }\n\n /**\n * Write a \"deliver this signal\" message through `tx`: after commit, the payload is delivered to\n * the run waiting on `token` (`ctx.waitForSignal(token)`), or buffered for it like\n * `WorkflowService.signal`.\n */\n async signal(\n tx: Tx,\n token: string,\n payload: unknown,\n opts: DurableOutboxSignalOptions = {},\n ): Promise<void> {\n const message: DurableOutboxPayload = { v: 1, kind: 'signal', token, payload };\n await this.outbox.add(tx, {\n topic: this.options.topic,\n payload: message,\n key: opts.key === undefined ? token : opts.key,\n ...(opts.id !== undefined ? { id: opts.id } : {}),\n });\n }\n\n /** Poll the relay now (after your transaction commits) instead of waiting for its interval. */\n notify(): void {\n this.outbox.notify();\n }\n}\n\n/**\n * Applies a durable outbox message to the engine. Exported for tests and for a remote consumer that\n * receives the envelope over a broker; the module's `@OnOutboxMessage` handler calls it.\n *\n * A start is idempotent by run id (an existing run is a no-op success), so a redelivery never starts\n * a second run. An input the workflow rejects (a `FatalError` such as `SchemaValidationError`), an\n * unknown payload shape, dead-letters at once instead of being retried.\n */\nexport async function applyDurableOutboxMessage(\n engine: WorkflowEngine,\n message: DurableOutboxPayload,\n): Promise<void> {\n if (!message || message.v !== 1) {\n throw new NonRetryableMessageError(\n `unsupported durable outbox payload: ${JSON.stringify(message)?.slice(0, 200)}`,\n );\n }\n try {\n if (message.kind === 'start') {\n await engine.start(\n message.workflow,\n message.input,\n message.runId,\n message.opts as StartOptions,\n );\n return;\n }\n if (message.kind === 'signal') {\n await engine.signal(message.token, message.payload);\n return;\n }\n } catch (error) {\n if (error instanceof FatalError) {\n throw new NonRetryableMessageError(error.message, { cause: error });\n }\n throw error;\n }\n throw new NonRetryableMessageError(\n `unknown durable outbox message kind: ${(message as { kind?: unknown }).kind}`,\n );\n}\n\n/** The consumer side; one fresh subclass per registration carries that registration's topic. */\n@Injectable()\nexport class DurableOutboxHandler {\n constructor(private readonly engine: WorkflowEngine) {}\n\n handle(payload: DurableOutboxPayload, _ctx?: OutboxHandlerContext): Promise<void> {\n return applyDurableOutboxMessage(this.engine, payload);\n }\n}\n\nfunction handlerFor(options: ResolvedOptions): typeof DurableOutboxHandler {\n const derived = class extends DurableOutboxHandler {};\n Object.defineProperty(derived, 'name', { value: DurableOutboxHandler.name });\n // Re-declare the method on the subclass so the `@OnOutboxMessage` metadata (stored on the function\n // object) belongs to THIS registration only, never to the shared base method.\n const handle = function (\n this: DurableOutboxHandler,\n payload: DurableOutboxPayload,\n ctx?: OutboxHandlerContext,\n ) {\n return DurableOutboxHandler.prototype.handle.call(this, payload, ctx);\n };\n const descriptor: PropertyDescriptor = { value: handle, writable: true, configurable: true };\n OnOutboxMessage(options.topic, { consumer: options.consumer })(\n derived.prototype,\n 'handle',\n descriptor,\n );\n Object.defineProperty(derived.prototype, 'handle', descriptor);\n return derived;\n}\n\n/**\n * Wires durable runs to `@nestjs/outbox`. Import it next to `OutboxModule.forRoot()` (which owns the\n * store, relay, retries and dead letters) and `DurableModule.forRoot()`.\n */\n@Module({})\nexport class DurableOutboxModule {\n static forRoot(options: DurableOutboxModuleOptions = {}): DynamicModule {\n const resolved: ResolvedOptions = {\n topic: options.topic ?? DURABLE_OUTBOX_TOPIC,\n consumer: options.consumer ?? DURABLE_OUTBOX_CONSUMER,\n };\n return {\n module: DurableOutboxModule,\n providers: [{ provide: OPTIONS, useValue: resolved }, DurableOutbox, handlerFor(resolved)],\n exports: [DurableOutbox],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;ACAA,yBAA2B;AAC3B,iCAQO;AACP,oBAA+D;AAC/D,oBAKO;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAMA,uBAAuB;AAE7B,IAAMC,0BAA0B;AA+CvC,IAAMC,UAAUC,OAAO,wBAAA;AAoBhB,IAAMC,gBAAN,MAAMA;SAAAA;;;;;EACX,YACmBC,QACiBC,SAClC;SAFiBD,SAAAA;SACiBC,UAAAA;EACjC;EAmBH,MAAMC,MACJC,IACAC,UACAC,OACAC,OAAkC,CAAC,GACP;AAC5B,UAAM,EAAEC,YAAQC,+BAAAA,GAAcC,KAAKC,SAAS,GAAGC,KAAAA,IAASL;AACxD,UAAMM,WAA6B;MACjC,GAAGD;MACH,GAAID,YAAYG,SACZ;QAAEH,SAASA,mBAAmBI,OAA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S;QAAC/D;;IACZ;EACF;AACF;;;;","names":["DURABLE_OUTBOX_TOPIC","DURABLE_OUTBOX_CONSUMER","OPTIONS","Symbol","DurableOutbox","outbox","options","start","tx","workflow","input","opts","runId","randomUUID","key","startAt","rest","wireOpts","undefined","Date","getTime","payload","v","kind","workflowName","Object","keys","length","add","topic","signal","token","message","id","notify","applyDurableOutboxMessage","engine","NonRetryableMessageError","JSON","stringify","slice","error","FatalError","cause","DurableOutboxHandler","handle","_ctx","handlerFor","derived","defineProperty","value","name","ctx","prototype","call","descriptor","writable","configurable","OnOutboxMessage","consumer","DurableOutboxModule","forRoot","resolved","module","providers","provide","useValue","exports"]}
@@ -0,0 +1,117 @@
1
+ import { WorkflowClass, WorkflowInputOf, StartOptions, WorkflowEngine } from '@dudousxd/nestjs-durable-core';
2
+ import { DynamicModule } from '@nestjs/common';
3
+ import { Outbox, OutboxHandlerContext } from '@nestjs/outbox';
4
+
5
+ /** Default outbox topic the durable messages are written to. */
6
+ declare const DURABLE_OUTBOX_TOPIC = "nestjs-durable";
7
+ /** Default inbox consumer name of the handler that starts/signals runs. */
8
+ declare const DURABLE_OUTBOX_CONSUMER = "nestjs-durable";
9
+ /** Options for {@link DurableOutboxModule.forRoot}. */
10
+ interface DurableOutboxModuleOptions {
11
+ /** The outbox topic durable's messages use. Default {@link DURABLE_OUTBOX_TOPIC}. */
12
+ topic?: string;
13
+ /**
14
+ * The `@OnOutboxMessage` consumer name its inbox entries are recorded under. Keep it stable: a new
15
+ * name makes every past message look new. Default {@link DURABLE_OUTBOX_CONSUMER}.
16
+ */
17
+ consumer?: string;
18
+ }
19
+ /** `StartOptions` as they travel in an outbox message: JSON-safe (`startAt` as epoch ms). */
20
+ type WireStartOptions = Omit<StartOptions, 'startAt'> & {
21
+ startAt?: number;
22
+ };
23
+ /** The payload of a durable outbox message. Versioned so a later shape can coexist. */
24
+ type DurableOutboxPayload = {
25
+ v: 1;
26
+ kind: 'start';
27
+ workflow: string;
28
+ input: unknown;
29
+ runId: string;
30
+ opts?: WireStartOptions;
31
+ } | {
32
+ v: 1;
33
+ kind: 'signal';
34
+ token: string;
35
+ payload: unknown;
36
+ };
37
+ /** {@link DurableOutbox.start} options: `StartOptions` plus the run id. */
38
+ interface DurableOutboxStartOptions extends StartOptions {
39
+ /**
40
+ * The run's id. Optional: when omitted, a random id is chosen NOW and written into the message,
41
+ * so every redelivery starts the same run (the engine's start is idempotent by run id).
42
+ */
43
+ runId?: string;
44
+ /** Outbox ordering key (messages sharing it publish in order). */
45
+ key?: string;
46
+ }
47
+ /** {@link DurableOutbox.signal} options. */
48
+ interface DurableOutboxSignalOptions {
49
+ /** Outbox ordering key; defaults to the token, so signals to one token arrive in order. */
50
+ key?: string | null;
51
+ /** The outbox message id (dedupe key of the inbox). Default: the fresh UUIDv7 `Outbox.add` assigns. */
52
+ id?: string;
53
+ }
54
+ interface ResolvedOptions {
55
+ topic: string;
56
+ consumer: string;
57
+ }
58
+ /**
59
+ * Starts and signals durable runs INSIDE the application's database transaction, through
60
+ * `@nestjs/outbox`: the message commits or rolls back with your business writes, and the relay
61
+ * delivers it to the engine after commit.
62
+ *
63
+ * ```ts
64
+ * await db.transaction(async (tx) => {
65
+ * await tx.insert(orders).values(order);
66
+ * await durableOutbox.start(tx, CheckoutWorkflow, { orderId: order.id }, { runId: `checkout:${order.id}` });
67
+ * });
68
+ * ```
69
+ */
70
+ declare class DurableOutbox<Tx = unknown> {
71
+ private readonly outbox;
72
+ private readonly options;
73
+ constructor(outbox: Outbox<Tx>, options: ResolvedOptions);
74
+ /**
75
+ * Write a "start this run" message through `tx`. Resolves the run id (yours, or the one chosen
76
+ * here). A workflow class is written by its registered NAME, so the message stays serializable
77
+ * and is delivered to whichever instance runs the relay.
78
+ */
79
+ start<C extends WorkflowClass>(tx: Tx, workflow: C, input: WorkflowInputOf<C>, opts?: DurableOutboxStartOptions): Promise<{
80
+ runId: string;
81
+ }>;
82
+ start(tx: Tx, workflow: string, input: unknown, opts?: DurableOutboxStartOptions): Promise<{
83
+ runId: string;
84
+ }>;
85
+ /**
86
+ * Write a "deliver this signal" message through `tx`: after commit, the payload is delivered to
87
+ * the run waiting on `token` (`ctx.waitForSignal(token)`), or buffered for it like
88
+ * `WorkflowService.signal`.
89
+ */
90
+ signal(tx: Tx, token: string, payload: unknown, opts?: DurableOutboxSignalOptions): Promise<void>;
91
+ /** Poll the relay now (after your transaction commits) instead of waiting for its interval. */
92
+ notify(): void;
93
+ }
94
+ /**
95
+ * Applies a durable outbox message to the engine. Exported for tests and for a remote consumer that
96
+ * receives the envelope over a broker; the module's `@OnOutboxMessage` handler calls it.
97
+ *
98
+ * A start is idempotent by run id (an existing run is a no-op success), so a redelivery never starts
99
+ * a second run. An input the workflow rejects (a `FatalError` such as `SchemaValidationError`), an
100
+ * unknown payload shape, dead-letters at once instead of being retried.
101
+ */
102
+ declare function applyDurableOutboxMessage(engine: WorkflowEngine, message: DurableOutboxPayload): Promise<void>;
103
+ /** The consumer side; one fresh subclass per registration carries that registration's topic. */
104
+ declare class DurableOutboxHandler {
105
+ private readonly engine;
106
+ constructor(engine: WorkflowEngine);
107
+ handle(payload: DurableOutboxPayload, _ctx?: OutboxHandlerContext): Promise<void>;
108
+ }
109
+ /**
110
+ * Wires durable runs to `@nestjs/outbox`. Import it next to `OutboxModule.forRoot()` (which owns the
111
+ * store, relay, retries and dead letters) and `DurableModule.forRoot()`.
112
+ */
113
+ declare class DurableOutboxModule {
114
+ static forRoot(options?: DurableOutboxModuleOptions): DynamicModule;
115
+ }
116
+
117
+ export { DURABLE_OUTBOX_CONSUMER, DURABLE_OUTBOX_TOPIC, DurableOutbox, DurableOutboxHandler, DurableOutboxModule, type DurableOutboxModuleOptions, type DurableOutboxPayload, type DurableOutboxSignalOptions, type DurableOutboxStartOptions, applyDurableOutboxMessage };
@@ -0,0 +1,117 @@
1
+ import { WorkflowClass, WorkflowInputOf, StartOptions, WorkflowEngine } from '@dudousxd/nestjs-durable-core';
2
+ import { DynamicModule } from '@nestjs/common';
3
+ import { Outbox, OutboxHandlerContext } from '@nestjs/outbox';
4
+
5
+ /** Default outbox topic the durable messages are written to. */
6
+ declare const DURABLE_OUTBOX_TOPIC = "nestjs-durable";
7
+ /** Default inbox consumer name of the handler that starts/signals runs. */
8
+ declare const DURABLE_OUTBOX_CONSUMER = "nestjs-durable";
9
+ /** Options for {@link DurableOutboxModule.forRoot}. */
10
+ interface DurableOutboxModuleOptions {
11
+ /** The outbox topic durable's messages use. Default {@link DURABLE_OUTBOX_TOPIC}. */
12
+ topic?: string;
13
+ /**
14
+ * The `@OnOutboxMessage` consumer name its inbox entries are recorded under. Keep it stable: a new
15
+ * name makes every past message look new. Default {@link DURABLE_OUTBOX_CONSUMER}.
16
+ */
17
+ consumer?: string;
18
+ }
19
+ /** `StartOptions` as they travel in an outbox message: JSON-safe (`startAt` as epoch ms). */
20
+ type WireStartOptions = Omit<StartOptions, 'startAt'> & {
21
+ startAt?: number;
22
+ };
23
+ /** The payload of a durable outbox message. Versioned so a later shape can coexist. */
24
+ type DurableOutboxPayload = {
25
+ v: 1;
26
+ kind: 'start';
27
+ workflow: string;
28
+ input: unknown;
29
+ runId: string;
30
+ opts?: WireStartOptions;
31
+ } | {
32
+ v: 1;
33
+ kind: 'signal';
34
+ token: string;
35
+ payload: unknown;
36
+ };
37
+ /** {@link DurableOutbox.start} options: `StartOptions` plus the run id. */
38
+ interface DurableOutboxStartOptions extends StartOptions {
39
+ /**
40
+ * The run's id. Optional: when omitted, a random id is chosen NOW and written into the message,
41
+ * so every redelivery starts the same run (the engine's start is idempotent by run id).
42
+ */
43
+ runId?: string;
44
+ /** Outbox ordering key (messages sharing it publish in order). */
45
+ key?: string;
46
+ }
47
+ /** {@link DurableOutbox.signal} options. */
48
+ interface DurableOutboxSignalOptions {
49
+ /** Outbox ordering key; defaults to the token, so signals to one token arrive in order. */
50
+ key?: string | null;
51
+ /** The outbox message id (dedupe key of the inbox). Default: the fresh UUIDv7 `Outbox.add` assigns. */
52
+ id?: string;
53
+ }
54
+ interface ResolvedOptions {
55
+ topic: string;
56
+ consumer: string;
57
+ }
58
+ /**
59
+ * Starts and signals durable runs INSIDE the application's database transaction, through
60
+ * `@nestjs/outbox`: the message commits or rolls back with your business writes, and the relay
61
+ * delivers it to the engine after commit.
62
+ *
63
+ * ```ts
64
+ * await db.transaction(async (tx) => {
65
+ * await tx.insert(orders).values(order);
66
+ * await durableOutbox.start(tx, CheckoutWorkflow, { orderId: order.id }, { runId: `checkout:${order.id}` });
67
+ * });
68
+ * ```
69
+ */
70
+ declare class DurableOutbox<Tx = unknown> {
71
+ private readonly outbox;
72
+ private readonly options;
73
+ constructor(outbox: Outbox<Tx>, options: ResolvedOptions);
74
+ /**
75
+ * Write a "start this run" message through `tx`. Resolves the run id (yours, or the one chosen
76
+ * here). A workflow class is written by its registered NAME, so the message stays serializable
77
+ * and is delivered to whichever instance runs the relay.
78
+ */
79
+ start<C extends WorkflowClass>(tx: Tx, workflow: C, input: WorkflowInputOf<C>, opts?: DurableOutboxStartOptions): Promise<{
80
+ runId: string;
81
+ }>;
82
+ start(tx: Tx, workflow: string, input: unknown, opts?: DurableOutboxStartOptions): Promise<{
83
+ runId: string;
84
+ }>;
85
+ /**
86
+ * Write a "deliver this signal" message through `tx`: after commit, the payload is delivered to
87
+ * the run waiting on `token` (`ctx.waitForSignal(token)`), or buffered for it like
88
+ * `WorkflowService.signal`.
89
+ */
90
+ signal(tx: Tx, token: string, payload: unknown, opts?: DurableOutboxSignalOptions): Promise<void>;
91
+ /** Poll the relay now (after your transaction commits) instead of waiting for its interval. */
92
+ notify(): void;
93
+ }
94
+ /**
95
+ * Applies a durable outbox message to the engine. Exported for tests and for a remote consumer that
96
+ * receives the envelope over a broker; the module's `@OnOutboxMessage` handler calls it.
97
+ *
98
+ * A start is idempotent by run id (an existing run is a no-op success), so a redelivery never starts
99
+ * a second run. An input the workflow rejects (a `FatalError` such as `SchemaValidationError`), an
100
+ * unknown payload shape, dead-letters at once instead of being retried.
101
+ */
102
+ declare function applyDurableOutboxMessage(engine: WorkflowEngine, message: DurableOutboxPayload): Promise<void>;
103
+ /** The consumer side; one fresh subclass per registration carries that registration's topic. */
104
+ declare class DurableOutboxHandler {
105
+ private readonly engine;
106
+ constructor(engine: WorkflowEngine);
107
+ handle(payload: DurableOutboxPayload, _ctx?: OutboxHandlerContext): Promise<void>;
108
+ }
109
+ /**
110
+ * Wires durable runs to `@nestjs/outbox`. Import it next to `OutboxModule.forRoot()` (which owns the
111
+ * store, relay, retries and dead letters) and `DurableModule.forRoot()`.
112
+ */
113
+ declare class DurableOutboxModule {
114
+ static forRoot(options?: DurableOutboxModuleOptions): DynamicModule;
115
+ }
116
+
117
+ export { DURABLE_OUTBOX_CONSUMER, DURABLE_OUTBOX_TOPIC, DurableOutbox, DurableOutboxHandler, DurableOutboxModule, type DurableOutboxModuleOptions, type DurableOutboxPayload, type DurableOutboxSignalOptions, type DurableOutboxStartOptions, applyDurableOutboxMessage };