Refs: docs/reviews/2026-11-03-maturity-review/README.md 03-01~03-06 0929/03-03 08-05 10-02 10-04 12-06 # Conflicts: # docs/manual/02-decision-tables.md
316 lines
10 KiB
TypeScript
316 lines
10 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import type { DemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
|
|
import { createRuntimeAdapters } from "../../../src/bootstrap/runtime-adapters.ts";
|
|
import { createRuntimeIdentityRegistry } from "../../../src/contracts/query-keys.ts";
|
|
import { bindQuery } from "../../../src/contracts/server-state.ts";
|
|
import type { CacheScopeSnapshot } from "../../../src/contracts/server-state-scope.ts";
|
|
import {
|
|
REFERENCE_FEATURE_ID,
|
|
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
|
} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
|
import { testRuntimeConfig } from "../../helpers/runtime-config.ts";
|
|
|
|
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
|
|
type Release = Parameters<typeof createRuntimeAdapters>[0]["release"];
|
|
|
|
const runtime: Runtime = {
|
|
config: testRuntimeConfig({
|
|
APP_ENV: "local",
|
|
API_BASE_URL: "http://localhost:8080",
|
|
TELEMETRY_ENABLED: false,
|
|
AUTH_MODE: "demo",
|
|
REQUEST_TIMEOUT_MS: 4321,
|
|
MAX_RETRY_ATTEMPTS: 0,
|
|
RELEASE_MANIFEST_URL: "/release-manifest.json",
|
|
CONFIG_SCHEMA_VERSION: "2.0",
|
|
CAPABILITY_OVERRIDES: {
|
|
REALTIME: "DEFAULT",
|
|
WEB_WORKER: "DEFAULT",
|
|
SERVICE_WORKER: "DEFAULT",
|
|
OFFLINE_COMMANDS: "DEFAULT",
|
|
},
|
|
FEATURE_OVERRIDES: {},
|
|
}),
|
|
configSchema: "V2",
|
|
build: {
|
|
buildId: "build-a",
|
|
commitSha: "abc123",
|
|
routerBasePath: "/",
|
|
runtimeConfigUrl: "/config.json",
|
|
},
|
|
validationDurationMs: 0,
|
|
};
|
|
|
|
const release: Release = {
|
|
schemaVersion: 2,
|
|
appVersion: "0.2.0",
|
|
buildId: "build-a",
|
|
commitSha: "abc123",
|
|
configSchemaVersion: "2.0",
|
|
contractSet: {
|
|
setAlgorithm: "CA_CONTRACT_SET_V1",
|
|
setDigest: `sha256:${"0".repeat(64)}`,
|
|
packages: [],
|
|
},
|
|
assetManifestHash: "hash-a",
|
|
releaseId: "release-a",
|
|
builtAt: "2026-07-25T00:00:00Z",
|
|
routeChunks: { "route-home": "assets/home.js" },
|
|
};
|
|
|
|
function referenceBoundQueryKey() {
|
|
const scope: CacheScopeSnapshot = {
|
|
generation: 1,
|
|
fingerprint: "runtime-scope-fingerprint-0001",
|
|
identities: createRuntimeIdentityRegistry({
|
|
tokenFactory: () => "runtime-identity-token-0001",
|
|
}),
|
|
signal: new AbortController().signal,
|
|
isCurrent: () => true,
|
|
};
|
|
return bindQuery(
|
|
{
|
|
definitionId: "reference-resource-runtime-test-v1",
|
|
definitionVersion: 1,
|
|
owner: REFERENCE_FEATURE_ID,
|
|
namespace: "reference-resource",
|
|
namespaceVersion: 1,
|
|
operationId: "GET_REFERENCE_RESOURCE",
|
|
profileId: "DETAIL_STANDARD",
|
|
measureResult: () => ({ itemCount: 1, estimatedBytes: 8 }),
|
|
execute: async () => ({ ok: true as const, value: "reference-1" }),
|
|
},
|
|
"reference-1",
|
|
scope,
|
|
).queryKey;
|
|
}
|
|
|
|
/**
|
|
* The installed feature inputs are partial by design: a feature the product
|
|
* manifest did not select supplies none. This suite is about the reference
|
|
* feature being composed, so it asserts that first and narrows once.
|
|
*/
|
|
async function referenceInput(
|
|
adapters: Awaited<ReturnType<typeof createRuntimeAdapters>>,
|
|
) {
|
|
// 15-01. The input is created when the feature's runtime half loads.
|
|
const load = adapters.featureLoaders[REFERENCE_FEATURE_ID];
|
|
const input = load ? (await load())[REFERENCE_FEATURE_ID] : undefined;
|
|
if (!input) {
|
|
throw new Error(
|
|
`${REFERENCE_FEATURE_ID} is not installed; the manifest did not select it`,
|
|
);
|
|
}
|
|
return input;
|
|
}
|
|
|
|
describe("reference feature runtime composition", () => {
|
|
it("invalidates a real bound query through the installed production graph", async () => {
|
|
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
|
|
const queryKey = referenceBoundQueryKey();
|
|
adapters.infrastructure.queryClient.setQueryData(queryKey, {
|
|
resourceId: "reference-1",
|
|
});
|
|
|
|
await adapters.infrastructure.queryInvalidation.invalidate([
|
|
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
|
]);
|
|
|
|
expect(
|
|
adapters.infrastructure.queryClient.getQueryState(queryKey)?.isInvalidated,
|
|
).toBe(true);
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
it("executes installed feature HTTP through the composed contract registry", async () => {
|
|
const fetcher = vi.fn(async () =>
|
|
Response.json([{ id: "reference-1", name: "Direct contract payload" }]),
|
|
);
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
await adapters.outputPorts.session.beginSignIn();
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).listResources({ limit: 20 }),
|
|
).resolves.toEqual({
|
|
ok: true,
|
|
value: [
|
|
{
|
|
resourceId: "reference-1",
|
|
title: "Direct contract payload",
|
|
createdAt: null,
|
|
},
|
|
],
|
|
});
|
|
expect(fetcher).toHaveBeenCalledWith(
|
|
"http://localhost:8080/api/reference-resources?limit=20",
|
|
expect.objectContaining({
|
|
method: "GET",
|
|
redirect: "error",
|
|
cache: "no-store",
|
|
}),
|
|
);
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
// 1103/10-04 ①. MAX_RETRY_ATTEMPTS is the operator's dial over every
|
|
// contract's retry budget (the list declares 2). Zero must stop retries.
|
|
it.each([
|
|
[0, 1],
|
|
[1, 2],
|
|
])("honours MAX_RETRY_ATTEMPTS %i: a retryable list read goes out %i time(s)", async (maxRetryAttempts, sends) => {
|
|
const fetcher = vi.fn(async (_input: RequestInfo | URL) =>
|
|
Response.json(
|
|
{ type: "about:blank", title: "temporary", status: 503 },
|
|
{ status: 503 },
|
|
),
|
|
);
|
|
// No backoff wait: the jitter is the random draw times a ceiling.
|
|
const random = vi.spyOn(Math, "random").mockReturnValue(0);
|
|
try {
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime: {
|
|
...runtime,
|
|
config: { ...runtime.config, MAX_RETRY_ATTEMPTS: maxRetryAttempts },
|
|
},
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
await adapters.outputPorts.session.beginSignIn();
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).listResources({ limit: 20 }),
|
|
).resolves.toMatchObject({ ok: false, error: { kind: "SERVER_FAILURE" } });
|
|
expect(
|
|
fetcher.mock.calls.filter(([url]) =>
|
|
String(url).includes("/api/reference-resources"),
|
|
),
|
|
).toHaveLength(sends);
|
|
adapters.infrastructure.dispose();
|
|
} finally {
|
|
random.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("keeps private command intent identity out of URLs and diagnostics", async () => {
|
|
const requests: Array<Readonly<{ url: string; headers: Headers }>> = [];
|
|
const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
requests.push({
|
|
url: String(input),
|
|
headers: new Headers(init?.headers),
|
|
});
|
|
return Response.json(
|
|
{ id: "resource-1", name: "Created resource" },
|
|
{ status: 201 },
|
|
);
|
|
});
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
await adapters.outputPorts.session.beginSignIn();
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
const intent = Object.freeze({
|
|
intentId: "private-intent-id",
|
|
operationId: "CREATE_REFERENCE_RESOURCE",
|
|
canonicalInputIdentity: "private-canonical-input",
|
|
idempotencyKey: "private-idempotency-key",
|
|
createdAtMonotonicMs: 42,
|
|
});
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).createResource(
|
|
{ name: "Created resource" },
|
|
{ intent },
|
|
),
|
|
).resolves.toMatchObject({ ok: true });
|
|
|
|
expect(requests).toHaveLength(1);
|
|
expect(requests[0]?.headers.get("Idempotency-Key")).toBe(
|
|
"private-idempotency-key",
|
|
);
|
|
expect(requests[0]?.url).toBe(
|
|
"http://localhost:8080/api/reference-resources",
|
|
);
|
|
const safeEvidence = JSON.stringify({
|
|
requests: requests.map((request) => request.url),
|
|
diagnostics: adapters.outputPorts.diagnostics.entries(),
|
|
});
|
|
expect(safeEvidence).not.toContain("private-intent-id");
|
|
expect(safeEvidence).not.toContain("private-canonical-input");
|
|
expect(safeEvidence).not.toContain("private-idempotency-key");
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
/**
|
|
* R-3.2. A request refused before dispatch because no credential exists is
|
|
* not a session verdict. Reporting it to the owner overwrote a recovering
|
|
* session and could loop through the scope fence; only a server 401 may.
|
|
*/
|
|
it("does not report a request refused before dispatch as a sign-out", async () => {
|
|
const fetcher = vi.fn(async () => Response.json([]));
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
const session = adapters.outputPorts.session as DemoSessionAdapter;
|
|
session.setState("recovery-pending");
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
const notifications = vi.fn();
|
|
session.subscribe(notifications);
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).listResources({ limit: 20 }),
|
|
).resolves.toMatchObject({ ok: false });
|
|
|
|
expect(fetcher).not.toHaveBeenCalled();
|
|
expect(session.getState()).toBe("recovery-pending");
|
|
expect(notifications).not.toHaveBeenCalled();
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
it("still signs out when the server answers 401", async () => {
|
|
const fetcher = vi.fn(
|
|
async () => new Response(null, { status: 401 }),
|
|
);
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
await adapters.outputPorts.session.beginSignIn();
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).listResources({ limit: 20 }),
|
|
).resolves.toMatchObject({ ok: false });
|
|
|
|
expect(fetcher).toHaveBeenCalledOnce();
|
|
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated");
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
});
|