@dudousxd/nestjs-durable 0.61.0 → 0.63.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.
@@ -378,6 +378,27 @@ var StoreRunGateway = class {
378
378
  republishLifecycle(target) {
379
379
  return this.engine.republishLifecycle(target);
380
380
  }
381
+ /** The persisted schedules (`[]` when the store does not persist them). */
382
+ async listSchedules(query) {
383
+ return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];
384
+ }
385
+ async getSchedule(id) {
386
+ if (!this.engine.schedules?.supported) return null;
387
+ return await this.engine.schedules.get(id) ?? null;
388
+ }
389
+ scheduleAction(id, action) {
390
+ if (action === "pause") return this.engine.schedules.pause(id);
391
+ if (action === "resume") return this.engine.schedules.resume(id);
392
+ if (action === "trigger") return this.engine.schedules.trigger(id);
393
+ return Promise.reject(new Error(`unknown schedule action ${String(action)}`));
394
+ }
395
+ signal(token, payload) {
396
+ return this.engine.signal(token, payload);
397
+ }
398
+ async signalWaiter(token) {
399
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
400
+ return waiter?.runId ?? null;
401
+ }
381
402
  /**
382
403
  * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
383
404
  * run that does not exist yet are held until its row shows whose it is.
@@ -1 +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 RunGateway} 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 /**\n * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s\n * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).\n */\n private scoped<Q extends RunQuery | RunFacetQuery>(query: Q): Q {\n return typeof this.engine?.scopeRunQuery === 'function'\n ? (this.engine.scopeRunQuery(query as RunQuery) as Q)\n : query;\n }\n\n /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */\n private async visibleRun(runId: string): Promise<WorkflowRun | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const { tenantIds } = this.scoped({} as RunQuery);\n return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;\n }\n\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const run = await this.visibleRun(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.visibleRun(runId);\n }\n\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (!(await this.visibleRun(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(this.scoped(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 = this.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, this.scoped(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(this.scoped({ 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 /**\n * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a\n * run that does not exist yet are held until its row shows whose it is.\n */\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n // Read the caller's tenant now: the events arrive outside its async context.\n const { tenantIds } = this.scoped({} as RunQuery);\n if (!tenantIds) {\n return this.engine.subscribe((event) => {\n if (event.runId === runId) onEvent(event);\n });\n }\n let visible: boolean | undefined; // undefined until the run's row has been read\n let held: EngineEvent[] = [];\n let checking = false;\n const check = (): void => {\n if (checking || visible !== undefined) return;\n checking = true;\n void this.store\n .getRun(runId)\n .then(\n (run) => {\n if (run) visible = tenantIds.includes(run.tenantId ?? null);\n },\n () => undefined,\n )\n .finally(() => {\n checking = false;\n if (visible === undefined) return;\n const pending = held;\n held = [];\n if (visible) for (const event of pending) onEvent(event);\n });\n };\n const off = this.engine.subscribe((event) => {\n if (event.runId !== runId || visible === false) return;\n if (visible) return onEvent(event);\n held.push(event);\n check();\n });\n check();\n return () => {\n held = [];\n off();\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,IAAAA,8BAYO;AACP,8CAAmD;AACnD,IAAAC,iBAA+D;AAC/D,uBAAoE;;;ACfpE,iCAoDO;AACP,oBAAmC;;;;;;;;;;;;;;;;;;;;;;;;;;;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;E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","import_common","detailExtras","links","lifecycleSubscribers","lifecycleDeliveries","waitsFor","awaitedBy","triggeredBy","undefined","withoutRegistry","query","workflow","LIFECYCLE_REGISTRY_WORKFLOW","workflows","includes","excludeWorkflows","StoreRunGateway","store","engine","topology","role","scoped","scopeRunQuery","visibleRun","runId","run","getRun","tenantIds","tenantId","getRunDetail","options","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","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","visible","held","checking","check","then","finally","pending","off","push","import_nestjs_durable_core","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"]}
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 ScheduleAction,\n type ScheduleDescription,\n type ScheduleListQuery,\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 RunGateway} 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 /**\n * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s\n * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).\n */\n private scoped<Q extends RunQuery | RunFacetQuery>(query: Q): Q {\n return typeof this.engine?.scopeRunQuery === 'function'\n ? (this.engine.scopeRunQuery(query as RunQuery) as Q)\n : query;\n }\n\n /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */\n private async visibleRun(runId: string): Promise<WorkflowRun | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const { tenantIds } = this.scoped({} as RunQuery);\n return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;\n }\n\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const run = await this.visibleRun(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.visibleRun(runId);\n }\n\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (!(await this.visibleRun(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(this.scoped(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 = this.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, this.scoped(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(this.scoped({ 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 /** The persisted schedules (`[]` when the store does not persist them). */\n async listSchedules(query: ScheduleListQuery): Promise<ScheduleDescription[]> {\n return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];\n }\n\n async getSchedule(id: string): Promise<ScheduleDescription | null> {\n if (!this.engine.schedules?.supported) return null;\n return (await this.engine.schedules.get(id)) ?? null;\n }\n\n scheduleAction(id: string, action: ScheduleAction): Promise<ScheduleDescription | RunResult> {\n if (action === 'pause') return this.engine.schedules.pause(id);\n if (action === 'resume') return this.engine.schedules.resume(id);\n if (action === 'trigger') return this.engine.schedules.trigger(id);\n return Promise.reject(new Error(`unknown schedule action ${String(action)}`));\n }\n\n signal(token: string, payload: unknown): Promise<RunResult | null> {\n return this.engine.signal(token, payload);\n }\n\n async signalWaiter(token: string): Promise<string | null> {\n const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);\n return waiter?.runId ?? null;\n }\n\n /**\n * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a\n * run that does not exist yet are held until its row shows whose it is.\n */\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n // Read the caller's tenant now: the events arrive outside its async context.\n const { tenantIds } = this.scoped({} as RunQuery);\n if (!tenantIds) {\n return this.engine.subscribe((event) => {\n if (event.runId === runId) onEvent(event);\n });\n }\n let visible: boolean | undefined; // undefined until the run's row has been read\n let held: EngineEvent[] = [];\n let checking = false;\n const check = (): void => {\n if (checking || visible !== undefined) return;\n checking = true;\n void this.store\n .getRun(runId)\n .then(\n (run) => {\n if (run) visible = tenantIds.includes(run.tenantId ?? null);\n },\n () => undefined,\n )\n .finally(() => {\n checking = false;\n if (visible === undefined) return;\n const pending = held;\n held = [];\n if (visible) for (const event of pending) onEvent(event);\n });\n };\n const off = this.engine.subscribe((event) => {\n if (event.runId !== runId || visible === false) return;\n if (visible) return onEvent(event);\n held.push(event);\n check();\n });\n check();\n return () => {\n held = [];\n off();\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,IAAAA,8BAYO;AACP,8CAAmD;AACnD,IAAAC,iBAA+D;AAC/D,uBAAoE;;;ACfpE,iCAuDO;AACP,oBAAmC;;;;;;;;;;;;;;;;;;;;;;;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I,KAAKuB,cAAcd,SAAY;QAAEe,SAASxB,KAAKuB;MAAU,IAAI,CAAC,CAAA,EAC5EE,MAAM,CAACT,UAAAA;AAEN,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,4DAAoBJ,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":["import_nestjs_durable_core","import_common","detailExtras","links","lifecycleSubscribers","lifecycleDeliveries","waitsFor","awaitedBy","triggeredBy","undefined","withoutRegistry","query","workflow","LIFECYCLE_REGISTRY_WORKFLOW","workflows","includes","excludeWorkflows","StoreRunGateway","store","engine","topology","role","scoped","scopeRunQuery","visibleRun","runId","run","getRun","tenantIds","tenantId","getRunDetail","options","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","mergeRunFacetRows","r","origin","count","runValueFacets","axis","waitingFor","runIds","idSet","suspended","waiters","statuses","result","has","workerHealth","cancel","retry","requeue","continue","retryWithInput","input","redispatchPending","republishLifecycle","listSchedules","schedules","supported","list","getSchedule","scheduleAction","action","pause","resume","trigger","reject","Error","String","signal","token","payload","signalWaiter","waiter","find","subscribe","onEvent","event","visible","held","checking","check","then","finally","pending","off","push","import_nestjs_durable_core","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"]}
@@ -354,6 +354,27 @@ var StoreRunGateway = class {
354
354
  republishLifecycle(target) {
355
355
  return this.engine.republishLifecycle(target);
356
356
  }
357
+ /** The persisted schedules (`[]` when the store does not persist them). */
358
+ async listSchedules(query) {
359
+ return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];
360
+ }
361
+ async getSchedule(id) {
362
+ if (!this.engine.schedules?.supported) return null;
363
+ return await this.engine.schedules.get(id) ?? null;
364
+ }
365
+ scheduleAction(id, action) {
366
+ if (action === "pause") return this.engine.schedules.pause(id);
367
+ if (action === "resume") return this.engine.schedules.resume(id);
368
+ if (action === "trigger") return this.engine.schedules.trigger(id);
369
+ return Promise.reject(new Error(`unknown schedule action ${String(action)}`));
370
+ }
371
+ signal(token, payload) {
372
+ return this.engine.signal(token, payload);
373
+ }
374
+ async signalWaiter(token) {
375
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
376
+ return waiter?.runId ?? null;
377
+ }
357
378
  /**
358
379
  * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
359
380
  * run that does not exist yet are held until its row shows whose it is.
@@ -1 +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 RunGateway} 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 /**\n * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s\n * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).\n */\n private scoped<Q extends RunQuery | RunFacetQuery>(query: Q): Q {\n return typeof this.engine?.scopeRunQuery === 'function'\n ? (this.engine.scopeRunQuery(query as RunQuery) as Q)\n : query;\n }\n\n /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */\n private async visibleRun(runId: string): Promise<WorkflowRun | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const { tenantIds } = this.scoped({} as RunQuery);\n return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;\n }\n\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const run = await this.visibleRun(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.visibleRun(runId);\n }\n\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (!(await this.visibleRun(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(this.scoped(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 = this.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, this.scoped(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(this.scoped({ 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 /**\n * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a\n * run that does not exist yet are held until its row shows whose it is.\n */\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n // Read the caller's tenant now: the events arrive outside its async context.\n const { tenantIds } = this.scoped({} as RunQuery);\n if (!tenantIds) {\n return this.engine.subscribe((event) => {\n if (event.runId === runId) onEvent(event);\n });\n }\n let visible: boolean | undefined; // undefined until the run's row has been read\n let held: EngineEvent[] = [];\n let checking = false;\n const check = (): void => {\n if (checking || visible !== undefined) return;\n checking = true;\n void this.store\n .getRun(runId)\n .then(\n (run) => {\n if (run) visible = tenantIds.includes(run.tenantId ?? null);\n },\n () => undefined,\n )\n .finally(() => {\n checking = false;\n if (visible === undefined) return;\n const pending = held;\n held = [];\n if (visible) for (const event of pending) onEvent(event);\n });\n };\n const off = this.engine.subscribe((event) => {\n if (event.runId !== runId || visible === false) return;\n if (visible) return onEvent(event);\n held.push(event);\n check();\n });\n check();\n return () => {\n held = [];\n off();\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,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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","scoped","scopeRunQuery","visibleRun","runId","run","getRun","tenantIds","tenantId","getRunDetail","options","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","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","visible","held","checking","check","then","finally","pending","off","push","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"]}
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 ScheduleAction,\n type ScheduleDescription,\n type ScheduleListQuery,\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 RunGateway} 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 /**\n * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s\n * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).\n */\n private scoped<Q extends RunQuery | RunFacetQuery>(query: Q): Q {\n return typeof this.engine?.scopeRunQuery === 'function'\n ? (this.engine.scopeRunQuery(query as RunQuery) as Q)\n : query;\n }\n\n /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */\n private async visibleRun(runId: string): Promise<WorkflowRun | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const { tenantIds } = this.scoped({} as RunQuery);\n return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;\n }\n\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const run = await this.visibleRun(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.visibleRun(runId);\n }\n\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (!(await this.visibleRun(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(this.scoped(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 = this.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, this.scoped(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(this.scoped({ 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 /** The persisted schedules (`[]` when the store does not persist them). */\n async listSchedules(query: ScheduleListQuery): Promise<ScheduleDescription[]> {\n return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];\n }\n\n async getSchedule(id: string): Promise<ScheduleDescription | null> {\n if (!this.engine.schedules?.supported) return null;\n return (await this.engine.schedules.get(id)) ?? null;\n }\n\n scheduleAction(id: string, action: ScheduleAction): Promise<ScheduleDescription | RunResult> {\n if (action === 'pause') return this.engine.schedules.pause(id);\n if (action === 'resume') return this.engine.schedules.resume(id);\n if (action === 'trigger') return this.engine.schedules.trigger(id);\n return Promise.reject(new Error(`unknown schedule action ${String(action)}`));\n }\n\n signal(token: string, payload: unknown): Promise<RunResult | null> {\n return this.engine.signal(token, payload);\n }\n\n async signalWaiter(token: string): Promise<string | null> {\n const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);\n return waiter?.runId ?? null;\n }\n\n /**\n * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a\n * run that does not exist yet are held until its row shows whose it is.\n */\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n // Read the caller's tenant now: the events arrive outside its async context.\n const { tenantIds } = this.scoped({} as RunQuery);\n if (!tenantIds) {\n return this.engine.subscribe((event) => {\n if (event.runId === runId) onEvent(event);\n });\n }\n let visible: boolean | undefined; // undefined until the run's row has been read\n let held: EngineEvent[] = [];\n let checking = false;\n const check = (): void => {\n if (checking || visible !== undefined) return;\n checking = true;\n void this.store\n .getRun(runId)\n .then(\n (run) => {\n if (run) visible = tenantIds.includes(run.tenantId ?? null);\n },\n () => undefined,\n )\n .finally(() => {\n checking = false;\n if (visible === undefined) return;\n const pending = held;\n held = [];\n if (visible) for (const event of pending) onEvent(event);\n });\n };\n const off = this.engine.subscribe((event) => {\n if (event.runId !== runId || visible === false) return;\n if (visible) return onEvent(event);\n held.push(event);\n check();\n });\n check();\n return () => {\n held = [];\n off();\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,qBAKAC,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,kBA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AOxB,OAAOI,KAAKuB,cAAcd,SAAY;QAAEe,SAASxB,KAAKuB;MAAU,IAAI,CAAC,CAAA,EAC5EE,MAAM,CAACT,UAAAA;AAEN,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","scoped","scopeRunQuery","visibleRun","runId","run","getRun","tenantIds","tenantId","getRunDetail","options","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","mergeRunFacetRows","r","origin","count","runValueFacets","axis","waitingFor","runIds","idSet","suspended","waiters","statuses","result","has","workerHealth","cancel","retry","requeue","continue","retryWithInput","input","redispatchPending","republishLifecycle","listSchedules","schedules","supported","list","getSchedule","scheduleAction","action","pause","resume","trigger","reject","Error","String","signal","token","payload","signalWaiter","waiter","find","subscribe","onEvent","event","visible","held","checking","check","then","finally","pending","off","push","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"]}