@open-mercato/shared 0.10.1-develop.8072.1.592356afda → 0.10.1-develop.8098.1.f4decc8a57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/lib/commands/command-bus.js +49 -2
- package/dist/lib/commands/command-bus.js.map +2 -2
- package/dist/lib/commands/types.js.map +2 -2
- package/dist/lib/logger/transport.pretty.js +5 -1
- package/dist/lib/logger/transport.pretty.js.map +2 -2
- package/dist/lib/sse/connectionBounds.js +39 -0
- package/dist/lib/sse/connectionBounds.js.map +7 -0
- package/dist/lib/version.js +1 -1
- package/dist/lib/version.js.map +1 -1
- package/package.json +2 -2
- package/src/lib/commands/__tests__/command-bus.redo-claim.test.ts +161 -0
- package/src/lib/commands/__tests__/command-bus.undo-toctou.test.ts +1 -0
- package/src/lib/commands/command-bus.ts +59 -1
- package/src/lib/commands/types.ts +5 -2
- package/src/lib/logger/__tests__/logger.test.ts +2 -0
- package/src/lib/logger/transport.pretty.ts +9 -1
- package/src/lib/sse/__tests__/connectionBounds.test.ts +76 -0
- package/src/lib/sse/connectionBounds.ts +47 -0
- package/src/modules/widgets/injection.ts +5 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -19,6 +19,7 @@ import { CommandInterceptorError } from "./errors.js";
|
|
|
19
19
|
import { isReadProjectionAlwaysConsistent } from "@open-mercato/shared/lib/data/consistency";
|
|
20
20
|
import { createLogger } from "../logger/index.js";
|
|
21
21
|
import { withAtomicFlush } from "./flush.js";
|
|
22
|
+
import { getTelemetryRuntime } from "../telemetry/runtime.js";
|
|
22
23
|
import {
|
|
23
24
|
getTransactionLifetime,
|
|
24
25
|
onTransactionLifetimeComplete,
|
|
@@ -403,6 +404,15 @@ class CommandBus {
|
|
|
403
404
|
coreResult = await executeCore(effectiveOptions);
|
|
404
405
|
}], { transaction: true, label: `${commandId}.redo` });
|
|
405
406
|
replaySourceFinalized = !ambientReplay.joinsAmbient;
|
|
407
|
+
} else if (replayLogEntry?.id) {
|
|
408
|
+
const redoClaimRelease = await this.claimRedoSource(effectiveOptions.ctx, commandId, replayLogEntry.id);
|
|
409
|
+
try {
|
|
410
|
+
coreResult = await executeCore(effectiveOptions);
|
|
411
|
+
} catch (err) {
|
|
412
|
+
await redoClaimRelease?.();
|
|
413
|
+
throw err;
|
|
414
|
+
}
|
|
415
|
+
replaySourceFinalized = redoClaimRelease !== null;
|
|
406
416
|
} else {
|
|
407
417
|
coreResult = await executeCore(effectiveOptions);
|
|
408
418
|
}
|
|
@@ -568,15 +578,24 @@ class CommandBus {
|
|
|
568
578
|
label: `${log.commandId}.undo`
|
|
569
579
|
});
|
|
570
580
|
} else {
|
|
581
|
+
let undoClaimed = false;
|
|
571
582
|
try {
|
|
572
583
|
await claimUndo();
|
|
584
|
+
undoClaimed = true;
|
|
573
585
|
const prepared = await runBeforeUndoInterceptors(ctx);
|
|
574
586
|
undoInterceptorMetadata = prepared.metadata;
|
|
575
587
|
userFeatures = prepared.userFeatures;
|
|
576
588
|
await finishUndo(ctx);
|
|
577
589
|
} catch (err) {
|
|
578
|
-
|
|
579
|
-
|
|
590
|
+
if (undoClaimed) {
|
|
591
|
+
await service.releaseUndoClaim(log.id).catch((releaseErr) => {
|
|
592
|
+
logger.error("Failed to release undo claim", { commandId: log.commandId, logId: log.id, err: releaseErr });
|
|
593
|
+
getTelemetryRuntime()?.reportError(releaseErr, {
|
|
594
|
+
module: "shared",
|
|
595
|
+
code: "shared.undo_claim_release_failed"
|
|
596
|
+
});
|
|
597
|
+
});
|
|
598
|
+
}
|
|
580
599
|
throw err;
|
|
581
600
|
}
|
|
582
601
|
}
|
|
@@ -683,6 +702,34 @@ class CommandBus {
|
|
|
683
702
|
await ctx.replayTransactionGuard({ operation, logEntry, transactionalEm: guardEm });
|
|
684
703
|
}], { transaction: true, label: `${logEntry.commandId}.${operation}.request-guard` });
|
|
685
704
|
}
|
|
705
|
+
async claimRedoSource(ctx, commandId, sourceLogId) {
|
|
706
|
+
let service = null;
|
|
707
|
+
try {
|
|
708
|
+
service = ctx.container.resolve("actionLogService");
|
|
709
|
+
} catch {
|
|
710
|
+
service = null;
|
|
711
|
+
}
|
|
712
|
+
if (!service || typeof service.claimForRedo !== "function" || typeof service.releaseRedoClaim !== "function") {
|
|
713
|
+
logger.warn("Redo source claim unavailable; replaying without an atomic claim", { commandId, sourceLogId });
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
const releaseClaim = service.releaseRedoClaim.bind(service);
|
|
717
|
+
const transactionalEm = ctx.transactionalEm;
|
|
718
|
+
const claimed = transactionalEm ? await service.claimForRedo(sourceLogId, transactionalEm) : await service.claimForRedo(sourceLogId);
|
|
719
|
+
if (!claimed) throw new Error("[internal] Redo source already consumed");
|
|
720
|
+
return async () => {
|
|
721
|
+
try {
|
|
722
|
+
const released = transactionalEm ? await releaseClaim(sourceLogId, transactionalEm) : await releaseClaim(sourceLogId);
|
|
723
|
+
if (!released) logger.warn("Redo source claim was not held at release", { commandId, sourceLogId });
|
|
724
|
+
} catch (releaseErr) {
|
|
725
|
+
logger.error("Failed to release redo source claim", { commandId, sourceLogId, err: releaseErr });
|
|
726
|
+
getTelemetryRuntime()?.reportError(releaseErr, {
|
|
727
|
+
module: "shared",
|
|
728
|
+
code: "shared.redo_claim_release_failed"
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
}
|
|
686
733
|
async resolveHandler(commandId) {
|
|
687
734
|
const handler = commandRegistry.get(commandId) ?? await commandRegistry.load(commandId);
|
|
688
735
|
if (!handler) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/commands/command-bus.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ActionLog } from '@open-mercato/core/modules/audit_logs/data/entities'\nimport type { ActionLogCreateInput } from '@open-mercato/core/modules/audit_logs/data/validators'\nimport { commandRegistry } from './registry'\nimport type {\n BulkImportSuppression,\n CommandExecutionOptions,\n CommandExecuteResult,\n CommandHandler,\n CommandLogBuilderArgs,\n CommandLogMetadata,\n CommandRuntimeContext,\n CommandUndoLogEntry,\n} from './types'\nimport { defaultUndoToken } from './types'\nimport type { AwilixContainer } from 'awilix'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport {\n canonicalizeResourceTag,\n deriveResourceFromCommandId,\n invalidateCrudCache,\n pickFirstIdentifier,\n isCrudCacheDebugEnabled,\n} from '@open-mercato/shared/lib/crud/cache'\nimport { normalizeCustomFieldKey } from '@open-mercato/shared/lib/custom-fields/keys'\nimport { getAllCommandInterceptorInstances } from './command-interceptor-store'\nimport {\n runCommandInterceptorsBefore,\n runCommandInterceptorsAfter,\n runCommandInterceptorsBeforeUndo,\n runCommandInterceptorsAfterUndo,\n} from './command-interceptor-runner'\nimport type { CommandInterceptorContext } from './command-interceptor'\nimport { CommandInterceptorError } from './errors'\nimport { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'\nimport { createLogger } from '../logger'\nimport { withAtomicFlush } from './flush'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n getTransactionLifetime,\n onTransactionLifetimeComplete,\n ownsTransactionLifetime,\n type TransactionLifetime,\n} from './transaction-lifetime'\n\nconst logger = createLogger('shared').child({ component: 'commands' })\n\ntype CommandActionLogService = {\n findByUndoToken(undoToken: string): Promise<ActionLog | null>\n claimForUndo(id: string, transactionalEm?: EntityManager): Promise<boolean>\n releaseUndoClaim(id: string, transactionalEm?: EntityManager): Promise<boolean>\n markUndone(id: string, traceInput?: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null | void>\n claimForRedo(id: string, transactionalEm?: EntityManager): Promise<boolean>\n log(input: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null>\n}\n\ntype AtomicReplayTransaction = {\n em: EntityManager\n joinsAmbient: boolean\n}\n\nfunction isInTransaction(em: EntityManager): boolean {\n const probe = (em as { isInTransaction?: () => boolean }).isInTransaction\n return typeof probe === 'function' && probe.call(em)\n}\n\nfunction resolveAtomicReplayTransaction(ctx: CommandRuntimeContext): AtomicReplayTransaction {\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager)\n const joinsAmbient = isInTransaction(em)\n if (joinsAmbient && !ownsTransactionLifetime(em, ctx.transactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay requires its outer transaction lifetime owner')\n }\n return { em, joinsAmbient }\n}\n\nfunction bindReplayTransactionContext(\n ctx: CommandRuntimeContext,\n em: EntityManager,\n expectedLifetime?: TransactionLifetime,\n): CommandRuntimeContext {\n const transactionLifetime = getTransactionLifetime(em)\n if (!transactionLifetime || (expectedLifetime && transactionLifetime !== expectedLifetime)) {\n throw new Error('[internal] Atomic replay transaction lifetime owner changed before replay')\n }\n return { ...ctx, transactionalEm: em, transactionLifetime }\n}\n\nconst SKIPPED_ACTION_LOG_RESOURCE_KINDS = new Set<string>([\n 'audit_logs.access',\n 'audit_logs.action',\n 'dashboards.layout',\n 'dashboards.user_widgets',\n 'dashboards.role_widgets',\n])\n\nfunction asRecord(input: unknown): Record<string, unknown> | null {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return null\n return input as Record<string, unknown>\n}\n\n/** Command handlers often return domain keys (e.g. warehouseId) without `id`; cache invalidation must still resolve the record. */\nfunction extractPrimaryIdFromCommandResult(result: unknown): string | null {\n const r = asRecord(result)\n if (!r) return null\n const direct = pickFirstIdentifier(r.id, r.entityId, r.recordId)\n if (direct) return direct\n for (const key of [\n 'warehouseId',\n 'zoneId',\n 'locationId',\n 'lotId',\n 'reservationId',\n 'profileId',\n 'movementId',\n 'balanceId',\n ]) {\n const v = r[key]\n if (typeof v === 'string' && v.trim().length > 0) return v.trim()\n }\n return null\n}\n\nfunction toISOString(value: unknown): string | null {\n if (value instanceof Date) {\n const iso = value.toISOString()\n return Number.isNaN(value.getTime()) ? null : iso\n }\n if (typeof value === 'string') {\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction deepEqual(a: unknown, b: unknown, seen?: Set<unknown>): boolean {\n if (Object.is(a, b)) return true\n if (a instanceof Date || b instanceof Date) {\n const aIso = toISOString(a)\n const bIso = toISOString(b)\n if (aIso != null && bIso != null) return aIso === bIso\n return false\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((value, index) => deepEqual(value, b[index], seen))\n }\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n if (!seen) seen = new Set()\n // `seen` is the current path: an object met again on it is a cycle. An object reached twice by\n // different paths (the items of one array held under two keys) is compared like any other.\n if (seen.has(a) || seen.has(b)) return false\n seen.add(a)\n seen.add(b)\n try {\n const aRec = a as Record<string, unknown>\n const bRec = b as Record<string, unknown>\n const keysA = Object.keys(aRec)\n const keysB = Object.keys(bRec)\n if (keysA.length !== keysB.length) return false\n return keysA.every((key) => deepEqual(aRec[key], bRec[key], seen))\n } finally {\n seen.delete(a)\n seen.delete(b)\n }\n }\n return false\n}\n\nconst CUSTOM_FIELD_CONTAINER_KEYS = new Set(['custom', 'customFields', 'customValues', 'cf'])\nconst SKIPPED_CHANGE_KEYS = new Set(['updatedAt', 'updated_at'])\n\nfunction appendCustomFieldChanges(\n changes: Record<string, { from: unknown; to: unknown }>,\n before: unknown,\n after: unknown\n): boolean {\n const beforeRec = asRecord(before)\n const afterRec = asRecord(after)\n if (!beforeRec && !afterRec) return false\n const left = beforeRec ?? {}\n const right = afterRec ?? {}\n const keys = new Set([...Object.keys(left), ...Object.keys(right)])\n for (const key of keys) {\n const from = left[key]\n const to = right[key]\n if (!deepEqual(from, to)) {\n changes[normalizeCustomFieldKey(key)] = { from, to }\n }\n }\n return true\n}\n\nfunction buildRecordChanges(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): Record<string, { from: unknown; to: unknown }> {\n return buildRecordChangesDeep(before, after)\n}\n\nfunction buildRecordChangesDeep(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n prefix?: string,\n seen?: Set<unknown>,\n): Record<string, { from: unknown; to: unknown }> {\n const changes: Record<string, { from: unknown; to: unknown }> = {}\n if (!seen) seen = new Set()\n if (seen.has(before) || seen.has(after)) return changes\n seen.add(before)\n seen.add(after)\n const keys = new Set([...Object.keys(before), ...Object.keys(after)])\n for (const key of keys) {\n if (SKIPPED_CHANGE_KEYS.has(key)) continue\n if (CUSTOM_FIELD_CONTAINER_KEYS.has(key)) {\n const handled = appendCustomFieldChanges(changes, before[key], after[key])\n if (handled) continue\n }\n const from = before[key]\n const to = after[key]\n const path = prefix ? `${prefix}.${key}` : key\n const fromRec = asRecord(from)\n const toRec = asRecord(to)\n if (fromRec && toRec) {\n const nested = buildRecordChangesDeep(fromRec, toRec, path, seen)\n if (Object.keys(nested).length) {\n Object.assign(changes, nested)\n continue\n }\n }\n if (!deepEqual(from, to)) {\n changes[path] = { from, to }\n }\n }\n return changes\n}\n\nfunction deriveChangesFromSnapshots(\n before: unknown,\n after: unknown,\n): Record<string, { from: unknown; to: unknown }> | null {\n const beforeRec = asRecord(before)\n const afterRec = asRecord(after)\n if (!beforeRec || !afterRec) return null\n const changes = buildRecordChanges(beforeRec, afterRec)\n return Object.keys(changes).length ? changes : null\n}\n\nfunction invertRecordedChanges(\n changes: unknown,\n): Record<string, { from: unknown; to: unknown }> | null {\n const source = asRecord(changes)\n if (!source) return null\n const inverted: Record<string, { from: unknown; to: unknown }> = {}\n for (const [key, value] of Object.entries(source)) {\n const entry = asRecord(value)\n if (!entry || (!('from' in entry) && !('to' in entry))) continue\n inverted[key] = {\n from: entry.to,\n to: entry.from,\n }\n }\n return Object.keys(inverted).length ? inverted : null\n}\n\nfunction extractAliasList(source: unknown): string[] {\n if (!source || typeof source !== 'object' || Array.isArray(source)) return []\n const record = source as Record<string, unknown>\n const raw = record.cacheAliases\n if (!Array.isArray(raw)) return []\n const aliases = new Set<string>()\n for (const value of raw) {\n if (typeof value !== 'string') continue\n const normalized = canonicalizeResourceTag(value)\n if (normalized) aliases.add(normalized)\n }\n return Array.from(aliases)\n}\n\nexport class CommandBus {\n async execute<TInput = unknown, TResult = unknown>(\n commandId: string,\n options: CommandExecutionOptions<TInput>\n ): Promise<CommandExecuteResult<TResult>> {\n const handler = await this.resolveHandler<TInput, TResult>(commandId)\n\n const replayLogEntry = options.redoLogEntry ?? null\n const isAtomicReplay = replayLogEntry !== null && handler.atomicReplay === true\n const allInterceptors = getAllCommandInterceptorInstances()\n let interceptorMetadata = new Map<string, Record<string, unknown>>()\n let effectiveOptions = options\n let userFeatures: string[] = []\n const runBeforeExecuteInterceptors = async (baseOptions: CommandExecutionOptions<TInput>) => {\n const resolvedUserFeatures = allInterceptors.length\n ? await this.resolveUserFeaturesForInterceptors(baseOptions.ctx)\n : []\n if (!allInterceptors.length) {\n return {\n effectiveOptions: baseOptions,\n metadata: new Map<string, Record<string, unknown>>(),\n userFeatures: resolvedUserFeatures,\n }\n }\n const interceptorCtx: CommandInterceptorContext = {\n commandId,\n auth: baseOptions.ctx.auth ?? null,\n selectedOrganizationId: baseOptions.ctx.selectedOrganizationId ?? baseOptions.ctx.auth?.orgId ?? null,\n container: baseOptions.ctx.container,\n organizationScope: baseOptions.ctx.organizationScope ?? null,\n request: baseOptions.ctx.request ?? null,\n }\n const beforeResult = await runCommandInterceptorsBefore(\n allInterceptors, commandId, baseOptions.input, interceptorCtx, resolvedUserFeatures,\n )\n if (!beforeResult.ok) {\n const blocked = beforeResult.error!\n throw new CommandInterceptorError(blocked.message, { status: blocked.status, body: blocked.body })\n }\n const preparedOptions = beforeResult.modifiedInput\n ? {\n ...baseOptions,\n input: { ...(baseOptions.input as object), ...beforeResult.modifiedInput } as TInput,\n }\n : baseOptions\n return {\n effectiveOptions: preparedOptions,\n metadata: beforeResult.metadataByInterceptor,\n userFeatures: resolvedUserFeatures,\n }\n }\n\n if (replayLogEntry && !isAtomicReplay) {\n await this.runReplayTransactionGuard(options.ctx, 'redo', replayLogEntry)\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'redo',\n input: options.input,\n ctx: options.ctx,\n logEntry: replayLogEntry,\n })\n }\n }\n\n if (!isAtomicReplay) {\n const prepared = await runBeforeExecuteInterceptors(options)\n effectiveOptions = prepared.effectiveOptions\n interceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n }\n\n const executeCore = async (coreOptions: CommandExecutionOptions<TInput>) => {\n const snapshots: { before?: unknown } = {}\n let executionOptions = coreOptions\n if (handler.prepareSnapshotInsideTransaction && handler.prepare) {\n const prepare = handler.prepare\n const originalCtx = coreOptions.ctx\n const originalBeforeTransactionalWrite = originalCtx.beforeTransactionalWrite\n let prepared = false\n let transactionalCtx: CommandRuntimeContext\n transactionalCtx = {\n ...originalCtx,\n beforeTransactionalWrite: async (em, input) => {\n await originalBeforeTransactionalWrite?.(em, input)\n if (prepared) return\n Object.assign(\n snapshots,\n (await prepare(coreOptions.input, { ...transactionalCtx, transactionalEm: em })) ?? {},\n )\n prepared = true\n },\n }\n executionOptions = { ...coreOptions, ctx: transactionalCtx }\n } else {\n Object.assign(snapshots, await this.prepareSnapshots(handler, coreOptions))\n }\n effectiveOptions = executionOptions\n const sourceLog = executionOptions.redoLogEntry ?? null\n const result =\n sourceLog && typeof handler.redo === 'function'\n ? await handler.redo({ input: executionOptions.input, ctx: executionOptions.ctx, logEntry: sourceLog })\n : await handler.execute(executionOptions.input, executionOptions.ctx)\n const afterSnapshot = await this.captureAfter(handler, executionOptions, result)\n const snapshotsWithAfter = { ...snapshots, after: afterSnapshot }\n const logMeta = await this.buildLog(handler, executionOptions, result, snapshotsWithAfter)\n let mergedMeta = this.mergeMetadata(executionOptions.metadata, logMeta)\n // Interceptors opt into audit-log enrichment with a reserved `logContext` key rather\n // than the generic `context` one, so the metadata an interceptor already passes to its\n // own afterExecute hook is never silently promoted into audit storage.\n // Map iteration order is interceptor priority order (see collectMatching), so a\n // later-priority interceptor overrides an earlier one on key collisions.\n let interceptorContextMerged: Record<string, unknown> = {}\n for (const meta of interceptorMetadata.values()) {\n const logContextRecord = asRecord(asRecord(meta)?.logContext)\n if (!logContextRecord) continue\n interceptorContextMerged = {\n ...interceptorContextMerged,\n ...logContextRecord,\n }\n }\n const baseContext = asRecord(executionOptions.metadata?.context) ?? {}\n const logMetaContext = asRecord(logMeta?.context) ?? {}\n if (Object.keys(interceptorContextMerged).length > 0 || Object.keys(baseContext).length > 0 || Object.keys(logMetaContext).length > 0) {\n mergedMeta = mergedMeta ?? {}\n mergedMeta.context = {\n ...baseContext,\n ...interceptorContextMerged,\n ...logMetaContext,\n }\n }\n const undoable = this.isUndoable(handler)\n if (undoable && mergedMeta?.replayable !== false) {\n mergedMeta = mergedMeta ?? {}\n if (!mergedMeta.undoToken) mergedMeta.undoToken = defaultUndoToken()\n if (mergedMeta.actorUserId === undefined) mergedMeta.actorUserId = executionOptions.ctx.auth?.sub ?? null\n } else if (mergedMeta?.replayable === false) {\n mergedMeta.undoToken = null\n }\n if (afterSnapshot !== undefined && afterSnapshot !== null) {\n if (!mergedMeta) {\n mergedMeta = { snapshotAfter: afterSnapshot }\n } else if (!mergedMeta.snapshotAfter) {\n mergedMeta.snapshotAfter = afterSnapshot\n }\n }\n if (snapshots.before) {\n if (!mergedMeta) {\n mergedMeta = { snapshotBefore: snapshots.before }\n } else if (!mergedMeta.snapshotBefore) {\n mergedMeta.snapshotBefore = snapshots.before\n }\n }\n if (mergedMeta?.snapshotBefore !== undefined && mergedMeta?.snapshotAfter !== undefined) {\n const currentChanges = mergedMeta.changes\n const shouldInfer =\n currentChanges === undefined ||\n currentChanges === null ||\n (typeof currentChanges === 'object' && !Array.isArray(currentChanges) && Object.keys(currentChanges).length === 0)\n if (shouldInfer) {\n const inferred = deriveChangesFromSnapshots(mergedMeta.snapshotBefore, mergedMeta.snapshotAfter)\n if (inferred) mergedMeta.changes = inferred\n }\n }\n const logEntry = await this.persistLog(commandId, executionOptions, mergedMeta)\n return { result, mergedMeta, logEntry }\n }\n\n let replaySourceFinalized = false\n let coreResult: Awaited<ReturnType<typeof executeCore>>\n const atomicSourceLog = options.redoLogEntry ?? null\n let ambientReplay: AtomicReplayTransaction | null = null\n let replayTransactionLifetime: TransactionLifetime | null = null\n if (atomicSourceLog && isAtomicReplay) {\n ambientReplay = resolveAtomicReplayTransaction(options.ctx)\n const replayEm = ambientReplay.em\n await withAtomicFlush(replayEm, [async () => {\n const replayCtx = bindReplayTransactionContext(\n options.ctx,\n replayEm,\n ambientReplay?.joinsAmbient ? options.ctx.transactionLifetime : undefined,\n )\n replayTransactionLifetime = replayCtx.transactionLifetime ?? null\n const transactionalBaseOptions: CommandExecutionOptions<TInput> = {\n ...options,\n ctx: replayCtx,\n }\n if (!atomicSourceLog.id) throw new Error('[internal] Atomic redo source log id is required')\n if (handler.stabilizeReplay) {\n await handler.stabilizeReplay({\n operation: 'redo',\n input: transactionalBaseOptions.input,\n ctx: transactionalBaseOptions.ctx,\n logEntry: atomicSourceLog,\n })\n }\n await this.runReplayTransactionGuard(\n transactionalBaseOptions.ctx,\n 'redo',\n atomicSourceLog,\n replayEm,\n )\n const prepared = await runBeforeExecuteInterceptors(transactionalBaseOptions)\n effectiveOptions = prepared.effectiveOptions\n interceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n const service = effectiveOptions.ctx.container.resolve('actionLogService') as CommandActionLogService\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'redo',\n input: effectiveOptions.input,\n ctx: effectiveOptions.ctx,\n logEntry: atomicSourceLog,\n })\n }\n const claimed = await service.claimForRedo(atomicSourceLog.id, replayEm)\n if (!claimed) throw new Error('[internal] Redo source already consumed')\n coreResult = await executeCore(effectiveOptions)\n }], { transaction: true, label: `${commandId}.redo` })\n replaySourceFinalized = !ambientReplay.joinsAmbient\n } else {\n coreResult = await executeCore(effectiveOptions)\n }\n const { result, mergedMeta, logEntry } = coreResult!\n\n const runPostCommit = async () => {\n let finalResult = result\n if (allInterceptors.length) {\n const interceptorCtx: CommandInterceptorContext = {\n commandId,\n auth: effectiveOptions.ctx.auth ?? null,\n selectedOrganizationId: effectiveOptions.ctx.selectedOrganizationId ?? effectiveOptions.ctx.auth?.orgId ?? null,\n container: effectiveOptions.ctx.container,\n organizationScope: effectiveOptions.ctx.organizationScope ?? null,\n request: effectiveOptions.ctx.request ?? null,\n }\n const afterResult = await runCommandInterceptorsAfter(\n allInterceptors, commandId, effectiveOptions.input, result, interceptorCtx,\n userFeatures, interceptorMetadata,\n )\n if (afterResult.modifiedResult && typeof result === 'object' && result) {\n finalResult = { ...(result as object), ...afterResult.modifiedResult } as Awaited<TResult>\n }\n }\n\n if (!effectiveOptions.skipCacheInvalidation) {\n await this.invalidateCacheAfterExecute(commandId, effectiveOptions, finalResult, mergedMeta)\n }\n // Bulk-import backfills defer heavy per-record side effects: the ctx flags are read here and\n // threaded as a local into the flush (never stored on the shared dataEngine), so a concurrent\n // command with different flags can't observe them. Reindex is restored by the caller's\n // end-of-run `query_index rebuild`. Mirrors `skipCacheInvalidation` above.\n await this.flushCrudSideEffects(effectiveOptions.ctx.container, effectiveOptions.ctx?.bulkImport)\n return finalResult\n }\n\n const executionResult: CommandExecuteResult<TResult> = {\n result,\n logEntry,\n replaySourceFinalized,\n }\n if (ambientReplay?.joinsAmbient) {\n if (!replayTransactionLifetime || !ownsTransactionLifetime(ambientReplay.em, replayTransactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay lost its outer transaction lifetime owner')\n }\n onTransactionLifetimeComplete(ambientReplay.em, async (outcome) => {\n if (outcome !== 'committed') return\n executionResult.result = await runPostCommit()\n executionResult.replaySourceFinalized = true\n })\n return executionResult\n }\n\n executionResult.result = await runPostCommit()\n return executionResult\n }\n\n async undo(undoToken: string, ctx: CommandRuntimeContext): Promise<void> {\n const service = (ctx.container.resolve('actionLogService') as CommandActionLogService)\n const log = await service.findByUndoToken(undoToken)\n if (!log) throw new Error('Undo token expired or not found')\n const handler = await this.resolveHandler(log.commandId)\n if (!handler.undo || this.isUndoable(handler) === false) {\n throw new Error(`Command ${log.commandId} is not undoable`)\n }\n\n const isAtomicReplay = handler.atomicReplay === true\n const allInterceptors = getAllCommandInterceptorInstances()\n let undoInterceptorMetadata = new Map<string, Record<string, unknown>>()\n let userFeatures: string[] = []\n const runBeforeUndoInterceptors = async (replayCtx: CommandRuntimeContext) => {\n const resolvedUserFeatures = allInterceptors.length\n ? await this.resolveUserFeaturesForInterceptors(replayCtx)\n : []\n if (!allInterceptors.length) {\n return {\n metadata: new Map<string, Record<string, unknown>>(),\n userFeatures: resolvedUserFeatures,\n }\n }\n const undoCtx = { input: log.commandPayload, logEntry: log, undoToken }\n const interceptorCtx: CommandInterceptorContext = {\n commandId: log.commandId,\n auth: replayCtx.auth ?? null,\n selectedOrganizationId: replayCtx.selectedOrganizationId ?? replayCtx.auth?.orgId ?? null,\n container: replayCtx.container,\n organizationScope: replayCtx.organizationScope ?? null,\n request: replayCtx.request ?? null,\n }\n const beforeResult = await runCommandInterceptorsBeforeUndo(\n allInterceptors, log.commandId, undoCtx, interceptorCtx, resolvedUserFeatures,\n )\n if (!beforeResult.ok) {\n const blocked = beforeResult.error!\n throw new CommandInterceptorError(blocked.message, { status: blocked.status, body: blocked.body })\n }\n return {\n metadata: beforeResult.metadataByInterceptor,\n userFeatures: resolvedUserFeatures,\n }\n }\n\n if (!isAtomicReplay) {\n await this.runReplayTransactionGuard(ctx, 'undo', log)\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.authorizeReplay>>[0]['input'],\n ctx,\n logEntry: log,\n })\n }\n }\n\n const claimUndo = async (replayEm?: EntityManager) => {\n // Two contenders can both pass the initial lookup; only the compare-and-set\n // below may proceed. On the atomic path this state is still uncommitted and\n // rolls back with every handler/log write if anything later fails.\n const claimed = replayEm\n ? await service.claimForUndo(log.id, replayEm)\n : await service.claimForUndo(log.id)\n if (!claimed) throw new Error('[internal] Undo token already consumed')\n }\n const finishUndo = async (replayCtx: CommandRuntimeContext, replayEm?: EntityManager) => {\n await handler.undo!({\n input: log.commandPayload as Parameters<NonNullable<typeof handler.undo>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n const traceLog = this.buildUndoTraceLog(log, replayCtx)\n if (replayEm) {\n await service.markUndone(log.id, traceLog, replayEm)\n } else {\n await service.markUndone(log.id, traceLog)\n }\n }\n\n let ambientReplay: AtomicReplayTransaction | null = null\n let replayTransactionLifetime: TransactionLifetime | null = null\n if (isAtomicReplay) {\n ambientReplay = resolveAtomicReplayTransaction(ctx)\n const replayEm = ambientReplay.em\n await withAtomicFlush(replayEm, [async () => {\n const replayCtx = bindReplayTransactionContext(\n ctx,\n replayEm,\n ambientReplay?.joinsAmbient ? ctx.transactionLifetime : undefined,\n )\n replayTransactionLifetime = replayCtx.transactionLifetime ?? null\n if (handler.stabilizeReplay) {\n await handler.stabilizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.stabilizeReplay>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n }\n await this.runReplayTransactionGuard(replayCtx, 'undo', log, replayEm)\n const prepared = await runBeforeUndoInterceptors(replayCtx)\n undoInterceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.authorizeReplay>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n }\n await claimUndo(replayEm)\n await finishUndo(replayCtx, replayEm)\n }], {\n transaction: true,\n label: `${log.commandId}.undo`,\n })\n } else {\n try {\n // Preserve the established non-atomic lifecycle exactly: authorization,\n // source claim, before-undo interceptors, handler, then finalization.\n await claimUndo()\n const prepared = await runBeforeUndoInterceptors(ctx)\n undoInterceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n await finishUndo(ctx)\n } catch (err) {\n // Legacy handlers retain their compensating release behavior because\n // their domain mutation may not share the action-log transaction.\n await service.releaseUndoClaim(log.id).catch(() => {})\n throw err\n }\n }\n\n const runPostCommit = async () => {\n // Post-commit hooks and side effects run only after an atomic replay has\n // durably committed both the domain state and source/trace log state.\n if (allInterceptors.length) {\n const undoCtx = { input: log.commandPayload, logEntry: log, undoToken }\n const interceptorCtx: CommandInterceptorContext = {\n commandId: log.commandId,\n auth: ctx.auth ?? null,\n selectedOrganizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n container: ctx.container,\n organizationScope: ctx.organizationScope ?? null,\n request: ctx.request ?? null,\n }\n await runCommandInterceptorsAfterUndo(\n allInterceptors, log.commandId, undoCtx, interceptorCtx,\n userFeatures, undoInterceptorMetadata,\n )\n }\n\n await this.invalidateCacheAfterUndo(log, ctx)\n await this.flushCrudSideEffects(ctx.container)\n }\n\n if (ambientReplay?.joinsAmbient) {\n if (!replayTransactionLifetime || !ownsTransactionLifetime(ambientReplay.em, replayTransactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay lost its outer transaction lifetime owner')\n }\n onTransactionLifetimeComplete(ambientReplay.em, async (outcome) => {\n if (outcome === 'committed') await runPostCommit()\n })\n return\n }\n\n await runPostCommit()\n }\n\n private buildUndoTraceLog(log: ActionLog, ctx: CommandRuntimeContext): ActionLogCreateInput | undefined {\n const snapshotBefore = log.snapshotAfter ?? null\n const snapshotAfter = log.snapshotBefore ?? null\n const changes =\n deriveChangesFromSnapshots(snapshotBefore, snapshotAfter)\n ?? invertRecordedChanges(log.changesJson)\n ?? undefined\n\n const baseContext = asRecord(log.contextJson) ?? {}\n const context = {\n ...baseContext,\n historyAction: 'undo',\n sourceLogId: log.id,\n sourceCommandId: log.commandId,\n }\n\n return {\n tenantId: log.tenantId ?? ctx.auth?.tenantId ?? null,\n organizationId: log.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n actorUserId: ctx.auth?.sub ?? log.actorUserId ?? null,\n commandId: log.commandId,\n actionLabel: log.actionLabel ?? undefined,\n resourceKind: log.resourceKind ?? undefined,\n resourceId: log.resourceId ?? undefined,\n parentResourceKind: log.parentResourceKind ?? null,\n parentResourceId: log.parentResourceId ?? null,\n relatedResourceKind: log.relatedResourceKind ?? null,\n relatedResourceId: log.relatedResourceId ?? null,\n snapshotBefore,\n snapshotAfter,\n changes,\n context,\n }\n }\n\n private async resolveUserFeaturesForInterceptors(ctx: CommandRuntimeContext): Promise<string[]> {\n if (!ctx.auth) return []\n type RbacLike = {\n getGrantedFeatures: (\n userId: string,\n opts: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n getGrantedFeaturesWithEntityManager?: (\n em: EntityManager,\n userId: string,\n opts: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n }\n let rbac: RbacLike | undefined\n try {\n rbac = ctx.container.resolve('rbacService') as RbacLike | undefined\n } catch {\n // Intentional: rbacService is not registered in all runtime contexts (CLI, tests, bootstrap).\n return []\n }\n const scope = {\n tenantId: ctx.auth.tenantId,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth.orgId,\n }\n if (ctx.transactionalEm) {\n if (!rbac?.getGrantedFeaturesWithEntityManager) return []\n return await rbac.getGrantedFeaturesWithEntityManager(\n ctx.transactionalEm,\n ctx.auth.sub,\n scope,\n )\n }\n try {\n if (rbac?.getGrantedFeatures) {\n return await rbac.getGrantedFeatures(ctx.auth.sub, scope)\n }\n } catch {\n // Outside a transaction a failed lookup cannot poison anything; interceptors without\n // feature gating still run. Inside one the error is rethrown above, because the failed\n // query has already aborted the transaction.\n }\n return []\n }\n\n private async runReplayTransactionGuard(\n ctx: CommandRuntimeContext,\n operation: 'undo' | 'redo',\n logEntry: CommandUndoLogEntry,\n transactionalEm?: EntityManager,\n ): Promise<void> {\n if (!ctx.replayTransactionGuard) return\n if (transactionalEm) {\n await ctx.replayTransactionGuard({ operation, logEntry, transactionalEm })\n return\n }\n const requestEm = ctx.container.resolve('em') as EntityManager\n const guardEm = typeof requestEm.fork === 'function' ? requestEm.fork() : requestEm\n await withAtomicFlush(guardEm, [async () => {\n await ctx.replayTransactionGuard!({ operation, logEntry, transactionalEm: guardEm })\n }], { transaction: true, label: `${logEntry.commandId}.${operation}.request-guard` })\n }\n\n private async resolveHandler<TInput, TResult>(commandId: string): Promise<CommandHandler<TInput, TResult>> {\n const handler =\n commandRegistry.get<TInput, TResult>(commandId) ??\n ((await commandRegistry.load(commandId)) as CommandHandler<TInput, TResult> | null)\n if (!handler) {\n const moduleName = commandId.split('.')[0]\n const registered = commandRegistry.list()\n const sameModule = registered.filter((id) => id.split('.')[0] === moduleName)\n const registeredLoaders = commandRegistry.listLoaders()\n const sameModuleLoaders = registeredLoaders.filter((id) => id === commandId || id.startsWith(`${moduleName}:`))\n const hint = sameModule.length > 0\n ? ` Registered commands for module \"${moduleName}\": [${sameModule.join(', ')}].`\n : sameModuleLoaders.length > 0\n ? ` Command loaders for module \"${moduleName}\" were registered but none loaded \"${commandId}\".`\n : ` No commands or command loaders registered for module \"${moduleName}\". Ensure the command file is imported or generated lazy command loaders are registered.`\n throw new Error(`Command handler not registered for id ${commandId}.${hint}`)\n }\n return handler\n }\n\n private async prepareSnapshots<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>\n ): Promise<{ before?: unknown }> {\n if (!handler.prepare) return {}\n try {\n return (await handler.prepare(options.input, options.ctx)) || {}\n } catch (err) {\n throw err\n }\n }\n\n private async captureAfter<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>,\n result: TResult\n ): Promise<unknown> {\n if (!handler.captureAfter) return undefined\n return handler.captureAfter(options.input, result, options.ctx)\n }\n\n private async buildLog<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>,\n result: TResult,\n snapshots: { before?: unknown; after?: unknown }\n ): Promise<CommandLogMetadata | null> {\n if (!handler.buildLog) return null\n const args: CommandLogBuilderArgs<TInput, TResult> = {\n input: options.input,\n result,\n ctx: options.ctx,\n snapshots,\n }\n return (await handler.buildLog(args)) || null\n }\n\n private mergeMetadata(primary?: CommandLogMetadata | null, secondary?: CommandLogMetadata | null): CommandLogMetadata | null {\n if (!primary && !secondary) return null\n return {\n skipLog: secondary?.skipLog ?? primary?.skipLog ?? false,\n replayable:\n secondary?.replayable === false || primary?.replayable === false\n ? false\n : secondary?.replayable ?? primary?.replayable,\n tenantId: secondary?.tenantId ?? primary?.tenantId ?? null,\n organizationId: secondary?.organizationId ?? primary?.organizationId ?? null,\n actorUserId: secondary?.actorUserId ?? primary?.actorUserId ?? null,\n onBehalfOfUserId: secondary?.onBehalfOfUserId ?? primary?.onBehalfOfUserId ?? null,\n actionLabel: secondary?.actionLabel ?? primary?.actionLabel ?? null,\n resourceKind: secondary?.resourceKind ?? primary?.resourceKind ?? null,\n resourceId: secondary?.resourceId ?? primary?.resourceId ?? null,\n parentResourceKind: secondary?.parentResourceKind ?? primary?.parentResourceKind ?? null,\n parentResourceId: secondary?.parentResourceId ?? primary?.parentResourceId ?? null,\n relatedResourceKind: secondary?.relatedResourceKind ?? primary?.relatedResourceKind ?? null,\n relatedResourceId: secondary?.relatedResourceId ?? primary?.relatedResourceId ?? null,\n undoToken: secondary?.undoToken ?? primary?.undoToken ?? null,\n // A redacted redo input always wins: it exists precisely because the raw\n // input carries a secret that must not reach `action_logs`.\n redoInput: secondary?.redoInput !== undefined ? secondary.redoInput : primary?.redoInput,\n payload: secondary?.payload ?? primary?.payload ?? null,\n snapshotBefore: secondary?.snapshotBefore ?? primary?.snapshotBefore ?? null,\n snapshotAfter: secondary?.snapshotAfter ?? primary?.snapshotAfter ?? null,\n changes: secondary?.changes ?? primary?.changes ?? null,\n context: secondary?.context ?? primary?.context ?? null,\n }\n }\n\n private async persistLog<TInput>(\n commandId: string,\n options: CommandExecutionOptions<TInput>,\n metadata: CommandLogMetadata | null\n ): Promise<ActionLog | null> {\n if (!metadata) return null\n if (metadata.skipLog) return null\n const resourceKind =\n typeof metadata.resourceKind === 'string' ? metadata.resourceKind : null\n if (resourceKind && SKIPPED_ACTION_LOG_RESOURCE_KINDS.has(resourceKind)) {\n return null\n }\n let service: CommandActionLogService | null = null\n try {\n service = (options.ctx.container.resolve('actionLogService') as CommandActionLogService)\n } catch {\n service = null\n }\n if (!service) return null\n\n const tenantId = metadata.tenantId ?? options.ctx.auth?.tenantId ?? null\n const organizationId =\n metadata.organizationId ?? options.ctx.selectedOrganizationId ?? options.ctx.auth?.orgId ?? null\n // On-behalf-of attribution (Wave 4 P2): when `ctx.runAs` is set the actor is\n // the agent principal and the human it acts for is recorded separately. This\n // funnels agent writes through the SAME ActionLog path as a human's \u2014 only the\n // attribution differs (actorUserId=agent, onBehalfOfUserId=human, source='agent').\n const runAs = options.ctx.runAs ?? null\n const actorUserId = runAs?.actorUserId ?? metadata.actorUserId ?? options.ctx.auth?.sub ?? null\n const onBehalfOfUserId = runAs ? (runAs.onBehalfOfUserId ?? null) : (metadata.onBehalfOfUserId ?? null)\n const systemActorContext = !actorUserId && options.ctx.systemActor === true\n ? { systemActor: 'system:command' }\n : null\n const payload: Record<string, unknown> = {\n tenantId: tenantId ?? undefined,\n organizationId: organizationId ?? undefined,\n actorUserId: actorUserId ?? undefined,\n onBehalfOfUserId: onBehalfOfUserId ?? undefined,\n commandId,\n }\n\n if (metadata) {\n if ('actionLabel' in metadata && metadata.actionLabel != null) payload.actionLabel = metadata.actionLabel\n if ('resourceKind' in metadata && metadata.resourceKind != null) payload.resourceKind = metadata.resourceKind\n if ('resourceId' in metadata && metadata.resourceId != null) payload.resourceId = metadata.resourceId\n if ('parentResourceKind' in metadata && metadata.parentResourceKind != null) payload.parentResourceKind = metadata.parentResourceKind\n if ('parentResourceId' in metadata && metadata.parentResourceId != null) payload.parentResourceId = metadata.parentResourceId\n if ('relatedResourceKind' in metadata && metadata.relatedResourceKind != null) payload.relatedResourceKind = metadata.relatedResourceKind\n if ('relatedResourceId' in metadata && metadata.relatedResourceId != null) payload.relatedResourceId = metadata.relatedResourceId\n if ('undoToken' in metadata && metadata.undoToken != null) payload.undoToken = metadata.undoToken\n if ('payload' in metadata && metadata.payload !== undefined) payload.commandPayload = metadata.payload\n if ('snapshotBefore' in metadata && metadata.snapshotBefore !== undefined) payload.snapshotBefore = metadata.snapshotBefore\n if ('snapshotAfter' in metadata && metadata.snapshotAfter !== undefined) payload.snapshotAfter = metadata.snapshotAfter\n if ('changes' in metadata && metadata.changes !== undefined && metadata.changes !== null) payload.changes = metadata.changes\n if ('context' in metadata && metadata.context !== undefined && metadata.context !== null) {\n payload.context = { ...(systemActorContext ?? {}), ...metadata.context }\n } else if (systemActorContext) {\n payload.context = systemActorContext\n }\n }\n\n if (runAs) {\n // Stamp the audit source so `deriveActionLogSource` projects `sourceKey='agent'`.\n // Merge into any caller-provided context rather than replacing it.\n const baseContext = asRecord(payload.context) ?? {}\n payload.context = { ...baseContext, source: runAs.source }\n }\n\n if (metadata.replayable === false) {\n delete payload.commandPayload\n } else {\n const redoInput = metadata.redoInput !== undefined ? metadata.redoInput : options.input\n const redoEnvelope = wrapRedoPayload('commandPayload' in payload ? (payload.commandPayload as unknown) : undefined, redoInput)\n payload.commandPayload = redoEnvelope\n }\n\n return options.ctx.transactionalEm\n ? await service.log(payload as ActionLogCreateInput, options.ctx.transactionalEm)\n : await service.log(payload as ActionLogCreateInput)\n }\n\n private isUndoable(handler: CommandHandler<unknown, unknown>): boolean {\n return handler.isUndoable !== false && typeof handler.undo === 'function'\n }\n\n private async invalidateCacheAfterExecute<TResult>(\n commandId: string,\n options: CommandExecutionOptions<unknown>,\n result: TResult,\n metadata: CommandLogMetadata | null\n ): Promise<void> {\n const resource = typeof metadata?.resourceKind === 'string' ? metadata.resourceKind : null\n if (!resource) return\n try {\n const ctx = options.ctx\n const resultRecord = asRecord(result)\n const resultEntity = asRecord(resultRecord?.entity)\n const inputRecord = asRecord(options.input)\n const inputEntity = asRecord(inputRecord?.entity)\n\n const recordId = pickFirstIdentifier(\n metadata?.resourceId,\n extractPrimaryIdFromCommandResult(result),\n resultRecord?.entityId,\n resultRecord?.id,\n resultRecord?.recordId,\n resultEntity?.id,\n inputRecord?.id,\n inputRecord?.entityId,\n inputRecord?.recordId,\n inputEntity?.id\n )\n\n const organizationId = pickFirstIdentifier(\n metadata?.organizationId,\n resultRecord?.organizationId,\n resultEntity?.organizationId,\n inputRecord?.organizationId,\n inputEntity?.organizationId,\n ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n )\n\n const tenantId = pickFirstIdentifier(\n metadata?.tenantId,\n resultRecord?.tenantId,\n resultEntity?.tenantId,\n inputRecord?.tenantId,\n inputEntity?.tenantId,\n ctx.auth?.tenantId ?? null\n )\n\n const fallbackTenant = pickFirstIdentifier(metadata?.tenantId, ctx.auth?.tenantId ?? null)\n\n const aliasSet = new Set<string>()\n for (const alias of extractAliasList(metadata?.context ?? null)) {\n aliasSet.add(alias)\n }\n const derived = deriveResourceFromCommandId(commandId)\n if (derived) aliasSet.add(derived)\n const aliasExtras = Array.from(aliasSet)\n await invalidateCrudCache(\n ctx.container,\n resource,\n { id: recordId, organizationId, tenantId },\n fallbackTenant,\n `command:${commandId}:execute`,\n aliasExtras\n )\n } catch (err) {\n if (isCrudCacheDebugEnabled()) {\n try {\n logger.debug('Cache execute-invalidation failed', { commandId, err })\n } catch {}\n }\n }\n }\n\n private async invalidateCacheAfterUndo(log: ActionLog, ctx: CommandRuntimeContext): Promise<void> {\n const resource = typeof log.resourceKind === 'string' ? log.resourceKind : null\n if (!resource) return\n try {\n const recordId = pickFirstIdentifier(log.resourceId)\n const organizationId = pickFirstIdentifier(log.organizationId, ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null)\n const tenantId = pickFirstIdentifier(log.tenantId, ctx.auth?.tenantId ?? null)\n const fallbackTenant = pickFirstIdentifier(log.tenantId, ctx.auth?.tenantId ?? null)\n const aliasSet = new Set<string>()\n for (const alias of extractAliasList(log.contextJson ?? null)) {\n aliasSet.add(alias)\n }\n const derived = deriveResourceFromCommandId(log.commandId)\n if (derived) aliasSet.add(derived)\n const aliasExtras = Array.from(aliasSet)\n await invalidateCrudCache(\n ctx.container,\n resource,\n { id: recordId, organizationId, tenantId },\n fallbackTenant,\n `command:${log.commandId}:undo`,\n aliasExtras\n )\n } catch (err) {\n if (isCrudCacheDebugEnabled()) {\n try {\n logger.debug('Cache undo-invalidation failed', { commandId: log.commandId, err })\n } catch {}\n }\n }\n }\n\n private async flushCrudSideEffects(container: AwilixContainer, suppress?: BulkImportSuppression): Promise<void> {\n try {\n const dataEngine = (container.resolve('dataEngine') as DataEngine)\n await dataEngine.flushOrmEntityChanges(suppress)\n } catch (error) {\n if (isReadProjectionAlwaysConsistent()) {\n throw error\n }\n // best-effort: failures should not block command execution\n }\n }\n}\n\ntype RedoEnvelope = {\n __redoInput: unknown\n [key: string]: unknown\n}\n\nfunction wrapRedoPayload(existing: unknown, input: unknown): RedoEnvelope {\n if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {\n const envelope: RedoEnvelope = { __redoInput: input }\n if (existing !== undefined) envelope.value = existing\n return envelope\n }\n const current = existing as Record<string, unknown>\n if ('__redoInput' in current && current.__redoInput !== undefined) {\n return current as RedoEnvelope\n }\n return { __redoInput: input, ...current }\n}\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,uBAAuB;AAWhC,SAAS,wBAAwB;AAGjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B;AACxC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,wCAAwC;AACjD,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAEhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,WAAW,CAAC;AAgB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AAC;AAAA,QAClF,QAAQ;AAAA,QAAC;AAAA,MACX;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAc,qBAAqB,WAA4B,UAAiD;AAC9G,QAAI;AACF,YAAM,aAAc,UAAU,QAAQ,YAAY;AAClD,YAAM,WAAW,sBAAsB,QAAQ;AAAA,IACjD,SAAS,OAAO;AACd,UAAI,iCAAiC,GAAG;AACtC,cAAM;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACF;AAOA,SAAS,gBAAgB,UAAmB,OAA8B;AACxE,MAAI,CAAC,YAAY,OAAO,aAAa,YAAY,MAAM,QAAQ,QAAQ,GAAG;AACxE,UAAM,WAAyB,EAAE,aAAa,MAAM;AACpD,QAAI,aAAa,OAAW,UAAS,QAAQ;AAC7C,WAAO;AAAA,EACT;AACA,QAAM,UAAU;AAChB,MAAI,iBAAiB,WAAW,QAAQ,gBAAgB,QAAW;AACjE,WAAO;AAAA,EACT;AACA,SAAO,EAAE,aAAa,OAAO,GAAG,QAAQ;AAC1C;",
|
|
4
|
+
"sourcesContent": ["import type { ActionLog } from '@open-mercato/core/modules/audit_logs/data/entities'\nimport type { ActionLogCreateInput } from '@open-mercato/core/modules/audit_logs/data/validators'\nimport { commandRegistry } from './registry'\nimport type {\n BulkImportSuppression,\n CommandExecutionOptions,\n CommandExecuteResult,\n CommandHandler,\n CommandLogBuilderArgs,\n CommandLogMetadata,\n CommandRuntimeContext,\n CommandUndoLogEntry,\n} from './types'\nimport { defaultUndoToken } from './types'\nimport type { AwilixContainer } from 'awilix'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport {\n canonicalizeResourceTag,\n deriveResourceFromCommandId,\n invalidateCrudCache,\n pickFirstIdentifier,\n isCrudCacheDebugEnabled,\n} from '@open-mercato/shared/lib/crud/cache'\nimport { normalizeCustomFieldKey } from '@open-mercato/shared/lib/custom-fields/keys'\nimport { getAllCommandInterceptorInstances } from './command-interceptor-store'\nimport {\n runCommandInterceptorsBefore,\n runCommandInterceptorsAfter,\n runCommandInterceptorsBeforeUndo,\n runCommandInterceptorsAfterUndo,\n} from './command-interceptor-runner'\nimport type { CommandInterceptorContext } from './command-interceptor'\nimport { CommandInterceptorError } from './errors'\nimport { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'\nimport { createLogger } from '../logger'\nimport { withAtomicFlush } from './flush'\nimport { getTelemetryRuntime } from '../telemetry/runtime'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n getTransactionLifetime,\n onTransactionLifetimeComplete,\n ownsTransactionLifetime,\n type TransactionLifetime,\n} from './transaction-lifetime'\n\nconst logger = createLogger('shared').child({ component: 'commands' })\n\ntype CommandActionLogService = {\n findByUndoToken(undoToken: string): Promise<ActionLog | null>\n claimForUndo(id: string, transactionalEm?: EntityManager): Promise<boolean>\n releaseUndoClaim(id: string, transactionalEm?: EntityManager): Promise<boolean>\n markUndone(id: string, traceInput?: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null | void>\n claimForRedo(id: string, transactionalEm?: EntityManager): Promise<boolean>\n releaseRedoClaim?(id: string, transactionalEm?: EntityManager): Promise<boolean>\n log(input: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null>\n}\n\ntype AtomicReplayTransaction = {\n em: EntityManager\n joinsAmbient: boolean\n}\n\nfunction isInTransaction(em: EntityManager): boolean {\n const probe = (em as { isInTransaction?: () => boolean }).isInTransaction\n return typeof probe === 'function' && probe.call(em)\n}\n\nfunction resolveAtomicReplayTransaction(ctx: CommandRuntimeContext): AtomicReplayTransaction {\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager)\n const joinsAmbient = isInTransaction(em)\n if (joinsAmbient && !ownsTransactionLifetime(em, ctx.transactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay requires its outer transaction lifetime owner')\n }\n return { em, joinsAmbient }\n}\n\nfunction bindReplayTransactionContext(\n ctx: CommandRuntimeContext,\n em: EntityManager,\n expectedLifetime?: TransactionLifetime,\n): CommandRuntimeContext {\n const transactionLifetime = getTransactionLifetime(em)\n if (!transactionLifetime || (expectedLifetime && transactionLifetime !== expectedLifetime)) {\n throw new Error('[internal] Atomic replay transaction lifetime owner changed before replay')\n }\n return { ...ctx, transactionalEm: em, transactionLifetime }\n}\n\nconst SKIPPED_ACTION_LOG_RESOURCE_KINDS = new Set<string>([\n 'audit_logs.access',\n 'audit_logs.action',\n 'dashboards.layout',\n 'dashboards.user_widgets',\n 'dashboards.role_widgets',\n])\n\nfunction asRecord(input: unknown): Record<string, unknown> | null {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return null\n return input as Record<string, unknown>\n}\n\n/** Command handlers often return domain keys (e.g. warehouseId) without `id`; cache invalidation must still resolve the record. */\nfunction extractPrimaryIdFromCommandResult(result: unknown): string | null {\n const r = asRecord(result)\n if (!r) return null\n const direct = pickFirstIdentifier(r.id, r.entityId, r.recordId)\n if (direct) return direct\n for (const key of [\n 'warehouseId',\n 'zoneId',\n 'locationId',\n 'lotId',\n 'reservationId',\n 'profileId',\n 'movementId',\n 'balanceId',\n ]) {\n const v = r[key]\n if (typeof v === 'string' && v.trim().length > 0) return v.trim()\n }\n return null\n}\n\nfunction toISOString(value: unknown): string | null {\n if (value instanceof Date) {\n const iso = value.toISOString()\n return Number.isNaN(value.getTime()) ? null : iso\n }\n if (typeof value === 'string') {\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction deepEqual(a: unknown, b: unknown, seen?: Set<unknown>): boolean {\n if (Object.is(a, b)) return true\n if (a instanceof Date || b instanceof Date) {\n const aIso = toISOString(a)\n const bIso = toISOString(b)\n if (aIso != null && bIso != null) return aIso === bIso\n return false\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((value, index) => deepEqual(value, b[index], seen))\n }\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n if (!seen) seen = new Set()\n // `seen` is the current path: an object met again on it is a cycle. An object reached twice by\n // different paths (the items of one array held under two keys) is compared like any other.\n if (seen.has(a) || seen.has(b)) return false\n seen.add(a)\n seen.add(b)\n try {\n const aRec = a as Record<string, unknown>\n const bRec = b as Record<string, unknown>\n const keysA = Object.keys(aRec)\n const keysB = Object.keys(bRec)\n if (keysA.length !== keysB.length) return false\n return keysA.every((key) => deepEqual(aRec[key], bRec[key], seen))\n } finally {\n seen.delete(a)\n seen.delete(b)\n }\n }\n return false\n}\n\nconst CUSTOM_FIELD_CONTAINER_KEYS = new Set(['custom', 'customFields', 'customValues', 'cf'])\nconst SKIPPED_CHANGE_KEYS = new Set(['updatedAt', 'updated_at'])\n\nfunction appendCustomFieldChanges(\n changes: Record<string, { from: unknown; to: unknown }>,\n before: unknown,\n after: unknown\n): boolean {\n const beforeRec = asRecord(before)\n const afterRec = asRecord(after)\n if (!beforeRec && !afterRec) return false\n const left = beforeRec ?? {}\n const right = afterRec ?? {}\n const keys = new Set([...Object.keys(left), ...Object.keys(right)])\n for (const key of keys) {\n const from = left[key]\n const to = right[key]\n if (!deepEqual(from, to)) {\n changes[normalizeCustomFieldKey(key)] = { from, to }\n }\n }\n return true\n}\n\nfunction buildRecordChanges(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): Record<string, { from: unknown; to: unknown }> {\n return buildRecordChangesDeep(before, after)\n}\n\nfunction buildRecordChangesDeep(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n prefix?: string,\n seen?: Set<unknown>,\n): Record<string, { from: unknown; to: unknown }> {\n const changes: Record<string, { from: unknown; to: unknown }> = {}\n if (!seen) seen = new Set()\n if (seen.has(before) || seen.has(after)) return changes\n seen.add(before)\n seen.add(after)\n const keys = new Set([...Object.keys(before), ...Object.keys(after)])\n for (const key of keys) {\n if (SKIPPED_CHANGE_KEYS.has(key)) continue\n if (CUSTOM_FIELD_CONTAINER_KEYS.has(key)) {\n const handled = appendCustomFieldChanges(changes, before[key], after[key])\n if (handled) continue\n }\n const from = before[key]\n const to = after[key]\n const path = prefix ? `${prefix}.${key}` : key\n const fromRec = asRecord(from)\n const toRec = asRecord(to)\n if (fromRec && toRec) {\n const nested = buildRecordChangesDeep(fromRec, toRec, path, seen)\n if (Object.keys(nested).length) {\n Object.assign(changes, nested)\n continue\n }\n }\n if (!deepEqual(from, to)) {\n changes[path] = { from, to }\n }\n }\n return changes\n}\n\nfunction deriveChangesFromSnapshots(\n before: unknown,\n after: unknown,\n): Record<string, { from: unknown; to: unknown }> | null {\n const beforeRec = asRecord(before)\n const afterRec = asRecord(after)\n if (!beforeRec || !afterRec) return null\n const changes = buildRecordChanges(beforeRec, afterRec)\n return Object.keys(changes).length ? changes : null\n}\n\nfunction invertRecordedChanges(\n changes: unknown,\n): Record<string, { from: unknown; to: unknown }> | null {\n const source = asRecord(changes)\n if (!source) return null\n const inverted: Record<string, { from: unknown; to: unknown }> = {}\n for (const [key, value] of Object.entries(source)) {\n const entry = asRecord(value)\n if (!entry || (!('from' in entry) && !('to' in entry))) continue\n inverted[key] = {\n from: entry.to,\n to: entry.from,\n }\n }\n return Object.keys(inverted).length ? inverted : null\n}\n\nfunction extractAliasList(source: unknown): string[] {\n if (!source || typeof source !== 'object' || Array.isArray(source)) return []\n const record = source as Record<string, unknown>\n const raw = record.cacheAliases\n if (!Array.isArray(raw)) return []\n const aliases = new Set<string>()\n for (const value of raw) {\n if (typeof value !== 'string') continue\n const normalized = canonicalizeResourceTag(value)\n if (normalized) aliases.add(normalized)\n }\n return Array.from(aliases)\n}\n\nexport class CommandBus {\n async execute<TInput = unknown, TResult = unknown>(\n commandId: string,\n options: CommandExecutionOptions<TInput>\n ): Promise<CommandExecuteResult<TResult>> {\n const handler = await this.resolveHandler<TInput, TResult>(commandId)\n\n const replayLogEntry = options.redoLogEntry ?? null\n const isAtomicReplay = replayLogEntry !== null && handler.atomicReplay === true\n const allInterceptors = getAllCommandInterceptorInstances()\n let interceptorMetadata = new Map<string, Record<string, unknown>>()\n let effectiveOptions = options\n let userFeatures: string[] = []\n const runBeforeExecuteInterceptors = async (baseOptions: CommandExecutionOptions<TInput>) => {\n const resolvedUserFeatures = allInterceptors.length\n ? await this.resolveUserFeaturesForInterceptors(baseOptions.ctx)\n : []\n if (!allInterceptors.length) {\n return {\n effectiveOptions: baseOptions,\n metadata: new Map<string, Record<string, unknown>>(),\n userFeatures: resolvedUserFeatures,\n }\n }\n const interceptorCtx: CommandInterceptorContext = {\n commandId,\n auth: baseOptions.ctx.auth ?? null,\n selectedOrganizationId: baseOptions.ctx.selectedOrganizationId ?? baseOptions.ctx.auth?.orgId ?? null,\n container: baseOptions.ctx.container,\n organizationScope: baseOptions.ctx.organizationScope ?? null,\n request: baseOptions.ctx.request ?? null,\n }\n const beforeResult = await runCommandInterceptorsBefore(\n allInterceptors, commandId, baseOptions.input, interceptorCtx, resolvedUserFeatures,\n )\n if (!beforeResult.ok) {\n const blocked = beforeResult.error!\n throw new CommandInterceptorError(blocked.message, { status: blocked.status, body: blocked.body })\n }\n const preparedOptions = beforeResult.modifiedInput\n ? {\n ...baseOptions,\n input: { ...(baseOptions.input as object), ...beforeResult.modifiedInput } as TInput,\n }\n : baseOptions\n return {\n effectiveOptions: preparedOptions,\n metadata: beforeResult.metadataByInterceptor,\n userFeatures: resolvedUserFeatures,\n }\n }\n\n if (replayLogEntry && !isAtomicReplay) {\n await this.runReplayTransactionGuard(options.ctx, 'redo', replayLogEntry)\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'redo',\n input: options.input,\n ctx: options.ctx,\n logEntry: replayLogEntry,\n })\n }\n }\n\n if (!isAtomicReplay) {\n const prepared = await runBeforeExecuteInterceptors(options)\n effectiveOptions = prepared.effectiveOptions\n interceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n }\n\n const executeCore = async (coreOptions: CommandExecutionOptions<TInput>) => {\n const snapshots: { before?: unknown } = {}\n let executionOptions = coreOptions\n if (handler.prepareSnapshotInsideTransaction && handler.prepare) {\n const prepare = handler.prepare\n const originalCtx = coreOptions.ctx\n const originalBeforeTransactionalWrite = originalCtx.beforeTransactionalWrite\n let prepared = false\n let transactionalCtx: CommandRuntimeContext\n transactionalCtx = {\n ...originalCtx,\n beforeTransactionalWrite: async (em, input) => {\n await originalBeforeTransactionalWrite?.(em, input)\n if (prepared) return\n Object.assign(\n snapshots,\n (await prepare(coreOptions.input, { ...transactionalCtx, transactionalEm: em })) ?? {},\n )\n prepared = true\n },\n }\n executionOptions = { ...coreOptions, ctx: transactionalCtx }\n } else {\n Object.assign(snapshots, await this.prepareSnapshots(handler, coreOptions))\n }\n effectiveOptions = executionOptions\n const sourceLog = executionOptions.redoLogEntry ?? null\n const result =\n sourceLog && typeof handler.redo === 'function'\n ? await handler.redo({ input: executionOptions.input, ctx: executionOptions.ctx, logEntry: sourceLog })\n : await handler.execute(executionOptions.input, executionOptions.ctx)\n const afterSnapshot = await this.captureAfter(handler, executionOptions, result)\n const snapshotsWithAfter = { ...snapshots, after: afterSnapshot }\n const logMeta = await this.buildLog(handler, executionOptions, result, snapshotsWithAfter)\n let mergedMeta = this.mergeMetadata(executionOptions.metadata, logMeta)\n // Interceptors opt into audit-log enrichment with a reserved `logContext` key rather\n // than the generic `context` one, so the metadata an interceptor already passes to its\n // own afterExecute hook is never silently promoted into audit storage.\n // Map iteration order is interceptor priority order (see collectMatching), so a\n // later-priority interceptor overrides an earlier one on key collisions.\n let interceptorContextMerged: Record<string, unknown> = {}\n for (const meta of interceptorMetadata.values()) {\n const logContextRecord = asRecord(asRecord(meta)?.logContext)\n if (!logContextRecord) continue\n interceptorContextMerged = {\n ...interceptorContextMerged,\n ...logContextRecord,\n }\n }\n const baseContext = asRecord(executionOptions.metadata?.context) ?? {}\n const logMetaContext = asRecord(logMeta?.context) ?? {}\n if (Object.keys(interceptorContextMerged).length > 0 || Object.keys(baseContext).length > 0 || Object.keys(logMetaContext).length > 0) {\n mergedMeta = mergedMeta ?? {}\n mergedMeta.context = {\n ...baseContext,\n ...interceptorContextMerged,\n ...logMetaContext,\n }\n }\n const undoable = this.isUndoable(handler)\n if (undoable && mergedMeta?.replayable !== false) {\n mergedMeta = mergedMeta ?? {}\n if (!mergedMeta.undoToken) mergedMeta.undoToken = defaultUndoToken()\n if (mergedMeta.actorUserId === undefined) mergedMeta.actorUserId = executionOptions.ctx.auth?.sub ?? null\n } else if (mergedMeta?.replayable === false) {\n mergedMeta.undoToken = null\n }\n if (afterSnapshot !== undefined && afterSnapshot !== null) {\n if (!mergedMeta) {\n mergedMeta = { snapshotAfter: afterSnapshot }\n } else if (!mergedMeta.snapshotAfter) {\n mergedMeta.snapshotAfter = afterSnapshot\n }\n }\n if (snapshots.before) {\n if (!mergedMeta) {\n mergedMeta = { snapshotBefore: snapshots.before }\n } else if (!mergedMeta.snapshotBefore) {\n mergedMeta.snapshotBefore = snapshots.before\n }\n }\n if (mergedMeta?.snapshotBefore !== undefined && mergedMeta?.snapshotAfter !== undefined) {\n const currentChanges = mergedMeta.changes\n const shouldInfer =\n currentChanges === undefined ||\n currentChanges === null ||\n (typeof currentChanges === 'object' && !Array.isArray(currentChanges) && Object.keys(currentChanges).length === 0)\n if (shouldInfer) {\n const inferred = deriveChangesFromSnapshots(mergedMeta.snapshotBefore, mergedMeta.snapshotAfter)\n if (inferred) mergedMeta.changes = inferred\n }\n }\n const logEntry = await this.persistLog(commandId, executionOptions, mergedMeta)\n return { result, mergedMeta, logEntry }\n }\n\n let replaySourceFinalized = false\n let coreResult: Awaited<ReturnType<typeof executeCore>>\n const atomicSourceLog = options.redoLogEntry ?? null\n let ambientReplay: AtomicReplayTransaction | null = null\n let replayTransactionLifetime: TransactionLifetime | null = null\n if (atomicSourceLog && isAtomicReplay) {\n ambientReplay = resolveAtomicReplayTransaction(options.ctx)\n const replayEm = ambientReplay.em\n await withAtomicFlush(replayEm, [async () => {\n const replayCtx = bindReplayTransactionContext(\n options.ctx,\n replayEm,\n ambientReplay?.joinsAmbient ? options.ctx.transactionLifetime : undefined,\n )\n replayTransactionLifetime = replayCtx.transactionLifetime ?? null\n const transactionalBaseOptions: CommandExecutionOptions<TInput> = {\n ...options,\n ctx: replayCtx,\n }\n if (!atomicSourceLog.id) throw new Error('[internal] Atomic redo source log id is required')\n if (handler.stabilizeReplay) {\n await handler.stabilizeReplay({\n operation: 'redo',\n input: transactionalBaseOptions.input,\n ctx: transactionalBaseOptions.ctx,\n logEntry: atomicSourceLog,\n })\n }\n await this.runReplayTransactionGuard(\n transactionalBaseOptions.ctx,\n 'redo',\n atomicSourceLog,\n replayEm,\n )\n const prepared = await runBeforeExecuteInterceptors(transactionalBaseOptions)\n effectiveOptions = prepared.effectiveOptions\n interceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n const service = effectiveOptions.ctx.container.resolve('actionLogService') as CommandActionLogService\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'redo',\n input: effectiveOptions.input,\n ctx: effectiveOptions.ctx,\n logEntry: atomicSourceLog,\n })\n }\n const claimed = await service.claimForRedo(atomicSourceLog.id, replayEm)\n if (!claimed) throw new Error('[internal] Redo source already consumed')\n coreResult = await executeCore(effectiveOptions)\n }], { transaction: true, label: `${commandId}.redo` })\n replaySourceFinalized = !ambientReplay.joinsAmbient\n } else if (replayLogEntry?.id) {\n const redoClaimRelease = await this.claimRedoSource(effectiveOptions.ctx, commandId, replayLogEntry.id)\n try {\n coreResult = await executeCore(effectiveOptions)\n } catch (err) {\n await redoClaimRelease?.()\n throw err\n }\n replaySourceFinalized = redoClaimRelease !== null\n } else {\n coreResult = await executeCore(effectiveOptions)\n }\n const { result, mergedMeta, logEntry } = coreResult!\n\n const runPostCommit = async () => {\n let finalResult = result\n if (allInterceptors.length) {\n const interceptorCtx: CommandInterceptorContext = {\n commandId,\n auth: effectiveOptions.ctx.auth ?? null,\n selectedOrganizationId: effectiveOptions.ctx.selectedOrganizationId ?? effectiveOptions.ctx.auth?.orgId ?? null,\n container: effectiveOptions.ctx.container,\n organizationScope: effectiveOptions.ctx.organizationScope ?? null,\n request: effectiveOptions.ctx.request ?? null,\n }\n const afterResult = await runCommandInterceptorsAfter(\n allInterceptors, commandId, effectiveOptions.input, result, interceptorCtx,\n userFeatures, interceptorMetadata,\n )\n if (afterResult.modifiedResult && typeof result === 'object' && result) {\n finalResult = { ...(result as object), ...afterResult.modifiedResult } as Awaited<TResult>\n }\n }\n\n if (!effectiveOptions.skipCacheInvalidation) {\n await this.invalidateCacheAfterExecute(commandId, effectiveOptions, finalResult, mergedMeta)\n }\n // Bulk-import backfills defer heavy per-record side effects: the ctx flags are read here and\n // threaded as a local into the flush (never stored on the shared dataEngine), so a concurrent\n // command with different flags can't observe them. Reindex is restored by the caller's\n // end-of-run `query_index rebuild`. Mirrors `skipCacheInvalidation` above.\n await this.flushCrudSideEffects(effectiveOptions.ctx.container, effectiveOptions.ctx?.bulkImport)\n return finalResult\n }\n\n const executionResult: CommandExecuteResult<TResult> = {\n result,\n logEntry,\n replaySourceFinalized,\n }\n if (ambientReplay?.joinsAmbient) {\n if (!replayTransactionLifetime || !ownsTransactionLifetime(ambientReplay.em, replayTransactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay lost its outer transaction lifetime owner')\n }\n onTransactionLifetimeComplete(ambientReplay.em, async (outcome) => {\n if (outcome !== 'committed') return\n executionResult.result = await runPostCommit()\n executionResult.replaySourceFinalized = true\n })\n return executionResult\n }\n\n executionResult.result = await runPostCommit()\n return executionResult\n }\n\n async undo(undoToken: string, ctx: CommandRuntimeContext): Promise<void> {\n const service = (ctx.container.resolve('actionLogService') as CommandActionLogService)\n const log = await service.findByUndoToken(undoToken)\n if (!log) throw new Error('Undo token expired or not found')\n const handler = await this.resolveHandler(log.commandId)\n if (!handler.undo || this.isUndoable(handler) === false) {\n throw new Error(`Command ${log.commandId} is not undoable`)\n }\n\n const isAtomicReplay = handler.atomicReplay === true\n const allInterceptors = getAllCommandInterceptorInstances()\n let undoInterceptorMetadata = new Map<string, Record<string, unknown>>()\n let userFeatures: string[] = []\n const runBeforeUndoInterceptors = async (replayCtx: CommandRuntimeContext) => {\n const resolvedUserFeatures = allInterceptors.length\n ? await this.resolveUserFeaturesForInterceptors(replayCtx)\n : []\n if (!allInterceptors.length) {\n return {\n metadata: new Map<string, Record<string, unknown>>(),\n userFeatures: resolvedUserFeatures,\n }\n }\n const undoCtx = { input: log.commandPayload, logEntry: log, undoToken }\n const interceptorCtx: CommandInterceptorContext = {\n commandId: log.commandId,\n auth: replayCtx.auth ?? null,\n selectedOrganizationId: replayCtx.selectedOrganizationId ?? replayCtx.auth?.orgId ?? null,\n container: replayCtx.container,\n organizationScope: replayCtx.organizationScope ?? null,\n request: replayCtx.request ?? null,\n }\n const beforeResult = await runCommandInterceptorsBeforeUndo(\n allInterceptors, log.commandId, undoCtx, interceptorCtx, resolvedUserFeatures,\n )\n if (!beforeResult.ok) {\n const blocked = beforeResult.error!\n throw new CommandInterceptorError(blocked.message, { status: blocked.status, body: blocked.body })\n }\n return {\n metadata: beforeResult.metadataByInterceptor,\n userFeatures: resolvedUserFeatures,\n }\n }\n\n if (!isAtomicReplay) {\n await this.runReplayTransactionGuard(ctx, 'undo', log)\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.authorizeReplay>>[0]['input'],\n ctx,\n logEntry: log,\n })\n }\n }\n\n const claimUndo = async (replayEm?: EntityManager) => {\n // Two contenders can both pass the initial lookup; only the compare-and-set\n // below may proceed. On the atomic path this state is still uncommitted and\n // rolls back with every handler/log write if anything later fails.\n const claimed = replayEm\n ? await service.claimForUndo(log.id, replayEm)\n : await service.claimForUndo(log.id)\n if (!claimed) throw new Error('[internal] Undo token already consumed')\n }\n const finishUndo = async (replayCtx: CommandRuntimeContext, replayEm?: EntityManager) => {\n await handler.undo!({\n input: log.commandPayload as Parameters<NonNullable<typeof handler.undo>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n const traceLog = this.buildUndoTraceLog(log, replayCtx)\n if (replayEm) {\n await service.markUndone(log.id, traceLog, replayEm)\n } else {\n await service.markUndone(log.id, traceLog)\n }\n }\n\n let ambientReplay: AtomicReplayTransaction | null = null\n let replayTransactionLifetime: TransactionLifetime | null = null\n if (isAtomicReplay) {\n ambientReplay = resolveAtomicReplayTransaction(ctx)\n const replayEm = ambientReplay.em\n await withAtomicFlush(replayEm, [async () => {\n const replayCtx = bindReplayTransactionContext(\n ctx,\n replayEm,\n ambientReplay?.joinsAmbient ? ctx.transactionLifetime : undefined,\n )\n replayTransactionLifetime = replayCtx.transactionLifetime ?? null\n if (handler.stabilizeReplay) {\n await handler.stabilizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.stabilizeReplay>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n }\n await this.runReplayTransactionGuard(replayCtx, 'undo', log, replayEm)\n const prepared = await runBeforeUndoInterceptors(replayCtx)\n undoInterceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n if (handler.authorizeReplay) {\n await handler.authorizeReplay({\n operation: 'undo',\n input: log.commandPayload as Parameters<NonNullable<typeof handler.authorizeReplay>>[0]['input'],\n ctx: replayCtx,\n logEntry: log,\n })\n }\n await claimUndo(replayEm)\n await finishUndo(replayCtx, replayEm)\n }], {\n transaction: true,\n label: `${log.commandId}.undo`,\n })\n } else {\n let undoClaimed = false\n try {\n // Preserve the established non-atomic lifecycle exactly: authorization,\n // source claim, before-undo interceptors, handler, then finalization.\n await claimUndo()\n undoClaimed = true\n const prepared = await runBeforeUndoInterceptors(ctx)\n undoInterceptorMetadata = prepared.metadata\n userFeatures = prepared.userFeatures\n await finishUndo(ctx)\n } catch (err) {\n // Legacy handlers retain their compensating release behavior because\n // their domain mutation may not share the action-log transaction.\n if (undoClaimed) {\n await service.releaseUndoClaim(log.id).catch((releaseErr: unknown) => {\n logger.error('Failed to release undo claim', { commandId: log.commandId, logId: log.id, err: releaseErr })\n getTelemetryRuntime()?.reportError(releaseErr, {\n module: 'shared',\n code: 'shared.undo_claim_release_failed',\n })\n })\n }\n throw err\n }\n }\n\n const runPostCommit = async () => {\n // Post-commit hooks and side effects run only after an atomic replay has\n // durably committed both the domain state and source/trace log state.\n if (allInterceptors.length) {\n const undoCtx = { input: log.commandPayload, logEntry: log, undoToken }\n const interceptorCtx: CommandInterceptorContext = {\n commandId: log.commandId,\n auth: ctx.auth ?? null,\n selectedOrganizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n container: ctx.container,\n organizationScope: ctx.organizationScope ?? null,\n request: ctx.request ?? null,\n }\n await runCommandInterceptorsAfterUndo(\n allInterceptors, log.commandId, undoCtx, interceptorCtx,\n userFeatures, undoInterceptorMetadata,\n )\n }\n\n await this.invalidateCacheAfterUndo(log, ctx)\n await this.flushCrudSideEffects(ctx.container)\n }\n\n if (ambientReplay?.joinsAmbient) {\n if (!replayTransactionLifetime || !ownsTransactionLifetime(ambientReplay.em, replayTransactionLifetime)) {\n throw new Error('[internal] Ambient atomic replay lost its outer transaction lifetime owner')\n }\n onTransactionLifetimeComplete(ambientReplay.em, async (outcome) => {\n if (outcome === 'committed') await runPostCommit()\n })\n return\n }\n\n await runPostCommit()\n }\n\n private buildUndoTraceLog(log: ActionLog, ctx: CommandRuntimeContext): ActionLogCreateInput | undefined {\n const snapshotBefore = log.snapshotAfter ?? null\n const snapshotAfter = log.snapshotBefore ?? null\n const changes =\n deriveChangesFromSnapshots(snapshotBefore, snapshotAfter)\n ?? invertRecordedChanges(log.changesJson)\n ?? undefined\n\n const baseContext = asRecord(log.contextJson) ?? {}\n const context = {\n ...baseContext,\n historyAction: 'undo',\n sourceLogId: log.id,\n sourceCommandId: log.commandId,\n }\n\n return {\n tenantId: log.tenantId ?? ctx.auth?.tenantId ?? null,\n organizationId: log.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n actorUserId: ctx.auth?.sub ?? log.actorUserId ?? null,\n commandId: log.commandId,\n actionLabel: log.actionLabel ?? undefined,\n resourceKind: log.resourceKind ?? undefined,\n resourceId: log.resourceId ?? undefined,\n parentResourceKind: log.parentResourceKind ?? null,\n parentResourceId: log.parentResourceId ?? null,\n relatedResourceKind: log.relatedResourceKind ?? null,\n relatedResourceId: log.relatedResourceId ?? null,\n snapshotBefore,\n snapshotAfter,\n changes,\n context,\n }\n }\n\n private async resolveUserFeaturesForInterceptors(ctx: CommandRuntimeContext): Promise<string[]> {\n if (!ctx.auth) return []\n type RbacLike = {\n getGrantedFeatures: (\n userId: string,\n opts: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n getGrantedFeaturesWithEntityManager?: (\n em: EntityManager,\n userId: string,\n opts: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n }\n let rbac: RbacLike | undefined\n try {\n rbac = ctx.container.resolve('rbacService') as RbacLike | undefined\n } catch {\n // Intentional: rbacService is not registered in all runtime contexts (CLI, tests, bootstrap).\n return []\n }\n const scope = {\n tenantId: ctx.auth.tenantId,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth.orgId,\n }\n if (ctx.transactionalEm) {\n if (!rbac?.getGrantedFeaturesWithEntityManager) return []\n return await rbac.getGrantedFeaturesWithEntityManager(\n ctx.transactionalEm,\n ctx.auth.sub,\n scope,\n )\n }\n try {\n if (rbac?.getGrantedFeatures) {\n return await rbac.getGrantedFeatures(ctx.auth.sub, scope)\n }\n } catch {\n // Outside a transaction a failed lookup cannot poison anything; interceptors without\n // feature gating still run. Inside one the error is rethrown above, because the failed\n // query has already aborted the transaction.\n }\n return []\n }\n\n private async runReplayTransactionGuard(\n ctx: CommandRuntimeContext,\n operation: 'undo' | 'redo',\n logEntry: CommandUndoLogEntry,\n transactionalEm?: EntityManager,\n ): Promise<void> {\n if (!ctx.replayTransactionGuard) return\n if (transactionalEm) {\n await ctx.replayTransactionGuard({ operation, logEntry, transactionalEm })\n return\n }\n const requestEm = ctx.container.resolve('em') as EntityManager\n const guardEm = typeof requestEm.fork === 'function' ? requestEm.fork() : requestEm\n await withAtomicFlush(guardEm, [async () => {\n await ctx.replayTransactionGuard!({ operation, logEntry, transactionalEm: guardEm })\n }], { transaction: true, label: `${logEntry.commandId}.${operation}.request-guard` })\n }\n\n private async claimRedoSource(\n ctx: CommandRuntimeContext,\n commandId: string,\n sourceLogId: string,\n ): Promise<(() => Promise<void>) | null> {\n let service: CommandActionLogService | null = null\n try {\n service = ctx.container.resolve('actionLogService') as CommandActionLogService\n } catch {\n service = null\n }\n if (!service || typeof service.claimForRedo !== 'function' || typeof service.releaseRedoClaim !== 'function') {\n logger.warn('Redo source claim unavailable; replaying without an atomic claim', { commandId, sourceLogId })\n return null\n }\n const releaseClaim = service.releaseRedoClaim.bind(service)\n const transactionalEm = ctx.transactionalEm\n const claimed = transactionalEm\n ? await service.claimForRedo(sourceLogId, transactionalEm)\n : await service.claimForRedo(sourceLogId)\n if (!claimed) throw new Error('[internal] Redo source already consumed')\n return async () => {\n try {\n const released = transactionalEm\n ? await releaseClaim(sourceLogId, transactionalEm)\n : await releaseClaim(sourceLogId)\n if (!released) logger.warn('Redo source claim was not held at release', { commandId, sourceLogId })\n } catch (releaseErr) {\n logger.error('Failed to release redo source claim', { commandId, sourceLogId, err: releaseErr })\n getTelemetryRuntime()?.reportError(releaseErr, {\n module: 'shared',\n code: 'shared.redo_claim_release_failed',\n })\n }\n }\n }\n\n private async resolveHandler<TInput, TResult>(commandId: string): Promise<CommandHandler<TInput, TResult>> {\n const handler =\n commandRegistry.get<TInput, TResult>(commandId) ??\n ((await commandRegistry.load(commandId)) as CommandHandler<TInput, TResult> | null)\n if (!handler) {\n const moduleName = commandId.split('.')[0]\n const registered = commandRegistry.list()\n const sameModule = registered.filter((id) => id.split('.')[0] === moduleName)\n const registeredLoaders = commandRegistry.listLoaders()\n const sameModuleLoaders = registeredLoaders.filter((id) => id === commandId || id.startsWith(`${moduleName}:`))\n const hint = sameModule.length > 0\n ? ` Registered commands for module \"${moduleName}\": [${sameModule.join(', ')}].`\n : sameModuleLoaders.length > 0\n ? ` Command loaders for module \"${moduleName}\" were registered but none loaded \"${commandId}\".`\n : ` No commands or command loaders registered for module \"${moduleName}\". Ensure the command file is imported or generated lazy command loaders are registered.`\n throw new Error(`Command handler not registered for id ${commandId}.${hint}`)\n }\n return handler\n }\n\n private async prepareSnapshots<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>\n ): Promise<{ before?: unknown }> {\n if (!handler.prepare) return {}\n try {\n return (await handler.prepare(options.input, options.ctx)) || {}\n } catch (err) {\n throw err\n }\n }\n\n private async captureAfter<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>,\n result: TResult\n ): Promise<unknown> {\n if (!handler.captureAfter) return undefined\n return handler.captureAfter(options.input, result, options.ctx)\n }\n\n private async buildLog<TInput, TResult>(\n handler: CommandHandler<TInput, TResult>,\n options: CommandExecutionOptions<TInput>,\n result: TResult,\n snapshots: { before?: unknown; after?: unknown }\n ): Promise<CommandLogMetadata | null> {\n if (!handler.buildLog) return null\n const args: CommandLogBuilderArgs<TInput, TResult> = {\n input: options.input,\n result,\n ctx: options.ctx,\n snapshots,\n }\n return (await handler.buildLog(args)) || null\n }\n\n private mergeMetadata(primary?: CommandLogMetadata | null, secondary?: CommandLogMetadata | null): CommandLogMetadata | null {\n if (!primary && !secondary) return null\n return {\n skipLog: secondary?.skipLog ?? primary?.skipLog ?? false,\n replayable:\n secondary?.replayable === false || primary?.replayable === false\n ? false\n : secondary?.replayable ?? primary?.replayable,\n tenantId: secondary?.tenantId ?? primary?.tenantId ?? null,\n organizationId: secondary?.organizationId ?? primary?.organizationId ?? null,\n actorUserId: secondary?.actorUserId ?? primary?.actorUserId ?? null,\n onBehalfOfUserId: secondary?.onBehalfOfUserId ?? primary?.onBehalfOfUserId ?? null,\n actionLabel: secondary?.actionLabel ?? primary?.actionLabel ?? null,\n resourceKind: secondary?.resourceKind ?? primary?.resourceKind ?? null,\n resourceId: secondary?.resourceId ?? primary?.resourceId ?? null,\n parentResourceKind: secondary?.parentResourceKind ?? primary?.parentResourceKind ?? null,\n parentResourceId: secondary?.parentResourceId ?? primary?.parentResourceId ?? null,\n relatedResourceKind: secondary?.relatedResourceKind ?? primary?.relatedResourceKind ?? null,\n relatedResourceId: secondary?.relatedResourceId ?? primary?.relatedResourceId ?? null,\n undoToken: secondary?.undoToken ?? primary?.undoToken ?? null,\n // A redacted redo input always wins: it exists precisely because the raw\n // input carries a secret that must not reach `action_logs`.\n redoInput: secondary?.redoInput !== undefined ? secondary.redoInput : primary?.redoInput,\n payload: secondary?.payload ?? primary?.payload ?? null,\n snapshotBefore: secondary?.snapshotBefore ?? primary?.snapshotBefore ?? null,\n snapshotAfter: secondary?.snapshotAfter ?? primary?.snapshotAfter ?? null,\n changes: secondary?.changes ?? primary?.changes ?? null,\n context: secondary?.context ?? primary?.context ?? null,\n }\n }\n\n private async persistLog<TInput>(\n commandId: string,\n options: CommandExecutionOptions<TInput>,\n metadata: CommandLogMetadata | null\n ): Promise<ActionLog | null> {\n if (!metadata) return null\n if (metadata.skipLog) return null\n const resourceKind =\n typeof metadata.resourceKind === 'string' ? metadata.resourceKind : null\n if (resourceKind && SKIPPED_ACTION_LOG_RESOURCE_KINDS.has(resourceKind)) {\n return null\n }\n let service: CommandActionLogService | null = null\n try {\n service = (options.ctx.container.resolve('actionLogService') as CommandActionLogService)\n } catch {\n service = null\n }\n if (!service) return null\n\n const tenantId = metadata.tenantId ?? options.ctx.auth?.tenantId ?? null\n const organizationId =\n metadata.organizationId ?? options.ctx.selectedOrganizationId ?? options.ctx.auth?.orgId ?? null\n // On-behalf-of attribution (Wave 4 P2): when `ctx.runAs` is set the actor is\n // the agent principal and the human it acts for is recorded separately. This\n // funnels agent writes through the SAME ActionLog path as a human's \u2014 only the\n // attribution differs (actorUserId=agent, onBehalfOfUserId=human, source='agent').\n const runAs = options.ctx.runAs ?? null\n const actorUserId = runAs?.actorUserId ?? metadata.actorUserId ?? options.ctx.auth?.sub ?? null\n const onBehalfOfUserId = runAs ? (runAs.onBehalfOfUserId ?? null) : (metadata.onBehalfOfUserId ?? null)\n const systemActorContext = !actorUserId && options.ctx.systemActor === true\n ? { systemActor: 'system:command' }\n : null\n const payload: Record<string, unknown> = {\n tenantId: tenantId ?? undefined,\n organizationId: organizationId ?? undefined,\n actorUserId: actorUserId ?? undefined,\n onBehalfOfUserId: onBehalfOfUserId ?? undefined,\n commandId,\n }\n\n if (metadata) {\n if ('actionLabel' in metadata && metadata.actionLabel != null) payload.actionLabel = metadata.actionLabel\n if ('resourceKind' in metadata && metadata.resourceKind != null) payload.resourceKind = metadata.resourceKind\n if ('resourceId' in metadata && metadata.resourceId != null) payload.resourceId = metadata.resourceId\n if ('parentResourceKind' in metadata && metadata.parentResourceKind != null) payload.parentResourceKind = metadata.parentResourceKind\n if ('parentResourceId' in metadata && metadata.parentResourceId != null) payload.parentResourceId = metadata.parentResourceId\n if ('relatedResourceKind' in metadata && metadata.relatedResourceKind != null) payload.relatedResourceKind = metadata.relatedResourceKind\n if ('relatedResourceId' in metadata && metadata.relatedResourceId != null) payload.relatedResourceId = metadata.relatedResourceId\n if ('undoToken' in metadata && metadata.undoToken != null) payload.undoToken = metadata.undoToken\n if ('payload' in metadata && metadata.payload !== undefined) payload.commandPayload = metadata.payload\n if ('snapshotBefore' in metadata && metadata.snapshotBefore !== undefined) payload.snapshotBefore = metadata.snapshotBefore\n if ('snapshotAfter' in metadata && metadata.snapshotAfter !== undefined) payload.snapshotAfter = metadata.snapshotAfter\n if ('changes' in metadata && metadata.changes !== undefined && metadata.changes !== null) payload.changes = metadata.changes\n if ('context' in metadata && metadata.context !== undefined && metadata.context !== null) {\n payload.context = { ...(systemActorContext ?? {}), ...metadata.context }\n } else if (systemActorContext) {\n payload.context = systemActorContext\n }\n }\n\n if (runAs) {\n // Stamp the audit source so `deriveActionLogSource` projects `sourceKey='agent'`.\n // Merge into any caller-provided context rather than replacing it.\n const baseContext = asRecord(payload.context) ?? {}\n payload.context = { ...baseContext, source: runAs.source }\n }\n\n if (metadata.replayable === false) {\n delete payload.commandPayload\n } else {\n const redoInput = metadata.redoInput !== undefined ? metadata.redoInput : options.input\n const redoEnvelope = wrapRedoPayload('commandPayload' in payload ? (payload.commandPayload as unknown) : undefined, redoInput)\n payload.commandPayload = redoEnvelope\n }\n\n return options.ctx.transactionalEm\n ? await service.log(payload as ActionLogCreateInput, options.ctx.transactionalEm)\n : await service.log(payload as ActionLogCreateInput)\n }\n\n private isUndoable(handler: CommandHandler<unknown, unknown>): boolean {\n return handler.isUndoable !== false && typeof handler.undo === 'function'\n }\n\n private async invalidateCacheAfterExecute<TResult>(\n commandId: string,\n options: CommandExecutionOptions<unknown>,\n result: TResult,\n metadata: CommandLogMetadata | null\n ): Promise<void> {\n const resource = typeof metadata?.resourceKind === 'string' ? metadata.resourceKind : null\n if (!resource) return\n try {\n const ctx = options.ctx\n const resultRecord = asRecord(result)\n const resultEntity = asRecord(resultRecord?.entity)\n const inputRecord = asRecord(options.input)\n const inputEntity = asRecord(inputRecord?.entity)\n\n const recordId = pickFirstIdentifier(\n metadata?.resourceId,\n extractPrimaryIdFromCommandResult(result),\n resultRecord?.entityId,\n resultRecord?.id,\n resultRecord?.recordId,\n resultEntity?.id,\n inputRecord?.id,\n inputRecord?.entityId,\n inputRecord?.recordId,\n inputEntity?.id\n )\n\n const organizationId = pickFirstIdentifier(\n metadata?.organizationId,\n resultRecord?.organizationId,\n resultEntity?.organizationId,\n inputRecord?.organizationId,\n inputEntity?.organizationId,\n ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n )\n\n const tenantId = pickFirstIdentifier(\n metadata?.tenantId,\n resultRecord?.tenantId,\n resultEntity?.tenantId,\n inputRecord?.tenantId,\n inputEntity?.tenantId,\n ctx.auth?.tenantId ?? null\n )\n\n const fallbackTenant = pickFirstIdentifier(metadata?.tenantId, ctx.auth?.tenantId ?? null)\n\n const aliasSet = new Set<string>()\n for (const alias of extractAliasList(metadata?.context ?? null)) {\n aliasSet.add(alias)\n }\n const derived = deriveResourceFromCommandId(commandId)\n if (derived) aliasSet.add(derived)\n const aliasExtras = Array.from(aliasSet)\n await invalidateCrudCache(\n ctx.container,\n resource,\n { id: recordId, organizationId, tenantId },\n fallbackTenant,\n `command:${commandId}:execute`,\n aliasExtras\n )\n } catch (err) {\n if (isCrudCacheDebugEnabled()) {\n try {\n logger.debug('Cache execute-invalidation failed', { commandId, err })\n } catch {}\n }\n }\n }\n\n private async invalidateCacheAfterUndo(log: ActionLog, ctx: CommandRuntimeContext): Promise<void> {\n const resource = typeof log.resourceKind === 'string' ? log.resourceKind : null\n if (!resource) return\n try {\n const recordId = pickFirstIdentifier(log.resourceId)\n const organizationId = pickFirstIdentifier(log.organizationId, ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null)\n const tenantId = pickFirstIdentifier(log.tenantId, ctx.auth?.tenantId ?? null)\n const fallbackTenant = pickFirstIdentifier(log.tenantId, ctx.auth?.tenantId ?? null)\n const aliasSet = new Set<string>()\n for (const alias of extractAliasList(log.contextJson ?? null)) {\n aliasSet.add(alias)\n }\n const derived = deriveResourceFromCommandId(log.commandId)\n if (derived) aliasSet.add(derived)\n const aliasExtras = Array.from(aliasSet)\n await invalidateCrudCache(\n ctx.container,\n resource,\n { id: recordId, organizationId, tenantId },\n fallbackTenant,\n `command:${log.commandId}:undo`,\n aliasExtras\n )\n } catch (err) {\n if (isCrudCacheDebugEnabled()) {\n try {\n logger.debug('Cache undo-invalidation failed', { commandId: log.commandId, err })\n } catch {}\n }\n }\n }\n\n private async flushCrudSideEffects(container: AwilixContainer, suppress?: BulkImportSuppression): Promise<void> {\n try {\n const dataEngine = (container.resolve('dataEngine') as DataEngine)\n await dataEngine.flushOrmEntityChanges(suppress)\n } catch (error) {\n if (isReadProjectionAlwaysConsistent()) {\n throw error\n }\n // best-effort: failures should not block command execution\n }\n }\n}\n\ntype RedoEnvelope = {\n __redoInput: unknown\n [key: string]: unknown\n}\n\nfunction wrapRedoPayload(existing: unknown, input: unknown): RedoEnvelope {\n if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {\n const envelope: RedoEnvelope = { __redoInput: input }\n if (existing !== undefined) envelope.value = existing\n return envelope\n }\n const current = existing as Record<string, unknown>\n if ('__redoInput' in current && current.__redoInput !== undefined) {\n return current as RedoEnvelope\n }\n return { __redoInput: input, ...current }\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,uBAAuB;AAWhC,SAAS,wBAAwB;AAGjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B;AACxC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,wCAAwC;AACjD,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,WAAW,CAAC;AAiBrE,SAAS,gBAAgB,IAA4B;AACnD,QAAM,QAAS,GAA2C;AAC1D,SAAO,OAAO,UAAU,cAAc,MAAM,KAAK,EAAE;AACrD;AAEA,SAAS,+BAA+B,KAAqD;AAC3F,QAAM,KAAK,IAAI,mBAAoB,IAAI,UAAU,QAAQ,IAAI;AAC7D,QAAM,eAAe,gBAAgB,EAAE;AACvC,MAAI,gBAAgB,CAAC,wBAAwB,IAAI,IAAI,mBAAmB,GAAG;AACzE,UAAM,IAAI,MAAM,gFAAgF;AAAA,EAClG;AACA,SAAO,EAAE,IAAI,aAAa;AAC5B;AAEA,SAAS,6BACP,KACA,IACA,kBACuB;AACvB,QAAM,sBAAsB,uBAAuB,EAAE;AACrD,MAAI,CAAC,uBAAwB,oBAAoB,wBAAwB,kBAAmB;AAC1F,UAAM,IAAI,MAAM,2EAA2E;AAAA,EAC7F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Q,GAAG;AACxE,UAAM,WAAyB,EAAE,aAAa,MAAM;AACpD,QAAI,aAAa,OAAW,UAAS,QAAQ;AAC7C,WAAO;AAAA,EACT;AACA,QAAM,UAAU;AAChB,MAAI,iBAAiB,WAAW,QAAQ,gBAAgB,QAAW;AACjE,WAAO;AAAA,EACT;AACA,SAAO,EAAE,aAAa,OAAO,GAAG,QAAQ;AAC1C;",
|
|
6
6
|
"names": ["result", "mergedMeta", "logEntry"]
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/commands/types.ts"],
|
|
4
|
-
"sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { ZodTypeAny } from 'zod'\nimport { randomUUID } from 'crypto'\nimport type { AuthContext } from '../auth/server'\nimport type { OrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { TransactionLifetime } from './transaction-lifetime'\n\n/**\n * Bulk-import / backfill deferral flags. When a command runs under a context that\n * carries this, the command bus and data engine suppress the heavy per-record side\n * effects flagged below so a large backfill can defer them to a single batched pass.\n *\n * IMPORTANT \u2014 the caller owns restoring whatever it suppresses. With `skipReindex`\n * the `query_index` projection (and its search tokens) is stale for every record\n * written under this context until the caller runs a batched `query_index rebuild`\n * for the affected entity types at end-of-run.\n *\n * Concurrency: these flags are read from the context and threaded as a local\n * parameter through the side-effect flush \u2014 no shared engine state is mutated \u2014 so\n * two commands running concurrently with different flags never clobber each other.\n */\nexport type BulkImportSuppression = {\n /** Skip the inline `query_index.upsert_one` / `delete_one` reindex (rebuild after the run). */\n skipReindex?: boolean\n /** Skip the per-record `<module>.<entity>.<action>` domain event emission. */\n skipEvents?: boolean\n /** Advisory: handlers that fan out per-record notifications SHOULD honor this and skip them. */\n skipNotifications?: boolean\n /**\n * Skip a command's own full-collection derived-data rebuild (e.g. category tree\n * `parentId`/`treePath`/`depth`/ancestor-descendant rewrite). The caller MUST run that rebuild\n * itself exactly once after the batch, in a `finally` that covers the completed, cancelled and\n * failed paths \u2014 otherwise every record written under this context is left with a stale\n * derived shape.\n */\n skipDerivedRebuild?: boolean\n}\n\nexport type CommandRuntimeContext = {\n container: AwilixContainer\n auth: AuthContext | null\n organizationScope: OrganizationScope | null\n selectedOrganizationId: string | null\n organizationIds: string[] | null\n request?: Request\n syncOrigin?: string | null\n /**\n * See {@link BulkImportSuppression}. Set by bulk backfill callers to defer heavy\n * per-record side effects (reindex, events, notifications). The caller MUST rebuild\n * the `query_index` for the affected entity types after the run when `skipReindex`\n * is set. Unset for normal (interactive) writes \u2014 they get all side effects.\n */\n bulkImport?: BulkImportSuppression\n /**\n * Marks a trusted server-side invocation (CLI seeding, tenant setup) that runs\n * without an authenticated end-user actor. Commands that gate writes behind a\n * privileged actor (e.g. super-admin-only platform tables) may treat this as\n * an explicit system grant. HTTP request paths MUST NOT set this \u2014 they always\n * carry a real `auth` actor, so a present-but-unprivileged actor stays denied.\n */\n systemActor?: boolean\n /**\n * When set, command handlers that support it MUST run their writes within this\n * existing transactional EntityManager (reusing its row locks) instead of\n * opening their own transaction. Lets a caller compose a command with its own\n * surrounding work as a single atomic, single-locked operation.\n */\n transactionalEm?: EntityManager\n /**\n * Optional server-side guard that supported command handlers invoke after\n * opening their write transaction and before reading or mutating records.\n * The guard receives that same transaction-bound EntityManager and, when the\n * handler provides it, the final input after command interceptors. The input\n * stays optional so existing handlers and callers remain source-compatible.\n */\n beforeTransactionalWrite?: (em: EntityManager, input?: unknown) => Promise<void>\n /**\n * Identifies the owner of an already-active {@link transactionalEm} lifetime.\n * Atomic replay accepts an ambient EntityManager only when this is the exact\n * token returned by `getTransactionLifetime(transactionalEm)` from the outer\n * `withAtomicFlush` phase. The owner completes the token after its real commit\n * or rollback, allowing replay leases and post-commit work to follow that\n * boundary. Omit when the command bus opens and owns the transaction itself.\n */\n transactionLifetime?: TransactionLifetime\n /**\n * Optional request-level replay authorization that the command bus binds to\n * its replay EntityManager. Atomic handlers run this guard in the same\n * transaction as the source-log transition and domain mutation; legacy\n * handlers run it in a dedicated read transaction before preserving their\n * existing replay lifecycle.\n */\n replayTransactionGuard?: (args: {\n operation: CommandReplayOperation\n logEntry: CommandUndoLogEntry\n transactionalEm: EntityManager\n }) => Promise<void> | void\n /**\n * On-behalf-of attribution for non-human principals (Agent Identity &\n * On-Behalf-Of, Wave 4 P2). When an agent runs on behalf of a human, the\n * orchestrator's `runAs` wrapper sets this so every `ActionLog` the command\n * path writes records `actorUserId = runAs.actorUserId` (the agent principal's\n * `auth.User` id), `onBehalfOfUserId = runAs.onBehalfOfUserId` (the invoking\n * human, or null for system-invoked agents), and `sourceKey = runAs.source`\n * (`'agent'`). Additive + optional: callers that omit it keep the existing\n * `ctx.auth.sub`-derived attribution unchanged. This threads agent attribution\n * through the SAME audited Command/CRUD path as a human action \u2014 not a parallel\n * audit path.\n */\n runAs?: CommandRunAsContext\n}\n\nexport type CommandRunAsContext = {\n /** The actor stamped on every ActionLog this context produces (agent `auth.User` id). */\n actorUserId: string\n /** The human (or system) principal the actor acts on behalf of; null when system-invoked. */\n onBehalfOfUserId?: string | null\n /** The audit source key for the attributed writes; `'agent'` for agent runs. */\n source: 'agent'\n}\n\nexport type CommandLogMetadata = {\n skipLog?: boolean\n /**\n * Per-execution replay policy. `false` records the audit entry without an undo\n * token or command payload, so neither undo nor redo can replay sensitive input.\n * Omitted preserves the command handler's existing replay behavior.\n */\n replayable?: boolean\n /**\n * Overrides the command input persisted in the audit entry's redo envelope.\n * The default is the raw input, which for credential-bearing commands would put\n * a plaintext secret at rest in `action_logs`. A handler that still wants its\n * operation to be undoable supplies a redacted projection here instead of\n * switching the whole entry to `replayable: false` \u2014 suppressing the undo token\n * removes the operator's ability to revert a write that carries no secret of its\n * own (undoing a user create only deletes a row).\n */\n redoInput?: unknown\n tenantId?: string | null\n organizationId?: string | null\n actorUserId?: string | null\n onBehalfOfUserId?: string | null\n actionLabel?: string | null\n resourceKind?: string | null\n resourceId?: string | null\n parentResourceKind?: string | null\n parentResourceId?: string | null\n undoToken?: string | null\n payload?: unknown\n snapshotBefore?: unknown\n snapshotAfter?: unknown\n relatedResourceKind?: string | null\n relatedResourceId?: string | null\n changes?: Record<string, unknown> | null\n context?: Record<string, unknown> | null\n}\n\nexport type CommandExecuteResult<TResult> = {\n result: TResult\n logEntry: any | null\n /**\n * True when an atomic redo finalized its source action log in the same\n * transaction as the domain mutation and the newly persisted log entry, and\n * that transaction has committed. An ambient replay returns this as false\n * while its caller-owned transaction is still active; the returned result\n * object is updated to true by the owner's commit callback. It remains false\n * on rollback. Callers that historically finalized redo themselves can use\n * this additive signal to avoid a redundant post-commit write.\n */\n replaySourceFinalized?: boolean\n}\n\n/**\n * Shape of the persisted action log handed to a command's `undo()` handler.\n *\n * IMPORTANT: there is intentionally **no `payload` field**. `buildLog()` returns\n * a `payload` in its metadata, but the command bus persists that under\n * `commandPayload` (column `command_payload`, wrapped in a redo envelope) \u2014 the\n * stored row never has a top-level `payload`. Reading `logEntry.payload` in an\n * undo handler is therefore always `undefined` and silently no-ops the undo\n * (issue #2504). Always read the undo snapshot through\n * `extractUndoPayload(logEntry)` from `@open-mercato/shared/lib/commands/undo`,\n * which unwraps `commandPayload`/snapshots correctly. Omitting `payload` here\n * makes the footgun a compile-time error instead of a runtime silent failure.\n */\nexport type CommandUndoLogEntry = {\n id?: string\n commandId?: string\n commandPayload?: unknown | null\n snapshotBefore?: unknown | null\n snapshotAfter?: unknown | null\n resourceKind?: string | null\n resourceId?: string | null\n undoToken?: string | null\n actionLabel?: string | null\n tenantId?: string | null\n organizationId?: string | null\n actorUserId?: string | null\n changesJson?: Record<string, unknown> | null\n contextJson?: Record<string, unknown> | null\n createdAt?: Date | string\n updatedAt?: Date | string\n}\n\nexport type CommandLogBuilderArgs<TInput, TResult> = {\n input: TInput\n result: TResult\n ctx: CommandRuntimeContext\n snapshots: {\n before?: unknown\n after?: unknown\n }\n}\n\nexport type CommandReplayOperation = 'undo' | 'redo'\n\nexport type CommandReplayAuthorizationArgs<TInput> = {\n operation: CommandReplayOperation\n input: TInput\n ctx: CommandRuntimeContext\n logEntry: CommandUndoLogEntry\n}\n\nexport interface CommandHandler<TInput = unknown, TResult = unknown> {\n readonly id: string\n readonly isUndoable?: boolean\n /**\n * Opts replay into the command bus's transaction-bound lifecycle. The source\n * action-log transition, handler mutation, and any new replay log share one\n * EntityManager and commit or roll back together. Handlers that enable this\n * MUST reuse `ctx.transactionalEm` for every replay-time database operation.\n * Omitted preserves the legacy non-atomic replay path.\n */\n readonly atomicReplay?: boolean\n /**\n * Acquires every authorization-state lock needed by an atomic replay before\n * request-level replay authorization and feature-gated interceptors run.\n * Implementations MUST discover their complete actor/target/destination set\n * before taking the first lock and MUST reuse `ctx.transactionalEm`.\n * Omitted preserves the existing lifecycle for handlers that do not need\n * domain-specific authorization stabilization.\n */\n stabilizeReplay?(params: CommandReplayAuthorizationArgs<TInput>): Promise<void> | void\n /**\n * Optional Zod schema describing the command's return value. Feeds the\n * workflows context ledger so downstream activities can reason about the\n * shape a command produces; when absent the ledger renders the output as\n * unknown.\n */\n readonly outputSchema?: ZodTypeAny\n prepare?(input: TInput, ctx: CommandRuntimeContext): Promise<{ before?: unknown } | null> | { before?: unknown } | null\n /**\n * Opt in to taking the undo snapshot inside the write transaction. The bus\n * defers `prepare()` into `ctx.beforeTransactionalWrite`, after the handler's\n * transaction guard and before its first read or mutation.\n */\n readonly prepareSnapshotInsideTransaction?: boolean\n execute(input: TInput, ctx: CommandRuntimeContext): Promise<TResult> | TResult\n buildLog?(args: CommandLogBuilderArgs<TInput, TResult>): Promise<CommandLogMetadata | null | undefined> | CommandLogMetadata | null | undefined\n captureAfter?(input: TInput, result: TResult, ctx: CommandRuntimeContext): Promise<unknown> | unknown\n /**\n * Re-authorizes a stored command against the actor and resource state that\n * exist at replay time. Legacy handlers are checked before claiming an undo\n * log or beginning redo processing. Atomic handlers are checked inside their\n * replay transaction before the guarded source transition; their mutation\n * path can repeat the check after taking domain locks. Throwing aborts replay\n * without committed domain side effects.\n */\n authorizeReplay?(params: CommandReplayAuthorizationArgs<TInput>): Promise<void> | void\n undo?(params: { input: TInput; ctx: CommandRuntimeContext; logEntry: CommandUndoLogEntry }): Promise<void> | void\n /**\n * Optional redo handler. When defined, the command bus calls this instead of\n * `execute()` while replaying a previously undone action (the redo route passes\n * `redoLogEntry` in the execution options). It receives the source action log so\n * it can re-materialize the original record **reusing its id** \u2014 for a create\n * command this restores the soft-deleted row (or re-creates it from the\n * `snapshotAfter`) instead of minting a new id, keeping undo/redo snapshots and\n * references stable (issue #2506, invariant I6). Handlers without `redo` keep the\n * legacy behavior of replaying `execute(__redoInput)`.\n */\n redo?(params: { input: TInput; ctx: CommandRuntimeContext; logEntry: CommandUndoLogEntry }): Promise<TResult> | TResult\n}\n\nexport type CommandExecutionOptions<TInput> = {\n input: TInput\n ctx: CommandRuntimeContext\n metadata?: CommandLogMetadata | null\n skipCacheInvalidation?: boolean\n /**\n * When set, marks this execution as a redo of a previously undone action. If the\n * resolved handler defines a `redo` method, the command bus calls\n * `handler.redo({ input, ctx, logEntry })` instead of `handler.execute(...)`. The\n * rest of the pipeline (snapshots, buildLog, undo-token minting, persistence,\n * cache invalidation, side effects) is identical, so the fresh log entry \u2014 and\n * the `x-om-operation` header derived from it \u2014 automatically carry the restored\n * resourceId. Ignored when the handler has no `redo` method (legacy replay path).\n */\n redoLogEntry?: CommandUndoLogEntry | null\n}\n\nexport function defaultUndoToken(): string {\n return randomUUID()\n}\n"],
|
|
5
|
-
"mappings": "AAGA,SAAS,kBAAkB;
|
|
4
|
+
"sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { ZodTypeAny } from 'zod'\nimport { randomUUID } from 'crypto'\nimport type { AuthContext } from '../auth/server'\nimport type { OrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { TransactionLifetime } from './transaction-lifetime'\n\n/**\n * Bulk-import / backfill deferral flags. When a command runs under a context that\n * carries this, the command bus and data engine suppress the heavy per-record side\n * effects flagged below so a large backfill can defer them to a single batched pass.\n *\n * IMPORTANT \u2014 the caller owns restoring whatever it suppresses. With `skipReindex`\n * the `query_index` projection (and its search tokens) is stale for every record\n * written under this context until the caller runs a batched `query_index rebuild`\n * for the affected entity types at end-of-run.\n *\n * Concurrency: these flags are read from the context and threaded as a local\n * parameter through the side-effect flush \u2014 no shared engine state is mutated \u2014 so\n * two commands running concurrently with different flags never clobber each other.\n */\nexport type BulkImportSuppression = {\n /** Skip the inline `query_index.upsert_one` / `delete_one` reindex (rebuild after the run). */\n skipReindex?: boolean\n /** Skip the per-record `<module>.<entity>.<action>` domain event emission. */\n skipEvents?: boolean\n /** Advisory: handlers that fan out per-record notifications SHOULD honor this and skip them. */\n skipNotifications?: boolean\n /**\n * Skip a command's own full-collection derived-data rebuild (e.g. category tree\n * `parentId`/`treePath`/`depth`/ancestor-descendant rewrite). The caller MUST run that rebuild\n * itself exactly once after the batch, in a `finally` that covers the completed, cancelled and\n * failed paths \u2014 otherwise every record written under this context is left with a stale\n * derived shape.\n */\n skipDerivedRebuild?: boolean\n}\n\nexport type CommandRuntimeContext = {\n container: AwilixContainer\n auth: AuthContext | null\n organizationScope: OrganizationScope | null\n selectedOrganizationId: string | null\n organizationIds: string[] | null\n request?: Request\n syncOrigin?: string | null\n /**\n * See {@link BulkImportSuppression}. Set by bulk backfill callers to defer heavy\n * per-record side effects (reindex, events, notifications). The caller MUST rebuild\n * the `query_index` for the affected entity types after the run when `skipReindex`\n * is set. Unset for normal (interactive) writes \u2014 they get all side effects.\n */\n bulkImport?: BulkImportSuppression\n /**\n * Marks a trusted server-side invocation (CLI seeding, tenant setup) that runs\n * without an authenticated end-user actor. Commands that gate writes behind a\n * privileged actor (e.g. super-admin-only platform tables) may treat this as\n * an explicit system grant. HTTP request paths MUST NOT set this \u2014 they always\n * carry a real `auth` actor, so a present-but-unprivileged actor stays denied.\n */\n systemActor?: boolean\n /**\n * When set, command handlers that support it MUST run their writes within this\n * existing transactional EntityManager (reusing its row locks) instead of\n * opening their own transaction. Lets a caller compose a command with its own\n * surrounding work as a single atomic, single-locked operation.\n */\n transactionalEm?: EntityManager\n /**\n * Optional server-side guard that supported command handlers invoke after\n * opening their write transaction and before reading or mutating records.\n * The guard receives that same transaction-bound EntityManager and, when the\n * handler provides it, the final input after command interceptors. The input\n * stays optional so existing handlers and callers remain source-compatible.\n */\n beforeTransactionalWrite?: (em: EntityManager, input?: unknown) => Promise<void>\n /**\n * Identifies the owner of an already-active {@link transactionalEm} lifetime.\n * Atomic replay accepts an ambient EntityManager only when this is the exact\n * token returned by `getTransactionLifetime(transactionalEm)` from the outer\n * `withAtomicFlush` phase. The owner completes the token after its real commit\n * or rollback, allowing replay leases and post-commit work to follow that\n * boundary. Omit when the command bus opens and owns the transaction itself.\n */\n transactionLifetime?: TransactionLifetime\n /**\n * Optional request-level replay authorization that the command bus binds to\n * its replay EntityManager. Atomic handlers run this guard in the same\n * transaction as the source-log transition and domain mutation; legacy\n * handlers run it in a dedicated read transaction before preserving their\n * existing replay lifecycle.\n */\n replayTransactionGuard?: (args: {\n operation: CommandReplayOperation\n logEntry: CommandUndoLogEntry\n transactionalEm: EntityManager\n }) => Promise<void> | void\n /**\n * On-behalf-of attribution for non-human principals (Agent Identity &\n * On-Behalf-Of, Wave 4 P2). When an agent runs on behalf of a human, the\n * orchestrator's `runAs` wrapper sets this so every `ActionLog` the command\n * path writes records `actorUserId = runAs.actorUserId` (the agent principal's\n * `auth.User` id), `onBehalfOfUserId = runAs.onBehalfOfUserId` (the invoking\n * human, or null for system-invoked agents), and `sourceKey = runAs.source`\n * (`'agent'`). Additive + optional: callers that omit it keep the existing\n * `ctx.auth.sub`-derived attribution unchanged. This threads agent attribution\n * through the SAME audited Command/CRUD path as a human action \u2014 not a parallel\n * audit path.\n */\n runAs?: CommandRunAsContext\n}\n\nexport type CommandRunAsContext = {\n /** The actor stamped on every ActionLog this context produces (agent `auth.User` id). */\n actorUserId: string\n /** The human (or system) principal the actor acts on behalf of; null when system-invoked. */\n onBehalfOfUserId?: string | null\n /** The audit source key for the attributed writes; `'agent'` for agent runs. */\n source: 'agent'\n}\n\nexport type CommandLogMetadata = {\n skipLog?: boolean\n /**\n * Per-execution replay policy. `false` records the audit entry without an undo\n * token or command payload, so neither undo nor redo can replay sensitive input.\n * Omitted preserves the command handler's existing replay behavior.\n */\n replayable?: boolean\n /**\n * Overrides the command input persisted in the audit entry's redo envelope.\n * The default is the raw input, which for credential-bearing commands would put\n * a plaintext secret at rest in `action_logs`. A handler that still wants its\n * operation to be undoable supplies a redacted projection here instead of\n * switching the whole entry to `replayable: false` \u2014 suppressing the undo token\n * removes the operator's ability to revert a write that carries no secret of its\n * own (undoing a user create only deletes a row).\n */\n redoInput?: unknown\n tenantId?: string | null\n organizationId?: string | null\n actorUserId?: string | null\n onBehalfOfUserId?: string | null\n actionLabel?: string | null\n resourceKind?: string | null\n resourceId?: string | null\n parentResourceKind?: string | null\n parentResourceId?: string | null\n undoToken?: string | null\n payload?: unknown\n snapshotBefore?: unknown\n snapshotAfter?: unknown\n relatedResourceKind?: string | null\n relatedResourceId?: string | null\n changes?: Record<string, unknown> | null\n context?: Record<string, unknown> | null\n}\n\nexport type CommandExecuteResult<TResult> = {\n result: TResult\n logEntry: any | null\n /**\n * True when an atomic redo finalized its source action log in the same\n * transaction as the domain mutation and the newly persisted log entry, and\n * that transaction has committed. An ambient replay returns this as false\n * while its caller-owned transaction is still active; the returned result\n * object is updated to true by the owner's commit callback. It remains false\n * on rollback. A non-atomic redo returns true once its compare-and-set claim\n * moved the source log to redone before the command ran; with\n * `ctx.transactionalEm` that claim is part of the caller's transaction, whose\n * rollback reverts it. Callers that historically finalized redo themselves\n * can use this additive signal to avoid a redundant post-commit write.\n */\n replaySourceFinalized?: boolean\n}\n\n/**\n * Shape of the persisted action log handed to a command's `undo()` handler.\n *\n * IMPORTANT: there is intentionally **no `payload` field**. `buildLog()` returns\n * a `payload` in its metadata, but the command bus persists that under\n * `commandPayload` (column `command_payload`, wrapped in a redo envelope) \u2014 the\n * stored row never has a top-level `payload`. Reading `logEntry.payload` in an\n * undo handler is therefore always `undefined` and silently no-ops the undo\n * (issue #2504). Always read the undo snapshot through\n * `extractUndoPayload(logEntry)` from `@open-mercato/shared/lib/commands/undo`,\n * which unwraps `commandPayload`/snapshots correctly. Omitting `payload` here\n * makes the footgun a compile-time error instead of a runtime silent failure.\n */\nexport type CommandUndoLogEntry = {\n id?: string\n commandId?: string\n commandPayload?: unknown | null\n snapshotBefore?: unknown | null\n snapshotAfter?: unknown | null\n resourceKind?: string | null\n resourceId?: string | null\n undoToken?: string | null\n actionLabel?: string | null\n tenantId?: string | null\n organizationId?: string | null\n actorUserId?: string | null\n changesJson?: Record<string, unknown> | null\n contextJson?: Record<string, unknown> | null\n createdAt?: Date | string\n updatedAt?: Date | string\n}\n\nexport type CommandLogBuilderArgs<TInput, TResult> = {\n input: TInput\n result: TResult\n ctx: CommandRuntimeContext\n snapshots: {\n before?: unknown\n after?: unknown\n }\n}\n\nexport type CommandReplayOperation = 'undo' | 'redo'\n\nexport type CommandReplayAuthorizationArgs<TInput> = {\n operation: CommandReplayOperation\n input: TInput\n ctx: CommandRuntimeContext\n logEntry: CommandUndoLogEntry\n}\n\nexport interface CommandHandler<TInput = unknown, TResult = unknown> {\n readonly id: string\n readonly isUndoable?: boolean\n /**\n * Opts replay into the command bus's transaction-bound lifecycle. The source\n * action-log transition, handler mutation, and any new replay log share one\n * EntityManager and commit or roll back together. Handlers that enable this\n * MUST reuse `ctx.transactionalEm` for every replay-time database operation.\n * Omitted preserves the legacy non-atomic replay path.\n */\n readonly atomicReplay?: boolean\n /**\n * Acquires every authorization-state lock needed by an atomic replay before\n * request-level replay authorization and feature-gated interceptors run.\n * Implementations MUST discover their complete actor/target/destination set\n * before taking the first lock and MUST reuse `ctx.transactionalEm`.\n * Omitted preserves the existing lifecycle for handlers that do not need\n * domain-specific authorization stabilization.\n */\n stabilizeReplay?(params: CommandReplayAuthorizationArgs<TInput>): Promise<void> | void\n /**\n * Optional Zod schema describing the command's return value. Feeds the\n * workflows context ledger so downstream activities can reason about the\n * shape a command produces; when absent the ledger renders the output as\n * unknown.\n */\n readonly outputSchema?: ZodTypeAny\n prepare?(input: TInput, ctx: CommandRuntimeContext): Promise<{ before?: unknown } | null> | { before?: unknown } | null\n /**\n * Opt in to taking the undo snapshot inside the write transaction. The bus\n * defers `prepare()` into `ctx.beforeTransactionalWrite`, after the handler's\n * transaction guard and before its first read or mutation.\n */\n readonly prepareSnapshotInsideTransaction?: boolean\n execute(input: TInput, ctx: CommandRuntimeContext): Promise<TResult> | TResult\n buildLog?(args: CommandLogBuilderArgs<TInput, TResult>): Promise<CommandLogMetadata | null | undefined> | CommandLogMetadata | null | undefined\n captureAfter?(input: TInput, result: TResult, ctx: CommandRuntimeContext): Promise<unknown> | unknown\n /**\n * Re-authorizes a stored command against the actor and resource state that\n * exist at replay time. Legacy handlers are checked before claiming an undo\n * log or beginning redo processing. Atomic handlers are checked inside their\n * replay transaction before the guarded source transition; their mutation\n * path can repeat the check after taking domain locks. Throwing aborts replay\n * without committed domain side effects.\n */\n authorizeReplay?(params: CommandReplayAuthorizationArgs<TInput>): Promise<void> | void\n undo?(params: { input: TInput; ctx: CommandRuntimeContext; logEntry: CommandUndoLogEntry }): Promise<void> | void\n /**\n * Optional redo handler. When defined, the command bus calls this instead of\n * `execute()` while replaying a previously undone action (the redo route passes\n * `redoLogEntry` in the execution options). It receives the source action log so\n * it can re-materialize the original record **reusing its id** \u2014 for a create\n * command this restores the soft-deleted row (or re-creates it from the\n * `snapshotAfter`) instead of minting a new id, keeping undo/redo snapshots and\n * references stable (issue #2506, invariant I6). Handlers without `redo` keep the\n * legacy behavior of replaying `execute(__redoInput)`.\n */\n redo?(params: { input: TInput; ctx: CommandRuntimeContext; logEntry: CommandUndoLogEntry }): Promise<TResult> | TResult\n}\n\nexport type CommandExecutionOptions<TInput> = {\n input: TInput\n ctx: CommandRuntimeContext\n metadata?: CommandLogMetadata | null\n skipCacheInvalidation?: boolean\n /**\n * When set, marks this execution as a redo of a previously undone action. If the\n * resolved handler defines a `redo` method, the command bus calls\n * `handler.redo({ input, ctx, logEntry })` instead of `handler.execute(...)`. The\n * rest of the pipeline (snapshots, buildLog, undo-token minting, persistence,\n * cache invalidation, side effects) is identical, so the fresh log entry \u2014 and\n * the `x-om-operation` header derived from it \u2014 automatically carry the restored\n * resourceId. Ignored when the handler has no `redo` method (legacy replay path).\n */\n redoLogEntry?: CommandUndoLogEntry | null\n}\n\nexport function defaultUndoToken(): string {\n return randomUUID()\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,kBAAkB;AA8SpB,SAAS,mBAA2B;AACzC,SAAO,WAAW;AACpB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -44,6 +44,10 @@ function formatTimestamp(date) {
|
|
|
44
44
|
const millis = String(date.getMilliseconds()).padStart(3, "0");
|
|
45
45
|
return `${hours}:${minutes}:${seconds}.${millis}`;
|
|
46
46
|
}
|
|
47
|
+
const STACK_INDENT = " ";
|
|
48
|
+
function indentStack(stack) {
|
|
49
|
+
return stack.split("\n").map((stackLine) => `${STACK_INDENT}${stackLine}`).join("\n");
|
|
50
|
+
}
|
|
47
51
|
function createPrettyLogger(namespace, bindings = {}) {
|
|
48
52
|
const emit = (level, msg, fields) => {
|
|
49
53
|
if (!isLevelEnabled(level)) return;
|
|
@@ -63,7 +67,7 @@ function createPrettyLogger(namespace, bindings = {}) {
|
|
|
63
67
|
let line = `${timestampPart} ${levelPart} [${scope}] ${msg}`;
|
|
64
68
|
if (tail) line += ` ${tail}`;
|
|
65
69
|
if (err instanceof Error) line += `
|
|
66
|
-
${err.stack ?? err.message}`;
|
|
70
|
+
${indentStack(err.stack ?? err.message)}`;
|
|
67
71
|
stream.write(`${line}
|
|
68
72
|
`);
|
|
69
73
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/logger/transport.pretty.ts"],
|
|
4
|
-
"sourcesContent": ["import type { LogBindings, Logger } from './index'\nimport { parseBooleanToken } from '../boolean'\nimport { isLevelEnabled, type LogLevel } from './level'\nimport { formatBindings } from './transport.console'\nimport { OM_LOG_DESTINATION_ENV, isStderrDestinationToken } from './transport.server'\n\nexport const OM_LOG_PRETTY_ENV = 'OM_LOG_PRETTY'\n\ntype EnvSource = Record<string, string | undefined>\n\nfunction readProcessEnv(): EnvSource {\n return typeof process === 'undefined' ? {} : process.env\n}\n\n/** Resolve pretty mode from `OM_LOG_PRETTY`, defaulting to on outside production. */\nexport function resolvePrettyMode(env: EnvSource = readProcessEnv()): boolean {\n const parsed = parseBooleanToken(env[OM_LOG_PRETTY_ENV])\n if (parsed !== null) return parsed\n return env.NODE_ENV !== 'production'\n}\n\nlet cachedPrettyMode: boolean | null = null\n\nexport function isPrettyModeEnabled(): boolean {\n if (cachedPrettyMode === null) cachedPrettyMode = resolvePrettyMode()\n return cachedPrettyMode\n}\n\n/** Internal: clear the memoized pretty mode so tests can vary `OM_LOG_PRETTY`. */\nexport function resetLogPrettyCache(): void {\n cachedPrettyMode = null\n}\n\nconst LEVEL_LABELS: Record<LogLevel, string> = {\n debug: 'DEBUG',\n info: 'INFO ',\n warn: 'WARN ',\n error: 'ERROR',\n}\n\nconst ANSI_RESET = '\\x1b[0m'\nconst ANSI_DIM = '\\x1b[2m'\n\nconst LEVEL_COLORS: Record<LogLevel, string> = {\n debug: ANSI_DIM,\n info: '\\x1b[36m',\n warn: '\\x1b[33m',\n error: '\\x1b[31m',\n}\n\ntype WritableLogStream = { write(chunk: string): unknown; isTTY?: boolean }\n\nfunction resolveStream(): WritableLogStream {\n const useStderr = isStderrDestinationToken(readProcessEnv()[OM_LOG_DESTINATION_ENV])\n return useStderr ? process.stderr : process.stdout\n}\n\nfunction formatTimestamp(date: Date): string {\n const hours = String(date.getHours()).padStart(2, '0')\n const minutes = String(date.getMinutes()).padStart(2, '0')\n const seconds = String(date.getSeconds()).padStart(2, '0')\n const millis = String(date.getMilliseconds()).padStart(3, '0')\n return `${hours}:${minutes}:${seconds}.${millis}`\n}\n\nexport function createPrettyLogger(namespace: string, bindings: LogBindings = {}): Logger {\n const emit = (level: LogLevel, msg: string, fields?: LogBindings): void => {\n if (!isLevelEnabled(level)) return\n const stream = resolveStream()\n const { err, ...rest } = { ...bindings, ...fields }\n let scope = namespace\n if (typeof rest.component === 'string' && rest.component) {\n scope = `${namespace}:${rest.component}`\n delete rest.component\n }\n const tail = formatBindings(err instanceof Error || err === undefined ? rest : { ...rest, err })\n const colored = stream.isTTY === true\n const timestamp = formatTimestamp(new Date())\n const timestampPart = colored ? `${ANSI_DIM}${timestamp}${ANSI_RESET}` : timestamp\n const label = LEVEL_LABELS[level]\n const levelPart = colored ? `${LEVEL_COLORS[level]}${label}${ANSI_RESET}` : label\n let line = `${timestampPart} ${levelPart} [${scope}] ${msg}`\n if (tail) line += ` ${tail}`\n if (err instanceof Error) line += `\\n${err.stack ?? err.message}`\n stream.write(`${line}\\n`)\n }\n return {\n debug: (msg, fields) => emit('debug', msg, fields),\n info: (msg, fields) => emit('info', msg, fields),\n warn: (msg, fields) => emit('warn', msg, fields),\n error: (msg, fields) => emit('error', msg, fields),\n child: (childBindings) => createPrettyLogger(namespace, { ...bindings, ...childBindings }),\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,yBAAyB;AAClC,SAAS,sBAAqC;AAC9C,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB,gCAAgC;AAE1D,MAAM,oBAAoB;AAIjC,SAAS,iBAA4B;AACnC,SAAO,OAAO,YAAY,cAAc,CAAC,IAAI,QAAQ;AACvD;AAGO,SAAS,kBAAkB,MAAiB,eAAe,GAAY;AAC5E,QAAM,SAAS,kBAAkB,IAAI,iBAAiB,CAAC;AACvD,MAAI,WAA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,SAAS;AACtC,aAAO,KAAK;AAAA,IACd;AACA,UAAM,OAAO,eAAe,eAAe,SAAS,QAAQ,SAAY,OAAO,EAAE,GAAG,MAAM,IAAI,CAAC;AAC/F,UAAM,UAAU,OAAO,UAAU;AACjC,UAAM,YAAY,gBAAgB,oBAAI,KAAK,CAAC;AAC5C,UAAM,gBAAgB,UAAU,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,KAAK;AACzE,UAAM,QAAQ,aAAa,KAAK;AAChC,UAAM,YAAY,UAAU,GAAG,aAAa,KAAK,CAAC,GAAG,KAAK,GAAG,UAAU,KAAK;AAC5E,QAAI,OAAO,GAAG,aAAa,IAAI,SAAS,KAAK,KAAK,KAAK,GAAG;AAC1D,QAAI,KAAM,SAAQ,IAAI,IAAI;
|
|
4
|
+
"sourcesContent": ["import type { LogBindings, Logger } from './index'\nimport { parseBooleanToken } from '../boolean'\nimport { isLevelEnabled, type LogLevel } from './level'\nimport { formatBindings } from './transport.console'\nimport { OM_LOG_DESTINATION_ENV, isStderrDestinationToken } from './transport.server'\n\nexport const OM_LOG_PRETTY_ENV = 'OM_LOG_PRETTY'\n\ntype EnvSource = Record<string, string | undefined>\n\nfunction readProcessEnv(): EnvSource {\n return typeof process === 'undefined' ? {} : process.env\n}\n\n/** Resolve pretty mode from `OM_LOG_PRETTY`, defaulting to on outside production. */\nexport function resolvePrettyMode(env: EnvSource = readProcessEnv()): boolean {\n const parsed = parseBooleanToken(env[OM_LOG_PRETTY_ENV])\n if (parsed !== null) return parsed\n return env.NODE_ENV !== 'production'\n}\n\nlet cachedPrettyMode: boolean | null = null\n\nexport function isPrettyModeEnabled(): boolean {\n if (cachedPrettyMode === null) cachedPrettyMode = resolvePrettyMode()\n return cachedPrettyMode\n}\n\n/** Internal: clear the memoized pretty mode so tests can vary `OM_LOG_PRETTY`. */\nexport function resetLogPrettyCache(): void {\n cachedPrettyMode = null\n}\n\nconst LEVEL_LABELS: Record<LogLevel, string> = {\n debug: 'DEBUG',\n info: 'INFO ',\n warn: 'WARN ',\n error: 'ERROR',\n}\n\nconst ANSI_RESET = '\\x1b[0m'\nconst ANSI_DIM = '\\x1b[2m'\n\nconst LEVEL_COLORS: Record<LogLevel, string> = {\n debug: ANSI_DIM,\n info: '\\x1b[36m',\n warn: '\\x1b[33m',\n error: '\\x1b[31m',\n}\n\ntype WritableLogStream = { write(chunk: string): unknown; isTTY?: boolean }\n\nfunction resolveStream(): WritableLogStream {\n const useStderr = isStderrDestinationToken(readProcessEnv()[OM_LOG_DESTINATION_ENV])\n return useStderr ? process.stderr : process.stdout\n}\n\nfunction formatTimestamp(date: Date): string {\n const hours = String(date.getHours()).padStart(2, '0')\n const minutes = String(date.getMinutes()).padStart(2, '0')\n const seconds = String(date.getSeconds()).padStart(2, '0')\n const millis = String(date.getMilliseconds()).padStart(3, '0')\n return `${hours}:${minutes}:${seconds}.${millis}`\n}\n\nconst STACK_INDENT = ' '\n\nfunction indentStack(stack: string): string {\n return stack.split('\\n').map((stackLine) => `${STACK_INDENT}${stackLine}`).join('\\n')\n}\n\nexport function createPrettyLogger(namespace: string, bindings: LogBindings = {}): Logger {\n const emit = (level: LogLevel, msg: string, fields?: LogBindings): void => {\n if (!isLevelEnabled(level)) return\n const stream = resolveStream()\n const { err, ...rest } = { ...bindings, ...fields }\n let scope = namespace\n if (typeof rest.component === 'string' && rest.component) {\n scope = `${namespace}:${rest.component}`\n delete rest.component\n }\n const tail = formatBindings(err instanceof Error || err === undefined ? rest : { ...rest, err })\n const colored = stream.isTTY === true\n const timestamp = formatTimestamp(new Date())\n const timestampPart = colored ? `${ANSI_DIM}${timestamp}${ANSI_RESET}` : timestamp\n const label = LEVEL_LABELS[level]\n const levelPart = colored ? `${LEVEL_COLORS[level]}${label}${ANSI_RESET}` : label\n let line = `${timestampPart} ${levelPart} [${scope}] ${msg}`\n if (tail) line += ` ${tail}`\n // Indented so log readers (e.g. the dev runtime filter) can tell the\n // entry's own stack from unrelated `Error:` output that follows it.\n if (err instanceof Error) line += `\\n${indentStack(err.stack ?? err.message)}`\n stream.write(`${line}\\n`)\n }\n return {\n debug: (msg, fields) => emit('debug', msg, fields),\n info: (msg, fields) => emit('info', msg, fields),\n warn: (msg, fields) => emit('warn', msg, fields),\n error: (msg, fields) => emit('error', msg, fields),\n child: (childBindings) => createPrettyLogger(namespace, { ...bindings, ...childBindings }),\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,yBAAyB;AAClC,SAAS,sBAAqC;AAC9C,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB,gCAAgC;AAE1D,MAAM,oBAAoB;AAIjC,SAAS,iBAA4B;AACnC,SAAO,OAAO,YAAY,cAAc,CAAC,IAAI,QAAQ;AACvD;AAGO,SAAS,kBAAkB,MAAiB,eAAe,GAAY;AAC5E,QAAM,SAAS,kBAAkB,IAAI,iBAAiB,CAAC;AACvD,MAAI,WAAW,KAAM,QAAO;AAC5B,SAAO,IAAI,aAAa;AAC1B;AAEA,IAAI,mBAAmC;AAEhC,SAAS,sBAA+B;AAC7C,MAAI,qBAAqB,KAAM,oBAAmB,kBAAkB;AACpE,SAAO;AACT;AAGO,SAAS,sBAA4B;AAC1C,qBAAmB;AACrB;AAEA,MAAM,eAAyC;AAAA,EAC7C,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAEA,MAAM,aAAa;AACnB,MAAM,WAAW;AAEjB,MAAM,eAAyC;AAAA,EAC7C,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAIA,SAAS,gBAAmC;AAC1C,QAAM,YAAY,yBAAyB,eAAe,EAAE,sBAAsB,CAAC;AACnF,SAAO,YAAY,QAAQ,SAAS,QAAQ;AAC9C;AAEA,SAAS,gBAAgB,MAAoB;AAC3C,QAAM,QAAQ,OAAO,KAAK,SAAS,CAAC,EAAE,SAAS,GAAG,GAAG;AACrD,QAAM,UAAU,OAAO,KAAK,WAAW,CAAC,EAAE,S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AY,IAAI,SAAS,IAAI,OAAO,CAAC;AAC5E,WAAO,MAAM,GAAG,IAAI;AAAA,CAAI;AAAA,EAC1B;AACA,SAAO;AAAA,IACL,OAAO,CAAC,KAAK,WAAW,KAAK,SAAS,KAAK,MAAM;AAAA,IACjD,MAAM,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK,MAAM;AAAA,IAC/C,MAAM,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK,MAAM;AAAA,IAC/C,OAAO,CAAC,KAAK,WAAW,KAAK,SAAS,KAAK,MAAM;AAAA,IACjD,OAAO,CAAC,kBAAkB,mBAAmB,WAAW,EAAE,GAAG,UAAU,GAAG,cAAc,CAAC;AAAA,EAC3F;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { parseNumberWithDefault } from "../number.js";
|
|
2
|
+
const SSE_AUTH_REVALIDATION_INTERVAL_ENV = "OM_EVENTS_SSE_AUTH_REVALIDATION_INTERVAL_MS";
|
|
3
|
+
const SSE_CONNECTION_MAX_AGE_ENV = "OM_EVENTS_SSE_CONNECTION_MAX_AGE_MS";
|
|
4
|
+
const DEFAULT_AUTH_REVALIDATION_INTERVAL_MS = 3e4;
|
|
5
|
+
const DEFAULT_CONNECTION_MAX_AGE_MS = 5 * 6e4;
|
|
6
|
+
const MIN_AUTH_REVALIDATION_INTERVAL_MS = 1e3;
|
|
7
|
+
const MIN_CONNECTION_MAX_AGE_MS = 1e3;
|
|
8
|
+
const CONNECTION_MAX_AGE_JITTER_RATIO = 0.15;
|
|
9
|
+
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
10
|
+
function resolveSseConnectionBounds(env = process.env) {
|
|
11
|
+
return {
|
|
12
|
+
authRevalidationIntervalMs: Math.min(
|
|
13
|
+
parseNumberWithDefault(
|
|
14
|
+
env[SSE_AUTH_REVALIDATION_INTERVAL_ENV],
|
|
15
|
+
DEFAULT_AUTH_REVALIDATION_INTERVAL_MS,
|
|
16
|
+
{ integer: true, min: MIN_AUTH_REVALIDATION_INTERVAL_MS }
|
|
17
|
+
),
|
|
18
|
+
MAX_TIMER_DELAY_MS
|
|
19
|
+
),
|
|
20
|
+
connectionMaxAgeMs: applyConnectionMaxAgeJitter(
|
|
21
|
+
parseNumberWithDefault(
|
|
22
|
+
env[SSE_CONNECTION_MAX_AGE_ENV],
|
|
23
|
+
DEFAULT_CONNECTION_MAX_AGE_MS,
|
|
24
|
+
{ integer: true, min: MIN_CONNECTION_MAX_AGE_MS }
|
|
25
|
+
)
|
|
26
|
+
)
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function applyConnectionMaxAgeJitter(configuredMs) {
|
|
30
|
+
const jitterFactor = 1 + (Math.random() * 2 - 1) * CONNECTION_MAX_AGE_JITTER_RATIO;
|
|
31
|
+
const jitteredMs = Math.round(configuredMs * jitterFactor);
|
|
32
|
+
return Math.min(Math.max(jitteredMs, MIN_CONNECTION_MAX_AGE_MS), MAX_TIMER_DELAY_MS);
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
SSE_AUTH_REVALIDATION_INTERVAL_ENV,
|
|
36
|
+
SSE_CONNECTION_MAX_AGE_ENV,
|
|
37
|
+
resolveSseConnectionBounds
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=connectionBounds.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/lib/sse/connectionBounds.ts"],
|
|
4
|
+
"sourcesContent": ["import { parseNumberWithDefault } from '../number'\n\nexport const SSE_AUTH_REVALIDATION_INTERVAL_ENV = 'OM_EVENTS_SSE_AUTH_REVALIDATION_INTERVAL_MS'\nexport const SSE_CONNECTION_MAX_AGE_ENV = 'OM_EVENTS_SSE_CONNECTION_MAX_AGE_MS'\n\nconst DEFAULT_AUTH_REVALIDATION_INTERVAL_MS = 30_000\nconst DEFAULT_CONNECTION_MAX_AGE_MS = 5 * 60_000\nconst MIN_AUTH_REVALIDATION_INTERVAL_MS = 1_000\nconst MIN_CONNECTION_MAX_AGE_MS = 1_000\nconst CONNECTION_MAX_AGE_JITTER_RATIO = 0.15\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\nexport type SseConnectionBounds = {\n authRevalidationIntervalMs: number\n connectionMaxAgeMs: number\n}\n\n/**\n * Per-connection timing shared by the DOM Event Bridge and the Portal Event Bridge.\n * Reads the env on every call so each new stream picks up the current bounds; the\n * max age gets \u00B115% jitter so streams opened together do not reconnect together.\n */\nexport function resolveSseConnectionBounds(env: NodeJS.ProcessEnv = process.env): SseConnectionBounds {\n return {\n authRevalidationIntervalMs: Math.min(\n parseNumberWithDefault(\n env[SSE_AUTH_REVALIDATION_INTERVAL_ENV],\n DEFAULT_AUTH_REVALIDATION_INTERVAL_MS,\n { integer: true, min: MIN_AUTH_REVALIDATION_INTERVAL_MS },\n ),\n MAX_TIMER_DELAY_MS,\n ),\n connectionMaxAgeMs: applyConnectionMaxAgeJitter(\n parseNumberWithDefault(\n env[SSE_CONNECTION_MAX_AGE_ENV],\n DEFAULT_CONNECTION_MAX_AGE_MS,\n { integer: true, min: MIN_CONNECTION_MAX_AGE_MS },\n ),\n ),\n }\n}\n\nfunction applyConnectionMaxAgeJitter(configuredMs: number): number {\n const jitterFactor = 1 + (Math.random() * 2 - 1) * CONNECTION_MAX_AGE_JITTER_RATIO\n const jitteredMs = Math.round(configuredMs * jitterFactor)\n return Math.min(Math.max(jitteredMs, MIN_CONNECTION_MAX_AGE_MS), MAX_TIMER_DELAY_MS)\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,8BAA8B;AAEhC,MAAM,qCAAqC;AAC3C,MAAM,6BAA6B;AAE1C,MAAM,wCAAwC;AAC9C,MAAM,gCAAgC,IAAI;AAC1C,MAAM,oCAAoC;AAC1C,MAAM,4BAA4B;AAClC,MAAM,kCAAkC;AACxC,MAAM,qBAAqB;AAYpB,SAAS,2BAA2B,MAAyB,QAAQ,KAA0B;AACpG,SAAO;AAAA,IACL,4BAA4B,KAAK;AAAA,MAC/B;AAAA,QACE,IAAI,kCAAkC;AAAA,QACtC;AAAA,QACA,EAAE,SAAS,MAAM,KAAK,kCAAkC;AAAA,MAC1D;AAAA,MACA;AAAA,IACF;AAAA,IACA,oBAAoB;AAAA,MAClB;AAAA,QACE,IAAI,0BAA0B;AAAA,QAC9B;AAAA,QACA,EAAE,SAAS,MAAM,KAAK,0BAA0B;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,4BAA4B,cAA8B;AACjE,QAAM,eAAe,KAAK,KAAK,OAAO,IAAI,IAAI,KAAK;AACnD,QAAM,aAAa,KAAK,MAAM,eAAe,YAAY;AACzD,SAAO,KAAK,IAAI,KAAK,IAAI,YAAY,yBAAyB,GAAG,kBAAkB;AACrF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/lib/version.js
CHANGED
package/dist/lib/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/version.ts"],
|
|
4
|
-
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.
|
|
4
|
+
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8098.1.f4decc8a57';\nexport const appVersion = APP_VERSION;\n"],
|
|
5
5
|
"mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/shared",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8098.1.f4decc8a57",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -130,7 +130,7 @@
|
|
|
130
130
|
"@mikro-orm/core": "^7.1.14",
|
|
131
131
|
"@mikro-orm/decorators": "^7.1.14",
|
|
132
132
|
"@mikro-orm/postgresql": "^7.1.14",
|
|
133
|
-
"@open-mercato/cache": "0.10.1-develop.
|
|
133
|
+
"@open-mercato/cache": "0.10.1-develop.8098.1.f4decc8a57",
|
|
134
134
|
"@types/html-to-text": "^9.0.4",
|
|
135
135
|
"@types/sanitize-html": "^2.16.1",
|
|
136
136
|
"dotenv": "^17.4.2",
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { asValue, createContainer, InjectionMode } from 'awilix'
|
|
2
|
+
import { CommandBus, commandRegistry, registerCommand } from '@open-mercato/shared/lib/commands'
|
|
3
|
+
|
|
4
|
+
const COMMAND_ID = 'test.command.redo-claim'
|
|
5
|
+
|
|
6
|
+
type SourceState = { executionState: string }
|
|
7
|
+
|
|
8
|
+
function buildCasService(source: SourceState) {
|
|
9
|
+
let logCount = 0
|
|
10
|
+
return {
|
|
11
|
+
log: jest.fn(async () => ({ id: `log-${++logCount}` })),
|
|
12
|
+
claimForRedo: jest.fn(async () => {
|
|
13
|
+
await Promise.resolve()
|
|
14
|
+
if (source.executionState !== 'undone') return false
|
|
15
|
+
source.executionState = 'redone'
|
|
16
|
+
return true
|
|
17
|
+
}),
|
|
18
|
+
releaseRedoClaim: jest.fn(async () => {
|
|
19
|
+
if (source.executionState !== 'redone') return false
|
|
20
|
+
source.executionState = 'undone'
|
|
21
|
+
return true
|
|
22
|
+
}),
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function buildCtx(service: Record<string, unknown>) {
|
|
27
|
+
const container = createContainer({ injectionMode: InjectionMode.CLASSIC })
|
|
28
|
+
container.register({ actionLogService: asValue(service) })
|
|
29
|
+
return {
|
|
30
|
+
container,
|
|
31
|
+
auth: { sub: 'user-1', tenantId: 'tenant-1', orgId: null },
|
|
32
|
+
organizationScope: null,
|
|
33
|
+
selectedOrganizationId: null,
|
|
34
|
+
organizationIds: null,
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const sourceLog = { id: 'source-log', commandId: COMMAND_ID }
|
|
39
|
+
|
|
40
|
+
describe('CommandBus.execute redo source claim (non-atomic replay)', () => {
|
|
41
|
+
afterEach(() => {
|
|
42
|
+
commandRegistry.clear()
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('lets only one of two concurrent redos of the same source log run the command', async () => {
|
|
46
|
+
const execute = jest.fn(async () => {
|
|
47
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
48
|
+
return { ok: true }
|
|
49
|
+
})
|
|
50
|
+
registerCommand({ id: COMMAND_ID, execute, undo: jest.fn(async () => undefined) })
|
|
51
|
+
const source = { executionState: 'undone' }
|
|
52
|
+
const service = buildCasService(source)
|
|
53
|
+
const ctx = buildCtx(service)
|
|
54
|
+
const bus = new CommandBus()
|
|
55
|
+
|
|
56
|
+
const outcomes = await Promise.allSettled([
|
|
57
|
+
bus.execute(COMMAND_ID, { input: {}, ctx, redoLogEntry: sourceLog }),
|
|
58
|
+
bus.execute(COMMAND_ID, { input: {}, ctx, redoLogEntry: sourceLog }),
|
|
59
|
+
])
|
|
60
|
+
|
|
61
|
+
const fulfilled = outcomes.filter((outcome) => outcome.status === 'fulfilled')
|
|
62
|
+
const rejected = outcomes.filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')
|
|
63
|
+
expect(fulfilled).toHaveLength(1)
|
|
64
|
+
expect(rejected).toHaveLength(1)
|
|
65
|
+
expect(String(rejected[0].reason)).toContain('Redo source already consumed')
|
|
66
|
+
expect((fulfilled[0] as PromiseFulfilledResult<{ replaySourceFinalized?: boolean }>).value.replaySourceFinalized).toBe(true)
|
|
67
|
+
expect(execute).toHaveBeenCalledTimes(1)
|
|
68
|
+
expect(service.log).toHaveBeenCalledTimes(1)
|
|
69
|
+
expect(service.claimForRedo).toHaveBeenCalledWith('source-log')
|
|
70
|
+
expect(service.releaseRedoClaim).not.toHaveBeenCalled()
|
|
71
|
+
expect(source.executionState).toBe('redone')
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('releases the claim when the command fails so the redo can be retried', async () => {
|
|
75
|
+
const execute = jest
|
|
76
|
+
.fn<Promise<{ ok: boolean }>, []>()
|
|
77
|
+
.mockRejectedValueOnce(new Error('handler boom'))
|
|
78
|
+
.mockResolvedValueOnce({ ok: true })
|
|
79
|
+
registerCommand({ id: COMMAND_ID, execute, undo: jest.fn(async () => undefined) })
|
|
80
|
+
const source = { executionState: 'undone' }
|
|
81
|
+
const service = buildCasService(source)
|
|
82
|
+
const ctx = buildCtx(service)
|
|
83
|
+
const bus = new CommandBus()
|
|
84
|
+
|
|
85
|
+
await expect(
|
|
86
|
+
bus.execute(COMMAND_ID, { input: {}, ctx, redoLogEntry: sourceLog }),
|
|
87
|
+
).rejects.toThrow('handler boom')
|
|
88
|
+
expect(service.releaseRedoClaim).toHaveBeenCalledWith('source-log')
|
|
89
|
+
expect(source.executionState).toBe('undone')
|
|
90
|
+
|
|
91
|
+
const retry = await bus.execute(COMMAND_ID, { input: {}, ctx, redoLogEntry: sourceLog })
|
|
92
|
+
expect(retry.result).toEqual({ ok: true })
|
|
93
|
+
expect(source.executionState).toBe('redone')
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
it('keeps the original command error when releasing the claim fails', async () => {
|
|
97
|
+
registerCommand({
|
|
98
|
+
id: COMMAND_ID,
|
|
99
|
+
execute: jest.fn(async () => {
|
|
100
|
+
throw new Error('handler boom')
|
|
101
|
+
}),
|
|
102
|
+
undo: jest.fn(async () => undefined),
|
|
103
|
+
})
|
|
104
|
+
const source = { executionState: 'undone' }
|
|
105
|
+
const service = {
|
|
106
|
+
...buildCasService(source),
|
|
107
|
+
releaseRedoClaim: jest.fn(async () => {
|
|
108
|
+
throw new Error('release boom')
|
|
109
|
+
}),
|
|
110
|
+
}
|
|
111
|
+
const ctx = buildCtx(service)
|
|
112
|
+
|
|
113
|
+
await expect(
|
|
114
|
+
new CommandBus().execute(COMMAND_ID, { input: {}, ctx, redoLogEntry: sourceLog }),
|
|
115
|
+
).rejects.toThrow('handler boom')
|
|
116
|
+
expect(service.releaseRedoClaim).toHaveBeenCalledTimes(1)
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
it('claims and releases on the caller transaction when ctx carries a transactional EntityManager', async () => {
|
|
120
|
+
registerCommand({
|
|
121
|
+
id: COMMAND_ID,
|
|
122
|
+
execute: jest.fn(async () => {
|
|
123
|
+
throw new Error('handler boom')
|
|
124
|
+
}),
|
|
125
|
+
undo: jest.fn(async () => undefined),
|
|
126
|
+
})
|
|
127
|
+
const source = { executionState: 'undone' }
|
|
128
|
+
const service = buildCasService(source)
|
|
129
|
+
const transactionalEm = { id: 'caller-transaction' }
|
|
130
|
+
const ctx = { ...buildCtx(service), transactionalEm: transactionalEm as never }
|
|
131
|
+
|
|
132
|
+
await expect(
|
|
133
|
+
new CommandBus().execute(COMMAND_ID, { input: {}, ctx, redoLogEntry: sourceLog }),
|
|
134
|
+
).rejects.toThrow('handler boom')
|
|
135
|
+
expect(service.claimForRedo).toHaveBeenCalledWith('source-log', transactionalEm)
|
|
136
|
+
expect(service.releaseRedoClaim).toHaveBeenCalledWith('source-log', transactionalEm)
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it('replays without a claim when the action log service cannot claim redo sources', async () => {
|
|
140
|
+
const execute = jest.fn(async () => ({ ok: true }))
|
|
141
|
+
registerCommand({ id: COMMAND_ID, execute, undo: jest.fn(async () => undefined) })
|
|
142
|
+
const service = { log: jest.fn(async () => ({ id: 'new-log' })) }
|
|
143
|
+
const ctx = buildCtx(service)
|
|
144
|
+
|
|
145
|
+
const outcome = await new CommandBus().execute(COMMAND_ID, { input: {}, ctx, redoLogEntry: sourceLog })
|
|
146
|
+
|
|
147
|
+
expect(execute).toHaveBeenCalledTimes(1)
|
|
148
|
+
expect(outcome.replaySourceFinalized).toBe(false)
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
it('does not claim anything for a plain execute', async () => {
|
|
152
|
+
registerCommand({ id: COMMAND_ID, execute: jest.fn(async () => ({ ok: true })) })
|
|
153
|
+
const source = { executionState: 'undone' }
|
|
154
|
+
const service = buildCasService(source)
|
|
155
|
+
|
|
156
|
+
await new CommandBus().execute(COMMAND_ID, { input: {}, ctx: buildCtx(service) })
|
|
157
|
+
|
|
158
|
+
expect(service.claimForRedo).not.toHaveBeenCalled()
|
|
159
|
+
expect(source.executionState).toBe('undone')
|
|
160
|
+
})
|
|
161
|
+
})
|
|
@@ -96,6 +96,7 @@ describe('CommandBus.undo TOCTOU race guard', () => {
|
|
|
96
96
|
|
|
97
97
|
expect(undoMock).not.toHaveBeenCalled()
|
|
98
98
|
expect(service.markUndone).not.toHaveBeenCalled()
|
|
99
|
+
expect(service.releaseUndoClaim).not.toHaveBeenCalled()
|
|
99
100
|
})
|
|
100
101
|
|
|
101
102
|
it('releases the claim when the undo handler fails so the action stays retryable', async () => {
|
|
@@ -34,6 +34,7 @@ import { CommandInterceptorError } from './errors'
|
|
|
34
34
|
import { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'
|
|
35
35
|
import { createLogger } from '../logger'
|
|
36
36
|
import { withAtomicFlush } from './flush'
|
|
37
|
+
import { getTelemetryRuntime } from '../telemetry/runtime'
|
|
37
38
|
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
38
39
|
import {
|
|
39
40
|
getTransactionLifetime,
|
|
@@ -50,6 +51,7 @@ type CommandActionLogService = {
|
|
|
50
51
|
releaseUndoClaim(id: string, transactionalEm?: EntityManager): Promise<boolean>
|
|
51
52
|
markUndone(id: string, traceInput?: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null | void>
|
|
52
53
|
claimForRedo(id: string, transactionalEm?: EntityManager): Promise<boolean>
|
|
54
|
+
releaseRedoClaim?(id: string, transactionalEm?: EntityManager): Promise<boolean>
|
|
53
55
|
log(input: ActionLogCreateInput, transactionalEm?: EntityManager): Promise<ActionLog | null>
|
|
54
56
|
}
|
|
55
57
|
|
|
@@ -494,6 +496,15 @@ export class CommandBus {
|
|
|
494
496
|
coreResult = await executeCore(effectiveOptions)
|
|
495
497
|
}], { transaction: true, label: `${commandId}.redo` })
|
|
496
498
|
replaySourceFinalized = !ambientReplay.joinsAmbient
|
|
499
|
+
} else if (replayLogEntry?.id) {
|
|
500
|
+
const redoClaimRelease = await this.claimRedoSource(effectiveOptions.ctx, commandId, replayLogEntry.id)
|
|
501
|
+
try {
|
|
502
|
+
coreResult = await executeCore(effectiveOptions)
|
|
503
|
+
} catch (err) {
|
|
504
|
+
await redoClaimRelease?.()
|
|
505
|
+
throw err
|
|
506
|
+
}
|
|
507
|
+
replaySourceFinalized = redoClaimRelease !== null
|
|
497
508
|
} else {
|
|
498
509
|
coreResult = await executeCore(effectiveOptions)
|
|
499
510
|
}
|
|
@@ -670,10 +681,12 @@ export class CommandBus {
|
|
|
670
681
|
label: `${log.commandId}.undo`,
|
|
671
682
|
})
|
|
672
683
|
} else {
|
|
684
|
+
let undoClaimed = false
|
|
673
685
|
try {
|
|
674
686
|
// Preserve the established non-atomic lifecycle exactly: authorization,
|
|
675
687
|
// source claim, before-undo interceptors, handler, then finalization.
|
|
676
688
|
await claimUndo()
|
|
689
|
+
undoClaimed = true
|
|
677
690
|
const prepared = await runBeforeUndoInterceptors(ctx)
|
|
678
691
|
undoInterceptorMetadata = prepared.metadata
|
|
679
692
|
userFeatures = prepared.userFeatures
|
|
@@ -681,7 +694,15 @@ export class CommandBus {
|
|
|
681
694
|
} catch (err) {
|
|
682
695
|
// Legacy handlers retain their compensating release behavior because
|
|
683
696
|
// their domain mutation may not share the action-log transaction.
|
|
684
|
-
|
|
697
|
+
if (undoClaimed) {
|
|
698
|
+
await service.releaseUndoClaim(log.id).catch((releaseErr: unknown) => {
|
|
699
|
+
logger.error('Failed to release undo claim', { commandId: log.commandId, logId: log.id, err: releaseErr })
|
|
700
|
+
getTelemetryRuntime()?.reportError(releaseErr, {
|
|
701
|
+
module: 'shared',
|
|
702
|
+
code: 'shared.undo_claim_release_failed',
|
|
703
|
+
})
|
|
704
|
+
})
|
|
705
|
+
}
|
|
685
706
|
throw err
|
|
686
707
|
}
|
|
687
708
|
}
|
|
@@ -819,6 +840,43 @@ export class CommandBus {
|
|
|
819
840
|
}], { transaction: true, label: `${logEntry.commandId}.${operation}.request-guard` })
|
|
820
841
|
}
|
|
821
842
|
|
|
843
|
+
private async claimRedoSource(
|
|
844
|
+
ctx: CommandRuntimeContext,
|
|
845
|
+
commandId: string,
|
|
846
|
+
sourceLogId: string,
|
|
847
|
+
): Promise<(() => Promise<void>) | null> {
|
|
848
|
+
let service: CommandActionLogService | null = null
|
|
849
|
+
try {
|
|
850
|
+
service = ctx.container.resolve('actionLogService') as CommandActionLogService
|
|
851
|
+
} catch {
|
|
852
|
+
service = null
|
|
853
|
+
}
|
|
854
|
+
if (!service || typeof service.claimForRedo !== 'function' || typeof service.releaseRedoClaim !== 'function') {
|
|
855
|
+
logger.warn('Redo source claim unavailable; replaying without an atomic claim', { commandId, sourceLogId })
|
|
856
|
+
return null
|
|
857
|
+
}
|
|
858
|
+
const releaseClaim = service.releaseRedoClaim.bind(service)
|
|
859
|
+
const transactionalEm = ctx.transactionalEm
|
|
860
|
+
const claimed = transactionalEm
|
|
861
|
+
? await service.claimForRedo(sourceLogId, transactionalEm)
|
|
862
|
+
: await service.claimForRedo(sourceLogId)
|
|
863
|
+
if (!claimed) throw new Error('[internal] Redo source already consumed')
|
|
864
|
+
return async () => {
|
|
865
|
+
try {
|
|
866
|
+
const released = transactionalEm
|
|
867
|
+
? await releaseClaim(sourceLogId, transactionalEm)
|
|
868
|
+
: await releaseClaim(sourceLogId)
|
|
869
|
+
if (!released) logger.warn('Redo source claim was not held at release', { commandId, sourceLogId })
|
|
870
|
+
} catch (releaseErr) {
|
|
871
|
+
logger.error('Failed to release redo source claim', { commandId, sourceLogId, err: releaseErr })
|
|
872
|
+
getTelemetryRuntime()?.reportError(releaseErr, {
|
|
873
|
+
module: 'shared',
|
|
874
|
+
code: 'shared.redo_claim_release_failed',
|
|
875
|
+
})
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
822
880
|
private async resolveHandler<TInput, TResult>(commandId: string): Promise<CommandHandler<TInput, TResult>> {
|
|
823
881
|
const handler =
|
|
824
882
|
commandRegistry.get<TInput, TResult>(commandId) ??
|
|
@@ -166,8 +166,11 @@ export type CommandExecuteResult<TResult> = {
|
|
|
166
166
|
* that transaction has committed. An ambient replay returns this as false
|
|
167
167
|
* while its caller-owned transaction is still active; the returned result
|
|
168
168
|
* object is updated to true by the owner's commit callback. It remains false
|
|
169
|
-
* on rollback.
|
|
170
|
-
*
|
|
169
|
+
* on rollback. A non-atomic redo returns true once its compare-and-set claim
|
|
170
|
+
* moved the source log to redone before the command ran; with
|
|
171
|
+
* `ctx.transactionalEm` that claim is part of the caller's transaction, whose
|
|
172
|
+
* rollback reverts it. Callers that historically finalized redo themselves
|
|
173
|
+
* can use this additive signal to avoid a redundant post-commit write.
|
|
171
174
|
*/
|
|
172
175
|
replaySourceFinalized?: boolean
|
|
173
176
|
}
|
|
@@ -567,6 +567,8 @@ describe('structured logging facade', () => {
|
|
|
567
567
|
const [firstLine, ...stackLines] = chunks[0].split('\n')
|
|
568
568
|
expect(firstLine).toContain('ERROR [err-ns] Handler error event=x.y.z')
|
|
569
569
|
expect(stackLines.join('\n')).toContain('pretty kaboom')
|
|
570
|
+
expect(stackLines[0]).toBe(' Error: pretty kaboom')
|
|
571
|
+
expect(stackLines.filter(Boolean).every((stackLine) => stackLine.startsWith(' '))).toBe(true)
|
|
570
572
|
})
|
|
571
573
|
|
|
572
574
|
it('gates each method by the effective level', () => {
|
|
@@ -63,6 +63,12 @@ function formatTimestamp(date: Date): string {
|
|
|
63
63
|
return `${hours}:${minutes}:${seconds}.${millis}`
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
const STACK_INDENT = ' '
|
|
67
|
+
|
|
68
|
+
function indentStack(stack: string): string {
|
|
69
|
+
return stack.split('\n').map((stackLine) => `${STACK_INDENT}${stackLine}`).join('\n')
|
|
70
|
+
}
|
|
71
|
+
|
|
66
72
|
export function createPrettyLogger(namespace: string, bindings: LogBindings = {}): Logger {
|
|
67
73
|
const emit = (level: LogLevel, msg: string, fields?: LogBindings): void => {
|
|
68
74
|
if (!isLevelEnabled(level)) return
|
|
@@ -81,7 +87,9 @@ export function createPrettyLogger(namespace: string, bindings: LogBindings = {}
|
|
|
81
87
|
const levelPart = colored ? `${LEVEL_COLORS[level]}${label}${ANSI_RESET}` : label
|
|
82
88
|
let line = `${timestampPart} ${levelPart} [${scope}] ${msg}`
|
|
83
89
|
if (tail) line += ` ${tail}`
|
|
84
|
-
|
|
90
|
+
// Indented so log readers (e.g. the dev runtime filter) can tell the
|
|
91
|
+
// entry's own stack from unrelated `Error:` output that follows it.
|
|
92
|
+
if (err instanceof Error) line += `\n${indentStack(err.stack ?? err.message)}`
|
|
85
93
|
stream.write(`${line}\n`)
|
|
86
94
|
}
|
|
87
95
|
return {
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SSE_AUTH_REVALIDATION_INTERVAL_ENV,
|
|
3
|
+
SSE_CONNECTION_MAX_AGE_ENV,
|
|
4
|
+
resolveSseConnectionBounds,
|
|
5
|
+
} from '../connectionBounds'
|
|
6
|
+
|
|
7
|
+
const MAX_TIMER_DELAY_MS = 2_147_483_647
|
|
8
|
+
|
|
9
|
+
function envWith(revalidation?: string, maxAge?: string): NodeJS.ProcessEnv {
|
|
10
|
+
const env: NodeJS.ProcessEnv = {}
|
|
11
|
+
if (revalidation !== undefined) env[SSE_AUTH_REVALIDATION_INTERVAL_ENV] = revalidation
|
|
12
|
+
if (maxAge !== undefined) env[SSE_CONNECTION_MAX_AGE_ENV] = maxAge
|
|
13
|
+
return env
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('resolveSseConnectionBounds', () => {
|
|
17
|
+
let randomSpy: jest.SpyInstance<number, []>
|
|
18
|
+
|
|
19
|
+
beforeEach(() => {
|
|
20
|
+
randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0.5)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
afterEach(() => {
|
|
24
|
+
randomSpy.mockRestore()
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('uses the defaults when the env is unset', () => {
|
|
28
|
+
expect(resolveSseConnectionBounds(envWith())).toEqual({
|
|
29
|
+
authRevalidationIntervalMs: 30_000,
|
|
30
|
+
connectionMaxAgeMs: 300_000,
|
|
31
|
+
})
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('reads configured positive integer values', () => {
|
|
35
|
+
expect(resolveSseConnectionBounds(envWith('5000', '60000'))).toEqual({
|
|
36
|
+
authRevalidationIntervalMs: 5_000,
|
|
37
|
+
connectionMaxAgeMs: 60_000,
|
|
38
|
+
})
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it.each(['abc', '-1', '0', '999', '1.5', ''])('falls back to the defaults for invalid value %p', (value) => {
|
|
42
|
+
expect(resolveSseConnectionBounds(envWith(value, value))).toEqual({
|
|
43
|
+
authRevalidationIntervalMs: 30_000,
|
|
44
|
+
connectionMaxAgeMs: 300_000,
|
|
45
|
+
})
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('caps both values at the Node timer maximum', () => {
|
|
49
|
+
randomSpy.mockReturnValue(1)
|
|
50
|
+
const bounds = resolveSseConnectionBounds(envWith('9999999999999', '9999999999999'))
|
|
51
|
+
expect(bounds.authRevalidationIntervalMs).toBe(MAX_TIMER_DELAY_MS)
|
|
52
|
+
expect(bounds.connectionMaxAgeMs).toBe(MAX_TIMER_DELAY_MS)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('applies at most 15% jitter to the max age and never drops below 1000ms', () => {
|
|
56
|
+
randomSpy.mockReturnValue(0)
|
|
57
|
+
expect(resolveSseConnectionBounds(envWith(undefined, '100000')).connectionMaxAgeMs).toBe(85_000)
|
|
58
|
+
randomSpy.mockReturnValue(0.999999)
|
|
59
|
+
expect(resolveSseConnectionBounds(envWith(undefined, '100000')).connectionMaxAgeMs).toBe(115_000)
|
|
60
|
+
randomSpy.mockReturnValue(0)
|
|
61
|
+
expect(resolveSseConnectionBounds(envWith(undefined, '1000')).connectionMaxAgeMs).toBe(1_000)
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('reads process.env by default on every call', () => {
|
|
65
|
+
const previous = process.env[SSE_AUTH_REVALIDATION_INTERVAL_ENV]
|
|
66
|
+
try {
|
|
67
|
+
process.env[SSE_AUTH_REVALIDATION_INTERVAL_ENV] = '2000'
|
|
68
|
+
expect(resolveSseConnectionBounds().authRevalidationIntervalMs).toBe(2_000)
|
|
69
|
+
process.env[SSE_AUTH_REVALIDATION_INTERVAL_ENV] = '3000'
|
|
70
|
+
expect(resolveSseConnectionBounds().authRevalidationIntervalMs).toBe(3_000)
|
|
71
|
+
} finally {
|
|
72
|
+
if (previous === undefined) delete process.env[SSE_AUTH_REVALIDATION_INTERVAL_ENV]
|
|
73
|
+
else process.env[SSE_AUTH_REVALIDATION_INTERVAL_ENV] = previous
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
})
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { parseNumberWithDefault } from '../number'
|
|
2
|
+
|
|
3
|
+
export const SSE_AUTH_REVALIDATION_INTERVAL_ENV = 'OM_EVENTS_SSE_AUTH_REVALIDATION_INTERVAL_MS'
|
|
4
|
+
export const SSE_CONNECTION_MAX_AGE_ENV = 'OM_EVENTS_SSE_CONNECTION_MAX_AGE_MS'
|
|
5
|
+
|
|
6
|
+
const DEFAULT_AUTH_REVALIDATION_INTERVAL_MS = 30_000
|
|
7
|
+
const DEFAULT_CONNECTION_MAX_AGE_MS = 5 * 60_000
|
|
8
|
+
const MIN_AUTH_REVALIDATION_INTERVAL_MS = 1_000
|
|
9
|
+
const MIN_CONNECTION_MAX_AGE_MS = 1_000
|
|
10
|
+
const CONNECTION_MAX_AGE_JITTER_RATIO = 0.15
|
|
11
|
+
const MAX_TIMER_DELAY_MS = 2_147_483_647
|
|
12
|
+
|
|
13
|
+
export type SseConnectionBounds = {
|
|
14
|
+
authRevalidationIntervalMs: number
|
|
15
|
+
connectionMaxAgeMs: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Per-connection timing shared by the DOM Event Bridge and the Portal Event Bridge.
|
|
20
|
+
* Reads the env on every call so each new stream picks up the current bounds; the
|
|
21
|
+
* max age gets ±15% jitter so streams opened together do not reconnect together.
|
|
22
|
+
*/
|
|
23
|
+
export function resolveSseConnectionBounds(env: NodeJS.ProcessEnv = process.env): SseConnectionBounds {
|
|
24
|
+
return {
|
|
25
|
+
authRevalidationIntervalMs: Math.min(
|
|
26
|
+
parseNumberWithDefault(
|
|
27
|
+
env[SSE_AUTH_REVALIDATION_INTERVAL_ENV],
|
|
28
|
+
DEFAULT_AUTH_REVALIDATION_INTERVAL_MS,
|
|
29
|
+
{ integer: true, min: MIN_AUTH_REVALIDATION_INTERVAL_MS },
|
|
30
|
+
),
|
|
31
|
+
MAX_TIMER_DELAY_MS,
|
|
32
|
+
),
|
|
33
|
+
connectionMaxAgeMs: applyConnectionMaxAgeJitter(
|
|
34
|
+
parseNumberWithDefault(
|
|
35
|
+
env[SSE_CONNECTION_MAX_AGE_ENV],
|
|
36
|
+
DEFAULT_CONNECTION_MAX_AGE_MS,
|
|
37
|
+
{ integer: true, min: MIN_CONNECTION_MAX_AGE_MS },
|
|
38
|
+
),
|
|
39
|
+
),
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function applyConnectionMaxAgeJitter(configuredMs: number): number {
|
|
44
|
+
const jitterFactor = 1 + (Math.random() * 2 - 1) * CONNECTION_MAX_AGE_JITTER_RATIO
|
|
45
|
+
const jitteredMs = Math.round(configuredMs * jitterFactor)
|
|
46
|
+
return Math.min(Math.max(jitteredMs, MIN_CONNECTION_MAX_AGE_MS), MAX_TIMER_DELAY_MS)
|
|
47
|
+
}
|
|
@@ -222,6 +222,11 @@ export type InjectionWidgetPlacement = {
|
|
|
222
222
|
* order.
|
|
223
223
|
*/
|
|
224
224
|
priority?: number
|
|
225
|
+
/**
|
|
226
|
+
* Optional lucide icon name (`'list-checks'`, `'ListChecks'` or `'lucide:list-checks'`)
|
|
227
|
+
* shown next to the label by hosts that render the widget as a tab.
|
|
228
|
+
*/
|
|
229
|
+
icon?: string
|
|
225
230
|
}
|
|
226
231
|
|
|
227
232
|
/**
|