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 at 8210d48.

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 at
8210d48 first 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:
DongHyeonka
2026-11-12 08:28:54 +09:00
parent 585c62431a
commit c80320dfc7
738 changed files with 55027 additions and 13567 deletions
@@ -86,16 +86,14 @@ jobs:
if: \${{ startsWith(gitea.ref, 'refs/tags/v') || (gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'release' || inputs.stage == 'production' || inputs.stage == 'field')) }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
HOSTING_BASE_URL: "\${{ vars.HOSTING_BASE_URL }}"
strategy:
fail-fast: false
matrix:
include:
- { gate: FE-GATE-012, name: bundle, browser: false }
- { gate: FE-GATE-014, name: config-compatibility, browser: false }
- { gate: FE-GATE-019, name: hosting-header, browser: false }
- { gate: FE-GATE-026, name: lab-performance, browser: true }
- { gate: FE-GATE-028, name: manual-accessibility-review, browser: false }
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
@@ -145,6 +143,8 @@ jobs:
corepack pnpm install --frozen-lockfile --ignore-scripts
- name: Build candidate once and verify local evidence
run: corepack pnpm ci:gate -- FE-GATE-015
- name: Admit the candidate to the declared release target
run: corepack pnpm ci:gate -- FE-GATE-027
- name: Archive and validate the exact candidate file set
id: candidate
run: |
@@ -372,15 +372,18 @@ jobs:
production_gate:
name: "\${{ matrix.gate }} / \${{ matrix.name }}"
needs: promotion
needs: [immutable_build, promotion]
if: \${{ gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'production' || inputs.stage == 'field') }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
HOSTING_BASE_URL: "\${{ vars.HOSTING_BASE_URL }}"
CANDIDATE_ARCHIVE_SHA256: "\${{ needs.immutable_build.outputs.archive_sha256 }}"
strategy:
fail-fast: false
matrix:
include:
- { gate: FE-GATE-016, name: rollback-drill }
- { gate: FE-GATE-019, name: hosting-header }
- { gate: FE-GATE-021, name: runbook-boot-config }
- { gate: FE-GATE-022, name: runbook-chunk-mismatch }
- { gate: FE-GATE-023, name: runbook-api-degradation }
@@ -397,6 +400,13 @@ jobs:
run: |
corepack enable
corepack pnpm install --frozen-lockfile --ignore-scripts
- name: Download promoted release
uses: https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7
with:
name: "promoted-release-\${{ gitea.run_id }}-\${{ gitea.run_attempt }}"
path: .release/promoted
- name: Verify and extract the candidate through one inode-bound operation
run: node scripts/verify-ci-candidate-archive.ts --archive ".release/promoted/release-candidate.tar.gz" --extract-to ".release/promoted-release"
- name: Run blocking gate
run: corepack pnpm ci:gate -- \${{ matrix.gate }}
- name: Upload production gate evidence
+30
View File
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import {
combineAbortSignals,
compensateLateHandle,
createAbortableOperation,
} from "../../src/adapters/platform/abortable-operation.ts";
@@ -369,3 +370,32 @@ describe("shared abortable operation mechanics", () => {
await Promise.resolve();
});
});
describe("combineAbortSignals", () => {
it("aborts when either input aborts, and is aborted at once for an aborted input", () => {
for (const which of [0, 1]) {
const inputs = [new AbortController(), new AbortController()];
const combined = combineAbortSignals(inputs[0]!.signal, inputs[1]!.signal);
expect(combined.signal.aborted).toBe(false);
inputs[which]!.abort();
expect(combined.signal.aborted).toBe(true);
}
const aborted = new AbortController();
aborted.abort();
expect(
combineAbortSignals(aborted.signal, new AbortController().signal).signal
.aborted,
).toBe(true);
});
it("release drops the listeners without aborting the combined signal", () => {
const first = new AbortController();
const second = new AbortController();
const combined = combineAbortSignals(first.signal, second.signal);
combined.release();
expect(combined.signal.aborted).toBe(false);
first.abort();
second.abort();
expect(combined.signal.aborted).toBe(false);
});
});
+55
View File
@@ -3,7 +3,9 @@ import { describe, expect, it } from "vitest";
import {
composeApiOperations,
defineRestOperation,
type RestOperationV2,
} from "../../src/contracts/api-operations.ts";
import { API_OPERATIONS } from "../../src/features/installed-feature-contracts.ts";
function operation(operationId = "GET_RESOURCE") {
return defineRestOperation({
@@ -56,3 +58,56 @@ describe("REST operation v2 registry", () => {
).toThrow("Incoherent REST replay contract");
});
});
function command(): RestOperationV2 {
return {
...operation(),
semantics: "COMMAND",
method: "POST",
path: "/resources",
operationId: "CREATE_RESOURCE",
idempotency: "keyed",
replayPolicy: "KEYED_COMMAND",
idempotencyKeyPolicy: "REQUIRED",
requestSource: "body",
pathSchema: "NoRequest",
pathParameterNames: [],
};
}
/**
* R-7.4. CSRF protection is chosen from the HTTP method, so a COMMAND sent
* as GET/HEAD would skip it. browser-rpc and the V3 composition already bind
* commands to unsafe methods; REST V2 must too.
*/
describe("REST operation v2 command method and enum rules", () => {
it.each(["POST", "PUT", "PATCH", "DELETE"])("accepts a COMMAND sent as %s", (method) => {
expect(defineRestOperation({ ...command(), method }).method).toBe(method);
});
it.each(["GET", "HEAD", "OPTIONS", "post"])("rejects a COMMAND sent as %s", (method) => {
expect(() => defineRestOperation({ ...command(), method })).toThrow(TypeError);
expect(() =>
composeApiOperations([{ CREATE_RESOURCE: { ...command(), method } }]),
).toThrow(TypeError);
});
it.each<[string, Record<string, unknown>]>([
["semantics", { semantics: "SUBSCRIBE" }],
["replayPolicy", { replayPolicy: "ALWAYS" }],
])("rejects an unknown %s value", (_field, patch) => {
void _field;
const candidate = { ...command(), ...patch } as unknown as RestOperationV2;
expect(() => defineRestOperation(candidate)).toThrow(TypeError);
});
it("keeps every installed REST v2 operation valid", () => {
for (const installed of Object.values(API_OPERATIONS)) {
if (installed.contractVersion !== 2) continue;
expect(
() => defineRestOperation(installed as RestOperationV2),
installed.operationId,
).not.toThrow();
}
});
});
+68
View File
@@ -0,0 +1,68 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { architectureDependencyReportArtifactSchema } from "../../scripts/contracts/release-artifacts.ts";
// 12-05 (D-11). dependency-cruiser cannot parse TypeScript 7, so it checked
// zero modules and passed while its report claimed a result. The import graph
// in check-architecture.ts is the only checker; the report carries only it.
const staticImportGraph = {
analyzer: "babel-parser-node-resolver",
modules: [],
dependencies: [],
unresolved: [],
parseFailures: [],
cycles: [],
violations: [],
summary: {
modules: 0,
typescriptModules: 0,
dependencies: 0,
localDependencies: 0,
unresolved: 0,
parseFailures: 0,
cycles: 0,
errors: 0,
typeScriptOnlyPolicyPassed: true,
nonTypeScriptExecutableSources: 0,
},
fixtureChecks: { passed: true, checks: [], failures: [] },
typeScriptOnlySourcePolicy: {
checkedRoots: ["src"],
exceptionsAllowed: false,
violations: [],
passed: true,
},
};
describe("architecture dependency report", () => {
it("carries the import graph only", () => {
expect(architectureDependencyReportArtifactSchema.parse({ staticImportGraph })).toEqual({
staticImportGraph,
});
});
it("rejects a dependency-cruiser section", () => {
const cruiserSummary = {
violations: [],
error: 0,
warn: 0,
info: 0,
ignore: 0,
totalCruised: 0,
totalDependenciesCruised: 0,
};
expect(
architectureDependencyReportArtifactSchema.safeParse({
modules: [],
summary: cruiserSummary,
staticImportGraph,
}).success,
).toBe(false);
});
it("does not run dependency-cruiser", async () => {
expect(await readFile("scripts/check-architecture.ts", "utf8")).not.toMatch(/depcruise/u);
});
});
@@ -0,0 +1,35 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { formatArchitectureViolation } from "../../scripts/lib/architecture-violation-message.ts";
// 12-11. A violation used to print only the rule name and the file pair; the
// reason and the way out were in .dependency-cruiser.json.
describe("architecture violation message", () => {
it("names the import and says why and where to go", () => {
expect(
formatArchitectureViolation(
{
rule: "concrete-adapters-compose-only-in-bootstrap",
source: "src/presentation/pages/probe.tsx",
target: "src/adapters/http/index.ts",
},
["../../adapters/http/index.ts"],
"Only src/bootstrap constructs concrete adapters.",
),
).toBe(
"Architecture violation [concrete-adapters-compose-only-in-bootstrap]: " +
"src/presentation/pages/probe.tsx -> src/adapters/http/index.ts " +
'(import "../../adapters/http/index.ts")\n' +
" why: Only src/bootstrap constructs concrete adapters.\n",
);
});
it("gives every rule a reason to print", async () => {
const config = JSON.parse(await readFile(".dependency-cruiser.json", "utf8")) as {
forbidden: { name: string; comment?: string }[];
};
expect(config.forbidden.filter(({ comment }) => !comment?.trim()).map(({ name }) => name)).toEqual([]);
});
});
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { promotionEvidenceTime } from "../../scripts/lib/exact-promotion-bundle.ts";
import { evaluatePromotionEvidence } from "../../scripts/lib/provider-evidence.ts";
import { syntheticSignedPromotionBundle } from "./security-followup-fixture.ts";
// 13-04. Provider evidence lives two hours at most, so a promoted release could
// not be re-verified the next day, which the rollback runbook requires. The
// archived mode checks freshness at the recorded promotion time instead.
const promotedAt = Date.parse("2026-08-02T01:00:00.000Z");
const threeHoursLater = promotedAt + 3 * 60 * 60 * 1_000;
function evidenceAt(freshness: "current" | "archived", now: number) {
const fixture = syntheticSignedPromotionBundle();
const provider = JSON.parse(fixture.files["provider-verification.json"].toString("utf8"));
return evaluatePromotionEvidence({
expected: {
run: provider.run,
source: provider.source,
candidate: provider.candidate,
vulnerabilityInvocationNonce: provider.providerEvidence.vulnerabilityInvocationNonce,
provenanceInvocationNonce: provider.providerEvidence.provenanceInvocationNonce,
secretScanAttestation: provider.providerEvidence.secretScanAttestation,
},
localStatus: "PASS",
vulnerabilityReport: JSON.parse(fixture.files["vulnerability-report.json"].toString("utf8")),
provenanceAttestation: JSON.parse(fixture.files["provenance-attestation.json"].toString("utf8")),
vulnerabilityTrust: fixture.verification.vulnerabilityTrust,
provenanceTrust: fixture.verification.provenanceTrust,
nowEpochMs: () => promotionEvidenceTime(freshness, provider.verifiedAt, now),
});
}
describe("archived promotion re-verification", () => {
it("accepts evidence three hours after promotion in archived mode only", () => {
expect(evidenceAt("archived", threeHoursLater).status).toBe("PASS");
expect(evidenceAt("current", threeHoursLater)).toMatchObject({
status: "FAIL_UNVERIFIED",
failures: expect.arrayContaining(["vulnerability report is expired"]),
});
});
it("refuses a promotion time recorded in the future", () => {
expect(() =>
promotionEvidenceTime("archived", "2026-08-02T05:00:00.000Z", promotedAt),
).toThrow(/verifiedAt is in the future/u);
});
});
+66
View File
@@ -4,12 +4,14 @@ import {
createAnonymousSessionAdapter,
createDemoSessionAdapter,
createExternalAuthSessionAdapter,
type ExternalSessionOwner,
} from "../../src/adapters/auth/external-session-adapter.ts";
describe("external AuthSessionPort adapter", () => {
it("attaches opaque credentials without exposing a token-shaped session", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
@@ -27,6 +29,7 @@ describe("external AuthSessionPort adapter", () => {
});
expect(patch.headers.authorization).toBe("Bearer opaque");
expect(adapter.getState()).toBe("authenticated");
expect(adapter.getSubject()).toBe("user-a");
expect(adapter).not.toHaveProperty("accessToken");
expect(adapter).not.toHaveProperty("refreshToken");
});
@@ -34,6 +37,7 @@ describe("external AuthSessionPort adapter", () => {
it("fails invalid recovery states closed", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
@@ -49,6 +53,7 @@ describe("external AuthSessionPort adapter", () => {
it("rejects credential patches that can alter transport-owned headers", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
@@ -68,8 +73,48 @@ describe("external AuthSessionPort adapter", () => {
).rejects.toThrow("forbidden credential patch");
});
it("rejects credential headers that differ only in case instead of merging them", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({
headers: { Authorization: "Bearer a", authorization: "Bearer b" },
}),
recoverSession: async () => "restored",
notifyUnauthenticated: vi.fn(),
});
await expect(
adapter.credentialPatch({
origin: "https://api.test",
method: "GET",
operationId: "GET_RESOURCE",
}),
).rejects.toThrow("forbidden credential patch");
});
it("requires the owner to name its subject", () => {
// An owner without readSubject would clear server state on every token
// refresh; check:types:test fails if this ever compiles again.
// @ts-expect-error readSubject is a required owner method.
const owner: ExternalSessionOwner = {
readState: () => "authenticated",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "restored",
notifyUnauthenticated: () => {},
};
expect(owner).not.toHaveProperty("readSubject");
});
it("provides a safe anonymous adapter", async () => {
const adapter = createAnonymousSessionAdapter();
expect(adapter.getSubject()).toBeNull();
expect(adapter.getState()).toBe("unauthenticated");
await expect(adapter.recover()).resolves.toBe("no-session");
});
@@ -89,4 +134,25 @@ describe("external AuthSessionPort adapter", () => {
expect(notifications).toBe(2);
unsubscribe();
});
it("does not notify when the demo state is set to its current value", async () => {
const adapter = createDemoSessionAdapter("recovery-pending");
let notifications = 0;
adapter.subscribe(() => {
notifications += 1;
});
adapter.setState("recovery-pending");
expect(notifications).toBe(0);
adapter.setState("authenticated");
await adapter.beginSignIn();
expect(notifications).toBe(1);
adapter.onUnauthenticated();
adapter.onUnauthenticated();
await adapter.signOut();
expect(adapter.getState()).toBe("unauthenticated");
expect(notifications).toBe(2);
});
});
+13
View File
@@ -3,8 +3,11 @@ import { describe, expect, it } from "vitest";
import { mapOperationPayload } from "../../src/adapters/http/resource-mapper.ts";
import {
composeBoundaryMapperRegistry,
mappingFailure,
mappingSuccess,
toContractMappingResult,
} from "../../src/contracts/boundary-mapper.ts";
import { mappingViolation } from "../../src/contracts/external-contract-runtime.ts";
describe("platform DTO mapper boundary", () => {
it("fails closed when no feature mapper was injected", () => {
@@ -31,4 +34,14 @@ describe("platform DTO mapper boundary", () => {
]),
).toThrow("duplicate boundary mapper");
});
it("adapts a boundary result to the canonical mapping result (D-15)", () => {
expect(toContractMappingResult(mappingSuccess(1))).toEqual({
ok: true,
value: 1,
});
expect(
toContractMappingResult(mappingFailure("UNSUPPORTED_WIRE_VALUE")),
).toEqual(mappingViolation("UNSUPPORTED_WIRE_VALUE"));
});
});
+314
View File
@@ -83,6 +83,50 @@ function pngPolicies(
});
}
async function verifiedPngPreview(
leases: ObjectUrlLeaseRegistry,
reportedType = "image/png",
) {
const policies = pngPolicies();
const vault = new BrowserFileVault({ policies });
const captured = vault.captureFiles(
[
new File(
[new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])],
"preview.png",
{ type: reportedType, lastModified: 1 },
),
],
{ ...pngSelectionPolicy, accept: Object.freeze([]) },
);
if (!captured.ok || !captured.value[0]) throw new Error("capture");
const ref = captured.value[0].ref;
const inspected = await vault.inspect({
ref,
policy: pngPolicy,
signal: new AbortController().signal,
});
if (!inspected.ok || !inspected.value.verificationReceipt) {
throw new Error("inspect");
}
const verificationReceipt = inspected.value.verificationReceipt;
const preview = new BrowserTransientPreview({
files: vault,
policies,
leases,
hardMaxPreviewBytes: 10,
});
return {
preview,
request: (signal: AbortSignal) => ({
ref,
verificationReceipt,
policy: pngPolicy,
signal,
}),
};
}
describe("browser file content policy", () => {
it("neutralizes path, bidi, device-name and executable filename tricks", () => {
expect(
@@ -121,6 +165,31 @@ describe("browser file content policy", () => {
).toBe("d.bin");
});
it("truncates a huge filename in linear time with the same result (Q-6.2-10)", () => {
const policy = { safeExtension: ".pdf", maxUtf8Bytes: 180 } as const;
expect(
sanitizeSuggestedFileName(`${"a".repeat(175)} bbbb.pdf`, policy),
).toBe(`${"a".repeat(175)}.pdf`);
expect(
sanitizeSuggestedFileName(`${"가".repeat(100)}.pdf`, policy),
).toBe(`${"가".repeat(58)}.pdf`);
expect(
sanitizeSuggestedFileName(`${"😀".repeat(50)}.pdf`, policy),
).toBe(`${"😀".repeat(44)}.pdf`);
// A server-supplied name used to be re-encoded whole once per dropped
// code point: O(n^2), so a 100k-character name froze the tab.
const encode = vi.spyOn(TextEncoder.prototype, "encode");
try {
expect(
sanitizeSuggestedFileName("x".repeat(5_000), policy),
).toBe(`${"x".repeat(176)}.pdf`);
expect(encode.mock.calls.length).toBeLessThan(10);
} finally {
encode.mockRestore();
}
});
it("keeps native files behind opaque refs and performs bounded reads", async () => {
const policies = pngPolicies();
const vault = new BrowserFileVault({
@@ -545,6 +614,80 @@ describe("browser file content policy", () => {
});
});
it("returns ABORTED without a lease when the caller aborts right after create() (02-01)", async () => {
const revoked: string[] = [];
let urlSequence = 0;
const leases = new ObjectUrlLeaseRegistry({
createObjectURL: () => `blob:aborted-${urlSequence++}`,
revokeObjectURL: (url) => revoked.push(url),
});
const { preview, request } = await verifiedPngPreview(leases);
const controller = new AbortController();
// Same-turn abort: the effect cleanup of a React StrictMode double effect.
const pending = preview.create(request(controller.signal));
controller.abort();
expect(await pending).toMatchObject({
ok: false,
error: { code: "ABORTED", operation: "PREVIEW" },
});
expect(leases.activeLeaseCount).toBe(0);
expect(urlSequence).toBe(0);
expect(revoked).toEqual([]);
});
it("reports a preview that finds every lease slot in use as retryable (02-04)", async () => {
let urlSequence = 0;
const leases = new ObjectUrlLeaseRegistry(
{
createObjectURL: () => `blob:slot-${urlSequence++}`,
revokeObjectURL() {},
},
{
hardMaxActiveLeases: 1,
hardMaxSingleLeaseBytes: 16,
hardMaxAggregateLeaseBytes: 16,
},
);
const { preview, request } = await verifiedPngPreview(leases);
const held = leases.create(new Blob([new Uint8Array(1)]));
expect(
await preview.create(request(new AbortController().signal)),
).toMatchObject({
ok: false,
error: {
code: "LIMIT_EXCEEDED",
retryable: true,
recovery: "RETRY",
},
});
held.release();
expect(
await preview.create(request(new AbortController().signal)),
).toMatchObject({ ok: true });
});
it("types the preview Blob from the signature, not from File.type (02-08)", async () => {
const blobs: Blob[] = [];
const leases = new ObjectUrlLeaseRegistry({
createObjectURL: (blob) => {
blobs.push(blob);
return "blob:typed";
},
revokeObjectURL() {},
});
// An empty File.type still passes the signature check, so only the typed
// slice decides how the browser interprets the object URL.
const { preview, request } = await verifiedPngPreview(leases, "");
expect(
await preview.create(request(new AbortController().signal)),
).toMatchObject({ ok: true, value: { mediaType: "image/png" } });
expect(blobs.map((blob) => blob.type)).toEqual(["image/png"]);
});
it("cannot weaken the built-in active-content preview denylist", async () => {
const htmlPolicy = browserFilePolicyReference(
"active-content",
@@ -657,6 +800,37 @@ describe("browser file content policy", () => {
expect(vault.activeReferenceCount).toBe(0);
});
it("caps retained bytes while reference slots remain (02-08)", () => {
let referenceSequence = 0;
const vault = new BrowserFileVault({
policies: pngPolicies(),
createReference: () => `file:bytes-${referenceSequence++}`,
hardMaxActiveReferences: 8,
hardMaxRetainedBytes: 3,
});
const permissive = {
...pngSelectionPolicy,
accept: Object.freeze([]),
};
expect(
vault.captureFiles(
[new File([new Uint8Array(2)], "one.bin")],
permissive,
),
).toMatchObject({ ok: true });
expect(
vault.captureFiles(
[new File([new Uint8Array(2)], "two.bin")],
permissive,
),
).toMatchObject({
ok: false,
error: { code: "LIMIT_EXCEEDED" },
});
expect(vault.activeReferenceCount).toBe(1);
expect(vault.retainedByteLength).toBe(2);
});
it("caps retained files and aggregate object URL leases", () => {
let referenceSequence = 0;
const vault = new BrowserFileVault({
@@ -755,4 +929,144 @@ describe("browser file content policy", () => {
},
]);
});
it("keeps the shared token, limit and media-type checks (Q-6.2-12 characterization)", () => {
const policies = pngPolicies();
const file = new File([new Uint8Array([1])], "a.png", {
type: "image/png",
lastModified: 1,
});
expect(
new BrowserFileVault({
policies,
createReference: () => "file with space",
}).captureFiles([file], pngSelectionPolicy),
).toMatchObject({ ok: false, error: { code: "UNAVAILABLE" } });
expect(
new BrowserFileVault({
policies,
createReference: () => `file:${"x".repeat(123)}`,
}).captureFiles([file], pngSelectionPolicy),
).toMatchObject({ ok: true });
expect(
() => new BrowserFileVault({ policies, hardMaxRangeBytes: 0 }),
).toThrow(TypeError);
const revoked: string[] = [];
const registry = new ObjectUrlLeaseRegistry({
createObjectURL: () => "",
revokeObjectURL: (url) => revoked.push(url),
});
expect(() => registry.create(new Blob([new Uint8Array([1])]))).toThrow(
"Object URL allocation failed",
);
expect(revoked).toEqual([]);
expect(
() =>
new ObjectUrlLeaseRegistry(URL, {
hardMaxActiveLeases: 1.5,
hardMaxSingleLeaseBytes: 1,
hardMaxAggregateLeaseBytes: 1,
}),
).toThrow(TypeError);
const download = (mediaType: string, maxTransferBytes = 8) =>
new BrowserFilePolicyRegistry({
profiles: [
{
reference: browserFilePolicyReference("files", "download"),
download: {
strategy: "BOUNDED_OBJECT_URL",
mediaType,
safeExtension: ".bin",
maxTransferBytes,
maxBufferedBytes: 8,
integrity: "OPTIONAL",
},
},
],
hardLimits: {
maxInspectionBytes: 64,
maxRetainedFileBytes: 64,
maxPreviewBytes: 64,
maxObjectUrlBytes: 64,
maxTransferBytes: 64,
},
});
expect(() => download("application/octet-stream")).not.toThrow();
expect(() => download("application/*")).toThrow(TypeError);
expect(() => download("application/octet-stream", 0)).toThrow(TypeError);
});
it("ends a pending native read on caller abort and on vault dispose", async () => {
const pendingStream = () => {
const state = { cancelled: 0 };
const file = new File([new Uint8Array([1])], "slow.bin", {
lastModified: 1,
});
Object.defineProperty(file, "stream", {
value: () =>
new ReadableStream<Uint8Array>({
pull: () => new Promise<void>(() => {}),
cancel() {
state.cancelled += 1;
},
}),
});
return { file, state };
};
const open = async (vault: BrowserFileVault, file: File) => {
const captured = vault.captureFiles(
[file],
{ ...pngSelectionPolicy, accept: Object.freeze([]) },
);
if (!captured.ok || !captured.value[0]) throw new Error("capture");
const opened = await vault.openSource({
ref: captured.value[0].ref,
signal: new AbortController().signal,
});
if (!opened.ok) throw new Error("open");
return opened.value;
};
const collect = async (
stream: AsyncIterable<unknown>,
): Promise<unknown[]> => {
const results: unknown[] = [];
for await (const result of stream) results.push(result);
return results;
};
const aborted = pendingStream();
const callerVault = new BrowserFileVault({
policies: pngPolicies(),
createReference: () => "file:caller-abort",
});
const controller = new AbortController();
const callerRead = collect(
(await open(callerVault, aborted.file)).stream(controller.signal),
);
await new Promise((resolve) => setTimeout(resolve, 0));
controller.abort();
expect(await callerRead).toMatchObject([
{ ok: false, error: { code: "ABORTED", operation: "FILE_READ" } },
]);
expect(aborted.state.cancelled).toBe(1);
const disposed = pendingStream();
const disposedVault = new BrowserFileVault({
policies: pngPolicies(),
createReference: () => "file:vault-dispose",
});
const disposedRead = collect(
(await open(disposedVault, disposed.file)).stream(
new AbortController().signal,
),
);
await new Promise((resolve) => setTimeout(resolve, 0));
disposedVault.dispose();
expect(await disposedRead).toMatchObject([
{ ok: false, error: { code: "UNAVAILABLE", operation: "FILE_READ" } },
]);
expect(disposed.state.cancelled).toBe(1);
});
});
+387 -26
View File
@@ -292,34 +292,38 @@ describe("browser download delivery", () => {
});
it("rejects cross-origin or query-bearing browser-managed targets", async () => {
const handoff = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(
() => "https://evil.example/a?token=secret",
),
baseOrigin: "https://app.example",
userActivation: { isActive: true },
});
// 02-08. Each href breaks one rule, so neither check hides the other.
for (const href of [
"https://evil.example/downloads/a",
"/downloads/a?token=secret",
]) {
const handoff = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(() => href),
baseOrigin: "https://app.example",
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
capabilityReceipt,
},
"BROWSER_MANAGED",
expect(
await adapter.deliver(
deliveryInput(
{
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
capabilityReceipt,
},
"BROWSER_MANAGED",
),
),
),
).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
expect(handoff).not.toHaveBeenCalled();
).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
expect(handoff).not.toHaveBeenCalled();
}
});
it("requires an exact, unexpired, server-bound synchronous capability receipt", async () => {
@@ -440,6 +444,38 @@ describe("browser download delivery", () => {
);
});
it("calls an injected window save picker without rebinding its receiver", async () => {
const events: string[] = [];
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
// A Window operation throws "Illegal invocation" unless `this` is the
// Window. Web IDL maps an undefined `this` to the global object.
showSaveFilePicker: function (this: unknown) {
if (this !== undefined && this !== globalThis) {
throw new TypeError("Illegal invocation");
}
return Promise.resolve(writableHandle(events));
},
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([new Uint8Array([1, 2])]),
},
"PROMPT_AND_STREAM",
),
),
).toMatchObject({ ok: true, value: { kind: "SAVED" } });
expect(events).toEqual(["write:2", "close"]);
});
it("snapshots the generated source before awaiting the save picker", async () => {
const events: string[] = [];
let resolvePicker:
@@ -573,6 +609,46 @@ describe("browser download delivery", () => {
expect(events).toEqual(["hash", "write:2", "abort"]);
});
it("records a save-picker dismissal apart from a browser handoff (02-06)", async () => {
const records: unknown[] = [];
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(
(resourceId) => `/downloads/${resourceId}`,
),
showSaveFilePicker: async () => {
throw new DOMException("dismissed", "AbortError");
},
baseOrigin: "https://app.example",
userActivation: { isActive: true },
observer: { record: (observation) => records.push(observation) },
});
await adapter.deliver(
deliveryInput(
{
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
capabilityReceipt,
},
"BROWSER_MANAGED",
),
);
await adapter.deliver(
deliveryInput(
{ kind: "GENERATED", bytes: byteSource([new Uint8Array([1])]) },
"PROMPT_AND_STREAM",
),
);
expect(records).toEqual([
{ operation: "DOWNLOAD", outcome: "SUCCEEDED" },
{ operation: "DOWNLOAD", outcome: "DISMISSED" },
]);
});
it("distinguishes save-picker dismissal from active cancellation", async () => {
const dismissed = createDownloadDeliveryAdapter({
...HARD_LIMITS,
@@ -746,6 +822,70 @@ describe("browser download delivery", () => {
expect(handoff).not.toHaveBeenCalled();
});
it("resolves ABORTED and closes a late lease when a bounded source open is aborted", async () => {
const controller = new AbortController();
let releaseOpen: ((value: unknown) => void) | undefined;
const close = vi.fn();
const handoff = vi.fn();
const record = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(),
userActivation: { isActive: true },
observer: { record },
// Ignores the signal and resolves only when the test says so.
openAuthorizedSource: () =>
new Promise((resolve) => {
releaseOpen = resolve;
}) as never,
});
const capability = Object.freeze({
capabilityReceipt: "capability-bounded-1",
method: "GET" as const,
binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" },
mediaType: "application/pdf",
byteLength: 3,
maxBytes: 3,
expectedSha256: "a".repeat(64),
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
});
const delivering = adapter.deliver(
deliveryInput(
{
kind: "AUTHORIZED_STREAM_RESOURCE",
resourceId: "resource-1",
capability: capability as never,
},
"BOUNDED_OBJECT_URL",
controller.signal,
),
);
await new Promise((resolve) => setTimeout(resolve, 0));
controller.abort();
await expect(delivering).resolves.toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
expect(record).toHaveBeenCalled();
releaseOpen?.({
ok: true,
value: {
byteLength: 3,
integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION",
capability,
close,
async *stream() {},
},
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(close).toHaveBeenCalledOnce();
expect(handoff).not.toHaveBeenCalled();
});
it("rejects caller limits above runtime hard caps before side effects", async () => {
const handoff = vi.fn();
const showSaveFilePicker = vi.fn(async () => writableHandle([]));
@@ -943,4 +1083,225 @@ describe("browser download delivery", () => {
},
});
});
it("closes a lease that resolves in the same turn as the abort (Q-6.2-7)", async () => {
const controller = new AbortController();
let releaseOpen: ((value: unknown) => void) | undefined;
const close = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
userActivation: { isActive: true },
openAuthorizedSource: () =>
new Promise((resolve) => {
releaseOpen = resolve;
}) as never,
});
const capability = Object.freeze({
capabilityReceipt: "capability-gap-1",
method: "GET" as const,
binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" },
mediaType: "application/pdf",
byteLength: 3,
maxBytes: 3,
expectedSha256: "a".repeat(64),
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
});
const delivering = adapter.deliver(
deliveryInput(
{
kind: "AUTHORIZED_STREAM_RESOURCE",
resourceId: "resource-1",
capability: capability as never,
},
"BOUNDED_OBJECT_URL",
controller.signal,
),
);
await new Promise((resolve) => setTimeout(resolve, 0));
// The lease lands after the abort but before the delivery's own cleanup.
controller.abort();
releaseOpen?.({
ok: true,
value: {
byteLength: 3,
integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION",
capability,
close,
async *stream() {},
},
});
await expect(delivering).resolves.toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(close).toHaveBeenCalledOnce();
});
it("aborts a writable that arrives after the delivery was aborted (Q-6.2-7)", async () => {
const controller = new AbortController();
const events: string[] = [];
let createWritableCalled: (() => void) | undefined;
const writableRequested = new Promise<void>((resolve) => {
createWritableCalled = resolve;
});
let releaseWritable:
| ((writable: WritableStream<Uint8Array>) => void)
| undefined;
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: async () => ({
createWritable() {
createWritableCalled?.();
return new Promise<WritableStream<Uint8Array>>((resolve) => {
releaseWritable = resolve;
});
},
}),
userActivation: { isActive: true },
});
const delivering = adapter.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([new Uint8Array([1])]),
},
"PROMPT_AND_STREAM",
controller.signal,
),
);
await writableRequested;
controller.abort();
await expect(delivering).resolves.toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
// Chrome keeps a `.crswap` file for an open writable until it is aborted.
releaseWritable?.(
new WritableStream<Uint8Array>({
abort() {
events.push("abort");
},
}),
);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(events).toEqual(["abort"]);
});
it("keeps input validation failure codes (Q-6.2-11 characterization)", async () => {
const adapter = (
overrides: Partial<Parameters<typeof createDownloadDeliveryAdapter>[0]> = {},
) =>
createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(
(resourceId) => `/downloads/${resourceId}`,
),
baseOrigin: "https://app.example",
showSaveFilePicker: async () => writableHandle([]),
userActivation: { isActive: true },
...overrides,
});
const code = async (
source: DownloadSource,
strategy: DownloadStrategy,
overrides: Partial<Parameters<typeof createDownloadDeliveryAdapter>[0]> = {},
): Promise<string> => {
const result = await adapter(overrides).deliver(
deliveryInput(source, strategy),
);
return result.ok ? result.value.kind : result.error.code;
};
const generated = (
bytes: FileByteSource = byteSource([new Uint8Array([1])]),
expectedSha256?: string,
): DownloadSource => ({
kind: "GENERATED",
bytes,
...(expectedSha256 === undefined ? {} : { expectedSha256 }),
});
const managed = (resourceId: string): DownloadSource => ({
kind: "BROWSER_MANAGED_RESOURCE",
resourceId,
capabilityReceipt,
});
expect(await code(generated(), "BOUNDED_OBJECT_URL")).toBe(
"BROWSER_HANDOFF",
);
expect(
await code({ kind: "UNKNOWN" } as never, "BOUNDED_OBJECT_URL"),
).toBe("INVALID_INPUT");
expect(
await code(
generated({ byteLength: 1, stream: "no" } as never),
"BOUNDED_OBJECT_URL",
),
).toBe("INVALID_INPUT");
expect(
await code(
generated(byteSource([new Uint8Array([1])], -1)),
"BOUNDED_OBJECT_URL",
),
).toBe("INTEGRITY_FAILED");
expect(
await code(generated(undefined, "not-a-digest"), "BOUNDED_OBJECT_URL"),
).toBe("INVALID_INPUT");
expect(await code(generated(), "BROWSER_MANAGED")).toBe(
"POLICY_REJECTED",
);
expect(await code(managed("artifact-1"), "BOUNDED_OBJECT_URL")).toBe(
"POLICY_REJECTED",
);
expect(await code(managed(""), "BROWSER_MANAGED")).toBe("INVALID_INPUT");
expect(await code(managed("has space"), "BROWSER_MANAGED")).toBe(
"INVALID_INPUT",
);
expect(
await code(generated(), "BOUNDED_OBJECT_URL", {
userActivation: { isActive: false },
}),
).toBe("PERMISSION_DENIED");
expect(
await code(generated(), "BOUNDED_OBJECT_URL", {
filenameMaxUtf8Bytes: 2,
}),
).toBe("INVALID_INPUT");
expect(
await code(generated(), "BOUNDED_OBJECT_URL", {
createTransferId: () => "transfer with space",
}),
).toBe("UNAVAILABLE");
expect(
await code(managed("artifact-1"), "BROWSER_MANAGED", {
browserManagedCapabilities: capabilityResolver(
() => "https://user:secret@app.example/downloads/artifact-1",
),
}),
).toBe("POLICY_REJECTED");
expect(
await code(managed("artifact-1"), "BROWSER_MANAGED", {
browserManagedCapabilities: capabilityResolver(undefined, {
expiresAtEpochMs: 1,
}),
}),
).toBe("EXPIRED_RESOURCE");
expect(
await code(managed("artifact-1"), "BROWSER_MANAGED", {
browserManagedCapabilities: capabilityResolver(undefined, {
mediaType: "text/html",
}),
}),
).toBe("POLICY_REJECTED");
});
});
+134
View File
@@ -98,6 +98,28 @@ describe("browser file pickers", () => {
expect(baselineShowPicker).not.toHaveBeenCalled();
});
it("refuses to open the native input without user activation (02-08)", async () => {
const input = labelledFileInput();
const click = vi.fn(() => {
queueMicrotask(() => input.dispatchEvent(new Event("cancel")));
});
Object.defineProperty(input, "click", {
configurable: true,
value: click,
});
const picker = new NativeInputFilePicker({
input,
...createHarness(),
userActivation: { isActive: false },
});
expect(await picker.select({ policy })).toMatchObject({
ok: false,
error: { code: "PERMISSION_DENIED", operation: "FILE_SELECT" },
});
expect(click).not.toHaveBeenCalled();
});
it("resets the native input and supports same-file reselection", async () => {
const input = labelledFileInput();
const selected = new File(["hello"], "notes.txt", {
@@ -263,6 +285,60 @@ describe("browser file pickers", () => {
expect(vault.activeReferenceCount).toBe(1);
});
it("stops the focus fallback once a native cancel event was observed (Q-6.2-8)", async () => {
const input = labelledFileInput();
const selected = new File(["slow"], "slow.txt", {
type: "text/plain",
lastModified: 1,
});
let onClick = (): void => {
queueMicrotask(() => input.dispatchEvent(new Event("cancel")));
};
Object.defineProperty(input, "click", {
configurable: true,
value: vi.fn(() => onClick()),
});
const scheduled: Array<() => void> = [];
const { policies, vault } = createHarness(policyDefinition, {
createReference: () => "file:slow",
});
const picker = new NativeInputFilePicker({
input,
vault,
policies,
userActivation: { isActive: true },
scheduler: {
setTimeout(callback) {
scheduled.push(callback);
return scheduled.length;
},
clearTimeout() {},
},
});
// This engine supports the native cancel event.
expect(await picker.select({ policy })).toEqual({
ok: true,
value: { kind: "DISMISSED" },
});
// A cloud provider returns focus first and dispatches change only after
// the file has been fetched, well past the focus grace.
onClick = () => window.dispatchEvent(new Event("focus"));
const pending = picker.select({ policy });
for (const callback of scheduled.splice(0)) callback();
Object.defineProperty(input, "files", {
configurable: true,
value: [selected],
});
input.dispatchEvent(new Event("change"));
expect(await pending).toMatchObject({
ok: true,
value: { kind: "SELECTED", files: [{ displayName: "slow.txt" }] },
});
});
it("lets the native cancel event settle before the focus fallback", async () => {
const input = labelledFileInput();
let fallback: (() => void) | undefined;
@@ -416,6 +492,64 @@ describe("browser file pickers", () => {
});
});
it("settles a pending enhanced picker when the runtime is disposed", async () => {
// R3-2 characterization: dispose ends the wait even though the native
// picker never settles, and a late native result changes nothing.
let resolvePicker: ((handles: never[]) => void) | undefined;
const harness = createHarness();
const picker = new EnhancedFilePicker({
showOpenFilePicker: () =>
new Promise<never[]>((resolve) => {
resolvePicker = resolve;
}),
...harness,
userActivation: { isActive: true },
});
const pending = picker.select({
policy,
signal: new AbortController().signal,
});
await new Promise((resolve) => setTimeout(resolve, 0));
picker.dispose();
resolvePicker?.([]);
expect(await pending).toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
});
it("calls an injected window picker without rebinding its receiver", async () => {
const harness = createHarness();
const picker = new EnhancedFilePicker({
// A Window operation throws "Illegal invocation" unless `this` is the
// Window. Web IDL maps an undefined `this` to the global object.
showOpenFilePicker: function (this: unknown) {
if (this !== undefined && this !== globalThis) {
throw new TypeError("Illegal invocation");
}
return Promise.resolve([
{
kind: "file" as const,
name: "safe.txt",
async getFile() {
return new File(["safe"], "safe.txt", {
type: "text/plain",
lastModified: 1,
});
},
},
]);
},
...harness,
userActivation: { isActive: true },
});
expect(await picker.select({ policy })).toMatchObject({
ok: true,
value: { kind: "SELECTED" },
});
});
it("rejects excessive enhanced selections before reading handles", async () => {
const getFile = vi.fn(async () => new File(["a"], "a.txt"));
const multiplePolicy = {
+66
View File
@@ -176,6 +176,72 @@ describe("browser file runtime hard limits and disposal", () => {
expect(revoked).toEqual(["blob:runtime-download"]);
});
it("reports exhausted object URL leases as retryable until the grace ends (02-04)", async () => {
const scheduled: Array<() => void> = [];
let urlSequence = 0;
const runtime = createBrowserFileRuntime({
input: fileInput(),
policies,
limits: {
hardMaxPreviewBytes: 8,
hardMaxObjectUrlBytes: 8,
hardMaxTransferBytes: 16,
hardMaxActiveObjectUrls: 2,
},
objectUrlApi: {
createObjectURL: () => `blob:runtime-download-${urlSequence++}`,
revokeObjectURL() {},
},
download: {
host: { handoff: vi.fn() },
browserManagedCapabilities:
unusedBrowserManagedCapabilities,
scheduler: {
setTimeout(callback) {
scheduled.push(callback);
return scheduled.length;
},
},
},
});
const deliver = () =>
runtime.downloads.deliver({
policy: downloadPolicy,
source: {
kind: "GENERATED",
bytes: {
byteLength: 3,
async *stream() {
yield { ok: true, value: new Uint8Array([1, 2, 3]) };
},
},
},
suggestedFileName: "artifact",
signal: new AbortController().signal,
onProgress() {},
});
// Each handoff keeps its lease for the revoke grace, so the third
// download inside that window finds every slot in use.
expect(await deliver()).toMatchObject({ ok: true });
expect(await deliver()).toMatchObject({ ok: true });
expect(await deliver()).toMatchObject({
ok: false,
error: {
code: "LIMIT_EXCEEDED",
retryable: true,
recovery: "RETRY",
},
});
for (const release of scheduled.splice(0)) release();
expect(await deliver()).toMatchObject({
ok: true,
value: { kind: "BROWSER_HANDOFF" },
});
runtime.dispose();
});
it("aborts a pending native picker and prevents event resurrection", async () => {
const input = fileInput();
Object.defineProperty(input, "click", {
@@ -795,3 +795,229 @@ describe("RPC-03 registries are snapshotted before they are validated", () => {
});
}
});
/**
* Q-6.3-9. A command the transport already received may have been applied, a
* retry must not outlive the scope generation that started it, and a stream the
* consumer aborted without calling `return()` must not hold the operation in
* DRAINING forever.
*/
describe("Q-6.3-9 command effect, retry scope and abandoned streams", () => {
const COMMAND_KEY = "command-key-0001";
const commandOperation = (
overrides: Parameters<typeof unaryOperation>[0] = {},
) =>
unaryOperation({
semantics: "COMMAND",
replayPolicy: "KEYED_COMMAND",
idempotencyKeyPolicy: "REQUIRED",
idempotencyLevel: "IDEMPOTENT",
serverStateProfileId: null,
...overrides,
});
function commandRuntime(
invokeUnary: BrowserRpcTransport["invokeUnary"],
extra: Readonly<{
operation?: ReturnType<typeof unaryOperation>;
profile?: ReturnType<typeof unaryProfile>;
generationFence?: Readonly<{
capture(): unknown;
isCurrent(token: unknown): boolean;
}>;
}> = {},
) {
return createBrowserRpcRuntime({
operations: { GET_RPC_RESOURCE: extra.operation ?? commandOperation() },
profiles: { CONNECT_REFERENCE_UNARY: extra.profile ?? unaryProfile() },
schemaCodecs: SCHEMA_CODECS,
mappers: MAPPERS,
requestEncoders: { RpcResourceRequestEncoder: UNARY_ENCODER },
transports: { CONNECT_REFERENCE_UNARY: unaryTransport(invokeUnary) },
...(extra.generationFence === undefined
? {}
: { generationFence: extra.generationFence }),
}).bindUnary("GET_RPC_RESOURCE", isResourceView);
}
const afterSend: ReadonlyArray<
Readonly<{
label: string;
invokeUnary: BrowserRpcTransport["invokeUnary"];
operation?: ReturnType<typeof unaryOperation>;
}>
> = [
{
label: "answers UNAVAILABLE",
invokeUnary: async () => ({
ok: false,
failure: { code: "UNAVAILABLE" },
}),
},
{
label: "throws",
invokeUnary: async () => {
throw new TypeError("connection reset");
},
},
{
label: "never answers",
invokeUnary: () => new Promise<never>(() => {}),
operation: commandOperation({ totalDeadlineMs: 25 }),
},
];
for (const { label, invokeUnary, operation } of afterSend) {
it(`reports MAYBE_APPLIED when a sent command's transport ${label}`, async () => {
const port = commandRuntime(invokeUnary, {
...(operation === undefined ? {} : { operation }),
});
await expect(
port.execute({ resourceId: "r-1" }, { idempotencyKey: COMMAND_KEY }),
).resolves.toMatchObject({
ok: false,
error: {
effect: "MAYBE_APPLIED",
retryable: false,
action: "contact-support",
},
});
});
}
it("keeps a command rejected before send and a failed query effect-free", async () => {
const unsent = await commandRuntime(async () => {
throw new Error("must not be called");
}).execute({ resourceId: "r-1" });
expect(unsent).toMatchObject({
ok: false,
error: { kind: "VALIDATION_REJECTED" },
});
expect(unsent.ok ? null : unsent.error).not.toHaveProperty("effect");
const query = await unaryRuntime(
unaryTransport(async () => ({
ok: false,
failure: { code: "UNAVAILABLE" },
})),
)
.bindUnary("GET_RPC_RESOURCE", isResourceView)
.execute({ resourceId: "r-1" });
expect(query).toMatchObject({
ok: false,
error: { kind: "SERVER_FAILURE", retryable: true },
});
expect(query.ok ? null : query.error).not.toHaveProperty("effect");
});
it("does not retry a command after its scope generation changed", async () => {
let calls = 0;
let generation = 1;
const port = commandRuntime(
async () => {
calls += 1;
// The session changes while the first attempt is in flight.
generation = 2;
return { ok: false, failure: { code: "UNAVAILABLE" } };
},
{
profile: unaryProfile({
retryProfileId: "RPC_RETRY_TWO",
retryOwner: "FRONTEND_ADAPTER",
maxAttempts: 2,
backoffMs: [0],
retryableFailures: ["UNAVAILABLE"],
maxRetryAfterMs: 100,
}),
operation: commandOperation({ retryProfileId: "RPC_RETRY_TWO" }),
generationFence: {
capture: () => generation,
isCurrent: (token) => token === generation,
},
},
);
const result = await port.execute(
{ resourceId: "r-1" },
{ idempotencyKey: COMMAND_KEY },
);
expect(calls).toBe(1);
expect(result).toMatchObject({
ok: false,
error: {
kind: "SCOPE_GENERATION_CHANGED",
effect: "MAYBE_APPLIED",
},
});
});
it("releases a stream the consumer aborted without calling return()", async () => {
const cancels: string[] = [];
let opened = 0;
const transport = defineBrowserRpcTransport({
runtimeProfileId: "CONNECT_REFERENCE_STREAM",
providerId: "REFERENCE_RPC",
protocol: "CONNECT_HTTP",
rpcKind: "SERVER_STREAM",
openServerStream: () => {
opened += 1;
let closed: () => void = () => {};
const closure = new Promise<void>((resolve) => {
closed = resolve;
});
let sent = false;
return {
streamId: `physical-${opened}`,
frames: {
[Symbol.asyncIterator]: () =>
({
next: () => {
if (sent) return new Promise<never>(() => {});
sent = true;
return Promise.resolve({
done: false,
value: {
kind: "MESSAGE",
message: { id: "r-1", name: "Resource" },
encodedBytes: 16,
},
});
},
}) as AsyncIterator<BrowserRpcStreamFrame>,
},
cancel(reason: string) {
cancels.push(reason);
closed();
},
waitClosed: () => closure,
};
},
});
const stream = streamingRuntime(transport).bindServerStream(
"WATCH_RPC_RESOURCES",
isResourceView,
);
const consumer = new AbortController();
const opening = stream.open(
{ resourceId: "r-1" },
{ signal: consumer.signal },
);
const first = opening[Symbol.asyncIterator]();
await expect(first.next()).resolves.toMatchObject({
value: { ok: true },
});
// The consumer walks away: it aborts but never calls next() or return().
consumer.abort();
await new Promise((resolve) => setTimeout(resolve, 5));
expect(cancels).toHaveLength(1);
const second = stream.open({ resourceId: "r-1" })[Symbol.asyncIterator]();
await expect(second.next()).resolves.toMatchObject({
value: { ok: true },
});
expect(opened).toBe(2);
});
});
@@ -21,7 +21,6 @@ import {
streamProfile,
unaryOperation,
unaryProfile,
type ResourceView,
} from "./fixture.ts";
describe("Browser RPC provider-neutral runtime", () => {
@@ -0,0 +1,89 @@
import { spawnSync } from "node:child_process";
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { filesBelow } from "../../scripts/lib/removal-fixture.ts";
/**
* 13-06. Which VITE_* values reach the bundle. The declared values the app
* reads must still be there (build id, commit, runtime config URL, base path);
* a declared value nothing reads and an undeclared one must not be, and the
* design-system chunk must not change with the build id.
*/
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
function inheritedEnvironment(): NodeJS.ProcessEnv {
return Object.fromEntries(
Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")),
);
}
async function build(variables: Readonly<Record<string, string>>) {
const outDir = await mkdtemp(path.join(tmpdir(), "build-environment-"));
roots.push(outDir);
const run = spawnSync(
path.resolve("node_modules/.bin/vite"),
["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"],
{ encoding: "utf8", env: { ...inheritedEnvironment(), ...variables } },
);
const contents = run.status === 0
? await Promise.all(
(await filesBelow(outDir))
.filter((file) => /\.(?:js|html)$/u.test(file))
.map(async (file) => ({ file, text: await readFile(file, "utf8") })),
)
: [];
return { run, outDir, contents };
}
const DECLARED = Object.freeze({
VITE_COMMIT_SHA: "commit-probe-13",
VITE_ROUTER_BASE_PATH: "/base-probe/",
VITE_RUNTIME_CONFIG_URL: "/base-probe/runtime-probe.json",
// Declared, but applied by the index generator; the bundle never reads it.
VITE_PRODUCT_FEATURES: "unreferenced-probe-13",
});
describe("build variables in the bundle (13-06)", () => {
it("keeps the values the app reads and nothing else", async () => {
const first = await build({ ...DECLARED, VITE_BUILD_ID: "build-probe-1" });
expect(first.run.stderr).toBe("");
expect(first.run.status).toBe(0);
const bundled = (value: string) =>
first.contents.some(({ text }) => text.includes(value));
expect(bundled("build-probe-1")).toBe(true);
expect(bundled("commit-probe-13")).toBe(true);
expect(bundled("/base-probe/runtime-probe.json")).toBe(true);
const html = first.contents.find(({ file }) => file.endsWith("index.html"));
expect(html?.text).toContain('src="/base-probe/assets/');
expect(bundled("unreferenced-probe-13")).toBe(false);
const second = await build({ ...DECLARED, VITE_BUILD_ID: "build-probe-2" });
expect(second.run.status).toBe(0);
// The shared application chunk, which Vite names after one of its modules:
// `design-system-*` upstream. This product's route chunk split
// (vite.config.ts) leaves `render-boot-failure-*` as that chunk here.
const designSystem = async (outDir: string) =>
(await readdir(path.join(outDir, "assets"))).filter((name) =>
name.startsWith("render-boot-failure-"),
);
const firstChunks = await designSystem(first.outDir);
expect(firstChunks).toHaveLength(1);
expect(await designSystem(second.outDir)).toEqual(firstChunks);
}, 120_000);
it("refuses a VITE_* variable the build does not declare", async () => {
const refused = await build({ VITE_PAYMENT_KEY: "sk_live_probe" });
expect(refused.run.status).not.toBe(0);
expect(refused.run.stderr + refused.run.stdout).toMatch(
/Undeclared VITE_\* build variables: VITE_PAYMENT_KEY/u,
);
}, 120_000);
});
+25
View File
@@ -26,6 +26,31 @@ describe("Vite bundle classification", () => {
});
});
it("counts the entry's own dynamic imports as initial (09-03)", () => {
// main.tsx does nothing but import the application graph dynamically, so
// that graph is loaded on every visit; the routes it lazy-loads are not.
expect(
classifyViteJavascript({
"index.html": {
file: "assets/entry.js",
isEntry: true,
dynamicImports: ["src/boot.tsx"],
},
"src/boot.tsx": {
file: "assets/boot.js",
imports: ["_shared.js"],
dynamicImports: ["src/lazy.js"],
},
"_shared.js": { file: "assets/shared.js" },
"src/lazy.js": { file: "assets/lazy.js" },
}),
).toEqual({
initialFiles: ["assets/boot.js", "assets/entry.js", "assets/shared.js"],
lazyFiles: ["assets/lazy.js"],
missingImports: [],
});
});
it("reports a manifest import that cannot be resolved", () => {
expect(
classifyViteJavascript({
+56
View File
@@ -37,6 +37,62 @@ describe("controlled chunk recovery", () => {
});
});
const storageError = {
kind: "STORAGE_UNAVAILABLE" as const,
code: "STORAGE_UNAVAILABLE",
retryable: false,
operationId: "STORAGE",
attemptCount: 1,
userMessageKey: "error.storage_unavailable",
action: "none" as const,
};
const mismatch = {
failureKind: "CHUNK_LOAD_FAILURE",
manifestLoaded: true,
currentBuildId: "build-a",
currentReleaseId: "release-a",
activeBuildId: "build-b",
activeReleaseId: "release-b",
} as const;
it("fails closed when the guard cannot be read", () => {
const storage: StoragePort = {
...memoryStorage(),
read: () => ({ ok: false, error: storageError }),
};
expect(decideChunkRecovery({ ...mismatch, storage })).toEqual({
action: "support",
reason: "guard-read-failed",
});
});
it("fails closed when the guard cannot be written", () => {
const storage: StoragePort = {
...memoryStorage(),
write: () => ({ ok: false, error: storageError }),
};
expect(decideChunkRecovery({ ...mismatch, storage })).toEqual({
action: "support",
reason: "guard-write-failed",
});
});
it("allows no second reload when replicas alternate the release pair (Q-6.9-9)", () => {
const storage = memoryStorage();
expect(decideChunkRecovery({ ...mismatch, storage }).action).toBe("reload-once");
// After the reload the page is on build-b while a replica still serves A.
expect(
decideChunkRecovery({
...mismatch,
currentBuildId: "build-b",
currentReleaseId: "release-b",
activeBuildId: "build-a",
activeReleaseId: "release-a",
storage,
}),
).toEqual({ action: "support", reason: "reload-already-attempted" });
});
it.each([
[{ failureKind: "SERVER_FAILURE" }, "not-recoverable"],
[{ manifestLoaded: false }, "manifest-unavailable"],
+179 -26
View File
@@ -20,6 +20,7 @@ import {
createCiWorkflowGenerator,
generateCiWorkflow,
renderCiWorkflow,
workflowGateExecutionFailures,
type CiWorkflowFileSystem,
} from "../../scripts/generate-ci-workflow.ts";
import {
@@ -135,6 +136,10 @@ async function createUnsafeCiGateFixture(
Object.assign(packageDocument.scripts, additionalScripts);
await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`);
await writeFile(path.join(root, "package.json"), `${JSON.stringify(packageDocument)}\n`);
await writeFile(
path.join(root, "config/ci/contract-baseline.json"),
await readFile("config/ci/contract-baseline.json"),
);
return root;
}
@@ -184,29 +189,21 @@ describe("CI gate contract", () => {
const index = indexCiGateContract(contract);
expect(contract.schemaVersion).toBe(2);
expect(contract.gates.map(({ id }) => id)).toEqual(
Array.from({ length: 27 }, (_, index) =>
Array.from({ length: 28 }, (_, index) =>
`FE-GATE-${String(index + 1).padStart(3, "0")}`,
),
).filter((gateId) => gateId !== "FE-GATE-016"),
);
expect(contract.jobs).toHaveLength(9);
// Final fix wave item 1: FE-GATE-010 gained `check-tech-log-contract`.
// Alignment follow-up item 2: FE-GATE-007 gained `test-tech-log`.
// Dev release manifest drift fix item 2: FE-GATE-010 gained
// `check-dev-release-manifest`.
// Task 11 added TECH_LOG_STUDIO_ASSETS's manual accessibility evidence.
// Alignment follow-up item 2 added the TechLog junit report.
// 주제 화면 셋(`/topics`, `/topics/:slug/:variant`, `/studio/topics/:id`)이 라우트마다
// 하나씩인 수동 접근성 증거를 셋 더했다.
// 환경 구성(SETUP)이 `/setups/:slug` 로 하나를 더 더했다.
// Template sync (ebea300). Every count below is recounted from the merged
// config/ci/gates.json rather than taken from either side: this product
// pinned 85/97/23/118/139 and the template pinned 91/103/30/88/109, and
// neither set describes the merged file. The method was checked by first
// reproducing this product's numbers from the pre-merge gates.json.
expect(contract.commands).toHaveLength(94);
// Template sync (af3d8e6). Recounted from the merged config/ci/gates.json,
// not taken from either side: this product pinned 94/106/30/120/141 and
// the template 98/103/30/87/109. The method was checked by reproducing
// both sides' numbers from their own gates.json first. The template's four
// new commands and this product's three TechLog commands are all present;
// FE-GATE-028 now carries this product's per-route manual review evidence.
expect(contract.commands).toHaveLength(101);
expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(106);
expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(30);
expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(120);
expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(119);
expect(contract.artifacts).toHaveLength(141);
expect(contract.stages).toHaveLength(5);
expect(contract.retention.classes).toHaveLength(5);
@@ -219,7 +216,7 @@ describe("CI gate contract", () => {
JSON.stringify(await loadCiGateContract(process.cwd())),
) as Record<string, any>;
const gate = candidate.gates.find(
(entry: Record<string, any>) => entry.id === "FE-GATE-009",
(entry: Record<string, any>) => entry.id === "FE-GATE-028",
);
const artifactId =
"artifact-artifacts-tests-a11y-manual-TECH-LOG-HOME-md";
@@ -231,8 +228,121 @@ describe("CI gate contract", () => {
);
expect(() =>
parseCiGateContract(candidate, { mode: "removal-fixture" }),
).toThrow(/FE-GATE-009 manual accessibility evidence.*installed route scope/i);
parseCiGateContract(candidate),
).toThrow(/FE-GATE-028 manual accessibility evidence.*installed route scope/i);
});
it("runs the signed manual accessibility review at release, not merge (08-06)", async () => {
const contract = await loadCiGateContract(process.cwd());
const index = indexCiGateContract(contract);
const scriptsOf = (gateId: string) =>
(index.gates.get(gateId)?.commandIds ?? []).map((id) => {
const command = index.commands.get(id);
return [command?.script, ...(command?.args ?? [])].join(" ");
});
const stageOf = (gateId: string) =>
contract.stages.find(({ gateIds }) => gateIds.includes(gateId))?.id;
expect(scriptsOf("FE-GATE-009")).toEqual(["test:a11y", "review:a11y-manual -- --format-only"]);
expect(scriptsOf("FE-GATE-028")).toEqual(["review:a11y-manual"]);
expect(stageOf("FE-GATE-009")).toBe("merge");
expect(stageOf("FE-GATE-028")).toBe("release");
});
it("runs the CPU-independent scale PR tier in a merge gate (11-03)", async () => {
const contract = await loadCiGateContract(process.cwd());
const index = indexCiGateContract(contract);
const scripts = index.gates.get("FE-GATE-005")?.commandIds.map((id) => index.commands.get(id)?.script);
expect(scripts).toContain("check:scale:pr");
expect(contract.stages.find(({ id }) => id === "merge")?.gateIds).toContain("FE-GATE-005");
});
it("probes live hosting headers after promotion, not before the release is built (13-05)", async () => {
const contract = await loadCiGateContract(process.cwd());
expect(contract.stages.find(({ id }) => id === "production")?.gateIds).toContain("FE-GATE-019");
expect(contract.stages.find(({ id }) => id === "release")?.gateIds).not.toContain("FE-GATE-019");
const productionGate = contract.jobs.find(({ id }) => id === "production_gate");
expect(productionGate?.gateIds).toContain("FE-GATE-019");
expect(productionGate?.environment).toContainEqual({
name: "HOSTING_BASE_URL",
value: "${{ vars.HOSTING_BASE_URL }}",
});
});
it("drills the downloaded promoted archive in the production stage without rebuilding (13-03)", async () => {
const contract = await loadCiGateContract(process.cwd());
const index = indexCiGateContract(contract);
const productionGate = contract.jobs.find(({ id }) => id === "production_gate");
const kinds = productionGate?.steps.map(({ kind }) => kind) ?? [];
const download = productionGate?.steps.find((step) => step.kind === "download");
const extract = productionGate?.steps.find((step) => step.kind === "extract");
expect(download).toEqual({
kind: "download",
transferId: "promoted-release",
path: ".release/promoted",
});
expect(extract).toEqual({
kind: "extract",
archivePath: ".release/promoted/release-candidate.tar.gz",
targetRoot: ".release/promoted-release",
});
expect(kinds.indexOf("download")).toBeLessThan(kinds.indexOf("extract"));
expect(kinds.indexOf("extract")).toBeLessThan(kinds.indexOf("run-gate"));
// The extract step checks the archive against the digest immutable_build
// recorded, so the drilled bytes are the promoted candidate.
expect(productionGate?.needs).toContain("immutable_build");
expect(productionGate?.environment).toContainEqual({
name: "CANDIDATE_ARCHIVE_SHA256",
value: "${{ needs.immutable_build.outputs.archive_sha256 }}",
});
for (const gateId of ["FE-GATE-021", "FE-GATE-022", "FE-GATE-023", "FE-GATE-024", "FE-GATE-025"]) {
const commands = index.gates.get(gateId)?.commandIds.map((id) => index.commands.get(id)!) ?? [];
expect(commands.map(({ script }) => script), gateId).toEqual(["drill:runbook"]);
const args = commands[0]?.args ?? [];
expect(args[args.indexOf("--release-root") + 1], gateId).toBe(".release/promoted-release");
}
const workflow = renderCiWorkflow(contract);
const productionJob = workflow.slice(
workflow.indexOf(" production_gate:\n"),
workflow.indexOf(" field_gate:\n"),
);
const downloadAt = productionJob.indexOf("- name: Download promoted release");
const extractAt = productionJob.indexOf(
'--archive ".release/promoted/release-candidate.tar.gz" --extract-to ".release/promoted-release"',
);
expect(downloadAt).toBeGreaterThan(0);
expect(extractAt).toBeGreaterThan(downloadAt);
expect(productionJob.indexOf("Run blocking gate")).toBeGreaterThan(extractAt);
});
it.each([
[
"a drill without --release-root",
(contract: Record<string, any>) => {
const drill = contract.commands.find((command: Record<string, any>) => command.id === "drill-runbook");
drill.args = ["--", "FE-RB-005"];
},
],
[
"a drill gate that rebuilds from source",
(contract: Record<string, any>) => {
const gate = contract.gates.find((candidate: Record<string, any>) => candidate.id === "FE-GATE-025");
gate.commandIds = ["build", ...gate.commandIds];
},
],
[
"a production stage without the promoted archive",
(contract: Record<string, any>) => {
const job = contract.jobs.find((candidate: Record<string, any>) => candidate.id === "production_gate");
job.steps = job.steps.filter((step: Record<string, any>) => !["download", "extract"].includes(step.kind));
},
],
])("rejects %s in the production stage (13-03)", async (_name, mutate) => {
const contract = JSON.parse(
JSON.stringify(await loadCiGateContract(process.cwd())),
) as Record<string, any>;
mutate(contract);
expect(() => parseCiGateContract(contract)).toThrow(/promoted/iu);
});
it("keeps the action registry recursively immutable and resolves only known actions", () => {
@@ -358,10 +468,12 @@ describe("CI gate contract", () => {
gate.name = `${gate.name}-renamed`;
await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`);
await writeFile(path.join(root, "package.json"), await readFile("package.json"));
await expect(loadCiGateContract(root)).rejects.toThrow(
/canonical gate semantic shape/i,
await writeFile(
path.join(root, "config/ci/contract-baseline.json"),
await readFile("config/ci/contract-baseline.json"),
);
await expect(loadCiGateContract(root)).rejects.toThrow(/gateShapeSha256: baseline/i);
});
it.each(["check:artifact-schemas", "check:ci-workflow"])(
@@ -1353,6 +1465,10 @@ describe("CI gate contract", () => {
await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`);
await writeFile(path.join(root, "package.json"), await readFile("package.json"));
await writeFile(path.join(root, ".nvmrc"), await readFile(".nvmrc"));
await writeFile(
path.join(root, "config/ci/contract-baseline.json"),
await readFile("config/ci/contract-baseline.json"),
);
const drift = Buffer.from("drifted workflow\n", "utf8");
await writeFile(path.join(root, ".gitea/workflows/quality-gates.yml"), drift);
const result = spawnSync(process.execPath, [path.resolve("scripts/check-ci-contract.ts")], {
@@ -1394,7 +1510,10 @@ describe("CI workflow generation", () => {
).toHaveLength(9);
expect(first).not.toMatch(/corepack pnpm install --frozen-lockfile$/mu);
expect(first).toContain("verify-ci-candidate-archive.ts --archive");
expect(first).not.toContain("--extract-to");
// Providers and promotion read the archive without extracting it; only the
// production drills extract the promoted archive (13-03).
expect(first.match(/--extract-to/gu)).toHaveLength(1);
expect(first.indexOf("--extract-to")).toBeGreaterThan(first.indexOf(" production_gate:\n"));
expect(first).not.toMatch(/\btar\s+[^\n]*--extract/u);
expect(first).toContain("node scripts/stage-verified-promotion.ts");
expect(first).toContain("outputs:\n invocation_nonce: ${{ steps.supervise_vulnerability.outputs.invocation_nonce }}");
@@ -1424,7 +1543,7 @@ describe("CI workflow generation", () => {
'if [ -n "$PROMOTION_STAGING_ROOT" ] && [ -n "$PROMOTION_CLEANUP_TOKEN" ] && [ -n "$PROMOTION_RUNNER_TEMP_DEV" ] && [ -n "$PROMOTION_RUNNER_TEMP_INO" ] && [ -n "$PROMOTION_STAGING_DEV" ] && [ -n "$PROMOTION_STAGING_INO" ]; then',
);
const actionUses = [...first.matchAll(/^\s+-?\s*uses: (.+)$/gmu)].map((match) => match[1]);
expect(actionUses).toHaveLength(32);
expect(actionUses).toHaveLength(33);
expect(new Set(actionUses)).toEqual(
new Set([
"https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5",
@@ -1436,6 +1555,40 @@ describe("CI workflow generation", () => {
expect(actionUses.every((uses) => /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+@[0-9a-f]{40}$/u.test(uses!))).toBe(true);
});
// 12-01: main is the integration branch; a push there must run the gates.
it("runs on pushes to main", async () => {
const workflow = renderCiWorkflow(await loadCiGateContract(process.cwd()));
// This product integrates on `main` only; the template also lists `develop`.
expect(workflow).toMatch(/^on:\n {2}push:\n {4}branches: \[main\]$/mu);
});
// 12-02 / 13-01: immutable_build owns FE-GATE-015 and FE-GATE-027, but only
// the first gate of a non-matrix job was ever rendered, so release admission
// never ran in CI.
it("runs every gate a job owns, in order", async () => {
const contract = await loadCiGateContract(process.cwd());
const workflow = renderCiWorkflow(contract);
const immutable = workflow.slice(
workflow.indexOf(" immutable_build:\n"),
workflow.indexOf(" vulnerability_provider:\n"),
);
expect([...immutable.matchAll(/ci:gate -- (FE-GATE-\d{3})$/gmu)].map((match) => match[1]))
.toEqual(["FE-GATE-015", "FE-GATE-027"]);
expect(workflowGateExecutionFailures(contract, workflow)).toEqual([]);
});
it.each([
["a non-matrix gate step", " run: corepack pnpm ci:gate -- FE-GATE-027\n", "FE-GATE-027"],
["a matrix entry", " - { gate: FE-GATE-020, name: removability, browser: false }\n", "FE-GATE-020"],
])("rejects a workflow that drops %s", async (_name, line, gateId) => {
const contract = await loadCiGateContract(process.cwd());
const workflow = renderCiWorkflow(contract);
expect(workflow).toContain(line);
expect(workflowGateExecutionFailures(contract, workflow.replace(line, ""))).toEqual([
`gate is not executed by any workflow run step: ${gateId}`,
]);
});
it("derives download artifact names from the typed upload producer", async () => {
const contract = await loadCiGateContract(process.cwd());
const candidate = JSON.parse(JSON.stringify(contract)) as Record<string, any>;
+77
View File
@@ -1,4 +1,7 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
classifyObjectSchemaChange,
@@ -6,6 +9,7 @@ import {
parseNumericVersion,
verifyCompatibilityTuple,
} from "../../src/contracts/compatibility.ts";
import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts";
describe("contract compatibility", () => {
it("uses numeric version parsing rather than lexical comparison", () => {
@@ -15,6 +19,11 @@ describe("contract compatibility", () => {
expect(isVersionCompatible("next", "1.0")).toBe(false);
});
it("rejects a runtime whose minor version is lower than the supported one", () => {
expect(isVersionCompatible("2.1", "2.0")).toBe(false);
expect(isVersionCompatible("2.1", "2.1")).toBe(true);
});
it("distinguishes additive and breaking object changes", () => {
const base = { required: ["id"], properties: { id: {} } };
expect(
@@ -31,6 +40,74 @@ describe("contract compatibility", () => {
).toBe("breaking");
});
it("classifies changes it cannot prove compatible as breaking", () => {
const base = {
required: ["id"],
properties: {
id: { type: "string" },
state: { type: "string", enum: ["A", "B"] },
note: { type: "string" },
},
};
const withProperty = (key: string, schema: unknown) => ({
...base,
properties: { ...base.properties, [key]: schema },
});
expect(classifyObjectSchemaChange(base, base)).toBe("none");
expect(
classifyObjectSchemaChange(base, withProperty("id", { type: "number" })),
).toBe("breaking");
expect(
classifyObjectSchemaChange(
base,
withProperty("state", { type: "string", enum: ["A"] }),
),
).toBe("breaking");
expect(
classifyObjectSchemaChange(
base,
withProperty("note", { type: ["string", "null"] }),
),
).toBe("breaking");
expect(classifyObjectSchemaChange(base, { ...base, required: [] })).toBe(
"breaking",
);
expect(
classifyObjectSchemaChange(base, { ...base, additionalProperties: false }),
).toBe("breaking");
});
it("treats a property added under a reader that rejects unknown keys as breaking", () => {
const strict = {
required: ["id"],
properties: { id: {} },
additionalProperties: false,
};
expect(
classifyObjectSchemaChange(strict, {
...strict,
properties: { id: {}, displayName: {} },
}),
).toBe("breaking");
});
it("classifies an optional runtime config key as breaking against the committed baseline", () => {
const baseline = JSON.parse(
readFileSync("config/compatibility/runtime-config.schema.baseline.json", "utf8"),
) as Record<string, unknown>;
const current = z.toJSONSchema(runtimeConfigV2ArtifactSchema) as Record<
string,
unknown
> & { properties: Record<string, unknown> };
expect(classifyObjectSchemaChange(baseline, current)).toBe("none");
expect(
classifyObjectSchemaChange(baseline, {
...current,
properties: { ...current.properties, NEW_OPTIONAL_KEY: { type: "string" } },
}),
).toBe("breaking");
});
it("treats release ID mismatch as a warning when the blocking tuple is coherent", () => {
const frontend = {
buildId: "build-a",
@@ -79,6 +79,8 @@ describe("conditional validator CAS sidecar", () => {
scope: firstScope.snapshot,
};
expect(store.install(first, "raw-etag", 1)).toBe(false);
// Q-6.3-12. The opening quote of `W/"` is not also its closing quote.
expect(store.install(first, 'W/"', 1)).toBe(false);
expect(store.install(first, 'W/"etag-a"', 1)).toBe(true);
expect(
store.install(
@@ -0,0 +1,124 @@
import { describe, expect, it } from "vitest";
import { validateOfflineCommandContribution } from "../../src/contracts/offline-command.ts";
import {
defineQueryInvalidationTopic,
indexInvalidationRegistry,
indexInvalidationTopicVersions,
} from "../../src/contracts/query-invalidation.ts";
import { defineQueryNamespaceIdentity } from "../../src/contracts/query-keys.ts";
import { validateRealtimeContributions } from "../../src/contracts/runtime-capabilities.ts";
import { validateWebWorkerContributions } from "../../src/contracts/web-worker.ts";
/**
* Q-6.7-7. A validated index or registry is authority. `Object.freeze` on the
* outer wrapper leaves a returned `Map` clearable and leaves every row the
* caller's still-mutable object, so a later write changes what was validated.
*/
function tryClear(map: unknown): void {
try {
(map as Map<unknown, unknown>).clear();
} catch {
// A read facade has no `clear`; that is the expected outcome.
}
try {
Map.prototype.clear.call(map as Map<unknown, unknown>);
} catch {
// Borrowing the mutator must fail on the missing internal slot.
}
}
describe("query invalidation index", () => {
const topic = defineQueryInvalidationTopic("qinv.orders.changed");
const orders = defineQueryNamespaceIdentity("orders", 1);
const registry = {
topics: [topic],
namespaces: [orders],
edges: [{ topicId: topic, namespace: orders }],
};
it("cannot be cleared after indexing", () => {
const index = indexInvalidationRegistry(registry);
tryClear(index.namespacesForTopic);
tryClear(index.topicsForNamespace);
expect(index.namespacesForTopic.get(topic)).toEqual([orders]);
expect(index.topicsForNamespace.get('["orders",1]')).toEqual([topic]);
});
it("returns topic versions that cannot be cleared", () => {
const versions = indexInvalidationTopicVersions(registry, [
{ topicId: topic, topicVersion: 1 },
]);
tryClear(versions);
expect(versions.get(topic)).toBe(1);
});
});
describe("runtime capability contributions", () => {
it("snapshots web worker task bounds", () => {
const task = {
taskId: "hash",
taskVersion: 1 as const,
maximumInputBytes: 1_024,
maximumOutputBytes: 1_024,
deadlineMs: 1_000,
};
const [installed] = validateWebWorkerContributions([
{ taskGroupId: "crypto", tasks: [task], fallback: "UNSUPPORTED" },
]);
task.deadlineMs = 999_999;
expect(installed?.tasks[0]?.deadlineMs).toBe(1_000);
expect(Object.isFrozen(installed?.tasks[0])).toBe(true);
});
it("snapshots offline command operation bounds", () => {
const operation = {
operationId: "CREATE_ORDER",
contractPackageId: "@test/contracts",
maximumRequestBytes: 1_024,
retentionClass: "STANDARD_7D" as const,
};
const installed = validateOfflineCommandContribution({
datasetId: "OFFLINE_COMMANDS_V1",
operations: [operation],
});
operation.maximumRequestBytes = 999_999_999;
expect(installed.operations[0]?.maximumRequestBytes).toBe(1_024);
expect(Object.isFrozen(installed.operations[0])).toBe(true);
});
it("snapshots realtime transport and effect rows", () => {
const transport = {
kind: "POLLING" as const,
operationId: "LIST_ORDERS",
intervalMs: 5_000,
};
const topics = ["qinv.orders.changed"];
const [installed] = validateRealtimeContributions([
{
contributionId: "orders-realtime",
featureId: "orders",
contractSourcePackageId: "@test/contracts",
streamId: "ORDERS",
recoveryMode: "SESSION_REBUILD",
eventEffects: [
{
eventType: "orders.changed",
mapperId: "OrdersChanged",
effect: "INVALIDATE_TOPICS",
invalidationTopics: topics,
},
],
transport,
},
]);
transport.intervalMs = 1;
topics.length = 0;
const effect = installed?.eventEffects[0];
expect(installed?.transport).toMatchObject({ intervalMs: 5_000 });
expect(effect?.invalidationTopics).toEqual(["qinv.orders.changed"]);
expect(Object.isFrozen(installed?.transport)).toBe(true);
expect(Object.isFrozen(effect?.invalidationTopics)).toBe(true);
});
});
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import { getApiOperation } from "../../src/contracts/api-operations.ts";
import { mapWithBoundaryRegistry } from "../../src/contracts/boundary-mapper.ts";
import {
isAllowedOfflineTransition,
type OfflineCommandState,
} from "../../src/contracts/offline-command.ts";
import { validateWithRuntimeSchemaRegistry } from "../../src/contracts/schema-registry.ts";
import { getStorageDefinition } from "../../src/contracts/storage-keys.ts";
/**
* Q-6.7-11. A registry lookup answers only for its own keys. `registry[id]`
* walks the prototype chain, so `constructor` or `__proto__` resolved to
* `Object` / `Object.prototype` instead of "not registered".
*/
const INHERITED = ["constructor", "__proto__", "toString", "hasOwnProperty"];
describe("registry lookups ignore inherited keys", () => {
it("getApiOperation", () => {
for (const id of INHERITED) {
expect(() => getApiOperation(id), id).toThrow("Unregistered API operation");
}
});
it("getStorageDefinition", () => {
for (const id of INHERITED) {
expect(() => getStorageDefinition(id), id).toThrow(
"Unregistered storage key",
);
}
});
it("validateWithRuntimeSchemaRegistry", () => {
for (const id of INHERITED) {
expect(validateWithRuntimeSchemaRegistry(id, {}, {}), id).toEqual({
success: false,
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }],
});
}
});
it("mapWithBoundaryRegistry", () => {
for (const id of INHERITED) {
expect(mapWithBoundaryRegistry(id, {}, {}), id).toEqual({
ok: false,
code: "MAPPING_INVARIANT_REJECTED",
});
}
});
});
describe("offline command transitions", () => {
it("answers false for a state that is not listed", () => {
for (const from of ["UNKNOWN", ...INHERITED]) {
expect(
isAllowedOfflineTransition(from as OfflineCommandState, "PENDING"),
from,
).toBe(false);
}
});
it("keeps the listed transitions", () => {
expect(isAllowedOfflineTransition("PENDING", "LEASED")).toBe(true);
expect(isAllowedOfflineTransition("ACKED", "PENDING")).toBe(false);
});
});
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import {
CONTRACT_SET_ALGORITHM,
computeContractSetDigest,
} from "../../src/contracts/contract-set-canonical.ts";
import { verifyContractSet } from "../../src/contracts/contract-set.ts";
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
import { compareReleaseToRuntime } from "../../src/contracts/release-tokens.ts";
/** Q-6.7-12. Quiet passes and small defects in the release contracts. */
describe("release to runtime comparison", () => {
it("reports the asset manifest hash as unverified, not as compared", () => {
const result = compareReleaseToRuntime(
{
buildId: "build-a",
configSchemaVersion: "1.0",
apiContractVersion: "1.0",
assetManifestHash: "assets-a",
releaseId: "release-a",
},
{
BUILD_ID: "build-a",
CONFIG_SCHEMA_VERSION: "1.0",
API_CONTRACT_VERSION: "1.0",
RELEASE_ID: "release-a",
},
);
expect(result).toMatchObject({ compatible: true, mismatches: [] });
expect(result.unverified).toEqual(["assetManifestHash"]);
});
});
describe("contract set verification", () => {
const accounts = Object.freeze({
packageId: "@example/accounts",
version: "1.2.3",
digest: `sha256:${"1".repeat(64)}` as const,
runtimeProtocolVersion: 1 as const,
sourceRevision: "a".repeat(40),
});
it("returns a failure code for a duplicated expected package", async () => {
const manifest = {
setAlgorithm: CONTRACT_SET_ALGORITHM,
setDigest: await computeContractSetDigest([accounts]),
packages: [accounts],
};
await expect(
verifyContractSet({ expected: [accounts, accounts], manifest }),
).resolves.toEqual({ ok: false, code: "CONTRACT_SET_DUPLICATE_PACKAGE" });
});
it("still admits a matching set", async () => {
const manifest = {
setAlgorithm: CONTRACT_SET_ALGORITHM,
setDigest: await computeContractSetDigest([accounts]),
packages: [accounts],
};
await expect(
verifyContractSet({ expected: [accounts], manifest }),
).resolves.toEqual({ ok: true });
});
});
describe("runtime identity registry eviction", () => {
it("evicts the least recently touched released row first", () => {
let sequence = 0;
const registry = createRuntimeIdentityRegistry({
maxEntries: 2,
tokenFactory: () => `identity-token-${String(sequence++).padStart(4, "0")}`,
});
const first = registry.intern({ resource: "first" }).token;
const second = registry.intern({ resource: "second" }).token;
// Touch "first" again so "second" becomes the eviction candidate.
expect(registry.intern({ resource: "first" }).token).toBe(first);
registry.intern({ resource: "third" });
expect(registry.inspect().entries).toBe(2);
expect(registry.intern({ resource: "first" }).token).toBe(first);
expect(registry.intern({ resource: "second" }).token).not.toBe(second);
});
});
+262
View File
@@ -0,0 +1,262 @@
import { describe, expect, it } from "vitest";
import { installBrowserRpcContractBindings } from "../../src/contracts/browser-rpc.ts";
import { parseCacheInvalidationWireEvent } from "../../src/contracts/cache-invalidation.ts";
import {
composeContractContributions,
ContractContributionError,
} from "../../src/contracts/external-contract-runtime.ts";
import { createRealtimePolicyRegistry } from "../../src/contracts/realtime-streams.ts";
import {
installRestAuthProfileRegistry,
REST_AUTH_PROFILES,
} from "../../src/contracts/rest-profiles.ts";
import { decodeStaticAssetManifest } from "../../src/contracts/service-worker-static-manifest.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
import {
MAPPERS,
SCHEMA_CODECS,
UNARY_ENCODER,
unaryOperation,
unaryProfile,
} from "./browser-rpc/fixture.ts";
import {
EFFECT_PROFILE_ID,
ENDPOINT_ID,
KILL_SWITCH_ID,
TEST_API_OPERATIONS,
TEST_MAPPERS,
TEST_SCHEMA_CODECS,
createTestRealtimeRegistry,
} from "./realtime/fixture.ts";
/**
* Q-6.7-6. Every contract that installs a caller-supplied row must validate
* and install one owned snapshot. An own `Symbol.iterator` on an array or an
* accessor on a row lets the value that was checked differ from the value
* that was installed.
*/
/** An array whose length and indices say one thing and whose iterator says another. */
function iteratorSmuggling<T>(visible: readonly T[], smuggled: readonly T[]): T[] {
const array = [...visible];
Object.defineProperty(array, Symbol.iterator, {
value: function* () {
yield* smuggled;
},
});
return array;
}
const validator = Object.freeze({
schemaId: "SmuggledSchema",
safeParse: (value: unknown) =>
Object.freeze({ success: true as const, data: value }),
});
describe("external contract composition", () => {
it("does not install an event hidden behind an array iterator", () => {
const smuggled = Object.freeze({
eventType: "test.smuggled",
envelopeValidator: validator,
payloadValidator: validator,
});
let composed: ReturnType<typeof composeContractContributions> | undefined;
try {
composed = composeContractContributions([
{
contributionId: "fixture-v1",
featureId: "test-feature",
source: {
kind: "TEMPLATE_FIXTURE",
fixtureId: "REFERENCE_FEATURE_V1",
revision: 1,
},
http: [],
events: iteratorSmuggling([], [smuggled]),
},
] as never);
} catch (error) {
expect(error).toBeInstanceOf(ContractContributionError);
return;
}
expect(composed.eventByType.has("test.smuggled")).toBe(false);
});
it("reports a throwing reflection trap as a composition failure", () => {
const row = new Proxy(
{ ...TEST_CONTRACT_CONTRIBUTION.http[0]! },
{
ownKeys() {
throw new TypeError("hostile ownKeys trap");
},
},
);
expect(() =>
composeContractContributions([
{ ...TEST_CONTRACT_CONTRIBUTION, http: [row] },
] as never),
).toThrow(ContractContributionError);
});
});
describe("realtime policy registry", () => {
it("rejects a limit accessor instead of reading it twice", () => {
const baseline = createTestRealtimeRegistry();
const stream = baseline.listStreams()[0]!;
let reads = 0;
const limits = { ...stream.limits };
Object.defineProperty(limits, "maxEventBytes", {
enumerable: true,
configurable: true,
get: () => {
reads += 1;
// Three reads validate it; the fourth is the install copy.
return reads <= 3 ? 1_024 : 999_999_999;
},
});
expect(() =>
createRealtimePolicyRegistry({
streams: [{ ...stream, limits }],
eventTypes: [baseline.listEventTypes()[0]!],
bindings: {
schemaCodecs: TEST_SCHEMA_CODECS,
mappers: TEST_MAPPERS,
apiOperations: TEST_API_OPERATIONS,
endpointIds: [ENDPOINT_ID],
effectProfileIds: [EFFECT_PROFILE_ID],
killSwitchIds: [KILL_SWITCH_ID],
rebuildInputIds: ["referenceRealtimeRebuild"],
},
}),
).toThrow();
});
});
describe("cache invalidation wire event", () => {
it("rejects an accessor field", () => {
const now = 1_000_000;
const event = {
protocolVersion: 1,
eventId: "remote-event-00000001",
sourceId: "remote-source-0000001",
sourceEpoch: "remote-epoch-0000001",
sequence: 1,
cacheEpoch: "cache-epoch-0001",
topicVersion: 1,
emittedAt: now,
expiresAt: now + 60_000,
};
Object.defineProperty(event, "topic", {
enumerable: true,
get: () => "sample-topic-alpha",
});
expect(
parseCacheInvalidationWireEvent(event, {
cacheEpoch: "cache-epoch-0001",
topicVersions: { "sample-topic-alpha": 1 },
nowEpochMilliseconds: now,
}),
).toEqual({ ok: false, reason: "INVALID_ENVELOPE" });
});
});
describe("static asset manifest", () => {
const row = {
url: "/assets/app-abcdefgh.js",
sha256: `sha256:${"a".repeat(64)}`,
bytes: 16,
contentType: "text/javascript",
};
const manifest = (assets: unknown) => ({
schemaVersion: 1,
buildId: "build-1",
releaseId: "release-1",
setDigest: `sha256:${"b".repeat(64)}`,
assets,
});
it("rejects an accessor on a row", () => {
const accessorRow = { ...row };
Object.defineProperty(accessorRow, "bytes", {
enumerable: true,
get: () => 16,
});
expect(decodeStaticAssetManifest(manifest([accessorRow])).ok).toBe(false);
});
it("does not decode rows hidden behind an array iterator", () => {
const decoded = decodeStaticAssetManifest(
manifest(iteratorSmuggling([], [row])),
);
expect(decoded.ok && decoded.manifest.assets.length > 0).toBe(false);
});
});
describe("browser RPC contract bindings", () => {
const install = (operations: Record<string, unknown>) =>
installBrowserRpcContractBindings({
operations: operations as never,
profiles: { [unaryProfile().runtimeProfileId]: unaryProfile() },
schemaCodecs: SCHEMA_CODECS,
mappers: MAPPERS,
requestEncoders: { RpcResourceRequestEncoder: UNARY_ENCODER },
});
it("rejects a non-enumerable registry entry", () => {
const operations = {};
Object.defineProperty(operations, "GET_RPC_RESOURCE", {
enumerable: false,
value: unaryOperation(),
});
expect(() => install(operations)).toThrow(TypeError);
});
it("rejects a non-enumerable row field", () => {
const { totalDeadlineMs, ...rest } = unaryOperation();
const operation = Object.defineProperty(rest, "totalDeadlineMs", {
enumerable: false,
value: totalDeadlineMs,
});
expect(() => install({ GET_RPC_RESOURCE: operation })).toThrow(TypeError);
});
});
describe("REST auth profile registry", () => {
it("rejects an accessor field", () => {
const profile = { ...REST_AUTH_PROFILES.ANONYMOUS };
Object.defineProperty(profile, "transport", {
enumerable: true,
get: () => "ANONYMOUS",
});
expect(() => installRestAuthProfileRegistry({ ANONYMOUS: profile })).toThrow(
TypeError,
);
});
it("installs the header set it validated, not the one an iterator yields", () => {
let iterations = 0;
const allowed = ["authorization"];
Object.defineProperty(allowed, Symbol.iterator, {
value: function* () {
iterations += 1;
yield "authorization";
if (iterations > 1) yield* ["x-csrf-token", "x-csrf-token"];
},
});
let installed: ReturnType<typeof installRestAuthProfileRegistry> | undefined;
try {
installed = installRestAuthProfileRegistry({
REFERENCE_EXTERNAL_BEARER: {
...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER,
allowedCredentialHeaders: allowed as never,
},
});
} catch {
return;
}
expect(
installed.get("REFERENCE_EXTERNAL_BEARER")?.allowedCredentialHeaders,
).toEqual(["authorization"]);
});
});
+164 -3
View File
@@ -4,12 +4,14 @@ import {
CACHE_INVALIDATION_PROTOCOL_VERSION,
CACHE_INVALIDATION_WIRE_LIMITS,
decodeCacheInvalidationWireEvent,
isCacheInvalidationOpaqueIdentifier,
parseCacheInvalidationWireEvent,
type CacheInvalidationWireEvent,
} from "../../src/contracts/cache-invalidation.ts";
import {
createBrowserCrossContextInvalidation,
createBrowserCrossContextInvalidationFromHost,
crossContextCacheEpochForRelease,
type BroadcastChannelFacade,
type BroadcastMessageListener,
type BrowserCrossContextInvalidationDependencies,
@@ -346,6 +348,66 @@ describe("browser cross-context host", () => {
).toBeUndefined();
expect(reads).toEqual([]);
});
it("reports an inactive host through observe instead of failing silently (Q-6.2-9)", () => {
const observations: CrossContextInvalidationObservation[] = [];
const topics = [{ topic: TOPIC, topicVersion: 1 }];
expect(
createBrowserCrossContextInvalidationFromHost({
host: {},
cacheEpoch: CACHE_EPOCH,
topics,
observe: (observation) => observations.push(observation),
}),
).toBeUndefined();
expect(
createBrowserCrossContextInvalidationFromHost({
host: { crypto: globalThis.crypto },
cacheEpoch: "release.1.2.3+sha.abc",
topics,
observe: (observation) => observations.push(observation),
}),
).toBeUndefined();
expect(observations).toEqual([
{
operation: "OPEN",
outcome: "FAILED",
transport: "NONE",
reason: "SECURE_RANDOM_UNAVAILABLE",
},
{
operation: "OPEN",
outcome: "FAILED",
transport: "NONE",
reason: "INVALID_CACHE_EPOCH",
},
]);
});
it("derives a valid, stable cache epoch from any release id (Q-6.2-9)", () => {
const releaseIds = [
"1.2.3+sha.abc",
"feature/x",
"app@1.2.3",
"x".repeat(500),
"1.2.3",
];
const epochs = releaseIds.map(crossContextCacheEpochForRelease);
for (const epoch of epochs) {
expect(isCacheInvalidationOpaqueIdentifier(epoch)).toBe(true);
}
expect(new Set(epochs).size).toBe(releaseIds.length);
expect(crossContextCacheEpochForRelease("feature/x")).toBe(epochs[1]);
const runtime = createBrowserCrossContextInvalidationFromHost({
host: { crypto: globalThis.crypto },
cacheEpoch: crossContextCacheEpochForRelease("app@1.2.3"),
topics: [{ topic: TOPIC, topicVersion: 1 }],
});
expect(runtime).toBeDefined();
runtime?.close();
});
});
describe("browser cross-context invalidation transport", () => {
@@ -440,6 +502,15 @@ describe("browser cross-context invalidation transport", () => {
sequence: 1,
}),
);
// 02-08. A source first seen mid-stream has already sent events this tab
// missed, so its first event is a gap on its own.
network.emit(
wireEvent({
eventId: "joined-event-00000004",
sourceId: "joined-source-0000001",
sequence: 4,
}),
);
expect(
delivered.map(({ event, ordering }) => [
@@ -450,6 +521,7 @@ describe("browser cross-context invalidation transport", () => {
[1, "NEXT"],
[3, "GAP"],
[1, "NEXT"],
[4, "GAP"],
]);
expect(observations).toContainEqual({
operation: "RECEIVE",
@@ -460,6 +532,42 @@ describe("browser cross-context invalidation transport", () => {
runtime.close();
});
it("keeps the per-source sequence watermark past the event TTL", () => {
const network = new FakeBroadcastNetwork();
let currentTime = NOW;
const runtime = createBrowserCrossContextInvalidation(
dependencies("tab-b", {
createBroadcastChannel: network.createChannel,
nowEpochMilliseconds: () => currentTime,
}),
);
const delivered: CrossContextInvalidationDelivery[] = [];
runtime.subscribe((delivery) => delivered.push(delivery));
network.emit(wireEvent({ eventId: "remote-event-00000001", sequence: 1 }));
// The source stays quiet longer than the 60 s event TTL.
currentTime += 61_000;
network.emit(
wireEvent({
eventId: "remote-event-00000002",
sequence: 2,
emittedAt: currentTime,
expiresAt: currentTime + 60_000,
}),
);
expect(
delivered.map(({ event, ordering }) => [
event.sequence,
ordering,
]),
).toEqual([
[1, "NEXT"],
[2, "NEXT"],
]);
runtime.close();
});
it("falls back when BroadcastChannel open or publish fails", () => {
const storageBus = new FakeStorageBus();
const firstStorage = storageBus.createEndpoint();
@@ -487,7 +595,9 @@ describe("browser cross-context invalidation transport", () => {
const received = vi.fn();
second.subscribe(received);
expect(second.getStatus()).toBe("ACTIVE_STORAGE_FALLBACK");
// R-2.3. Other tabs publish on BroadcastChannel only, so a tab whose
// channel failed to open misses their events and must not look healthy.
expect(second.getStatus()).toBe("DEGRADED_STORAGE_FALLBACK");
expect(first.publish({ topic: TOPIC, topicVersion: 1 })).toEqual({
ok: true,
transport: "STORAGE",
@@ -498,11 +608,54 @@ describe("browser cross-context invalidation transport", () => {
expect(firstStorage.storage.removeCount).toBe(1);
expect(storageBus.values.has(STORAGE_PULSE_KEY)).toBe(false);
expect(secondNetwork.channels).toHaveLength(0);
expect(second.publish({ topic: TOPIC, topicVersion: 1 })).toEqual({
ok: true,
transport: "STORAGE",
});
expect(second.getStatus()).toBe("DEGRADED_STORAGE_FALLBACK");
first.close();
second.close();
});
it("keeps receiving broadcasts after its own broadcast publish fails", () => {
const network = new FakeBroadcastNetwork();
const storageBus = new FakeStorageBus();
const senderStorage = storageBus.createEndpoint();
const receiverStorage = storageBus.createEndpoint();
const sender = createBrowserCrossContextInvalidation(
dependencies("tab-a", {
createBroadcastChannel: network.createChannel,
storage: senderStorage.storage,
storageEvents: senderStorage.target,
}),
);
const receiver = createBrowserCrossContextInvalidation(
dependencies("tab-b", {
createBroadcastChannel: network.createChannel,
storage: receiverStorage.storage,
storageEvents: receiverStorage.target,
}),
);
network.channels[1]!.failPost = true;
expect(
receiver.publish({ topic: TOPIC, topicVersion: 1 }),
).toEqual({ ok: true, transport: "STORAGE" });
const delivered: CrossContextInvalidationDelivery[] = [];
receiver.subscribe((delivery) => delivered.push(delivery));
expect(
sender.publish({ topic: TOPIC, topicVersion: 1 }),
).toEqual({ ok: true, transport: "BROADCAST" });
expect(delivered.map(({ transport }) => transport)).toEqual([
"BROADCAST",
]);
expect(receiver.getStatus()).toBe("ACTIVE_STORAGE_FALLBACK");
sender.close();
receiver.close();
});
it("rejects storage pulses from another or unknown storage area", () => {
const storageBus = new FakeStorageBus();
const publisherStorage = storageBus.createEndpoint();
@@ -563,7 +716,7 @@ describe("browser cross-context invalidation transport", () => {
}),
);
expect(runtime.getStatus()).toBe("ACTIVE_STORAGE_FALLBACK");
expect(runtime.getStatus()).toBe("DEGRADED_STORAGE_FALLBACK");
expect(runtime.publish({ topic: TOPIC, topicVersion: 1 })).toEqual({
ok: false,
reason: "TRANSPORT_UNAVAILABLE",
@@ -618,12 +771,14 @@ describe("browser cross-context invalidation transport", () => {
it("bounds TTL and LRU tracking instead of growing with remote sources", () => {
const network = new FakeBroadcastNetwork();
let currentTime = NOW;
const observations: CrossContextInvalidationObservation[] = [];
const runtime = createBrowserCrossContextInvalidation(
dependencies("tab-b", {
createBroadcastChannel: network.createChannel,
nowEpochMilliseconds: () => currentTime,
dedupeCapacity: 2,
sourceCapacity: 2,
observe: (observation) => observations.push(observation),
}),
);
const received = vi.fn();
@@ -651,7 +806,13 @@ describe("browser cross-context invalidation transport", () => {
network.emit(
distinctSource(3, "bounded-event-3", currentTime),
);
expect(received).toHaveBeenCalledTimes(5);
// The dedupe entry expired with the event TTL, but the sequence watermark
// does not expire, so the replay is dropped as stale, not redelivered.
expect(received).toHaveBeenCalledTimes(4);
expect(observations.at(-1)).toMatchObject({
outcome: "DROPPED",
reason: "STALE",
});
runtime.close();
});
@@ -157,6 +157,67 @@ describe("bounded cursor pagination runtime", () => {
error: { code: "PAGINATION_SNAPSHOT_CHANGED" },
});
});
// Q-6.3-12. The byte estimate serialized every accumulated item again on
// each page, and `push(...items)` spreads a page into call arguments.
it("serializes each page once", async () => {
const pages = [["a", "b"], ["c", "d"], ["e", "f"]];
const stringify = vi.spyOn(JSON, "stringify");
try {
const runtime = createCursorPaginationRuntime({
definitionId: "LIST_ALL",
profile: { ...profile, maxTotalItems: 6 },
loadPage: async (cursor) => {
const index = cursor === null ? 0 : Number(cursor);
const last = index === pages.length - 1;
return {
ok: true,
value: {
items: pages[index] ?? [],
nextCursor: last ? null : String(index + 1),
hasMore: !last,
snapshotToken: null,
},
};
},
});
const result = await runtime.loadAll({});
const serializedItems = stringify.mock.calls
.map(([value]) => (Array.isArray(value) ? value.length : 0))
.reduce((sum, length) => sum + length, 0);
stringify.mockRestore();
expect(result).toEqual({
ok: true,
value: ["a", "b", "c", "d", "e", "f"],
});
expect(serializedItems).toBe(6);
} finally {
stringify.mockRestore();
}
});
it("accepts a page larger than the call argument limit", async () => {
const large = new Array<number>(1_000_000).fill(0);
const bulk = createCursorPaginationRuntime({
definitionId: "LIST_ALL",
profile: {
...profile,
maxTotalItems: large.length,
maxEstimatedBytes: 4 * large.length,
},
loadPage: async () => ({
ok: true,
value: {
items: large,
nextCursor: null,
hasMore: false,
snapshotToken: null,
},
}),
});
const result = await bulk.loadAll({});
expect(result.ok && result.value.length).toBe(large.length);
});
});
/**
@@ -0,0 +1,65 @@
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { describe, expect, it } from "vitest";
/**
* README.md, "Files you can delete after copying", tells a new project that
* the build and the gates read none of the history documents except
* `docs/reviews/adapters/INVENTORY.md`. The removal fixtures rely on the same
* promise: they do not copy `docs/`. A test that opens a review document broke
* all three removal checks (fix of 11-04), so the promise is checked here.
*/
const CODE_ROOTS = ["src", "tests", "scripts", "config", "recipes", "schemas", ".gitea"];
const ROOT_FILES = [
"package.json",
"vite.config.ts",
"vitest.config.ts",
"eslint.config.ts",
"playwright.config.ts",
];
// Built from pieces so that this file does not match itself.
const REVIEWS = ["docs", "reviews", ""].join("/");
const KEPT = `${REVIEWS}adapters/INVENTORY.md`;
const DELETABLE = [
new RegExp(`${REVIEWS}(?!adapters/INVENTORY\\.md)`, "u"),
new RegExp(["docs", "superpowers"].join("/"), "u"),
new RegExp(`\\b${"SPEC"}\\.md\\b`, "u"),
new RegExp(`\\b${"CLAUDE"}\\.md\\b`, "u"),
new RegExp(`(^|["'\`(\\s])${"tasks"}/`, "u"),
];
async function codeFiles(directory: string): Promise<string[]> {
const entries = await readdir(directory, { withFileTypes: true }).catch(
() => [],
);
const files = await Promise.all(
entries.map(async (entry) => {
const target = path.join(directory, entry.name);
if (entry.isDirectory())
return entry.name === "node_modules" ? [] : codeFiles(target);
return /\.(?:[cm]?[jt]sx?|json|ya?ml)$/u.test(entry.name) ? [target] : [];
}),
);
return files.flat();
}
describe("deletable history documents", () => {
it("are read by no code, test, script or configuration", async () => {
const files = [
...(await Promise.all(CODE_ROOTS.map(codeFiles))).flat(),
...ROOT_FILES,
];
const readers: string[] = [];
for (const file of files) {
const lines = (await readFile(file, "utf8").catch(() => "")).split("\n");
lines.forEach((line, index) => {
if (DELETABLE.some((pattern) => pattern.test(line)))
readers.push(`${file}:${index + 1}`);
});
}
expect(readers, `only ${KEPT} may be read`).toEqual([]);
});
});
+112 -7
View File
@@ -1,4 +1,6 @@
import { readFile, readdir } from "node:fs/promises";
import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
@@ -9,6 +11,7 @@ import {
isDeploymentTarget,
type AdmissionInput,
} from "../../src/contracts/deployment-admission.ts";
import { ENV_REGISTRY, getBuildConfig } from "../../src/contracts/env.ts";
import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts";
import { generateRuntimeConfig } from "../../scripts/generate-runtime-config.ts";
@@ -80,13 +83,51 @@ describe("deployment admission", () => {
}
});
it("permits a routable public host", () => {
expect(
findAdmissionViolations("production", {
it("refuses IPv6, mapped, CGNAT, 0/8 and internal-name hosts (Q-6.7-10)", () => {
for (const host of [
"https://[::ffff:127.0.0.1]/",
"https://[::ffff:8.8.8.8]/",
"https://[fd00::1]/",
"https://[fc12:3456::1]/",
"https://[fe80::1]/",
"https://[febf::1]/",
"https://[0:0:0:0:0:0:0:1]/",
"https://100.64.0.1/",
"https://100.127.255.254/",
"https://0.1.2.3/",
"https://api.internal/",
"https://printer.local/",
"https://localhost./",
"https://api.internal./",
]) {
const violations = findAdmissionViolations("production", {
...PRODUCTION_ARTIFACT,
API_BASE_URL: "https://api.172.16.example.com/",
} as AdmissionInput),
).toEqual([]);
API_BASE_URL: host,
} as AdmissionInput);
expect(violations.map((violation) => violation.field), host).toContain(
"API_BASE_URL",
);
}
});
it("permits a routable public host", () => {
for (const host of [
"https://api.172.16.example.com/",
"https://100.128.0.1/",
"https://100.63.255.255/",
"https://[2001:db8::1]/",
"https://[fec0::1]/",
"https://internal.example.com/",
"https://local.example.com/",
]) {
expect(
findAdmissionViolations("production", {
...PRODUCTION_ARTIFACT,
API_BASE_URL: host,
} as AdmissionInput),
host,
).toEqual([]);
}
});
it("refuses a placeholder identity on a public target", () => {
@@ -155,6 +196,32 @@ describe("runtime config profiles", () => {
).rejects.toThrow(/runtime config is invalid/u);
});
it("refuses a staging or production build without VITE_BUILD_ID (F-6)", async () => {
for (const target of ["staging", "production"] as const) {
await expect(
generateRuntimeConfig(target, { RELEASE_ID: "r-1" }),
).rejects.toThrow(/VITE_BUILD_ID/u);
await expect(
generateRuntimeConfig(target, { VITE_BUILD_ID: "", RELEASE_ID: "r-1" }),
).rejects.toThrow(/VITE_BUILD_ID/u);
}
});
it("declares the build defaults that getBuildConfig applies (F-6)", () => {
const applied = getBuildConfig({});
expect({
VITE_BUILD_ID: ENV_REGISTRY.VITE_BUILD_ID.defaultValue,
VITE_COMMIT_SHA: ENV_REGISTRY.VITE_COMMIT_SHA.defaultValue,
VITE_ROUTER_BASE_PATH: ENV_REGISTRY.VITE_ROUTER_BASE_PATH.defaultValue,
VITE_RUNTIME_CONFIG_URL: ENV_REGISTRY.VITE_RUNTIME_CONFIG_URL.defaultValue,
}).toEqual({
VITE_BUILD_ID: applied.buildId,
VITE_COMMIT_SHA: applied.commitSha,
VITE_ROUTER_BASE_PATH: applied.routerBasePath,
VITE_RUNTIME_CONFIG_URL: applied.runtimeConfigUrl,
});
});
it("keeps a developer build from carrying a released identity by default", async () => {
const config = await generateRuntimeConfig("local", {});
expect(config["BUILD_ID"]).toBe("local-build");
@@ -163,4 +230,42 @@ describe("runtime config profiles", () => {
.length,
).toBeGreaterThan(0);
});
// F-5 (13-15). `corepack pnpm dev` serves public/config.json while every
// build writes the local profile instead, so the two copies must not drift.
it("keeps public/config.json equal to what a local build writes", async () => {
const served: unknown = JSON.parse(await readFile("public/config.json", "utf8"));
expect(served).toEqual(await generateRuntimeConfig("local", {}));
});
// 13-01: the build profile and the admission target are two repository
// variables. A staging profile left in place for a production release has to
// stop the release, whatever the built document happens to say.
it.each([
["staging", 1],
["production", 0],
] as const)("admits a production artifact under APP_PROFILE=%s only when it names the target", async (profile, status) => {
const root = await mkdtemp(path.join(tmpdir(), "release-admission-profile-"));
try {
const config = await generateRuntimeConfig("production", {
VITE_BUILD_ID: "20260815.42",
RELEASE_ID: "r-2026.08.15-1",
});
await mkdir(path.join(root, "dist"), { recursive: true });
await writeFile(path.join(root, "dist/config.json"), JSON.stringify(config));
const result = spawnSync(
process.execPath,
[path.resolve("scripts/check-release-admission.ts")],
{
cwd: root,
encoding: "utf8",
env: { ...process.env, APP_PROFILE: profile, RELEASE_TARGET: "production" },
},
);
expect(result.status, result.stderr).toBe(status);
if (status === 1) expect(result.stderr).toMatch(/APP_PROFILE=staging/u);
} finally {
await rm(root, { recursive: true, force: true });
}
});
});
+31
View File
@@ -139,3 +139,34 @@ describe("structured diagnostics contract", () => {
).not.toThrow();
});
});
describe("bounded diagnostic dimensions", () => {
it.each([
["component_boundary", "route", true],
["component_boundary", "feature", true],
["component_boundary", "boot", true],
["component_boundary", "SomeComponentName", false],
["component_boundary", 1, false],
["queue_size_bucket", "0", true],
["queue_size_bucket", "1-10", true],
["queue_size_bucket", "51+", true],
["queue_size_bucket", "4096", false],
["queue_size_bucket", 3, false],
] as const)("admits %s=%s only from its finite set (%s)", (key, value, admitted) => {
const projected = projectDiagnosticRecord(
{ level: "warn", eventId: "ui.render.failed", context: { [key]: value } },
() => 0,
);
expect(projected.success).toBe(admitted);
});
});
describe("open-ended bucket labels", () => {
it("records the top buckets that contain a plus sign", () => {
for (const context of [{ queue_size_bucket: "51+" }, { attempt_count_bucket: "5+" }]) {
expect(
projectDiagnosticRecord({ level: "warn", eventId: "ui.render.failed", context }, () => 0),
).toMatchObject({ success: true, record: { context } });
}
});
});
+38
View File
@@ -0,0 +1,38 @@
import { chmod, mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { makeDistFilesPublic } from "../../scripts/lib/dist-permissions.ts";
// 13-02. The validated JSON writer publishes with mode 0600, so dist/config.json
// and dist/release-manifest.json reached the release archive unreadable to a web
// server running as another user, and every boot failed with 403.
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
describe("dist file permissions", () => {
it("makes every dist file readable by other users and keeps other bits", async () => {
const root = await mkdtemp(path.join(tmpdir(), "dist-permissions-"));
roots.push(root);
await mkdir(path.join(root, ".vite"), { recursive: true });
const files = {
"config.json": 0o600,
".vite/manifest.json": 0o600,
"index.html": 0o664,
} as const;
for (const [file, mode] of Object.entries(files)) {
await writeFile(path.join(root, file), "{}");
await chmod(path.join(root, file), mode);
}
await makeDistFilesPublic(root);
expect((await stat(path.join(root, "config.json"))).mode & 0o777).toBe(0o644);
expect((await stat(path.join(root, ".vite/manifest.json"))).mode & 0o777).toBe(0o644);
expect((await stat(path.join(root, "index.html"))).mode & 0o777).toBe(0o664);
});
});
+63 -12
View File
@@ -5,23 +5,19 @@ import {
createFailure,
kindForStatus,
normalizeUnknownFailure,
withFailureEffect,
} from "../../src/contracts/errors.ts";
describe("frontend failure classification", () => {
it("defines all stable error kinds with the seven contract fields", () => {
it("defines all stable error kinds with the four contract fields", () => {
expect(Object.keys(ERROR_REGISTRY)).toHaveLength(38);
for (const definition of Object.values(ERROR_REGISTRY)) {
expect(definition).toEqual(
expect.objectContaining({
kind: expect.any(String),
defaultRetryable: expect.any(Boolean),
severity: expect.any(String),
userMessageKey: expect.any(String),
action: expect.any(String),
telemetryEvent: expect.any(String),
redaction: expect.any(Array),
}),
);
expect(Object.keys(definition).sort()).toEqual([
"action",
"defaultRetryable",
"kind",
"userMessageKey",
]);
}
});
@@ -38,6 +34,36 @@ describe("frontend failure classification", () => {
expect(kindForStatus(status)).toBe(kind);
});
it("keeps re-login first for an auth failure whose effect is unknown (D-2)", () => {
expect(
createFailure("AUTH_REQUIRED", "CREATE", 0, { effect: "MAYBE_APPLIED" }),
).toMatchObject({ action: "reauth", retryable: false });
expect(
withFailureEffect(createFailure("AUTH_REQUIRED", "CREATE", 0), "MAYBE_APPLIED"),
).toMatchObject({ action: "reauth", retryable: false });
// Every other kind still sends an unknown effect to support.
expect(
createFailure("FORBIDDEN", "CREATE", 0, { effect: "MAYBE_APPLIED" }),
).toMatchObject({ action: "contact-support" });
});
it("never marks a failure retryable once the write may or did take effect (07-04)", () => {
expect(ERROR_REGISTRY.SERVER_FAILURE.defaultRetryable).toBe(true);
expect(createFailure("SERVER_FAILURE", "CREATE", 0).retryable).toBe(true);
expect(
createFailure("SERVER_FAILURE", "CREATE", 0, { effect: "MAYBE_APPLIED" }),
).toMatchObject({ retryable: false, action: "contact-support" });
expect(
createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "APPLIED_CONFIRMED",
}),
).toMatchObject({ retryable: false, action: "none" });
expect(
createFailure("SERVER_FAILURE", "CREATE", 0, { effect: "NOT_APPLIED" })
.retryable,
).toBe(true);
});
it("projects only allowlisted safe fields", () => {
const untrustedDetails = {
code: "TEMPORARY",
@@ -63,6 +89,31 @@ describe("frontend failure classification", () => {
expect(JSON.stringify(result)).not.toMatch(/stack|body|Bearer|secret/);
});
it("bounds validation metadata even for direct failure callers", () => {
const oversizedPath = "p".repeat(121);
const oversizedCode = "C".repeat(81);
const validationIssues = [
{ path: oversizedPath, code: "TOO_LONG_PATH" },
{ path: "field", code: oversizedCode },
...Array.from({ length: 100 }, (_, index) => ({
path: `field.${index}`,
code: "INVALID",
})),
];
const result = createFailure("VALIDATION_REJECTED", "SAVE_ENTITY", 0, {
validationIssues,
});
expect(result.validationIssues).toHaveLength(50);
expect(result.validationIssues?.[0]).toEqual({
path: "field.0",
code: "INVALID",
});
expect(JSON.stringify(result.validationIssues)).not.toContain(oversizedPath);
expect(JSON.stringify(result.validationIssues)).not.toContain(oversizedCode);
});
it("normalizes any thrown value without leaking it", () => {
const secret = { token: "sensitive", nested: { rawBody: "private" } };
const result = normalizeUnknownFailure(secret);
@@ -3,7 +3,9 @@ import { describe, expect, it } from "vitest";
import {
ContractContributionError,
composeContractContributions,
invokeValidator,
type InstalledContractContribution,
type RuntimeValidator,
} from "../../src/contracts/external-contract-runtime.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
@@ -83,3 +85,34 @@ describe("external contract contribution composition", () => {
expect(error.reason).toContain("method");
});
});
describe("validator invocation (07-06)", () => {
const returning = (result: unknown): RuntimeValidator<unknown> => ({
schemaId: "Malformed",
safeParse: () => result as never,
});
it.each([
["non-array issues", { success: false, issues: 5 }],
["object issues", { success: false, issues: {} }],
["non-boolean success", { success: "no", data: "unchecked" }],
["throwing issues getter", {
success: false,
get issues(): never {
throw new Error("hostile");
},
}],
])("reports THROWN for a result with %s", (_label, result) => {
expect(invokeValidator(returning(result), {})).toEqual({ outcome: "THROWN" });
});
it("keeps well-formed results", () => {
expect(invokeValidator(returning({ success: true, data: 1 }), {})).toEqual({
outcome: "VALID",
value: 1,
});
expect(
invokeValidator(returning({ success: false, issues: [{ path: [], code: "X" }] }), {}),
).toEqual({ outcome: "INVALID", issues: [{ path: [], code: "X" }] });
});
});
@@ -0,0 +1,126 @@
import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { COMPILED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts";
import { generateRuntimeConfig } from "../../scripts/generate-runtime-config.ts";
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
// 09-09. An override key this build does not declare stays inert (one runtime
// document may serve several builds), but a misspelt kill switch used to leave
// the feature running without a trace.
const MISSPELT = "reference-featrue";
function runtimeWith(overrides: Readonly<Record<string, "DISABLED">>): Runtime {
return {
config: {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
REQUEST_TIMEOUT_MS: 1000,
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: overrides,
// This product's runtime config also selects the TechLog sources.
TECH_LOG_STUDIO_SOURCE: "MOCK",
TECH_LOG_PUBLIC_SOURCE: "MOCK",
},
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
};
}
const 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: {},
} as Parameters<typeof createRuntimeAdapters>[0]["release"];
describe("unknown feature override keys (09-09)", () => {
it("records one diagnostic per key the build does not declare", async () => {
const declared = COMPILED_PRODUCT_FEATURE_IDS[0];
const adapters = await createRuntimeAdapters({
runtime: runtimeWith({
[MISSPELT]: "DISABLED",
...(declared === undefined ? {} : { [declared]: "DISABLED" }),
}),
release,
host: {},
});
try {
const unknown = adapters.outputPorts.diagnostics
.entries()
.filter((entry) => entry.eventId === "feature.override.unknown");
expect(unknown).toEqual([
expect.objectContaining({
level: "warn",
context: { feature_override_key: MISSPELT },
}),
]);
} finally {
adapters.infrastructure.dispose();
}
});
it("warns in the admission record without refusing the artifact", async () => {
const root = await mkdtemp(path.join(tmpdir(), "admission-override-"));
try {
const config = await generateRuntimeConfig("local", {});
await mkdir(path.join(root, "dist"), { recursive: true });
await writeFile(
path.join(root, "dist/config.json"),
JSON.stringify({ ...config, FEATURE_OVERRIDES: { [MISSPELT]: "DISABLED" } }),
);
const result = spawnSync(
process.execPath,
[path.resolve("scripts/check-release-admission.ts")],
{
cwd: root,
encoding: "utf8",
env: { ...process.env, APP_PROFILE: "local", RELEASE_TARGET: "local" },
},
);
expect(result.status, result.stderr).toBe(0);
expect(result.stderr).toContain(MISSPELT);
const record = JSON.parse(
await readFile(path.join(root, "artifacts/release/deployment-admission.json"), "utf8"),
) as { status: string; warnings: { field: string; reason: string }[] };
expect(record.status).toBe("ADMITTED");
expect(record.warnings).toEqual([
expect.objectContaining({ field: `FEATURE_OVERRIDES.${MISSPELT}` }),
]);
} finally {
await rm(root, { recursive: true, force: true });
}
});
});
@@ -0,0 +1,20 @@
import { spawnSync } from "node:child_process";
import { describe, expect, it } from "vitest";
// 09-07 (D-10). The removal gate takes the feature to remove as an argument
// instead of hard-coding the sample; an id no feature declares stops it before
// any fixture is built.
describe("feature removal argument", () => {
it("refuses a feature id that no installed feature declares", () => {
const run = spawnSync(
process.execPath,
["scripts/test-sample-removal.ts", "--feature=missing-feature"],
{ encoding: "utf8" },
);
expect(run.status).not.toBe(0);
expect(run.stderr).toMatch(
/No installed feature declares FEATURE_MODULE_ID "missing-feature"/u,
);
});
});
+128
View File
@@ -0,0 +1,128 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import {
FEATURE_SHAPE_BASELINE_PATH,
FEATURE_SHAPE_CEILINGS_PATH,
renameReferenceFeature,
} from "../../scripts/scale/measure-feature-shape-growth.ts";
import { APP_MAX_CONTEXTS } from "../../src/apps/template-app/app-module.ts";
import { CONTEXT_MAX_FEATURES } from "../../src/contexts/reference-context/context-module.ts";
/**
* 11-04 (D-18). The scale evidence used to come from stub features that only
* differ by name, so the cost of one app growing towards its declared ceiling
* (20 contexts x 200 features) was never measured. The committed baseline is a
* measurement with copies of the real reference feature.
*/
const context = { id: "shape-context-0", routeRoot: "shape-0" } as const;
type Run = Readonly<{
addedFeatures: number;
routes: number;
tsc: Readonly<{ passed: boolean; instantiations: number; wallMs: number }>;
build: Readonly<{
wallMs: number;
initialJavascriptGzipBytes: number;
lazyJavascriptFiles: number;
}>;
loadBefore: readonly number[];
}>;
describe("feature-shape growth measurement (11-04)", () => {
it("renames every feature-owned identifier of a reference copy", () => {
const source = [
'featureId: "reference-feature"',
'path: "/examples/reference-resources/:id"',
"REFERENCE_RESOURCE_LIST",
"ReferenceResourcePage",
'contextId: "reference-context"',
'topic: "qinv.01k10f7m3w9p6r2c8v5n4x"',
"NoRequest",
].join("\n");
const renamed = renameReferenceFeature(source, "s007", context);
expect(renamed).not.toMatch(/reference/iu);
expect(renamed).toContain('featureId: "s007-feature"');
expect(renamed).toContain('path: "/shape-0/s007-resources/:id"');
expect(renamed).toContain("S007_RESOURCE_LIST");
expect(renamed).toContain("S007ResourcePage");
expect(renamed).toContain('contextId: "shape-context-0"');
expect(renamed).toContain('topic: "qinv.shape.s007"');
expect(renamed).toContain("S007NoRequest");
});
it("keeps platform-owned names that only contain the word", () => {
const source =
"REFERENCE_EXTERNAL_BEARER REFERENCE_FEATURE_V1 supportReference";
expect(renameReferenceFeature(source, "s001", context)).toBe(source);
});
it("commits a baseline measured at 25 and 100 real-shape features, twice each", async () => {
const baseline = JSON.parse(
await readFile(FEATURE_SHAPE_BASELINE_PATH, "utf8"),
) as Readonly<{
environment: Readonly<Record<string, unknown>>;
runs: readonly Run[];
}>;
expect(baseline.environment).toMatchObject({
cpuModel: expect.any(String),
logicalCpus: expect.any(Number),
});
const bySize = (size: number) =>
baseline.runs.filter((run) => run.addedFeatures === size);
const [origin] = bySize(0);
expect(origin?.tsc.passed).toBe(true);
for (const size of [25, 100]) {
const runs = bySize(size);
// A failed typecheck is the result and is not repeated.
expect(runs.length).toBeGreaterThanOrEqual(runs[0]?.tsc.passed ? 2 : 1);
for (const run of runs) {
// Every copy contributes the reference feature's own routes.
expect((run.routes - origin!.routes) % size).toBe(0);
expect(run.routes).toBeGreaterThan(origin!.routes);
expect(run.build.lazyJavascriptFiles).toBeGreaterThan(
origin!.build.lazyJavascriptFiles,
);
expect(run.loadBefore).toHaveLength(3);
}
// Compiler counts are deterministic; only times vary with the host.
expect(new Set(runs.map((run) => run.tsc.instantiations)).size).toBe(1);
}
});
it("states in the committed rationale what the ceilings rest on", async () => {
// The rationale lives next to the baseline, not in a review document: the
// history documents may be deleted after copying (README.md).
const rationale = JSON.parse(
await readFile(FEATURE_SHAPE_CEILINGS_PATH, "utf8"),
) as Readonly<{
baseline: string;
ceilings: Readonly<{ contextMaxFeatures: number; appMaxContexts: number }>;
axes: readonly Readonly<Record<string, string>>[];
}>;
expect(rationale.baseline).toBe(FEATURE_SHAPE_BASELINE_PATH);
expect(rationale.ceilings).toEqual({
contextMaxFeatures: CONTEXT_MAX_FEATURES,
appMaxContexts: APP_MAX_CONTEXTS,
});
expect(rationale.axes.map((row) => row.axis)).toEqual(
expect.arrayContaining([
"Typecheck of one app",
"Production build",
"Initial JavaScript",
"Lazy JavaScript",
"Routes",
]),
);
for (const row of rationale.axes) {
for (const column of ["axis", "verified", "condition", "notVerified"])
expect(row[column], `${row.axis}.${column}`).toMatch(/\S/u);
}
});
});
+202 -4
View File
@@ -1,10 +1,24 @@
import { mkdtemp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { spawnSync } from "node:child_process";
import {
copyFile,
lstat,
mkdtemp,
mkdir,
readdir,
readFile,
rm,
stat,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { afterEach, describe, expect, it } from "vitest";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
import {
FIXTURE_PNPM_ENVIRONMENT,
linkFixtureNodeModules,
} from "../../scripts/lib/fixture-node-modules.ts";
/**
* A removal or provider fixture runs `pnpm` inside a throwaway copy of the
@@ -69,12 +83,71 @@ describe("fixture node_modules linking", () => {
}
});
// pnpm rewrites `.pnpm-workspace-state-v1.json` in place when it runs inside
// the fixture. Through a symlink that write landed in the repository's own
// state file, so the next pnpm command there re-verified the install.
it("copies the pnpm state files instead of linking them", async () => {
const source = await sourceTree();
const fixture = await mkdtemp(path.join(tmpdir(), "fixture-root-"));
const stateFiles = [".modules.yaml", ".package-map.json", ".pnpm-workspace-state-v1.json"];
try {
for (const file of stateFiles) {
await writeFile(path.join(source, "node_modules", file), `{"projects":{"${source}":{}}}\n`);
}
await linkFixtureNodeModules(fixture, source);
for (const file of stateFiles) {
const copied = path.join(fixture, "node_modules", file);
expect((await lstat(copied)).isSymbolicLink(), file).toBe(false);
await writeFile(copied, `{"projects":{"${fixture}":{}}}\n`);
expect(await readFile(path.join(source, "node_modules", file), "utf8"), file)
.toBe(`{"projects":{"${source}":{}}}\n`);
}
} finally {
await rm(source, { recursive: true, force: true });
await rm(fixture, { recursive: true, force: true });
}
});
// A copied state file still names the repository as the validated project,
// so pnpm inside the fixture re-verified the install and started one through
// the linked directories. Pointing it at the fixture keeps pnpm from
// installing into a tree whose packages are shared with the repository.
it("points the copied workspace state at the fixture root", async () => {
const source = await sourceTree();
const fixture = await mkdtemp(path.join(tmpdir(), "fixture-root-"));
const statePath = ".pnpm-workspace-state-v1.json";
try {
await writeFile(
path.join(source, "node_modules", statePath),
JSON.stringify({
lastValidatedTimestamp: 1,
projects: { [source]: { name: "template", version: "0.1.0" } },
settings: { dev: true },
}),
);
const before = Date.now();
await linkFixtureNodeModules(fixture, source);
const state = JSON.parse(
await readFile(path.join(fixture, "node_modules", statePath), "utf8"),
);
expect(state.projects).toEqual({
[fixture]: { name: "template", version: "0.1.0" },
});
expect(state.lastValidatedTimestamp).toBeGreaterThanOrEqual(before);
expect(state.settings).toEqual({ dev: true });
} finally {
await rm(source, { recursive: true, force: true });
await rm(fixture, { recursive: true, force: true });
}
});
it("creates node_modules as a real directory, never a symlink", async () => {
const source = await sourceTree();
const fixture = await mkdtemp(path.join(tmpdir(), "fixture-root-"));
try {
await linkFixtureNodeModules(fixture, source);
const { lstat } = await import("node:fs/promises");
const entry = await lstat(path.join(fixture, "node_modules"));
expect(entry.isSymbolicLink()).toBe(false);
expect(entry.isDirectory()).toBe(true);
@@ -87,3 +160,128 @@ describe("fixture node_modules linking", () => {
}
});
});
/**
* F-4. pnpm 11 verifies the install before it runs a script and, finding the
* fixture's copied state unfamiliar, installs. `.pnpm` and `.bin` are
* directory links into the repository's own node_modules, so that install
* rewrote the shared `.pnpm/lock.yaml` and bin shims. A fixture launched
* through `pnpm <script>` inherited `pnpm_config_verify_deps_before_run=false`
* from pnpm and was safe; the same fixture started directly
* (`node scripts/run-vitest.ts run <file>`) was not.
*/
describe("pnpm inside a linked fixture (F-4)", () => {
const scratch: string[] = [];
afterEach(async () => {
await Promise.all(
scratch.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
/** A tiny installed workspace standing in for the repository, offline. */
async function installedSource() {
const root = await mkdtemp(path.join(tmpdir(), "fixture-pnpm-"));
scratch.push(root);
const tool = path.join(root, "tool");
const source = path.join(root, "source");
await mkdir(tool, { recursive: true });
await mkdir(source, { recursive: true });
await writeFile(
path.join(tool, "package.json"),
JSON.stringify({ name: "tool", version: "1.0.0", bin: { tool: "cli.js" } }),
);
await writeFile(path.join(tool, "cli.js"), "#!/usr/bin/env node\n");
await writeFile(
path.join(source, "package.json"),
JSON.stringify({
name: "fixture-source",
version: "1.0.0",
private: true,
packageManager: "pnpm@11.17.0",
scripts: { hello: "echo hello-from-fixture" },
dependencies: { tool: "file:../tool" },
}),
);
await writeFile(path.join(source, "pnpm-workspace.yaml"), "allowBuilds: {}\n");
const environment: NodeJS.ProcessEnv = {
...pnpmFreeEnvironment(),
pnpm_config_store_dir: path.join(root, "store"),
};
// Installed on a developer machine (no CI); the fixtures then run pnpm
// with CI=true, which pnpm reads as different settings and reinstalls.
const { CI: _ci, ...developer } = environment;
const install = spawnSync("corepack", ["pnpm", "install", "--offline"], {
cwd: source,
encoding: "utf8",
env: developer,
});
expect(install.status, install.stdout + install.stderr).toBe(0);
return { root, source, environment };
}
// The test runner itself may run under pnpm, which exports the setting.
function pnpmFreeEnvironment(): NodeJS.ProcessEnv {
const environment: NodeJS.ProcessEnv = { ...process.env, CI: "true" };
delete environment.pnpm_config_verify_deps_before_run;
return environment;
}
async function sharedState(source: string) {
const lock = await stat(path.join(source, "node_modules/.pnpm/lock.yaml"));
const bin = await stat(path.join(source, "node_modules/.bin/tool"));
return [lock.mtimeMs, lock.ino, bin.mtimeMs, bin.ino];
}
async function runInFixture(
root: string,
source: string,
environment: NodeJS.ProcessEnv,
) {
const fixture = path.join(root, `fixture-${scratch.length}-${Date.now()}`);
await mkdir(fixture);
for (const file of ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"]) {
await copyFile(path.join(source, file), path.join(fixture, file));
}
await linkFixtureNodeModules(fixture, source);
const before = await sharedState(source);
const result = spawnSync("corepack", ["pnpm", "hello"], {
cwd: fixture,
encoding: "utf8",
env: environment,
});
return { result, changed: (await sharedState(source)).join() !== before.join() };
}
it("installs through the linked directories unless told not to", async () => {
const { root, source, environment } = await installedSource();
// The hazard: the default re-verification installs into the shared tree.
expect((await runInFixture(root, source, environment)).changed).toBe(true);
const guarded = await runInFixture(root, source, {
...environment,
...FIXTURE_PNPM_ENVIRONMENT,
});
expect(guarded.result.status, guarded.result.stderr).toBe(0);
expect(guarded.result.stdout).toContain("hello-from-fixture");
expect(guarded.changed).toBe(false);
}, 60_000);
it("is used by every fixture that links node_modules and runs pnpm", async () => {
const listed = spawnSync(
"git",
["grep", "-l", "linkFixtureNodeModules(", "--", "scripts", "tests"],
{ encoding: "utf8" },
);
expect(listed.status, listed.stderr).toBe(0);
const offenders: string[] = [];
for (const file of listed.stdout.trim().split("\n")) {
if (file === "scripts/lib/fixture-node-modules.ts") continue;
if (file === "tests/unit/fixture-node-modules.test.ts") continue;
const source = await readFile(file, "utf8");
const runsPnpm = /\["pnpm"|\[pnpmCli\b/u.test(source);
if (runsPnpm && !source.includes("FIXTURE_PNPM_ENVIRONMENT")) offenders.push(file);
}
expect(offenders).toEqual([]);
});
});
+72 -1
View File
@@ -1,6 +1,56 @@
import { describe, expect, it } from "vitest";
import { classifyLiveHostingBaseUrl } from "../../scripts/lib/hosting-probe.ts";
import {
checkPublicServiceWorkers,
classifyLiveHostingBaseUrl,
hostingVerdict,
servedEntryScript,
} from "../../scripts/lib/hosting-probe.ts";
describe("public service worker in dist", () => {
const app = ["index.html", "config.json", "assets/index-abc.js"];
const active = {
mode: "ACTIVE",
scriptPath: "service-worker.js",
handlers: ["PWA_STATIC_ASSETS"],
} as const;
const removal = { mode: "REMOVE_REGISTRATION", scriptPath: "service-worker.js" } as const;
const purge = { mode: "PURGE_OWNED_RESOURCES", scriptPath: "service-worker.js" } as const;
it("accepts the selected worker when the selection is ACTIVE", () => {
expect(
checkPublicServiceWorkers([...app, "service-worker.js"], active),
).toMatchObject({ expected: true, observed: true, passed: true });
});
// 06-03 (D-5). REMOVE_REGISTRATION ships the self-unregistering worker.
it("accepts the selected worker when the selection is REMOVE_REGISTRATION", () => {
expect(
checkPublicServiceWorkers([...app, "service-worker.js"], removal),
).toMatchObject({ expected: true, observed: true, passed: true });
});
it("accepts a worker-free dist when no worker is selected", () => {
expect(checkPublicServiceWorkers(app, null)).toMatchObject({
expected: false,
passed: true,
});
});
it.each([
["no selection", [...app, "service-worker.js"], null],
["a PURGE_OWNED_RESOURCES selection", [...app, "service-worker.js"], purge],
["REMOVE_REGISTRATION without the worker", app, removal],
["ACTIVE without the worker", app, active],
["ACTIVE with an extra worker", [...app, "service-worker.js", "assets/sw.js"], active],
["ACTIVE with the worker off the root", [...app, "assets/service-worker.js"], active],
] as const)("rejects %s", (_, files, selection) => {
expect(checkPublicServiceWorkers(files, selection)).toMatchObject({
passed: false,
reason: expect.stringContaining("dist worker scripts"),
});
});
});
describe("live hosting evidence target", () => {
it("accepts a canonical production HTTPS root", () => {
@@ -25,3 +75,24 @@ describe("live hosting evidence target", () => {
});
});
});
// 13-05 (D-14). The declared-header fixture proves nothing about hosting, so it
// is UNVERIFIED, and a live probe checks the release actually served.
describe("hosting header verdict", () => {
it("passes only a live probe of the deployed release", () => {
expect(hostingVerdict("live", true)).toBe("PASS");
expect(hostingVerdict("fixture", true)).toBe("UNVERIFIED");
expect(hostingVerdict("fixture", false)).toBe("FAIL");
expect(hostingVerdict("invalid-live", false)).toBe("FAIL");
expect(hostingVerdict("live", false)).toBe("FAIL");
});
it("probes the entry script named by the served index.html", () => {
expect(
servedEntryScript(
'<head><link rel="modulepreload" href="/assets/a-1.js"><script type="module" crossorigin src="/app/assets/index-Dpjd89Th.js"></script></head>',
),
).toBe("/app/assets/index-Dpjd89Th.js");
expect(servedEntryScript("<html><body>maintenance</body></html>")).toBeNull();
});
});
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from "vitest";
import {
admitCredentialHeaders,
checkFinalInvariants,
projectRequest,
} from "../../src/adapters/http/http-contract-bridge.ts";
import { TEST_DETAIL_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
const BEARER_PROFILE = Object.freeze({
authProfileId: "TEST_BEARER",
transport: "BEARER_HEADER" as const,
credentials: "omit" as const,
allowedCredentialHeaders: Object.freeze(["authorization" as const]),
requiredCredentialHeaders: Object.freeze(["authorization" as const]),
});
describe("credential header admission", () => {
it.each([
["NUL", "Bearer abc\u0000def"],
["non-Latin-1", "Bearer 한"],
["tab", "Bearer abc\tdef"],
["DEL", "Bearer abc\u007fdef"],
["C1 control", "Bearer abc\u0085def"],
["CR/LF", "Bearer abc\r\nX-Evil: 1"],
])("rejects a %s value before any header object is built", (_label, value) => {
expect(
admitCredentialHeaders({ authorization: value }, BEARER_PROFILE),
).toEqual({ ok: false, failure: "CREDENTIAL_HEADER_VALUE_INVALID" });
});
it("admits an ordinary bearer token", () => {
const token = "Bearer eyJhbGciOi.J9-abc_DEF~+/=";
expect(
admitCredentialHeaders({ Authorization: token }, BEARER_PROFILE),
).toEqual({ ok: true, headers: { authorization: token } });
});
it("rejects names that differ only in case", () => {
expect(
admitCredentialHeaders(
{ Authorization: "Bearer a", authorization: "Bearer b" },
BEARER_PROFILE,
).ok,
).toBe(false);
});
});
describe("final request invariants", () => {
it("fails before dispatch when Fetch would reject a header value", () => {
const request = Object.freeze({
url: "https://api.test/base/x",
method: "POST",
bodyBytes: null,
});
const init: RequestInit = {
method: "POST",
redirect: "error",
credentials: "omit",
};
expect(
checkFinalInvariants({
request,
expectedMethod: "POST",
baseUrl: "https://api.test/base/",
init,
headers: {
authorization: "Bearer ok",
"Idempotency-Key": "키",
},
requestByteLimit: 0,
deadlineRemainingMs: 1_000,
scopeIsCurrent: true,
authProfile: BEARER_PROFILE,
}),
).toBe("HEADER_VALUE_INVALID");
});
});
describe("descriptor-driven path projection", () => {
it.each([".", ".."])(
"rejects the dot segment %j instead of letting URL resolution move the target",
(entityId) => {
expect(
projectRequest(
TEST_DETAIL_HTTP_CONTRACT,
{ entityId },
"https://api.test/base/",
),
).toEqual({ ok: false, failure: "PATH_VALUE_INVALID" });
},
);
it("still encodes an ordinary value containing dots", () => {
const outcome = projectRequest(
TEST_DETAIL_HTTP_CONTRACT,
{ entityId: "..a." },
"https://api.test/base/",
);
expect(outcome.ok && outcome.request.url).toBe(
"https://api.test/base/api/test-entities/..a.",
);
});
});
+564 -1
View File
@@ -1,7 +1,19 @@
import { describe, expect, it, vi } from "vitest";
import { createContractHttpExecutor } from "../../src/adapters/http/http-execution-v3.ts";
import {
createFeatureHttpBinding,
defineFeatureHttpOperation,
} from "../../src/adapters/http/feature-http-binding.ts";
import {
createContractHttpExecutor,
type HttpExecutionObservation,
} from "../../src/adapters/http/http-execution-v3.ts";
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
import type { InstalledHttpContract } from "../../src/contracts/external-contract-runtime.ts";
import {
createExecutionContext,
type ExecutionContext,
} from "../../src/platform/execution/execution-context.ts";
import {
TEST_CREATE_HTTP_CONTRACT,
TEST_LIST_HTTP_CONTRACT,
@@ -137,6 +149,32 @@ describe("runtime request deadline ceiling", () => {
});
describe("descriptor-driven HTTP execution lifetime", () => {
it("tells a missing credential apart from a server 401", async () => {
const refusedFetcher = vi.fn();
const refused = await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "UNAUTHENTICATED" }),
fetcher: refusedFetcher,
}).execute(installed, { limit: 20 }, { routeId: ROUTE_ID, scope });
const rejected = await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher: async () => new Response(null, { status: 401 }),
}).execute(installed, { limit: 20 }, { routeId: ROUTE_ID, scope });
// Only the server's answer carries response metadata; the composition
// root reports just that one to the session owner.
expect(refusedFetcher).not.toHaveBeenCalled();
expect(refused).toEqual({ kind: "UNAUTHENTICATED", effect: "NOT_APPLICABLE" });
expect(rejected).toMatchObject({
kind: "UNAUTHENTICATED",
effect: "NOT_APPLICABLE",
metadata: { status: 401 },
});
});
it("normalizes a read-side 429 to the non-applicable effect vocabulary", async () => {
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
@@ -751,3 +789,528 @@ describe("descriptor-driven HTTP execution lifetime", () => {
});
});
});
/**
* R-3.3. A gateway 5xx/408 with an HTML, empty or broken body is a server
* outage. It must keep its status and stay retryable instead of surfacing as a
* "contact support" contract breach.
*/
describe("gateway failures without a usable problem body", () => {
it.each([
[502, "text/html", "<html>Bad Gateway</html>"],
[503, "application/json", ""],
[504, "application/json", "{"],
[408, "text/plain", "timeout"],
])(
"ends a %i response as a retryable server failure with its status",
async (status, contentType, body) => {
const fetcher = vi.fn(
async () =>
new Response(body, { status, headers: { "content-type": contentType } }),
);
const observations: HttpExecutionObservation[] = [];
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 1,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher,
sleep: async () => {},
observe: (observation) => void observations.push(observation),
});
const list = defineFeatureHttpOperation({
contract: TEST_LIST_HTTP_CONTRACT,
routeId: ROUTE_ID,
mapSuccess: (value) => mappingSuccess(value),
});
const binding = createFeatureHttpBinding(
{
execute: (contract, input, context) =>
executor.execute(contract, input, { ...context, scope }),
},
{ [list.operationId]: list },
);
const result = await binding.execute(list.operationId, { limit: 20 });
expect(fetcher).toHaveBeenCalledTimes(2);
expect(observations.at(-1)?.status).toBe(status);
expect(result).toMatchObject({
ok: false,
error: {
kind: "SERVER_FAILURE",
httpStatus: status,
retryable: true,
action: "retry",
},
});
},
);
});
/**
* Q-6.3-6. Every wait the lifetime signal can end reports its owner the same
* way: the caller cancels, the deadline times out, and a scope fence ends as a
* scope abort — a transport abort before response headers, the stale-generation
* violation after them. A fence during a retry backoff used to read as TIMEOUT.
*/
describe("terminal owner classification at every wait", () => {
const phases = [
"credentials",
"lease",
"dispatch",
"transport backoff",
"admission",
"retry backoff",
] as const;
type Phase = (typeof phases)[number];
type Owner = "CALLER" | "SCOPE_FENCE" | "DEADLINE";
const hang = () => new Promise<never>(() => {});
async function endWaitAt(phase: Phase, owner: Owner) {
const caller = new AbortController();
const fence = new AbortController();
const fencedScope = Object.freeze({
...scope,
signal: fence.signal,
isCurrent: () => !fence.signal.aborted,
});
let reached = false;
const reach = () => {
reached = true;
};
let execution: ExecutionContext | undefined;
if (phase === "lease") {
execution = createExecutionContext({
interactionId: "held-lease",
deadlineMs: 10_000,
traffic: {
maxPhysicalRequests: 4,
maxRetries: 2,
maxConcurrentRequests: 1,
maxQueuedRequests: 1,
},
});
await execution.traffic.concurrency.acquire(new AbortController().signal);
}
const observations: HttpExecutionObservation[] = [];
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 2,
attachCredentials: () =>
phase === "credentials"
? (reach(), hang())
: { kind: "READY", headers: {} },
fetcher: vi.fn(async () => {
switch (phase) {
case "transport backoff":
throw new TypeError("network down");
case "admission":
return new Response(
new ReadableStream<Uint8Array>({
pull: () => (reach(), hang()),
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
case "retry backoff":
return Response.json(
{ type: "about:blank", title: "temporary", status: 503 },
{ status: 503 },
);
default:
reach();
return hang();
}
}),
sleep: () => (reach(), hang()),
random: () => 0,
observe: (observation) => void observations.push(observation),
});
const pending = executor.execute(
operation({ deadlineMs: owner === "DEADLINE" ? 30 : 10_000 }),
{ limit: 20 },
{
routeId: ROUTE_ID,
scope: fencedScope,
signal: caller.signal,
...(execution === undefined ? {} : { execution }),
},
);
if (owner !== "DEADLINE") {
await vi.waitFor(() =>
expect(reached || execution?.traffic.concurrency.queued === 1).toBe(
true,
),
);
(owner === "CALLER" ? caller : fence).abort();
}
const outcome = await pending;
return {
outcome,
cancellationOwner: observations.at(-1)?.cancellationOwner,
};
}
it.each(phases)(
"cancels at the %s wait when the caller aborts",
async (phase) => {
await expect(endWaitAt(phase, "CALLER")).resolves.toMatchObject({
outcome: { kind: "CANCELLED", effect: "NOT_STARTED" },
cancellationOwner: "CALLER",
});
},
);
it.each(phases)(
"times out at the %s wait when the deadline fires",
async (phase) => {
await expect(endWaitAt(phase, "DEADLINE")).resolves.toMatchObject({
outcome: { kind: "TRANSPORT_FAILURE", failure: { kind: "TIMEOUT" } },
cancellationOwner: "DEADLINE",
});
},
);
it.each(phases)(
"ends the %s wait as a scope abort when the scope is fenced",
async (phase) => {
await expect(endWaitAt(phase, "SCOPE_FENCE")).resolves.toMatchObject({
outcome:
phase === "admission"
? {
kind: "CONTRACT_VIOLATION",
violation: { kind: "SCOPE_FENCED" },
}
: {
kind: "TRANSPORT_FAILURE",
failure: { kind: "ABORTED_BY_SCOPE" },
},
cancellationOwner: "SCOPE_FENCE",
});
},
);
});
/**
* 10-03. The executor, not only the pure rule, must read the contract's retry
* semantics: a KEYED command with budget left retries a send that never left,
* and never replays one that was dispatched.
*/
describe("KEYED retry budget through the executor", () => {
const keyedWithBudget: InstalledHttpContract<unknown, unknown, unknown> = {
...createInstalled,
frontend: { ...createInstalled.frontend, retryBudget: 2 as const },
};
function keyedExecutor(fetcher: typeof fetch) {
return createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 2,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher,
sleep: async () => {},
random: () => 0,
});
}
it("retries a KEYED send that failed before dispatch, with the same key", async () => {
const keys: (string | null)[] = [];
const fetcher = vi.fn<typeof fetch>((_input, init) => {
keys.push(new Headers(init?.headers).get("idempotency-key"));
if (keys.length === 1) throw new TypeError("fetch refused to start");
return Promise.resolve(
Response.json({ id: "created", name: "created" }, { status: 201 }),
);
});
const outcome = await keyedExecutor(fetcher).execute(
keyedWithBudget,
{ name: "created" },
{ routeId: ROUTE_ID, scope, intent: mutationIntent() },
);
expect(fetcher).toHaveBeenCalledTimes(2);
expect(keys).toEqual(["key-1", "key-1"]);
expect(outcome).toMatchObject({
kind: "SUCCESS",
effect: "APPLIED_CONFIRMED",
});
});
it("does not replay a dispatched KEYED send even with budget left", async () => {
const fetcher = vi.fn<typeof fetch>(async () => {
throw new TypeError("connection reset");
});
const outcome = await keyedExecutor(fetcher).execute(
keyedWithBudget,
{ name: "created" },
{ routeId: ROUTE_ID, scope, intent: mutationIntent() },
);
expect(fetcher).toHaveBeenCalledOnce();
expect(outcome).toMatchObject({
kind: "TRANSPORT_FAILURE",
effect: "MAYBE_APPLIED",
});
});
});
/**
* 03-03. A support reference must reach the server log: every logical
* execution sends one request id, and a failure carries the server's echoed
* `x-correlation-id` as `requestId`.
*/
describe("request correlation", () => {
it("sends one request id per logical execution, shared by its retries", async () => {
const sent: (string | null)[] = [];
const fetcher = vi.fn<typeof fetch>(async (_input, init) => {
sent.push(new Headers(init?.headers).get("x-correlation-id"));
return sent.length === 1
? new Response(null, { status: 503 })
: Response.json([{ id: "a", name: "A" }]);
});
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 2,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher,
sleep: async () => {},
random: () => 0,
});
const retried = {
...installed,
frontend: { ...installed.frontend, retryBudget: 1 as const },
};
await executor.execute(retried, { limit: 20 }, { routeId: ROUTE_ID, scope });
await executor.execute(retried, { limit: 20 }, { routeId: ROUTE_ID, scope });
expect(sent).toHaveLength(3);
expect(sent[0]).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u);
expect(sent[1]).toBe(sent[0]);
expect(sent[2]).not.toBe(sent[0]);
});
it("still sends the request when no request id can be made", async () => {
const fetcher = vi.fn<typeof fetch>(async () =>
Response.json([{ id: "a", name: "A" }]),
);
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher,
createRequestId: () => {
throw new TypeError("randomUUID needs a secure context");
},
});
const outcome = await executor.execute(installed, { limit: 20 }, {
routeId: ROUTE_ID,
scope,
});
expect(outcome.kind).toBe("SUCCESS");
expect(
new Headers(fetcher.mock.calls[0]?.[1]?.headers).get("x-correlation-id"),
).toBeNull();
});
it.each([
["a problem", 400, { type: "about:blank", title: "rejected", status: 400 }],
["an unauthenticated answer", 401, null],
["a forbidden answer", 403, null],
["a rate limit", 429, null],
["a gateway outage", 504, null],
] as const)("carries the server correlation id on %s", async (_label, status, body) => {
const observations: HttpExecutionObservation[] = [];
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher: vi.fn(async () =>
body === null
? new Response(null, {
status,
headers: { "x-correlation-id": "server-ref-42" },
})
: Response.json(body, {
status,
headers: { "x-correlation-id": "server-ref-42" },
}),
),
observe: (observation) => observations.push(observation),
});
const list = defineFeatureHttpOperation({
contract: TEST_LIST_HTTP_CONTRACT,
routeId: ROUTE_ID,
mapSuccess: (value) => mappingSuccess(value),
});
const binding = createFeatureHttpBinding(
{
execute: (contract, input, context) =>
executor.execute(contract, input, { ...context, scope }),
},
{ [list.operationId]: list },
);
const result = await binding.execute(list.operationId, { limit: 20 });
expect(result).toMatchObject({
ok: false,
error: { requestId: "server-ref-42" },
});
expect(observations.at(-1)?.correlationId).toBe("server-ref-42");
});
});
/**
* D-2 (03-02). 401, 403 and 429 are admitted before any problem body is read.
* The package may classify them by status; without a classifier, or when it
* misbehaves, a dispatched command stays MAYBE_APPLIED.
*/
describe("command status classification", () => {
function withStatusClassifier(
classifyStatus: ((status: 401 | 403 | 429) => unknown) | undefined,
): InstalledHttpContract<unknown, unknown, unknown> {
return {
...createInstalled,
contract: {
...createInstalled.contract,
commandEffect: {
...createInstalled.contract.commandEffect!,
...(classifyStatus === undefined ? {} : { classifyStatus }),
} as NonNullable<typeof createInstalled.contract.commandEffect>,
},
};
}
async function effectFor(
status: number,
contract: InstalledHttpContract<unknown, unknown, unknown>,
) {
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher: vi.fn(async () => new Response(null, { status })),
});
const outcome = await executor.execute(
contract,
{ name: "created" },
{ routeId: ROUTE_ID, scope, intent: mutationIntent() },
);
return { kind: outcome.kind, effect: outcome.effect };
}
it.each([
[401, "UNAUTHENTICATED"],
[403, "FORBIDDEN"],
[429, "RATE_LIMITED"],
] as const)("uses the package classifier for %i", async (status, kind) => {
const classifyStatus = vi.fn(() => "NOT_APPLIED");
await expect(
effectFor(status, withStatusClassifier(classifyStatus)),
).resolves.toEqual({ kind, effect: "NOT_APPLIED" });
expect(classifyStatus).toHaveBeenCalledWith(status);
});
const throwingClassifier = (): unknown => {
throw new Error("package defect");
};
const unknownAnswer = (): unknown => "APPLIED_CONFIRMED";
it.each([
["no classifier", undefined],
["a throwing classifier", throwingClassifier],
["an unknown answer", unknownAnswer],
] as const)("keeps MAYBE_APPLIED for %s", async (_label, classifyStatus) => {
for (const status of [401, 403, 429]) {
await expect(
effectFor(status, withStatusClassifier(classifyStatus)),
).resolves.toMatchObject({ effect: "MAYBE_APPLIED" });
}
});
});
/**
* Q-6.3-7. A retried command's final effect joins what earlier attempts already
* established, and an answer that says the command may already be applied is
* not replayed.
*/
describe("command effect across retries", () => {
const idempotentCommand: InstalledHttpContract<unknown, unknown, unknown> = {
...createInstalled,
contract: {
...createInstalled.contract,
retrySemantics: "IDEMPOTENT" as const,
},
frontend: { ...createInstalled.frontend, retryBudget: 1 as const },
};
async function runThenReject(first: () => Promise<Response>) {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementationOnce(first)
.mockImplementation(async () =>
// The fixture classifier reads a 400 problem as NOT_APPLIED.
Response.json(
{ type: "about:blank", title: "rejected", status: 400 },
{ status: 400 },
),
);
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 1,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher,
sleep: async () => {},
random: () => 0,
});
const outcome = await executor.execute(
idempotentCommand,
{ name: "created" },
{
routeId: ROUTE_ID,
scope,
intent: mutationIntent({ idempotencyKey: null }),
},
);
return { outcome, attempts: fetcher.mock.calls.length };
}
it("keeps MAYBE_APPLIED when the retry after a lost response is rejected", async () => {
await expect(
runThenReject(async () => {
throw new TypeError("connection reset");
}),
).resolves.toMatchObject({
attempts: 2,
outcome: { kind: "PROBLEM", effect: "MAYBE_APPLIED" },
});
});
it("keeps MAYBE_APPLIED when the retry after a rate limit is rejected", async () => {
await expect(
runThenReject(async () => new Response(null, { status: 429 })),
).resolves.toMatchObject({
attempts: 2,
outcome: { kind: "PROBLEM", effect: "MAYBE_APPLIED" },
});
});
it("does not replay a command whose gateway failure may already be applied", async () => {
await expect(
runThenReject(async () => new Response("", { status: 504 })),
).resolves.toMatchObject({
attempts: 1,
outcome: {
kind: "CONTRACT_VIOLATION",
metadata: { status: 504 },
effect: "MAYBE_APPLIED",
},
});
});
});
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import type {
ApiOperation,
RestOperationV2,
} from "../../src/contracts/api-operations.ts";
import { INSTALLED_CONTRACT_CONTRIBUTIONS } from "../../src/features/installed-contract-contributions.ts";
import { API_OPERATIONS } from "../../src/features/installed-feature-contracts.ts";
// 07-03 (D-7). FE-REG-API governs the V2 rows while the V3 descriptors are
// what executes. Until V2 is generated from V3, both copies must agree.
const RETRY_SEMANTICS_FOR_REPLAY_POLICY = Object.freeze({
SAFE: "SAFE",
IDEMPOTENT: "IDEMPOTENT",
KEYED_COMMAND: "KEYED",
NON_REPLAYABLE: "NEVER",
} as const);
const v3ByOperationId = new Map(
INSTALLED_CONTRACT_CONTRIBUTIONS.flatMap((contribution) =>
contribution.http.map(
(descriptor) => [descriptor.contract.operationId, descriptor] as const,
),
),
);
const v2Rows = (Object.values(API_OPERATIONS) as readonly ApiOperation[]).filter(
(operation): operation is RestOperationV2 => operation.contractVersion === 2,
);
describe("HTTP operation V2 rows and V3 descriptors", () => {
it("declare the same method, path, statuses, limit, auth profile and replay policy", () => {
for (const row of v2Rows) {
const descriptor = v3ByOperationId.get(row.operationId);
expect(descriptor, `${row.operationId} has no V3 descriptor`).toBeDefined();
if (!descriptor) continue;
expect(
{
method: descriptor.contract.method,
path: descriptor.contract.pathTemplate,
successStatuses: [...descriptor.contract.acceptedStatuses],
maxResponseBytes: descriptor.frontend.responseByteLimit,
authProfileId: descriptor.frontend.authProfileId,
retrySemantics: descriptor.contract.retrySemantics,
},
row.operationId,
).toEqual({
method: row.method,
path: row.path,
successStatuses: [...row.successStatuses],
maxResponseBytes: row.maxResponseBytes,
authProfileId: row.authProfileId,
retrySemantics: RETRY_SEMANTICS_FOR_REPLAY_POLICY[row.replayPolicy],
});
}
});
});
+4 -1
View File
@@ -42,7 +42,10 @@ describe("HTTP retry lifecycle policy", () => {
expect(jitteredDelay(8, () => 0.5)).toBe(1_000);
expect(retryDelayFor(null, 0, () => 0.5)).toBe(125);
expect(retryDelayFor(400, 0, () => 0.5)).toBe(400);
// §13.3: Retry-After is a floor plus bounded jitter, never an exact
// synchronized instant (400 + floor(0.5 * max(250, 100))).
expect(retryDelayFor(400, 0, () => 0.5)).toBe(525);
expect(retryDelayFor(400, 0, () => 0)).toBe(400);
expect(retryDelayFor(5_001, 0, () => 0.5)).toBeNull();
});
});
+18 -1
View File
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
import { ERROR_REGISTRY } from "../../src/contracts/errors.ts";
import {
catalogKeys,
FORMAT_FALLBACK,
@@ -34,6 +36,17 @@ describe("internationalization message contract", () => {
expect(MESSAGE_CATALOGS["ar-EG"]).toBe(EN_MESSAGES);
});
// 07-01/08-02. A kind without copy renders "This message is unavailable."
// as the failure title, so every registry row must resolve in both locales.
it("gives every error registry kind its own message in every locale", () => {
const missing = Object.values(ERROR_REGISTRY).flatMap((definition) =>
[KO_MESSAGES, EN_MESSAGES]
.filter((catalog) => !Object.hasOwn(catalog, definition.userMessageKey))
.map(() => definition.userMessageKey),
);
expect(missing).toEqual([]);
});
it("formats typed parameters and expands the pseudo locale", () => {
expect(
formatMessage("en-US", "route.documentTitle", {
@@ -52,10 +65,14 @@ describe("internationalization message contract", () => {
expect(normalizeLocale("fr-FR")).toBe("ko-KR");
expect(resolveMessage("fr-FR", "action.retry")).toBe("다시 시도");
expect(resolveMessage("en-US", "action.login")).toBe("Sign in");
// The fallback copy follows the requested locale.
expect(resolveMessage("en-US", "backend.stack.trace")).toBe(
"요청한 문구를 표시할 수 없습니다.",
"This message is unavailable.",
);
expect(resolveMessage("en-US", "action.closeNamed")).toBe(
"This message is unavailable.",
);
expect(resolveMessage("ko-KR", "backend.stack.trace")).toBe(
"요청한 문구를 표시할 수 없습니다.",
);
expect(resolveMessage("en-US", "backend.stack.trace")).not.toContain(
@@ -108,6 +108,40 @@ describe("browser image probe", () => {
expect(close).toHaveBeenCalledTimes(samples.length);
});
// Q-6.1-8. The header parser reads pre-rotation dimensions, so the native
// decode must not apply EXIF/irot orientation either; otherwise an
// orientation 5-8 JPEG decodes with width and height swapped.
it("decodes with the default bitmap factory without applying orientation", async () => {
const bytes = jpegBytes(640, 360);
const exactUrl = imageUrl.replace("format=png", "format=jpeg");
const nativeCreateImageBitmap = vi.fn(async () => ({
width: 640,
height: 360,
close() {},
}));
vi.stubGlobal("createImageBitmap", nativeCreateImageBitmap);
try {
const probe = createBrowserImageProbe({
fetcher: (async () =>
responseAt(exactUrl, bytes, {
status: 200,
headers: publicImageHeaders("image/jpeg", bytes.byteLength),
})) as typeof fetch,
});
await expect(
probe.probe(
request({ absoluteUrl: exactUrl, expectedMediaType: "image/jpeg" }),
),
).resolves.toMatchObject({ ok: true });
expect(nativeCreateImageBitmap).toHaveBeenCalledWith(
expect.any(Blob),
{ imageOrientation: "none" },
);
} finally {
vi.unstubAllGlobals();
}
});
it("fails closed on duplicate/conflicting cache directives and oversized bodies", async () => {
const png = pngBytes(640, 360);
const createBitmap = vi.fn(async () => ({
+170
View File
@@ -397,6 +397,40 @@ describe("production image CDN runtime", () => {
expect(resolved.value.sources[0]?.type).toBe("image/avif");
});
// Q-6.1-7 / D-12. The probe demands the exact primary pixel size, which a
// ratio-preserving fit (inside/outside) does not produce for an asset whose
// ratio differs, so that preset could only ever fail at probe time.
it("allows a PRIMARY_REQUIRED probe only with an exact-size fit", () => {
for (const fit of ["inside", "outside"] as const) {
expect(() =>
createPolicies([
createPreset(imageCdnPresetReference("probe", `fit-${fit}`), {
fit,
probeMode: "PRIMARY_REQUIRED",
}),
]),
).toThrow(/preset policy is invalid/u);
// Without the probe a ratio-preserving fit stays allowed.
expect(() =>
createPolicies([
createPreset(imageCdnPresetReference("probe", `none-${fit}`), {
fit,
}),
]),
).not.toThrow();
}
for (const fit of ["cover", "contain", "fill"] as const) {
expect(() =>
createPolicies([
createPreset(imageCdnPresetReference("probe", `exact-${fit}`), {
fit,
probeMode: "PRIMARY_REQUIRED",
}),
]),
).not.toThrow();
}
});
it("rejects unsafe origins and preset budgets at composition time", () => {
const preset = imageCdnPresetReference(
"unsafe",
@@ -1406,3 +1440,139 @@ describe("production image CDN runtime", () => {
]);
});
});
describe("image probe cost (01-11)", () => {
const preset = imageCdnPresetReference("probe-cost", "render-probed");
const policies = () =>
createPolicies([
createPreset(preset, {
bindingId: "probe-cost-v1",
probeMode: "PRIMARY_REQUIRED",
}),
]);
const receipt = (request: ImageProbeRequest) => ({
ok: true as const,
value: {
absoluteUrl: request.absoluteUrl,
mediaType: request.expectedMediaType,
encodedBytes: 1_024,
decodedWidth: request.expectedWidth,
decodedHeight: request.expectedHeight,
},
});
it("reuses a passed probe for the same asset and preset", async () => {
let fail = true;
const probe = vi.fn(async (request: ImageProbeRequest) => {
if (fail) {
fail = false;
return {
ok: false as const,
error: {
code: "UNAVAILABLE" as const,
operation: "IMAGE_RESOLVE" as const,
retryable: true,
recovery: "RETRY" as const,
},
};
}
return receipt(request);
});
const runtime = createImageCdnRuntime({
policies: policies(),
probe: { probe },
});
const accepted = runtime.assets.acceptPublicImmutable(publicAsset());
if (!accepted.ok) throw new Error("accept failed");
const resolve = async () =>
await runtime.presentation.resolve({
asset: accepted.value,
preset,
signal: new AbortController().signal,
});
// A failed probe is not remembered; the first pass is.
expect((await resolve()).ok).toBe(false);
const first = await resolve();
const second = await resolve();
expect(first.ok && second.ok).toBe(true);
expect(second).toEqual(first);
expect(probe).toHaveBeenCalledTimes(2);
});
it("never runs more probes at once than maxConcurrentProbes", async () => {
let active = 0;
let peak = 0;
const releases: (() => void)[] = [];
const probe = vi.fn(async (request: ImageProbeRequest) => {
active += 1;
peak = Math.max(peak, active);
await new Promise<void>((resolve) => releases.push(resolve));
active -= 1;
return receipt(request);
});
const runtime = createImageCdnRuntime({
policies: policies(),
probe: { probe },
maxConcurrentProbes: 2,
});
const pending = Array.from({ length: 5 }, () => {
const accepted = runtime.assets.acceptPublicImmutable(publicAsset());
if (!accepted.ok) throw new Error("accept failed");
return runtime.presentation.resolve({
asset: accepted.value,
preset,
signal: new AbortController().signal,
});
});
for (let released = 0; released < 5; released += 1) {
await vi.waitFor(() => expect(releases.length).toBeGreaterThan(0));
releases.shift()?.();
}
const results = await Promise.all(pending);
expect(results.every((result) => result.ok)).toBe(true);
expect(probe).toHaveBeenCalledTimes(5);
expect(peak).toBe(2);
});
it("gives a waiting caller's slot back when it aborts before its turn", async () => {
const releases: (() => void)[] = [];
const probe = vi.fn(async (request: ImageProbeRequest) => {
await new Promise<void>((resolve) => releases.push(resolve));
return receipt(request);
});
const runtime = createImageCdnRuntime({
policies: policies(),
probe: { probe },
maxConcurrentProbes: 1,
});
const resolveNew = (signal: AbortSignal) => {
const accepted = runtime.assets.acceptPublicImmutable(publicAsset());
if (!accepted.ok) throw new Error("accept failed");
return runtime.presentation.resolve({
asset: accepted.value,
preset,
signal,
});
};
const holder = resolveNew(new AbortController().signal);
await vi.waitFor(() => expect(releases).toHaveLength(1));
const waiting = new AbortController();
const abandoned = resolveNew(waiting.signal);
waiting.abort();
expect(await abandoned).toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
releases.shift()?.();
expect((await holder).ok).toBe(true);
const next = resolveNew(new AbortController().signal);
await vi.waitFor(() => expect(releases).toHaveLength(1));
releases.shift()?.();
expect((await next).ok).toBe(true);
expect(probe).toHaveBeenCalledTimes(2);
});
});
+91
View File
@@ -469,6 +469,65 @@ describe("shared IndexedDB connection mechanics", () => {
});
});
describe("Q-6.5-10 an upgrade that starts after the open settled", () => {
function openWithUpgrade(
stub: StubFactory,
options: Readonly<{ signal?: AbortSignal }> = {},
) {
const upgrade = vi.fn(() => ({ kind: "APPLIED" as const }));
const pending = openIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
version: 2,
translate: recordingTranslate([]),
upgrade,
...options,
});
const request = stub.opened[0];
if (!request) throw new Error("no open request");
return { pending, request, upgrade };
}
function startUpgrade(request: StubOpenRequest) {
const abort = vi.fn();
request.transaction = { abort } as unknown as IDBTransaction;
request.onupgradeneeded?.(versionChangeEvent(1, 2));
return abort;
}
it("is aborted instead of migrating after the caller gave up", async () => {
const stub = stubFactory();
const controller = new AbortController();
const { pending, request, upgrade } = openWithUpgrade(stub, {
signal: controller.signal,
});
// No versionchange transaction exists yet, so there is nothing to abort.
controller.abort();
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "CALLER_ABORT" },
});
const abort = startUpgrade(request);
expect(upgrade).not.toHaveBeenCalled();
expect(abort).toHaveBeenCalledTimes(1);
});
it("is aborted after a terminal BLOCKED", async () => {
const stub = stubFactory();
const { pending, request, upgrade } = openWithUpgrade(stub);
request.onblocked?.(versionChangeEvent(1, 2));
await expect(pending).resolves.toMatchObject({
ok: false,
error: { cause: "BLOCKED" },
});
const abort = startUpgrade(request);
expect(upgrade).not.toHaveBeenCalled();
expect(abort).toHaveBeenCalledTimes(1);
});
});
it("closes a connection that arrives after the caller gave up", async () => {
const memory = new MemoryIndexedDbFactory();
const controller = new AbortController();
@@ -884,3 +943,35 @@ describe("IndexedDB database deletion", () => {
});
});
});
describe("05-13 a versionchange that arrives while admission runs", () => {
it("closes the connection and ends the open instead of blocking the upgrade", async () => {
const memory = new MemoryIndexedDbFactory();
let admitting!: () => void;
const admissionStarted = new Promise<void>((resolve) => {
admitting = resolve;
});
let finishAdmission!: () => void;
const pending = openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: () => ({ kind: "APPLIED" }),
admit: async () => {
admitting();
await new Promise<void>((resolve) => {
finishAdmission = resolve;
});
return { kind: "ADMIT" };
},
});
await admissionStarted;
// Another context asks to upgrade while this one is still admitting.
memory.triggerVersionChange(2);
expect(memory.isConnectionClosed()).toBe(true);
finishAdmission();
expect(await pending).toEqual({ ok: false, error: { cause: "CLOSED" } });
});
});
+155 -3
View File
@@ -35,7 +35,11 @@ const TEST_STORAGE_POLICY = Object.freeze({
unavailableFallback: "ONLINE_ONLY" as const,
});
function createSchemaRuntime(memory: MemoryIndexedDbFactory) {
function createSchemaRuntime(
memory: MemoryIndexedDbFactory,
measureStoredBytes: (value: CurrentPayload) => number = (value) =>
new TextEncoder().encode(JSON.stringify(value)).byteLength,
) {
return createIndexedDbRuntime<CurrentPayload, CurrentPayload, null>({
scope: TEST_SCOPE,
storagePolicy: TEST_STORAGE_POLICY,
@@ -98,8 +102,7 @@ function createSchemaRuntime(memory: MemoryIndexedDbFactory) {
codec: {
currentVersion: 2,
encode: (value) => ({ ok: true, value }),
measureStoredBytes: (value) =>
new TextEncoder().encode(JSON.stringify(value)).byteLength,
measureStoredBytes,
decode: (version, value) =>
version === 2 &&
value !== null &&
@@ -1008,3 +1011,152 @@ describe("IndexedDB bounded codec maintenance", () => {
).toBeDefined();
});
});
/**
* Q-6.5-7 characterization. The runtime, maintenance and the dataset binding
* each carried their own copy of the stored-row rules. These pin what every
* call site does today so merging the copies cannot move any of it.
*/
describe("Q-6.5-7 stored-row rules stay the same at every call site", () => {
const encodedBytes = (value: unknown) =>
new TextEncoder().encode(JSON.stringify(value)).byteLength;
it("measures a record as payload + 512 + 2 bytes per key character in both writers", async () => {
const memory = new MemoryIndexedDbFactory();
const runtime = createSchemaRuntime(memory);
expect(await runtime.open()).toMatchObject({ ok: true });
expect(
await runtime.compareAndSwap({
key: "abc",
value: { label: "x" },
expectedRevision: null,
idempotencyKey: "abc-create",
}),
).toMatchObject({ ok: true });
runtime.close();
expect(memory.readRaw("retention", "abc")).toMatchObject({
measuredBytes: encodedBytes({ label: "x" }) + 512 + 6,
});
seedLegacy(memory, "k1", "legacy");
const maintenance = createMaintenance(memory, defaultPolicy());
expect(
await maintenance.migrateCodecBatch({
maxRows: 10,
maxDurationMs: 10_000,
}),
).toMatchObject({ ok: true, value: { migratedRows: 1 } });
expect(memory.readRaw("retention", "k1")).toMatchObject({
measuredBytes: encodedBytes({ label: "legacy" }) + 512 + 4,
});
});
it.each([
["NaN", Number.NaN],
["a negative size", -1],
["a size past the stored maximum", 2_147_483_647],
])(
"rejects %s as INVALID_INPUT in the runtime and MIGRATION_FAILED in maintenance",
async (_label, measured) => {
const memory = new MemoryIndexedDbFactory();
const runtime = createSchemaRuntime(memory, () => measured);
expect(await runtime.open()).toMatchObject({ ok: true });
expect(
await runtime.compareAndSwap({
key: "measured",
value: { label: "x" },
expectedRevision: null,
idempotencyKey: "measured-create",
}),
).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
runtime.close();
seedLegacy(memory, "legacy", "value");
const maintenance = createMaintenance(memory, {
...defaultPolicy(),
measureStoredBytes: () => measured,
});
expect(
await maintenance.migrateCodecBatch({
maxRows: 10,
maxDurationMs: 10_000,
}),
).toMatchObject({
ok: false,
error: { code: "MIGRATION_FAILED", recovery: "READ_ONLY" },
});
},
);
it("bounds a stored budget by hardBudgetBytes when the dataset binding is verified", async () => {
const memory = new MemoryIndexedDbFactory();
await prepareSchema(memory);
const budget = memory.readRaw("governance", "dataset-budget") as Record<
string,
unknown
>;
memory.seed("governance", {
...budget,
usedBytes: TEST_STORAGE_POLICY.hardBudgetBytes,
});
const atLimit = createSchemaRuntime(memory);
expect(await atLimit.open()).toMatchObject({ ok: true });
atLimit.close();
memory.seed("governance", {
...budget,
usedBytes: TEST_STORAGE_POLICY.hardBudgetBytes + 1,
});
const overLimit = createSchemaRuntime(memory);
const opened = await overLimit.open();
overLimit.close();
expect(opened).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
expect(
await createMaintenance(memory, defaultPolicy()).migrateCodecBatch({
maxRows: 10,
maxDurationMs: 10_000,
}),
).toMatchObject({ ok: false, error: { code: "POLICY_REJECTED" } });
});
});
describe("05-05 a receipt prune steps over a corrupt receipt", () => {
it("deletes every expired healthy receipt, leaves the corrupt one and reports CORRUPT_DATA", async () => {
const memory = new MemoryIndexedDbFactory();
await prepareSchema(memory);
seedReceipt(memory, "expired-a", 100);
seedReceipt(memory, "expired-b", 200);
memory.seed("receipts", { idempotencyKey: "broken", expiresAtEpochMs: 0 });
const observations: IndexedDbObservation[] = [];
const maintenance = createMaintenance(memory, defaultPolicy(), {
nowEpochMilliseconds: () => 300,
observe: (event) => observations.push(event),
});
expect(
await maintenance.pruneExpiredReceipts({
maxRows: 10,
maxDurationMs: 10_000,
}),
).toMatchObject({
ok: true,
value: { state: "COMPLETE", deletedRows: 2 },
});
expect(memory.readRaw("receipts", "expired-a")).toBeUndefined();
expect(memory.readRaw("receipts", "expired-b")).toBeUndefined();
expect(memory.readRaw("receipts", "broken")).toBeDefined();
expect(
memory.readRaw("governance", "dataset-budget"),
).toMatchObject({ receiptCount: 0 });
expect(observations).toContainEqual(
expect.objectContaining({
outcome: "FAILED",
failureCode: "CORRUPT_DATA",
}),
);
});
});
+80
View File
@@ -710,6 +710,61 @@ describe("IndexedDB OPFS journal", () => {
expect(second.value.nextObjectId).toBeNull();
});
it("R-5.5 keeps an object readable by its own chunk size and still rejects an inconsistent one", async () => {
const { journal } = createHarness();
const chunkSizeBytes = 4 * 1024 * 1024;
const byteLength = chunkSizeBytes + 1;
const input: BeginOpfsJournalTransaction = {
...beginInput("transaction_chunk001", "object_chunk_001", byteLength),
targetStoragePolicy: {
...policy,
softBudgetBytes: 2 * byteLength,
hardBudgetBytes: 2 * byteLength,
},
};
const base = prepared(input);
const stored: OpfsPreparedObject = {
...base,
descriptor: {
...base.descriptor,
integrity: { ...base.descriptor.integrity, chunkSizeBytes },
},
chunks: [
{ sequence: 0, byteLength: chunkSizeBytes, digestHex: "c".repeat(64) },
{ sequence: 1, byteLength: 1, digestHex: "d".repeat(64) },
],
};
const begun = await journal.begin(input);
if (!begun.ok) throw new Error("begin failed");
const token = begun.value.fencingToken;
// A first chunk shorter than the object's own chunk size is not a
// well-formed object under any policy.
expect(
await journal.markFilesReady(input.transactionId, token, {
...stored,
chunks: [
{ sequence: 0, byteLength: 1, digestHex: "c".repeat(64) },
{ sequence: 1, byteLength: chunkSizeBytes, digestHex: "d".repeat(64) },
],
}),
).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
expect(
await journal.markFilesReady(input.transactionId, token, stored),
).toMatchObject({ ok: true, value: { phase: "FILES_READY" } });
expect(await journal.listIncomplete(10)).toMatchObject({
ok: true,
value: { transactions: [{ preparedObject: stored }] },
});
expect(
await journal.commitPut(input.transactionId, token),
).toMatchObject({ ok: true });
expect(
await journal.getCommittedObject(scope, input.objectId),
).toEqual({ ok: true, value: stored });
});
it("answers UNSUPPORTED once the journal is closed", async () => {
const { factory, journal } = createHarness();
expect(
@@ -740,3 +795,28 @@ describe("IndexedDB OPFS journal", () => {
).toMatchObject({ ok: false, error: { code: "UNSUPPORTED" } });
});
});
describe("05-06 a journal from a newer release", () => {
it("answers online-only instead of a migration failure", async () => {
const memory = new MemoryIndexedDbFactory();
const name = opfsJournalDatabaseName("authority_12345678");
await new Promise<void>((resolve, reject) => {
const request = memory.factory.open(name, 2);
request.onsuccess = () => {
request.result.close();
resolve();
};
request.onerror = () => reject(request.error);
});
const journal = createIndexedDbOpfsJournal({
authorityToken: "authority_12345678",
factory: memory.factory,
keyRange: memory.keyRange,
});
expect(await journal.listIncomplete(10)).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED", recovery: "ONLINE_ONLY" },
});
});
});
+402 -15
View File
@@ -6,7 +6,7 @@ import type {
IndexedDbObservation,
IndexedDbRuntimeDependencies,
} from "../../src/adapters/storage/indexeddb/indexeddb-types.ts";
import { mapIndexedDbException } from "../../src/adapters/storage/indexeddb/indexeddb-failure.ts";
import { mapIndexedDbException } from "../../src/adapters/browser-file-storage/result.ts";
import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts";
type Item = Readonly<{
@@ -449,7 +449,7 @@ describe("IndexedDB runtime", () => {
expect(runtime.getStatus()).toEqual({ kind: "READY", schemaVersion: 1 });
});
it("times out a blocked upgrade, then closes a late successful connection", async () => {
it("times out a blocked upgrade, then aborts the late upgrade instead of committing it", async () => {
const memory = new MemoryIndexedDbFactory();
memory.blockNextOpen();
let timeout: (() => void) | undefined;
@@ -484,7 +484,10 @@ describe("IndexedDB runtime", () => {
memory.releaseBlockedOpen();
await Promise.resolve();
expect(memory.isConnectionClosed()).toBe(true);
// Q-6.5-10. The upgrade that starts after the deadline is aborted, so no
// schema commits and no connection exists to leak. (This test used to
// expect the late upgrade to commit and its connection to be closed.)
expect(memory.hasStore("records")).toBe(false);
expect(runtime.getStatus()).toEqual({
kind: "CLOSED",
reason: "NOT_OPENED",
@@ -1032,9 +1035,10 @@ describe("IndexedDB runtime", () => {
});
});
it("aborts a sweep whose budget row cannot account for the deleted bytes", async () => {
it("05-05 sweeps a row the budget cannot account for and leaves the budget high", async () => {
const memory = new MemoryIndexedDbFactory();
let epochMs = 1_000;
const observations: IndexedDbObservation[] = [];
const runtime = createIndexedDbRuntime(
dependencies(memory, {
storagePolicy: {
@@ -1051,6 +1055,7 @@ describe("IndexedDB runtime", () => {
authorized: true,
proofToken: "sweep_authority_proof_001",
}),
observe: (event) => observations.push(event),
}),
);
expect(await runtime.open()).toMatchObject({ ok: true });
@@ -1063,9 +1068,8 @@ describe("IndexedDB runtime", () => {
}),
).toMatchObject({ ok: true });
// A budget that cannot account for the record's bytes is corrupt, and the
// sweep only discovers it after both deletions have already succeeded
// inside the transaction.
// A budget that cannot account for the record's bytes is corrupt. The
// sweep finds it only after both deletions succeeded in the transaction.
memory.seed("governance", {
bindingKey: "dataset-budget",
budgetVersion: 1,
@@ -1082,15 +1086,20 @@ describe("IndexedDB runtime", () => {
maxDurationMs: 1_000,
}),
).toMatchObject({
ok: false,
error: { code: "CORRUPT_DATA" },
ok: true,
value: { state: "COMPLETE", deletedRows: 1 },
});
// `fail` aborts. Recording the failure without aborting would report the
// same code while letting the two deletions commit against a budget that
// never moved.
expect(aborts.count).toBe(1);
expect(memory.readRaw("records", "sweep-record")).toBeDefined();
expect(memory.readRaw("retention", "sweep-record")).toBeDefined();
expect(aborts.count).toBe(0);
expect(memory.readRaw("records", "sweep-record")).toBeUndefined();
expect(memory.readRaw("retention", "sweep-record")).toBeUndefined();
// Not lowered below what it cannot account for: a budget that reads high
// blocks writes, one that reads low would admit them.
expect(memory.readRaw("governance", "dataset-budget")).toMatchObject({
usedBytes: 0,
});
expect(observations).toContainEqual(
expect.objectContaining({ failureCode: "CORRUPT_DATA" }),
);
});
it("requires lifecycle authority and only deletes sync-confirmed rows", async () => {
@@ -1240,6 +1249,127 @@ describe("IndexedDB runtime", () => {
).toMatchObject({ usedBytes: 0, receiptCount: 0 });
});
it.each(["LOGOUT", "ACCOUNT_DELETION"] as const)(
"R-5.4 completes a %s purge past corrupt rows, reports them, and leaves other partitions alone",
async (action) => {
const partitionScope = {
...TEST_SCOPE,
accountScope: "OPAQUE_PARTITION" as const,
};
const otherScope = {
...partitionScope,
partitionToken: "partitiontoken_002",
};
const partitionPolicy = {
...TEST_STORAGE_POLICY,
accountScope: "OPAQUE_PARTITION" as const,
logoutAction: "PURGE_PARTITION" as const,
accountDeletionAction: "PURGE_PARTITION" as const,
};
// One factory, routed by the physical database name the runtime derives
// from its partition, the way the browser keeps databases apart.
const purged = new MemoryIndexedDbFactory();
const other = new MemoryIndexedDbFactory();
const otherName = indexedDbPhysicalDatabaseName(otherScope);
const factory = {
open: (name: string, version?: number) =>
(name === otherName ? other : purged).factory.open(name, version),
cmp: purged.factory.cmp,
} as IDBFactory;
const observations: IndexedDbObservation[] = [];
const runtime = createIndexedDbRuntime(
dependencies(purged, {
scope: partitionScope,
storagePolicy: partitionPolicy,
factory,
nowMonotonicMilliseconds: () => 0,
observe: (event) => observations.push(event),
}),
);
const otherRuntime = createIndexedDbRuntime(
dependencies(other, {
scope: otherScope,
storagePolicy: partitionPolicy,
factory,
nowMonotonicMilliseconds: () => 0,
}),
);
expect(await runtime.open()).toMatchObject({ ok: true });
expect(await otherRuntime.open()).toMatchObject({ ok: true });
for (const key of ["healthy", "bad-record", "bad-sidecar"]) {
expect(
await runtime.compareAndSwap({
key,
value: { label: key, rank: 1 },
expectedRevision: null,
idempotencyKey: `${key}-create`,
}),
).toMatchObject({ ok: true });
}
expect(
await otherRuntime.compareAndSwap({
key: "other-partition",
value: { label: "kept", rank: 1 },
expectedRevision: null,
idempotencyKey: "other-create",
}),
).toMatchObject({ ok: true });
// Four corrupt rows and a budget that no longer matches the data.
purged.seed("records", { key: "bad-record", codecVersion: 0 });
purged.seed("retention", { recordKey: "bad-sidecar", measuredBytes: -1 });
purged.seed("retention", { recordKey: "orphan-sidecar" });
purged.seed("receipts", { idempotencyKey: "bad-receipt" });
purged.seed("governance", {
bindingKey: "dataset-budget",
budgetVersion: 1,
usedBytes: 1,
receiptCount: 0,
});
const receipts = [];
for (let batch = 0; batch < 5; batch += 1) {
const receipt = await runtime.enforceLifecycleBatch({
action,
maxRows: 2,
maxDurationMs: 1_000,
});
receipts.push(receipt);
if (!receipt.ok || receipt.value.state === "COMPLETE") break;
}
expect(receipts.at(-1)).toMatchObject({
ok: true,
value: { state: "COMPLETE" },
});
for (const key of ["healthy", "bad-record", "bad-sidecar"]) {
expect(purged.readRaw("records", key)).toBeUndefined();
expect(purged.readRaw("retention", key)).toBeUndefined();
expect(purged.readRaw("receipts", `${key}-create`)).toBeUndefined();
}
expect(purged.readRaw("retention", "orphan-sidecar")).toBeUndefined();
expect(purged.readRaw("receipts", "bad-receipt")).toBeUndefined();
expect(purged.readRaw("governance", "dataset-budget")).toEqual({
bindingKey: "dataset-budget",
budgetVersion: 1,
usedBytes: 0,
receiptCount: 0,
});
// Corruption is reported, never a reason to stop deleting.
const corrupt = observations.filter(
(event) => event.failureCode === "CORRUPT_DATA",
);
expect(corrupt.length).toBeGreaterThan(0);
expect(observations.at(-1)).toMatchObject({ outcome: "SUCCESS" });
expect(other.readRaw("records", "other-partition")).toBeDefined();
expect(await otherRuntime.read("other-partition")).toMatchObject({
ok: true,
value: { value: { label: "kept" } },
});
},
);
it("rejects invalid measurements, byte overage, and receipt-count overage atomically", async () => {
const invalidMemory = new MemoryIndexedDbFactory();
const invalidBase = dependencies(invalidMemory);
@@ -1329,3 +1459,260 @@ describe("IndexedDB runtime", () => {
expect(hardMemory.readRaw("records", "x")).toBeUndefined();
});
});
describe("05-03 a LOGOUT or ACCOUNT_DELETION purge survives corrupt governance", () => {
const partitionScope = {
...TEST_SCOPE,
accountScope: "OPAQUE_PARTITION" as const,
};
const otherScope = {
...partitionScope,
partitionToken: "partitiontoken_002",
};
const partitionPolicy = {
...TEST_STORAGE_POLICY,
accountScope: "OPAQUE_PARTITION" as const,
logoutAction: "PURGE_PARTITION" as const,
accountDeletionAction: "PURGE_PARTITION" as const,
};
const batch = { maxRows: 100, maxDurationMs: 1_000 } as const;
/**
* Another partition and this one each hold a record in one factory; this
* partition's budget row is then corrupted, so a fresh runtime cannot pass
* admission (E1).
*/
async function corruptedPartition(
authorizeLifecycle: IndexedDbRuntimeDependencies<
Item,
Item,
Query
>["authorizeLifecycle"] = () => ({
authorized: true,
proofToken: "authorityproof_001",
}),
) {
const memory = new MemoryIndexedDbFactory();
const other = createIndexedDbRuntime(
dependencies(memory, {
scope: otherScope,
storagePolicy: partitionPolicy,
}),
);
expect(await other.open()).toMatchObject({ ok: true });
await other.compareAndSwap({
key: "kept",
value: { label: "other", rank: 1 },
expectedRevision: null,
idempotencyKey: "kept-create",
});
const writer = createIndexedDbRuntime(
dependencies(memory, {
scope: partitionScope,
storagePolicy: partitionPolicy,
}),
);
expect(await writer.open()).toMatchObject({ ok: true });
await writer.compareAndSwap({
key: "personal-1",
value: { label: "mine", rank: 1 },
expectedRevision: null,
idempotencyKey: "personal-create",
});
writer.close();
memory.seed("governance", {
bindingKey: "dataset-budget",
budgetVersion: 1,
usedBytes: -5,
receiptCount: 1,
});
const deleteDatabase = vi.spyOn(memory.factory, "deleteDatabase");
const fresh = createIndexedDbRuntime(
dependencies(memory, {
scope: partitionScope,
storagePolicy: partitionPolicy,
authorizeLifecycle,
}),
);
expect(await fresh.open()).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
return { memory, other, fresh, deleteDatabase };
}
it.each(["LOGOUT", "ACCOUNT_DELETION"] as const)(
"deletes the partition's whole dataset for an authorized %s and leaves other partitions alone",
async (action) => {
const { memory, other, fresh, deleteDatabase } =
await corruptedPartition();
expect(
await fresh.enforceLifecycleBatch({ action, ...batch }),
).toMatchObject({
ok: true,
value: { state: "COMPLETE", datasetDeleted: true },
});
expect(deleteDatabase).toHaveBeenCalledTimes(1);
expect(deleteDatabase).toHaveBeenCalledWith(
indexedDbPhysicalDatabaseName(partitionScope),
);
expect(memory.hasStore("records")).toBe(false);
expect(await other.read("kept")).toMatchObject({
ok: true,
value: { value: { label: "other", rank: 1 } },
});
},
);
it("keeps the dataset when the authority does not approve", async () => {
const { memory, fresh, deleteDatabase } = await corruptedPartition(
() => ({ authorized: false }),
);
expect(
await fresh.enforceLifecycleBatch({ action: "ACCOUNT_DELETION", ...batch }),
).toMatchObject({ ok: false, error: { code: "POLICY_REJECTED" } });
expect(deleteDatabase).not.toHaveBeenCalled();
expect(memory.readRaw("records", "personal-1")).toBeDefined();
});
it("purges row by row, never the database, when governance is healthy", async () => {
const memory = new MemoryIndexedDbFactory();
const deleteDatabase = vi.spyOn(memory.factory, "deleteDatabase");
const runtime = createIndexedDbRuntime(
dependencies(memory, {
scope: partitionScope,
storagePolicy: partitionPolicy,
}),
);
expect(await runtime.open()).toMatchObject({ ok: true });
await runtime.compareAndSwap({
key: "personal-1",
value: { label: "mine", rank: 1 },
expectedRevision: null,
idempotencyKey: "personal-create",
});
runtime.close();
const fresh = createIndexedDbRuntime(
dependencies(memory, {
scope: partitionScope,
storagePolicy: partitionPolicy,
}),
);
const purged = await fresh.enforceLifecycleBatch({
action: "LOGOUT",
...batch,
});
expect(purged).toMatchObject({ ok: true, value: { state: "COMPLETE" } });
expect(purged.ok && purged.value).not.toHaveProperty("datasetDeleted");
expect(deleteDatabase).not.toHaveBeenCalled();
expect(memory.hasStore("records")).toBe(true);
expect(memory.readRaw("records", "personal-1")).toBeUndefined();
});
});
describe("05-05 a retention sweep steps over a corrupt row", () => {
it("deletes every expired healthy row, leaves the corrupt sidecar and reports it", async () => {
const memory = new MemoryIndexedDbFactory();
let epochMs = 1_000;
const observations: IndexedDbObservation[] = [];
const runtime = createIndexedDbRuntime(
dependencies(memory, {
storagePolicy: {
...TEST_STORAGE_POLICY,
retention: { kind: "TTL", maxAgeMs: 10 },
},
keyRange:
memory.keyRange as NonNullable<
IndexedDbRuntimeDependencies<Item, Item, Query>["keyRange"]
>,
nowEpochMilliseconds: () => epochMs,
nowMonotonicMilliseconds: () => 0,
observe: (event) => observations.push(event),
}),
);
expect(await runtime.open()).toMatchObject({ ok: true });
for (const key of ["a", "b", "c"]) {
await runtime.compareAndSwap({
key,
value: { label: key, rank: 1 },
expectedRevision: null,
idempotencyKey: `create-${key}`,
});
}
// Sorts first on the eligibility index and names a record it is not keyed by.
memory.seed("retention", {
recordKey: "zzz",
writtenAtEpochMs: 0,
synchronization: "NONE",
measuredBytes: 0,
eligibleAtEpochMs: 0,
});
epochMs = 5_000;
for (let attempt = 0; attempt < 2; attempt += 1) {
expect(
await runtime.enforceLifecycleBatch({
action: "RETENTION_SWEEP",
maxRows: 100,
maxDurationMs: 1_000,
}),
).toMatchObject({ ok: true, value: { state: "COMPLETE" } });
}
expect(
["a", "b", "c"].filter(
(key) => memory.readRaw("records", key) !== undefined,
),
).toEqual([]);
expect(memory.readRaw("retention", "zzz")).toBeDefined();
expect(observations).toContainEqual(
expect.objectContaining({
operation: "INDEXEDDB_WRITE",
outcome: "FAILED",
failureCode: "CORRUPT_DATA",
}),
);
});
});
describe("05-06 an older tab that meets a newer schema", () => {
it("reports INCOMPATIBLE and online-only, not a migration failure", async () => {
const memory = new MemoryIndexedDbFactory();
const base = dependencies(memory);
const newer = createIndexedDbRuntime({
...base,
schemaVersion: 2,
migrations: [
...base.migrations,
{
id: "schema-v2",
fromVersion: 1,
toVersion: 2,
operations: [{ kind: "CREATE_STORE", name: "extra", keyPath: "k" }],
},
],
});
expect(await newer.open()).toMatchObject({ ok: true });
newer.close();
const older = createIndexedDbRuntime(dependencies(memory));
expect(await older.open()).toMatchObject({
ok: false,
error: {
code: "UNSUPPORTED",
operation: "INDEXEDDB_OPEN",
recovery: "ONLINE_ONLY",
},
});
expect(older.getStatus()).toEqual({
kind: "INCOMPATIBLE",
schemaVersion: 1,
});
expect(await older.read("x")).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED", recovery: "ONLINE_ONLY" },
});
});
});
+46 -6
View File
@@ -383,12 +383,52 @@ describe("shared IndexedDB transaction mechanics", () => {
transaction.error = new DOMException("aborted", "AbortError");
transaction.onabort?.(new Event("abort"));
const result = await pending;
expect(result.ok).toBe(false);
if (result.ok) return;
// The first candidate wins, so the later `fail` never becomes the value;
// an aborted transaction still cannot report the success it never kept.
expect(result.error.cause).toBe("NATIVE_EXCEPTION");
// Q-6.5-10. A `fail` after `succeed` replaces the success candidate, so
// the caller's own failure is reported instead of an anonymous native
// abort. (This test used to expect NATIVE_EXCEPTION, which dropped it.)
expect(await pending).toEqual({ ok: false, error: { cause: "CLOSED" } });
});
it("keeps the first failure when fail() is called twice", async () => {
const stub = stubDatabase();
const pending = runIndexedDbTransaction<string, TestFailure>({
database: stub.database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (_transaction, context) => {
context.fail({ cause: "CLOSED" });
context.succeed("value");
context.fail({ cause: "BLOCKED" });
},
});
stub.transactions[0]?.onabort?.(new Event("abort"));
expect(await pending).toEqual({ ok: false, error: { cause: "CLOSED" } });
});
it("does not commit a write when fail() follows succeed()", async () => {
const { database, memory } = await seededDatabase();
const result = await runIndexedDbTransaction<string, TestFailure>({
database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (transaction, context) => {
const store = transaction.objectStore("rows");
onIndexedDbRequest(store.put({ id: "e", rank: 5 }), context, () => {
context.succeed("written");
context.fail({ cause: "ADMISSION_REJECTED", detail: "late" });
});
},
});
expect(result).toEqual({
ok: false,
error: { cause: "ADMISSION_REJECTED", detail: "late" },
});
expect(memory.readRaw("rows", "e")).toBeUndefined();
});
});
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import {
composeInstalledMessageCatalogs,
INSTALLED_MESSAGE_CATALOGS,
} from "../../src/features/installed-feature-messages.ts";
import { INSTALLED_PRODUCT_FEATURE_MODULES } from "../../src/features/installed-product-manifest.ts";
import { TECH_LOG_MESSAGE_CATALOGS } from "../../src/features/tech-log/contracts/tech-log-message-catalog.ts";
// Template sync (af3d8e6). TechLog's catalogs are composed directly beside the
// installed modules' (src/features/tech-log/NOT_INSTALLED).
const SOURCES = [
...INSTALLED_PRODUCT_FEATURE_MODULES,
{ messages: TECH_LOG_MESSAGE_CATALOGS },
];
describe("installed feature message catalogs (Q-6.9-12)", () => {
it("keeps every message each installed feature declares", () => {
// Read from the installed modules, not a named sample: the catalog is
// empty once the sample is removed (FE-GATE-020), and that is still valid.
const locales = new Set(
SOURCES.flatMap((module) => Object.keys(module.messages)),
);
expect(Object.keys(INSTALLED_MESSAGE_CATALOGS).sort()).toEqual([...locales].sort());
for (const module of SOURCES) {
for (const [locale, catalog] of Object.entries(module.messages)) {
expect(INSTALLED_MESSAGE_CATALOGS[locale as keyof typeof INSTALLED_MESSAGE_CATALOGS])
.toMatchObject(catalog);
}
}
});
it("composes every locale a feature declares, not a fixed list", () => {
const catalogs = composeInstalledMessageCatalogs([
{ messages: { "ko-KR": { a: "가" }, "ja-JP": { a: "あ" } } },
{ messages: { "ko-KR": { b: "나" } } },
]);
expect(catalogs).toEqual({
"ko-KR": { a: "가", b: "나" },
"ja-JP": { a: "あ" },
});
expect(Object.isFrozen(catalogs["ko-KR"])).toBe(true);
});
it("rejects a key two features define for the same locale", () => {
expect(() =>
composeInstalledMessageCatalogs([
{ messages: { "en-US": { a: "A" } } },
{ messages: { "en-US": { a: "B" } } },
]),
).toThrow("Duplicate en-US message key: a");
});
});
+106
View File
@@ -0,0 +1,106 @@
import { spawn } from "node:child_process";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
assertPortUnused,
assertServedRelease,
previewArguments,
summarizeSamples,
} from "../../scripts/lib/lab-performance.ts";
/**
* 11-07. The lab performance gate measured once, and measured whatever server
* held its port: `vite preview` without `--strictPort` moved elsewhere and the
* script never checked which build answered.
*/
const servers: Server[] = [];
afterEach(async () => {
await Promise.all(
servers.splice(0).map(
(server) => new Promise<void>((resolve) => server.close(() => resolve())),
),
);
});
async function foreignServer(manifest: unknown): Promise<string> {
const server = createServer((_request, response) => {
response
.writeHead(200, { "content-type": "application/json" })
.end(JSON.stringify(manifest));
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
}
describe("lab performance gate (11-07)", () => {
it("starts the preview server on exactly the requested port", () => {
expect(previewArguments(4173)).toEqual([
"pnpm",
"preview",
"--host",
"127.0.0.1",
"--port",
"4173",
"--strictPort",
]);
});
it("summarizes repeated runs by their median and keeps every sample", () => {
expect(summarizeSamples([326, 1103, 410, 390, 505])).toEqual({
median: 410,
min: 326,
max: 1103,
samples: [326, 1103, 410, 390, 505],
});
expect(summarizeSamples([1, 4, 2, 3]).median).toBe(2.5);
expect(() => summarizeSamples([])).toThrow(RangeError);
});
it("refuses a port that another server already answers on", async () => {
const baseUrl = await foreignServer({});
await expect(assertPortUnused(baseUrl)).rejects.toThrow(/another server/u);
await expect(assertPortUnused("http://127.0.0.1:9")).resolves.toBeUndefined();
});
it("refuses a server that serves a different build", async () => {
const baseUrl = await foreignServer({ buildId: "other", releaseId: "r1" });
await expect(
assertServedRelease(baseUrl, { buildId: "measured", releaseId: "r1" }),
).rejects.toThrow(/serves build other\/r1, not the measured measured\/r1/u);
await expect(
assertServedRelease(baseUrl, { buildId: "other", releaseId: "r1" }),
).resolves.toBeUndefined();
});
it("fails the gate before measuring when its port is taken", async () => {
const baseUrl = await foreignServer({ buildId: "other", releaseId: "r1" });
const child = spawn(
process.execPath,
[path.resolve("scripts/test-performance.ts")],
{
env: { ...process.env, LAB_PERFORMANCE_PORT: new URL(baseUrl).port },
stdio: ["ignore", "ignore", "pipe"],
},
);
let stderr = "";
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
});
const code = await new Promise<number | null>((resolve) => {
const timer = setTimeout(() => child.kill("SIGKILL"), 20_000);
child.on("exit", (exitCode) => {
clearTimeout(timer);
resolve(exitCode);
});
});
expect(code).not.toBe(0);
expect(stderr).toMatch(/another server holds the port/u);
}, 30_000);
});
@@ -115,11 +115,21 @@ describe("OPT-NET-02 shared idempotency key validation", () => {
"key\u007fdelete",
"key\u009fc1",
"a".repeat(257),
// R-7.1. fetch strips surrounding whitespace, so " order-1 " would reach
// the wire as "order-1" and collide with another command's key.
" order-1 ",
"order-1\t",
"key with-space",
// R-7.1. A non-ByteString value makes Headers.set throw a TypeError that
// the client reports as a retryable network failure.
"키-값",
"ключ",
"key nbsp",
];
it("rejects the same values at intent definition and at admission", () => {
for (const value of rejected) {
expect(isValidIdempotencyKey(value)).toBe(false);
expect(isValidIdempotencyKey(value), JSON.stringify(value)).toBe(false);
expect(() =>
defineMutationIntent({
intentId: "intent-1",
@@ -132,8 +142,13 @@ describe("OPT-NET-02 shared idempotency key validation", () => {
}
});
it("accepts the bounded printable and Unicode values both sides allow", () => {
for (const value of ["key-1", "a".repeat(256), "키-값", "ключ"]) {
it("accepts the bounded visible-ASCII values both sides allow", () => {
for (const value of [
"key-1",
"a".repeat(256),
"0f8fad5b-d9cb-469f-a165-70867728950e",
"!~",
]) {
expect(isValidIdempotencyKey(value)).toBe(true);
expect(
defineMutationIntent({
+54
View File
@@ -0,0 +1,54 @@
import { describe, expect, it, vi } from "vitest";
import {
createLocalDraftFeatureInput,
type LocalDraftStore,
} from "../../src/features/local-draft-feature/application/local-draft-api.ts";
function recordingStore() {
const save = vi.fn<LocalDraftStore["save"]>(async () =>
Object.freeze({ ok: true as const, value: Object.freeze({ revision: 1 }) }),
);
const store: LocalDraftStore = Object.freeze({
save,
find: async () => Object.freeze({ ok: true as const, value: null }),
remove: async () => Object.freeze({ ok: true as const, value: undefined }),
});
return { save, store };
}
function command(draft: Readonly<{ draftId: string; title: string; body: string }>) {
return Object.freeze({ draft, expectedRevision: null, idempotencyKey: "save-1" });
}
describe("local-draft save applies the domain rules (09-06)", () => {
it.each([
["a blank draft id", { draftId: " ", title: "Title", body: "" }],
["a blank title", { draftId: "draft-1", title: " ", body: "" }],
["a 161-character title", { draftId: "draft-1", title: "t".repeat(161), body: "" }],
["a body over 100,000 characters", { draftId: "draft-1", title: "Title", body: "b".repeat(100_001) }],
])("rejects %s without calling the store", async (_case, draft) => {
const { save, store } = recordingStore();
const result = await createLocalDraftFeatureInput(store).saveDraft(command(draft));
expect(result).toMatchObject({
ok: false,
error: { kind: "VALIDATION_REJECTED", operationId: "LOCAL_DRAFT_SAVE" },
});
expect(save).not.toHaveBeenCalled();
});
it("stores the normalized draft at the limits", async () => {
const { save, store } = recordingStore();
const title = "t".repeat(160);
const body = "b".repeat(100_000);
await expect(
createLocalDraftFeatureInput(store).saveDraft(
command({ draftId: " draft-1 ", title: ` ${title} `, body }),
),
).resolves.toEqual({ ok: true, value: { revision: 1 } });
expect(save).toHaveBeenCalledWith(
expect.objectContaining({ draft: { draftId: "draft-1", title, body } }),
undefined,
);
});
});
+38
View File
@@ -1,8 +1,11 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import {
MANUAL_A11Y_ROUTE_IDS,
validateManualA11yEvidence,
validateManualA11yRecordFormat,
} from "../../scripts/lib/manual-a11y-evidence.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
@@ -64,4 +67,39 @@ describe("manual accessibility evidence", () => {
passed: false,
});
});
// 08-06: the merge stage checks only that each record keeps the template's
// shape; the signed review itself is a release-stage gate (FE-GATE-028).
describe("record format", () => {
const pending = reviewed
.replace("Status: reviewed", "Status: pending-manual-review")
.replace("Release ID: release-1", "Release ID:")
.replace("Reviewer: reviewer@example.test", "Reviewer:")
.replace("Reviewed at: 2026-07-25T12:00:00Z", "Reviewed at:")
.replace("Signature: review-record-1", "Signature:")
.replace("Attestation: accepted", "Attestation: pending")
.replace("M1 Keyboard: pass", "M1 Keyboard: pending");
it("accepts a pending template and a signed record", () => {
expect(validateManualA11yRecordFormat(pending, "TECH_LOG_HOME")).toEqual([]);
expect(validateManualA11yRecordFormat(reviewed, "TECH_LOG_HOME")).toEqual([]);
});
it("accepts every checked-in route record", () => {
for (const routeId of MANUAL_A11Y_ROUTE_IDS) {
const record = readFileSync(`artifacts/tests/a11y-manual/${routeId}.md`, "utf8");
expect(validateManualA11yRecordFormat(record, routeId), routeId).toEqual([]);
}
});
it.each([
["a missing field", pending.replace("Signature:\n", ""), "TECH_LOG_HOME", "Signature"],
["an unknown status", pending.replace("Status: pending-manual-review", "Status: done"), "TECH_LOG_HOME", "Status"],
["an unknown verdict", pending.replace("M1 Keyboard: pending", "M1 Keyboard: ok"), "TECH_LOG_HOME", "M1 Keyboard"],
["another route's record", pending, "NOT_FOUND", "Route ID"],
["a reviewed record that is not complete", reviewed.replace("Signature: review-record-1", "Signature:"), "TECH_LOG_HOME", "Signature"],
])("rejects %s", (_name, record, routeId, field) => {
expect(validateManualA11yRecordFormat(record, routeId)).toContain(field);
});
});
});
@@ -0,0 +1,120 @@
import { describe, expect, it } from "vitest";
import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts";
/**
* 05-08. Where the fake used to part from native IndexedDB, each case pins
* the native result, so a test built on the fake cannot pass on a behavior no
* browser has.
*/
function settle<Value>(request: IDBRequest<Value>): Promise<Value> {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function outcome(transaction: IDBTransaction): Promise<string> {
return new Promise((resolve) => {
transaction.oncomplete = () => resolve("complete");
transaction.onabort = () =>
resolve(`abort:${transaction.error?.name ?? "none"}`);
});
}
async function openWithStore(
memory: MemoryIndexedDbFactory,
name: string,
): Promise<IDBDatabase> {
const request = memory.factory.open(name, 1);
request.onupgradeneeded = () => {
request.result.createObjectStore("s", { keyPath: "k" });
};
return await settle(request);
}
describe("05-08 memory IndexedDB matches native semantics the adapters rely on", () => {
it("(a) runs overlapping readwrite transactions one after another", async () => {
const memory = new MemoryIndexedDbFactory();
const database = await openWithStore(memory, "a");
memory.seed("s", { k: "counter", n: 0 });
const first = database.transaction(["s"], "readwrite");
const second = database.transaction(["s"], "readwrite");
const settled = [outcome(first), outcome(second)];
for (const transaction of [first, second]) {
const read = transaction.objectStore("s").get("counter");
read.onsuccess = () => {
const { n } = read.result as { n: number };
transaction.objectStore("s").put({ k: "counter", n: n + 1 });
};
}
expect(await Promise.all(settled)).toEqual(["complete", "complete"]);
expect(memory.readRaw("s", "counter")).toEqual({ k: "counter", n: 2 });
});
it("(b) rejects a request placed after the transaction's task ended", async () => {
const memory = new MemoryIndexedDbFactory();
const database = await openWithStore(memory, "b");
const transaction = database.transaction(["s"], "readwrite");
const settled = outcome(transaction);
await new Promise((resolve) => setTimeout(resolve, 5));
expect(() =>
transaction.objectStore("s").put({ k: "late" }),
).toThrow(expect.objectContaining({ name: "TransactionInactiveError" }));
// A transaction with no request left commits on its own.
expect(await settled).toBe("complete");
expect(memory.readRaw("s", "late")).toBeUndefined();
});
it("(b) keeps a transaction active for requests placed in a success callback's microtasks", async () => {
const memory = new MemoryIndexedDbFactory();
const database = await openWithStore(memory, "b2");
const transaction = database.transaction(["s"], "readwrite");
const settled = outcome(transaction);
const read = transaction.objectStore("s").get("absent");
read.onsuccess = () => {
void Promise.resolve().then(() => {
transaction.objectStore("s").put({ k: "chained" });
});
};
expect(await settled).toBe("complete");
expect(memory.readRaw("s", "chained")).toEqual({ k: "chained" });
});
it("(d) keeps databases of different names apart", async () => {
const memory = new MemoryIndexedDbFactory();
const userA = await openWithStore(memory, "user-A");
await settle(
userA.transaction(["s"], "readwrite").objectStore("s").put({
k: "secret-of-A",
}),
);
let upgraded = false;
const request = memory.factory.open("user-B", 1);
request.onupgradeneeded = () => {
upgraded = true;
request.result.createObjectStore("s", { keyPath: "k" });
};
const userB = await settle(request);
expect(upgraded).toBe(true);
expect(
await settle(
userB.transaction(["s"], "readonly").objectStore("s").get(
"secret-of-A",
),
),
).toBeUndefined();
expect(
await settle(
userA.transaction(["s"], "readonly").objectStore("s").get(
"secret-of-A",
),
),
).toEqual({ k: "secret-of-A" });
});
});
@@ -0,0 +1,120 @@
import { describe, expect, it } from "vitest";
import {
DIAGNOSTIC_CONTEXT_ALLOWLIST,
DIAGNOSTIC_CONTEXT_CARDINALITY,
projectDiagnosticRecord,
statusGroup,
} from "../../src/contracts/diagnostics.ts";
import {
TELEMETRY_ATTRIBUTE_ALLOWLIST,
projectTelemetryEvent,
} from "../../src/contracts/telemetry.ts";
describe("observability cardinality policy", () => {
it("classifies every diagnostic context key exactly once", () => {
expect(Object.keys(DIAGNOSTIC_CONTEXT_CARDINALITY).sort()).toEqual(
[...DIAGNOSTIC_CONTEXT_ALLOWLIST].sort(),
);
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.correlation_id).toBe("request");
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.route_id).toBe("topology");
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.operation_id).toBe("topology");
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.duration_bucket).toBe("bounded");
});
it("keeps request-cardinality keys out of telemetry dimensions", () => {
for (const key of TELEMETRY_ATTRIBUTE_ALLOWLIST) {
expect(DIAGNOSTIC_CONTEXT_CARDINALITY[key]).not.toBe("request");
}
expect(TELEMETRY_ATTRIBUTE_ALLOWLIST).not.toContain("correlation_id");
});
it("rejects free-form values for bounded diagnostic dimensions", () => {
expect(
projectDiagnosticRecord({
level: "info",
eventId: "http.request.completed",
context: {
outcome: "customer-123",
http_status_group: "599",
attempt_count_bucket: "37",
duration_bucket: "12345ms",
},
}),
).toEqual({ success: false, reason: "invalid-context" });
});
it("allows request correlation only in bounded diagnostics evidence", () => {
const projected = projectDiagnosticRecord({
level: "info",
eventId: "http.request.completed",
context: {
correlation_id: "request-a1b2c3",
outcome: "success",
http_status_group: "2xx",
attempt_count_bucket: "1",
duration_bucket: "lt100ms",
},
});
expect(projected.success).toBe(true);
});
});
/**
* R-7.5. One operationId grammar. The V3 composition accepts camelCase ids of
* up to 128 characters; a failure for such an operation must not be dropped
* as an invalid telemetry attribute, and diagnostics apply the same rule.
*/
describe("shared operationId and status-group grammar", () => {
function telemetryFailure(operationId: string, httpStatusGroup = "5xx") {
return projectTelemetryEvent("api.request.failed", {
error_kind: "SERVER_FAILURE",
http_status_group: httpStatusGroup,
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
operation_id: operationId,
});
}
function diagnosticCompletion(operationId: string, httpStatusGroup = "5xx") {
return projectDiagnosticRecord({
level: "warn",
eventId: "http.request.completed",
context: { operation_id: operationId, http_status_group: httpStatusGroup },
});
}
it.each([
"getUser",
"LIST_ORDER_ITEMS",
"users.v1.get-item",
`a${"b".repeat(127)}`,
])("keeps both observability records for operationId %s", (operationId) => {
expect(telemetryFailure(operationId).success).toBe(true);
expect(diagnosticCompletion(operationId).success).toBe(true);
});
it.each(["", "1getUser", "get user", "get:user", "get/user", `a${"b".repeat(128)}`])(
"rejects operationId %j in both sinks",
(operationId) => {
expect(telemetryFailure(operationId)).toEqual({
success: false,
reason: "invalid-attribute-value",
});
expect(diagnosticCompletion(operationId)).toEqual({
success: false,
reason: "invalid-context",
});
},
);
it.each([undefined, 0, 101, 204, 302, 404, 503, 999])(
"accepts the status group statusGroup(%s) produces in both sinks",
(status) => {
const group = statusGroup(status);
expect(telemetryFailure("GET_USER", group).success).toBe(true);
expect(diagnosticCompletion("GET_USER", group).success).toBe(true);
},
);
});
+238 -4
View File
@@ -8,7 +8,6 @@ import type {
OpfsStorageScope,
} from "../../src/application/ports/browser-file-storage/opfs-ports.ts";
import type {
BrowserDataResult,
BrowserStoragePolicy,
ByteSource,
} from "../../src/application/ports/browser-file-storage/shared.ts";
@@ -630,7 +629,7 @@ describe("OPFS byte-store coordinator", () => {
},
{
async abortPreparedPut() {
return browserDataSuccess({ kind: "EFFECT_UNKNOWN" as const });
return browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE");
},
},
]) {
@@ -666,11 +665,120 @@ describe("OPFS byte-store coordinator", () => {
}
});
it("does not roll back journal after an unknown worker mutation effect", async () => {
it("05-01 decides a reconciled row from what the journal holds once its lock is taken", async () => {
// Listed while its owner still ran, the row was PREPARING. By the time
// the owner let go it had committed and only finalization failed, so the
// staging receipt names the committed generation. Cleaning it up from the
// stale snapshot would delete a committed object.
const journal = createJournal();
const row: OpfsJournalTransaction = {
transactionId: "transaction_12345678",
fencingToken: "fencing_12345678",
mutation: "PUT",
scope,
phase: "PREPARING",
objectId: "object_12345678",
expectedGeneration: null,
targetGeneration: 1,
targetByteLength: 1,
targetStoragePolicy: storagePolicy,
budgetReservation: {
namespace: scope.namespace,
reservedBytes: 1,
hardBudgetBytes: storagePolicy.hardBudgetBytes,
},
startedAtEpochMs: 100,
};
journal.transactions.set(row.transactionId, {
...row,
phase: "COMMITTED",
preparedObject: committedObject("object_12345678", storagePolicy, 100),
});
vi.spyOn(journal, "listIncomplete").mockResolvedValueOnce(
browserDataSuccess({ transactions: [row], moreAvailable: false }),
);
const worker = createWorker();
const cleanupTransaction = vi.spyOn(worker, "cleanupTransaction");
const finalizePut = vi.spyOn(worker, "finalizePut");
const adapter = createOpfsByteStoreAdapter({
journal,
worker,
scope,
storagePolicy,
now: () => 100,
});
expect(await adapter.maintenance.reconcile()).toMatchObject({
ok: true,
value: { inspectedTransactions: 1, rolledBackTransactions: 0 },
});
expect(cleanupTransaction).not.toHaveBeenCalled();
expect(finalizePut).toHaveBeenCalledTimes(1);
});
it("05-02 skips a row it cannot reconcile, settles the rest and still runs orphan GC", async () => {
const journal = createJournal();
const row = (transactionId: string): OpfsJournalTransaction => ({
transactionId,
fencingToken: "fencing_12345678",
mutation: "PUT",
scope,
phase: "PREPARING",
objectId: `object_${transactionId.slice(-8)}`,
expectedGeneration: null,
targetGeneration: 1,
targetByteLength: 1,
targetStoragePolicy: storagePolicy,
budgetReservation: {
namespace: scope.namespace,
reservedBytes: 1,
hardBudgetBytes: storagePolicy.hardBudgetBytes,
},
startedAtEpochMs: 100,
});
journal.transactions.set("transaction_broken_1", row("transaction_broken_1"));
journal.transactions.set("transaction_healthy_1", row("transaction_healthy_1"));
const worker = createWorker({
async cleanupTransaction(_scope, transactionId) {
return transactionId === "transaction_broken_1"
? browserDataFailure("CORRUPT_DATA", "OBJECT_RECONCILE")
: browserDataSuccess({ kind: "CLEANED" as const });
},
});
const listOrphanCandidates = vi.spyOn(worker, "listOrphanCandidates");
const observations: unknown[] = [];
const adapter = createOpfsByteStoreAdapter({
journal,
worker,
scope,
storagePolicy,
now: () => 100,
observer: (event) => observations.push(event),
});
expect(await adapter.maintenance.reconcile()).toMatchObject({
ok: true,
value: {
inspectedTransactions: 2,
failedTransactions: 1,
rolledBackTransactions: 1,
orphanGcStatus: "COMPLETED",
},
});
expect([...journal.transactions.keys()]).toEqual(["transaction_broken_1"]);
expect(listOrphanCandidates).toHaveBeenCalledTimes(1);
expect(observations).toContainEqual({
operation: "OBJECT_RECONCILE",
outcome: "FAILED",
failureCode: "CORRUPT_DATA",
});
});
it("does not roll back journal after an unconfirmed worker cleanup", async () => {
const journal = createJournal();
const worker = createWorker({
async abortPreparedPut() {
return browserDataSuccess({ kind: "EFFECT_UNKNOWN" as const });
return browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE");
},
});
const rollback = vi.spyOn(journal, "rollback");
@@ -697,6 +805,130 @@ describe("OPFS byte-store coordinator", () => {
expect(rollback).not.toHaveBeenCalled();
});
/**
* Q-6.5-9. A failed compensation leaves the journal row for reconciliation,
* but the caller still needs to know why the put failed: a cancel or a full
* disk must not turn into a bare CONFLICT.
*/
describe("Q-6.5-9 keeps the put's own failure when compensation fails", () => {
const quota = browserDataFailure("QUOTA_EXCEEDED", "OBJECT_WRITE", {
retryable: true,
recovery: "READ_ONLY",
});
async function putWith(
worker: Partial<OpfsWorkerGateway>,
journal = createJournal(),
) {
const adapter = createOpfsByteStoreAdapter({
journal,
worker: createWorker(worker),
scope,
storagePolicy,
createTransactionId: () => "transaction_12345678",
now: () => 100,
});
return await adapter.objects.put({
objectId: "object_12345678",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: sourceFrom(new Uint8Array([1])),
});
}
it.each([
[
"a failed cleanup",
async () => browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE"),
],
[
"an aborted cleanup",
async () => browserDataFailure("ABORTED", "OBJECT_RECONCILE"),
],
])("after %s", async (_label, abortPreparedPut) => {
const journal = createJournal();
expect(
await putWith(
{ preparePut: async () => quota, abortPreparedPut },
journal,
),
).toEqual({
ok: false,
error: {
code: "QUOTA_EXCEEDED",
operation: "OBJECT_WRITE",
retryable: true,
recovery: "RECONCILE",
},
});
expect(
journal.transactions.get("transaction_12345678")?.phase,
).toBe("PREPARING");
});
it("keeps a caller cancel as ABORTED", async () => {
expect(
await putWith({
preparePut: async () =>
browserDataFailure("ABORTED", "OBJECT_WRITE"),
abortPreparedPut: async () =>
browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE"),
}),
).toMatchObject({
ok: false,
error: { code: "ABORTED", recovery: "RECONCILE" },
});
});
it("after a failed journal rollback", async () => {
const journal = createJournal();
vi.spyOn(journal, "rollback").mockResolvedValueOnce(
browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE"),
);
expect(
await putWith({ preparePut: async () => quota }, journal),
).toMatchObject({
ok: false,
error: {
code: "QUOTA_EXCEEDED",
operation: "OBJECT_WRITE",
recovery: "RECONCILE",
},
});
});
it("after FILES_READY could not be recorded", async () => {
const journal = createJournal();
vi.spyOn(journal, "markFilesReady").mockResolvedValueOnce(
browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE", {
retryable: true,
recovery: "REOPEN",
}),
);
expect(
await putWith(
{
abortPreparedPut: async () =>
browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE"),
},
journal,
),
).toEqual({
ok: false,
error: {
code: "UNAVAILABLE",
operation: "OBJECT_WRITE",
retryable: true,
recovery: "RECONCILE",
},
});
});
it("returns the put's failure unchanged when compensation succeeds", async () => {
expect(await putWith({ preparePut: async () => quota })).toEqual(quota);
});
});
it("holds the OPFS mutation lease until exact physical cleanup completes", async () => {
const journal = createJournal();
const observed: Array<Readonly<Record<string, unknown>>> = [];
@@ -1100,11 +1332,13 @@ describe("OPFS byte-store coordinator", () => {
orphanGcStatus: "COMPLETED",
},
});
// The first page carries no cursor.
expect(listOrphans).toHaveBeenCalledWith(
scope,
expect.any(Number),
expect.any(Number),
undefined,
undefined,
);
expect(deleteOrphan).toHaveBeenCalledWith(
scope,
File diff suppressed because it is too large Load Diff
+58
View File
@@ -87,4 +87,62 @@ describe("optional runtime host", () => {
expect(runtime.health().serviceWorker).toBe("DISABLED");
expect(runtime.browserLifecycle()).toBeNull();
});
// 06-05. An ACTIVE selection whose worker install fails must be visible to
// operators, not only in `health()`, which nothing reads.
it.each([
{
outcome: { kind: "FAILED", code: "INSTALL_FAILED" } as const,
events: [
[
"service-worker.start.failed",
{ error_kind: "INSTALL_FAILED", build_id: "build-1" },
],
],
},
{
outcome: { kind: "INCOMPATIBLE" } as const,
events: [
[
"service-worker.start.failed",
{ error_kind: "INCOMPATIBLE", build_id: "build-1" },
],
],
},
{ outcome: { kind: "ACTIVE", buildId: "build-1" } as const, events: [] },
{ outcome: { kind: "RELOAD_TO_ENABLE" } as const, events: [] },
])(
"records $outcome.kind as $events.length telemetry event(s)",
async ({ outcome, events }) => {
const emit = vi.fn();
const runtime = createOptionalRuntimeHost({
capabilities: {
...capabilities,
serviceWorker: {
mode: "ACTIVE",
scriptPath: "service-worker.js",
handlers: ["PWA_STATIC_ASSETS"],
},
},
routerBasePath: "/",
buildId: "build-1",
serviceWorkerHost: {
start: vi.fn(async (): Promise<ServiceWorkerStartOutcome> => outcome),
requestActivation: vi.fn(),
resetOwnedCaches: vi.fn(),
stop: vi.fn(async () => {}),
},
browserLifecycleHost: {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
},
telemetry: { emit },
});
await runtime.startAfterMount();
expect(emit.mock.calls).toEqual(events);
await runtime.stop();
},
);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import {
evaluateFieldBudget,
evaluateLabBudget,
percentile75,
} from "../../src/application/policies/performance-budgets.ts";
} from "../../scripts/lib/performance-budgets.ts";
describe("performance budgets", () => {
it("rejects initial and lazy JavaScript above their named limits", () => {
@@ -9,23 +9,12 @@ import {
type SaveFileHandle,
} from "../../src/adapters/browser-files/download-delivery-adapter.ts";
import {
CHECKSUM_HEADER,
CONTROL_ENDPOINT,
DATA_ORIGIN,
DIGEST_HEADER,
DOWNLOAD_HREF,
DOWNLOAD_PATH,
NOW,
POLICY_HEADER,
REQUEST_BINDING_SHA256,
UPLOAD_SESSION_ID,
collect,
createHarness,
downloadCapabilityPayload,
downloadResponse,
jsonResponse,
responseWithUrl,
uploadCapabilityPayload,
} from "./presigned-transfer-fixture.ts";
describe("presigned DownloadDelivery integration", () => {
+232 -3
View File
@@ -4,10 +4,8 @@ import { PRESIGNED_TRANSFER_PROTOCOL } from "../../src/application/ports/browser
import { createPresignedCapabilityVault } from "../../src/adapters/browser-transfer/presigned/presigned-capability-vault.ts";
import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts";
import {
CHECKSUM_HEADER,
CONTROL_ENDPOINT,
DATA_ORIGIN,
DIGEST_HEADER,
DOWNLOAD_HREF,
DOWNLOAD_PATH,
NOW,
@@ -177,6 +175,26 @@ describe("presigned download stream lifecycle", () => {
});
}
// Q-6.1-11. The duplicate check read the issuer's object again after the
// snapshot, so a stateful object could show it a receipt the vault had
// never stored while the snapshot carried one it already held.
it("checks a duplicate receipt against the snapshot, not the issuer's object", () => {
const vault = freshVault();
expect(vault.register(baseRegistration() as never).ok).toBe(true);
const replay = new Proxy(baseRegistration(), {
get(target, key, receiver) {
return key === "capabilityReceipt"
? "capability-never-registered"
: Reflect.get(target, key, receiver);
},
});
expect(vault.register(replay as never)).toMatchObject({
ok: false,
error: { code: "CONFLICT", recovery: "REISSUE_CAPABILITY" },
});
vault.dispose();
});
it("does not observe a mutation of the issuer's object after registration", () => {
const vault = freshVault();
const registration = baseRegistration();
@@ -425,6 +443,51 @@ describe("presigned download stream lifecycle", () => {
]);
});
it("ends a pending read when only the stream consumer signal aborts", async () => {
// R3-2 characterization: the consumer signal is composed into the read
// scope separately from the owner signal, which stays live here.
const bytes = new Uint8Array([1]);
const payload = downloadCapabilityPayload(bytes);
let cancelled = false;
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(
new ReadableStream<Uint8Array>({
pull() {},
cancel() {
cancelled = true;
},
}),
payload,
),
) as unknown as typeof fetch;
const harness = createHarness({ fetcher });
const owner = new AbortController();
const issued = await harness.provider.issueDownload({
resourceId: "resource-1",
signal: owner.signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
const opened = await harness.executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: owner.signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
const consumer = new AbortController();
const pending = collect(opened.value, consumer.signal);
await new Promise((resolve) => setTimeout(resolve, 0));
consumer.abort("consumer");
expect(await pending).toMatchObject([
{ ok: false, error: { code: "ABORTED" } },
]);
expect(owner.signal.aborted).toBe(false);
expect(cancelled).toBe(true);
});
it("rejects an expired capability before data-plane fetch", async () => {
const bytes = new Uint8Array([1]);
const payload = downloadCapabilityPayload(bytes);
@@ -599,9 +662,23 @@ describe("presigned download stream lifecycle", () => {
ok: false,
error: { code: "INVALID_INPUT" },
});
// 01-07. The refused open released the capability from the vault.
expect(
await executor.downloadSources.open({
resourceId: "resource-1",
capability: issuedDownload.value,
signal: new AbortController().signal,
}),
).toMatchObject({ ok: false, error: { code: "POLICY_REJECTED" } });
const reissuedDownload = await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(reissuedDownload.ok).toBe(true);
if (!reissuedDownload.ok) return;
const opened = await executor.downloadSources.open({
resourceId: "resource-1",
capability: issuedDownload.value,
capability: reissuedDownload.value,
signal: new AbortController().signal,
});
expect(opened.ok).toBe(true);
@@ -648,3 +725,155 @@ describe("presigned download stream lifecycle", () => {
});
});
describe("presigned transfer time limits (01-03)", () => {
async function openDownload(
bytes: Uint8Array,
pull: (controller: ReadableStreamDefaultController<Uint8Array>) => Promise<void> | void,
options: Readonly<{ minTransferBytesPerSecond: number; idleTimeoutMs?: number }>,
) {
const payload = downloadCapabilityPayload(bytes);
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(new ReadableStream<Uint8Array>({ pull }), payload),
) as unknown as typeof fetch;
const harness = createHarness({ fetcher, ...options });
const issued = await harness.provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
if (!issued.ok) throw new Error("issue failed");
const opened = await harness.executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: new AbortController().signal,
});
if (!opened.ok) throw new Error("open failed");
return opened.value;
}
it("keeps a slow but progressing download past the base deadline", async () => {
vi.useFakeTimers();
try {
const bytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let offset = 0;
// Two bytes every 3 s: 12 s in total against a 5 s base deadline.
const source = await openDownload(
bytes,
async (controller) => {
await new Promise((resolve) => setTimeout(resolve, 3_000));
controller.enqueue(bytes.slice(offset, offset + 2));
offset += 2;
if (offset >= bytes.byteLength) controller.close();
},
{ minTransferBytesPerSecond: 1 },
);
const pending = collect(source);
await vi.advanceTimersByTimeAsync(12_500);
const results = await pending;
expect(results.every((result) => result.ok)).toBe(true);
expect(results).toHaveLength(4);
} finally {
vi.useRealTimers();
}
});
it("ends a download whose stream stops making progress at the idle limit", async () => {
vi.useFakeTimers();
try {
const bytes = new Uint8Array([1, 2, 3, 4]);
let pulls = 0;
const source = await openDownload(
bytes,
(controller) => {
pulls += 1;
if (pulls === 1) controller.enqueue(bytes.slice(0, 2));
// Then the connection stalls: no more chunks, no close.
return pulls === 1 ? undefined : new Promise<void>(() => {});
},
{ minTransferBytesPerSecond: 1, idleTimeoutMs: 2_000 },
);
let settled = false;
const pending = collect(source).finally(() => {
settled = true;
});
await vi.advanceTimersByTimeAsync(1_900);
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(200);
expect(settled).toBe(true);
expect((await pending).at(-1)).toMatchObject({
ok: false,
error: { code: "UNAVAILABLE", recovery: "REISSUE_CAPABILITY" },
});
} finally {
vi.useRealTimers();
}
});
it("extends a PUT deadline by the part's byte allowance", async () => {
vi.useFakeTimers();
try {
const original = new Uint8Array(60).fill(7);
const checksum = sha256Hex(original);
const payload = uploadCapabilityPayload({ bytes: original, checksum });
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === CONTROL_ENDPOINT) return jsonResponse(payload);
// 30 ms past the 5 s base deadline; 60 bytes at 1000 B/s allow 60 ms.
await new Promise((resolve) => setTimeout(resolve, 5_030));
return responseWithUrl(
new Response(null, {
status: 200,
headers: {
[POLICY_HEADER]: "v1",
"Content-Length": "0",
ETag: "\"part-etag-slow\"",
},
}),
String(payload.href),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({
fetcher,
minTransferBytesPerSecond: 1_000,
digestBytes: async (bytes) => sha256Hex(bytes),
});
const issued = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: original.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
if (!issued.ok) throw new Error("issue failed");
const pending = executor.uploadParts.put({
capability: issued.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: original.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes: original,
signal: new AbortController().signal,
});
await vi.advanceTimersByTimeAsync(5_040);
expect(await pending).toMatchObject({
ok: true,
value: { receiptToken: "part-etag-slow" },
});
} finally {
vi.useRealTimers();
}
});
});
+12
View File
@@ -158,6 +158,9 @@ export function createHarness(input: Readonly<{
now?: () => number;
digestBytes?: PresignedTransferExecutorOptions["digestBytes"];
scheduler?: PresignedTransferExecutorOptions["scheduler"];
minTransferBytesPerSecond?: number;
idleTimeoutMs?: number;
maxClockSkewMs?: number;
observer?: Readonly<{
record(observation: BrowserDataObservation): void;
}>;
@@ -193,6 +196,9 @@ export function createHarness(input: Readonly<{
now,
scheduler: input.scheduler,
observer: input.observer,
...(input.maxClockSkewMs === undefined
? {}
: { maxClockSkewMs: input.maxClockSkewMs }),
});
const executor = createPresignedTransferExecutor({
vault,
@@ -207,6 +213,12 @@ export function createHarness(input: Readonly<{
scheduler: input.scheduler,
digestBytes: input.digestBytes,
observer: input.observer,
...(input.minTransferBytesPerSecond === undefined
? {}
: { minTransferBytesPerSecond: input.minTransferBytesPerSecond }),
...(input.idleTimeoutMs === undefined
? {}
: { idleTimeoutMs: input.idleTimeoutMs }),
});
return { provider, executor, vault };
}
+334 -5
View File
@@ -5,11 +5,7 @@ import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/increme
import {
CHECKSUM_HEADER,
CONTROL_ENDPOINT,
DATA_ORIGIN,
DIGEST_HEADER,
DOWNLOAD_HREF,
DOWNLOAD_PATH,
NOW,
POLICY_HEADER,
REQUEST_BINDING_SHA256,
UPLOAD_SESSION_ID,
@@ -526,8 +522,10 @@ describe("presigned upload part execution", () => {
outcome: "SUCCEEDED",
byteBucket: "LT1MIB",
},
// 01-10. A PUT attempt is PRESIGNED_TRANSFER; UPLOAD_PART is the
// resumable runtime's one record per part.
{
operation: "UPLOAD_PART",
operation: "PRESIGNED_TRANSFER",
outcome: "SUCCEEDED",
byteBucket: "LT1MIB",
},
@@ -547,3 +545,334 @@ describe("presigned upload part execution", () => {
});
});
/**
* R-1.2. The control plane accepts base64url IDs (`[A-Za-z0-9_-]{8,512}`), but
* the presigned layer re-checked them with its own grammar and refused IDs that
* start with `-`/`_` or exceed 256 characters, so every part issue for such a
* session failed as INVALID_INPUT.
*/
describe("presigned layer accepts every control-plane opaque ID", () => {
const controlPlaneIds = [
["a leading '-'", `-${"aZ09_-".repeat(7)}`],
["a leading '_'", `_${"aZ09_-".repeat(7)}`],
["512 characters", "Q".repeat(512)],
] as const;
it.each(controlPlaneIds)(
"issues and PUTs an upload part for a session ID with %s",
async (_label, sessionId) => {
const bytes = new Uint8Array([4, 5, 6]);
const checksum = sha256Hex(bytes);
const idempotencyKey = `_${sessionId.slice(1, 43)}`;
const payload = uploadCapabilityPayload(
{ bytes, checksum },
{
binding: {
...uploadCapabilityPayload({ bytes, checksum }).binding,
sessionId,
idempotencyKey,
},
},
);
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === CONTROL_ENDPOINT) return jsonResponse(payload);
return responseWithUrl(
new Response(null, {
status: 200,
headers: {
[POLICY_HEADER]: "v1",
"Content-Length": "0",
ETag: "\"part-etag-1\"",
},
}),
String(payload.href),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const binding = {
sessionId,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey,
};
const issued = await provider.issueUploadPart({
...binding,
mediaType: "application/octet-stream",
signal: new AbortController().signal,
});
expect(issued).toMatchObject({ ok: true });
if (!issued.ok) return;
await expect(
executor.uploadParts.put({
...binding,
capability: issued.value,
bytes,
signal: new AbortController().signal,
}),
).resolves.toMatchObject({ ok: true });
},
);
it.each(controlPlaneIds)(
"issues a download capability for a resource ID with %s",
async (_label, resourceId) => {
const payload = downloadCapabilityPayload(new Uint8Array([1, 2]), {
binding: { kind: "DOWNLOAD", resourceId },
});
const fetcher = vi.fn(async () =>
jsonResponse(payload),
) as unknown as typeof fetch;
const { provider } = createHarness({ fetcher });
await expect(
provider.issueDownload({
resourceId,
signal: new AbortController().signal,
}),
).resolves.toMatchObject({ ok: true });
},
);
});
describe("presigned vault slot release (01-07)", () => {
const scenarios = {
"the digest does not match": {
digest: async () => "f".repeat(64),
abortDuringDigest: false,
sessionId: UPLOAD_SESSION_ID,
code: "INTEGRITY_FAILED",
},
"the caller aborts during the digest": {
digest: async (bytes: Uint8Array) => sha256Hex(bytes),
abortDuringDigest: true,
sessionId: UPLOAD_SESSION_ID,
code: "ABORTED",
},
"the PUT binding check refuses it": {
digest: async (bytes: Uint8Array) => sha256Hex(bytes),
abortDuringDigest: false,
sessionId: "another-session",
code: "POLICY_REJECTED",
},
} as const;
it.each(Object.keys(scenarios) as (keyof typeof scenarios)[])(
"frees the only vault slot when %s",
async (name) => {
const scenario = scenarios[name];
const bytes = new Uint8Array([9, 8, 7]);
const checksum = sha256Hex(bytes);
let issued = 0;
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) !== CONTROL_ENDPOINT) {
throw new Error("no PUT is expected");
}
issued += 1;
return jsonResponse(
uploadCapabilityPayload(
{ bytes, checksum },
{ capabilityReceipt: `capability-upload-${issued}` },
),
);
}) as unknown as typeof fetch;
const controller = new AbortController();
const { provider, executor } = createHarness({
fetcher,
maxActiveCapabilities: 1,
digestBytes: async (value) => {
if (scenario.abortDuringDigest) controller.abort();
return await scenario.digest(value);
},
});
const issue = async () =>
await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
const first = await issue();
if (!first.ok) throw new Error("issue failed");
const put = await executor.uploadParts.put({
capability: first.value,
sessionId: scenario.sessionId,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: controller.signal,
});
expect(put).toMatchObject({ ok: false, error: { code: scenario.code } });
expect((await issue()).ok).toBe(true);
},
);
const earlyExits = {
"the caller signal is already aborted": {
override: { signal: AbortSignal.abort() },
code: "ABORTED",
},
"the byte length does not match the bytes": {
override: { byteLength: 4 },
code: "INTEGRITY_FAILED",
},
"the input is invalid": {
override: { idempotencyKey: "" },
code: "INVALID_INPUT",
},
"the signal is not an AbortSignal": {
override: { signal: {} as AbortSignal },
code: "INVALID_INPUT",
},
} as const;
it.each(Object.keys(earlyExits) as (keyof typeof earlyExits)[])(
"frees the only vault slot when put() returns early because %s",
async (name) => {
const bytes = new Uint8Array([9, 8, 7]);
const checksum = sha256Hex(bytes);
let issued = 0;
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) !== CONTROL_ENDPOINT) {
throw new Error("no PUT is expected");
}
issued += 1;
return jsonResponse(
uploadCapabilityPayload(
{ bytes, checksum },
{ capabilityReceipt: `capability-upload-${issued}` },
),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({
fetcher,
maxActiveCapabilities: 1,
});
const issue = async () =>
await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
const first = await issue();
if (!first.ok) throw new Error("issue failed");
const { override, code } = earlyExits[name];
const put = await executor.uploadParts.put({
capability: first.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: new AbortController().signal,
...override,
});
expect(put).toMatchObject({ ok: false, error: { code } });
expect((await issue()).ok).toBe(true);
},
);
it.each([
["the caller signal is already aborted", AbortSignal.abort(), "ABORTED"],
["the signal is not an AbortSignal", {} as AbortSignal, "INVALID_INPUT"],
] as const)(
"frees the only vault slot when open() returns early because %s",
async (_name, signal, code) => {
const bytes = new Uint8Array([1, 2, 3]);
let issued = 0;
const fetcher = vi.fn(async () => {
issued += 1;
return jsonResponse(
downloadCapabilityPayload(bytes, {
capabilityReceipt: `capability-download-${issued}`,
}),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({
fetcher,
maxActiveCapabilities: 1,
});
const issue = async () =>
await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
const first = await issue();
if (!first.ok) throw new Error("issue failed");
const opened = await executor.downloadSources.open({
resourceId: "resource-1",
capability: first.value,
signal,
});
expect(opened).toMatchObject({ ok: false, error: { code } });
expect((await issue()).ok).toBe(true);
},
);
it("frees the only vault slot when a download open is refused", async () => {
const bytes = new Uint8Array([1, 2, 3]);
let issued = 0;
const fetcher = vi.fn(async () => {
issued += 1;
return jsonResponse(
downloadCapabilityPayload(bytes, {
capabilityReceipt: `capability-download-${issued}`,
}),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({
fetcher,
maxActiveCapabilities: 1,
});
const issue = async () =>
await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
const first = await issue();
if (!first.ok) throw new Error("issue failed");
const opened = await executor.downloadSources.open({
resourceId: "resource-2",
capability: first.value,
signal: new AbortController().signal,
});
expect(opened).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
expect((await issue()).ok).toBe(true);
});
});
+125 -3
View File
@@ -1,3 +1,5 @@
import { createHash } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import {
@@ -5,16 +7,17 @@ import {
type PresignedDownloadCapability,
} from "../../src/application/ports/browser-transfer/presigned-transfer.ts";
import { createPresignedCapabilityVault } from "../../src/adapters/browser-transfer/presigned/presigned-capability-vault.ts";
import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts";
import {
CHECKSUM_HEADER,
createStreamingSha256Verifier,
sha256Hex,
} from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts";
import {
CONTROL_ENDPOINT,
DATA_ORIGIN,
DIGEST_HEADER,
DOWNLOAD_HREF,
DOWNLOAD_PATH,
NOW,
POLICY_HEADER,
REQUEST_BINDING_SHA256,
UPLOAD_SESSION_ID,
collect,
@@ -32,8 +35,66 @@ describe("presigned transfer capability issuance and admission", () => {
expect(sha256Hex(new TextEncoder().encode("abc"))).toBe(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
);
// FIPS 180-2 two-block vector: the padding spills into a second block.
expect(
sha256Hex(
new TextEncoder().encode(
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
),
),
).toBe(
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
);
});
it("agrees with node:crypto across block boundaries and chunk splits", () => {
for (const size of [
...Array.from({ length: 130 }, (_, index) => index),
1023,
1024,
4097,
]) {
const bytes = Uint8Array.from({ length: size }, (_, index) =>
(index * 31 + size) % 256,
);
const expected = createHash("sha256").update(bytes).digest("hex");
expect(sha256Hex(bytes)).toBe(expected);
const verifier = createStreamingSha256Verifier(expected);
for (let offset = 0, step = 1; offset < size; offset += step, step += 7) {
verifier.update(bytes.subarray(offset, offset + step));
}
expect(verifier.verify()).toBe(true);
}
});
it.each([
[500, true],
[501, false],
] as const)(
"accepts a max-TTL capability from a server %i ms ahead: %s (01-06)",
async (skewMs, accepted) => {
const bytes = new Uint8Array([1, 2, 3]);
const payload = downloadCapabilityPayload(bytes, {
// The harness allows 60 s; the server clock runs `skewMs` ahead.
expiresAtEpochMs: NOW + skewMs + 60_000,
});
const fetcher = vi.fn(async () =>
jsonResponse(payload),
) as unknown as typeof fetch;
const { provider } = createHarness({ fetcher, maxClockSkewMs: 500 });
const issued = await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(accepted);
if (!accepted) {
expect(issued).toMatchObject({ error: { code: "POLICY_REJECTED" } });
}
},
);
it("answers a refused capability envelope with a re-issuable recovery", async () => {
// BT-PRE-04. A capability document the adapter will not accept is closed as
// `POLICY_REJECTED`, and the caller's only way forward is a new capability.
@@ -565,6 +626,67 @@ describe("presigned transfer capability issuance and admission", () => {
});
});
// Q-6.1-9. `Number(declaredLength)` accepted "5e0", "0x5" and "+5" as 5.
it("rejects a download Content-Length that is not a plain decimal", async () => {
const bytes = new Uint8Array([1, 2, 3, 4, 5]);
const payload = downloadCapabilityPayload(bytes);
for (const declared of ["5e0", "0x5", "+5", "5.0"]) {
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(bytes.slice().buffer, payload, {
"Content-Length": declared,
}),
) as unknown as typeof fetch;
const harness = createHarness({ fetcher });
const issued = await harness.provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
await expect(
firstStreamResult(
await harness.executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: new AbortController().signal,
}),
),
declared,
).resolves.toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED" },
});
}
});
// Q-6.1-9. The provider and the executor share one status table: a refused
// or failed capability HTTP exchange is recovered by a new capability.
it("maps capability endpoint statuses with the executor's recovery table", async () => {
for (const [status, code, retryable] of [
[401, "PERMISSION_DENIED", false],
[403, "PERMISSION_DENIED", false],
[503, "UNAVAILABLE", true],
[429, "UNAVAILABLE", true],
] as const) {
const fetcher = vi.fn(async () =>
responseWithUrl(new Response(null, { status }), CONTROL_ENDPOINT),
) as unknown as typeof fetch;
const { provider } = createHarness({ fetcher });
expect(
await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
}),
String(status),
).toMatchObject({
ok: false,
error: { code, retryable, recovery: "REISSUE_CAPABILITY" },
});
}
});
it("accepts a valid opaque UTF-8 path segment", async () => {
const bytes = new Uint8Array([1, 2, 3]);
// BT-PRE-05. Canonical uppercase percent-hex for a real UTF-8 segment.
@@ -0,0 +1,109 @@
import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { afterAll, describe, expect, it } from "vitest";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
import { filesBelow } from "../../scripts/lib/removal-fixture.ts";
import { ROUTE_FEATURE_OWNER } from "../../src/features/installed-feature-contracts.ts";
import { COMPILED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts";
/**
* 09-02 (D-9). `VITE_PRODUCT_FEATURES=none` has to leave every feature out of
* every consumer, not only the browser bundle: the generated context index
* (router), the installed contract contributions (Node contract-set
* generation) and the built assets. This runs the production generator and a
* Vite build over a copy of the build inputs. Written against whatever
* features the tree declares, so it holds after the sample's removal too.
*/
const BUILD_INPUTS = [
"src",
"public",
"index.html",
"package.json",
"vite.config.ts",
"tsconfig.base.json",
"tsconfig.app.json",
"scripts/lib/vite-module-inventory.ts",
] as const;
// Feature ids stay: the generated index still declares them so the platform
// overview reports NOT_INSTALLED. Their modules and route ids go.
const FEATURE_ROUTE_IDS = Object.keys(ROUTE_FEATURE_OWNER);
// Template sync (af3d8e6). TechLog is composed directly, not selected by
// VITE_PRODUCT_FEATURES (src/features/tech-log/NOT_INSTALLED), so the
// selection governs every feature but it.
const DIRECT_FEATURE_ID = "tech-log";
const FEATURE_MODULE = /^src\/(?:features\/(?!tech-log\/)[^/]+|contexts\/[^/]+)\//u;
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
describe("VITE_PRODUCT_FEATURES=none build (09-02)", () => {
it("leaves every feature out of the context index, the contract set and dist", async () => {
const root = await mkdtemp(path.join(tmpdir(), "product-selection-build-"));
roots.push(root);
for (const input of BUILD_INPUTS) {
await mkdir(path.dirname(path.join(root, input)), { recursive: true });
await cp(path.resolve(input), path.join(root, input), { recursive: true });
}
await linkFixtureNodeModules(root);
const env = { ...process.env, VITE_PRODUCT_FEATURES: "none" };
const generated = spawnSync(
process.execPath,
[path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`],
{ encoding: "utf8", env },
);
expect(generated.stderr).toBe("");
expect(generated.status).toBe(0);
const contextIndex = await readFile(
path.join(root, "src/.generated/product-context-index.ts"),
"utf8",
);
expect(contextIndex).not.toContain("../features/");
const contributions = (await import(
pathToFileURL(path.join(root, "src/features/installed-contract-contributions.ts")).href
)) as typeof import("../../src/features/installed-contract-contributions.ts");
expect(
contributions.INSTALLED_CONTRACT_CONTRIBUTIONS.filter(
(contribution) => contribution.featureId !== DIRECT_FEATURE_ID,
),
).toEqual([]);
const manifest = (await import(
pathToFileURL(path.join(root, "src/features/installed-product-manifest.ts")).href
)) as typeof import("../../src/features/installed-product-manifest.ts");
expect(manifest.INSTALLED_PRODUCT_FEATURE_IDS).toEqual([]);
// Still declared, so the platform overview reports them as NOT_INSTALLED.
expect(manifest.COMPILED_PRODUCT_FEATURE_IDS).toEqual(COMPILED_PRODUCT_FEATURE_IDS);
const built = spawnSync(
path.resolve("node_modules/.bin/vite"),
["build", "--logLevel", "error"],
{ cwd: root, encoding: "utf8", env },
);
expect(built.stderr).toBe("");
expect(built.status).toBe(0);
const residue: string[] = [];
for (const file of await filesBelow(path.join(root, "dist"))) {
if (!/\.(?:js|css|html)$/u.test(file)) continue;
const content = await readFile(file, "utf8");
for (const routeId of FEATURE_ROUTE_IDS) {
if (content.includes(routeId)) residue.push(`${path.relative(root, file)}: ${routeId}`);
}
}
expect(residue).toEqual([]);
const inventory = JSON.parse(
await readFile(path.join(root, "dist/.vite/module-inventory.json"), "utf8"),
) as { chunks: { modules: string[] }[] };
const modules = inventory.chunks.flatMap((chunk) => chunk.modules);
expect(modules).toContain("src/features/installed-product-manifest.ts");
expect(modules.filter((module) => FEATURE_MODULE.test(module))).toEqual([]);
}, 120_000);
});
+10 -21
View File
@@ -189,34 +189,23 @@ describe("every installed registry consults the manifest", () => {
// Message keys stay total on purpose; see the file for why.
"installed-feature-messages.ts",
]);
// A registry has to gate on the manifest when it composes something a
// manifest-declared feature owns. Deriving that from the file's own imports
// is the difference between a rule and a list: a product that replaces the
// template's demonstration feature with its own domain drops out of the
// rule honestly, and the day it imports a declared feature again the guard
// fires without anyone having to remember to re-add it.
//
// An earlier fix named `installed-feature-runtimes.tsx` in the exempt set
// once this product deleted the reference feature's screens. That silenced
// the guard for that file permanently — a worse outcome than the problem it
// solved.
let guarded = 0;
for (const registry of registries) {
if (exempt.has(registry)) continue;
const source = await readFile(nodePath.join(root, registry), "utf8");
const composesDeclaredFeature = COMPILED_PRODUCT_FEATURE_IDS.some(
(featureId) => source.includes(`./${featureId}/`),
const manifestImport = source.match(
/import\s*\{([\s\S]*?)\}\s*from\s*["']\.\/installed-product-manifest\.ts["']/u,
);
if (!composesDeclaredFeature) continue;
guarded += 1;
expect(
/INSTALLED_PRODUCT_FEATURE(S|_IDS)/u.test(source),
`${registry} composes a manifest-declared feature and must gate on the manifest`,
manifestImport,
`${registry} must import its selection from the product manifest`,
).not.toBeNull();
expect(
/\bINSTALLED_PRODUCT_FEATURE(?:S|_IDS|_MODULES)\b/u.test(
manifestImport?.[1] ?? "",
),
`${registry} must compose from a selected product-feature projection`,
).toBe(true);
}
// The rule has to still be watching something; an empty sweep would pass
// no matter what happened to these files.
expect(guarded).toBeGreaterThan(0);
});
});
@@ -0,0 +1,74 @@
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
// src/.generated is gitignored (R-0): every entry point that loads the product
// index must render it first, or a fresh checkout cannot run the gates.
const GENERATE = "node scripts/generate-product-feature-index.ts && ";
// Entry points the import walk below cannot see (tsc, vite, storybook).
const NON_NODE_ENTRY_SCRIPTS = [
"dev",
"build:app-only",
"storybook",
"build:storybook",
"check:types:app",
"check:types:node",
"check:types:test",
"check:types:fixture:route-runtime",
"check:types:fixture:page-action",
"check:types:fixture:icon-button",
"check:types:fixture:i18n-key",
"check:types:fixture:i18n-params",
] as const;
const ROOT = process.cwd();
const GENERATED_DIR = path.join(ROOT, "src/.generated");
const RELATIVE_IMPORT =
/(?:import|export)\s[^'"]*?from\s+["'](\.{1,2}\/[^"']+)["']|import\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)/gu;
function reachesGeneratedIndex(file: string, seen = new Set<string>()): boolean {
if (seen.has(file) || !existsSync(file)) return false;
seen.add(file);
for (const match of readFileSync(file, "utf8").matchAll(RELATIVE_IMPORT)) {
const resolved = path.resolve(path.dirname(file), match[1] ?? match[2] ?? "");
if (resolved.startsWith(GENERATED_DIR)) return true;
if (reachesGeneratedIndex(resolved, seen)) return true;
}
return false;
}
function packageScripts(): Record<string, string> {
return (JSON.parse(readFileSync("package.json", "utf8")) as { scripts: Record<string, string> })
.scripts;
}
describe("product index entry points", () => {
it("renders the generated index before tsc, vite and storybook entry points", () => {
const scripts = packageScripts();
for (const name of NON_NODE_ENTRY_SCRIPTS) {
expect(scripts[name]?.startsWith(GENERATE), name).toBe(true);
}
});
it("renders the generated index before every node script that imports it", () => {
const missing = Object.entries(packageScripts())
.filter(([, command]) => !command.startsWith(GENERATE))
.filter(([, command]) =>
[...command.matchAll(/node\s+(scripts\/[\w./-]+\.ts)/gu)]
.map((match) => match[1] ?? "")
.filter((entry) => entry !== "scripts/run-vitest.ts")
.some((entry) => reachesGeneratedIndex(path.join(ROOT, entry))),
)
.map(([name]) => name);
expect(missing).toEqual([]);
});
it("renders the generated index before every Vitest run", () => {
const runner = readFileSync("scripts/run-vitest.ts", "utf8");
expect(runner.indexOf("generate-product-feature-index.ts")).toBeGreaterThan(-1);
expect(runner.indexOf("generate-product-feature-index.ts")).toBeLessThan(
runner.indexOf("vitestEntry, ...process.argv"),
);
});
});
+2 -2
View File
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import {
evaluatePromotionReadiness,
PROMOTION_FORMULA,
} from "../../src/application/policies/promotion-readiness.ts";
} from "../../scripts/lib/promotion-readiness.ts";
const allGateIds = Object.values(PROMOTION_FORMULA).flat();
type GateResults = Parameters<typeof evaluatePromotionReadiness>[0];
@@ -25,7 +25,7 @@ describe("promotion readiness formula", () => {
it.each([
["FE-GATE-001", "MERGE_READY"],
["FE-GATE-012", "RELEASE_READY"],
["FE-GATE-016", "PROD_PROMOTION_READY"],
["FE-GATE-021", "PROD_PROMOTION_READY"],
["FE-GATE-018", "FIELD_SLO_READY"],
["FE-GATE-017", "DOCUMENTATION_READY"],
] as const)("fails closed when %s fails", (failedGate, readiness) => {
@@ -0,0 +1,326 @@
import { describe, expect, it } from "vitest";
import type { PublicCacheAsset } from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts";
import { createDefaultPublicCachePolicy } from "../../src/adapters/cache-storage/public-cache-policy.ts";
import { createPublicResponseCacheAdapter } from "../../src/adapters/cache-storage/public-response-cache-adapter.ts";
import {
MemoryCacheStorage,
digestHex,
immediateLock,
manifestFor,
} from "./public-response-cache-fixture.ts";
/**
* Q-6.2-11. Characterization of the manifest codec and response validation
* before they moved out of the adapter: every rejection keeps its code.
*/
const ORIGIN = "https://assets.example.test";
const policy = createDefaultPublicCachePolicy(ORIGIN);
const BYTES = new Uint8Array([1, 2, 3, 4]);
async function asset(
overrides: Partial<PublicCacheAsset> = {},
): Promise<PublicCacheAsset> {
return {
absoluteUrl: `${ORIGIN}/app.js`,
expectedByteLength: BYTES.byteLength,
expectedContentType: "application/javascript",
integrity: { algorithm: "SHA-256", digestHex: await digestHex(BYTES) },
...overrides,
};
}
function adapterWith(
respond: () => Response = () =>
new Response(Uint8Array.from(BYTES), {
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
}),
cacheStorage = new MemoryCacheStorage(),
) {
return createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async () => respond(),
});
}
async function stageCode(
assets: readonly PublicCacheAsset[],
respond?: () => Response,
): Promise<string> {
const manifest = {
releaseRegistryId: "codec-release",
assets,
manifestDigestHex: "0".repeat(64),
};
try {
Object.assign(manifest, await manifestFor("codec-release", assets, policy));
} catch {
// An invalid manifest has no digest; staging must still reject it.
}
const result = await adapterWith(respond).admin.stageRelease(manifest);
return result.ok ? "OK" : result.error.code;
}
describe("public cache codec and response validation (characterization)", () => {
it("keeps manifest normalization failure codes", async () => {
const valid = await asset();
expect(await stageCode([])).toBe("LIMIT_EXCEEDED");
expect(await stageCode([valid, valid])).toBe("CONFLICT");
expect(
await stageCode([
await asset({
integrity: { algorithm: "SHA-1" as "SHA-256", digestHex: "0" },
}),
]),
).toBe("INVALID_INPUT");
expect(
await stageCode([await asset({ expectedByteLength: -1 })]),
).toBe("INVALID_INPUT");
for (const absoluteUrl of [
"https://user:secret@assets.example.test/app.js",
"https://other.example.test/app.js",
`${ORIGIN}/app.js#fragment`,
`${ORIGIN}/app.js?token=secret`,
`${ORIGIN}/.well-known/ca-public-cache-v1/candidate`,
]) {
expect(await stageCode([await asset({ absoluteUrl })])).toBe(
"POLICY_REJECTED",
);
}
expect(await stageCode([await asset({ absoluteUrl: "not a url" })])).toBe(
"INVALID_INPUT",
);
expect(
await stageCode([await asset({ expectedContentType: "text/html" })]),
).toBe("POLICY_REJECTED");
expect(
await stageCode([
await asset({ requestHeaders: [["authorization", "Bearer x"]] }),
]),
).toBe("POLICY_REJECTED");
expect(
await stageCode([
await asset({
requestHeaders: [["accept"] as unknown as readonly [string, string]],
}),
]),
).toBe("INVALID_INPUT");
const wrongDigest = await adapterWith().admin.stageRelease({
releaseRegistryId: "codec-release",
assets: [valid],
manifestDigestHex: "0".repeat(64),
});
expect(wrongDigest).toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED" },
});
const badRelease = await adapterWith().admin.stageRelease({
...(await manifestFor("codec-release", [valid], policy)),
releaseRegistryId: "bad release id",
});
expect(badRelease).toMatchObject({
ok: false,
error: { code: "INVALID_INPUT" },
});
});
it("keeps response validation failure codes", async () => {
const valid = await asset();
const response = (
headers: Record<string, string>,
body: Uint8Array = BYTES,
init: ResponseInit = {},
) => () =>
new Response(Uint8Array.from(body), {
...init,
headers: {
"cache-control": "public",
"content-type": "application/javascript",
...headers,
},
});
expect(await stageCode([valid], response({}))).toBe("OK");
expect(
await stageCode([valid], response({}, BYTES, { status: 203 })),
).toBe("POLICY_REJECTED");
expect(
await stageCode([valid], response({ "cache-control": "no-store" })),
).toBe("POLICY_REJECTED");
expect(await stageCode([valid], response({ pragma: "no-cache" }))).toBe(
"POLICY_REJECTED",
);
expect(
await stageCode([valid], response({ "www-authenticate": "Basic" })),
).toBe("POLICY_REJECTED");
expect(
await stageCode([valid], response({ "content-type": "text/html" })),
).toBe("POLICY_REJECTED");
expect(
await stageCode([valid], response({ "content-type": "text/css" })),
).toBe("INTEGRITY_FAILED");
expect(await stageCode([valid], response({ vary: "Cookie" }))).toBe(
"POLICY_REJECTED",
);
expect(
await stageCode([valid], response({ "content-length": "99999999999" })),
).toBe("LIMIT_EXCEEDED");
expect(
await stageCode([valid], response({}, new Uint8Array([1, 2, 3, 4, 5]))),
).toBe("INTEGRITY_FAILED");
expect(
await stageCode([valid], response({}, new Uint8Array([1, 2, 3]))),
).toBe("INTEGRITY_FAILED");
expect(
await stageCode([valid], response({}, new Uint8Array([4, 3, 2, 1]))),
).toBe("INTEGRITY_FAILED");
});
it("cancels a pending cached body read when the lookup is aborted", async () => {
const valid = await asset();
const manifest = await manifestFor("codec-release", [valid], policy);
const storage = new MemoryCacheStorage();
const adapter = adapterWith(undefined, storage);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
const name = [...storage.caches.keys()].find((key) =>
key.includes(":codec-release:"),
)!;
const cache = storage.caches.get(name)!;
const match = cache.match.bind(cache);
let cancelled = 0;
let pulled: (() => void) | undefined;
const bodyRequested = new Promise<void>((resolve) => {
pulled = resolve;
});
cache.match = async (request: RequestInfo | URL) => {
if (request instanceof Request && request.url === valid.absoluteUrl) {
return new Response(
new ReadableStream<Uint8Array>({
pull() {
pulled?.();
return new Promise<void>(() => {});
},
cancel() {
cancelled += 1;
},
}),
{
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
},
);
}
return await match(request);
};
const controller = new AbortController();
const lookup = adapter.responses.matchActiveExact({
absoluteUrl: valid.absoluteUrl,
signal: controller.signal,
});
await bodyRequested;
controller.abort();
expect(await lookup).toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
expect(cancelled).toBe(1);
});
it("keeps control JSON decoding failure codes", async () => {
const valid = await asset();
const manifest = await manifestFor("codec-release", [valid], policy);
const lookupAfter = async (
tamper: (storage: MemoryCacheStorage) => Promise<void>,
): Promise<string> => {
const storage = new MemoryCacheStorage();
const adapter = adapterWith(undefined, storage);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
await tamper(storage);
const result = await adapter.responses.matchActiveExact({
absoluteUrl: valid.absoluteUrl,
});
return result.ok ? "OK" : result.error.code;
};
const replace = async (
storage: MemoryCacheStorage,
path: "active" | "candidate",
body: BodyInit,
): Promise<void> => {
const name = [...storage.caches.keys()].find((key) =>
path === "active"
? key.endsWith(":control")
: key.includes(":codec-release:"),
)!;
await storage.caches
.get(name)!
.put(
new Request(`${ORIGIN}/.well-known/ca-public-cache-v1/${path}`),
new Response(body, {
headers: { "content-type": "application/json" },
}),
);
};
expect(await lookupAfter(async () => {})).toBe("OK");
expect(
await lookupAfter((storage) => replace(storage, "active", "{not json")),
).toBe("CORRUPT_DATA");
expect(
await lookupAfter((storage) =>
replace(storage, "active", new Uint8Array([0xff, 0xfe])),
),
).toBe("CORRUPT_DATA");
expect(
await lookupAfter((storage) =>
replace(storage, "active", JSON.stringify({ schemaVersion: 2 })),
),
).toBe("CORRUPT_DATA");
expect(
await lookupAfter(async (storage) => {
const name = [...storage.caches.keys()].find((key) =>
key.includes(":codec-release:"),
)!;
const cache = storage.caches.get(name)!;
const marker = await (await cache.match(
new Request(`${ORIGIN}/.well-known/ca-public-cache-v1/candidate`),
))!.json();
await replace(
storage,
"candidate",
JSON.stringify({ ...marker, entryCount: 2 }),
);
}),
).toBe("CORRUPT_DATA");
expect(
await lookupAfter((storage) =>
replace(storage, "candidate", JSON.stringify({ verified: false })),
),
).toBe("CORRUPT_DATA");
});
});
+334 -1
View File
@@ -1,10 +1,12 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import type {
PublicCacheAsset,
PublicCacheReleaseManifest,
} from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts";
import type { ByteSource } from "../../src/application/ports/browser-file-storage/shared.ts";
import {
assertPublicCachePolicy,
createDefaultPublicCachePolicy,
resolvePublicCachePolicy,
type PublicCacheRuntimePolicy,
@@ -49,6 +51,116 @@ describe("public response Cache Storage adapter", () => {
).not.toThrow();
});
it("rejects a policy that strips Content-Type from stored responses", () => {
const base = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
// Activation re-validates the stored Content-Type, so without it every
// activation would fail as INTEGRITY_FAILED.
expect(() =>
assertPublicCachePolicy({
...base,
allowedResponseHeaderNames: base.allowedResponseHeaderNames.filter(
(name) => name !== "content-type",
),
}),
).toThrow(TypeError);
});
it("stages, activates and looks up a Vary: Accept-Encoding response with the default policy", async () => {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const bytes = new Uint8Array([7, 7, 7, 7]);
const asset: PublicCacheAsset = {
absoluteUrl: "https://assets.example.test/gzip-vary.js",
expectedByteLength: bytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(bytes),
},
};
const adapter = createPublicResponseCacheAdapter({
cacheStorage: new MemoryCacheStorage() as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
// nginx `gzip_vary on` and most CDNs add this header to JS and CSS.
fetcher: async () =>
new Response(bytes, {
headers: {
"cache-control": "public, max-age=31536000, immutable",
"content-type": "application/javascript",
vary: "Accept-Encoding",
},
}),
});
const manifest = await manifestFor("gzip-vary-release", [asset], policy);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
const match = await adapter.responses.matchActiveExact({
absoluteUrl: asset.absoluteUrl,
});
expect(match.ok && match.value !== null).toBe(true);
});
it("stages with an anonymous same-origin request that fails on redirect (02-02)", async () => {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const bytes = new Uint8Array([5, 5, 5, 5]);
const asset: PublicCacheAsset = {
absoluteUrl: "https://assets.example.test/anonymous.js",
expectedByteLength: bytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(bytes),
},
};
const requests: Request[] = [];
const adapter = createPublicResponseCacheAdapter({
cacheStorage: new MemoryCacheStorage() as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async (request) => {
requests.push(request);
return new Response(bytes, {
headers: {
"cache-control": "public, max-age=31536000, immutable",
"content-type": "application/javascript",
},
});
},
});
const manifest = await manifestFor("anonymous-release", [asset], policy);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
// The Cache Storage is origin-wide and has no logout purge, so a cookie
// on this request would let a per-user response outlive the session.
expect(
requests.map(({ credentials, mode, redirect }) => ({
credentials,
mode,
redirect,
})),
).toEqual([
{ credentials: "omit", mode: "same-origin", redirect: "error" },
]);
});
it("restages an evicted entry even when the release marker remains", async () => {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
@@ -97,12 +209,23 @@ describe("public response Cache Storage adapter", () => {
);
expect(payloadIndex).toBeGreaterThanOrEqual(0);
cache.responses.splice(payloadIndex, 1);
const candidates = async () => {
const inspection = await adapter.admin.inspect();
return inspection.ok ? inspection.value.releaseCandidates : null;
};
// 02-05. inspect() does not report the marker's claim as verified.
expect(await candidates()).toEqual([
{ releaseRegistryId: "evicted-release", verified: false, entryCount: 1 },
]);
// A marker is a claim, not evidence: restaging must repair.
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(fetches).toBe(2);
expect(await candidates()).toEqual([
{ releaseRegistryId: "evicted-release", verified: true, entryCount: 1 },
]);
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
@@ -1394,4 +1517,214 @@ describe("public response Cache Storage adapter", () => {
expect(bodyCancelled).toBe(true);
expect(await cacheStorage.keys()).toEqual([]);
});
it("spends one keys() and at most two body copies per lookup (02-07)", async () => {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const bytes = new Uint8Array([6, 6, 6, 6, 6]);
const asset: PublicCacheAsset = {
absoluteUrl: "https://assets.example.test/cost.js",
expectedByteLength: bytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(bytes),
},
};
const cacheStorage = new MemoryCacheStorage();
let keysCalls = 0;
const listKeys = cacheStorage.keys.bind(cacheStorage);
cacheStorage.keys = async () => {
keysCalls += 1;
return await listKeys();
};
const adapter = createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async () =>
new Response(Uint8Array.from(bytes), {
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
}),
});
const manifest = await manifestFor("cost-release", [asset], policy);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
const read = async (body: ByteSource): Promise<Uint8Array[]> => {
const chunks: Uint8Array[] = [];
for await (const chunk of body.stream(new AbortController().signal)) {
if (chunk.ok) chunks.push(chunk.value);
}
return chunks;
};
keysCalls = 0;
const copy = vi.spyOn(Uint8Array, "from");
const match = await adapter.responses.matchActiveExact({
absoluteUrl: asset.absoluteUrl,
});
if (!match.ok || !match.value) throw new Error("lookup");
const [chunk] = await read(match.value.body);
const bodyCopies = copy.mock.calls.filter(
([source]) =>
source instanceof Uint8Array &&
source.byteLength === bytes.byteLength,
).length;
copy.mockRestore();
expect(keysCalls).toBe(1);
// The bounded read buffer plus one copy for the stream consumer.
expect(bodyCopies).toBe(1);
// That copy is the consumer's own: changing it leaves the body intact.
chunk!.fill(0);
expect(await read(match.value.body)).toEqual([bytes]);
});
it("reuses a verified release marker across lookups (Q-6.2-6)", async () => {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const cacheStorage = new MemoryCacheStorage();
let digests = 0;
const countingCrypto = {
subtle: {
digest: async (
algorithm: AlgorithmIdentifier,
data: BufferSource,
): Promise<ArrayBuffer> => {
digests += 1;
return await globalThis.crypto.subtle.digest(algorithm, data);
},
},
} as unknown as Crypto;
const bodies = new Map<string, Uint8Array>();
const release = async (
releaseRegistryId: string,
files: Readonly<Record<string, readonly number[]>>,
): Promise<PublicCacheReleaseManifest> => {
const assets: PublicCacheAsset[] = [];
for (const [path, content] of Object.entries(files)) {
const bytes = Uint8Array.from(content);
const absoluteUrl = `https://assets.example.test/${path}`;
bodies.set(absoluteUrl, bytes);
assets.push({
absoluteUrl,
expectedByteLength: bytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(bytes),
},
});
}
return await manifestFor(releaseRegistryId, assets, policy);
};
const adapter = createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: countingCrypto,
mutationLock: immediateLock,
policy,
fetcher: async (request) =>
new Response(Uint8Array.from(bodies.get(request.url)!), {
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
}),
});
const publish = async (manifest: PublicCacheReleaseManifest) => {
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
};
const markerUrl =
"https://assets.example.test/.well-known/ca-public-cache-v1/candidate";
let markerReads = 0;
const countMarkerReads = (releaseRegistryId: string): void => {
const name = [...cacheStorage.caches.keys()].find((key) =>
key.includes(`:${releaseRegistryId}:`),
)!;
const cache = cacheStorage.caches.get(name)!;
const match = cache.match.bind(cache);
cache.match = async (request: RequestInfo | URL) => {
if (request instanceof Request && request.url === markerUrl) {
markerReads += 1;
}
return await match(request);
};
};
const lookup = async (path: string): Promise<number[] | null> => {
const match = await adapter.responses.matchActiveExact({
absoluteUrl: `https://assets.example.test/${path}`,
});
if (!match.ok) throw new Error(match.error.code);
if (!match.value) return null;
const bytes: number[] = [];
for await (const chunk of match.value.body.stream(
new AbortController().signal,
)) {
if (chunk.ok) bytes.push(...chunk.value);
}
return bytes;
};
const first = await release("marker-reuse-1", {
"a.js": [1],
"b.js": [2, 2],
"c.js": [3, 3, 3],
});
await publish(first);
countMarkerReads("marker-reuse-1");
digests = 0;
expect(await lookup("b.js")).toEqual([2, 2]);
// First lookup verifies the marker (manifest digest) and the body.
expect(markerReads).toBe(1);
expect(digests).toBe(2);
digests = 0;
markerReads = 0;
expect(await lookup("c.js")).toEqual([3, 3, 3]);
expect(await lookup("a.js")).toEqual([1]);
expect(await lookup("missing.js")).toBeNull();
// Later lookups neither re-read nor re-hash the verified marker; only
// each served body is still verified.
expect(markerReads).toBe(0);
expect(digests).toBe(2);
// A newly activated release is never answered from the old marker.
const second = await release("marker-reuse-2", { "d.js": [4] });
await publish(second);
expect(await lookup("d.js")).toEqual([4]);
expect(await lookup("a.js")).toBeNull();
// An evicted candidate is still reported even though its marker is known.
const secondName = [...cacheStorage.caches.keys()].find((key) =>
key.includes(":marker-reuse-2:"),
)!;
cacheStorage.caches.delete(secondName);
expect(
await adapter.responses.matchActiveExact({
absoluteUrl: "https://assets.example.test/d.js",
}),
).toMatchObject({ ok: false, error: { code: "STORAGE_EVICTED" } });
});
});
@@ -139,6 +139,65 @@ async function flush(): Promise<void> {
}
describe("bounded poll coordinator", () => {
it("observes lease start, each attempt and the stop reason", async () => {
const clock = new ManualClock();
const results: BoundedPollAttemptResult<string>[] = [
{ ok: true, value: { kind: "UNCHANGED", responseBytes: 0 } },
{
ok: false,
error: {
kind: "RATE_LIMITED",
operation: "POLL",
retryable: true,
},
},
{
ok: true,
value: {
kind: "VALUE",
value: "done",
responseBytes: 8,
state: "COMPLETED",
},
},
];
const observations: unknown[] = [];
const coordinator = createBoundedPollCoordinator({
policy,
operation,
execute: async () => results.shift()!,
environment: new MutableEnvironment(),
clock,
random: () => 0.5,
observe: (observation) => {
observations.push(observation);
throw new Error("sink failure must not change the lease");
},
});
let settled = false;
const running = coordinator.run();
void running.then(() => {
settled = true;
});
for (let step = 0; step < 50 && !settled; step += 1) {
clock.advance(1_000);
await flush();
}
await expect(running).resolves.toMatchObject({
ok: true,
value: { kind: "TERMINAL", attempts: 3 },
});
expect(observations).toEqual([
{ kind: "LEASE_STARTED" },
{ kind: "ATTEMPT_FINISHED", outcome: "UNCHANGED" },
{ kind: "ATTEMPT_FINISHED", outcome: "RATE_LIMITED" },
{ kind: "ATTEMPT_FINISHED", outcome: "VALUE" },
{ kind: "LEASE_STOPPED", outcome: "TERMINAL" },
]);
});
it("chains completed attempts without overlap and stops at a terminal state", async () => {
const clock = new ManualClock();
const environment = new MutableEnvironment();
@@ -562,17 +621,27 @@ describe("bounded poll coordinator", () => {
});
it.each(["RATE_LIMITED", "PROVIDER_UNAVAILABLE"] as const)(
"does not retry %s without a bounded server hint",
"retries retryable %s without a server hint on policy backoff",
async (kind) => {
const clock = new ManualClock();
const execute = vi.fn().mockResolvedValue({
ok: false,
error: {
kind,
operation: "POLL",
retryable: true,
},
});
const execute = vi
.fn()
.mockResolvedValueOnce({
ok: false,
error: {
kind,
operation: "POLL",
retryable: true,
},
})
.mockResolvedValue({
ok: false,
error: {
kind,
operation: "POLL",
retryable: false,
},
});
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
@@ -585,6 +654,10 @@ describe("bounded poll coordinator", () => {
const pending = coordinator.run();
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
clock.advance(5_000);
await flush();
await expect(pending).resolves.toEqual({
ok: false,
error: {
@@ -593,7 +666,7 @@ describe("bounded poll coordinator", () => {
retryable: false,
},
});
expect(execute).toHaveBeenCalledTimes(1);
expect(execute).toHaveBeenCalledTimes(2);
},
);
@@ -821,6 +894,78 @@ describe("bounded poll coordinator", () => {
});
});
it("ends a run whose executor throws with a retryable OFFLINE", async () => {
const clock = new ManualClock();
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: new MutableEnvironment(),
clock,
execute: async () => {
throw new TypeError("Failed to fetch");
},
});
const running = coordinator.run();
clock.advance(5_000);
await expect(running).resolves.toEqual({
ok: false,
error: { kind: "OFFLINE", operation: "POLL", retryable: true },
});
});
it("reads attempt results with the shared realtime snapshot rules", async () => {
const runWith = async (result: unknown) => {
const clock = new ManualClock();
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: new MutableEnvironment(),
clock,
execute: async () => result as BoundedPollAttemptResult<string>,
});
const running = coordinator.run();
clock.advance(5_000);
return running;
};
const terminalValue = () => ({
kind: "VALUE",
value: "done",
responseBytes: 1,
state: "COMPLETED",
});
// A hidden (non-enumerable) field is not plain data: rejected.
await expect(
runWith(
Object.defineProperties(
{},
{
ok: { enumerable: false, value: true },
value: { enumerable: true, value: terminalValue() },
},
),
),
).resolves.toMatchObject({
ok: false,
error: { kind: "PROTOCOL_MISMATCH" },
});
// A null-prototype record is plain data: accepted.
await expect(
runWith(
Object.assign(Object.create(null) as object, {
ok: true,
value: Object.assign(
Object.create(null) as object,
terminalValue(),
),
}),
),
).resolves.toMatchObject({
ok: true,
value: { kind: "TERMINAL", value: "done" },
});
});
it("fails closed on response ceilings, concurrent runs and close", async () => {
const clock = new ManualClock();
const coordinator = createBoundedPollCoordinator<string>({
+37 -14
View File
@@ -10,8 +10,10 @@ import {
} from "../../../src/contracts/realtime-events.ts";
import {
isValidatedRealtimeEventDto,
realtimeDecodeFailureStream,
} from "../../../src/adapters/realtime/event-codec.ts";
import {
STREAM_ID,
TEST_LIMITS,
createTestRealtimeCodec,
createTestRealtimeRegistry,
@@ -59,28 +61,31 @@ describe("REALTIME_EVENT_V1 codec", () => {
ok: false,
error: { kind: "MALFORMED_EVENT", operation: "DECODE" },
});
expect(
codec.decode(
realtimeEventJson({ streamId: "UNKNOWN_STREAM" }),
),
).toMatchObject({
const unknownStream = codec.decode(
realtimeEventJson({ streamId: "UNKNOWN_STREAM" }),
);
expect(unknownStream).toMatchObject({
ok: false,
error: { kind: "MALFORMED_EVENT" },
});
expect(
codec.decode(
realtimeEventJson({ eventType: "UNKNOWN_EVENT" }),
),
).toMatchObject({
expect(realtimeDecodeFailureStream(unknownStream)).toBeNull();
// A type added by a newer backend is a version mismatch, not corruption.
const unknownType = codec.decode(
realtimeEventJson({ eventType: "UNKNOWN_EVENT" }),
);
expect(unknownType).toMatchObject({
ok: false,
error: { kind: "MALFORMED_EVENT" },
error: { kind: "PROTOCOL_MISMATCH", operation: "REGISTRY" },
});
expect(
codec.decode(realtimeEventJson({ payload: { value: 42 } })),
).toMatchObject({
expect(realtimeDecodeFailureStream(unknownType)).toBe(STREAM_ID);
const badPayload = codec.decode(
realtimeEventJson({ payload: { value: 42 } }),
);
expect(badPayload).toMatchObject({
ok: false,
error: { kind: "MALFORMED_EVENT" },
});
expect(realtimeDecodeFailureStream(badPayload)).toBe(STREAM_ID);
const duplicateEnvelopeMember =
`{"eventId":"shadowed",${JSON.stringify(
@@ -227,6 +232,24 @@ describe("REALTIME_EVENT_V1 codec", () => {
);
});
it("keeps a fixed-size semantic fingerprint however large the payload", () => {
const codec = createTestRealtimeCodec();
const small = codec.decode(realtimeEventJson());
const large = codec.decode(
realtimeEventJson({ payload: { value: "x".repeat(3_000) } }),
);
expect(small.ok && large.ok).toBe(true);
if (!small.ok || !large.ok) return;
expect(large.value.fingerprintBytes).toBe(
small.value.fingerprintBytes,
);
expect(large.value.fingerprintBytes).toBeLessThanOrEqual(32);
expect(large.value.semanticFingerprint).not.toBe(
small.value.semanticFingerprint,
);
});
it("uses bounded uint64 sequence and header-safe cursor helpers", () => {
expect(isCanonicalRealtimeSequence("0")).toBe(true);
expect(isCanonicalRealtimeSequence(REALTIME_MAX_SEQUENCE)).toBe(true);
+192 -2
View File
@@ -18,9 +18,20 @@ import {
realtimeFailure,
realtimeSuccess,
} from "../../../src/adapters/realtime/result.ts";
import type {
RealtimeStreamCoordinator,
import {
createRealtimeStreamCoordinator,
type RealtimeStreamCoordinator,
} from "../../../src/adapters/realtime/stream-coordinator.ts";
import {
createFetchSseConnection,
} from "../../../src/adapters/realtime/sse/fetch-sse-connection.ts";
import {
STREAM_ID,
TEST_MAPPERS,
createTestRealtimeCodec,
createTestRealtimeRegistry,
realtimeEventJson,
} from "./fixture.ts";
function setup(
recoveryMode:
@@ -209,3 +220,182 @@ describe("realtime transport event consumer", () => {
expect(runtime.accept).toHaveBeenCalledTimes(1);
});
});
describe("SSE transport, consumer and stream coordinator together", () => {
it("keeps reading after a SNAPSHOT_ONLY recovery that needs no transport barrier", async () => {
const registry = createTestRealtimeRegistry({
recovery: {
mode: "SNAPSHOT_ONLY",
snapshotOperationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
checkpointCodecId: "ReferenceRealtimeCheckpoint",
barrier: "NONE",
},
delivery: "INVALIDATION_HINT",
stateBearing: false,
});
const snapshots = ["0", "3"];
const recoveries: string[] = [];
const apply = vi.fn(async () => realtimeSuccess(undefined));
const coordinator = createRealtimeStreamCoordinator({
registry,
mappers: TEST_MAPPERS,
authority: {
effects: { apply },
recovery: {
async recover(request) {
recoveries.push(request.reason);
const sequence = snapshots.shift() ?? "0";
return realtimeSuccess({
kind: "SNAPSHOT_RESET",
checkpoint: {
recoveryMode: "SNAPSHOT_ONLY",
streamEpoch: "stream-epoch-0001",
lastAppliedSequence: sequence,
resumeCursor: null,
snapshotRevision: `snapshot-revision-${sequence}`,
},
});
},
},
},
scope: {
generation: 7,
scopeBinding: "scope-binding-0001",
isCurrent: () => true,
},
now: () => 10_000,
});
const consumer = createRealtimeEventConsumer({
codec: createTestRealtimeCodec(registry),
coordinator,
});
await expect(
coordinator.recover(STREAM_ID, "INITIALIZE"),
).resolves.toMatchObject({ ok: true });
const frame = (sequence: string) =>
`data: ${realtimeEventJson({
eventId: `event-0000000${sequence}`,
sequence,
recoveryMode: "SNAPSHOT_ONLY",
resumeCursor: null,
})}\n\n`;
const body = [frame("1"), frame("3"), frame("4")].join("");
const connection = createFetchSseConnection({
endpoint: "https://app.example.test/events",
applicationOrigin: "https://app.example.test",
recoveryMode: "SNAPSHOT_ONLY",
fetcher: async () =>
new Response(body, {
status: 200,
headers: { "Content-Type": "text/event-stream" },
}),
});
// Sequence 3 is a gap: the coordinator recovers to snapshot 3, and the
// stream must keep reading so sequence 4 still applies.
const closed = await connection.read({
resumeCursor: null,
onEvent: (event, signal) =>
consumer.consumeForTransport(
event.data,
{ kind: "SSE_NO_CURSOR" },
signal,
),
});
expect(closed).toMatchObject({ ok: true, value: { kind: "EOF" } });
expect(recoveries).toEqual(["INITIALIZE", "SEQUENCE_GAP"]);
expect(apply).toHaveBeenCalledTimes(2);
expect(coordinator.getResumeState(STREAM_ID)).toMatchObject({
lastAppliedSequence: "4",
});
expect(coordinator.inspect(STREAM_ID).awaitingTransportBarrier).toBe(
false,
);
});
it("ends on an unregistered event type as a registry mismatch and leaves freshness UNKNOWN", async () => {
const registry = createTestRealtimeRegistry({
recovery: {
mode: "SNAPSHOT_ONLY",
snapshotOperationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
checkpointCodecId: "ReferenceRealtimeCheckpoint",
barrier: "NONE",
},
delivery: "INVALIDATION_HINT",
stateBearing: false,
});
const apply = vi.fn(async () => realtimeSuccess(undefined));
const coordinator = createRealtimeStreamCoordinator({
registry,
mappers: TEST_MAPPERS,
authority: {
effects: { apply },
recovery: {
recover: async () =>
realtimeSuccess({
kind: "SNAPSHOT_RESET",
checkpoint: {
recoveryMode: "SNAPSHOT_ONLY",
streamEpoch: "stream-epoch-0001",
lastAppliedSequence: "0",
resumeCursor: null,
snapshotRevision: "snapshot-revision-0",
},
}),
},
},
scope: {
generation: 7,
scopeBinding: "scope-binding-0001",
isCurrent: () => true,
},
now: () => 10_000,
});
const consumer = createRealtimeEventConsumer({
codec: createTestRealtimeCodec(registry),
coordinator,
});
await expect(
coordinator.recover(STREAM_ID, "INITIALIZE"),
).resolves.toMatchObject({ ok: true });
// A newer backend added an event type this bundle does not know.
const frame = (sequence: string, eventType?: string) =>
`data: ${realtimeEventJson({
eventId: `event-0000000${sequence}`,
sequence,
recoveryMode: "SNAPSHOT_ONLY",
resumeCursor: null,
...(eventType === undefined ? {} : { eventType }),
})}\n\n`;
const body = frame("1") + frame("2", "ADDED_BY_NEWER_BACKEND");
const connection = createFetchSseConnection({
endpoint: "https://app.example.test/events",
applicationOrigin: "https://app.example.test",
recoveryMode: "SNAPSHOT_ONLY",
fetcher: async () =>
new Response(body, {
status: 200,
headers: { "Content-Type": "text/event-stream" },
}),
});
const closed = await connection.read({
resumeCursor: null,
onEvent: (event, signal) =>
consumer.consumeForTransport(
event.data,
{ kind: "SSE_NO_CURSOR" },
signal,
),
});
expect(apply).toHaveBeenCalledOnce();
expect(closed).toEqual(
realtimeFailure("PROTOCOL_MISMATCH", "REGISTRY", false),
);
expect(coordinator.inspect(STREAM_ID).freshness).toBe("UNKNOWN");
});
});
@@ -8,6 +8,7 @@ import {
realtimeTransportRecoveryCommitted,
type RealtimeRecoveryCheckpoint,
} from "../../../src/application/ports/realtime/event-authority.ts";
import type { ClockPort } from "../../../src/application/ports/clock-port.ts";
import type { RealtimeResult } from "../../../src/application/ports/realtime/shared.ts";
import type {
StreamRegistrationId,
@@ -56,6 +57,66 @@ function eventStream(
);
}
type Sleeper = { dueAt: number; resolve(): void };
class ManualClock implements ClockPort {
current = 0;
private sleepers: Sleeper[] = [];
now(): number {
return this.current;
}
sleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(new Error("Aborted."));
return;
}
const sleeper = { dueAt: this.current + milliseconds, resolve };
signal?.addEventListener(
"abort",
() => {
this.sleepers = this.sleepers.filter((entry) => entry !== sleeper);
reject(new Error("Aborted."));
},
{ once: true },
);
this.sleepers.push(sleeper);
});
}
advance(milliseconds: number): void {
this.current += milliseconds;
const ready = this.sleepers.filter(
(sleeper) => sleeper.dueAt <= this.current,
);
this.sleepers = this.sleepers.filter(
(sleeper) => sleeper.dueAt > this.current,
);
for (const sleeper of ready) sleeper.resolve();
}
}
async function settle(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
}
function openStream() {
let push: ((text: string) => void) | undefined;
const cancel = vi.fn();
const response = new Response(
new ReadableStream<Uint8Array>({
start(controller) {
push = (text) => controller.enqueue(encoder.encode(text));
},
cancel,
}),
{ headers: { "Content-Type": "text/event-stream" } },
);
return { response, cancel, push: (text: string) => push?.(text) };
}
function connection(
fetcher: typeof fetch,
recoveryMode: "CURSOR" | "SESSION_REBUILD" | "SNAPSHOT_ONLY" =
@@ -526,6 +587,123 @@ describe("fetch SSE connection", () => {
);
});
it("dispatches a single chunk holding more events than the per-chunk item cap", async () => {
const chunk = Array.from(
{ length: 300 },
(_, index) =>
`id: cursor-${index}\ndata: ${"x".repeat(300)}\n\n`,
).join("");
const runtime = connection(
(async () => eventStream([chunk])) as typeof fetch,
);
const received: string[] = [];
await expect(
runtime.read({
resumeCursor: null,
onEvent: (event) => {
received.push(event.id ?? "");
return realtimeSuccess(SSE_CONTINUE);
},
}),
).resolves.toMatchObject({ ok: true, value: { kind: "EOF" } });
expect(received).toHaveLength(300);
expect(received[299]).toBe("cursor-299");
});
it("dispatches every normal event from a 1MB reader chunk", async () => {
// The browser, not the server, picks the chunk size.
const chunk = Array.from(
{ length: 2_000 },
(_, index) =>
`id: cursor-${index}\ndata: ${"é".repeat(250)}\n\n`,
).join("");
expect(encoder.encode(chunk).byteLength).toBeGreaterThan(1_000_000);
const runtime = connection(
(async () => eventStream([chunk])) as typeof fetch,
);
const received: string[] = [];
await expect(
runtime.read({
resumeCursor: null,
onEvent: (event) => {
received.push(event.id ?? "");
return realtimeSuccess(SSE_CONTINUE);
},
}),
).resolves.toMatchObject({ ok: true, value: { kind: "EOF" } });
expect(received).toHaveLength(2_000);
expect(received[1_999]).toBe("cursor-1999");
});
it("ends a silent stream with a retryable IDLE_TIMEOUT and cancels the reader", async () => {
const clock = new ManualClock();
const stream = openStream();
const runtime = createFetchSseConnection({
endpoint: "https://app.example.test/events",
applicationOrigin: "https://app.example.test",
recoveryMode: "CURSOR",
fetcher: (async () => stream.response) as typeof fetch,
clock,
idleTimeoutMs: 1_000,
});
let settled = false;
const pending = runtime.read({
resumeCursor: null,
onEvent: continueEvent,
});
void pending.then(() => {
settled = true;
});
await settle();
clock.advance(999);
await settle();
expect(settled).toBe(false);
clock.advance(1);
await expect(pending).resolves.toEqual(
realtimeFailure("IDLE_TIMEOUT", "RECEIVE", true),
);
expect(stream.cancel).toHaveBeenCalledOnce();
});
it("restarts the idle deadline on every comment", async () => {
const clock = new ManualClock();
const stream = openStream();
const comments = vi.fn();
const runtime = createFetchSseConnection({
endpoint: "https://app.example.test/events",
applicationOrigin: "https://app.example.test",
recoveryMode: "CURSOR",
fetcher: (async () => stream.response) as typeof fetch,
clock,
idleTimeoutMs: 1_000,
});
let settled = false;
const pending = runtime.read({
resumeCursor: null,
onEvent: continueEvent,
onComment: comments,
});
void pending.then(() => {
settled = true;
});
await settle();
for (let beat = 0; beat < 3; beat += 1) {
clock.advance(900);
stream.push(": heartbeat\n");
await settle();
}
expect(comments).toHaveBeenCalledTimes(3);
expect(settled).toBe(false);
clock.advance(1_000);
await expect(pending).resolves.toEqual(
realtimeFailure("IDLE_TIMEOUT", "RECEIVE", true),
);
});
it("rejects arbitrary endpoints and mode-incoherent cursors before fetch", async () => {
expect(() =>
createFetchSseConnection({
@@ -426,6 +426,41 @@ describe("live/poll authoritative writer handoff", () => {
});
});
it("bounds the probe by what is still buffered, not by all it ever accepted", async () => {
const firstLive = deferred<RealtimeResult<void>>();
const order: string[] = [];
const harness = createHarness({
initial: "POLL",
limits: { ...limits, maxProbeBufferedEvents: 2 },
apply: vi.fn(async ({ value }) => {
order.push(value);
if (value === "live-1") await firstLive.promise;
return realtimeSuccess(undefined);
}),
});
const live = expectProbe(harness.coordinator.beginLiveProbe());
await live.write("live-1", 3);
await live.write("live-2", 3);
const activation = live.activate();
// live-1 left the buffer for the drain, so one slot is free again.
await vi.waitFor(() => expect(order).toEqual(["live-1"]));
await expect(live.write("live-3", 3)).resolves.toMatchObject({
ok: true,
value: { kind: "BUFFERED" },
});
await expect(live.write("live-4", 3)).resolves.toMatchObject({
ok: false,
error: { kind: "QUEUE_OVERFLOW" },
});
// Overflow during activation still fails closed.
firstLive.resolve(realtimeSuccess(undefined));
await expect(activation).resolves.toMatchObject({ ok: false });
expect(harness.coordinator.inspect().state).toBe("CLOSED");
expect(order).toEqual(["live-1"]);
});
it("drops an overflowing probe without displacing poll and never reuses its generation", async () => {
const harness = createHarness({
initial: "POLL",
@@ -2,11 +2,11 @@ import { describe, expect, it, vi } from "vitest";
import type { ClockPort } from "../../../src/application/ports/clock-port.ts";
import type {
RealtimeFailureKind,
RealtimeResult,
} from "../../../src/application/ports/realtime/shared.ts";
import type {
RealtimeRecoveryCheckpoint,
import {
REALTIME_TRANSPORT_CONTINUE,
type RealtimeRecoveryCheckpoint,
} from "../../../src/application/ports/realtime/event-authority.ts";
import {
createRealtimeReconnectCoordinator,
@@ -27,6 +27,19 @@ import {
realtimeFailure,
realtimeSuccess,
} from "../../../src/adapters/realtime/result.ts";
import {
createFetchSseConnection,
readSseForReconnect,
SSE_CONTINUE,
} from "../../../src/adapters/realtime/sse/fetch-sse-connection.ts";
import {
createWebSocketConnection,
type WebSocketClosedReceipt,
type WebSocketFacade,
} from "../../../src/adapters/realtime/websocket/websocket-connection.ts";
import {
REALTIME_WEBSOCKET_PROTOCOL,
} from "../../../src/adapters/realtime/websocket/websocket-protocol.ts";
type Sleeper = Readonly<{
dueAt: number;
@@ -221,7 +234,8 @@ function deferred<Value>(): Readonly<{
}
async function flush(): Promise<void> {
for (let turn = 0; turn < 8; turn += 1) {
// Enough turns for a retry loop iteration: sleep, attempt and close races.
for (let turn = 0; turn < 16; turn += 1) {
await Promise.resolve();
}
}
@@ -309,62 +323,78 @@ describe("realtime reconnect coordinator", () => {
"RATE_LIMITED",
"PROVIDER_UNAVAILABLE",
] as const)(
"does not reconnect an external %s attempt failure without a server hint",
"reconnects a retryable external %s attempt failure without a server hint",
async (kind) => {
const clock = new ManualClock();
const terminal = realtimeFailure(
kind,
"CONNECT",
true,
);
const attempt = vi.fn(() => failed(terminal));
const retryable = realtimeFailure(kind, "CONNECT", true);
const terminal = realtimeFailure(kind, "CONNECT", false);
let attempts = 0;
const coordinator = createRealtimeReconnectCoordinator({
policy: policy(),
environment: new MutableOnlineEnvironment(true),
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
attempt,
attempt: () =>
failed(++attempts === 1 ? retryable : terminal),
});
const result = await coordinator.run();
const running = coordinator.run();
await flush();
expect(attempts).toBe(1);
expect(clock.sleepCalls).toEqual([50]);
clock.advance(50);
const result = await running;
expect(attempts).toBe(2);
expect(result).toBe(terminal);
expect(attempt).toHaveBeenCalledOnce();
expect(clock.sleepCalls).toEqual([]);
},
);
it("does not reconnect an external close failure that requires but omits a server hint", async () => {
it("reconnects a retryable external close failure without a server hint", async () => {
const clock = new ManualClock();
const terminal = realtimeFailure(
const retryable = realtimeFailure(
"PROVIDER_UNAVAILABLE",
"RECEIVE",
true,
);
const attempt = vi.fn(() =>
opened(
Object.freeze({
classifyClosed: (
receipt: RealtimeReconnectOutcome<void>,
) => receipt,
close: vi.fn(),
waitClosed: () => failed(terminal),
}),
),
const terminal = realtimeFailure(
"PROVIDER_UNAVAILABLE",
"RECEIVE",
false,
);
let attempts = 0;
const coordinator = createRealtimeReconnectCoordinator({
policy: policy(),
environment: new MutableOnlineEnvironment(true),
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
attempt,
attempt: () => {
const closedWith = ++attempts === 1 ? retryable : terminal;
return opened(
Object.freeze({
classifyClosed: (
receipt: RealtimeReconnectOutcome<void>,
) => receipt,
close: vi.fn(),
waitClosed: () => failed(closedWith),
}),
);
},
});
const result = await coordinator.run();
const running = coordinator.run();
await flush();
expect(attempts).toBe(1);
expect(clock.sleepCalls).toEqual([50]);
clock.advance(50);
const result = await running;
expect(attempts).toBe(2);
expect(result).toBe(terminal);
expect(attempt).toHaveBeenCalledOnce();
expect(clock.sleepCalls).toEqual([]);
});
it("waits for an explicit online signal without a retry timer", async () => {
@@ -404,8 +434,180 @@ describe("realtime reconnect coordinator", () => {
expect(result).toBe(terminal);
});
it("resets a spent retry only after policy eligibility", async () => {
const runScenario = async (markValid: boolean) => {
it("does not spend the elapsed budget while waiting offline", async () => {
const clock = new ManualClock();
const environment = new MutableOnlineEnvironment(false);
const terminal = realtimeFailure(
"FORBIDDEN",
"CONNECT",
false,
);
const attempt = vi.fn(() => failed(terminal));
const coordinator = createRealtimeReconnectCoordinator({
policy: policy(),
environment,
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
attempt,
});
const running = coordinator.run();
await flush();
// Offline for longer than maxElapsedMs before the first attempt.
clock.advance(6_000);
environment.emit(true);
await flushUntil(() => clock.sleepCalls.length === 1);
expect(clock.sleepCalls).toEqual([50]);
clock.advance(50);
const result = await running;
expect(attempt).toHaveBeenCalledTimes(1);
expect(result).toBe(terminal);
});
it.each(["an offline blip", "a waitClosed throw"] as const)(
"reconnects after %s ends a healthy session older than the elapsed budget",
async (ending) => {
const clock = new ManualClock();
const environment = new MutableOnlineEnvironment(true);
const closing = deferred<RealtimeReconnectOutcome<void>>();
const terminal = realtimeFailure(
"FORBIDDEN",
"CONNECT",
false,
);
let attempts = 0;
const coordinator = createRealtimeReconnectCoordinator({
policy: policy(),
environment,
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
attempt: (context: RealtimeReconnectAttemptContext) => {
attempts += 1;
if (attempts > 1) return failed(terminal);
context.markValidHeartbeatOrEvent();
return opened<RealtimeReconnectOutcome<void>>(
Object.freeze({
classifyClosed: (
receipt: RealtimeReconnectOutcome<void>,
) => receipt,
close: () =>
closing.resolve(
failed(
realtimeFailure("OFFLINE", "RECEIVE", true),
),
),
waitClosed: () =>
ending === "an offline blip"
? closing.promise
: closing.promise.then(() => {
throw new Error("transport failed");
}),
}),
);
},
});
const running = coordinator.run();
await flushUntil(() => attempts === 1);
await flush();
// Healthy for twice maxElapsedMs, then a one second outage.
clock.advance(10_000);
if (ending === "an offline blip") {
environment.emit(false);
await flush();
clock.advance(1_000);
environment.emit(true);
} else {
closing.resolve(closedSuccessfully());
}
await flushUntil(() => clock.sleepCalls.length === 1);
expect(clock.sleepCalls).toEqual([50]);
clock.advance(50);
const result = await running;
expect(attempts).toBe(2);
expect(result).toBe(terminal);
},
);
it("observes attempts, retries, the session and why the run ended", async () => {
const clock = new ManualClock();
const terminal = realtimeFailure("FORBIDDEN", "RECEIVE", false);
const observations: unknown[] = [];
let attempts = 0;
const coordinator = createRealtimeReconnectCoordinator({
policy: policy(),
environment: new MutableOnlineEnvironment(true),
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
observe: (observation) => {
observations.push(observation);
throw new Error("sink failure must not change the run");
},
attempt: () =>
++attempts === 1
? failed(realtimeFailure("CONNECT_TIMEOUT", "CONNECT", true))
: opened(
Object.freeze({
classifyClosed: (
receipt: RealtimeReconnectOutcome<void>,
) => receipt,
close: vi.fn(),
waitClosed: () => failed(terminal),
}),
),
});
const running = coordinator.run();
await flushUntil(() => clock.sleepCalls.length === 1);
clock.advance(50);
await expect(running).resolves.toBe(terminal);
expect(observations).toEqual([
{ kind: "ATTEMPT_STARTED" },
{
kind: "RETRY_SCHEDULED",
failureKind: "CONNECT_TIMEOUT",
delayBucket: "UNDER_1S",
},
{ kind: "ATTEMPT_STARTED" },
{ kind: "SESSION_OPENED" },
{ kind: "SESSION_CLOSED" },
{ kind: "RUN_ENDED", reason: "TERMINAL", failureKind: "FORBIDDEN" },
]);
// A second run that spends its retries ends as EXHAUSTED, not TERMINAL.
const exhausted = realtimeFailure("PROVIDER_UNAVAILABLE", "CONNECT", true);
const ends: unknown[] = [];
const spending = createRealtimeReconnectCoordinator({
policy: policy({ maxAttempts: 1 }),
environment: new MutableOnlineEnvironment(true),
clock,
random: () => 0,
confirmTransportBarrier: confirmationSucceeded,
observe: (observation) => {
if (observation.kind === "RUN_ENDED") ends.push(observation);
},
attempt: () => failed(exhausted),
});
const spent = spending.run();
await flushUntil(() => clock.sleepCalls.length === 2);
clock.advance(0);
await expect(spent).resolves.toBe(exhausted);
expect(ends).toEqual([
{
kind: "RUN_ENDED",
reason: "EXHAUSTED",
failureKind: "PROVIDER_UNAVAILABLE",
},
]);
});
it("resets a spent retry only after a valid signal and a stable open", async () => {
const runScenario = async (markValid: boolean, openMs: number) => {
const clock = new ManualClock();
const firstFailure = realtimeFailure(
"CONNECT_TIMEOUT",
@@ -423,6 +625,7 @@ describe("realtime reconnect coordinator", () => {
false,
);
const closeSession = vi.fn();
const closing = deferred<RealtimeReconnectOutcome<void>>();
let attempts = 0;
const coordinator = createRealtimeReconnectCoordinator({
policy: policy({ maxAttempts: 1 }),
@@ -445,8 +648,7 @@ describe("realtime reconnect coordinator", () => {
receipt: RealtimeReconnectOutcome<void>,
) => receipt,
close: closeSession,
waitClosed: () =>
failed(sessionFailure, 0),
waitClosed: () => closing.promise,
}),
);
}
@@ -457,12 +659,12 @@ describe("realtime reconnect coordinator", () => {
const running = coordinator.run();
await flush();
clock.advance(0);
await flushUntil(() => attempts === 2);
await flush();
if (markValid) {
await flushUntil(() => clock.sleepCalls.length === 2);
expect(clock.sleepCalls).toEqual([0, 0]);
clock.advance(0);
}
clock.advance(openMs);
closing.resolve(failed(sessionFailure, 0));
await flushUntil(() => clock.sleepCalls.length === 2);
clock.advance(0);
const result = await running;
return {
attempts,
@@ -473,12 +675,20 @@ describe("realtime reconnect coordinator", () => {
};
};
const unstable = await runScenario(false);
expect(unstable.attempts).toBe(2);
expect(unstable.result).toBe(unstable.sessionFailure);
expect(unstable.closeSession).toHaveBeenCalledOnce();
// A heartbeat on a short-lived connection, or a quiet long one, keeps
// the spent budget; only both together reset it.
for (const [markValid, openMs] of [
[false, 0],
[true, 499],
[false, 500],
] as const) {
const spent = await runScenario(markValid, openMs);
expect(spent.attempts).toBe(2);
expect(spent.result).toBe(spent.sessionFailure);
expect(spent.closeSession).toHaveBeenCalledOnce();
}
const eligible = await runScenario(true);
const eligible = await runScenario(true, 500);
expect(eligible.attempts).toBe(3);
expect(eligible.result).toBe(eligible.terminal);
expect(eligible.closeSession).toHaveBeenCalledOnce();
@@ -1455,3 +1665,356 @@ describe("realtime reconnect coordinator", () => {
expect(coordinator.getState()).toBe("IDLE");
});
});
class FakeWebSocket implements WebSocketFacade {
protocol: string = REALTIME_WEBSOCKET_PROTOCOL;
readyState = 0;
bufferedAmount = 0;
readonly listeners = new Map<
string,
Set<(event: unknown) => void>
>();
readonly sent: string[] = [];
send(data: string): void {
if (this.readyState !== 1) throw new Error("not open");
this.sent.push(data);
}
close(): void {
this.readyState = 3;
}
addEventListener(
type: string,
listener: (event: unknown) => void,
): void {
const listeners = this.listeners.get(type) ?? new Set();
listeners.add(listener);
this.listeners.set(type, listeners);
}
removeEventListener(
type: string,
listener: (event: unknown) => void,
): void {
this.listeners.get(type)?.delete(listener);
}
accept(): void {
this.readyState = 1;
this.emit("open", {});
this.emit("message", {
data: JSON.stringify({
type: "WELCOME",
protocol: REALTIME_WEBSOCKET_PROTOCOL,
connectionId: "connection.0001",
heartbeatMs: 5_000,
heartbeatAckTimeoutMs: 1_000,
limits: {
maxFrameBytes: 64 * 1_024,
maxSubscriptions: 32,
maxInboundQueueCount: 256,
maxInboundQueueBytes: 4 * 1_024 * 1_024,
maxOutboundQueueCount: 128,
maxOutboundQueueBytes: 256 * 1_024,
maxBufferedAmountBytes: 256 * 1_024,
maxEventsPerSecond: 256,
},
}),
});
}
nativeClose(code: number): void {
this.readyState = 3;
this.emit("close", { code, reason: "" });
}
ackHeartbeats(): void {
for (const raw of this.sent.splice(0)) {
const frame = JSON.parse(raw) as { type: string; nonce: string };
if (frame.type !== "HEARTBEAT") continue;
this.emit("message", {
data: JSON.stringify({
type: "HEARTBEAT_ACK",
protocol: REALTIME_WEBSOCKET_PROTOCOL,
nonce: frame.nonce,
}),
});
}
}
private emit(type: string, event: unknown): void {
for (const listener of [...(this.listeners.get(type) ?? [])]) {
listener(event);
}
}
}
describe("transport failures through the reconnect coordinator", () => {
it.each([
["NETWORK_LOST", 1_006],
["RESTART", 1_012],
] as const)(
"reconnects a WebSocket %s close that carries no server hint",
async (_category, code) => {
const clock = new ManualClock();
const sockets: FakeWebSocket[] = [];
const coordinator = createRealtimeReconnectCoordinator<
WebSocketClosedReceipt
>({
policy: policy(),
environment: new MutableOnlineEnvironment(true),
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
attempt: async (context) => {
const connection = createWebSocketConnection({
origin: "https://app.example.test",
endpointPath: "/_realtime/v1",
clock,
createNonce: () => "nonce.0001",
createSocket: () => {
const socket = new FakeWebSocket();
sockets.push(socket);
return socket;
},
onEvent: async () =>
realtimeSuccess(REALTIME_TRANSPORT_CONTINUE),
onRecoveryRequired: () => undefined,
});
const connected = await connection.connect(context.signal);
if (!connected.ok) return failed(connected);
return opened(
Object.freeze({
waitClosed: () => connection.waitClosed(),
classifyClosed: (receipt: WebSocketClosedReceipt) =>
Object.freeze({
result: Object.freeze({
ok: false as const,
error: receipt.error,
}),
}),
close: () => connection.close(),
}),
);
},
});
const running = coordinator.run();
await flushUntil(() => sockets.length === 1);
sockets[0]!.accept();
await flush();
sockets[0]!.nativeClose(code);
await flushUntil(() => clock.sleepCalls.includes(50));
clock.advance(50);
await flushUntil(() => sockets.length === 2);
expect(sockets).toHaveLength(2);
// OVERLOADED carries no hint either and stays terminal.
sockets[1]!.accept();
await flush();
sockets[1]!.nativeClose(1_013);
await expect(running).resolves.toEqual({
ok: false,
error: {
kind: "PROVIDER_UNAVAILABLE",
operation: "RECEIVE",
retryable: false,
},
});
expect(sockets).toHaveLength(2);
},
);
it("reconnects a quiet WebSocket whose heartbeats kept it healthy past the elapsed budget", async () => {
const clock = new ManualClock();
const sockets: FakeWebSocket[] = [];
let nonce = 0;
const coordinator = createRealtimeReconnectCoordinator<
WebSocketClosedReceipt
>({
policy: policy(),
environment: new MutableOnlineEnvironment(true),
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
attempt: async (context) => {
const connection = createWebSocketConnection({
origin: "https://app.example.test",
endpointPath: "/_realtime/v1",
clock,
createNonce: () => `nonce.${++nonce}`,
createSocket: () => {
const socket = new FakeWebSocket();
sockets.push(socket);
return socket;
},
onEvent: async () =>
realtimeSuccess(REALTIME_TRANSPORT_CONTINUE),
onRecoveryRequired: () => undefined,
observe: (observation) => {
if (observation.kind === "HEARTBEAT_ACK") {
context.markValidHeartbeatOrEvent();
}
},
});
const connected = await connection.connect(context.signal);
if (!connected.ok) return failed(connected);
return opened(
Object.freeze({
waitClosed: () => connection.waitClosed(),
classifyClosed: (receipt: WebSocketClosedReceipt) =>
Object.freeze({
result: Object.freeze({
ok: false as const,
error: receipt.error,
}),
}),
close: () => connection.close(),
}),
);
},
});
const running = coordinator.run();
await flushUntil(() => sockets.length === 1);
sockets[0]!.accept();
await flush();
// No events, only acknowledged heartbeats, for longer than maxElapsedMs.
for (let beat = 0; beat < 2; beat += 1) {
clock.advance(5_000);
await flush();
sockets[0]!.ackHeartbeats();
clock.advance(1_000);
await flush();
}
sockets[0]!.nativeClose(1_012);
await flushUntil(() => clock.sleepCalls.includes(50));
clock.advance(50);
await flushUntil(() => sockets.length === 2);
expect(sockets).toHaveLength(2);
coordinator.close();
await expect(running).resolves.toMatchObject({
ok: false,
error: { kind: "CLOSED" },
});
});
it.each([502, 504])(
"reconnects SSE HTTP %i that carries no server hint",
async (status) => {
const clock = new ManualClock();
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response(null, { status }))
.mockResolvedValueOnce(new Response(null, { status: 403 }));
const coordinator = createRealtimeReconnectCoordinator({
policy: policy(),
environment: new MutableOnlineEnvironment(true),
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
attempt: async (context) => {
const read = await createFetchSseConnection({
endpoint: "https://app.example.test/events",
applicationOrigin: "https://app.example.test",
recoveryMode: "CURSOR",
fetcher,
clock,
}).read({
resumeCursor: null,
signal: context.signal,
onEvent: () => realtimeSuccess(SSE_CONTINUE),
});
// Only connect failures are exercised here.
return failed(
read.ok
? realtimeFailure("PROTOCOL_MISMATCH", "CONNECT", false)
: read,
);
},
});
const running = coordinator.run();
await flushUntil(() => clock.sleepCalls.includes(50));
clock.advance(50);
await expect(running).resolves.toEqual({
ok: false,
error: {
kind: "FORBIDDEN",
operation: "CONNECT",
retryable: false,
},
});
expect(fetcher).toHaveBeenCalledTimes(2);
},
);
it.each([429, 503])(
"waits at least the SSE %i Retry-After through the reconnect bridge",
async (status) => {
const clock = new ManualClock();
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
new Response(null, {
status,
headers: { "retry-after": "3" },
}),
)
.mockResolvedValueOnce(
new Response(null, {
status,
headers: { "retry-after": "10" },
}),
);
const coordinator = createRealtimeReconnectCoordinator({
policy: policy({ maxDelayMs: 5_000, maxElapsedMs: 60_000 }),
environment: new MutableOnlineEnvironment(true),
clock,
random: () => 0.5,
confirmTransportBarrier: confirmationSucceeded,
attempt: async (context) => {
const read = await readSseForReconnect(
createFetchSseConnection({
endpoint: "https://app.example.test/events",
applicationOrigin: "https://app.example.test",
recoveryMode: "CURSOR",
fetcher,
clock,
}),
{
resumeCursor: null,
signal: context.signal,
onEvent: () => realtimeSuccess(SSE_CONTINUE),
},
);
// Only connect failures are exercised here.
if (read.result.ok) {
return failed(
realtimeFailure("PROTOCOL_MISMATCH", "CONNECT", false),
);
}
return read as RealtimeReconnectOutcome<never>;
},
});
// 10_000 is each read's connect timeout; 3_000 is the reconnect wait.
const running = coordinator.run();
await flushUntil(() => clock.sleepCalls.length === 2);
expect(clock.sleepCalls).toEqual([10_000, 3_000]);
clock.advance(3_000);
// A hint above the policy's maxDelayMs still ends the run.
await expect(running).resolves.toMatchObject({
ok: false,
error: { operation: "CONNECT", retryable: true },
});
expect(fetcher).toHaveBeenCalledTimes(2);
expect(clock.sleepCalls).toEqual([10_000, 3_000, 10_000]);
},
);
});
@@ -80,31 +80,19 @@ describe("realtime reconnect policy", () => {
expect(parseRetryAfterDelay("-1", 0)).toBeNull();
});
it("resets attempts only after stable open or a valid signal", () => {
expect(
it("resets attempts only after a valid signal on a stable open", () => {
const eligible = (nowMs: number, observed: boolean) =>
isReconnectAttemptResetEligible({
policy,
openedAtMs: 10,
nowMs: 29_000,
observedValidHeartbeatOrEvent: false,
}),
).toBe(false);
expect(
isReconnectAttemptResetEligible({
policy,
openedAtMs: 10,
nowMs: 30_010,
observedValidHeartbeatOrEvent: false,
}),
).toBe(true);
expect(
isReconnectAttemptResetEligible({
policy,
openedAtMs: 10,
nowMs: 11,
observedValidHeartbeatOrEvent: true,
}),
).toBe(true);
nowMs,
observedValidHeartbeatOrEvent: observed,
});
expect(eligible(29_000, false)).toBe(false);
expect(eligible(30_010, false)).toBe(false);
expect(eligible(11, true)).toBe(false);
expect(eligible(30_009, true)).toBe(false);
expect(eligible(30_010, true)).toBe(true);
expect(reconnectBudgetRemaining(policy, 1_000, 2_000)).toBe(
299_000,
);
+78 -1
View File
@@ -1,10 +1,12 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import {
isRealtimeResult,
raceRealtimeTask,
realtimeFailure,
realtimeSuccess,
snapshotRealtimeResult,
timerDeadline,
} from "../../../src/adapters/realtime/result.ts";
function isString(value: unknown): value is string {
@@ -166,3 +168,78 @@ describe("realtime result boundary", () => {
expect(snapshotRealtimeResult(source, isString)).toBeNull();
});
});
describe("realtime abort/deadline race", () => {
const never = () => new Promise<never>(() => undefined);
it("settles with the value, a rejection or a synchronous throw", async () => {
await expect(raceRealtimeTask(() => 7)).resolves.toEqual({
kind: "VALUE",
value: 7,
});
await expect(
raceRealtimeTask(() => Promise.reject(new Error("no"))),
).resolves.toEqual({ kind: "REJECTED" });
await expect(
raceRealtimeTask(() => {
throw new Error("sync");
}),
).resolves.toEqual({ kind: "REJECTED" });
});
it("aborts without starting, or mid-flight with cleanup", async () => {
const task = vi.fn(never);
await expect(
raceRealtimeTask(task, AbortSignal.abort()),
).resolves.toEqual({ kind: "ABORTED" });
expect(task).not.toHaveBeenCalled();
const caller = new AbortController();
const remove = vi.spyOn(caller.signal, "removeEventListener");
let lease: AbortSignal | undefined;
const running = raceRealtimeTask((signal) => {
lease = signal;
return never();
}, caller.signal);
caller.abort();
await expect(running).resolves.toEqual({ kind: "ABORTED" });
expect(lease?.aborted).toBe(true);
expect(remove).toHaveBeenCalledWith("abort", expect.any(Function));
});
it("times out on the deadline and reports a broken deadline", async () => {
let deadlineSignal: AbortSignal | undefined;
await expect(
raceRealtimeTask(never, undefined, (signal) => {
deadlineSignal = signal;
return Promise.resolve();
}),
).resolves.toEqual({ kind: "TIMEOUT" });
expect(deadlineSignal?.aborted).toBe(true);
await expect(
raceRealtimeTask(never, undefined, () => Promise.reject(new Error())),
).resolves.toEqual({ kind: "CLOCK_FAILED" });
// A deadline that throws still lets the task start (e.g. a cancel).
const task = vi.fn(never);
await expect(
raceRealtimeTask(task, undefined, () => {
throw new Error("clock");
}),
).resolves.toEqual({ kind: "CLOCK_FAILED" });
expect(task).toHaveBeenCalledOnce();
});
it("clears a host-timer deadline when the task wins", async () => {
vi.useFakeTimers();
try {
await expect(
raceRealtimeTask(() => "done", undefined, timerDeadline(1_000)),
).resolves.toEqual({ kind: "VALUE", value: "done" });
expect(vi.getTimerCount()).toBe(0);
} finally {
vi.useRealTimers();
}
});
});
+364
View File
@@ -0,0 +1,364 @@
// The round-2 SSE parser (decode each chunk, then re-encode every segment to
// count its bytes), kept only as the oracle for the differential test.
import type { RealtimeResult } from "../../../src/application/ports/realtime/shared.ts";
import {
realtimeFailure,
realtimeSuccess,
} from "../../../src/adapters/realtime/result.ts";
export const SSE_PARSER_CEILINGS = Object.freeze({
maxLineBytes: 64 * 1_024,
maxEventBytes: 64 * 1_024,
maxIncompleteBufferBytes: 128 * 1_024,
maxChunkBytes: 256 * 1_024,
maxItemsPerChunk: 256,
maxRetryMs: 60_000,
});
const LINE_BREAK = /[\r\n]/gu;
const NO_ITEMS: readonly SseParserItem[] = Object.freeze([]);
const COMMENT_ITEMS: readonly SseParserItem[] = Object.freeze([
Object.freeze({ kind: "COMMENT" as const }),
]);
export type SseParserLimits = Readonly<{
maxLineBytes: number;
maxEventBytes: number;
maxIncompleteBufferBytes: number;
maxChunkBytes: number;
maxItemsPerChunk: number;
maxRetryMs: number;
}>;
export type ParsedSseEvent = Readonly<{
kind: "EVENT";
eventType: string;
data: string;
/**
* Standard SSE last-event-ID state. Consumers that require cursor-after-
* effect must additionally require `hasExplicitId` and commit independently.
*/
id: string | null;
hasExplicitId: boolean;
}>;
export type SseParserItem =
| ParsedSseEvent
| Readonly<{ kind: "COMMENT" }>
| Readonly<{ kind: "RETRY"; retryMs: number }>;
export type SseParserFinish = Readonly<{
items: readonly SseParserItem[];
incompleteEventDiscarded: boolean;
}>;
export type IncrementalSseParser = Readonly<{
/**
* Returns at most `maxItemsPerChunk` items. Text past that cap is kept and
* must be taken with `drain()` until it returns no items; pushing or
* finishing before then fails with QUEUE_OVERFLOW.
*/
push(chunk: Uint8Array): RealtimeResult<readonly SseParserItem[]>;
drain(): RealtimeResult<readonly SseParserItem[]>;
finish(): RealtimeResult<SseParserFinish>;
}>;
export function createIncrementalSseParser(
limits: Partial<SseParserLimits> = {},
): IncrementalSseParser {
const resolved = resolveLimits(limits);
// ignoreBOM: false makes the decoder strip the one leading BOM the
// stream grammar allows; a second one is ordinary text.
const decoder = new TextDecoder("utf-8", {
fatal: true,
ignoreBOM: false,
});
const encoder = new TextEncoder();
let state: "OPEN" | "FAILED" | "FINISHED" = "OPEN";
let pendingCarriageReturn = false;
let line = "";
let lineBytes = 0;
let undrained = "";
let blockBytes = 0;
let dataLines: string[] = [];
let eventType = "";
let lastEventId: string | null = null;
let hasExplicitId = false;
function push(
chunk: Uint8Array,
): RealtimeResult<readonly SseParserItem[]> {
if (state !== "OPEN") {
return realtimeFailure("CLOSED", "DECODE");
}
if (!(chunk instanceof Uint8Array)) {
return fail("MALFORMED_EVENT");
}
if (chunk.byteLength > resolved.maxChunkBytes) {
return fail("EVENT_TOO_LARGE");
}
if (undrained.length > 0) return fail("QUEUE_OVERFLOW");
let text: string;
try {
text = decoder.decode(chunk, { stream: true });
} catch {
return fail("MALFORMED_EVENT");
}
return consumeText(text);
}
function drain(): RealtimeResult<readonly SseParserItem[]> {
if (state !== "OPEN") {
return realtimeFailure("CLOSED", "DECODE");
}
const text = undrained;
undrained = "";
return consumeText(text);
}
function finish(): RealtimeResult<SseParserFinish> {
if (state !== "OPEN") {
return realtimeFailure("CLOSED", "DECODE");
}
if (undrained.length > 0) return fail("QUEUE_OVERFLOW");
let tail: string;
try {
tail = decoder.decode();
} catch {
return fail("MALFORMED_EVENT");
}
const consumed = consumeText(tail);
if (!consumed.ok) return consumed;
const items = [...consumed.value];
if (pendingCarriageReturn) {
pendingCarriageReturn = false;
const processed = processLine(1);
if (!processed.ok) return processed;
items.push(...processed.value);
}
if (
undrained.length > 0 ||
items.length > resolved.maxItemsPerChunk
) {
return fail("QUEUE_OVERFLOW");
}
const incompleteEventDiscarded =
lineBytes > 0 ||
blockBytes > 0 ||
dataLines.length > 0 ||
eventType.length > 0 ||
hasExplicitId;
clearBlock();
line = "";
lineBytes = 0;
state = "FINISHED";
return success(
Object.freeze({
items: Object.freeze(items),
incompleteEventDiscarded,
}),
);
}
/**
* Works a line at a time: find the next CR/LF, append the text before it
* and count its UTF-8 bytes once. Byte counts only grow within a line, so
* checking the limits per segment fails exactly where a per-character check
* would. Stops at `maxItemsPerChunk` items and keeps the rest for `drain()`.
*/
function consumeText(
text: string,
): RealtimeResult<readonly SseParserItem[]> {
const items: SseParserItem[] = [];
let index = 0;
while (index < text.length) {
if (items.length >= resolved.maxItemsPerChunk) {
undrained = text.slice(index);
break;
}
if (pendingCarriageReturn) {
pendingCarriageReturn = false;
const lineFeed = text.charCodeAt(index) === 0x0a;
const processed = processLine(lineFeed ? 2 : 1);
if (!processed.ok) return processed;
items.push(...processed.value);
if (lineFeed) index += 1;
continue;
}
LINE_BREAK.lastIndex = index;
const lineBreak = LINE_BREAK.exec(text)?.index ?? text.length;
if (lineBreak > index) {
const segment = text.slice(index, lineBreak);
line += segment;
lineBytes += encoder.encode(segment).byteLength;
if (
lineBytes > resolved.maxLineBytes ||
lineBytes + blockBytes > resolved.maxIncompleteBufferBytes
) {
return fail("EVENT_TOO_LARGE");
}
}
if (lineBreak === text.length) break;
index = lineBreak + 1;
if (text.charCodeAt(lineBreak) === 0x0d) {
pendingCarriageReturn = true;
continue;
}
const processed = processLine(1);
if (!processed.ok) return processed;
items.push(...processed.value);
}
return success(Object.freeze(items));
}
function processLine(
terminatorBytes: number,
): RealtimeResult<readonly SseParserItem[]> {
const currentLine = line;
const currentLineBytes = lineBytes;
line = "";
lineBytes = 0;
if (currentLine.length === 0) {
const items: SseParserItem[] = [];
if (dataLines.length > 0) {
items.push(
Object.freeze({
kind: "EVENT",
eventType: eventType.length > 0 ? eventType : "message",
data: dataLines.join("\n"),
id: lastEventId,
hasExplicitId,
}),
);
}
clearBlock();
return success(Object.freeze(items));
}
if (currentLine.startsWith(":")) return success(COMMENT_ITEMS);
blockBytes += currentLineBytes + terminatorBytes;
if (blockBytes > resolved.maxEventBytes) {
return fail("EVENT_TOO_LARGE");
}
if (blockBytes > resolved.maxIncompleteBufferBytes) {
return fail("EVENT_TOO_LARGE");
}
const separator = currentLine.indexOf(":");
const field =
separator === -1
? currentLine
: currentLine.slice(0, separator);
let value =
separator === -1 ? "" : currentLine.slice(separator + 1);
if (value.startsWith(" ")) value = value.slice(1);
if (field === "data") {
dataLines.push(value);
return success(NO_ITEMS);
}
if (field === "event") {
eventType = value;
return success(NO_ITEMS);
}
if (field === "id") {
if (!value.includes("\0")) {
lastEventId = value;
hasExplicitId = true;
}
return success(NO_ITEMS);
}
if (field === "retry" && /^\d+$/u.test(value)) {
const retryMs = Number(value);
if (
Number.isSafeInteger(retryMs) &&
retryMs <= resolved.maxRetryMs
) {
return success(
Object.freeze([
Object.freeze({ kind: "RETRY" as const, retryMs }),
]),
);
}
}
return success(NO_ITEMS);
}
function clearBlock(): void {
blockBytes = 0;
dataLines = [];
eventType = "";
hasExplicitId = false;
}
function fail(
kind:
| "EVENT_TOO_LARGE"
| "MALFORMED_EVENT"
| "QUEUE_OVERFLOW",
): RealtimeResult<never> {
state = "FAILED";
line = "";
lineBytes = 0;
undrained = "";
clearBlock();
return realtimeFailure(kind, "DECODE");
}
return Object.freeze({ push, drain, finish });
}
function resolveLimits(
input: Partial<SseParserLimits>,
): SseParserLimits {
const limits = {
maxLineBytes:
input.maxLineBytes ?? SSE_PARSER_CEILINGS.maxLineBytes,
maxEventBytes:
input.maxEventBytes ?? SSE_PARSER_CEILINGS.maxEventBytes,
maxIncompleteBufferBytes:
input.maxIncompleteBufferBytes ??
SSE_PARSER_CEILINGS.maxIncompleteBufferBytes,
maxChunkBytes:
input.maxChunkBytes ?? SSE_PARSER_CEILINGS.maxChunkBytes,
maxItemsPerChunk:
input.maxItemsPerChunk ??
SSE_PARSER_CEILINGS.maxItemsPerChunk,
maxRetryMs: input.maxRetryMs ?? SSE_PARSER_CEILINGS.maxRetryMs,
};
if (
!positiveInteger(limits.maxLineBytes) ||
limits.maxLineBytes > SSE_PARSER_CEILINGS.maxLineBytes ||
!positiveInteger(limits.maxEventBytes) ||
limits.maxEventBytes > SSE_PARSER_CEILINGS.maxEventBytes ||
!positiveInteger(limits.maxIncompleteBufferBytes) ||
limits.maxIncompleteBufferBytes >
SSE_PARSER_CEILINGS.maxIncompleteBufferBytes ||
limits.maxIncompleteBufferBytes < limits.maxEventBytes ||
!positiveInteger(limits.maxChunkBytes) ||
limits.maxChunkBytes > SSE_PARSER_CEILINGS.maxChunkBytes ||
limits.maxChunkBytes < limits.maxEventBytes ||
!positiveInteger(limits.maxItemsPerChunk) ||
limits.maxItemsPerChunk >
SSE_PARSER_CEILINGS.maxItemsPerChunk ||
!positiveInteger(limits.maxRetryMs) ||
limits.maxRetryMs > SSE_PARSER_CEILINGS.maxRetryMs
) {
throw new TypeError("Invalid SSE parser limits.");
}
return Object.freeze(limits);
}
function success<Value>(value: Value): RealtimeResult<Value> {
return realtimeSuccess(value);
}
function positiveInteger(value: number): boolean {
return Number.isSafeInteger(value) && value > 0;
}
+332 -12
View File
@@ -4,6 +4,7 @@ import {
createIncrementalSseParser,
type SseParserItem,
} from "../../../src/adapters/realtime/sse/sse-parser.ts";
import { createIncrementalSseParser as createReferenceSseParser } from "./sse-parser-reference.ts";
const encoder = new TextEncoder();
@@ -46,6 +47,29 @@ describe("incremental SSE parser", () => {
});
});
it("strips exactly one leading BOM", () => {
const parser = createIncrementalSseParser();
// The second BOM belongs to the field name, so the line is ignored.
expect(
pushText(parser, "\uFEFF\uFEFFdata: x\n\ndata: y\n\n"),
).toEqual([
{
kind: "EVENT",
eventType: "message",
data: "y",
id: null,
hasExplicitId: false,
},
]);
// Also when the first BOM is split across reads. Node's streaming
// TextDecoder (ignoreBOM: false) drops both BOMs then; the parser must not.
const split = createIncrementalSseParser();
const bytes = encoder.encode("data: x\n\n");
expect(split.push(bytes.subarray(0, 1))).toEqual({ ok: true, value: [] });
expect(split.push(bytes.subarray(1))).toEqual({ ok: true, value: [] });
});
it("preserves standard inherited ID state while marking direct IDs", () => {
const parser = createIncrementalSseParser();
const items = pushText(
@@ -159,18 +183,6 @@ describe("incremental SSE parser", () => {
},
});
const excessiveBatch = createIncrementalSseParser({
maxItemsPerChunk: 2,
});
expect(excessiveBatch.push(encoder.encode(":\n:\n:\n"))).toEqual({
ok: false,
error: {
kind: "QUEUE_OVERFLOW",
operation: "DECODE",
retryable: false,
},
});
const oversizedChunk = createIncrementalSseParser({
maxChunkBytes: 65_536,
});
@@ -185,4 +197,312 @@ describe("incremental SSE parser", () => {
},
});
});
it("hands items past the per-chunk cap to drain() instead of failing", () => {
const parser = createIncrementalSseParser({ maxItemsPerChunk: 1 });
const comment = { kind: "COMMENT" };
expect(pushText(parser, ":\r:\r\n:\ndata: a\r")).toEqual([comment]);
// The retained text resumes between CR and LF.
expect(parser.drain()).toEqual({ ok: true, value: [comment] });
expect(parser.drain()).toEqual({ ok: true, value: [comment] });
expect(parser.drain()).toEqual({ ok: true, value: [] });
expect(parser.drain()).toEqual({ ok: true, value: [] });
expect(pushText(parser, "\n\n")).toEqual([
{
kind: "EVENT",
eventType: "message",
data: "a",
id: null,
hasExplicitId: false,
},
]);
// A lone CR followed by another complete line still honours the cap.
const loneCarriageReturn = createIncrementalSseParser({
maxItemsPerChunk: 1,
});
expect(pushText(loneCarriageReturn, ":\r:\n")).toEqual([comment]);
expect(loneCarriageReturn.drain()).toEqual({
ok: true,
value: [comment],
});
// Undrained items are a caller bug: fail closed instead of buffering.
const undrained = createIncrementalSseParser({ maxItemsPerChunk: 1 });
expect(pushText(undrained, ":\n:\n")).toEqual([comment]);
const overflow = {
ok: false,
error: {
kind: "QUEUE_OVERFLOW",
operation: "DECODE",
retryable: false,
},
};
expect(undrained.push(encoder.encode(":\n"))).toEqual(overflow);
const unfinished = createIncrementalSseParser({ maxItemsPerChunk: 1 });
expect(pushText(unfinished, ":\n:\n")).toEqual([comment]);
expect(unfinished.finish()).toEqual(overflow);
});
it("parses the same items whether bytes arrive at once or one by one", () => {
const stream = encoder.encode(
"event: a\r\ndata: 한글\rdata: 😀 é\r\n\r\n" +
": note\rid: c-1\ndata: xy\r\rretry: 10\n" +
"data: last\n\n",
);
const whole = createIncrementalSseParser();
const wholeResult = whole.push(stream);
if (!wholeResult.ok) throw new Error(wholeResult.error.kind);
const split = createIncrementalSseParser();
const splitItems: SseParserItem[] = [];
for (let index = 0; index < stream.length; index += 1) {
const pushed = split.push(stream.subarray(index, index + 1));
if (!pushed.ok) throw new Error(pushed.error.kind);
splitItems.push(...pushed.value);
}
const expected: SseParserItem[] = [
{
kind: "EVENT",
eventType: "a",
data: "한글\n😀 é",
id: null,
hasExplicitId: false,
},
{ kind: "COMMENT" },
{
kind: "EVENT",
eventType: "message",
data: "xy",
id: "c-1",
hasExplicitId: true,
},
{ kind: "RETRY", retryMs: 10 },
{
kind: "EVENT",
eventType: "message",
data: "last",
id: "c-1",
hasExplicitId: false,
},
];
expect(wholeResult.value).toEqual(expected);
expect(splitItems).toEqual(expected);
});
it("dispatches a trailing CR-terminated blank line only at finish", () => {
const parser = createIncrementalSseParser();
expect(pushText(parser, "data: a\rdata: b\r\r")).toEqual([]);
expect(parser.finish()).toEqual({
ok: true,
value: {
items: [
{
kind: "EVENT",
eventType: "message",
data: "a\nb",
id: null,
hasExplicitId: false,
},
],
incompleteEventDiscarded: false,
},
});
});
it("counts UTF-8 bytes, not UTF-16 units, against line and event limits", () => {
const limits = {
maxLineBytes: 9,
maxEventBytes: 11,
maxIncompleteBufferBytes: 11,
};
const tooLarge = {
ok: false,
error: {
kind: "EVENT_TOO_LARGE",
operation: "DECODE",
retryable: false,
},
};
// "data:😀" is 7 UTF-16 units but 9 bytes; the CRLF makes the event 11.
expect(
createIncrementalSseParser(limits).push(
encoder.encode("data:😀\r\n\r\n"),
),
).toMatchObject({ ok: true, value: [{ data: "😀" }] });
expect(
createIncrementalSseParser(limits).push(
encoder.encode("data:😀a"),
),
).toEqual(tooLarge);
expect(
createIncrementalSseParser(limits).push(
encoder.encode("data:한\r\ndata:\r\n"),
),
).toEqual(tooLarge);
// The same limit holds when the multibyte character is split across reads.
const split = createIncrementalSseParser(limits);
const bytes = encoder.encode("data:한한");
expect(split.push(bytes.subarray(0, 6))).toEqual({
ok: true,
value: [],
});
expect(split.push(bytes.subarray(6))).toEqual(tooLarge);
});
it("accepts a maximum-size line across many reads and rejects one byte more", () => {
const maxLineBytes = 32 * 1_024;
const payload = "é".repeat((maxLineBytes - 6) / 2);
const exact = encoder.encode(`data: ${payload}\n\n`);
// 1,000-byte reads split some two-byte "é" characters.
const parser = createIncrementalSseParser({ maxLineBytes });
const items: SseParserItem[] = [];
for (let index = 0; index < exact.length; index += 1_000) {
const pushed = parser.push(exact.subarray(index, index + 1_000));
if (!pushed.ok) throw new Error(pushed.error.kind);
items.push(...pushed.value);
}
expect(items).toEqual([
{
kind: "EVENT",
eventType: "message",
data: payload,
id: null,
hasExplicitId: false,
},
]);
const over = createIncrementalSseParser({ maxLineBytes });
const overBytes = encoder.encode(`data: ${payload}a`);
expect(over.push(overBytes.subarray(0, 20_000))).toEqual({
ok: true,
value: [],
});
expect(over.push(overBytes.subarray(20_000))).toEqual({
ok: false,
error: {
kind: "EVENT_TOO_LARGE",
operation: "DECODE",
retryable: false,
},
});
});
it("parses a full-size chunk of many events", () => {
const events = Array.from({ length: 200 }, (_, index) =>
JSON.stringify({ index, value: "v".repeat(1_200) }),
);
const chunk = encoder.encode(
events
.map((data, index) => `id: c-${index}\r\ndata: ${data}\r\n\r\n`)
.join(""),
);
expect(chunk.byteLength).toBeGreaterThan(240 * 1_024);
expect(chunk.byteLength).toBeLessThanOrEqual(256 * 1_024);
const pushed = createIncrementalSseParser().push(chunk);
if (!pushed.ok) throw new Error(pushed.error.kind);
expect(pushed.value).toHaveLength(200);
expect(pushed.value[199]).toEqual({
kind: "EVENT",
eventType: "message",
data: events[199],
id: "c-199",
hasExplicitId: true,
});
});
});
describe("byte-level SSE parser against the round-2 text parser", () => {
const asciiPieces = [
"data", "data:", "data: ", "event: ", "id: ", "id:", "retry: ",
":", "x", " ", "abc", "12", "\0", "\r", "\n", "\r\n", "\n\n", "\r\r",
];
const multibytePieces = [...asciiPieces, "é", "한글", "😀", ""];
type Create = typeof createIncrementalSseParser;
// mulberry32: a small seeded PRNG, so a failing seed can be replayed.
function randomSource(seed: number): () => number {
let state = seed;
return () => {
state = (state + 0x6d2b79f5) | 0;
let value = Math.imul(state ^ (state >>> 15), 1 | state);
value ^= value + Math.imul(value ^ (value >>> 7), 61 | value);
return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
};
}
function run(
create: Create,
limits: Parameters<Create>[0],
chunks: readonly Uint8Array[],
skipDrain: readonly boolean[],
): unknown[] {
const parser = create(limits);
const log: unknown[] = [];
for (const [index, chunk] of chunks.entries()) {
let result = parser.push(chunk);
log.push(result);
while (!skipDrain[index] && result.ok && result.value.length > 0) {
result = parser.drain();
log.push(result);
}
if (!result.ok) return log;
}
log.push(parser.finish());
return log;
}
it.each([
["ASCII", asciiPieces],
["multibyte", multibytePieces],
])("matches on random %s streams and read splits", (_, pieces) => {
for (let seed = 1; seed <= 1_500; seed += 1) {
const next = randomSource(seed);
const pick = (max: number) => Math.floor(next() * max);
let text = next() < 0.3 ? "" : "";
for (let count = 1 + pick(40); count > 0; count -= 1) {
text += pieces[pick(pieces.length)];
}
// Node's streaming TextDecoder, which the reference relies on, drops a
// U+FEFF right after the first character when that character is split
// across reads (see the BOM test above). Keep that input out.
const first = String.fromCodePoint(text.codePointAt(0) ?? 0x20);
while (text.startsWith("", first.length)) {
text = first + text.slice(first.length + 1);
}
let bytes = encoder.encode(text);
// Cutting the stream can end it inside a character.
if (next() < 0.2) bytes = bytes.subarray(0, pick(bytes.length + 1));
const chunks: Uint8Array[] = [];
const maxRead = 1 + pick(next() < 0.5 ? 6 : bytes.length + 1);
for (let index = 0; index < bytes.length; ) {
const size = 1 + pick(maxRead);
chunks.push(bytes.subarray(index, index + size));
index += size;
}
const skipDrain = chunks.map(() => next() < 0.05);
const maxEventBytes = 4 + pick(60);
const limits =
next() < 0.3
? {}
: {
maxLineBytes: 4 + pick(40),
maxEventBytes,
maxIncompleteBufferBytes: maxEventBytes + pick(20),
maxItemsPerChunk: 1 + pick(4),
};
expect(
run(createIncrementalSseParser, limits, chunks, skipDrain),
`seed ${seed}`,
).toEqual(run(createReferenceSseParser, limits, chunks, skipDrain));
}
});
});
+102 -15
View File
@@ -707,7 +707,7 @@ describe("transport-independent realtime stream coordinator", () => {
expect(harness.coordinator.inspect(STREAM_ID).freshness).toBe("STALE");
});
it("recovers instead of evicting and continuing after dedupe capacity", async () => {
it("evicts the oldest dedupe entry and keeps applying at capacity", async () => {
const harness = createHarness({
registry: createTestRealtimeRegistry({
limits: {
@@ -718,24 +718,58 @@ describe("transport-independent realtime stream coordinator", () => {
});
await harness.initialize();
await harness.coordinator.accept(harness.event());
const second = {
eventId: "event-00000002",
sequence: "2",
resumeCursor: "cursor-00000002",
};
await expect(
harness.coordinator.accept(
harness.event({
eventId: "event-00000002",
sequence: "2",
resumeCursor: "cursor-00000002",
}),
),
harness.coordinator.accept(harness.event(second)),
).resolves.toMatchObject({
ok: true,
value: {
outcome: "RECOVERED",
reason: "DEDUPE_OVERFLOW",
},
value: { outcome: "APPLIED" },
});
expect(harness.effects).toHaveBeenCalledTimes(1);
expect(harness.coordinator.inspect(STREAM_ID).dedupeEntries).toBe(0);
expect(harness.effects).toHaveBeenCalledTimes(2);
expect(harness.recoveryReasons).toEqual(["INITIALIZE"]);
expect(harness.coordinator.inspect(STREAM_ID).dedupeEntries).toBe(1);
// The newest entry still catches its duplicate; the evicted one is stale.
await expect(
harness.coordinator.accept(harness.event(second)),
).resolves.toMatchObject({
ok: true,
value: { outcome: "DROPPED", reason: "DUPLICATE_EVENT" },
});
await expect(
harness.coordinator.accept(harness.event()),
).resolves.toMatchObject({
ok: true,
value: { outcome: "DROPPED", reason: "STALE_EVENT" },
});
});
it("expires dedupe entries by TTL oldest first", async () => {
let now = 10_000;
const harness = createHarness({ now: () => now });
await harness.initialize();
await harness.coordinator.accept(harness.event());
now += TEST_LIMITS.dedupeTtlMs / 2;
await harness.coordinator.accept(
harness.event({
eventId: "event-00000002",
sequence: "2",
resumeCursor: "cursor-00000002",
}),
);
now += TEST_LIMITS.dedupeTtlMs / 2;
await harness.coordinator.accept(
harness.event({
eventId: "event-00000003",
sequence: "3",
resumeCursor: "cursor-00000003",
}),
);
expect(harness.coordinator.inspect(STREAM_ID).dedupeEntries).toBe(2);
});
it("rejects a regressing same-epoch recovery checkpoint atomically", async () => {
@@ -1053,6 +1087,58 @@ describe("realtime physical task ownership", () => {
firstApply.resolve(realtimeSuccess(undefined));
});
it("fails a recovery whose effect quiescence ends in DRAINING", async () => {
const wedged = deferred<RealtimeResult<void>>();
let recoveries = 0;
const harness = createHarness({
apply: async () => wedged.promise,
recover: async () => {
recoveries += 1;
return realtimeSuccess(snapshotCommit("0"));
},
taskLimits: { effectTimeoutMs: 5, drainTimeoutMs: 5 },
});
await harness.initialize();
recoveries = 0;
const applying = harness.coordinator.accept(
harness.event({
eventId: "event-00000001",
sequence: "1",
resumeCursor: "cursor-00000001",
}),
);
for (let flush = 0; flush < 10; flush += 1) await Promise.resolve();
expect(harness.effects).toHaveBeenCalledOnce();
expect(harness.coordinator.lifecycle(STREAM_ID)).toBe("OPEN");
// The effect ignores abort, so it outlives its deadline and the stream
// enters DRAINING while this recovery waits for quiescence.
const recovering = harness.coordinator.recover(
STREAM_ID,
"SEQUENCE_GAP",
);
await expect(applying).resolves.toMatchObject({
ok: false,
error: { kind: "IDLE_TIMEOUT", operation: "APPLY" },
});
await expect(recovering).resolves.toMatchObject({
ok: false,
error: { kind: "CLOSED", operation: "RECOVER" },
});
expect(recoveries).toBe(0);
expect(harness.coordinator.inspect(STREAM_ID).hasResumeState).toBe(
false,
);
// The late effect settles; the stream still needs a real recovery.
wedged.resolve(realtimeSuccess(undefined));
await vi.waitFor(() =>
expect(harness.coordinator.lifecycle(STREAM_ID)).toBe("OPEN"),
);
expect(harness.coordinator.inspect(STREAM_ID).freshness).toBe("STALE");
});
});
type HarnessOptions = Readonly<{
@@ -1070,6 +1156,7 @@ type HarnessOptions = Readonly<{
}>;
scheduleTimeout?: (callback: () => void, delayMs: number) => unknown;
clearScheduledTimeout?: (handle: unknown) => void;
now?: () => number;
}>;
function createHarness(options: HarnessOptions = {}) {
@@ -1113,7 +1200,7 @@ function createHarness(options: HarnessOptions = {}) {
scopeBinding: "scope-binding-0001",
isCurrent: () => current,
},
now: () => 10_000,
now: options.now ?? (() => 10_000),
observe: options.observe,
...(options.taskLimits ? { taskLimits: options.taskLimits } : {}),
...(options.scheduleTimeout
+4 -3
View File
@@ -334,10 +334,11 @@ describe("registry governance manifest", () => {
edges: expect.any(Array),
});
expect(versions?.rows).toBeDefined();
// Who approved and why, not this template's wording: a project that
// re-baselines with update:registry-baseline writes its own (D-13).
expect(approval).toMatchObject({
owner: "tech-log-frontend",
reason:
"Install approved TechLog Public and Studio route contract",
owner: expect.stringMatching(/\S/u),
reason: expect.stringMatching(/\S/u),
});
});
+3 -3
View File
@@ -63,7 +63,7 @@ const buildManifest = {
describe("release artifact contracts", () => {
it("verifies confined build outputs and the raw module inventory bytes", async () => {
const moduleInventoryBytes = Buffer.from(
'{"schemaVersion":1,"chunks":[]}\n',
'{"schemaVersion":1,"chunks":[],"packages":[]}\n',
);
const files = new Map<string, Buffer>([
["/repo/dist/.vite/manifest.json", Buffer.from("{}\n")],
@@ -158,7 +158,7 @@ describe("release artifact contracts", () => {
it("rejects a nested symlink that resolves inside the repository but outside dist", async () => {
const moduleInventoryBytes = Buffer.from(
'{"schemaVersion":1,"chunks":[]}\n',
'{"schemaVersion":1,"chunks":[],"packages":[]}\n',
);
const mismatches = await verifyBuildManifestOutputs(
{
@@ -183,7 +183,7 @@ describe("release artifact contracts", () => {
it("allows a legal dist child whose name begins with two dots", async () => {
const moduleInventoryBytes = Buffer.from(
'{"schemaVersion":1,"chunks":[]}\n',
'{"schemaVersion":1,"chunks":[],"packages":[]}\n',
);
const files = new Map<string, Buffer>([
["/repo/dist/.vite/manifest.json", Buffer.from("{}\n")],
+14 -64
View File
@@ -283,32 +283,32 @@ describe("release coherence", () => {
}
});
it("falls back to public rollback artifacts only when primary dist is absent", async () => {
// 13-03: the rollback drill checks the built release only. Reading the
// public/ placeholders when dist was absent let it pass without any build.
it("reads only the built dist pair and never falls back to public placeholders", async () => {
const exactV2 = await releaseV2With(contractPackages);
const tamperedPrimary = await releaseV2With(contractPackages.slice(0, 1));
const validPublic = {
"public/release-manifest.json": exactV2,
"public/config.json": runtimeV2,
};
const unavailablePrimary = [
new SyntaxError("invalid primary JSON"),
Object.assign(new Error("unreadable primary"), { code: "EACCES" }),
{ ...exactV2, unexpected: "tampered" },
];
for (const primaryFailure of unavailablePrimary) {
for (const primary of [
{},
{ "dist/config.json": runtimeV2 },
{ "dist/release-manifest.json": exactV2 },
{ "dist/release-manifest.json": new SyntaxError("invalid primary JSON"), "dist/config.json": runtimeV2 },
{ "dist/release-manifest.json": { ...exactV2, unexpected: "tampered" }, "dist/config.json": runtimeV2 },
]) {
const reads: string[] = [];
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader({
"dist/release-manifest.json": primaryFailure,
"dist/config.json": runtimeV2,
...validPublic,
}),
readArtifact: artifactReader({ ...primary, ...validPublic }, reads),
contractPackages,
}),
).rejects.toBeDefined();
expect(reads.some((read) => read.startsWith("public/"))).toBe(false);
}
const tamperedPrimary = await releaseV2With(contractPackages.slice(0, 1));
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader({
@@ -319,55 +319,5 @@ describe("release coherence", () => {
contractPackages,
}),
).resolves.toMatchObject({ coherence: { compatible: false } });
const releaseOnlyMissingReads: string[] = [];
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader(
{
"dist/config.json": runtimeV2,
...validPublic,
},
releaseOnlyMissingReads,
),
contractPackages,
}),
).rejects.toThrow("primary rollback artifact pair");
expect(releaseOnlyMissingReads).toEqual([
"dist/release-manifest.json",
"dist/config.json",
]);
const runtimeOnlyMissingReads: string[] = [];
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader(
{
"dist/release-manifest.json": exactV2,
...validPublic,
},
runtimeOnlyMissingReads,
),
contractPackages,
}),
).rejects.toThrow("primary rollback artifact pair");
expect(runtimeOnlyMissingReads).toEqual([
"dist/release-manifest.json",
"dist/config.json",
]);
const missingPairReads: string[] = [];
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader(validPublic, missingPairReads),
contractPackages,
}),
).resolves.toMatchObject({ coherence: { compatible: true } });
expect(missingPairReads).toEqual([
"dist/release-manifest.json",
"dist/config.json",
"public/release-manifest.json",
"public/config.json",
]);
});
});
+87 -36
View File
@@ -9,6 +9,7 @@ import {
assertNoRuntimeImports,
pruneRemovalFixtureCiContract,
removeRuntimeDependentTests,
renderRemovalJunit,
runtimeImportGraph,
} from "../../scripts/lib/removal-fixture.ts";
@@ -53,12 +54,20 @@ it("allows zero runtime imports after the runtime has been removed", async () =>
).resolves.toBeUndefined();
});
it("prunes removed command and evidence references from a reduced CI contract", async () => {
const root = await mkdtemp(path.join(tmpdir(), "removal-fixture-contract-"));
async function copyCiContract(prefix: string): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), prefix));
temporaryRoots.push(root);
await mkdir(path.join(root, "config/ci"), { recursive: true });
await writeFile(path.join(root, "config/ci/gates.json"), await readFile("config/ci/gates.json"));
await writeFile(path.join(root, "package.json"), await readFile("package.json"));
for (const file of ["config/ci/gates.json", "config/ci/contract-baseline.json", "package.json"]) {
await writeFile(path.join(root, file), await readFile(file));
}
return root;
}
// D-13: a removal takes the same step a downstream project takes — it records
// the reduced contract as the new baseline — and then loads canonically.
it("prunes removed command and evidence references and re-baselines the contract", async () => {
const root = await copyCiContract("removal-fixture-contract-");
await pruneRemovalFixtureCiContract({
root,
@@ -66,21 +75,36 @@ it("prunes removed command and evidence references from a reduced CI contract",
removedEvidencePathFragments: ["reference-feature.xml"],
});
const contract = await loadCiGateContract(root, { mode: "removal-fixture" });
const contract = await loadCiGateContract(root);
expect(contract.commands.some(({ script }) => script === "test:reference-feature")).toBe(false);
expect(contract.artifacts.some(({ path }) => path.includes("reference-feature.xml"))).toBe(false);
expect(contract.gates.some(({ commandIds }) => commandIds.includes("test-reference-feature"))).toBe(false);
expect(contract.gates.some(({ evidenceArtifactIds }) =>
evidenceArtifactIds.includes("artifact-artifacts-tests-reference-feature-xml")
)).toBe(false);
const baseline = JSON.parse(
await readFile(path.join(root, "config/ci/contract-baseline.json"), "utf8"),
) as Record<string, unknown>;
expect(baseline).toMatchObject({ commands: contract.commands.length, owner: "removal-fixture" });
const packageDocument = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")) as {
scripts: Record<string, string>;
};
expect(packageDocument.scripts["check:ci"]).not.toMatch(/reduced/u);
});
it("rejects a contract that no longer matches its committed baseline", async () => {
const root = await copyCiContract("removal-fixture-baseline-drift-");
const baselinePath = path.join(root, "config/ci/contract-baseline.json");
const baseline = JSON.parse(await readFile(baselinePath, "utf8")) as Record<string, number>;
await writeFile(baselinePath, JSON.stringify({ ...baseline, commands: baseline.commands! + 1 }));
await expect(loadCiGateContract(root)).rejects.toThrow(
/contract-baseline\.json[\s\S]*commands[\s\S]*update:ci-contract-baseline/u,
);
});
it("rejects pruning that leaves a reduced gate without commands", async () => {
const root = await mkdtemp(path.join(tmpdir(), "removal-fixture-empty-gate-"));
temporaryRoots.push(root);
await mkdir(path.join(root, "config/ci"), { recursive: true });
await writeFile(path.join(root, "config/ci/gates.json"), await readFile("config/ci/gates.json"));
await writeFile(path.join(root, "package.json"), await readFile("package.json"));
const root = await copyCiContract("removal-fixture-empty-gate-");
await expect(pruneRemovalFixtureCiContract({
root,
@@ -96,39 +120,66 @@ describe("release evidence fixture copy", () => {
const { RELEASE_CANDIDATE_EVIDENCE_PATHS } = await import(
"../../scripts/lib/release-candidate.ts"
);
const { mkdtemp, access, readdir } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const nodePath = (await import("node:path")).default;
const { access, readdir } = await import("node:fs/promises");
const root = await mkdtemp(nodePath.join(tmpdir(), "release-evidence-"));
await copyReleaseEvidenceTree(process.cwd(), root);
// The source is a fake checkout, not process.cwd(): release evidence is
// git-ignored, so a fresh clone has none of it and the copy would be
// checked against nothing.
const source = await mkdtemp(path.join(tmpdir(), "release-evidence-source-"));
const target = await mkdtemp(path.join(tmpdir(), "release-evidence-target-"));
temporaryRoots.push(source, target);
const evidencePaths = RELEASE_CANDIDATE_EVIDENCE_PATHS.filter((evidence) =>
evidence.startsWith("artifacts/")
);
expect(evidencePaths.length).toBeGreaterThan(0);
for (const relative of [
...evidencePaths,
...RELEASE_EVIDENCE_REGENERATED_TREES.map((tree) => `${tree}/trace.zip`),
]) {
await mkdir(path.dirname(path.join(source, relative)), { recursive: true });
await writeFile(path.join(source, relative), "{}\n");
}
// Every release artifact that exists here has to survive the copy; a
// fixture missing one cannot build a candidate at all, and every provider
// suite then fails while constructing its own fixture.
//
// Which ones exist depends on what this checkout has generated — a product
// repository that has not run the release chain has fewer than the template
// does — so the subject is preservation, not the presence of a full chain.
// Requiring at least one keeps that from quietly asserting nothing.
let preserved = 0;
for (const evidence of RELEASE_CANDIDATE_EVIDENCE_PATHS) {
if (!evidence.startsWith("artifacts/")) continue;
try {
await access(evidence);
} catch {
continue;
}
await expect(access(nodePath.join(root, evidence)), evidence).resolves.toBeUndefined();
preserved += 1;
await copyReleaseEvidenceTree(source, target);
// Every release artifact has to survive the copy; a fixture missing one
// cannot build a candidate at all, and every provider suite then fails
// while constructing its own fixture.
for (const evidence of evidencePaths) {
await expect(access(path.join(target, evidence)), evidence).resolves.toBeUndefined();
}
expect(preserved).toBeGreaterThan(0);
// The regenerated trees are why this is a filter and not a plain copy: they
// are tens of megabytes of traces and coverage HTML. They still exist,
// because the repository inventory expects the directories.
for (const tree of RELEASE_EVIDENCE_REGENERATED_TREES) {
await expect(access(nodePath.join(root, tree)), tree).resolves.toBeUndefined();
await expect(readdir(nodePath.join(root, tree)), tree).resolves.toEqual([]);
await expect(readdir(path.join(target, tree)), tree).resolves.toEqual([]);
}
});
});
describe("removal JUnit report (14-08)", () => {
it("counts every failure and gives each check its own cause", () => {
const xml = renderRemovalJunit("reference-feature-removal", [
{ name: "typecheck", passed: false, failure: "corepack pnpm check:types exited 2" },
{ name: "architecture", passed: true },
{ name: "build", passed: false, failure: "corepack pnpm build exited 1" },
{
name: "fixture-id-residue",
passed: false,
failure: "residue: tests/a.test.ts, tests/<b>&c.ts",
},
]);
expect(xml).toContain('tests="4" failures="3"');
expect(xml).toContain(
'<testcase name="typecheck"><failure message="corepack pnpm check:types exited 2" /></testcase>',
);
expect(xml).toContain('<testcase name="architecture"></testcase>');
expect(xml).toContain(
'<failure message="corepack pnpm build exited 1" />',
);
expect(xml).toContain(
'message="residue: tests/a.test.ts, tests/&lt;b&gt;&amp;c.ts"',
);
expect(xml.match(/residue:/gu)).toHaveLength(1);
});
});
+14 -2
View File
@@ -1,8 +1,8 @@
import { mkdtemp, mkdir, symlink, writeFile } from "node:fs/promises";
import { mkdtemp, mkdir, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { afterEach, describe, expect, it } from "vitest";
import {
buildRepositoryFileInventory,
@@ -23,8 +23,19 @@ function gitResult(
};
}
// 00-03. Every temp root is removed after its test; they used to pile up in
// /tmp by the thousand.
const temporaryRoots: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
async function repositoryFixture() {
const root = await mkdtemp(path.join(tmpdir(), "repository-inventory-"));
temporaryRoots.push(root);
await mkdir(path.join(root, "src"));
await mkdir(path.join(root, "docs"));
await writeFile(path.join(root, "src", "tracked.ts"), "tracked\n");
@@ -203,6 +214,7 @@ describe("repository file inventory", () => {
it("rejects a tracked symlink whose real path escapes the repository", async () => {
const repositoryRoot = await repositoryFixture();
const outside = await mkdtemp(path.join(tmpdir(), "inventory-outside-"));
temporaryRoots.push(outside);
await writeFile(path.join(outside, "secret.ts"), "secret\n");
await symlink(
path.join(outside, "secret.ts"),
+9
View File
@@ -62,4 +62,13 @@ describe("deterministic HTTP request target", () => {
buildRequestTarget("http://api.test", operation, { resourceId: "one" }),
).toEqual({ success: false, code: "BASE_URL_INVALID" });
});
it.each([".", ".."])(
"rejects the dot segment %j instead of letting pathname normalization move the target",
(resourceId) => {
expect(
buildRequestTarget("https://api.test/base/", operation, { resourceId }),
).toEqual({ success: false, code: "PATH_PARAMETER_INVALID" });
},
);
});
+76
View File
@@ -1,11 +1,19 @@
import { describe, expect, it } from "vitest";
import { defineRestOperation } from "../../src/contracts/api-operations.ts";
import {
composeContractContributions,
ContractContributionError,
} from "../../src/contracts/external-contract-runtime.ts";
import {
createRestProviderProfile,
INSTALLED_REST_AUTH_PROFILES,
installRestAuthProfileRegistry,
resolveRestSecurityProfiles,
REST_AUTH_PROFILES,
validateRestProfileBindings,
} from "../../src/contracts/rest-profiles.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
/**
* §24.12: the common REST profile contract must stay independently verifiable
@@ -96,3 +104,71 @@ describe("REST provider/auth/CSRF profiles", () => {
).toThrow("Unregistered REST provider binding");
});
});
/**
* Q-6.7-9. Composition, the V3 executor and the V2 resolve must all answer
* from one validated installed registry. A raw record handed to resolve used
* to skip installation, so a bearer profile with ambient credentials passed.
*/
describe("one installed REST auth profile registry", () => {
const provider = createRestProviderProfile("PRIMARY_API", "https://api.test", [
"omit",
"same-origin",
]);
it("rejects a raw profile record that installation would refuse", () => {
const incoherent = {
REFERENCE_EXTERNAL_BEARER: {
...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER,
credentials: "same-origin" as const,
},
};
expect(() =>
resolveRestSecurityProfiles(SAMPLE_COMMAND, provider, incoherent),
).toThrow(TypeError);
});
it("resolves through the installed registry", () => {
expect(
resolveRestSecurityProfiles(
SAMPLE_COMMAND,
provider,
INSTALLED_REST_AUTH_PROFILES,
).auth,
).toBe(INSTALLED_REST_AUTH_PROFILES.get("REFERENCE_EXTERNAL_BEARER"));
});
it("does not resolve an inherited profile id", () => {
expect(() =>
resolveRestSecurityProfiles(
{ ...SAMPLE_COMMAND, authProfileId: "toString" },
provider,
REST_AUTH_PROFILES,
),
).toThrow("incoherent");
});
it("composes contributions against the registry it is given", () => {
const registry = installRestAuthProfileRegistry({
...REST_AUTH_PROFILES,
CUSTOM_BEARER: {
...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER,
authProfileId: "CUSTOM_BEARER",
},
});
const row = TEST_CONTRACT_CONTRIBUTION.http[0]!;
const contribution = {
...TEST_CONTRACT_CONTRIBUTION,
http: [
{ ...row, frontend: { ...row.frontend, authProfileId: "CUSTOM_BEARER" } },
],
};
expect(() => composeContractContributions([contribution])).toThrow(
ContractContributionError,
);
expect(
composeContractContributions([contribution], registry).httpByOperationId
.size,
).toBe(1);
});
});
@@ -7,6 +7,7 @@ import {
createIndexedDbResumableUploadCheckpointStore,
uploadCheckpointDatabaseName,
} from "../../src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts";
import { mapIndexedDbException } from "../../src/adapters/browser-file-storage/result.ts";
import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts";
const scope = Object.freeze({
@@ -317,6 +318,43 @@ describe("IndexedDB resumable upload checkpoint", () => {
});
});
// Q-6.1-6. The revision-free delete exists only for rows this build cannot
// read; a readable checkpoint still needs the exact-revision remove.
it("removes only an unreadable row without a revision", async () => {
const memory = new MemoryIndexedDbFactory();
const store = createIndexedDbResumableUploadCheckpointStore({
scope,
factory: memory.factory,
});
const readable = checkpoint(1);
expect(
await store.compareAndSwap({ expectedRevision: null, checkpoint: readable }),
).toMatchObject({ ok: true });
expect(
await store.removeUnreadable?.({ uploadKey: readable.uploadKey }),
).toMatchObject({
ok: false,
error: { code: "CONFLICT", recovery: "RECONCILE" },
});
expect(await store.read(readable.uploadKey)).toEqual({
ok: true,
value: readable,
});
memory.seed("checkpoints", { ...readable, schemaVersion: 2 });
expect(await store.read(readable.uploadKey)).toMatchObject({
ok: false,
error: { code: "CORRUPT_DATA" },
});
expect(
await store.removeUnreadable?.({ uploadKey: readable.uploadKey }),
).toEqual({ ok: true, value: undefined });
expect(await store.read(readable.uploadKey)).toEqual({
ok: true,
value: null,
});
});
it("closes the bound partition before successful lifecycle deletion", async () => {
const memory = new MemoryIndexedDbFactory();
const runtime = createIndexedDbResumableUploadCheckpointRuntime({
@@ -477,6 +515,37 @@ describe("IndexedDB resumable upload checkpoint", () => {
});
});
// F-1 (05-11). The store maps native errors with the one IndexedDB table, so
// a missing store is a schema problem and a quota failure is not retried.
it("maps native request errors with the shared IndexedDB table", async () => {
for (const name of [
"ConstraintError",
"NotFoundError",
"QuotaExceededError",
"InvalidStateError",
"UnknownError",
"SecurityError",
]) {
const scripted = scriptedFactory();
const store = createIndexedDbResumableUploadCheckpointStore({
scope,
factory: scripted.factory,
});
const pending = store.read("upload_key_01");
const transaction = await openedCheckpointTransaction(scripted);
const read = transaction.requests[0];
if (!read) throw new Error("the checkpoint read queued no request");
const error = new DOMException("native detail", name);
read.error = error;
read.onerror?.(new Event("error"));
expect(await pending).toEqual(
mapIndexedDbException(error, "UPLOAD_RECONCILE"),
);
}
});
// CP-4. The transaction can already be durably committed while its completion
// event is still queued, which is when `abort()` throws. Claiming the abort
// would report a committed checkpoint as ABORTED.
@@ -4,10 +4,13 @@ import {
createResumableUploadFetchJsonTransport,
type ResumableUploadFetchTransportDependencies,
} from "../../src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts";
import type {
ResumableUploadControlOperation,
ResumableUploadJsonTransport,
import {
createResumableUploadHttpControlPlane,
type ResumableUploadControlOperation,
type ResumableUploadJsonTransport,
} from "../../src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts";
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../src/application/ports/browser-transfer/resumable-upload.ts";
import { browserDataFailure } from "../../src/adapters/browser-file-storage/result.ts";
import { createResumableUploadWebLock } from "../../src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts";
const API_ORIGIN = "https://api.example";
@@ -97,14 +100,21 @@ describe("resumable upload fetch transport", () => {
},
);
it("ignores an invalid Retry-After date instead of guessing", async () => {
it.each([
"not-a-date",
// R3-2: the kernel parser rejects these; the old local copy fed them to
// Date.parse and turned them into a zero-delay retry.
"1.5",
"2025-01-01",
"Wednesday, 21-Oct-15 07:28:00 GMT",
])("ignores an invalid Retry-After value instead of guessing (%s)", async (header) => {
const transport = createTransport(
(async () =>
responseAt(ENDPOINTS.GET_STATUS, null, {
status: 429,
headers: { "retry-after": "not-a-date" },
headers: { "retry-after": header },
})) as unknown as typeof fetch,
{ nowEpochMs: () => 1_000 },
{ nowEpochMs: () => Date.UTC(2026, 0, 1) },
);
const result = await transport.execute({
@@ -649,3 +659,81 @@ describe("resumable upload Web Lock", () => {
});
});
});
describe("transport byte limits against the part count (01-09)", () => {
const base = {
endpoints: ENDPOINTS,
allowedOrigins: [API_ORIGIN],
credentials: "same-origin" as const,
fetcher: vi.fn() as unknown as typeof fetch,
};
it("accepts the default limits for the default 1,024-part policy", () => {
expect(() =>
createResumableUploadFetchJsonTransport({ ...base, maxPartCount: 1_024 }),
).not.toThrow();
});
it.each([
["the policy ceiling of 10,000 parts", { maxPartCount: 10_000 }],
[
"a 64 KiB response cap",
{ maxPartCount: 1_024, maxResponseBytes: 64 * 1024 },
],
[
"a 64 KiB request cap",
{ maxPartCount: 1_024, maxRequestBytes: 64 * 1024 },
],
] as const)("refuses %s at composition", (_label, overrides) => {
expect(() =>
createResumableUploadFetchJsonTransport({ ...base, ...overrides }),
).toThrow(TypeError);
});
it("never accepts a request cap below a real worst-case complete body", async () => {
const partCount = 100;
const partSizeBytes = 64 * 1024 * 1024;
let body: unknown;
const controlPlane = createResumableUploadHttpControlPlane({
transport: {
async execute(request) {
body = request.body;
return browserDataFailure("UNAVAILABLE", "UPLOAD_COMPLETE");
},
},
partCapabilities: { issueUploadPart: vi.fn() },
});
await controlPlane.complete({
protocol: RESUMABLE_UPLOAD_PROTOCOL,
sessionId: "s".repeat(512),
requestBindingSha256: "c".repeat(64),
fingerprint: {
algorithm: "SHA-256-PARTS-V1",
digestHex: "d".repeat(64),
byteLength: partCount * partSizeBytes,
partSizeBytes,
partCount,
},
orderedParts: Array.from({ length: partCount }, (_, index) => ({
partNumber: index + 1,
offset: index * partSizeBytes,
byteLength: partSizeBytes,
checksumSha256: "a".repeat(64),
receiptToken: "r".repeat(512),
})),
idempotencyKey: "k".repeat(160),
signal: activeSignal,
});
const bodyBytes = new TextEncoder().encode(JSON.stringify(body)).byteLength;
// The adapter really built the body: every receipt is in it.
expect(bodyBytes).toBeGreaterThan(partCount * 600);
expect(() =>
createResumableUploadFetchJsonTransport({
...base,
maxPartCount: partCount,
maxRequestBytes: bodyBytes - 1,
}),
).toThrow(TypeError);
});
});
@@ -0,0 +1,371 @@
import { describe, expect, it } from "vitest";
import type { BrowserDataObservation } from "../../src/application/ports/browser-file-storage/shared.ts";
import {
browserDataFailure,
browserDataSuccess,
} from "../../src/adapters/browser-file-storage/result.ts";
import {
createResumableUploadRuntime,
type ResumableUploadRuntimeDependencies,
} from "../../src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts";
import {
activeSignal,
createControlHarness,
executorFor,
MemoryCheckpointStore,
noContentionLock,
rangeSource,
runtimePolicy,
type ControlHarness,
type TestCapability,
} from "./resumable-upload-runtime-fixture.ts";
/**
* Q-6.1-10. Characterization of the two blocks moved out of the runtime file:
* the dependency snapshot wrappers and the server response validators. The
* other runtime suites reach them only on their happy paths.
*/
function dependencies(
harness: ControlHarness,
overrides: Partial<ResumableUploadRuntimeDependencies<TestCapability>> = {},
): ResumableUploadRuntimeDependencies<TestCapability> {
return {
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints: new MemoryCheckpointStore(),
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy(),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
...overrides,
};
}
async function upload(
input: ResumableUploadRuntimeDependencies<TestCapability>,
) {
return await createResumableUploadRuntime(input).upload({
uploadKey: "upload_key_contract",
purpose: "attachment",
mediaType: "application/octet-stream",
source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
}
describe("resumable upload runtime dependency snapshots", () => {
it("rejects an invalid collaborator at composition", () => {
const harness = createControlHarness();
const invalid: Partial<
ResumableUploadRuntimeDependencies<TestCapability>
>[] = [
{
controlPlane: {
...harness.control,
abort: undefined,
} as unknown as typeof harness.control,
},
{ partExecutor: {} as never },
{
checkpoints: {
read: async () => browserDataSuccess(null),
} as never,
},
{
checkpoints: Object.assign(new MemoryCheckpointStore(), {
removeUnreadable: "not a function",
}) as never,
},
{ mutationLock: {} as never },
{
crossContextCancellation: {
publish: () => true,
subscribe: () => () => {},
} as never,
},
{
crossContextCancellation: {
publish: () => true,
subscribe: () => "not a release",
close: () => {},
} as never,
},
{ observer: {} as never },
{ now: 1_000 as never },
{ random: "0" as never },
{ sleep: 1 as never },
];
for (const override of invalid) {
expect(
() => createResumableUploadRuntime(dependencies(harness, override)),
Object.keys(override).join(","),
).toThrow(TypeError);
}
});
it("captures collaborator methods once at composition", async () => {
const harness = createControlHarness();
const runtime = createResumableUploadRuntime(dependencies(harness));
harness.control.createSession = async () => {
throw new Error("replaced after composition");
};
await expect(
runtime.upload({
uploadKey: "upload_key_contract",
purpose: "attachment",
mediaType: "application/octet-stream",
source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
}),
).resolves.toMatchObject({
ok: true,
value: { state: "QUARANTINED" },
});
});
it("hands the observer frozen copies and survives a throwing one", async () => {
const observations: BrowserDataObservation[] = [];
const harness = createControlHarness();
await expect(
upload(
dependencies(harness, {
observer: {
record(observation) {
observations.push(observation);
throw new Error("observer failure");
},
},
}),
),
).resolves.toMatchObject({ ok: true });
expect(observations.length).toBeGreaterThan(0);
expect(observations.every((value) => Object.isFrozen(value))).toBe(true);
});
it("sleeps between retries with the default timer when none is injected", async () => {
const harness = createControlHarness();
const create = harness.control.createSession.bind(harness.control);
let creates = 0;
harness.control.createSession = async (input) => {
creates += 1;
return creates === 1
? browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", {
retryable: true,
recovery: "RESUME",
})
: await create(input);
};
const { sleep: _injected, ...withoutSleep } = dependencies(harness);
await expect(upload(withoutSleep)).resolves.toMatchObject({
ok: true,
value: { state: "QUARANTINED" },
});
expect(creates).toBe(2);
});
it("ends the default retry sleep when the caller aborts", async () => {
const harness = createControlHarness();
let failed: () => void = () => {};
const firstFailure = new Promise<void>((resolve) => {
failed = resolve;
});
harness.control.createSession = async () => {
failed();
return browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", {
retryable: true,
recovery: "RESUME",
});
};
const { sleep: _injected, ...withoutSleep } = dependencies(harness, {
policy: runtimePolicy({
retryBaseDelayMs: 60_000,
retryMaxDelayMs: 60_000,
}),
});
const controller = new AbortController();
const uploading = createResumableUploadRuntime(withoutSleep).upload({
uploadKey: "upload_key_contract",
purpose: "attachment",
mediaType: "application/octet-stream",
source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: controller.signal,
});
await firstFailure;
controller.abort();
await expect(uploading).resolves.toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
});
it("treats a throwing clock as UNAVAILABLE", async () => {
const harness = createControlHarness();
await expect(
upload(
dependencies(harness, {
now: () => {
throw new Error("clock");
},
}),
),
).resolves.toMatchObject({
ok: false,
error: { code: "UNAVAILABLE", operation: "UPLOAD_SESSION" },
});
});
});
describe("resumable upload runtime server response validation", () => {
it("rejects a created session with an unknown field", async () => {
const harness = createControlHarness();
const create = harness.control.createSession.bind(harness.control);
harness.control.createSession = async (input) => {
const created = await create(input);
return created.ok
? browserDataSuccess({
...created.value,
uploadUrl: "https://objects.invalid/secret",
})
: created;
};
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: false,
error: {
code: "INTEGRITY_FAILED",
operation: "UPLOAD_SESSION",
// 01-05. The create key replays the same answer.
recovery: "NONE",
},
});
});
it("rejects a session concurrency above the local policy", async () => {
const harness = createControlHarness({ serverMaxConcurrency: 4 });
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED", operation: "UPLOAD_SESSION" },
});
});
it("refuses a session whose lifetime exceeds the policy ceiling", async () => {
const harness = createControlHarness();
const create = harness.control.createSession.bind(harness.control);
harness.control.createSession = async (input) => {
const created = await create(input);
return created.ok
? browserDataSuccess({
...created.value,
expiresAtEpochMs: 1_000 + 20_000,
})
: created;
};
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: false,
// 01-05. A restart gets the same session back, so there is no caller
// action; this is a server/policy mismatch.
error: {
code: "POLICY_REJECTED",
operation: "UPLOAD_SESSION",
recovery: "NONE",
},
});
});
it("rejects a part capability with an unknown field", async () => {
const harness = createControlHarness({
issueCapability: (input) =>
browserDataSuccess({
capability: Object.freeze({ id: "cap" }),
uploadBindingSha256: input.uploadBindingSha256,
expiresAtEpochMs: 1_000 + 4_000,
href: "https://objects.invalid/secret",
} as never),
});
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: false,
// 01-05. The caller's action for a capability refusal is upload().
error: {
code: "CORRUPT_DATA",
operation: "UPLOAD_PART",
recovery: "RESUME",
},
});
});
it("rejects a part capability that outlives its session", async () => {
const harness = createControlHarness({
issueCapability: (input) =>
browserDataSuccess({
capability: Object.freeze({ id: "cap" }),
uploadBindingSha256: input.uploadBindingSha256,
expiresAtEpochMs: 1_000 + 5_000 + 1,
}),
});
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: false,
error: {
code: "POLICY_REJECTED",
operation: "UPLOAD_PART",
recovery: "RESUME",
},
});
});
it("rejects a status in a state outside the protocol", async () => {
const harness = createControlHarness();
harness.control.getStatus = async (input) =>
browserDataSuccess({
state: "PAUSED",
protocol: input.protocol,
sessionId: input.sessionId,
requestBindingSha256: input.requestBindingSha256,
} as never);
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: false,
error: {
code: "INTEGRITY_FAILED",
operation: "UPLOAD_RECONCILE",
recovery: "RESTART",
},
});
});
it("rejects server receipts that are out of part order", async () => {
const harness = createControlHarness({
statusParts: (_session, accepted) =>
[...accepted.values()].sort(
(left, right) => right.partNumber - left.partNumber,
),
});
// The first status has no parts; once parts are accepted the reversed
// list is what the final reconcile reads.
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED", operation: "UPLOAD_RECONCILE" },
});
});
it("treats a definitive not-found status as terminal and restarts", async () => {
const harness = createControlHarness({
sessionId: (index) => `session_0${index}`,
});
let statusCalls = 0;
const status = harness.control.getStatus.bind(harness.control);
harness.control.getStatus = async (input) => {
statusCalls += 1;
return statusCalls === 1
? browserDataFailure("NOT_FOUND", "UPLOAD_RECONCILE")
: await status(input);
};
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: true,
value: { state: "QUARANTINED", replayed: false },
});
expect(harness.getSession()?.sessionId).toBe("session_02");
});
});
@@ -209,6 +209,7 @@ export function runtimePolicy(
maxRetryAfterMs: 100,
capabilityRefreshSkewMs: 5,
maxSessionLifetimeMs: 10_000,
maxClockSkewMs: 0,
providerAttemptTimeoutMs: 100,
...overrides,
};
File diff suppressed because it is too large Load Diff
@@ -185,4 +185,57 @@ describe("TR-04 teardown waits for raw provider work, not only its wrapper", ()
await expect(disposing).resolves.toMatchObject({ ok: true });
expect(runtime.lifecycle()).toBe("CLOSED");
});
// R-1.1. The expired drain was cached, so a retry after the work settled
// returned the same failure and the store stayed open forever.
it("closes on a later dispose() once work that outlived the deadline settles", async () => {
const harness = createControlHarness();
const checkpoints = new MemoryCheckpointStore();
let releaseProvider: (() => void) | undefined;
harness.control.createSession = () =>
new Promise((resolve) => {
releaseProvider = () =>
resolve(
browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", {
retryable: true,
recovery: "RESUME",
}),
);
});
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints,
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy({
providerAttemptTimeoutMs: 5,
cleanupDeadlineMs: 25,
maxRetries: 0,
}),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
const uploading = runtime.upload({
uploadKey: "upload_key_retry",
purpose: "attachment",
mediaType: "application/octet-stream",
source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
await vi.waitFor(() => expect(releaseProvider).toBeDefined());
await uploading;
const first = await runtime.dispose();
expect(first.ok).toBe(false);
expect(runtime.lifecycle()).toBe("CLOSING");
releaseProvider?.();
await expect(runtime.dispose()).resolves.toMatchObject({ ok: true });
expect(runtime.lifecycle()).toBe("CLOSED");
expect(checkpoints.closed).toBe(true);
});
});
+183 -13
View File
@@ -5,32 +5,23 @@ import type {
PresignedUploadPartPort,
} from "../../src/application/ports/browser-transfer/presigned-transfer.ts";
import type {
ResumableUploadCheckpoint,
ResumableUploadCheckpointStore,
ResumableUploadControlPlane,
ResumableUploadSource,
UploadPartExecutor,
UploadPartReceipt,
UploadProviderResult,
UploadSession,
} from "../../src/application/ports/browser-transfer/resumable-upload.ts";
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../src/application/ports/browser-transfer/resumable-upload.ts";
import type {
BrowserDataObservation,
BrowserDataResult,
} from "../../src/application/ports/browser-file-storage/shared.ts";
import {
browserDataFailure,
browserDataSuccess,
} from "../../src/adapters/browser-file-storage/result.ts";
import { createIndexedDbResumableUploadCheckpointStore } from "../../src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts";
import { createPresignedUploadPartExecutor } from "../../src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts";
import { createResumableUploadRuntime } from "../../src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts";
import { resolveResumableUploadRuntimePolicy } from "../../src/adapters/browser-transfer/resumable-upload/runtime-policy.ts";
import type {
UploadCancellationChannel,
UploadCancellationListener,
} from "../../src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts";
import type { UploadMutationLock } from "../../src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts";
import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts";
import {
activeSignal,
@@ -113,6 +104,42 @@ describe("production resumable upload runtime", () => {
runtimePolicy({ maxInFlightBytes: 15 }),
),
).toThrow(TypeError);
// R-1.3. partSize 4 × concurrency 4 × copyFactor 4 = 64 > 48 is refused
// up front instead of being silently clamped to fewer workers.
expect(() =>
resolveResumableUploadRuntimePolicy(
runtimePolicy({ maxConcurrency: 4 }),
),
).toThrow(TypeError);
});
// R-1.3. The default memory budget (20 MiB / (5 MiB × 4)) runs one worker,
// but createSession asked the server for 3.
it("requests the concurrency the default policy can actually run", async () => {
const harness = createControlHarness({ serverMaxConcurrency: 1 });
const createSession = vi.spyOn(harness.control, "createSession");
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints: new MemoryCheckpointStore(),
mutationLock: noContentionLock,
crypto,
// Only the capability skew differs from the default, to fit the harness.
policy: { capabilityRefreshSkewMs: 5 },
now: () => 1_000,
sleep: async () => {},
});
const result = await runtime.upload({
uploadKey: "upload_key_default_policy",
purpose: "attachment",
mediaType: "application/octet-stream",
source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
expect(result).toMatchObject({ ok: true });
expect(createSession).toHaveBeenCalledWith(
expect.objectContaining({ requestedMaxConcurrency: 1 }),
);
});
it("uploads bounded range parts, obeys the server concurrency ceiling and completes as quarantined", async () => {
@@ -189,6 +216,61 @@ describe("production resumable upload runtime", () => {
expect(serialized).not.toContain("etag-part");
});
// Q-6.1-5. A sibling worker used to keep retrying its part until its own
// attempt deadline; the first failure now aborts the whole transfer.
it("aborts in-flight sibling workers as soon as one part fails", async () => {
const harness = createControlHarness({ serverMaxConcurrency: 2 });
let secondStarted: () => void = () => {};
const secondRunning = new Promise<void>((resolve) => {
secondStarted = resolve;
});
let siblingAborted = false;
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: {
async uploadPart(input) {
if (input.part.partNumber === 1) {
await secondRunning;
return browserDataFailure("POLICY_REJECTED", "UPLOAD_PART");
}
secondStarted();
return await new Promise((resolve) => {
input.signal.addEventListener(
"abort",
() => {
siblingAborted = true;
resolve(browserDataFailure("ABORTED", "UPLOAD_PART"));
},
{ once: true },
);
});
},
},
checkpoints: new MemoryCheckpointStore(),
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy({ providerAttemptTimeoutMs: 60_000 }),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
const uploading = runtime.upload({
uploadKey: "upload_key_01",
purpose: "attachment",
mediaType: "application/octet-stream",
source: rangeSource(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9])),
signal: activeSignal,
});
await vi.waitFor(() => expect(siblingAborted).toBe(true));
// The caller sees the part that failed, not the sibling's ABORTED.
await expect(uploading).resolves.toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED", operation: "UPLOAD_PART" },
});
});
it("supports replayable FileByteSource without retaining the whole file", async () => {
const checkpoints = new MemoryCheckpointStore();
const harness = createControlHarness();
@@ -215,6 +297,36 @@ describe("production resumable upload runtime", () => {
});
});
// R-1.4. The size check used to throw inside request validation and surface
// as INVALID_INPUT; a file over the policy limit is LIMIT_EXCEEDED.
it("reports a source over maxFileBytes as LIMIT_EXCEEDED", async () => {
const harness = createControlHarness();
const createSession = vi.spyOn(harness.control, "createSession");
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints: new MemoryCheckpointStore(),
mutationLock: noContentionLock,
crypto,
// A valid policy already bounds the part count by maxFileBytes.
policy: runtimePolicy({ maxFileBytes: 4 }),
now: () => 1_000,
sleep: async () => {},
});
const result = await runtime.upload({
uploadKey: "upload_key_too_large",
purpose: "attachment",
mediaType: "application/octet-stream",
source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
expect(result).toMatchObject({
ok: false,
error: { code: "LIMIT_EXCEEDED" },
});
expect(createSession).not.toHaveBeenCalled();
});
it("fails closed when server list-parts disagrees with the current source manifest", async () => {
const checkpoints = new MemoryCheckpointStore();
const harness = createControlHarness({
@@ -248,12 +360,14 @@ describe("production resumable upload runtime", () => {
source: rangeSource(new Uint8Array([1, 2, 3, 4])),
signal: activeSignal,
});
// 01-05. Calling upload() again reads the same server parts, so the way
// out is abort() and a fresh session.
expect(result).toMatchObject({
ok: false,
error: {
code: "INTEGRITY_FAILED",
operation: "UPLOAD_RECONCILE",
recovery: "RECONCILE",
recovery: "RESTART",
},
});
expect(partExecutor.uploadPart).not.toHaveBeenCalled();
@@ -689,6 +803,56 @@ describe("production resumable upload runtime", () => {
);
});
// Q-6.1-6. A row this build cannot read (here a newer schemaVersion left by
// a rolled-back release) used to fail both upload and abort with
// CORRUPT_DATA until the whole partition was deleted.
it("removes an unreadable checkpoint row on abort and reports ORPHANED", async () => {
const memory = new MemoryIndexedDbFactory();
const checkpoints = createIndexedDbResumableUploadCheckpointStore({
scope: {
authorityToken: "authority_token_01",
namespaceToken: "namespace_token_01",
partitionToken: "partition_token_01",
},
factory: memory.factory,
});
// Opens the database so the object stores exist before seeding.
expect(await checkpoints.read("upload_key_unreadable")).toEqual({
ok: true,
value: null,
});
memory.seed("checkpoints", {
schemaVersion: 2,
uploadKey: "upload_key_unreadable",
revision: 7,
state: "PAUSED",
});
const harness = createControlHarness();
const serverAbort = vi.spyOn(harness.control, "abort");
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints,
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy(),
now: () => 1_000,
sleep: async () => {},
});
expect(
await runtime.abort({
uploadKey: "upload_key_unreadable",
signal: activeSignal,
}),
).toEqual({ ok: true, value: { state: "ORPHANED" } });
// No session id can be read from the row, so the server is not called.
expect(serverAbort).not.toHaveBeenCalled();
expect(memory.readRaw("checkpoints", "upload_key_unreadable")).toBe(
undefined,
);
});
it("interrupts a same-runtime active upload before explicit abort waits for the key lock", async () => {
const checkpoints = new MemoryCheckpointStore();
const harness = createControlHarness();
@@ -910,8 +1074,10 @@ describe("production resumable upload runtime", () => {
let forwardedUploadBinding = "";
let forwardedSessionId = "";
let forwardedRequestBinding = "";
let forwardedBytes: Uint8Array | undefined;
const port: PresignedUploadPartPort = {
async put(input) {
forwardedBytes = input.bytes;
forwardedUploadBinding = input.uploadBindingSha256;
forwardedSessionId = input.sessionId;
forwardedRequestBinding = input.requestBindingSha256;
@@ -942,6 +1108,7 @@ describe("production resumable upload runtime", () => {
expectedSha256: "a".repeat(64),
expiresAtEpochMs: 2_000,
} as unknown as PresignedUploadPartCapability;
const partBytes = new Uint8Array([1, 2, 3, 4]);
const result = await executor.uploadPart({
protocol: RESUMABLE_UPLOAD_PROTOCOL,
capability,
@@ -962,7 +1129,7 @@ describe("production resumable upload runtime", () => {
byteLength: 4,
checksumSha256: "a".repeat(64),
},
bytes: new Uint8Array([1, 2, 3, 4]),
bytes: partBytes,
idempotencyKey: "upload-part-idempotency-01",
signal: activeSignal,
});
@@ -970,6 +1137,9 @@ describe("production resumable upload runtime", () => {
ok: true,
value: { receiptToken: "etag.response-01" },
});
// Q-6.1-3b. The presigned port snapshots the bytes itself, so the bridge
// forwards the part buffer instead of adding a second copy per attempt.
expect(forwardedBytes).toBe(partBytes);
expect(forwardedUploadBinding).toBe("b".repeat(64));
expect(forwardedSessionId).toBe("session_01");
expect(forwardedRequestBinding).toBe("c".repeat(64));
+34
View File
@@ -15,11 +15,21 @@ describe("HTTP retry policy", () => {
it("parses retry-after and chooses the longer bounded delay", () => {
expect(parseRetryAfter("2", 0)).toBe(2_000);
expect(parseRetryAfter(" 2 ", 0)).toBe(2_000);
expect(parseRetryAfter("Thu, 01 Jan 1970 00:00:05 GMT", 1_000)).toBe(
4_000,
);
expect(retryDelay({ kind: "RATE_LIMITED", retryAfterMs: 500 }, 0, () => 0)).toBe(
500,
);
});
it("rejects Retry-After values that are not delta-seconds or an HTTP date", () => {
for (const value of ["", " ", "1e3", "1.5", "-1", "0x10", "2024-01-01"]) {
expect(parseRetryAfter(value, 0)).toBeNull();
}
});
it("allows at most two retries for safe or keyed requests", () => {
const failure = { kind: "SERVER_FAILURE" };
expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true);
@@ -35,6 +45,30 @@ describe("HTTP retry policy", () => {
).toBe(false);
});
// R3-1. 408/425 server failures share the 502/503/504 rule and honor
// Retry-After with the same 30s ceiling.
it("retries 408 and 425 server failures only for safe or keyed requests", () => {
for (const httpStatus of [408, 425]) {
const failure = { kind: "SERVER_FAILURE", httpStatus };
expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true);
expect(shouldRetry({ idempotency: "keyed" }, failure, 0)).toBe(true);
expect(shouldRetry({ idempotency: "none" }, failure, 0)).toBe(false);
expect(
shouldRetry({ idempotency: "safe", retry: "never" }, failure, 0),
).toBe(false);
expect(
retryDelay({ ...failure, retryAfterMs: 1_500 }, 0, () => 0),
).toBe(1_500);
expect(
shouldRetry(
{ idempotency: "safe" },
{ ...failure, retryAfterMs: 31_000 },
0,
),
).toBe(false);
}
});
it("does not automatically wait beyond 30 seconds", () => {
expect(
shouldRetry(
+10 -1
View File
@@ -5,6 +5,8 @@ import {
ROUTE_RUNTIME_CONTRACT,
} from "../../src/features/installed-feature-contracts.ts";
import { ROUTE_RUNTIME } from "../../src/features/installed-feature-runtimes.tsx";
import { PLATFORM_ROUTE_REGISTRY } from "../../src/contracts/routes.ts";
import { TECH_LOG_ROUTE_REGISTRY } from "../../src/features/tech-log/contracts/tech-log-route-contract.ts";
import { parseRouteInput } from "../../src/presentation/routes/route-codecs.ts";
describe("typed installed route catalog", () => {
@@ -12,8 +14,15 @@ describe("typed installed route catalog", () => {
expect(Object.keys(ROUTE_RUNTIME_CONTRACT).sort()).toEqual(
Object.keys(ROUTE_REGISTRY).sort(),
);
// Upstream the global runtime table holds only the platform's routes:
// installed features load theirs through their bounded context. TechLog
// is composed directly (src/features/tech-log/NOT_INSTALLED), so its
// runtimes sit beside the platform's.
expect(Object.keys(ROUTE_RUNTIME).sort()).toEqual(
Object.keys(ROUTE_REGISTRY).sort(),
[
...Object.keys(PLATFORM_ROUTE_REGISTRY),
...Object.keys(TECH_LOG_ROUTE_REGISTRY),
].sort(),
);
});
+129
View File
@@ -0,0 +1,129 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { runRunbookDrill } from "../../scripts/drill-runbook.ts";
import { computeContractSetDigest } from "../../src/contracts/contract-set-canonical.ts";
import type { InstalledContractPackageIdentity } from "../../src/contracts/external-contract-runtime.ts";
// 11-01 / 13-03 (D-14). A drill reports PASS only for what it observed on the
// local build. Boot, live traffic, smoke and the provider switch are not
// observable here, so a drill with provider scope ends UNVERIFIED, never PASS.
const contractPackages = [
{
packageId: "@example/accounts",
version: "1.2.3",
digest: `sha256:${"1".repeat(64)}`,
runtimeProtocolVersion: 1,
sourceRevision: "a".repeat(40),
},
] as const satisfies readonly InstalledContractPackageIdentity[];
const RUNBOOK_IDS = ["FE-RB-001", "FE-RB-002", "FE-RB-003", "FE-RB-004", "FE-RB-005"] as const;
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
async function builtDist(options: Readonly<{ withoutJs?: boolean; withoutDist?: boolean }> = {}) {
const root = await mkdtemp(path.join(tmpdir(), "runbook-drill-"));
roots.push(root);
if (options.withoutDist) return root;
const write = async (file: string, content: string) => {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
};
await write("dist/index.html", "<!doctype html><script type=module src=/assets/index-a.js></script>");
await write(
"dist/.vite/manifest.json",
JSON.stringify({
"index.html": { file: "assets/index-a.js", isEntry: true, css: ["assets/index-a.css"], imports: ["_shared-b.js"] },
"_shared-b.js": { file: "assets/shared-b.js" },
"src/pages/lazy.tsx": { file: "assets/lazy-c.js", isDynamicEntry: true },
}),
);
await write("dist/assets/index-a.css", "body{}");
if (!options.withoutJs) {
for (const file of ["assets/index-a.js", "assets/shared-b.js", "assets/lazy-c.js"]) {
await write(`dist/${file}`, "export {};");
}
}
await write(
"dist/release-manifest.json",
JSON.stringify({
schemaVersion: 2,
appVersion: "1.0.0",
buildId: "build-a",
commitSha: "abc1234",
configSchemaVersion: "2.0",
assetManifestHash: "assets-a",
releaseId: "release-a",
builtAt: "2026-08-01T00:00:00.000Z",
routeChunks: {},
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: await computeContractSetDigest(contractPackages),
packages: [...contractPackages],
},
}),
);
await write(
"dist/config.json",
JSON.stringify({
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080/",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 2,
TELEMETRY_ENABLED: false,
AUTH_MODE: "external",
CONFIG_SCHEMA_VERSION: "2.0",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "build-a",
RELEASE_ID: "release-a",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
}),
);
return root;
}
describe("runbook drill verdicts", () => {
it.each(RUNBOOK_IDS)("%s on a complete local build is UNVERIFIED, not PASS", async (runbookId) => {
const record = await runRunbookDrill(runbookId, { releaseRoot: await builtDist(), contractPackages });
expect(record.result).toBe("UNVERIFIED");
expect(record.recoveryAssertions.some(({ result }) => result === "FAIL")).toBe(false);
});
it.each(["FE-RB-002", "FE-RB-005"] as const)(
"%s fails when the build lost its JavaScript assets",
async (runbookId) => {
const record = await runRunbookDrill(runbookId, {
releaseRoot: await builtDist({ withoutJs: true }),
contractPackages,
});
expect(record.result).toBe("FAIL");
},
);
it("FE-RB-005 fails without a build instead of reading public/ placeholders", async () => {
await expect(
runRunbookDrill("FE-RB-005", { releaseRoot: await builtDist({ withoutDist: true }), contractPackages }),
).rejects.toThrow(/dist\/release-manifest\.json/u);
});
it("keeps no constant recovery verdict in the drill source", async () => {
const source = await readFile("scripts/drill-runbook.ts", "utf8");
expect(source).not.toMatch(/assertion\([^;]*,\s*true\s*\)/u);
expect(source).not.toMatch(/Asserted:\s*true\b/u);
expect(source).not.toMatch(/injectedMountFailure\s*=\s*true/u);
});
});
+131
View File
@@ -5,6 +5,9 @@ import {
createRuntimeHttpClient,
} from "../../src/bootstrap/runtime-adapters.ts";
import { createBrowserMutationIntentFactory } from "../../src/adapters/platform/browser-mutation-intent-factory.ts";
import { createApplication } from "../../src/application/create-application.ts";
import type { ApplicationFeatureId } from "../../src/application/ports/in/application-api.ts";
import { INSTALLED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts";
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
@@ -173,6 +176,44 @@ describe("runtime adapter composition", () => {
expect(fetcher).not.toHaveBeenCalled();
});
it("sends telemetry stamped with the release identity (13-11)", async () => {
const bodies: { events: Record<string, unknown>[] }[] = [];
const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
if (String(_url) === "https://telemetry.test/events") {
bodies.push(JSON.parse(String(init?.body)));
}
return new Response(null, { status: 204 });
});
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
TELEMETRY_ENABLED: true,
TELEMETRY_ENDPOINT: "https://telemetry.test/events",
},
} as Runtime,
release,
host: {},
fetcher: fetcher as unknown as typeof fetch,
});
adapters.outputPorts.telemetry.emit("api.request.failed", {
error_kind: "SERVER_FAILURE",
http_status_group: "5xx",
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
});
await adapters.outputPorts.telemetry.flush();
expect(bodies[0]?.events[0]).toMatchObject({
eventName: "api.request.failed",
build_id: "build-a",
release_id: "release-a",
});
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;
@@ -241,6 +282,51 @@ describe("runtime adapter composition", () => {
expect(adapters.outputPorts.session.getState()).toBe("integration-failed");
});
describe("installed external auth owner shape", () => {
const externalRuntime: Runtime = {
...runtime,
config: { ...runtime.config, AUTH_MODE: "external" },
};
const completeOwner = () => ({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
});
it("uses an owner that implements every method", async () => {
const adapters = await createRuntimeAdapters({
runtime: externalRuntime,
release,
host: { __CA_FRONTEND_AUTH_OWNER__: completeOwner() },
});
expect(adapters.outputPorts.session.getState()).toBe("authenticated");
expect(adapters.outputPorts.session.getSubject()).toBe("user-a");
adapters.infrastructure.dispose();
});
it.each(["readSubject", "readState"])(
"fails closed when the owner lacks %s",
async (method) => {
const owner: Record<string, unknown> = completeOwner();
delete owner[method];
const adapters = await createRuntimeAdapters({
runtime: externalRuntime,
release,
host: { __CA_FRONTEND_AUTH_OWNER__: owner },
});
expect(adapters.outputPorts.session.getState()).toBe(
"integration-failed",
);
adapters.infrastructure.dispose();
},
);
});
it("reports the static selection when no capability override disables it", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
@@ -280,6 +366,51 @@ describe("runtime adapter composition", () => {
expect(serviceWorker?.active).toBe(0);
});
it("gives a feature switched off by FEATURE_OVERRIDES no application API (Q-6.9-5)", async () => {
const [disabledId, ...activeIds] = INSTALLED_PRODUCT_FEATURE_IDS;
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
FEATURE_OVERRIDES: { [disabledId!]: "DISABLED" },
},
},
release,
host: {},
});
const application = createApplication(
adapters.outputPorts,
adapters.featureInputs,
);
expect(adapters.outputPorts.productFeatures.isActive(disabledId!)).toBe(false);
expect(application.features.has(disabledId!)).toBe(false);
expect(() =>
application.features.get(disabledId as ApplicationFeatureId),
).toThrow(/not installed/u);
for (const featureId of activeIds) {
expect(application.features.has(featureId)).toBe(true);
}
adapters.infrastructure.dispose();
});
it("still resolves every installed feature API when nothing is switched off", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const application = createApplication(
adapters.outputPorts,
adapters.featureInputs,
);
for (const featureId of INSTALLED_PRODUCT_FEATURE_IDS) {
expect(application.features.has(featureId)).toBe(true);
expect(
application.features.get(featureId as ApplicationFeatureId),
).toBeDefined();
}
adapters.infrastructure.dispose();
});
it("states contract identity as a digest for a V2 release manifest", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });

Some files were not shown because too many files have changed in this diff Show More