193 lines
8.8 KiB
TypeScript
193 lines
8.8 KiB
TypeScript
import { describe, expect, test, vi } from "vitest";
|
|
|
|
import { withIdempotency, type IdempotencyClient } from "./idempotency.js";
|
|
|
|
type StoredRow = {
|
|
requestHash: string;
|
|
responseStatus: number;
|
|
responseBody: Parameters<typeof JSON.stringify>[0] | null;
|
|
responseHeaders: Record<string, string> | null;
|
|
};
|
|
|
|
/** In-memory idempotency client backed by a Map, mirroring the Prisma contract. */
|
|
function memoryClient() {
|
|
const rows = new Map<string, StoredRow>();
|
|
const keyOf = (partitionKey: string, scope: string, key: string) => `${partitionKey}:${scope}:${key}`;
|
|
const client: IdempotencyClient = {
|
|
idempotencyKey: {
|
|
findUnique: vi.fn(async ({ where }) => {
|
|
const key = where.idempotency_key_partition_scope_key;
|
|
return rows.get(keyOf(key.partitionKey, key.scope, key.key)) ?? null;
|
|
}),
|
|
create: vi.fn(async ({ data }) => {
|
|
const k = keyOf(data.partitionKey, data.scope, data.key);
|
|
if (rows.has(k)) throw Object.assign(new Error("unique"), { code: "P2002" });
|
|
rows.set(k, { requestHash: data.requestHash, responseStatus: data.responseStatus, responseBody: data.responseBody ?? null, responseHeaders: data.responseHeaders ?? null });
|
|
}),
|
|
update: vi.fn(async ({ where, data }) => {
|
|
const key = where.idempotency_key_partition_scope_key;
|
|
const k = keyOf(key.partitionKey, key.scope, key.key);
|
|
const existing = rows.get(k);
|
|
if (!existing) throw new Error("missing reservation");
|
|
rows.set(k, { ...existing, responseStatus: data.responseStatus, responseBody: data.responseBody ?? null, responseHeaders: data.responseHeaders ?? null });
|
|
}),
|
|
deleteMany: vi.fn(async ({ where } = {}) => {
|
|
if (where?.partitionKey && where.scope && where.key) rows.delete(keyOf(where.partitionKey, where.scope, where.key));
|
|
}),
|
|
},
|
|
};
|
|
return { client, rows };
|
|
}
|
|
|
|
const tenantOwnership = { tenantId: "tenant_1" } as const;
|
|
|
|
describe("withIdempotency key handling", () => {
|
|
test("runs the operation directly when no idempotency key is supplied", async () => {
|
|
const { client } = memoryClient();
|
|
const operation = vi.fn(async () => ({ status: 200, body: { ok: true } }));
|
|
|
|
await expect(withIdempotency({ ...tenantOwnership, key: undefined, fingerprint: { a: 1 } }, client, operation)).resolves.toEqual({ status: 200, body: { ok: true }, replayed: false });
|
|
expect(operation).toHaveBeenCalledTimes(1);
|
|
expect(client.idempotencyKey.findUnique).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("treats a whitespace-only key as no key", async () => {
|
|
const { client } = memoryClient();
|
|
const operation = vi.fn(async () => ({ status: 201 }));
|
|
|
|
await expect(withIdempotency({ ...tenantOwnership, key: " ", fingerprint: 1 }, client, operation)).resolves.toMatchObject({ status: 201, replayed: false });
|
|
expect(client.idempotencyKey.create).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe("withIdempotency fingerprinting", () => {
|
|
test("replays when a reordered object fingerprint stringifies identically", async () => {
|
|
const { client } = memoryClient();
|
|
const operation = vi.fn(async () => ({ status: 201, body: { ok: true } }));
|
|
|
|
await withIdempotency({ ...tenantOwnership, key: "k1", fingerprint: { a: 1, b: [2, 3] } }, client, operation);
|
|
const replay = await withIdempotency({ ...tenantOwnership, key: "k1", fingerprint: { b: [2, 3], a: 1 } }, client, operation);
|
|
|
|
expect(replay).toMatchObject({ replayed: true, status: 201, body: { ok: true } });
|
|
expect(operation).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
test("replays stored response headers as well as the body", async () => {
|
|
const { client } = memoryClient();
|
|
await withIdempotency({ ...tenantOwnership, key: "kh", fingerprint: "a" }, client, async () => ({ status: 200, body: { ok: true }, headers: { "x-trace": "abc" } }));
|
|
const replay = await withIdempotency({ ...tenantOwnership, key: "kh", fingerprint: "a" }, client, async () => ({ status: 500 }));
|
|
|
|
expect(replay).toEqual({ status: 200, body: { ok: true }, headers: { "x-trace": "abc" }, replayed: true });
|
|
});
|
|
|
|
test("replays a stored no-content response without a body", async () => {
|
|
const { client } = memoryClient();
|
|
await withIdempotency({ ...tenantOwnership, key: "kn", fingerprint: "a" }, client, async () => ({ status: 204 }));
|
|
const replay = await withIdempotency({ ...tenantOwnership, key: "kn", fingerprint: "a" }, client, async () => ({ status: 500 }));
|
|
|
|
expect(replay).toEqual({ status: 204, body: undefined, headers: undefined, replayed: true });
|
|
});
|
|
|
|
test("rejects a replay whose fingerprint changed", async () => {
|
|
const { client } = memoryClient();
|
|
await withIdempotency({ ...tenantOwnership, key: "k2", fingerprint: "a" }, client, async () => ({ status: 200 }));
|
|
|
|
await expect(withIdempotency({ ...tenantOwnership, key: "k2", fingerprint: "b" }, client, async () => ({ status: 200 }))).rejects.toMatchObject({ code: "foundation.idempotency_conflict" });
|
|
});
|
|
});
|
|
|
|
describe("withIdempotency reservation states", () => {
|
|
test("surfaces an in-progress error when a matching reservation has no response yet", async () => {
|
|
const { rows, client } = memoryClient();
|
|
rows.set("tenant:tenant_1:default:k3", { requestHash: JSON.stringify("a"), responseStatus: 0, responseBody: null, responseHeaders: null });
|
|
const operation = vi.fn(async () => ({ status: 200 }));
|
|
|
|
await expect(withIdempotency({ ...tenantOwnership, key: "k3", fingerprint: "a" }, client, operation)).rejects.toMatchObject({ code: "foundation.idempotency_in_progress" });
|
|
expect(operation).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("replays the row reserved by a racing writer on a unique-constraint collision", async () => {
|
|
let findCalls = 0;
|
|
const reserved = { requestHash: JSON.stringify("a"), responseStatus: 201, responseBody: { ok: true }, responseHeaders: null };
|
|
const client: IdempotencyClient = {
|
|
idempotencyKey: {
|
|
findUnique: vi.fn(async () => (findCalls++ === 0 ? null : reserved)),
|
|
create: vi.fn(async () => {
|
|
throw Object.assign(new Error("unique"), { code: "P2002" });
|
|
}),
|
|
update: vi.fn(),
|
|
deleteMany: vi.fn(),
|
|
},
|
|
};
|
|
const operation = vi.fn(async () => ({ status: 500 }));
|
|
|
|
await expect(withIdempotency({ ...tenantOwnership, key: "race", fingerprint: "a" }, client, operation)).resolves.toMatchObject({ replayed: true, status: 201, body: { ok: true } });
|
|
expect(operation).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("rethrows a P2002 collision when no reservation can be re-read", async () => {
|
|
const p2002 = Object.assign(new Error("unique"), { code: "P2002" });
|
|
const client: IdempotencyClient = {
|
|
idempotencyKey: {
|
|
findUnique: vi.fn(async () => null),
|
|
create: vi.fn(async () => {
|
|
throw p2002;
|
|
}),
|
|
update: vi.fn(),
|
|
deleteMany: vi.fn(),
|
|
},
|
|
};
|
|
|
|
await expect(withIdempotency({ ...tenantOwnership, key: "race2", fingerprint: "a" }, client, async () => ({ status: 200 }))).rejects.toBe(p2002);
|
|
});
|
|
|
|
test("rethrows non-unique-constraint create failures untouched", async () => {
|
|
const client: IdempotencyClient = {
|
|
idempotencyKey: {
|
|
findUnique: vi.fn(async () => null),
|
|
create: vi.fn(async () => {
|
|
throw new Error("db unavailable");
|
|
}),
|
|
update: vi.fn(),
|
|
deleteMany: vi.fn(),
|
|
},
|
|
};
|
|
|
|
await expect(withIdempotency({ ...tenantOwnership, key: "boom", fingerprint: "a" }, client, async () => ({ status: 200 }))).rejects.toThrow("db unavailable");
|
|
});
|
|
});
|
|
|
|
describe("withIdempotency operation failures", () => {
|
|
test("releases the reservation and rethrows when the operation throws", async () => {
|
|
const { client } = memoryClient();
|
|
const error = new Error("operation failed");
|
|
|
|
await expect(
|
|
withIdempotency({ ...tenantOwnership, key: "k4", fingerprint: "a" }, client, async () => {
|
|
throw error;
|
|
}),
|
|
).rejects.toBe(error);
|
|
expect(client.idempotencyKey.deleteMany).toHaveBeenCalledWith({ where: { partitionKey: "tenant:tenant_1", scope: "default", key: "k4" } });
|
|
|
|
// After rollback the same key can be reserved again (no lingering reservation).
|
|
await expect(withIdempotency({ ...tenantOwnership, key: "k4", fingerprint: "a" }, client, async () => ({ status: 200 }))).resolves.toMatchObject({ status: 200, replayed: false });
|
|
});
|
|
|
|
test("rethrows even when the client cannot delete the reservation", async () => {
|
|
const client: IdempotencyClient = {
|
|
idempotencyKey: {
|
|
findUnique: vi.fn(async () => null),
|
|
create: vi.fn(async () => undefined),
|
|
update: vi.fn(),
|
|
// deleteMany intentionally omitted to exercise the optional-call path.
|
|
},
|
|
};
|
|
|
|
await expect(
|
|
withIdempotency({ ...tenantOwnership, key: "k5", fingerprint: "a" }, client, async () => {
|
|
throw new Error("late failure");
|
|
}),
|
|
).rejects.toThrow("late failure");
|
|
});
|
|
});
|