import { describe, expect, it, vi } from "vitest"; import { createContractHttpExecutor } from "../../src/adapters/http/http-execution-v3.ts"; import { joinMutationEffectCertainty } from "../../src/adapters/http/http-effect-certainty.ts"; import { TEST_CREATE_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; describe("mutation effect certainty lattice", () => { it.each([ ["NOT_STARTED", "NOT_APPLIED", "NOT_APPLIED"], ["NOT_APPLIED", "NOT_STARTED", "NOT_APPLIED"], ["NOT_STARTED", "MAYBE_APPLIED", "MAYBE_APPLIED"], ["MAYBE_APPLIED", "NOT_STARTED", "MAYBE_APPLIED"], ["MAYBE_APPLIED", "NOT_APPLIED", "MAYBE_APPLIED"], ["NOT_APPLIED", "MAYBE_APPLIED", "MAYBE_APPLIED"], ["MAYBE_APPLIED", "APPLIED_CONFIRMED", "APPLIED_CONFIRMED"], ["APPLIED_CONFIRMED", "NOT_STARTED", "APPLIED_CONFIRMED"], ["APPLIED_CONFIRMED", "MAYBE_APPLIED", "APPLIED_CONFIRMED"], ] as const)("joins %s with %s as %s", (current, observed, expected) => { expect(joinMutationEffectCertainty(current, observed)).toBe(expected); }); }); describe("HTTP operation execution contract", () => { it("permits a keyless command intent but rejects an unexpected key before dispatch", async () => { const attachCredentials = vi.fn(() => ({ kind: "READY" as const, headers: {}, })); const observedKeys: Array = []; const fetcher = vi.fn( async (_input: RequestInfo | URL, init?: RequestInit) => { observedKeys.push(new Headers(init?.headers).get("Idempotency-Key")); return Response.json( { id: "created", name: "Created" }, { status: 201 }, ); }, ); const executor = createContractHttpExecutor({ baseUrl: "https://api.example/", maxRetryAttempts: 0, attachCredentials, fetcher, }); const nonKeyedCommand = { ...TEST_CREATE_HTTP_CONTRACT, contract: { ...TEST_CREATE_HTTP_CONTRACT.contract, retrySemantics: "NEVER" as const, commandRecovery: null, }, }; const scope = Object.freeze({ generation: 1, fingerprint: "scope-1", identities: Object.freeze({}) as never, signal: new AbortController().signal, isCurrent: () => true, }); const intent = Object.freeze({ intentId: "intent-1", operationId: "TEST_CREATE_ENTITY", canonicalInputIdentity: "opaque-input-identity", createdAtMonotonicMs: 1, }); await expect( executor.execute( nonKeyedCommand, { name: "created" }, { routeId: "TEST_ROUTE", scope, intent }, ), ).resolves.toMatchObject({ kind: "SUCCESS" }); expect(observedKeys).toEqual([null]); attachCredentials.mockClear(); fetcher.mockClear(); await expect( executor.execute( nonKeyedCommand, { name: "created" }, { routeId: "TEST_ROUTE", scope, intent: { ...intent, idempotencyKey: "unexpected-key" } }, ), ).resolves.toMatchObject({ kind: "CONTRACT_VIOLATION", violation: { kind: "UNEXPECTED_IDEMPOTENCY_KEY", operation: "REQUEST", }, effect: "NOT_STARTED", }); expect(attachCredentials).not.toHaveBeenCalled(); expect(fetcher).not.toHaveBeenCalled(); }); });