386 lines
12 KiB
TypeScript
386 lines
12 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
createRuntimeAdapters,
|
|
createRuntimeHttpClient,
|
|
} from "../../src/bootstrap/runtime-adapters.ts";
|
|
import { INVALIDATION_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
|
|
import {
|
|
REFERENCE_FEATURE_ID,
|
|
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
|
} from "../../src/features/reference-feature/contracts/reference-feature-contract.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 { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
|
|
|
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
|
|
type Release = Parameters<typeof createRuntimeAdapters>[0]["release"];
|
|
|
|
const runtime: Runtime = {
|
|
config: {
|
|
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",
|
|
},
|
|
},
|
|
configSchema: "V2",
|
|
build: {
|
|
buildId: "build-a",
|
|
commitSha: "abc123",
|
|
routerBasePath: "/",
|
|
runtimeConfigUrl: "/config.json",
|
|
},
|
|
validationDurationMs: 0,
|
|
};
|
|
const release: Release = {
|
|
schemaVersion: 2,
|
|
appVersion: "0.1.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;
|
|
}
|
|
|
|
describe("runtime adapter composition", () => {
|
|
it("constructs the local demo seam and infrastructure adapters", async () => {
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
});
|
|
|
|
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated");
|
|
await expect(adapters.outputPorts.releaseInfo.getCurrent()).resolves.toMatchObject({
|
|
releaseId: "release-a",
|
|
});
|
|
expect(adapters.infrastructure.queryClient).toBeDefined();
|
|
expect(adapters.infrastructure.queryInvalidation).toBeDefined();
|
|
expect(
|
|
adapters.infrastructure.crossContextInvalidationStatus(),
|
|
).toBe("DEGRADED_LOCAL_ONLY");
|
|
expect(adapters.outputPorts.diagnostics.record).toEqual(expect.any(Function));
|
|
expect(adapters.outputPorts.telemetry.emit).toEqual(expect.any(Function));
|
|
expect(adapters.outputPorts.telemetry.pendingCount()).toBe(0);
|
|
expect(adapters).not.toHaveProperty("http");
|
|
expect(adapters).not.toHaveProperty("storage");
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
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(
|
|
adapters.featureInputs[REFERENCE_FEATURE_ID].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();
|
|
});
|
|
|
|
it("replaces the QueryClient and coordinator for each session generation", async () => {
|
|
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
|
|
const previousClient = adapters.infrastructure.queryClient;
|
|
const previousCoordinator = adapters.infrastructure.queryInvalidation;
|
|
const invalidatePrevious = vi.spyOn(previousClient, "invalidateQueries");
|
|
|
|
await adapters.outputPorts.session.beginSignIn();
|
|
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.queryClient).not.toBe(previousClient),
|
|
);
|
|
expect(adapters.infrastructure.queryInvalidation).not.toBe(
|
|
previousCoordinator,
|
|
);
|
|
|
|
const topic = INVALIDATION_REGISTRY.topics[0];
|
|
if (!topic) throw new Error("expected an installed invalidation topic");
|
|
await previousCoordinator.invalidate([topic]);
|
|
expect(invalidatePrevious).not.toHaveBeenCalled();
|
|
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
it("does not fail boot when Web Storage capability getters throw", async () => {
|
|
const host: Record<string, unknown> = {};
|
|
Object.defineProperties(host, {
|
|
localStorage: {
|
|
get() {
|
|
throw new DOMException("denied", "SecurityError");
|
|
},
|
|
},
|
|
sessionStorage: {
|
|
get() {
|
|
throw new DOMException("denied", "SecurityError");
|
|
},
|
|
},
|
|
});
|
|
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host,
|
|
});
|
|
|
|
expect(adapters.infrastructure.queryClient).toBeDefined();
|
|
expect(adapters.outputPorts.preferences.read("COLOR_SCHEME")).toEqual({
|
|
ok: true,
|
|
value: undefined,
|
|
});
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
it("fails closed when an external auth owner was not installed", async () => {
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime: {
|
|
...runtime,
|
|
config: { ...runtime.config, AUTH_MODE: "external" },
|
|
},
|
|
release,
|
|
host: {},
|
|
});
|
|
expect(adapters.outputPorts.session.getState()).toBe("integration-failed");
|
|
});
|
|
|
|
it("reports the static selection when no capability override disables it", async () => {
|
|
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
|
|
|
|
const snapshot = adapters.outputPorts.runtimeCapabilities.getSnapshot();
|
|
|
|
expect(snapshot.map((status) => status.capabilityId)).toEqual([
|
|
"REALTIME",
|
|
"WEB_WORKER",
|
|
"SERVICE_WORKER",
|
|
"OFFLINE_COMMANDS",
|
|
]);
|
|
expect(snapshot.every((status) => status.override === "DEFAULT")).toBe(true);
|
|
});
|
|
|
|
it("carries a disabling override into the capability snapshot", async () => {
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime: {
|
|
...runtime,
|
|
config: {
|
|
...runtime.config,
|
|
CAPABILITY_OVERRIDES: {
|
|
...runtime.config.CAPABILITY_OVERRIDES,
|
|
SERVICE_WORKER: "DISABLED",
|
|
},
|
|
},
|
|
},
|
|
release,
|
|
host: {},
|
|
});
|
|
|
|
const serviceWorker = adapters.outputPorts.runtimeCapabilities
|
|
.getSnapshot()
|
|
.find((status) => status.capabilityId === "SERVICE_WORKER");
|
|
|
|
expect(serviceWorker?.override).toBe("DISABLED");
|
|
expect(serviceWorker?.active).toBe(0);
|
|
});
|
|
|
|
it("states contract identity as a digest for a V2 release manifest", async () => {
|
|
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
|
|
|
|
const current = await adapters.outputPorts.releaseInfo.getCurrent();
|
|
|
|
expect(current.contractSetDigest).toBe(release.contractSet?.setDigest);
|
|
expect(current.apiContractVersion).toBeUndefined();
|
|
expect(current).not.toHaveProperty("contractSet");
|
|
});
|
|
|
|
it("states contract identity as the legacy scalar for a V1 release manifest", async () => {
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release: {
|
|
...release,
|
|
schemaVersion: 1,
|
|
contractSet: null,
|
|
legacyApiContractVersion: "1.4",
|
|
},
|
|
host: {},
|
|
});
|
|
|
|
const current = await adapters.outputPorts.releaseInfo.getCurrent();
|
|
|
|
expect(current.apiContractVersion).toBe("1.4");
|
|
expect(current.contractSetDigest).toBeUndefined();
|
|
expect(current).not.toHaveProperty("legacyApiContractVersion");
|
|
});
|
|
|
|
it("refetches the active release manifest with no-store semantics", async () => {
|
|
const activeRelease = {
|
|
...release,
|
|
buildId: "build-b",
|
|
releaseId: "release-b",
|
|
routeChunks: { "route-home": "assets/home-b.js" },
|
|
};
|
|
const fetcher = vi.fn(async () =>
|
|
new Response(JSON.stringify(activeRelease), {
|
|
headers: { "content-type": "application/json" },
|
|
}),
|
|
);
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
fetcher,
|
|
host: {},
|
|
});
|
|
|
|
await expect(adapters.outputPorts.releaseInfo.refresh()).resolves.toMatchObject({
|
|
buildId: "build-b",
|
|
releaseId: "release-b",
|
|
});
|
|
expect(fetcher).toHaveBeenCalledWith(
|
|
"/release-manifest.json",
|
|
expect.objectContaining({
|
|
method: "GET",
|
|
cache: "no-store",
|
|
credentials: "same-origin",
|
|
redirect: "error",
|
|
referrerPolicy: "no-referrer",
|
|
headers: { Accept: "application/json" },
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("injects runtime timeout and max-attempt policy into HTTP execution", async () => {
|
|
const scheduled: Array<{ callback: () => void; milliseconds: number }> = [];
|
|
const scheduler = {
|
|
setTimeout: vi.fn((callback: () => void, milliseconds: number) => {
|
|
scheduled.push({ callback, milliseconds });
|
|
return scheduled.length;
|
|
}),
|
|
clearTimeout: vi.fn(),
|
|
};
|
|
const fetcher = vi.fn(async () =>
|
|
Response.json(
|
|
{
|
|
success: false,
|
|
error: { code: "TEMPORARY" },
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
},
|
|
{ status: 503 },
|
|
),
|
|
);
|
|
const authSession =
|
|
(await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
})).outputPorts.session;
|
|
const client = createRuntimeHttpClient(
|
|
{
|
|
runtime,
|
|
authSession,
|
|
fetcher,
|
|
clock: { now: () => 0, sleep: async () => {} },
|
|
scheduler,
|
|
},
|
|
TEST_HTTP_CONTRACT,
|
|
);
|
|
|
|
await client.execute({
|
|
operationId: "LIST_ENTITIES",
|
|
routeId: "TEST_ROUTE",
|
|
});
|
|
|
|
expect(fetcher).toHaveBeenCalledOnce();
|
|
expect(scheduler.setTimeout).toHaveBeenCalledWith(
|
|
expect.any(Function),
|
|
4321,
|
|
);
|
|
expect(scheduler.clearTimeout).toHaveBeenCalledOnce();
|
|
});
|
|
});
|