129 lines
4.5 KiB
TypeScript
129 lines
4.5 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
|
import { TEST_CREATE_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
|
|
import {
|
|
jsonRows,
|
|
scopeSnapshot,
|
|
testExecutionContext,
|
|
testExecutor,
|
|
type Transport,
|
|
} from "../../helpers/traffic-test-kit.ts";
|
|
import { TEST_QUERY } from "../traffic/synthetic-traffic.ts";
|
|
|
|
const TEST_COMMAND = TEST_CREATE_HTTP_CONTRACT as InstalledHttpContract<
|
|
unknown,
|
|
unknown,
|
|
unknown
|
|
>;
|
|
|
|
/**
|
|
* Spec §42 (network flap). The network alternates online/offline. An
|
|
* offline attempt that reached `fetch` is a dispatched attempt whose effect is
|
|
* unknown; the executor must never replay a keyed command automatically.
|
|
*/
|
|
function flappingNetwork() {
|
|
let online = true;
|
|
const commandDispatches = new Map<string, number>();
|
|
const inFlight = new Set<AbortSignal>();
|
|
const transport: Transport = (_input, init) => {
|
|
const key = new Headers(init?.headers).get("idempotency-key");
|
|
if (key) commandDispatches.set(key, (commandDispatches.get(key) ?? 0) + 1);
|
|
if (!online) return Promise.reject(new TypeError("offline"));
|
|
if (key) {
|
|
return Promise.resolve(
|
|
Response.json({ id: key, name: "created" }, { status: 201 }),
|
|
);
|
|
}
|
|
return Promise.resolve(jsonRows(1));
|
|
};
|
|
return {
|
|
transport,
|
|
commandDispatches,
|
|
inFlight,
|
|
setOnline(value: boolean) {
|
|
online = value;
|
|
},
|
|
};
|
|
}
|
|
|
|
function intent(index: number) {
|
|
return Object.freeze({
|
|
intentId: `intent-${index}`,
|
|
operationId: "TEST_CREATE_ENTITY",
|
|
canonicalInputIdentity: `input-${index}`,
|
|
idempotencyKey: `key-${index.toString().padStart(6, "0")}`,
|
|
createdAtMonotonicMs: index,
|
|
});
|
|
}
|
|
|
|
describe("network flap", () => {
|
|
it("never replays an unsafe mutation and keeps queues bounded across flaps", async () => {
|
|
const network = flappingNetwork();
|
|
const executor = testExecutor(network.transport, { maxRetryAttempts: 2 });
|
|
let peakQueued = 0;
|
|
|
|
for (let cycle = 0; cycle < 400; cycle += 1) {
|
|
network.setOnline(cycle % 2 === 0);
|
|
const execution = testExecutionContext({
|
|
maxPhysicalRequests: 4,
|
|
maxRetries: 2,
|
|
maxConcurrentRequests: 1,
|
|
maxQueuedRequests: 2,
|
|
});
|
|
const context = { routeId: "TEST_ROUTE", scope: scopeSnapshot(), execution };
|
|
const work = Promise.all([
|
|
executor.execute(TEST_COMMAND, { name: `n${cycle}` }, { ...context, intent: intent(cycle) }),
|
|
executor.execute(TEST_QUERY, { limit: 1 }, context),
|
|
executor.execute(TEST_QUERY, { limit: 1 }, context),
|
|
]);
|
|
peakQueued = Math.max(peakQueued, execution.traffic.concurrency.queued);
|
|
await work;
|
|
expect(execution.traffic.concurrency.active).toBe(0);
|
|
expect(execution.traffic.concurrency.queued).toBe(0);
|
|
}
|
|
|
|
expect(Math.max(...network.commandDispatches.values())).toBe(1);
|
|
expect(network.commandDispatches.size).toBe(400);
|
|
expect(peakQueued).toBeLessThanOrEqual(2);
|
|
});
|
|
|
|
it("completes cancellation of stale interactions when the network drops", async () => {
|
|
const pendingSignals: AbortSignal[] = [];
|
|
const transport: Transport = (_input, init) =>
|
|
new Promise<Response>((_resolve, reject) => {
|
|
if (init?.signal) pendingSignals.push(init.signal);
|
|
init?.signal?.addEventListener(
|
|
"abort",
|
|
() => reject(new DOMException("aborted", "AbortError")),
|
|
{ once: true },
|
|
);
|
|
});
|
|
const executor = testExecutor(transport);
|
|
const interactions = Array.from({ length: 50 }, () =>
|
|
testExecutionContext({ maxConcurrentRequests: 1, maxQueuedRequests: 2 }),
|
|
);
|
|
const running = interactions.flatMap((execution) =>
|
|
[0, 1, 2].map(() =>
|
|
executor.execute(TEST_QUERY, { limit: 1 }, {
|
|
routeId: "TEST_ROUTE",
|
|
scope: scopeSnapshot(),
|
|
execution,
|
|
}),
|
|
),
|
|
);
|
|
await vi.waitFor(() => expect(pendingSignals).toHaveLength(50));
|
|
|
|
// "offline" event: the session cancels every interaction started online.
|
|
for (const execution of interactions) execution.cancellation.cancel();
|
|
const outcomes = await Promise.all(running);
|
|
|
|
expect(outcomes.every((outcome) => outcome.kind === "CANCELLED")).toBe(true);
|
|
expect(pendingSignals.every((signal) => signal.aborted)).toBe(true);
|
|
for (const execution of interactions) {
|
|
expect(execution.traffic.concurrency.active).toBe(0);
|
|
expect(execution.traffic.concurrency.queued).toBe(0);
|
|
}
|
|
});
|
|
});
|