@cosmicdrift/kumiko-testing 0.413.1 → 0.414.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,694 +0,0 @@
1
- // @runtime dev
2
- import { createHash } from "node:crypto";
3
- import {
4
- buildServer,
5
- createSseBroker,
6
- withFileProviderResolver,
7
- } from "@cosmicdrift/kumiko-framework/api";
8
- import {
9
- assertRowLevelSecurityBootState,
10
- type DbConnection,
11
- type EntityTableMeta,
12
- knownTablesOf,
13
- type RowLevelSecurityMode,
14
- } from "@cosmicdrift/kumiko-framework/db";
15
- import { createRegistry, validateBoot } from "@cosmicdrift/kumiko-framework/engine";
16
- import type { FeatureDefinition } from "@cosmicdrift/kumiko-framework/engine/types";
17
- import {
18
- createArchivedStreamsTable,
19
- createEventsTable,
20
- } from "@cosmicdrift/kumiko-framework/event-store";
21
- import {
22
- appHookScopedRunner,
23
- DEFAULT_ROW_LEVEL_SECURITY_MODE,
24
- systemScopedRunner,
25
- } from "@cosmicdrift/kumiko-framework/internal/row-level-security";
26
- import {
27
- createRateLimitResolver,
28
- unsafePushTables,
29
- validateNavBootSubset,
30
- validateOwnershipBoot,
31
- } from "@cosmicdrift/kumiko-framework/internal/stack-support";
32
- import { createJobRunner, type JobRunner } from "@cosmicdrift/kumiko-framework/jobs";
33
- import { createNoopProvider } from "@cosmicdrift/kumiko-framework/observability";
34
- import type { EventDispatcher } from "@cosmicdrift/kumiko-framework/pipeline";
35
- import {
36
- createEntityCache,
37
- createEventDedup,
38
- createIdempotencyGuard,
39
- dispatcherToWriteRef,
40
- } from "@cosmicdrift/kumiko-framework/pipeline";
41
- import {
42
- type ClosableCacheSyncBus,
43
- createLocalCacheSyncBus,
44
- createRedisCacheSyncBus,
45
- } from "@cosmicdrift/kumiko-framework/redis";
46
- import type { SearchAdapter } from "@cosmicdrift/kumiko-framework/search";
47
- import { createInMemorySearchAdapter } from "@cosmicdrift/kumiko-framework/search";
48
- import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
49
- import type { Clock } from "@cosmicdrift/kumiko-types/tz-context";
50
- import {
51
- createTestDb,
52
- ensureTestDbTemplate,
53
- TEST_APPLICATION_ROLE,
54
- TEST_DB_TEMPLATE_RUN_ENV,
55
- testDbTemplatePrefix,
56
- } from "./db.ts";
57
- import { type createJobFailureTracker, drainJobs } from "./drain-jobs.ts";
58
- import { createEventCollector } from "./event-collector.ts";
59
- import { createTestRedis, queueNamePrefixForTestRedis, type TestRedis } from "./redis.ts";
60
- import { createRequestHelper } from "./request-helper.ts";
61
- import type { TestStack, TestStackOptions } from "./test-stack.ts";
62
-
63
- type MfaTokenSecretBinder = (
64
- masterSecret: string,
65
- env: Readonly<Record<string, string | undefined>>,
66
- ) => void;
67
-
68
- // Mirrors bindMfaTokenSecretsFromFeature from bundled-features/auth-mfa,
69
- // which this package cannot import: bundled-features is an optional peer.
70
- function isMfaTokenSecretBinder(value: unknown): value is MfaTokenSecretBinder {
71
- return typeof value === "function";
72
- }
73
-
74
- // The env is empty on purpose: test secrets derive from jwtSecret,
75
- // independent of the host env.
76
- function bindMfaTokenSecrets(features: readonly FeatureDefinition[], jwtSecret: string): void {
77
- for (const { exports } of features) {
78
- if (typeof exports !== "object" || exports === null || !("bindTokenSecrets" in exports)) {
79
- continue;
80
- }
81
- const { bindTokenSecrets } = exports;
82
- if (isMfaTokenSecretBinder(bindTokenSecrets)) bindTokenSecrets(jwtSecret, {});
83
- }
84
- }
85
-
86
- // Same table list as `kumiko schema generate` (collectTableMetas) — divergence
87
- // caused a production crash and left r.entity() tables missing.
88
- async function collectStackTableMetas(
89
- options: TestStackOptions,
90
- ): Promise<readonly EntityTableMeta[]> {
91
- const { collectTableMetas, enumerateFeatureTableSources, extractTableInfo } = await import(
92
- "@cosmicdrift/kumiko-framework/db"
93
- );
94
- const metas = collectTableMetas(options.features);
95
- if (options.entityTables !== false) return metas;
96
- const nonEntityNames = new Set(
97
- options.features.flatMap((f) =>
98
- enumerateFeatureTableSources(f).map((s) => extractTableInfo(s.table).name),
99
- ),
100
- );
101
- return metas.filter((m) => nonEntityNames.has(m.tableName));
102
- }
103
-
104
- async function pushStackSchema(
105
- db: DbConnection,
106
- metas: readonly EntityTableMeta[],
107
- withFileTables: boolean,
108
- ): Promise<void> {
109
- // Every ES-entity writes events via createEventStoreExecutor in the
110
- // feature's write handlers. Auto-create the events table so every
111
- // setupTestStack call is ready for writes without needing a manual
112
- // createEventsTable().
113
- await createEventsTable(db);
114
- // Archive-stream metadata — needed by ctx.events.append's archive guard and
115
- // loadAggregate's default-skip. Idempotent, so production boot running
116
- // the same call is fine.
117
- await createArchivedStreamsTable(db);
118
-
119
- // Framework state for projection rebuild/status + event-consumer cursors.
120
- // Idempotent — production boot flows run the same calls.
121
- const { createProjectionStateTable, createEventConsumerStateTable } = await import(
122
- "@cosmicdrift/kumiko-framework/pipeline"
123
- );
124
- await createProjectionStateTable(db);
125
- await createEventConsumerStateTable(db);
126
-
127
- // Files support: when a provider is registered, the fileRefs table must
128
- // exist before the first upload. Skipped when no provider — the table
129
- // stays off tenant test DBs that never touch files.
130
- if (withFileTables) {
131
- const { fileRefsTable, fileUploadLedgerTable } = await import(
132
- "@cosmicdrift/kumiko-framework/files"
133
- );
134
- await unsafePushTables(db, { fileRefsTable, fileUploadLedgerTable });
135
- }
136
-
137
- const { tableExists } = await import("@cosmicdrift/kumiko-framework/db");
138
- const missing: Record<string, unknown> = {};
139
- for (const meta of metas) {
140
- if (await tableExists(db, `public.${meta.tableName}`)) continue;
141
- missing[meta.tableName] = meta;
142
- }
143
- if (Object.keys(missing).length > 0) {
144
- await unsafePushTables(db, missing);
145
- }
146
- }
147
-
148
- // Only inside an integration-runner run: the framework tables above are not part
149
- // of the fingerprint, which holds because one run never sees two framework versions.
150
- async function resolveTestDbTemplateName(
151
- options: TestStackOptions,
152
- metas: readonly EntityTableMeta[],
153
- withFileTables: boolean,
154
- rowLevelSecurity: RowLevelSecurityMode,
155
- ): Promise<string | undefined> {
156
- const runId = process.env[TEST_DB_TEMPLATE_RUN_ENV];
157
- if (runId === undefined || options.persistentDb === true || options.dbName !== undefined) {
158
- return undefined;
159
- }
160
- const { renderTablesDdl } = await import("@cosmicdrift/kumiko-framework/db");
161
- const fingerprint = createHash("sha256")
162
- .update(
163
- JSON.stringify({
164
- withFileTables,
165
- rowLevelSecurity,
166
- role: rowLevelSecurity === "on" ? TEST_APPLICATION_ROLE : "superuser",
167
- ddl: renderTablesDdl(metas, { rowLevelSecurity }),
168
- }),
169
- )
170
- .digest("hex")
171
- .slice(0, 16);
172
- return `${testDbTemplatePrefix(runId)}${fingerprint}`;
173
- }
174
-
175
- // Best-effort and sequential: a broken cleanup must never mask the setup error the caller rethrows.
176
- export async function runCleanupsIgnoringErrors(
177
- cleanups: ReadonlyArray<() => Promise<void>>,
178
- ): Promise<void> {
179
- for (const cleanup of cleanups) {
180
- try {
181
- await cleanup();
182
- } catch {
183
- // ignore — the setup error is the one that matters
184
- }
185
- }
186
- }
187
-
188
- export async function validateStackFeatures(
189
- options: TestStackOptions,
190
- jwtSecret: string,
191
- ): Promise<void> {
192
- // Install the Temporal polyfill before feature code runs. Idempotent: the
193
- // production server boot does the same. A no-op on runtimes with native Temporal.
194
- const { ensureTemporalPolyfill } = await import("@cosmicdrift/kumiko-framework/time");
195
- await ensureTemporalPolyfill();
196
-
197
- // Ownership boot-guards (unqualified where-fragments, where-rules on the
198
- // write path) otherwise run only in the prod boot via validateBoot, leaving
199
- // every test stack blind to a broken access map.
200
- // Runs after the polyfill (buildEntityTable needs it to derive the probe
201
- // columns) and before the ephemeral DB/Redis exist, so a throw can't leak
202
- // a database that nothing will clean up.
203
- validateOwnershipBoot(options.features);
204
- // Nav/workspace refs fail the prod boot too; the subset check tolerates refs into unmounted features.
205
- validateNavBootSubset(options.features);
206
- if (options.validateBoot === "full") validateBoot(options.features);
207
- bindMfaTokenSecrets(options.features, jwtSecret);
208
- }
209
-
210
- export type StackStorage = {
211
- readonly testDb: Awaited<ReturnType<typeof createTestDb>>;
212
- readonly testRedis: TestRedis;
213
- };
214
-
215
- export async function provisionStackStorage(options: TestStackOptions): Promise<StackStorage> {
216
- const stackTableMetas = await collectStackTableMetas(options);
217
- const withFileTables = options.files !== undefined;
218
- const buildStackSchema = (db: DbConnection): Promise<void> =>
219
- pushStackSchema(db, stackTableMetas, withFileTables);
220
- const rowLevelSecurity = options.rowLevelSecurity ?? "on";
221
- const applicationRole = rowLevelSecurity === "on";
222
- const templateDbName = await resolveTestDbTemplateName(
223
- options,
224
- stackTableMetas,
225
- withFileTables,
226
- rowLevelSecurity,
227
- );
228
- if (templateDbName !== undefined) {
229
- await ensureTestDbTemplate(templateDbName, buildStackSchema, { applicationRole });
230
- }
231
-
232
- // Forward db-name/persistent-flag through to createTestDb. The
233
- // defaults (undefined dbName, persistent:false) keep the legacy
234
- // test contract: fresh kumiko_test_<random> DB per setup, dropped
235
- // on cleanup.
236
- const [testDb, testRedis] = await Promise.all([
237
- createTestDb({
238
- ...(options.dbName !== undefined && { dbName: options.dbName }),
239
- ...(options.persistentDb !== undefined && { persistent: options.persistentDb }),
240
- ...(options.dbPoolMax !== undefined && { poolMax: options.dbPoolMax }),
241
- ...(options.outsideTransactionPoolMax !== undefined && {
242
- outsideTransactionPoolMax: options.outsideTransactionPoolMax,
243
- }),
244
- ...(templateDbName !== undefined && { templateDbName }),
245
- applicationRole,
246
- }),
247
- createTestRedis(
248
- options.sharedRedisWith && { borrowKeyPrefix: options.sharedRedisWith.redis.keyPrefix },
249
- ),
250
- ]);
251
-
252
- // Any throw in this DDL region must still drop the just-created ephemeral
253
- // DB/Redis — the caller never gets the stack object back to call
254
- // cleanup() itself (same "leaked ephemeral DB" failure class as the later
255
- // try/catch in setupTestStack, but for setup that runs before that try starts).
256
- try {
257
- if (templateDbName === undefined) await buildStackSchema(testDb.db);
258
- await assertRowLevelSecurityBootState(
259
- testDb.db,
260
- rowLevelSecurity,
261
- knownTablesOf(options.features),
262
- );
263
- } catch (error) {
264
- await runCleanupsIgnoringErrors([() => testDb.cleanup(), () => testRedis.cleanup()]);
265
- throw error;
266
- }
267
- return { testDb, testRedis };
268
- }
269
-
270
- // Redis only where two stacks can actually disagree (avoids two extra
271
- // Pub/Sub connections); otherwise a local bus so invalidation still works
272
- // inside this stack. Passing it explicitly keeps buildServer from using its
273
- // REDIS_URL default (an unnamespaced channel).
274
- export function createStackCacheSync(
275
- options: TestStackOptions,
276
- testRedis: TestRedis,
277
- ): ClosableCacheSyncBus {
278
- return options.cacheSync || options.sharedRedisWith
279
- ? createRedisCacheSyncBus({
280
- redisUrl: testRedis.redisUrl,
281
- channelPrefix: testRedis.keyPrefix,
282
- })
283
- : createLocalCacheSyncBus();
284
- }
285
-
286
- // A static `files.storageProvider` is wired as the per-tenant resolver — the
287
- // framework test seam that doesn't require mounting config + file-foundation.
288
- // (Bundled GDPR tests mount the real provider features instead.)
289
- function isClock(value: unknown): value is Clock {
290
- return (
291
- typeof value === "object" && value !== null && "now" in value && typeof value.now === "function"
292
- );
293
- }
294
-
295
- async function resolveStackFileProvider(
296
- options: TestStackOptions,
297
- testDb: StackStorage["testDb"],
298
- readClock: () => unknown,
299
- ): Promise<import("@cosmicdrift/kumiko-framework/files").FileProviderResolver | undefined> {
300
- if (!options.files) return undefined;
301
- const provider = options.files.storageProvider;
302
- const { withUploadLedger } = await import("@cosmicdrift/kumiko-framework/files");
303
- // Read per call: the clock arrives via extraContext, which is merged after this resolver is built.
304
- const now = (): Temporal.Instant => {
305
- const clock = readClock();
306
- return isClock(clock) ? clock.now() : Temporal.Now.instant();
307
- };
308
- return withUploadLedger(() => Promise.resolve(provider), testDb.db, now);
309
- }
310
-
311
- export async function buildStackServices(
312
- options: TestStackOptions,
313
- testDb: StackStorage["testDb"],
314
- testRedis: TestRedis,
315
- cacheSync: ClosableCacheSyncBus,
316
- ) {
317
- const searchAdapter = createInMemorySearchAdapter();
318
- const events = createEventCollector();
319
- const registry = createRegistry([...options.features]);
320
-
321
- // Wire SSE broker with event collector — built early (not just before
322
- // buildServer) because extraContext + the job context below both need it.
323
- const sseBroker = options.sseBroker ?? createSseBroker();
324
- sseBroker.addClient(
325
- "tenant:00000000-0000-4000-8000-000000000001",
326
- (event) => events.sse.push(event),
327
- () => {},
328
- );
329
-
330
- const entityCache = createEntityCache(testRedis.redis, { ttlSeconds: 60 });
331
- const extraContextClock: { current: unknown } = { current: undefined };
332
- const fileProviderResolver = await resolveStackFileProvider(
333
- options,
334
- testDb,
335
- () => extraContextClock.current,
336
- );
337
- const observability = options.observability ?? createNoopProvider();
338
-
339
- // Same AppContext buildServer() gets below (db/redis/searchAdapter/
340
- // entityCache/masterKeyProvider/fileProviderResolver/extraContext) —
341
- // shared so the job context can't drift from the request-path context:
342
- // a reduced `{ db, registry }` literal let jobs pass in tests while
343
- // reaching for fields only prod's context has.
344
- //
345
- // effectiveFeatures deliberately stays OUT of appContext — prod never puts
346
- // it there either (only dispatcherOptions.effectiveFeatures, consumed by
347
- // the command-dispatcher — see buildJobRunnerWithHook in entrypoint/
348
- // index.ts). Putting it here would reintroduce the exact test-vs-prod
349
- // drift fixed: a job/handler reading `ctx.services.effectiveFeatures` would pass in
350
- // tests and break in prod.
351
- const extraContext =
352
- typeof options.extraContext === "function"
353
- ? options.extraContext({
354
- registry,
355
- // The raw pool, as in prod: request-time services keep the ambient request scope, so a tenant leak shows in tests.
356
- db: testDb.db,
357
- sseBroker,
358
- redis: testRedis.redis,
359
- })
360
- : options.extraContext;
361
- // The prod entrypoint resolves the mounted file-provider plugins before the job runner sees
362
- // the context; without it a job's ctx.services.files is undefined only in tests.
363
- const appContext = withFileProviderResolver(
364
- registry,
365
- {
366
- db: testDb.db,
367
- redis: testRedis.redis,
368
- searchAdapter,
369
- entityCache,
370
- registry,
371
- ...(options.masterKeyProvider ? { masterKeyProvider: options.masterKeyProvider } : {}),
372
- ...(fileProviderResolver ? { _fileProviderResolver: fileProviderResolver } : {}),
373
- ...(options.defaultLocale !== undefined && { defaultLocale: options.defaultLocale }),
374
- ...extraContext,
375
- },
376
- // Same bus buildServer gets: the resolver built here is the one it reuses, so config and
377
- // secret writes must reach its per-tenant provider cache through it.
378
- cacheSync,
379
- );
380
- extraContextClock.current = extraContext?.["clock"];
381
- return { searchAdapter, events, registry, sseBroker, entityCache, observability, appContext };
382
- }
383
-
384
- export type StackServices = Awaited<ReturnType<typeof buildStackServices>>;
385
-
386
- type JobFailureTracker = ReturnType<typeof createJobFailureTracker>;
387
-
388
- // Built before buildServer() so it can be merged into dispatcherOptions
389
- // (write handlers' `ctx.services.jobRunner.dispatch(...)` and the afterCommit
390
- // event-trigger hook both need it present at dispatcher-construction
391
- // time, same as the prod entrypoint's buildJobRunnerWithHook). Uses the
392
- // test-stack's own ephemeral redis — no separate `redisUrl` seam needed.
393
- //
394
- // context = appContext + tracer/meter, mirroring the prod entrypoint's
395
- // `contextWithObservability(options.context, observability)`.
396
- export function createStackJobRunner(
397
- options: TestStackOptions,
398
- services: StackServices,
399
- testDb: StackStorage["testDb"],
400
- testRedis: TestRedis,
401
- jobFailureTracker: JobFailureTracker,
402
- ): JobRunner | undefined {
403
- const { registry, appContext, observability } = services;
404
- if (!options.jobs || registry.getAllJobs().size === 0) return undefined;
405
- const runLogger = options.jobs.runLogger?.({ registry, db: testDb.db });
406
- return createJobRunner({
407
- registry,
408
- context: { ...appContext, tracer: observability.tracer, meter: observability.meter },
409
- // The real REDIS_URL, not one rebuilt from `.options` — rebuilding it lost
410
- // password/username/tls/path.
411
- redisUrl: testRedis.redisUrl,
412
- ...(options.jobs.consumerLane !== undefined && { consumerLane: options.jobs.consumerLane }),
413
- queueNamePrefix:
414
- options.jobs.queueNamePrefix ?? queueNamePrefixForTestRedis(testRedis.keyPrefix),
415
- ...(options.jobs.getActiveTenantIds !== undefined && {
416
- getActiveTenantIds: options.jobs.getActiveTenantIds,
417
- }),
418
- ...(runLogger?.onJobStart !== undefined && { onJobStart: runLogger.onJobStart }),
419
- ...(runLogger?.onJobQueued !== undefined && { onJobQueued: runLogger.onJobQueued }),
420
- ...(runLogger?.onJobDropped !== undefined && { onJobDropped: runLogger.onJobDropped }),
421
- // Tracker fires in finally: drainJobs wakes on it, so the log row must
422
- // be written first, and a throwing logger must not swallow the signal.
423
- onJobComplete: async (jobName, jobId, ...rest) => {
424
- try {
425
- await runLogger?.onJobComplete?.(jobName, jobId, ...rest);
426
- } finally {
427
- jobFailureTracker.onJobComplete(jobName, jobId);
428
- }
429
- },
430
- onJobFailed: async (jobName, jobId, error, ...rest) => {
431
- try {
432
- await runLogger?.onJobFailed?.(jobName, jobId, error, ...rest);
433
- } finally {
434
- jobFailureTracker.onJobFailed(jobName, jobId, error);
435
- }
436
- },
437
- });
438
- }
439
-
440
- function collectSearchableFields(features: TestStackOptions["features"]): string[] {
441
- const searchableFields: string[] = [];
442
- for (const feature of features) {
443
- for (const [, entity] of Object.entries(feature.entities ?? {})) {
444
- for (const [fieldName, field] of Object.entries(entity.fields)) {
445
- if ((field.type === "text" || field.type === "longText") && field.searchable) {
446
- searchableFields.push(fieldName);
447
- }
448
- if (field.type === "embedded") {
449
- for (const [subName, subField] of Object.entries(field.schema)) {
450
- if (subField.searchable) {
451
- searchableFields.push(`${fieldName}_${subName}`);
452
- }
453
- }
454
- }
455
- }
456
- }
457
- }
458
- return searchableFields;
459
- }
460
-
461
- // Auto-configure search for tenant 1 based on registry
462
- async function configureStackSearch(
463
- options: TestStackOptions,
464
- enabledHooks: ReadonlyArray<string>,
465
- searchAdapter: SearchAdapter,
466
- ): Promise<void> {
467
- if (enabledHooks.includes("search")) {
468
- const searchableFields = collectSearchableFields(options.features);
469
- if (options.searchConfig) {
470
- await searchAdapter.configure(options.searchConfig.tenantId, {
471
- searchableFields: options.searchConfig.searchableFields,
472
- rankingFields: options.searchConfig.rankingFields,
473
- });
474
- } else if (searchableFields.length > 0) {
475
- await searchAdapter.configure("00000000-0000-4000-8000-000000000001", {
476
- searchableFields,
477
- rankingFields: searchableFields,
478
- });
479
- }
480
- }
481
- }
482
-
483
- // buildServer only auto-wires an L3 RateLimitResolver from
484
- // `context.redis` — a degradation test that nulls `redis` via
485
- // extraContext (to exercise a handler's own ctx.services.redis-down guard) also
486
- // silently strips rate-limiting, even though every handler with a
487
- // `rateLimit` declaration still requires a resolver at dispatch time.
488
- // Since e7bf543ad, an IP-keyed bucket key is built unconditionally
489
- // (falls back to a shared "unknown" IP rather than skipping), so the
490
- // missing resolver now throws instead of merely skipping enforcement.
491
- // Mirrors idempotency/eventDedup: built from the test-stack's own
492
- // always-real `testRedis.redis`, independent of whatever extraContext
493
- // did to `appContext.redis` — an explicit `context.rateLimit` from
494
- // extraContext still wins (same precedence buildServer documents).
495
- function resolveStackRateLimitFallback(
496
- options: TestStackOptions,
497
- appContext: StackServices["appContext"],
498
- testRedis: TestRedis,
499
- ): ReturnType<typeof createRateLimitResolver> | undefined {
500
- const explicitRateLimit = propertyOf(appContext, "rateLimit");
501
- const needsOwnRateLimitResolver =
502
- explicitRateLimit === undefined &&
503
- (appContext.redis === undefined || options.rateLimitNowMs !== undefined);
504
- if (!needsOwnRateLimitResolver) return undefined;
505
- return createRateLimitResolver({
506
- // An app-supplied redis keeps buckets and app redis on the same instance.
507
- redis: appContext.redis ?? testRedis.redis,
508
- ...(options.rateLimitNowMs ? { nowMs: options.rateLimitNowMs } : {}),
509
- });
510
- }
511
-
512
- function testCodeDb<T extends object>(options: TestStackOptions, db: T): T {
513
- return (options.rowLevelSecurity ?? DEFAULT_ROW_LEVEL_SECURITY_MODE) === "on"
514
- ? systemScopedRunner(db, "test stack seeds and reads rows across tenants")
515
- : db;
516
- }
517
-
518
- async function resolveStackAnonymousAccess(
519
- options: TestStackOptions,
520
- testDb: StackStorage["testDb"],
521
- testRedis: TestRedis,
522
- services: StackServices,
523
- ): Promise<Pick<ServerBuildOptions, "anonymousAccess">> {
524
- const { registry, sseBroker } = services;
525
- const hookDb = appHookScopedRunner(
526
- testDb.db,
527
- options.rowLevelSecurity ?? DEFAULT_ROW_LEVEL_SECURITY_MODE,
528
- );
529
- const baseAnon =
530
- typeof options.anonymousAccess === "function"
531
- ? options.anonymousAccess({ registry, db: hookDb, sseBroker, redis: testRedis.redis })
532
- : options.anonymousAccess;
533
- const resolvedAnon = options.enrichAnonymousAccess
534
- ? await options.enrichAnonymousAccess(baseAnon, { registry, db: hookDb })
535
- : baseAnon;
536
- return resolvedAnon ? { anonymousAccess: resolvedAnon } : {};
537
- }
538
-
539
- type ServerBuildOptions = Parameters<typeof buildServer>[0];
540
-
541
- // Default tests to no login rate-limiter so existing suites that loop
542
- // over logins don't hit a 429 after 10 attempts. Suites specifically
543
- // testing the limiter can override via authConfig.loginRateLimit.
544
- function buildStackAuthConfig(
545
- authConfig: TestStackOptions["authConfig"],
546
- ): Pick<ServerBuildOptions, "auth"> {
547
- if (!authConfig) return {};
548
- return {
549
- auth: {
550
- ...authConfig,
551
- ...(authConfig.loginRateLimit === undefined ? { loginRateLimit: null } : {}),
552
- },
553
- };
554
- }
555
-
556
- // Tests drive the dispatcher via stack.eventDispatcher.runOnce() for
557
- // deterministic drains — no timer-induced flakiness. pollIntervalMs
558
- // stays short anyway in case a test opts into `.start()`. pgClient
559
- // plumbs through the LISTEN wake-up for tests that want to measure
560
- // post-commit latency (Sprint E.4).
561
- function stackEventDispatcherOptions(
562
- options: TestStackOptions,
563
- testDb: StackStorage["testDb"],
564
- enabledHooks: ReadonlyArray<string>,
565
- ): NonNullable<ServerBuildOptions["eventDispatcher"]> {
566
- return {
567
- pollIntervalMs: options.eventDispatcherPollIntervalMs ?? 50,
568
- pgClient: testDb.client,
569
- systemConsumers: {
570
- sse: enabledHooks.includes("sse"),
571
- search: enabledHooks.includes("search"),
572
- accessInvalidation: enabledHooks.includes("sse"),
573
- },
574
- };
575
- }
576
-
577
- export type StackServerInput = {
578
- readonly options: TestStackOptions;
579
- readonly jwtSecret: string;
580
- readonly enabledHooks: ReadonlyArray<string>;
581
- readonly testDb: StackStorage["testDb"];
582
- readonly testRedis: TestRedis;
583
- readonly cacheSync: ClosableCacheSyncBus;
584
- readonly services: StackServices;
585
- readonly jobRunner: JobRunner | undefined;
586
- readonly jobFailureTracker: JobFailureTracker;
587
- };
588
-
589
- type StackServer = ReturnType<typeof buildServer>;
590
-
591
- function buildStackServerOptions(
592
- input: StackServerInput,
593
- anonymousAccess: Pick<ServerBuildOptions, "anonymousAccess">,
594
- ): ServerBuildOptions {
595
- const { options, jwtSecret, enabledHooks, testDb, testRedis, cacheSync, services, jobRunner } =
596
- input;
597
- const { registry, sseBroker, appContext } = services;
598
- const idempotency = createIdempotencyGuard(testRedis.redis, { ttlSeconds: 60 });
599
- const eventDedup = createEventDedup(testRedis.redis, { ttlSeconds: 60 });
600
- const rateLimitFallback = resolveStackRateLimitFallback(options, appContext, testRedis);
601
- return {
602
- registry,
603
- context: rateLimitFallback ? { ...appContext, rateLimit: rateLimitFallback } : appContext,
604
- jwtSecret,
605
- ...(options.observability ? { observability: options.observability } : {}),
606
- ...(options.lifecycleSystemHooks && { systemHooks: options.lifecycleSystemHooks }),
607
- dispatcherOptions: {
608
- idempotency,
609
- cacheSync,
610
- outsideTransactionDb: testDb.outsideTransactionDb,
611
- ...(options.effectiveFeatures && { effectiveFeatures: options.effectiveFeatures }),
612
- ...(jobRunner && { jobRunner }),
613
- },
614
- eventDedup,
615
- sseBroker,
616
- ...(options.trustedProxyHops !== undefined && { trustedProxyHops: options.trustedProxyHops }),
617
- ...(options.errorDocs && { errorDocs: options.errorDocs }),
618
- ...(options.extraRoutes && { extraRoutes: options.extraRoutes }),
619
- ...(options.metrics && { metrics: options.metrics }),
620
- eventDispatcher: stackEventDispatcherOptions(options, testDb, enabledHooks),
621
- ...buildStackAuthConfig(options.authConfig),
622
- ...(options.lifecycle ? { lifecycle: options.lifecycle } : {}),
623
- ...(options.rateLimit ? { rateLimit: options.rateLimit } : {}),
624
- ...anonymousAccess,
625
- };
626
- }
627
-
628
- function assembleTestStack(
629
- input: StackServerInput,
630
- server: StackServer,
631
- eventDispatcher: EventDispatcher | undefined,
632
- ): TestStack {
633
- const { options, testDb, testRedis, cacheSync, services, jobRunner, jobFailureTracker } = input;
634
- const http = createRequestHelper(server.app, server.jwt, {
635
- ...(options.authConfig?.sessionCreator !== undefined && {
636
- sessionCreator: options.authConfig.sessionCreator,
637
- }),
638
- });
639
- // Test code and the drain see every tenant's rows; the services keep the enforced pool.
640
- const crossTenantDb = testCodeDb(options, testDb.db);
641
- return {
642
- app: server.app,
643
- jwt: server.jwt,
644
- registry: services.registry,
645
- db: crossTenantDb,
646
- unscopedDb: testDb.db,
647
- dbPoolMax: testDb.poolMax,
648
- redis: testRedis,
649
- cacheSync,
650
- search: services.searchAdapter,
651
- events: services.events,
652
- http,
653
- observability: server.observability,
654
- sseBroker: services.sseBroker,
655
- dispatcher: server.dispatcher,
656
- context: server.context,
657
- ...(eventDispatcher ? { eventDispatcher } : {}),
658
- ...(server.lifecycle ? { lifecycle: server.lifecycle } : {}),
659
- ...(jobRunner ? { jobRunner } : {}),
660
- drainJobs: () =>
661
- drainJobs({ db: crossTenantDb, eventDispatcher, jobRunner }, jobFailureTracker),
662
- cleanup: async () => {
663
- if (jobRunner) await jobRunner.stop();
664
- if (eventDispatcher) await eventDispatcher.stop();
665
- await server.observability.shutdown();
666
- await cacheSync.close();
667
- await Promise.all([testDb.cleanup(), testRedis.cleanup()]);
668
- },
669
- };
670
- }
671
-
672
- export async function startStackServer(input: StackServerInput): Promise<TestStack> {
673
- const { options, enabledHooks, testDb, testRedis, services, jobRunner } = input;
674
- if (jobRunner) await jobRunner.start();
675
- await configureStackSearch(options, enabledHooks, services.searchAdapter);
676
-
677
- const anonymousAccess = await resolveStackAnonymousAccess(options, testDb, testRedis, services);
678
- const server = buildServer(buildStackServerOptions(input, anonymousAccess));
679
-
680
- // Mirrors the prod entrypoints — without this, JobContext.write/writeAs/
681
- // queryAs/queryAsMember throw on first use inside a test-stack job.
682
- if (jobRunner) jobRunner.attachDispatcher(dispatcherToWriteRef(server.dispatcher));
683
-
684
- const eventDispatcher: EventDispatcher | undefined = server.eventDispatcher;
685
-
686
- // Pre-register consumer state rows so tests can call runOnce() directly
687
- // without a preceding explicit start(). Timer fires at pollIntervalMs=50
688
- // but each consumer runs at most one turn at a time — tests that drain via
689
- // runOnce() remain deterministic. Tests that specifically exercise the
690
- // timer loop call start() again (idempotent) after setup.
691
- if (eventDispatcher) await eventDispatcher.ensureRegistered();
692
-
693
- return assembleTestStack(input, server, eventDispatcher);
694
- }