문제 1103 수정이 더한 플랫폼 규칙 테스트 둘이 참조 샘플에 기댄다. 샘플을 지우면 두 테스트가 사라지거나 비어도 test:all과 제거 드릴이 통과한다. - MAX_RETRY_ATTEMPTS가 실행기에 닿는다: 유일한 테스트가 tests/features/reference-feature/reference-runtime-composition.test.ts 에 있다. createRuntimeAdapters는 설치된 기능의 HTTP로만 실행기에 닿아, 기능이 없으면 시험할 길이 없다. REQUEST_TIMEOUT_MS도 같은 모양이다. - 복구 중인 세션은 보호 라우트에서 기다린다: tests/unit/navigation-policy.test.ts는 설치된 보호 라우트를 돌며 단언하는데, 보호 라우트는 모두 샘플 것이라 샘플을 지우면 반복이 0번이다. 고른 방법과 버린 대안 - src/bootstrap/runtime-adapters.ts: 설정 두 값과 auth profile 표로 실행기를 만드는 부분을 createRuntimeContractHttpExecutor로 뺀다. 조립 루트는 이 함수로만 실행기를 만든다. tests/unit/runtime-adapters .test.ts가 테스트 계약(TEST_LIST, 재시도 예산 2)으로 MAX_RETRY_ATTEMPTS 0·1·2에 1·2·3번 나가는지, REQUEST_TIMEOUT_MS 5가 10초 계약을 5ms에 끊는지 본다. 이 파일은 이미 제거 드릴의 공통 테스트 목록에 있다. - tests/unit/session-route-access.test.ts(새 파일): component 테스트와 같은 방법으로 생성 index를 mock해 tests/helpers/fixture-feature.tsx를 설치하고, 보호 라우트 FIXTURE_ITEMS에서 네 세션 상태의 결정을 본다. decideRouteAccess에 라우트 정의를 받는 순수 함수를 따로 두는 안(리뷰 ⓐ)은 버렸다. fixture 기능을 설치하는 방법이 이미 있어서 운영 코드를 바꾸지 않고 실제 getRoute 경로까지 시험할 수 있다. - scripts/test-sample-removal.ts: 새 파일을 공통 테스트 목록에 넣어, 제거 드릴이 그 파일이 남았는지 본다. - 매뉴얼에 "샘플을 지우면 다시 고정한다"고만 적는 안(ⓒ)은 사람이 기억해야 해서 버렸다. 위험·한계 - 조립 루트가 이 함수 대신 실행기를 직접 만들도록 바뀌면 새 unit 테스트는 그걸 모른다. 템플릿 상태에서는 참조 기능 테스트가 계속 조립 루트 전체를 지킨다. - 샘플을 지운 복사본에 변이를 넣어 돌리지는 않았다. 검증 - desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/runtime-adapters.test.ts tests/unit/session-route-access.test.ts tests/unit/navigation-policy.test.ts tests/features/reference-feature/reference-runtime-composition.test.ts - RED: 부모 커밋의 운영 코드에는 createRuntimeContractHttpExecutor가 없어 runtime-adapters.test.ts의 새 4건이 실패한다. - 변이: 새 함수의 maxRetryAttempts를 상수 2로 바꾸면 "honours MAX_RETRY_ATTEMPTS 0/1"이, navigation-policy.ts의 recovery-pending 분기를 show-sign-in으로 바꾸면 session-route-access.test.ts의 "answers a recovery-pending session …"이 실패해야 한다. Refs: 1105/10-01
318 lines
10 KiB
TypeScript
318 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.
|
|
// This drives it through the whole composition; the same rule without the
|
|
// sample is in tests/unit/runtime-adapters.test.ts (1105/10-01).
|
|
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();
|
|
});
|
|
});
|