chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the generator-built feature index with its app, bounded-context and feature declarations, the src/platform kernel and scale tooling, the 2026-09-24 src review fixes, and the 2026-09-25 maturity review round with its CHANGELOG [보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them merged with product changes; 127 are not carried. Product identity is unchanged: name, version 0.1.0, routes, design and the TechLog domain. Three decisions worth naming. TechLog stays composed directly, as the last two syncs recorded; its directory carries a NOT_INSTALLED marker that says so, and every installed-* composer takes the template's projection with TechLog added on top. The reference sample is no longer installed: the template now installs a feature only through feature-module.ts and context-routes.ts, which load the screens this product deleted, so its three operations, six schemas and one topic leave the registries, recorded as registry change evidence. And AppRouter mounts the platform and TechLog routes only; the template's bounded-context route gateway waits for a generator-installed feature. Required fixes: readSubject on the BFF session owner (without it every HTTP Studio session would close as integration-failed), zod through the facade in nine TechLog files, noUnusedLocals, and public/config.json written out to match the local profile. Derived baselines were recomputed after reproducing both sides' values: CI contract 101 commands / 106 references / 141 artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime config schema baseline equals the schema at8210d48. Verified here: types, lint, architecture, adapter inventory, CI contract, i18n, design system, diagnostics, browser security, dev release manifest, TechLog contract and build pass; 220 component, 155 integration, 15 contract, 418 TechLog, 43 reference-feature, 18 recipe and 46 release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at8210d48first and unchanged: check:registries (byte-identical), test:runtime-schema, verify:documentation. Brought by the template and escalated rather than suppressed: check:request-fanout on TechLog's cursor pagination, check:remediation-ledger (fails upstream too), the shared-chunk hash test, and the registry-dependent sample removal and second-feature tests. Playwright suites were not run. Full record, the five open questions and the follow-ups in docs/operations/template-sync-2026-09-29.md. (cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
import type { RouteObject } from "react-router-dom";
|
||||
import { z } from "zod";
|
||||
|
||||
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
|
||||
import { defineFeatureModule } from "../../src/features/feature-module.ts";
|
||||
|
||||
/**
|
||||
* A test-only product feature for platform tests that need a feature route: one
|
||||
* that requires a session, parses a search codec, and belongs to a feature the
|
||||
* runtime can switch off. Those tests install it by mocking the generated
|
||||
* indexes, so they do not depend on the removable sample feature (FE-GATE-020):
|
||||
*
|
||||
* vi.mock("../../src/.generated/product-feature-index.ts", async () => ({
|
||||
* DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"],
|
||||
* PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE],
|
||||
* }));
|
||||
* vi.mock("../../src/.generated/product-context-index.ts", async () => ({
|
||||
* PRODUCT_CONTEXT_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_CONTEXT_MODULE],
|
||||
* }));
|
||||
*/
|
||||
export const FIXTURE_FEATURE_ID = "fixture-feature";
|
||||
|
||||
function fixtureRoute(
|
||||
routeId: string,
|
||||
path: string,
|
||||
searchSchema: string | null,
|
||||
chunkId: string,
|
||||
) {
|
||||
return Object.freeze({
|
||||
routeId,
|
||||
path,
|
||||
paramsSchema: null,
|
||||
searchSchema,
|
||||
access: "session-required",
|
||||
loadingSurface: "fixture-page",
|
||||
errorSurface: "feature-boundary",
|
||||
chunkId,
|
||||
title: routeId,
|
||||
navigationLabel: null,
|
||||
navigationOrder: null,
|
||||
});
|
||||
}
|
||||
|
||||
const FIXTURE_ROUTES = Object.freeze({
|
||||
FIXTURE_ITEMS: fixtureRoute("FIXTURE_ITEMS", "/fixture/items", "FixtureItemsQuery", "route-fixture-items"),
|
||||
FIXTURE_ITEM_STATUS: fixtureRoute("FIXTURE_ITEM_STATUS", "/fixture/items/status", null, "route-fixture-item-status"),
|
||||
FIXTURE_ITEM_FORM: fixtureRoute("FIXTURE_ITEM_FORM", "/fixture/items/new", null, "route-fixture-item-form"),
|
||||
});
|
||||
|
||||
const FIXTURE_TITLES: Readonly<Record<keyof typeof FIXTURE_ROUTES, string>> = {
|
||||
FIXTURE_ITEMS: "Fixture items",
|
||||
FIXTURE_ITEM_STATUS: "Fixture item status",
|
||||
FIXTURE_ITEM_FORM: "Create fixture item",
|
||||
};
|
||||
|
||||
const FIXTURE_MESSAGES = Object.freeze(
|
||||
Object.fromEntries(
|
||||
Object.entries(FIXTURE_TITLES).flatMap(([routeId, title]) => [
|
||||
[`route.${routeId}.title`, title],
|
||||
[`route.${routeId}.navigation`, title],
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
export const FIXTURE_FEATURE_MODULE = defineFeatureModule({
|
||||
id: FIXTURE_FEATURE_ID,
|
||||
contracts: Object.freeze({
|
||||
featureId: FIXTURE_FEATURE_ID,
|
||||
routes: FIXTURE_ROUTES,
|
||||
routeRuntimeContracts: Object.freeze(
|
||||
Object.fromEntries(
|
||||
Object.values(FIXTURE_ROUTES).map((route) => [
|
||||
route.routeId,
|
||||
Object.freeze({
|
||||
routeId: route.routeId,
|
||||
moduleId: `${route.chunkId}-page`,
|
||||
paramsCodec: "none",
|
||||
searchCodec: route.searchSchema ?? "none",
|
||||
}),
|
||||
]),
|
||||
),
|
||||
),
|
||||
apiOperations: Object.freeze({}),
|
||||
invalidation: Object.freeze({ topics: [], namespaces: [], edges: [] }),
|
||||
topicVersions: Object.freeze([]),
|
||||
schemas: Object.freeze({}),
|
||||
runtimeSchemas: Object.freeze({}),
|
||||
mappers: Object.freeze({}),
|
||||
}),
|
||||
routes: FIXTURE_ROUTES,
|
||||
adapters: [],
|
||||
runtimes: [
|
||||
Object.freeze({
|
||||
featureId: FIXTURE_FEATURE_ID,
|
||||
routeCodecs: Object.freeze({
|
||||
FixtureItemsQuery: z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(20),
|
||||
}),
|
||||
}),
|
||||
routeRuntime: Object.freeze({}),
|
||||
}),
|
||||
],
|
||||
messages: Object.freeze({ "ko-KR": FIXTURE_MESSAGES, "en-US": FIXTURE_MESSAGES }),
|
||||
contractContributions: [],
|
||||
});
|
||||
|
||||
function FixturePage() {
|
||||
return <p>Fixture page</p>;
|
||||
}
|
||||
|
||||
export const FIXTURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze(
|
||||
Object.values(FIXTURE_ROUTES).map((route) =>
|
||||
Object.freeze({
|
||||
id: route.routeId,
|
||||
path: route.path,
|
||||
handle: Object.freeze({
|
||||
routeId: route.routeId,
|
||||
runtime: Object.freeze({ moduleId: `${route.chunkId}-page`, Component: FixturePage }),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const FIXTURE_CONTEXT_MODULE = defineBoundedContextModule({
|
||||
id: "fixture-context",
|
||||
features: [FIXTURE_FEATURE_MODULE],
|
||||
budget: { maxFeatures: 1 },
|
||||
route: {
|
||||
path: "fixture/items/*",
|
||||
loadRoutes: async () => FIXTURE_CONTEXT_ROUTES,
|
||||
},
|
||||
});
|
||||
@@ -24,6 +24,31 @@ type StoreState = {
|
||||
indexes: Map<string, IndexState>;
|
||||
};
|
||||
|
||||
/** One named database: its schema, rows and version. */
|
||||
type DatabaseState = {
|
||||
stores: Map<string, StoreState>;
|
||||
version: number;
|
||||
latest: FakeDatabase | null;
|
||||
/** Connections handed out by a successful open, closed or not. */
|
||||
connections: FakeDatabase[];
|
||||
/** Transactions that have not finished, in creation order. */
|
||||
transactions: FakeTransaction[];
|
||||
/** A `deleteDatabase` waiting for the open connections to close. */
|
||||
pendingDelete: (() => void) | null;
|
||||
};
|
||||
|
||||
function storeOf(state: DatabaseState, name: string): StoreState {
|
||||
const store = state.stores.get(name);
|
||||
if (!store) {
|
||||
throw new DOMException("Store does not exist.", "NotFoundError");
|
||||
}
|
||||
return store;
|
||||
}
|
||||
|
||||
// The fake decides when a transaction's task has ended with a real macrotask,
|
||||
// so a test that fakes timers cannot keep a transaction alive by accident.
|
||||
const realSetTimeout = globalThis.setTimeout.bind(globalThis);
|
||||
|
||||
type FakeKeyRange =
|
||||
| Readonly<{
|
||||
fakeKind: "ONLY";
|
||||
@@ -221,23 +246,26 @@ class FakeDatabase {
|
||||
onversionchange: ((event: IDBVersionChangeEvent) => unknown) | null = null;
|
||||
onclose: ((event: Event) => unknown) | null = null;
|
||||
|
||||
constructor(private readonly owner: MemoryIndexedDbFactory) {}
|
||||
constructor(
|
||||
private readonly owner: MemoryIndexedDbFactory,
|
||||
readonly state: DatabaseState,
|
||||
) {}
|
||||
|
||||
get objectStoreNames(): DOMStringList {
|
||||
return stringList(this.owner.storeNames());
|
||||
return stringList(this.state.stores.keys());
|
||||
}
|
||||
|
||||
createObjectStore(
|
||||
name: string,
|
||||
options?: IDBObjectStoreParameters,
|
||||
): IDBObjectStore {
|
||||
if (this.owner.hasStore(name)) {
|
||||
if (this.state.stores.has(name)) {
|
||||
throw new DOMException("Store already exists.", "ConstraintError");
|
||||
}
|
||||
if (typeof options?.keyPath !== "string") {
|
||||
throw new DOMException("The fake requires a string key path.", "DataError");
|
||||
}
|
||||
this.owner.createStore(name, {
|
||||
this.state.stores.set(name, {
|
||||
keyPath: options.keyPath,
|
||||
autoIncrement: options.autoIncrement ?? false,
|
||||
data: new Map(),
|
||||
@@ -247,13 +275,13 @@ class FakeDatabase {
|
||||
}
|
||||
|
||||
deleteObjectStore(name: string): void {
|
||||
if (!this.owner.deleteStore(name)) {
|
||||
if (!this.state.stores.delete(name)) {
|
||||
throw new DOMException("Store does not exist.", "NotFoundError");
|
||||
}
|
||||
}
|
||||
|
||||
schemaObjectStore(name: string): IDBObjectStore {
|
||||
const state = this.owner.store(name);
|
||||
const state = storeOf(this.state, name);
|
||||
return new FakeObjectStore(null, state) as unknown as IDBObjectStore;
|
||||
}
|
||||
|
||||
@@ -261,7 +289,7 @@ class FakeDatabase {
|
||||
name: string,
|
||||
transaction: FakeUpgradeTransaction,
|
||||
): IDBObjectStore {
|
||||
const state = this.owner.store(name);
|
||||
const state = storeOf(this.state, name);
|
||||
return new FakeObjectStore(
|
||||
null,
|
||||
state,
|
||||
@@ -278,16 +306,22 @@ class FakeDatabase {
|
||||
}
|
||||
const names =
|
||||
typeof storeNames === "string" ? [storeNames] : [...storeNames];
|
||||
const transaction = new FakeTransaction(this.owner, names, mode);
|
||||
const transaction = new FakeTransaction(
|
||||
this.owner,
|
||||
this.state,
|
||||
names,
|
||||
mode,
|
||||
);
|
||||
this.owner.noteTransaction(transaction);
|
||||
return transaction as unknown as IDBTransaction;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.state.pendingDelete?.();
|
||||
}
|
||||
|
||||
fireVersionChange(newVersion: number): void {
|
||||
fireVersionChange(newVersion: number | null): void {
|
||||
this.onversionchange?.({
|
||||
oldVersion: this.version,
|
||||
newVersion,
|
||||
@@ -307,19 +341,108 @@ class FakeTransaction {
|
||||
error: DOMException | null = null;
|
||||
readonly mode: IDBTransactionMode;
|
||||
private active = true;
|
||||
/**
|
||||
* Native "active" state: a request may be placed only in the task that
|
||||
* created the transaction or while one of its request events (and the
|
||||
* microtasks that event queued) is being handled.
|
||||
*/
|
||||
private accepting = true;
|
||||
/** Held back until every earlier overlapping transaction finishes. */
|
||||
private started = false;
|
||||
private readonly deferred: Array<() => void> = [];
|
||||
private completionQueued = false;
|
||||
private pending = 0;
|
||||
private readonly workingStores: Map<string, StoreState>;
|
||||
|
||||
constructor(
|
||||
private readonly owner: MemoryIndexedDbFactory,
|
||||
private readonly database: DatabaseState,
|
||||
private readonly names: readonly string[],
|
||||
mode: IDBTransactionMode,
|
||||
) {
|
||||
this.mode = mode;
|
||||
this.workingStores = new Map(
|
||||
names.map((name) => [name, cloneStore(owner.store(name))]),
|
||||
names.map((name) => [name, cloneStore(storeOf(database, name))]),
|
||||
);
|
||||
database.transactions.push(this);
|
||||
this.startIfUnblocked();
|
||||
this.deactivateAfterTask();
|
||||
}
|
||||
|
||||
/**
|
||||
* Native IndexedDB runs transactions with overlapping scopes in creation
|
||||
* order unless both are readonly. A later one starts from the rows the
|
||||
* earlier one committed.
|
||||
*/
|
||||
startIfUnblocked(): void {
|
||||
if (this.started || !this.active) return;
|
||||
const earlier = this.database.transactions.slice(
|
||||
0,
|
||||
this.database.transactions.indexOf(this),
|
||||
);
|
||||
if (earlier.some((transaction) => transaction.blocks(this))) return;
|
||||
this.started = true;
|
||||
for (const name of this.names) {
|
||||
const fresh = cloneStore(storeOf(this.database, name));
|
||||
const working = this.workingStores.get(name)!;
|
||||
working.data = fresh.data;
|
||||
working.indexes = fresh.indexes;
|
||||
}
|
||||
for (const callback of this.deferred.splice(0)) {
|
||||
this.owner.scheduleTransaction(callback, this.mode);
|
||||
}
|
||||
if (!this.accepting) this.commitIfIdle();
|
||||
}
|
||||
|
||||
private blocks(later: FakeTransaction): boolean {
|
||||
return (
|
||||
this.active &&
|
||||
(this.mode === "readwrite" || later.mode === "readwrite") &&
|
||||
this.names.some((name) => later.names.includes(name))
|
||||
);
|
||||
}
|
||||
|
||||
private schedule(callback: () => void): void {
|
||||
if (this.started) {
|
||||
this.owner.scheduleTransaction(callback, this.mode);
|
||||
} else {
|
||||
this.deferred.push(callback);
|
||||
}
|
||||
}
|
||||
|
||||
private deactivateAfterTask(): void {
|
||||
realSetTimeout(() => {
|
||||
this.accepting = false;
|
||||
this.commitIfIdle();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
/** A native transaction with no request left commits once inactive. */
|
||||
private commitIfIdle(): void {
|
||||
if (this.started && this.pending === 0) this.queueCompletion();
|
||||
}
|
||||
|
||||
private assertAccepting(): void {
|
||||
if (!this.active || !this.accepting) {
|
||||
throw new DOMException(
|
||||
"The transaction is not active.",
|
||||
"TransactionInactiveError",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatch(handler: () => void): void {
|
||||
this.accepting = true;
|
||||
handler();
|
||||
this.deactivateAfterTask();
|
||||
}
|
||||
|
||||
private finish(): void {
|
||||
const index = this.database.transactions.indexOf(this);
|
||||
if (index >= 0) this.database.transactions.splice(index, 1);
|
||||
for (const transaction of [...this.database.transactions]) {
|
||||
transaction.startIfUnblocked();
|
||||
}
|
||||
}
|
||||
|
||||
objectStore(name: string): IDBObjectStore {
|
||||
@@ -341,22 +464,23 @@ class FakeTransaction {
|
||||
}
|
||||
|
||||
request<Value>(operation: () => Value): IDBRequest<Value> {
|
||||
this.assertAccepting();
|
||||
const request = createRequest<Value>();
|
||||
this.pending += 1;
|
||||
this.owner.scheduleTransaction(() => {
|
||||
this.schedule(() => {
|
||||
if (!this.active) return;
|
||||
try {
|
||||
request.result = structuredClone(operation());
|
||||
request.onsuccess?.(new Event("success"));
|
||||
this.dispatch(() => request.onsuccess?.(new Event("success")));
|
||||
} catch (error) {
|
||||
request.error = asException(error);
|
||||
request.onerror?.(new Event("error"));
|
||||
this.dispatch(() => request.onerror?.(new Event("error")));
|
||||
this.abortWith(request.error);
|
||||
}
|
||||
if (!this.active) return;
|
||||
this.pending -= 1;
|
||||
this.queueCompletion();
|
||||
}, this.mode);
|
||||
});
|
||||
return request as unknown as IDBRequest<Value>;
|
||||
}
|
||||
|
||||
@@ -368,12 +492,13 @@ class FakeTransaction {
|
||||
}>[],
|
||||
direction: IDBCursorDirection,
|
||||
): IDBRequest<IDBCursorWithValue | null> {
|
||||
this.assertAccepting();
|
||||
const request = createRequest<IDBCursorWithValue | null>();
|
||||
let position = 0;
|
||||
this.pending += 1;
|
||||
|
||||
const emit = () => {
|
||||
this.owner.scheduleTransaction(() => {
|
||||
this.schedule(() => {
|
||||
if (!this.active) return;
|
||||
let continued = false;
|
||||
let eventReturned = false;
|
||||
@@ -445,12 +570,12 @@ class FakeTransaction {
|
||||
},
|
||||
} as unknown as IDBCursorWithValue;
|
||||
}
|
||||
request.onsuccess?.(new Event("success"));
|
||||
this.dispatch(() => request.onsuccess?.(new Event("success")));
|
||||
eventReturned = true;
|
||||
if (continued || !this.active) return;
|
||||
this.pending -= 1;
|
||||
this.queueCompletion();
|
||||
}, this.mode);
|
||||
});
|
||||
};
|
||||
|
||||
emit();
|
||||
@@ -472,7 +597,7 @@ class FakeTransaction {
|
||||
return;
|
||||
}
|
||||
this.completionQueued = true;
|
||||
this.owner.scheduleTransaction(() => {
|
||||
this.schedule(() => {
|
||||
this.completionQueued = false;
|
||||
if (!this.active || this.pending !== 0) return;
|
||||
const commitFailure =
|
||||
@@ -485,18 +610,20 @@ class FakeTransaction {
|
||||
}
|
||||
if (this.mode === "readwrite") {
|
||||
for (const [name, state] of this.workingStores) {
|
||||
this.owner.replaceStore(name, cloneStore(state));
|
||||
this.database.stores.set(name, cloneStore(state));
|
||||
}
|
||||
}
|
||||
this.active = false;
|
||||
this.finish();
|
||||
this.oncomplete?.(new Event("complete"));
|
||||
}, this.mode);
|
||||
});
|
||||
}
|
||||
|
||||
private abortWith(error: DOMException): void {
|
||||
if (!this.active) return;
|
||||
this.active = false;
|
||||
this.error = error;
|
||||
this.finish();
|
||||
this.owner.scheduleLifecycle(() => {
|
||||
this.onerror?.(new Event("error"));
|
||||
this.onabort?.(new Event("abort"));
|
||||
@@ -721,14 +848,36 @@ class FakeIndex {
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal deterministic IndexedDB model for adapter contract tests. It models
|
||||
* request ordering, transaction-level commit/rollback and upgrade blocking;
|
||||
* it is not intended to polyfill IndexedDB for application code.
|
||||
* Minimal deterministic IndexedDB model for adapter contract tests. It is not
|
||||
* intended to polyfill IndexedDB for application code.
|
||||
*
|
||||
* Modeled like a browser:
|
||||
* - request ordering and transaction-level commit/rollback;
|
||||
* - one database per name (`open(name)`), so two names never share rows;
|
||||
* - transactions with overlapping scopes run one after another unless both
|
||||
* are readonly, and a later one sees what the earlier one committed;
|
||||
* - a request placed after the transaction's task ended, outside a request
|
||||
* event and its microtasks, throws `TransactionInactiveError`, and a
|
||||
* transaction with nothing left to do commits on its own;
|
||||
* - upgrade blocking, through `blockNextOpen`/`releaseBlockedOpen`.
|
||||
*
|
||||
* Not modeled (05-08) — use a browser capability spec for these:
|
||||
* - key comparison is by `String`/JSON, and a compound (array) index key path
|
||||
* is not read, so such an index orders by primary key;
|
||||
* - opening a higher version does not fire `versionchange` on open
|
||||
* connections, and `onblocked` fires only for `blockNextOpen`; tests drive
|
||||
* `triggerVersionChange` by hand;
|
||||
* - the upgrade transaction ends synchronously, so an abort requested from an
|
||||
* asynchronous step inside `onupgradeneeded` is not rolled back;
|
||||
* - quota: writes never fail for lack of space unless a test injects it with
|
||||
* `failNextWriteCommit`.
|
||||
*
|
||||
* `seed`, `readRaw` and the lifecycle triggers act on the database opened
|
||||
* most recently.
|
||||
*/
|
||||
export class MemoryIndexedDbFactory {
|
||||
private stores = new Map<string, StoreState>();
|
||||
private databaseVersion = 0;
|
||||
private latestDatabase = new FakeDatabase(this);
|
||||
private readonly databases = new Map<string, DatabaseState>();
|
||||
private current: DatabaseState = this.databaseNamed("");
|
||||
private blockedRequest: Readonly<{
|
||||
request: MutableOpenRequest;
|
||||
targetVersion: number;
|
||||
@@ -741,8 +890,10 @@ export class MemoryIndexedDbFactory {
|
||||
lastTransaction: FakeTransaction | null = null;
|
||||
|
||||
readonly factory: IDBFactory = {
|
||||
open: (_name: string, version?: number) =>
|
||||
this.open(version ?? 1) as unknown as IDBOpenDBRequest,
|
||||
open: (name: string, version?: number) =>
|
||||
this.open(name, version ?? 1) as unknown as IDBOpenDBRequest,
|
||||
deleteDatabase: (name: string) =>
|
||||
this.deleteDatabase(name) as unknown as IDBOpenDBRequest,
|
||||
cmp: compareKeys,
|
||||
} as IDBFactory;
|
||||
|
||||
@@ -782,10 +933,12 @@ export class MemoryIndexedDbFactory {
|
||||
}) as unknown as IDBKeyRange,
|
||||
};
|
||||
|
||||
open(version: number): MutableOpenRequest {
|
||||
const database = new FakeDatabase(this);
|
||||
database.version = this.databaseVersion;
|
||||
this.latestDatabase = database;
|
||||
open(name: string, version: number): MutableOpenRequest {
|
||||
const state = this.databaseNamed(name);
|
||||
const database = new FakeDatabase(this, state);
|
||||
database.version = state.version;
|
||||
state.latest = database;
|
||||
this.current = state;
|
||||
const request: MutableOpenRequest = {
|
||||
...createRequest<IDBDatabase>(),
|
||||
result: database as unknown as IDBDatabase,
|
||||
@@ -802,7 +955,7 @@ export class MemoryIndexedDbFactory {
|
||||
database,
|
||||
};
|
||||
request.onblocked?.({
|
||||
oldVersion: this.databaseVersion,
|
||||
oldVersion: state.version,
|
||||
newVersion: version,
|
||||
} as IDBVersionChangeEvent);
|
||||
return;
|
||||
@@ -812,6 +965,51 @@ export class MemoryIndexedDbFactory {
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Like a browser: open connections get `versionchange` (new version
|
||||
* `null`); if any stays open the request reports `blocked` and completes
|
||||
* once the last one closes. The name then holds an empty version-0
|
||||
* database, so `hasStore` answers false.
|
||||
*/
|
||||
deleteDatabase(name: string): MutableOpenRequest {
|
||||
const request: MutableOpenRequest = {
|
||||
...createRequest<IDBDatabase>(),
|
||||
transaction: null,
|
||||
onblocked: null,
|
||||
onupgradeneeded: null,
|
||||
};
|
||||
queueMicrotask(() => {
|
||||
const state = this.databaseNamed(name);
|
||||
const oldVersion = state.version;
|
||||
const finish = () => {
|
||||
if (state.connections.some((connection) => !connection.closed)) {
|
||||
return;
|
||||
}
|
||||
state.pendingDelete = null;
|
||||
state.stores = new Map();
|
||||
state.version = 0;
|
||||
state.connections = [];
|
||||
request.onsuccess?.({
|
||||
oldVersion,
|
||||
newVersion: null,
|
||||
} as unknown as Event);
|
||||
};
|
||||
for (const connection of state.connections) {
|
||||
if (!connection.closed) connection.fireVersionChange(null);
|
||||
}
|
||||
if (state.connections.some((connection) => !connection.closed)) {
|
||||
state.pendingDelete = finish;
|
||||
request.onblocked?.({
|
||||
oldVersion,
|
||||
newVersion: null,
|
||||
} as IDBVersionChangeEvent);
|
||||
return;
|
||||
}
|
||||
finish();
|
||||
});
|
||||
return request;
|
||||
}
|
||||
|
||||
blockNextOpen(): void {
|
||||
this.shouldBlockNextOpen = true;
|
||||
}
|
||||
@@ -848,25 +1046,25 @@ export class MemoryIndexedDbFactory {
|
||||
}
|
||||
|
||||
triggerVersionChange(newVersion: number): void {
|
||||
this.latestDatabase.fireVersionChange(newVersion);
|
||||
this.current.latest?.fireVersionChange(newVersion);
|
||||
}
|
||||
|
||||
triggerForcedClose(): void {
|
||||
this.latestDatabase.fireForcedClose();
|
||||
this.current.latest?.fireForcedClose();
|
||||
}
|
||||
|
||||
isConnectionClosed(): boolean {
|
||||
return this.latestDatabase.closed;
|
||||
return this.current.latest?.closed ?? true;
|
||||
}
|
||||
|
||||
seed(storeName: string, value: unknown): void {
|
||||
const state = this.store(storeName);
|
||||
const state = storeOf(this.current, storeName);
|
||||
const key = primaryKey(state, value);
|
||||
state.data.set(key, structuredClone(value));
|
||||
}
|
||||
|
||||
readRaw(storeName: string, key: string): unknown {
|
||||
const value = this.store(storeName).data.get(key);
|
||||
const value = storeOf(this.current, storeName).data.get(key);
|
||||
return value === undefined ? undefined : structuredClone(value);
|
||||
}
|
||||
|
||||
@@ -896,39 +1094,36 @@ export class MemoryIndexedDbFactory {
|
||||
}
|
||||
|
||||
storeNames(): Iterable<string> {
|
||||
return this.stores.keys();
|
||||
return this.current.stores.keys();
|
||||
}
|
||||
|
||||
hasStore(name: string): boolean {
|
||||
return this.stores.has(name);
|
||||
return this.current.stores.has(name);
|
||||
}
|
||||
|
||||
store(name: string): StoreState {
|
||||
const state = this.stores.get(name);
|
||||
private databaseNamed(name: string): DatabaseState {
|
||||
let state = this.databases.get(name);
|
||||
if (!state) {
|
||||
throw new DOMException("Store does not exist.", "NotFoundError");
|
||||
state = {
|
||||
stores: new Map(),
|
||||
version: 0,
|
||||
latest: null,
|
||||
connections: [],
|
||||
transactions: [],
|
||||
pendingDelete: null,
|
||||
};
|
||||
this.databases.set(name, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
createStore(name: string, state: StoreState): void {
|
||||
this.stores.set(name, state);
|
||||
}
|
||||
|
||||
replaceStore(name: string, state: StoreState): void {
|
||||
this.stores.set(name, state);
|
||||
}
|
||||
|
||||
deleteStore(name: string): boolean {
|
||||
return this.stores.delete(name);
|
||||
}
|
||||
|
||||
private finishOpen(
|
||||
request: MutableOpenRequest,
|
||||
targetVersion: number,
|
||||
database: FakeDatabase,
|
||||
): void {
|
||||
if (targetVersion < this.databaseVersion) {
|
||||
const state = database.state;
|
||||
if (targetVersion < state.version) {
|
||||
request.error = new DOMException(
|
||||
"Requested version is older.",
|
||||
"VersionError",
|
||||
@@ -936,9 +1131,9 @@ export class MemoryIndexedDbFactory {
|
||||
request.onerror?.(new Event("error"));
|
||||
return;
|
||||
}
|
||||
if (targetVersion > this.databaseVersion) {
|
||||
const before = cloneStores(this.stores);
|
||||
const oldVersion = this.databaseVersion;
|
||||
if (targetVersion > state.version) {
|
||||
const before = cloneStores(state.stores);
|
||||
const oldVersion = state.version;
|
||||
const upgrade = new FakeUpgradeTransaction(database);
|
||||
request.transaction = upgrade as unknown as IDBTransaction;
|
||||
database.version = targetVersion;
|
||||
@@ -948,7 +1143,7 @@ export class MemoryIndexedDbFactory {
|
||||
} as IDBVersionChangeEvent);
|
||||
request.transaction = null;
|
||||
if (upgrade.aborted) {
|
||||
this.stores = before;
|
||||
state.stores = before;
|
||||
database.version = oldVersion;
|
||||
request.error = new DOMException(
|
||||
"Upgrade transaction aborted.",
|
||||
@@ -957,9 +1152,10 @@ export class MemoryIndexedDbFactory {
|
||||
request.onerror?.(new Event("error"));
|
||||
return;
|
||||
}
|
||||
this.databaseVersion = targetVersion;
|
||||
state.version = targetVersion;
|
||||
}
|
||||
database.version = this.databaseVersion;
|
||||
database.version = state.version;
|
||||
state.connections.push(database);
|
||||
request.result = database as unknown as IDBDatabase;
|
||||
request.onsuccess?.(new Event("success"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { createContractHttpExecutor } from "../../src/adapters/http/http-execution-v3.ts";
|
||||
import {
|
||||
createExecutionContext,
|
||||
type ExecutionContext,
|
||||
} from "../../src/platform/execution/execution-context.ts";
|
||||
|
||||
/**
|
||||
* Shared kit for traffic-budget integration tests (Phase 2) and the scale /
|
||||
* chaos scenarios (Phase 4). It drives the real V3 executor with an injected
|
||||
* transport so request counts are physical dispatch counts.
|
||||
*/
|
||||
|
||||
export function scopeSnapshot() {
|
||||
return Object.freeze({
|
||||
generation: 1,
|
||||
fingerprint: "traffic-scope",
|
||||
identities: Object.freeze({}) as never,
|
||||
signal: new AbortController().signal,
|
||||
isCurrent: () => true,
|
||||
});
|
||||
}
|
||||
|
||||
export type ManualClock = Readonly<{
|
||||
now(): number;
|
||||
advance(ms: number): void;
|
||||
}>;
|
||||
|
||||
export function manualClock(start = 0): ManualClock {
|
||||
let current = start;
|
||||
return Object.freeze({
|
||||
now: () => current,
|
||||
advance(ms: number) {
|
||||
current += ms;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** A clock that answers the listed readings in order, then keeps the last. */
|
||||
export function fakeClock(readings: readonly number[]): () => number {
|
||||
let index = 0;
|
||||
return () => {
|
||||
const value = readings[Math.min(index, readings.length - 1)] ?? 0;
|
||||
index += 1;
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
export function testExecutionContext(
|
||||
options: Readonly<{
|
||||
interactionId?: string;
|
||||
deadlineMs?: number;
|
||||
maxPhysicalRequests?: number;
|
||||
maxRetries?: number;
|
||||
maxConcurrentRequests?: number;
|
||||
maxQueuedRequests?: number;
|
||||
clock?: () => number;
|
||||
signal?: AbortSignal;
|
||||
}> = {},
|
||||
): ExecutionContext {
|
||||
return createExecutionContext({
|
||||
interactionId: options.interactionId ?? "interaction-test",
|
||||
deadlineMs: options.deadlineMs ?? 10_000,
|
||||
traffic: {
|
||||
maxPhysicalRequests: options.maxPhysicalRequests ?? 4,
|
||||
maxRetries: options.maxRetries ?? 2,
|
||||
maxConcurrentRequests: options.maxConcurrentRequests ?? 2,
|
||||
maxQueuedRequests: options.maxQueuedRequests ?? 4,
|
||||
},
|
||||
...(options.clock === undefined ? {} : { clock: options.clock }),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
}
|
||||
|
||||
export type Transport = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
export function testExecutor(
|
||||
transport: Transport,
|
||||
options: Readonly<{
|
||||
maxRetryAttempts?: number;
|
||||
monotonicNow?: () => number;
|
||||
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
||||
random?: () => number;
|
||||
credentialHeaders?: Readonly<Record<string, string>>;
|
||||
}> = {},
|
||||
) {
|
||||
const headers = options.credentialHeaders ?? {};
|
||||
return createContractHttpExecutor({
|
||||
baseUrl: "https://api.test",
|
||||
maxRetryAttempts: options.maxRetryAttempts ?? 2,
|
||||
attachCredentials: () => ({ kind: "READY" as const, headers }),
|
||||
fetcher: transport as typeof fetch,
|
||||
// Backoff is not what these tests measure; resolve it immediately unless a
|
||||
// scenario supplies its own sleep.
|
||||
sleep: options.sleep ?? (async () => {}),
|
||||
random: options.random ?? (() => 0.5),
|
||||
...(options.monotonicNow === undefined
|
||||
? {}
|
||||
: { monotonicNow: options.monotonicNow }),
|
||||
});
|
||||
}
|
||||
|
||||
export function networkFailure(): Promise<Response> {
|
||||
return Promise.reject(new TypeError("network"));
|
||||
}
|
||||
|
||||
export function jsonRows(count: number): Response {
|
||||
return Response.json(
|
||||
Array.from({ length: count }, (_, index) => ({
|
||||
id: `entity-${index}`,
|
||||
name: `Entity ${index}`,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A server-side collection of `totalRows` rows behind a bounded page API: each
|
||||
* request returns at most `limit` rows starting at the numeric `cursor`. The
|
||||
* collection's cardinality is independent of how many rows one page carries.
|
||||
*/
|
||||
export function paginatedCollection(totalRows: number): Transport & { calls: number } {
|
||||
const transport = (async (input: RequestInfo | URL) => {
|
||||
transport.calls += 1;
|
||||
const url = new URL(String(input instanceof Request ? input.url : input));
|
||||
const limit = Number(url.searchParams.get("limit") ?? "20");
|
||||
const offset = Number(url.searchParams.get("cursor") ?? "0");
|
||||
const count = Math.max(0, Math.min(limit, totalRows - offset));
|
||||
return Response.json(
|
||||
Array.from({ length: count }, (_, index) => ({
|
||||
id: `entity-${offset + index}`,
|
||||
name: `Entity ${offset + index}`,
|
||||
})),
|
||||
);
|
||||
}) as unknown as Transport & { calls: number };
|
||||
transport.calls = 0;
|
||||
return transport;
|
||||
}
|
||||
Reference in New Issue
Block a user