@cosmicdrift/kumiko-framework 0.146.2 → 0.146.4

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.
@@ -1,119 +1,22 @@
1
- import { requestContext } from "../api/request-context";
2
- import type { DbConnection, DbRow, DbTx } from "../db/connection";
3
- import { selectRowForUpdateById } from "../db/queries/entity-read";
4
- import { asEntityTableMeta, selectMany, transaction } from "../db/query";
5
- import { buildEntityTable, toSnakeCase } from "../db/table-builder";
6
- import { createTenantDb } from "../db/tenant-db";
7
- import { hasAccess } from "../engine/access";
8
- import { checkWriteFieldRoles, filterReadFields } from "../engine/field-access";
9
- import { defineTransitions, guardTransition } from "../engine/state-machine";
1
+ import type { buildEntityTable } from "../db/table-builder";
2
+ import type { defineTransitions } from "../engine/state-machine";
10
3
  import type { EffectiveFeaturesResolver } from "../engine/tier-resolver-extension";
11
- import type {
12
- AggregateStreamHandle,
13
- AppContext,
14
- AppendEventArgs,
15
- AppendEventFn,
16
- AuthClaimsContext,
17
- DeleteContext,
18
- FetchForWritingArgs,
19
- HandlerContext,
20
- JobRunnerRef,
21
- Registry,
22
- SaveContext,
23
- SessionUser,
24
- WriteResult,
25
- } from "../engine/types";
26
- import { HookPhases } from "../engine/types";
27
- import type { TenantId } from "../engine/types/identifiers";
28
- import { createFileContext } from "../files/file-handle";
29
- import { createFallbackLogger } from "../logging/utils";
4
+ import type { AppContext, JobRunnerRef, Registry, SessionUser, WriteResult } from "../engine/types";
5
+ import { reraiseAsKumikoError } from "../errors";
6
+ import { getFallbackMeter, getFallbackTracer, registerStandardMetrics } from "../observability";
7
+ import { runBatch, unwrapSingle } from "./dispatch-batch";
8
+ import { executeQuery } from "./dispatch-query";
9
+ import type { BatchCommand, BatchResult, DispatchContext } from "./dispatch-shared";
10
+ import { resolveAuthClaimsFn } from "./dispatch-shared";
11
+ import { type HandlerType, resolveType } from "./dispatcher-utils";
12
+ import type { IdempotencyGuard } from "./idempotency";
13
+ import type { LifecycleHooks } from "./lifecycle-pipeline";
30
14
 
31
15
  // Re-export for callers that reach for dispatcher-adjacent types (tests,
32
16
  // HTTP-layer stubs) — dispatch consumes these, grouping the type-surface
33
17
  // here keeps imports single-source.
34
18
  export type { WriteResult } from "../engine/types";
35
-
36
- import { runValidation } from "../engine/validation";
37
- import {
38
- AccessDeniedError,
39
- FeatureDisabledError,
40
- FrameworkReasons,
41
- InternalError,
42
- isKumikoError,
43
- NotFoundError,
44
- reraiseAsKumikoError,
45
- toWriteErrorInfo,
46
- ValidationError,
47
- VersionConflictError,
48
- validationErrorFromZod,
49
- type WriteErrorInfo,
50
- writeFailure,
51
- } from "../errors";
52
- import {
53
- archiveStream as archiveStreamHelper,
54
- isStreamArchived,
55
- restoreStream as restoreStreamHelper,
56
- } from "../event-store/archive";
57
- import {
58
- getStreamVersion,
59
- loadAggregate,
60
- loadAggregateAsOf,
61
- type StoredEvent,
62
- } from "../event-store/event-store";
63
- import {
64
- type LoadAggregateWithSnapshotOptions,
65
- type LoadAggregateWithSnapshotResult,
66
- loadAggregateWithSnapshot,
67
- type SnapshotReducer,
68
- saveSnapshot,
69
- } from "../event-store/snapshot";
70
- import { upcastStoredEvent, upcastStoredEvents } from "../event-store/upcaster";
71
- import {
72
- createMetricsHandle,
73
- createNoopMetricsHandle,
74
- emitDispatcherError,
75
- emitDispatcherHandler,
76
- getFallbackMeter,
77
- getFallbackTracer,
78
- registerStandardMetrics,
79
- } from "../observability";
80
- import { buildBucketKey } from "../rate-limit";
81
- import { assertNoSecretLeak } from "../secrets";
82
- import { createTzContext } from "../time";
83
- import { parseJsonSafe } from "../utils/safe-json";
84
- import { appendDomainEventCore } from "./append-event-core";
85
- import { resolveAuthClaims as runAuthClaimsResolver } from "./auth-claims-resolver";
86
- import {
87
- type AfterCommitHook,
88
- BatchRollback,
89
- describeShape,
90
- dispatcherSpanAttributes,
91
- extractNestedSpecs,
92
- type HandlerType,
93
- isFailedWriteResult,
94
- isLifecycleResult,
95
- isWriteResultShape,
96
- prefixValidationPath,
97
- resolveType,
98
- wrapToKumiko,
99
- } from "./dispatcher-utils";
100
- import type { IdempotencyGuard } from "./idempotency";
101
- import type { LifecycleHooks } from "./lifecycle-pipeline";
102
- import { runProjections } from "./projections-runner";
103
-
104
- export type BatchCommand = {
105
- readonly type: string;
106
- readonly payload: unknown;
107
- };
108
-
109
- export type BatchResult =
110
- | { readonly isSuccess: true; readonly results: readonly WriteResult[] }
111
- | {
112
- readonly isSuccess: false;
113
- readonly error: WriteErrorInfo;
114
- readonly failedIndex: number;
115
- readonly results: readonly WriteResult[];
116
- };
19
+ export type { BatchCommand, BatchResult } from "./dispatch-shared";
117
20
 
118
21
  export type DispatcherOptions = {
119
22
  idempotency?: IdempotencyGuard;
@@ -176,1291 +79,44 @@ export function createDispatcher(
176
79
  ): Dispatcher {
177
80
  const { idempotency, lifecycle, jobRunner, effectiveFeatures } = options;
178
81
 
179
- // Narrowing-helper: AppContext.db ist DbConnection|TenantDb|undefined. Die
180
- // dispatch-Pfade brauchen DbConnection (oder DbTx aus Caller-Scope) für
181
- // appendEvent/projection-writes; TenantDb-Branch wird hier ausgeschlossen.
182
- function resolveDbSource(tx: DbTx | undefined): DbConnection | DbTx | undefined {
183
- return tx ?? (context.db as DbConnection | undefined); // @cast-boundary db-operator
184
- }
185
-
186
82
  // Pre-build tables and transition maps for auto-guard (avoid per-request allocation)
187
83
  const tableCache = new Map<string, ReturnType<typeof buildEntityTable>>();
188
84
  const transitionCache = new Map<string, ReturnType<typeof defineTransitions>>();
189
85
 
190
- function getTable(entityName: string): ReturnType<typeof buildEntityTable> | undefined {
191
- if (tableCache.has(entityName)) return tableCache.get(entityName);
192
- const entity = registry.getEntity(entityName);
193
- if (!entity) return undefined;
194
- const table = buildEntityTable(entityName, entity, {
195
- relations: registry.getRelations(entityName),
196
- });
197
- tableCache.set(entityName, table);
198
- return table;
199
- }
200
-
201
- function getTransitions(args: {
202
- entityName: string;
203
- fieldName: string;
204
- map: Record<string, readonly string[]>;
205
- }): ReturnType<typeof defineTransitions> {
206
- // Scope by entity — `fieldName` alone collides across entities (e.g. both
207
- // `invoice.status` and `driverOrder.status` exist with different maps),
208
- // which would apply the wrong transition rules to whichever entity arrives
209
- // second.
210
- const key = `${args.entityName}:${args.fieldName}`;
211
- const cached = transitionCache.get(key);
212
- if (cached) return cached;
213
- const transitions = defineTransitions(args.map);
214
- transitionCache.set(key, transitions);
215
- return transitions;
216
- }
217
-
218
- // ctx.appendEvent — append a domain event onto a specific aggregate stream
219
- // in the current tx, then fire matching inline projections. Core logic
220
- // lives in appendDomainEventCore; this wrapper just locates dbSource +
221
- // stringifies the SessionUser id for the shared helper.
222
- async function appendDomainEvent(
223
- args: AppendEventArgs,
224
- user: SessionUser,
225
- tx: DbTx | undefined,
226
- callerFeature: string | undefined,
227
- ): Promise<void> {
228
- const dbSource = resolveDbSource(tx);
229
- if (!dbSource) {
230
- throw new InternalError({
231
- message: `ctx.appendEvent("${args.type}") requires a database connection — none is configured.`,
232
- });
233
- }
234
- await appendDomainEventCore(
235
- {
236
- registry,
237
- db: dbSource,
238
- tenantId: user.tenantId,
239
- userId: String(user.id),
240
- callSiteLabel: "ctx.appendEvent",
241
- callerFeature,
242
- },
243
- args,
244
- );
245
- }
246
-
247
- function buildHandlerContext(
248
- type: string,
249
- user: SessionUser,
250
- tx?: DbTx,
251
- afterCommitHooks?: AfterCommitHook[],
252
- includeDeleted?: boolean,
253
- ): HandlerContext {
254
- const isSystem = registry.isHandlerSystemScoped(type);
255
- // The outer dispatcher receives a DbConnection from the server/stack;
256
- // AppContext's `db` union also allows TenantDb (for downstream hook calls),
257
- // but at this point we're the root of the pipeline — cast is safe.
258
- const dbSource = resolveDbSource(tx);
259
- const reqCtx = requestContext.get();
260
- const db = dbSource
261
- ? createTenantDb(
262
- dbSource,
263
- user.tenantId,
264
- isSystem ? "system" : "tenant",
265
- context.tracer,
266
- context.meter,
267
- // Propagate the request's AbortSignal so every TenantDb query
268
- // throws when the client has disconnected — handlers with many
269
- // sequential queries skip the rest of the chain instead of
270
- // burning DB-CPU for results no one reads.
271
- reqCtx?.signal,
272
- )
273
- : undefined;
274
- const log = context.log?.child({
275
- handler: type,
276
- tenantId: user.tenantId,
277
- userId: user.id,
278
- ...(reqCtx && { requestId: reqCtx.requestId }),
279
- });
280
- const notify = context._notifyFactory ? context._notifyFactory(user, user.tenantId) : undefined;
281
- // Mirror notify: only built when the config feature wired its factory.
282
- const config =
283
- context._configAccessorFactory && db
284
- ? context._configAccessorFactory({
285
- user: { id: user.id, tenantId: user.tenantId },
286
- db,
287
- secrets: context.secrets,
288
- })
289
- : undefined;
290
- // ctx.files resolved per-tenant through file-foundation (lazy — the
291
- // provider is only resolved when a handle actually does I/O). Boot wires
292
- // _fileProviderResolver when a file-provider plugin is mounted; falls back
293
- // to a statically-injected context.files (tests).
294
- const fileResolver = context._fileProviderResolver;
295
- const files = fileResolver
296
- ? createFileContext(() => fileResolver(user.tenantId))
297
- : context.files;
298
-
299
- // Observability — feature-bound metrics handle, so ctx.metrics.inc("foo")
300
- // resolves to kumiko_<feature>_foo. Unknown feature falls back to noop
301
- // so legacy internal handlers don't crash.
302
- const tracer = context.tracer ?? getFallbackTracer();
303
- const meter = context.meter;
304
- const featureName = registry.getHandlerFeature(type);
305
- const metrics =
306
- meter && featureName ? createMetricsHandle(meter, featureName) : createNoopMetricsHandle();
307
-
308
- // Cross-feature bridge. Queries and writes invoked through ctx.* share:
309
- // - the current transaction (tx) — nested writes roll back with the parent
310
- // - the current afterCommitHooks sink — deferred side-effects fire once
311
- // when the outermost transaction commits
312
- // `queryAs` / `writeAs` let a handler explicitly switch identity
313
- // (e.g. system-privileged lookups that bypass field-access read filters).
314
- const bridgeSink = afterCommitHooks ?? [];
315
- const bridge = {
316
- query: (targetType: string, payload: unknown) => executeQuery(targetType, payload, user, tx), // @wrapper-known semantic-alias
317
- queryAs: (asUser: SessionUser, targetType: string, payload: unknown) =>
318
- executeQuery(targetType, payload, asUser, tx), // @wrapper-known semantic-alias
319
- write: async (targetType: string, payload: unknown) => {
320
- const res = await executeWrite(targetType, payload, user, tx, bridgeSink);
321
- return res;
322
- },
323
- writeAs: async (asUser: SessionUser, targetType: string, payload: unknown) => {
324
- const res = await executeWrite(targetType, payload, asUser, tx, bridgeSink);
325
- return res;
326
- },
327
- // Strict + unsafe share the same runtime — only the type-surface
328
- // differs. The strict signature is what's exposed to typed callers;
329
- // unsafe is the explicit escape-hatch for runtime-pluggable events.
330
- appendEvent: (async (args: AppendEventArgs) => {
331
- await appendDomainEvent(args, user, tx, registry.getHandlerFeature(type));
332
- }) as AppendEventFn, // @cast-boundary engine-bridge
333
- unsafeAppendEvent: async (args: AppendEventArgs) => {
334
- await appendDomainEvent(args, user, tx, registry.getHandlerFeature(type));
335
- },
336
- fetchForWriting: async (args: FetchForWritingArgs): Promise<AggregateStreamHandle> => {
337
- const dbSource = resolveDbSource(tx);
338
- if (!dbSource) {
339
- throw new InternalError({
340
- message: `ctx.fetchForWriting("${args.aggregateId}") requires a database connection — none is configured.`,
341
- });
342
- }
343
- // Stream-version authoritative (same policy as CRUD executor + Block 0).
344
- // A single SELECT MAX(version) is cheaper than loading the full stream
345
- // when the caller just wants to append — but most callers also want
346
- // the events (business-rule checks), so fetch both in parallel.
347
- const [storedEvents, fetchedVersion] = await Promise.all([
348
- loadAggregate(dbSource, args.aggregateId, user.tenantId),
349
- getStreamVersion(dbSource, args.aggregateId, user.tenantId),
350
- ]);
351
- const events = await upcastStoredEvents(storedEvents, registry.getEventUpcasters(), {
352
- db: dbSource,
353
- tenantId: user.tenantId,
354
- });
355
-
356
- // Optimistic concurrency: if the caller knows the version they
357
- // worked against (e.g. from a prior read-model row) and the stream
358
- // has moved on, fail fast before any downstream work.
359
- if (args.expectedVersion !== undefined && args.expectedVersion !== fetchedVersion) {
360
- throw new VersionConflictError({
361
- entityId: args.aggregateId,
362
- expectedVersion: args.expectedVersion,
363
- currentVersion: fetchedVersion,
364
- });
365
- }
366
-
367
- // Handle's internal version bumps on every appendOne so multiple
368
- // appends in a row stay in order without re-reading the DB.
369
- let handleVersion = fetchedVersion;
370
- const appendOne = async (appendArgs: {
371
- readonly type: string;
372
- readonly payload: unknown;
373
- }): Promise<void> => {
374
- await appendDomainEvent(
375
- {
376
- aggregateId: args.aggregateId,
377
- aggregateType: args.aggregateType,
378
- type: appendArgs.type,
379
- payload: appendArgs.payload,
380
- },
381
- user,
382
- tx,
383
- registry.getHandlerFeature(type),
384
- );
385
- handleVersion += 1;
386
- };
387
-
388
- return {
389
- events,
390
- get version() {
391
- return handleVersion;
392
- },
393
- appendOne,
394
- };
395
- },
396
- loadAggregate: async (
397
- aggregateId: string,
398
- loadOptions?: { readonly asOf?: Temporal.Instant },
399
- ): Promise<readonly StoredEvent[]> => {
400
- const dbSource = resolveDbSource(tx);
401
- if (!dbSource) {
402
- throw new InternalError({
403
- message: `ctx.loadAggregate("${aggregateId}") requires a database connection — none is configured.`,
404
- });
405
- }
406
- const events = loadOptions?.asOf
407
- ? await loadAggregateAsOf(dbSource, aggregateId, user.tenantId, loadOptions.asOf)
408
- : await loadAggregate(dbSource, aggregateId, user.tenantId);
409
- return upcastStoredEvents(events, registry.getEventUpcasters(), {
410
- db: dbSource,
411
- tenantId: user.tenantId,
412
- });
413
- },
414
- archiveStream: async (
415
- aggregateId: string,
416
- archiveArgs: { readonly aggregateType: string; readonly reason?: string },
417
- ): Promise<void> => {
418
- const dbSource = resolveDbSource(tx);
419
- if (!dbSource) {
420
- throw new InternalError({
421
- message: `ctx.archiveStream("${aggregateId}") requires a database connection — none is configured.`,
422
- });
423
- }
424
- await archiveStreamHelper(dbSource, {
425
- tenantId: user.tenantId,
426
- aggregateId,
427
- aggregateType: archiveArgs.aggregateType,
428
- archivedBy: user.id,
429
- reason: archiveArgs.reason,
430
- });
431
- },
432
- restoreStream: async (aggregateId: string): Promise<void> => {
433
- const dbSource = resolveDbSource(tx);
434
- if (!dbSource) {
435
- throw new InternalError({
436
- message: `ctx.restoreStream("${aggregateId}") requires a database connection — none is configured.`,
437
- });
438
- }
439
- await restoreStreamHelper(dbSource, user.tenantId, aggregateId);
440
- },
441
- isStreamArchived: async (aggregateId: string): Promise<boolean> => {
442
- const dbSource = resolveDbSource(tx);
443
- if (!dbSource) {
444
- throw new InternalError({
445
- message: `ctx.isStreamArchived("${aggregateId}") requires a database connection — none is configured.`,
446
- });
447
- }
448
- return isStreamArchived(dbSource, user.tenantId, aggregateId);
449
- },
450
- snapshotAggregate: async (snapshotArgs: {
451
- readonly aggregateId: string;
452
- readonly aggregateType: string;
453
- readonly version: number;
454
- readonly state: Record<string, unknown>;
455
- readonly snapshotVersion?: number;
456
- }): Promise<void> => {
457
- const dbSource = resolveDbSource(tx);
458
- if (!dbSource) {
459
- throw new InternalError({
460
- message: `ctx.snapshotAggregate("${snapshotArgs.aggregateId}") requires a database connection — none is configured.`,
461
- });
462
- }
463
- await saveSnapshot(dbSource, {
464
- aggregateId: snapshotArgs.aggregateId,
465
- tenantId: user.tenantId,
466
- aggregateType: snapshotArgs.aggregateType,
467
- version: snapshotArgs.version,
468
- state: snapshotArgs.state,
469
- snapshotVersion: snapshotArgs.snapshotVersion,
470
- });
471
- },
472
- loadAggregateWithSnapshot: async <TState extends Record<string, unknown>>(
473
- aggregateId: string,
474
- reducer: SnapshotReducer<TState>,
475
- initial: TState,
476
- loadOptions?: Omit<LoadAggregateWithSnapshotOptions, "upcastEvent">,
477
- ): Promise<LoadAggregateWithSnapshotResult<TState>> => {
478
- const dbSource = resolveDbSource(tx);
479
- if (!dbSource) {
480
- throw new InternalError({
481
- message: `ctx.loadAggregateWithSnapshot("${aggregateId}") requires a database connection — none is configured.`,
482
- });
483
- }
484
- // Upcaster-aware: pass an upcastEvent callback so loadAggregateWithSnapshot
485
- // walks every delta through the registered chain before invoking the
486
- // user's (sync) reducer. Async upcasters (DB-enrichment) are awaited
487
- // inside loadAggregateWithSnapshot — feature authors never see legacy
488
- // payload shapes regardless of which load path they chose.
489
- const upcasters = registry.getEventUpcasters();
490
- const upcastCtx = { db: dbSource, tenantId: user.tenantId };
491
- return loadAggregateWithSnapshot<TState>(
492
- dbSource,
493
- aggregateId,
494
- user.tenantId,
495
- reducer,
496
- initial,
497
- {
498
- ...loadOptions,
499
- upcastEvent: (event) => upcastStoredEvent(event, upcasters, upcastCtx), // @wrapper-known semantic-alias
500
- },
501
- );
502
- },
503
- queryProjection: async <T = Record<string, unknown>>(
504
- qualifiedName: string,
505
- queryOptions?: { readonly unsafeAllTenants?: boolean },
506
- ): Promise<readonly T[]> => {
507
- // queryProjection works against both single-stream and multi-stream
508
- // projections. MSPs without a table cannot be queried — those are
509
- // side-effect-only consumers (no state to read back).
510
- const singleProj = registry.getAllProjections().get(qualifiedName);
511
- const mspProj = registry.getAllMultiStreamProjections().get(qualifiedName);
512
- const projTable = singleProj?.table ?? mspProj?.table;
513
- if (!projTable) {
514
- const singleNames = [...registry.getAllProjections().keys()];
515
- const mspNames = [...registry.getAllMultiStreamProjections().keys()].filter(
516
- (n) => registry.getAllMultiStreamProjections().get(n)?.table,
517
- );
518
- const all = [...singleNames, ...mspNames];
519
- throw new InternalError({
520
- message:
521
- `ctx.queryProjection("${qualifiedName}") — projection not registered, or it is a ` +
522
- `table-less MSP (side-effect-only). Known queryable projections: ${all.join(", ") || "(none)"}`,
523
- });
524
- }
525
- const dbSource = resolveDbSource(tx);
526
- if (!dbSource) {
527
- throw new InternalError({
528
- message: `ctx.queryProjection("${qualifiedName}") requires a database connection — none is configured.`,
529
- });
530
- }
531
- // Introspect for a tenant_id column on the projection table. Auto-
532
- // filter keeps cross-tenant leaks out unless the handler explicitly
533
- // opts in. Works with any drizzle-table whose tenant column is named
534
- // tenantId on the JS side.
535
- const tenantCol = (projTable as Record<string, unknown>)["tenantId"];
536
- const where =
537
- tenantCol && !queryOptions?.unsafeAllTenants ? { tenantId: user.tenantId } : undefined;
538
- const rows = await selectMany<Record<string, unknown>>(dbSource, projTable, where);
539
- return rows as readonly T[]; // @cast-boundary engine-payload
540
- },
541
- // Thin pass-through: one resolve impl lives on the dispatcher, the
542
- // handler surface just forwards the call so both entry points (login
543
- // handler via ctx.resolveAuthClaims, switch-tenant route via
544
- // dispatcher.resolveAuthClaims) cannot drift.
545
- resolveAuthClaims: (claimsUser: SessionUser) => resolveAuthClaimsFn(claimsUser), // @wrapper-known semantic-alias
546
-
547
- // Feature-effective check for in-handler opt-in logic. Scope:
548
- // **current user's tenant** — for cross-tenant lookups (rare,
549
- // SysAdmin operations) read effectiveFeatures(otherTenantId) directly.
550
- // When the feature-toggles or tier-engine feature isn't wired (no
551
- // effectiveFeatures callback), always returns true — apps without
552
- // tier-cuts treat all features on.
553
- hasFeature: (featureName: string): boolean =>
554
- effectiveFeatures ? effectiveFeatures(user.tenantId).has(featureName) : true,
555
- };
556
-
557
- // Registry is always the dispatcher's registry — injecting it here lets
558
- // tests/callers pass `context` without `registry` and still get a valid
559
- // HandlerContext. The spread-then-assign order matters: anything in
560
- // `context` can be overridden, but we want the authoritative registry
561
- // from the dispatcher's own closure to win.
562
- // ctx.tz ist immer da. Tenant + User-Defaults kommen aus dem
563
- // SessionUser sobald die Felder existieren — bis dahin "UTC". Ein
564
- // app-injizierter GeoTzProvider (context.geoTzProvider) speist
565
- // ctx.tz.fromCoordinates / fromAddress.
566
- const tz = createTzContext(
567
- context.geoTzProvider !== undefined ? { geoTz: context.geoTzProvider } : {},
568
- );
569
-
570
- return {
571
- ...context,
572
- registry,
573
- db,
574
- log,
575
- notify,
576
- ...(config && { config }),
577
- ...(files && { files }),
578
- tracer,
579
- metrics,
580
- tz,
581
- // Cancellation signal flows from the HTTP middleware via
582
- // requestContext. Conditional spread so non-HTTP entry-points
583
- // (jobs, dispatcher MSP-applies) don't get a phantom signal that
584
- // would always read aborted=false but feel meaningful.
585
- ...(reqCtx?.signal ? { signal: reqCtx.signal } : {}),
586
- // Propagate the feature-toggle resolver so the lifecycle pipeline,
587
- // MSP runner, and ctx.hasFeature all pull from the same source.
588
- ...(effectiveFeatures && { effectiveFeatures }),
589
- // ctx.user als Convenience-Alias auf event.user. Der typisch-
590
- // intuitive Pfad „der Context kennt seinen User" — ohne den
591
- // schreiben Handler `event.user.tenantId` und brechen sich die
592
- // Finger an typo-resistenten ctx.user-Patterns. Identisch zum
593
- // event.user-Wert; Identity-Switches nutzen weiterhin queryAs/writeAs.
594
- user,
595
- _userId: user.id,
596
- _tenantId: user.tenantId,
597
- _handlerType: type,
598
- ...(includeDeleted && { includeDeleted: true }),
599
- ...bridge,
600
- } as HandlerContext; // @cast-boundary engine-bridge
601
- }
602
-
603
86
  const dispatcherTracer = context.tracer ?? getFallbackTracer();
604
87
  const dispatcherMeter = context.meter ?? getFallbackMeter();
605
88
  // Ensure standard metrics exist on whatever meter we ended up with.
606
89
  // Idempotent: buildServer may have registered them already.
607
90
  registerStandardMetrics(dispatcherMeter);
608
91
 
609
- // Wrap handler execution in a dispatcher.handler span AND emit the standard
610
- // dispatcher metrics (duration + error counter). Errors are re-thrown so
611
- // control flow stays identical to the uninstrumented path.
612
- //
613
- // Writes are special-cased: executeWriteInner converts thrown handler errors
614
- // into a WriteResult with isSuccess=false (rather than letting them bubble).
615
- // We inspect the result to paint the dispatcher span + error counter on
616
- // those structural failures too — otherwise "handler threw" would only show
617
- // up when the caller forgot to use writeFailure().
618
- async function runHandlerInstrumented<T>(
619
- type: string,
620
- operation: "query" | "write",
621
- user: SessionUser,
622
- inner: () => Promise<T>,
623
- ): Promise<T> {
624
- const start = performance.now();
625
- // Outcome recorded inside the withSpan callback, emitted in finally so
626
- // success/failure/throw all hit a single metric-emit path.
627
- let success = true;
628
- let errorClass: string | undefined;
629
-
630
- try {
631
- return await dispatcherTracer.withSpan(
632
- "kumiko.dispatcher.handler",
633
- {
634
- attributes: dispatcherSpanAttributes(
635
- type,
636
- operation,
637
- user,
638
- registry.getHandlerFeature(type),
639
- ),
640
- },
641
- async (span) => {
642
- try {
643
- const result = await inner();
644
- if (operation === "write" && isFailedWriteResult(result)) {
645
- success = false;
646
- errorClass = result.error?.code ?? "UnknownError";
647
- span.setStatus("error", errorClass);
648
- }
649
- return result;
650
- } catch (error) {
651
- success = false;
652
- errorClass = error instanceof Error && error.name ? error.name : "UnknownError";
653
- throw error;
654
- }
655
- },
656
- );
657
- } finally {
658
- if (!success && errorClass) {
659
- emitDispatcherError(dispatcherMeter, { handler: type, errorClass });
660
- }
661
- emitDispatcherHandler(
662
- dispatcherMeter,
663
- { handler: type, success },
664
- (performance.now() - start) / 1000,
665
- );
666
- }
667
- }
668
-
669
- // L3 rate limit gate. Called by both query and write paths before
670
- // access-check. Reasoning:
671
- // - handler without rateLimit → no-op
672
- // - app booted without rateLimit resolver → InternalError so the
673
- // misconfig surfaces immediately, not on first 429
674
- // - bucket builder returns "skip" (e.g. ip-based but no client IP):
675
- // pass through. ip-modes are commonly used at L1/L2 middleware
676
- // where the IP comes from Hono directly; falling back to "skip"
677
- // here keeps non-HTTP entry-points (jobs, MSPs) functional.
678
- // Feature-toggle gate. Returns the error to fold into a WriteFailure in the
679
- // write path, or throws for the query path (where throws flow through the
680
- // same outer instrumentation wrapper as other dispatcher errors).
681
- //
682
- // When `effectiveFeatures` is not wired (tests, apps without feature-toggles
683
- // loaded), every handler is treated as enabled — the gate is a pure
684
- // pass-through in that common case.
685
- async function checkFeatureEnabled(
686
- qualifiedHandler: string,
687
- tenantId: TenantId,
688
- ): Promise<import("../errors").FeatureDisabledError | undefined> {
689
- if (!effectiveFeatures) return undefined;
690
- const owner = registry.getHandlerFeature(qualifiedHandler);
691
- // skip: handler without an owning feature cannot be toggled — shouldn't
692
- // happen for registry-built handlers, but guards against edge-case
693
- // runtime injections.
694
- if (!owner) return undefined;
695
- const set = effectiveFeatures(tenantId);
696
- if (set.has(owner)) return undefined;
697
- // Feature is off for the stored tier — give the live trial-gate a last
698
- // chance. Time-derived (tenant.inserted_at + window), so it can't live in
699
- // the boot-cached sync resolver; consulted only on this already-disabled
700
- // cold path, never on the hot enabled path.
701
- if (effectiveFeatures.trialGate && (await effectiveFeatures.trialGate(tenantId, owner))) {
702
- return undefined;
703
- }
704
- return new FeatureDisabledError(owner, qualifiedHandler);
705
- }
706
-
707
- async function ensureFeatureEnabled(qualifiedHandler: string, tenantId: TenantId): Promise<void> {
708
- const err = await checkFeatureEnabled(qualifiedHandler, tenantId);
709
- if (err) throw err;
710
- }
711
-
712
- async function enforceRateLimit(
713
- rateLimit: import("../engine/types").RateLimitOption | undefined,
714
- handlerName: string,
715
- user: SessionUser,
716
- ): Promise<void> {
717
- // skip: defence-in-depth — both call-sites already gate on
718
- // handler.rateLimit !== undefined, so this branch only fires
719
- // if a future caller forgets the inline check.
720
- if (!rateLimit) return;
721
- const reqCtx = requestContext.get();
722
- const bucket = buildBucketKey(rateLimit, {
723
- handlerName,
724
- user,
725
- ip: reqCtx?.ip,
726
- });
727
- // skip: ip-bucket + no IP (non-HTTP entry point) — pass through before
728
- // requiring a resolver; HTTP path always has an IP + L1/L2 middleware.
729
- if (bucket.kind === "skip") return;
730
- if (!context.rateLimit) {
731
- throw new InternalError({
732
- message: `Handler "${handlerName}" declares rateLimit but no RateLimitResolver is configured. Load the rate-limiting feature or remove the option.`,
733
- });
734
- }
735
- await context.rateLimit.enforce(bucket.key, {
736
- limit: rateLimit.limit,
737
- windowSeconds: rateLimit.windowSeconds,
738
- cost: rateLimit.cost,
739
- });
740
- }
741
-
742
- // Standalone query execution — used by the public dispatcher.query() and
743
- // by ctx.query/ctx.queryAs inside handlers. Runs the handler, applies
744
- // field-level read filters for the given user, logs the event.
745
- async function executeQuery(
746
- type: string,
747
- payload: unknown,
748
- user: SessionUser,
749
- tx?: DbTx,
750
- ): Promise<unknown> {
751
- return runHandlerInstrumented(type, "query", user, () =>
752
- executeQueryInner(type, payload, user, tx),
753
- );
754
- }
755
-
756
- async function executeQueryInner(
757
- type: string,
758
- payload: unknown,
759
- user: SessionUser,
760
- tx?: DbTx,
761
- ): Promise<unknown> {
762
- const handler = registry.getQueryHandler(type);
763
- if (!handler) throw new NotFoundError("handler", type);
764
-
765
- // Feature-toggle gate runs BEFORE rate-limit on purpose: calls to a
766
- // disabled feature must not consume the rate-limit quota — the call
767
- // never happened from the feature's perspective. Order is: lookup →
768
- // feature-gate → rate-limit → access → validation → handler.
769
- await ensureFeatureEnabled(type, user.tenantId);
770
-
771
- // Rate-limit gate runs BEFORE access-check on purpose: anonymous /
772
- // unauthorized callers must hit the cap too (otherwise the limit
773
- // would be a free probe-detector for valid credentials). The
774
- // resolver throws RateLimitError which the dispatcher's outer
775
- // wrapper turns into a 429 response. Inline-skip when the handler
776
- // didn't opt in — keeps the hot path zero-cost (no await on a
777
- // no-op promise).
778
- if (handler.rateLimit !== undefined) {
779
- await enforceRateLimit(handler.rateLimit, type, user);
780
- }
781
-
782
- // Default-deny: missing access rule is treated as "no one has access".
783
- // The registry boot-validator refuses to register handlers without one,
784
- // so in normal boots this branch shouldn't fire — the guard is belt-and-
785
- // suspenders in case a handler sneaks through (e.g. runtime injection).
786
- if (!hasAccess(user, handler.access)) {
787
- throw new AccessDeniedError({
788
- message: `access denied for ${type}`,
789
- details: { handler: type },
790
- });
791
- }
792
-
793
- const parsed = handler.schema.safeParse(payload);
794
- if (!parsed.success) {
795
- throw validationErrorFromZod(parsed.error);
796
- }
797
-
798
- // Trash opt-in rides the validated query payload: only the entity-list
799
- // schema (and custom query schemas that opt in) carries `includeDeleted`,
800
- // so other handlers never see the flag. Visibility filters still apply
801
- // downstream (see HandlerContext.includeDeleted) — safe from raw input.
802
- const includeDeleted =
803
- typeof parsed.data === "object" &&
804
- parsed.data !== null &&
805
- (parsed.data as Record<string, unknown>)["includeDeleted"] === true; // @cast-boundary validated-payload
806
- const handlerContext = buildHandlerContext(type, user, tx, undefined, includeDeleted);
807
- let result = await handler.handler({ type, payload: parsed.data, user }, handlerContext);
808
-
809
- // postQuery-Hooks: fire BEFORE field-access-filter so hooks see raw data
810
- // and can merge custom-fields/computed-counts/tags/etc. Each hook is
811
- // responsible for its own field-access on values it adds (the filter
812
- // below only knows the entity's stammfields).
813
- //
814
- // Two firing-pfade kombiniert in dieser Reihenfolge:
815
- // 1. Handler-keyed hooks via r.hook("postQuery", "ns:query:list", fn)
816
- // — feuern nur für genau diesen handler
817
- // 2. Entity-keyed hooks via r.entityHook("postQuery", "property", fn)
818
- // — feuern für ALLE query-handlers des entity
819
- const entityName = registry.getHandlerEntity(type);
820
-
821
- // Handler-keyed postQuery hooks fire for any query (incl. entity-less
822
- // standalone queries like "ns:dashboard"). Entity-keyed hooks only apply
823
- // when the handler maps to an entity — so this block must NOT be gated on
824
- // entityName, or hooks on standalone queries register silently and never fire.
825
- const handlerHooks = registry.getPostQueryHooks(type);
826
- const entityHooks = entityName ? registry.getEntityPostQueryHooks(entityName) : [];
827
- const postQueryHooks = [...handlerHooks, ...entityHooks];
828
- if (postQueryHooks.length > 0 && result && typeof result === "object") {
829
- if (Array.isArray(result)) {
830
- let rows = result as Record<string, unknown>[]; // @cast-boundary engine-payload
831
- for (const hook of postQueryHooks) {
832
- const out = await hook({ entityName, rows }, handlerContext);
833
- rows = [...out.rows];
834
- }
835
- result = rows;
836
- } else if (Array.isArray((result as { rows?: unknown }).rows)) {
837
- // @cast-boundary engine-payload
838
- const r = result as { rows: Record<string, unknown>[]; nextCursor: string | null };
839
- let rows = r.rows;
840
- for (const hook of postQueryHooks) {
841
- const out = await hook({ entityName, rows }, handlerContext);
842
- rows = [...out.rows];
843
- }
844
- result = { ...r, rows };
845
- } else {
846
- let rows: Record<string, unknown>[] = [result as Record<string, unknown>]; // @cast-boundary engine-payload
847
- for (const hook of postQueryHooks) {
848
- const out = await hook({ entityName, rows }, handlerContext);
849
- rows = [...out.rows];
850
- }
851
- // A single-object result carries exactly one row through the hook
852
- // pipeline. Returning 0 rows (effect lost) or ≥2 rows (extras
853
- // dropped) cannot be represented in the single-object response —
854
- // surface it instead of silently falling back / truncating.
855
- if (rows.length !== 1) {
856
- throw new Error(
857
- `postQuery hook on single-object result for "${type}" must return exactly one row, got ${rows.length}`,
858
- );
859
- }
860
- result = rows[0];
861
- }
862
- }
863
-
864
- // Field-level read filter — only applies to entity-bound results.
865
- const entity = entityName ? registry.getEntity(entityName) : undefined;
866
- if (entity && result && typeof result === "object") {
867
- if (Array.isArray(result)) {
868
- result = result.map((row: Record<string, unknown>) => filterReadFields(entity, row, user));
869
- } else {
870
- const resultAsDbRow = result as DbRow; // @cast-boundary engine-payload
871
- if (Array.isArray((resultAsDbRow as { rows?: unknown }).rows)) {
872
- // generic handler-result shape narrow
873
- const r = result as { rows: Record<string, unknown>[]; nextCursor: string | null }; // @cast-boundary engine-payload
874
- result = {
875
- ...r,
876
- rows: r.rows.map((row) => filterReadFields(entity, row, user)),
877
- };
878
- } else {
879
- result = filterReadFields(entity, result as DbRow, user); // @cast-boundary engine-payload
880
- }
881
- }
882
- }
883
-
884
- // Response-guard: fail the request if a handler accidentally included
885
- // a Secret<> branded value in its return. Must run AFTER field-access
886
- // filtering so a legitimately stripped secret doesn't false-positive.
887
- assertNoSecretLeak(result);
888
- return result;
889
- }
890
-
891
- // Runs lifecycle hooks for a handler result. inTransaction hooks fire NOW
892
- // (they see the tx via ctx.db when batch/write opens a transaction).
893
- // afterCommit hooks are queued into `afterCommitHooks` for the caller to
894
- // flush after commit.
895
- async function runLifecycle(
896
- type: string,
897
- data: unknown,
898
- handlerContext: HandlerContext,
899
- afterCommitHooks: AfterCommitHook[],
900
- ): Promise<void> {
901
- if (!lifecycle) {
902
- handlerContext.log?.debug(`runLifecycle: skipping ${type} — no lifecycle pipeline`);
903
- return;
904
- }
905
- if (!isLifecycleResult(data)) {
906
- handlerContext.log?.debug(`runLifecycle: skipping ${type} — result is not a lifecycle kind`);
907
- return;
908
- }
909
- const result = data;
910
-
911
- // Projections run FIRST, inside the tx, before any user postSave/postDelete
912
- // hooks. If a projection apply() throws, the whole tx rolls back — the
913
- // event and the auto-projection row go with it. Running before the hooks
914
- // keeps projection state consistent with what the hooks observe.
915
- await runProjections(result, handlerContext);
916
-
917
- if (result.kind === "save") {
918
- await lifecycle.runPostSave(type, result, handlerContext, HookPhases.inTransaction);
919
- afterCommitHooks.push(() =>
920
- lifecycle.runPostSave(type, result, handlerContext, HookPhases.afterCommit),
921
- );
922
- } else if (result.kind === "delete") {
923
- await lifecycle.runPreDelete(type, result, handlerContext);
924
- await lifecycle.runPostDelete(type, result, handlerContext, HookPhases.inTransaction);
925
- afterCommitHooks.push(() =>
926
- lifecycle.runPostDelete(type, result, handlerContext, HookPhases.afterCommit),
927
- );
928
- }
929
- }
930
-
931
- // Shared write pipeline: validates, executes handler, runs lifecycle + side effects.
932
- // Used by runBatch (which opens a transaction and flushes afterCommitHooks on commit).
933
- //
934
- // Contract:
935
- // - `tx` is the active Drizzle transaction handle (or undefined for the no-DB
936
- // fallback path used by tests without a Postgres connection).
937
- // - `afterCommitHooks` collects deferred side-effects that must only fire
938
- // after the transaction commits. The caller flushes them on commit, drops
939
- // them on rollback. executeWrite never fires them directly.
940
- async function executeWrite(
941
- type: string,
942
- payload: unknown,
943
- user: SessionUser,
944
- tx: DbTx | undefined,
945
- afterCommitHooks: AfterCommitHook[],
946
- ): Promise<WriteResult> {
947
- return runHandlerInstrumented(type, "write", user, () =>
948
- executeWriteInner(type, payload, user, tx, afterCommitHooks),
949
- );
950
- }
951
-
952
- // Nested-write orchestration (v1: depth=1, create-only, hasMany-only).
953
- //
954
- // When a parent `:create` handler's payload carries values under keys
955
- // declared as `hasMany` relations with `nestedWrite: true`, those values
956
- // are expanded into child writes: parent first (so its new id exists),
957
- // then each nested entry as a separate `<target>:create` write with the
958
- // foreign key set by the framework — never taken from the client. All of
959
- // this runs inside the caller's transaction, so a child failure rolls the
960
- // parent (and any earlier children) back together.
961
- //
962
- // This wrapper is what runBatch calls, not executeWrite. Single writes
963
- // (`dispatcher.write`) flow through runBatch as batch-of-one, so they get
964
- // nested-expansion too for free. A batch with N heterogeneous commands
965
- // can each independently carry nested-children — all still one TX.
966
- async function executeNestedWrite(
967
- type: string,
968
- payload: unknown,
969
- user: SessionUser,
970
- tx: DbTx | undefined,
971
- afterCommitHooks: AfterCommitHook[],
972
- ): Promise<WriteResult> {
973
- const nested = extractNestedSpecs(type, payload, registry);
974
- if (!nested) return executeWrite(type, payload, user, tx, afterCommitHooks);
975
-
976
- // Pre-flight client-shape checks. Merge non-array issues (collected up
977
- // front by extractNestedSpecs) with fk-injection issues into one error
978
- // so the client sees every problem in a single round-trip.
979
- //
980
- // Security rail: the client MUST NOT supply the foreign key on nested
981
- // items. The framework binds it from the parent's new id. Silent-overwrite
982
- // would mask an attempt to attach children to a different parent — fail
983
- // loud with a ValidationError carrying a client-mappable path.
984
- const issues: Array<{ path: string; code: string; i18nKey: string }> = [...nested.typeIssues];
985
- for (const spec of nested.specs) {
986
- for (let i = 0; i < spec.items.length; i++) {
987
- const item = spec.items[i];
988
- if (item && typeof item === "object" && spec.foreignKey in item) {
989
- issues.push({
990
- path: `${spec.key}.${i}.${spec.foreignKey}`,
991
- code: "unexpected_field",
992
- i18nKey: "errors.validation.unexpected_field",
993
- });
994
- }
995
- }
996
- }
997
- if (issues.length > 0) {
998
- return writeFailure(new ValidationError({ fields: issues }));
999
- }
1000
-
1001
- const parentResult = await executeWrite(type, nested.cleanPayload, user, tx, afterCommitHooks);
1002
- if (!parentResult.isSuccess) return parentResult;
1003
-
1004
- // Handlers built on the CRUD executor return a SaveContext wrapper —
1005
- // `{ kind: "save", id, data: <row>, changes, previous, event, ... }`.
1006
- // The wrapper is load-bearing for batch-level hooks downstream (see
1007
- // flushBatchHooks), so we mutate in place: nested children land on the
1008
- // inner `data` (which mirrors the entity shape the client expects) while
1009
- // the wrapper keeps its SaveContext semantics intact for the lifecycle
1010
- // pipeline. For handlers that return a bare row (no wrapper), children
1011
- // land directly on that object.
1012
- //
1013
- // Hook-ordering note: per-entity postSave hooks already ran inside the
1014
- // parent's executeWrite call above — they never saw `tasks`, which is
1015
- // the right semantic (postSave gets the entity's own columns, not
1016
- // synthetic relation keys). A future postSaveBatch subscriber that
1017
- // enumerates columns generically WOULD see `tasks`; no such subscriber
1018
- // exists today. If you add one that iterates `Object.keys(save.data)`,
1019
- // filter by `entity.fields` membership to stay correct.
1020
- // handler-Result.data ist generic über alle Entity-Handler; nested-
1021
- // write inspiziert die shape strukturell.
1022
- const parentWrapper = parentResult.data as Record<string, unknown>; // @cast-boundary engine-payload
1023
- const parentRow = (parentWrapper["data"] ?? parentWrapper) as Record<string, unknown>; // @cast-boundary engine-payload
1024
- const parentId = parentRow["id"];
1025
- if (typeof parentId !== "string") {
1026
- return writeFailure(
1027
- new InternalError({
1028
- message: `nested-write: parent handler "${type}" returned no string "id" — cannot attach children`,
1029
- }),
1030
- );
1031
- }
1032
-
1033
- for (const spec of nested.specs) {
1034
- const subRows: Record<string, unknown>[] = [];
1035
- for (let i = 0; i < spec.items.length; i++) {
1036
- const rawItem = spec.items[i];
1037
- const itemObj = (rawItem ?? {}) as Record<string, unknown>; // @cast-boundary engine-payload
1038
- const subPayload = { ...itemObj, [spec.foreignKey]: parentId };
1039
- const subResult = await executeWrite(spec.subType, subPayload, user, tx, afterCommitHooks);
1040
- if (!subResult.isSuccess) {
1041
- return {
1042
- isSuccess: false,
1043
- error: prefixValidationPath(subResult.error, `${spec.key}.${i}`),
1044
- };
1045
- }
1046
- const subWrapper = subResult.data as Record<string, unknown>; // @cast-boundary engine-payload
1047
- const subRow = (subWrapper["data"] ?? subWrapper) as Record<string, unknown>; // @cast-boundary engine-payload
1048
- subRows.push(subRow);
1049
- }
1050
- parentRow[spec.key] = subRows;
1051
- }
1052
-
1053
- return parentResult;
1054
- }
1055
-
1056
- async function executeWriteInner(
1057
- type: string,
1058
- payload: unknown,
1059
- user: SessionUser,
1060
- tx: DbTx | undefined,
1061
- afterCommitHooks: AfterCommitHook[],
1062
- ): Promise<WriteResult> {
1063
- const handler = registry.getWriteHandler(type);
1064
- if (!handler) return writeFailure(new NotFoundError("handler", type));
1065
-
1066
- // Feature-toggle gate: disabled handlers must short-circuit before any
1067
- // rate-limit/access/validation work — see executeQueryInner comment.
1068
- const disabledErr = await checkFeatureEnabled(type, user.tenantId);
1069
- if (disabledErr) return writeFailure(disabledErr);
1070
-
1071
- // Rate-limit gate before access (same reasoning as in executeQueryInner).
1072
- // Throws RateLimitError; the outer wrapper turns it into a 429
1073
- // WriteFailure via toWriteErrorInfo. Inline-skip when no opt-in —
1074
- // hot path stays zero-cost.
1075
- if (handler.rateLimit !== undefined) {
1076
- try {
1077
- await enforceRateLimit(handler.rateLimit, type, user);
1078
- } catch (e) {
1079
- if (isKumikoError(e)) return writeFailure(e);
1080
- throw e;
1081
- }
1082
- }
1083
-
1084
- // Default-deny: missing access rule is treated as "no one has access".
1085
- // The registry boot-validator refuses to register handlers without one,
1086
- // so in normal boots this branch shouldn't fire — the guard is belt-and-
1087
- // suspenders in case a handler sneaks through (e.g. runtime injection).
1088
- if (!hasAccess(user, handler.access)) {
1089
- return writeFailure(
1090
- new AccessDeniedError({
1091
- message: `access denied for ${type}`,
1092
- details: { handler: type },
1093
- }),
1094
- );
1095
- }
1096
-
1097
- const parsed = handler.schema.safeParse(payload);
1098
- if (!parsed.success) {
1099
- return writeFailure(validationErrorFromZod(parsed.error));
1100
- }
1101
-
1102
- const hookErrors = runValidation(registry, type, parsed.data as DbRow); // @cast-boundary engine-payload
1103
- if (hookErrors) {
1104
- return writeFailure(
1105
- new ValidationError({
1106
- fields: hookErrors.map((e) => ({
1107
- path: e.field,
1108
- code: e.error,
1109
- i18nKey: `errors.validation.${e.error}`,
1110
- })),
1111
- }),
1112
- );
1113
- }
1114
-
1115
- // Field-level write access check
1116
- const entityName = registry.getHandlerEntity(type);
1117
- if (entityName) {
1118
- const entity = registry.getEntity(entityName);
1119
- if (entity) {
1120
- const fieldsToCheck = (parsed.data as DbRow)["changes"] as
1121
- | Record<string, unknown>
1122
- | undefined; // @cast-boundary engine-payload
1123
- const writePayload = fieldsToCheck ?? (parsed.data as DbRow); // @cast-boundary engine-payload
1124
- // Pre-handler check: role-only gate. Ownership-level row-match runs
1125
- // later in the executor where oldRow is loaded — that split lets
1126
- // updates with partial changes still pass the pre-handler check and
1127
- // get their full evaluation at save time.
1128
- const deniedField = checkWriteFieldRoles(entity, writePayload, user);
1129
- if (deniedField) {
1130
- return writeFailure(
1131
- new AccessDeniedError({
1132
- message: `field access denied: ${deniedField}`,
1133
- i18nKey: "errors.access.fieldDenied",
1134
- details: {
1135
- reason: FrameworkReasons.fieldAccessDenied,
1136
- field: deniedField,
1137
- handler: type,
1138
- },
1139
- }),
1140
- );
1141
- }
1142
- }
1143
- }
1144
-
1145
- const handlerContext = buildHandlerContext(type, user, tx, afterCommitHooks);
1146
-
1147
- // Auto transition guard: if entity has transitions and handler doesn't skip it
1148
- if (entityName && !handler.unsafeSkipTransitionGuard) {
1149
- const entity = registry.getEntity(entityName);
1150
- if (entity?.transitions && handlerContext.db) {
1151
- const parsedData = parsed.data as DbRow; // @cast-boundary engine-payload
1152
- const changes = (parsedData["changes"] as DbRow) ?? parsedData; // @cast-boundary engine-payload
1153
- const id = (parsedData["id"] as number) ?? undefined; // @cast-boundary engine-payload
1154
-
1155
- for (const [fieldName, transitionMap] of Object.entries(entity.transitions)) {
1156
- const newValue = changes[fieldName] as string | undefined; // @cast-boundary engine-bridge
1157
- if (!newValue || !id) continue;
1158
-
1159
- const table = getTable(entityName);
1160
- if (!table) continue;
1161
-
1162
- // SELECT FOR UPDATE inside the surrounding transaction — locks the
1163
- // row so a concurrent handler can't mutate `status` between our
1164
- // guard check and the handler's UPDATE. Without this lock the guard
1165
- // can false-pass; optimistic locking would catch it later, but with
1166
- // a less specific error. Falls back to a plain SELECT if no tx is
1167
- // active (tests without a DB connection).
1168
- const tableName = asEntityTableMeta(table)?.tableName ?? "";
1169
- const rows = tx
1170
- ? await selectRowForUpdateById(handlerContext.db, tableName, id)
1171
- : await selectMany(handlerContext.db, table, { id });
1172
- const row = rows[0];
1173
-
1174
- if (!row) continue;
1175
- // Skip guard for soft-deleted rows — they shouldn't be transitioning
1176
- // at all; a handler that wants to move a deleted row should use
1177
- // unsafeSkipTransitionGuard or restore first.
1178
- const rowAsRow = row as DbRow; // @cast-boundary engine-payload
1179
- const isDeleted = rowAsRow["isDeleted"] ?? rowAsRow["is_deleted"];
1180
- if (entity.softDelete && isDeleted === true) {
1181
- continue;
1182
- }
1183
- const currentValue =
1184
- ((row as DbRow)[fieldName] as string | undefined) ??
1185
- ((row as DbRow)[toSnakeCase(fieldName)] as string); // @cast-boundary engine-bridge
1186
- guardTransition(
1187
- getTransitions({ entityName, fieldName, map: transitionMap }),
1188
- currentValue,
1189
- newValue,
1190
- );
1191
- }
1192
- }
1193
- }
1194
-
1195
- // The handler itself plus the lifecycle pipeline run under the same
1196
- // try-wrapper: any KumikoError bubbles up as a typed WriteErrorInfo, any
1197
- // other throw gets wrapped in InternalError so the Prod contract holds
1198
- // ("unexpected throw → 500 with sanitized body"). We intentionally do NOT
1199
- // catch further out (runBatch still sees these as exceptions via
1200
- // writeFailure, not via a rethrow) so batches roll back naturally.
1201
- let result: WriteResult;
1202
- try {
1203
- result = await handler.handler({ type, payload: parsed.data, user }, handlerContext);
1204
- } catch (e) {
1205
- return writeFailure(wrapToKumiko(e));
1206
- }
1207
-
1208
- // Runtime shape-guard. The compile-time type WriteHandlerFn already
1209
- // requires `Promise<WriteResult>`, but custom handlers wired through
1210
- // r.writeHandler(name, schema, fn, opts) sometimes slip through with
1211
- // `Promise<{id: string}>` — TypeScript misses it under structural-
1212
- // widening, the dispatcher then reads .isSuccess on undefined and
1213
- // crashes obscure. Surface a clear actionable message instead.
1214
- if (!isWriteResultShape(result)) {
1215
- return writeFailure(
1216
- new InternalError({
1217
- message:
1218
- `Write handler "${type}" returned an invalid shape. Expected WriteResult ` +
1219
- `({ isSuccess: true, data: ... } or writeFailure(err)), got ${describeShape(result)}. ` +
1220
- `Use defineWriteHandler() or wrap the return as { isSuccess: true as const, data: ... }.`,
1221
- }),
1222
- );
1223
- }
1224
-
1225
- if (result.isSuccess) {
1226
- try {
1227
- await runLifecycle(type, result.data, handlerContext, afterCommitHooks);
1228
- } catch (e) {
1229
- return writeFailure(wrapToKumiko(e));
1230
- }
1231
-
1232
- // jobRunner has external side-effects (BullMQ enqueue) — must NOT
1233
- // fire for rolled-back writes. Defer to afterCommit.
1234
- if (jobRunner) {
1235
- const eventData = (parsed.data ?? {}) as DbRow; // @cast-boundary engine-payload
1236
- afterCommitHooks.push(() => jobRunner.handleEvent(type, eventData, user));
1237
- }
1238
- }
1239
-
1240
- // Response-guard: block Secret<> leaks in write responses (SaveContext
1241
- // data / previous / changes). Feature code that fed a plaintext through
1242
- // to the return payload fails here instead of hitting the client.
1243
- if (result.isSuccess) assertNoSecretLeak(result.data);
1244
- return result;
1245
- }
1246
-
1247
- // Core batch logic extracted so write() and command() can reuse it
1248
- // (a single write = batch of one, running in its own transaction).
1249
- async function runBatch(
1250
- commands: readonly BatchCommand[],
1251
- user: SessionUser,
1252
- requestId?: string,
1253
- ): Promise<BatchResult> {
1254
- if (commands.length === 0) {
1255
- return { isSuccess: true, results: [] };
1256
- }
1257
-
1258
- // Idempotency: if the same requestId has already been processed, return the
1259
- // cached result without re-executing. The cache holds the full BatchResult.
1260
- if (requestId && idempotency) {
1261
- const cached = await idempotency.check(requestId);
1262
- if (cached) {
1263
- const parsed = parseJsonSafe<BatchResult | null>(cached, null);
1264
- if (parsed) return parsed;
1265
- // corrupted cache entry — treat as miss, let the request re-run
1266
- }
1267
- }
1268
-
1269
- // Wrap return paths: cache the final result under requestId so retries get
1270
- // the same answer (both success and failure results are cached).
1271
- const finalize = async (result: BatchResult): Promise<BatchResult> => {
1272
- if (requestId && idempotency) {
1273
- await idempotency.store(requestId, result);
1274
- }
1275
- return result;
1276
- };
1277
-
1278
- const afterCommitHooks: AfterCommitHook[] = [];
1279
- const results: WriteResult[] = [];
1280
-
1281
- // Flush afterCommit hooks in parallel. Errors are logged, not rethrown:
1282
- // the writes are already committed, we can't undo them.
1283
- //
1284
- // Parallelisation is safe because afterCommit hooks are deferred side-
1285
- // effects (e.g. feature-level postSave hooks in afterCommit phase)
1286
- // that don't depend on each other — the in-transaction work already ran
1287
- // sequentially inside the lifecycle pipeline where ordering matters. If a
1288
- // future hook ever needs ordering, it should do its sequencing internally
1289
- // (one hook pushing multiple sub-calls) rather than relying on the
1290
- // flush-loop order.
1291
- const flushAfterCommit = async () => {
1292
- const logError = createFallbackLogger("dispatcher", context.log);
1293
- const outcomes = await Promise.allSettled(afterCommitHooks.map((hook) => hook()));
1294
- for (const outcome of outcomes) {
1295
- if (outcome.status === "rejected") {
1296
- const detail =
1297
- outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
1298
- logError.error("afterCommit hook failed", { error: detail });
1299
- }
1300
- }
1301
- };
1302
-
1303
- // Fires the batch-level system hooks with every successful save/delete
1304
- // context from this run. Called after flushAfterCommit so per-save hooks
1305
- // have all completed first; errors are isolated inside lifecycleHooks.
1306
- const flushBatchHooks = async () => {
1307
- try {
1308
- const saves: SaveContext[] = [];
1309
- const deletes: DeleteContext[] = [];
1310
- for (const r of results) {
1311
- if (!r.isSuccess) continue;
1312
- if (!isLifecycleResult(r.data)) continue;
1313
- if (r.data.kind === "save") saves.push(r.data);
1314
- else if (r.data.kind === "delete") deletes.push(r.data);
1315
- }
1316
- if (saves.length > 0 && lifecycle) await lifecycle.runPostSaveBatch(saves, context);
1317
- if (deletes.length > 0 && lifecycle) await lifecycle.runPostDeleteBatch(deletes, context);
1318
- } catch (e) {
1319
- // Batch hooks must never fail the batch — the commit already happened.
1320
- // Pass the raw error so the logger preserves stack + cause chain;
1321
- // collapsing to .message hides exactly what ops needs to debug.
1322
- const logError = createFallbackLogger("dispatcher", context.log);
1323
- logError.error("batch hook flush failed", { error: e });
1324
- }
1325
- };
1326
-
1327
- // batch() opens its own outer transaction — needs the top-level
1328
- // connection's `.begin()` (TransactionSql exposes only `.savepoint()`).
1329
- const db = resolveDbSource(undefined) as DbConnection | undefined;
1330
- if (!db) {
1331
- // Without a DB connection there is no transaction to open. Fall back to
1332
- // sequential execution — useful for unit tests that don't touch the DB.
1333
- // Each command runs independently; a failure stops the batch.
1334
- for (let i = 0; i < commands.length; i++) {
1335
- const cmd = commands[i];
1336
- if (!cmd) continue;
1337
- const res = await executeNestedWrite(
1338
- cmd.type,
1339
- cmd.payload,
1340
- user,
1341
- undefined,
1342
- afterCommitHooks,
1343
- );
1344
- results.push(res);
1345
- if (!res.isSuccess) {
1346
- // No tx means no rollback — but we still drop afterCommit hooks,
1347
- // matching the semantic "failure = side-effects don't fire".
1348
- return finalize({ isSuccess: false, error: res.error, failedIndex: i, results });
1349
- }
1350
- }
1351
- await flushAfterCommit();
1352
- await flushBatchHooks();
1353
- return finalize({ isSuccess: true, results });
1354
- }
1355
-
1356
- try {
1357
- await transaction(db, async (tx) => {
1358
- for (let i = 0; i < commands.length; i++) {
1359
- const cmd = commands[i];
1360
- if (!cmd) continue;
1361
- const res = await executeNestedWrite(cmd.type, cmd.payload, user, tx, afterCommitHooks);
1362
- results.push(res);
1363
- if (!res.isSuccess) {
1364
- throw new BatchRollback(i, res.error);
1365
- }
1366
- }
1367
- });
1368
- } catch (e) {
1369
- if (e instanceof BatchRollback) {
1370
- return finalize({
1371
- isSuccess: false,
1372
- error: e.failureError,
1373
- failedIndex: e.failedIndex,
1374
- results,
1375
- });
1376
- }
1377
- return finalize({
1378
- isSuccess: false,
1379
- error: toWriteErrorInfo(wrapToKumiko(e)),
1380
- failedIndex: results.length,
1381
- results,
1382
- });
1383
- }
1384
-
1385
- // Commit succeeded — fire deferred side-effects.
1386
- await flushAfterCommit();
1387
- await flushBatchHooks();
1388
- return finalize({ isSuccess: true, results });
1389
- }
1390
-
1391
- // Unwrap a BatchResult into a single WriteResult for write()/command().
1392
- // Picks the last result if present (the failing one for failures, the only
1393
- // one for successful single writes). Falls back to a synthetic error if the
1394
- // batch didn't produce any results (unexpected).
1395
- function unwrapSingle(batchResult: BatchResult): WriteResult {
1396
- if (batchResult.isSuccess) {
1397
- return (
1398
- batchResult.results[0] ?? writeFailure(new InternalError({ message: "empty_batch_result" }))
1399
- );
1400
- }
1401
- return (
1402
- batchResult.results[batchResult.failedIndex] ?? {
1403
- isSuccess: false,
1404
- error: batchResult.error,
1405
- }
1406
- );
1407
- }
1408
-
1409
- // Build the per-hook context every auth-claims invocation gets. Claims
1410
- // hooks run OUTSIDE any request transaction (login is itself the root
1411
- // operation, not a nested call) and read-only — so the TenantDb is
1412
- // scoped as "tenant" and no tx is threaded through. Hooks that need
1413
- // cross-tenant lookups opt in explicitly via queryAs(systemUser, ...).
1414
- function buildAuthClaimsContext(user: SessionUser): AuthClaimsContext {
1415
- const dbSource = resolveDbSource(undefined);
1416
- if (!dbSource) {
1417
- throw new InternalError({
1418
- message:
1419
- "dispatcher.resolveAuthClaims requires a database connection — none is configured.",
1420
- });
1421
- }
1422
- const db = createTenantDb(dbSource, user.tenantId, "tenant", context.tracer, context.meter);
1423
- const configAccessor = context._configAccessorFactory
1424
- ? context._configAccessorFactory({
1425
- user: { id: user.id, tenantId: user.tenantId },
1426
- db,
1427
- secrets: context.secrets,
1428
- })
1429
- : undefined;
1430
- return {
1431
- db,
1432
- queryAs: (asUser: SessionUser, qn: string, payload: unknown) =>
1433
- executeQuery(qn, payload, asUser), // @wrapper-known semantic-alias
1434
- ...(configAccessor && { config: configAccessor }),
1435
- };
1436
- }
1437
-
1438
- async function resolveAuthClaimsFn(user: SessionUser): Promise<Record<string, unknown>> {
1439
- const hooks = registry.getAuthClaimsHooks();
1440
- if (hooks.length === 0) return {};
1441
- return runAuthClaimsResolver({
1442
- user,
1443
- hooks,
1444
- contextFactory: buildAuthClaimsContext,
1445
- ...(context.log && { log: context.log }),
1446
- });
1447
- }
92
+ const ctx: DispatchContext = {
93
+ registry,
94
+ appContext: context,
95
+ idempotency,
96
+ lifecycle,
97
+ jobRunner,
98
+ effectiveFeatures,
99
+ tableCache,
100
+ transitionCache,
101
+ tracer: dispatcherTracer,
102
+ meter: dispatcherMeter,
103
+ };
1448
104
 
1449
105
  return {
1450
106
  async write(typeOrRef, payload, user, requestId?) {
1451
107
  const type = resolveType(typeOrRef);
1452
108
  // Idempotency handled inside runBatch (caches BatchResult under requestId).
1453
- const batchResult = await runBatch([{ type, payload }], user, requestId);
109
+ const batchResult = await runBatch(ctx, [{ type, payload }], user, requestId);
1454
110
  return unwrapSingle(batchResult);
1455
111
  },
1456
112
 
1457
- batch: runBatch,
113
+ batch: (commands, user, requestId?) => runBatch(ctx, commands, user, requestId),
1458
114
 
1459
- query: (typeOrRef, payload, user) => executeQuery(resolveType(typeOrRef), payload, user),
115
+ query: (typeOrRef, payload, user) => executeQuery(ctx, resolveType(typeOrRef), payload, user),
1460
116
 
1461
117
  async command(typeOrRef, payload, user) {
1462
118
  const type = resolveType(typeOrRef);
1463
- const batchResult = await runBatch([{ type, payload }], user);
119
+ const batchResult = await runBatch(ctx, [{ type, payload }], user);
1464
120
  const result = unwrapSingle(batchResult);
1465
121
 
1466
122
  if (!result.isSuccess) {
@@ -1468,6 +124,6 @@ export function createDispatcher(
1468
124
  }
1469
125
  },
1470
126
 
1471
- resolveAuthClaims: resolveAuthClaimsFn,
127
+ resolveAuthClaims: (user) => resolveAuthClaimsFn(ctx, user),
1472
128
  };
1473
129
  }