import { describe, expect, it } from "vitest"; import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store"; import { createSharedStoreIdempotencyStorageClient } from "./shared-store-client.js"; import { createIdempotencyStore } from "./store.js"; function makeClient(now?: () => number) { const store = createSharedStore({ namespace: "api", adapter: new MemoryAdapter() }); return { client: createSharedStoreIdempotencyStorageClient({ store, now }), store }; } const SCOPE = "api:tenant:t1"; /** * `IdempotencyStorageClient.findUnique` is typed via an intersection of * the base Prisma contract and an extended delegate; TS resolves the * call to the base overload, which omits `createdAt`. The SharedStore * client always populates `createdAt`, so narrow the result here to read * it in the assertions below. */ type WithCreatedAt = { createdAt?: Date | null; expiresAt?: Date | null }; describe("createSharedStoreIdempotencyStorageClient — Prisma-shaped contract", () => { it("round-trips a created entry through findUnique with Date fields", async () => { const { client } = makeClient(() => 1_000); await client.idempotencyKey.create({ data: { scope: SCOPE, key: "k1", requestHash: "hash-1", responseStatus: 201, responseBody: { ok: true }, responseHeaders: { "x-test": "1" }, expiresAt: new Date(1_000 + 60_000), }, }); const found = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "k1" } }, }); expect(found).not.toBeNull(); expect(found?.requestHash).toBe("hash-1"); expect(found?.responseStatus).toBe(201); expect(found?.responseBody).toEqual({ ok: true }); expect(found?.responseHeaders).toEqual({ "x-test": "1" }); const withDates = found as WithCreatedAt | null; expect(withDates?.createdAt).toBeInstanceOf(Date); expect(withDates?.expiresAt?.getTime()).toBe(61_000); }); it("returns null for an unknown key", async () => { const { client } = makeClient(); const found = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "missing" } }, }); expect(found).toBeNull(); }); it("throws a Prisma-style P2002 when the same scope+key is claimed twice", async () => { const { client } = makeClient(); const data = { scope: SCOPE, key: "dup", requestHash: "h", responseStatus: 0, responseBody: null, responseHeaders: null, expiresAt: new Date(Date.now() + 60_000), }; await client.idempotencyKey.create({ data }); await expect(client.idempotencyKey.create({ data })).rejects.toMatchObject({ code: "P2002" }); }); it("update overwrites the response and preserves createdAt", async () => { const { client } = makeClient(() => 5_000); await client.idempotencyKey.create({ data: { scope: SCOPE, key: "k2", requestHash: "h", responseStatus: 0, responseBody: null, responseHeaders: null, expiresAt: new Date(5_000 + 60_000), }, }); const before = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "k2" } }, }); await client.idempotencyKey.update({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "k2" } }, data: { responseStatus: 200, responseBody: { done: true }, responseHeaders: { h: "v" } }, }); const after = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "k2" } }, }); expect(after?.responseStatus).toBe(200); expect(after?.responseBody).toEqual({ done: true }); expect((after as WithCreatedAt | null)?.createdAt?.getTime()).toBe( (before as WithCreatedAt | null)?.createdAt?.getTime(), ); }); it("update throws when the reservation does not exist", async () => { const { client } = makeClient(); await expect( client.idempotencyKey.update({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "ghost" } }, data: { responseStatus: 200 }, }), ).rejects.toThrow(/not found/i); }); it("deleteMany with scope+key removes exactly that entry", async () => { const { client } = makeClient(); const base = { scope: SCOPE, requestHash: "h", responseStatus: 200, responseBody: null, responseHeaders: null, expiresAt: new Date(Date.now() + 60_000), }; await client.idempotencyKey.create({ data: { ...base, key: "a" } }); await client.idempotencyKey.create({ data: { ...base, key: "b" } }); await client.idempotencyKey.deleteMany?.({ where: { scope: SCOPE, key: "a" } }); expect( await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "a" } } }), ).toBeNull(); expect( await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "b" } } }), ).not.toBeNull(); }); it("deleteMany with expiresAt.lte only removes entries already past their expiry", async () => { const { client } = makeClient(() => 10_000); await client.idempotencyKey.create({ data: { scope: SCOPE, key: "fresh", requestHash: "h", responseStatus: 200, responseBody: null, responseHeaders: null, expiresAt: new Date(10_000 + 60_000), }, }); // Cut-off earlier than the entry's expiry → entry is kept. await client.idempotencyKey.deleteMany?.({ where: { scope: SCOPE, key: "fresh", expiresAt: { lte: new Date(20_000) } }, }); expect( await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope: SCOPE, key: "fresh" } } }), ).not.toBeNull(); }); it("deleteMany scoped to one scope leaves other scopes intact", async () => { const { client } = makeClient(); const base = { requestHash: "h", responseStatus: 200, responseBody: null, responseHeaders: null, expiresAt: new Date(Date.now() + 60_000), }; await client.idempotencyKey.create({ data: { ...base, scope: "api:system", key: "x" } }); await client.idempotencyKey.create({ data: { ...base, scope: "api:tenant:other", key: "y" } }); await client.idempotencyKey.deleteMany?.({ where: { scope: "api:system" } }); expect(await client.idempotencyKey.count?.({ where: { scope: "api:system" } })).toBe(0); expect(await client.idempotencyKey.count?.({ where: { scope: "api:tenant:other" } })).toBe(1); }); it("count tallies only entries in the requested scope", async () => { const { client } = makeClient(); const base = { requestHash: "h", responseStatus: 200, responseBody: null, responseHeaders: null, expiresAt: new Date(Date.now() + 60_000), }; await client.idempotencyKey.create({ data: { ...base, scope: SCOPE, key: "1" } }); await client.idempotencyKey.create({ data: { ...base, scope: SCOPE, key: "2" } }); await client.idempotencyKey.create({ data: { ...base, scope: "api:system", key: "3" } }); expect(await client.idempotencyKey.count?.({ where: { scope: SCOPE } })).toBe(2); }); }); describe("createSharedStoreIdempotencyStorageClient — driven through createIdempotencyStore", () => { it("stores then replays a successful operation", async () => { const { client } = makeClient(); const idempotency = createIdempotencyStore({ client, scope: SCOPE }); const response = { status: 200, headers: {}, body: { value: 1 } }; const first = await idempotency.run("key-A", "fp-A", async () => response); const second = await idempotency.run("key-A", "fp-A", async () => ({ status: 500, headers: {}, body: { value: 999 }, })); expect(first.type).toBe("stored"); expect(second.type).toBe("replay"); if (second.type === "replay") { expect(second.response.body).toEqual({ value: 1 }); } }); it("reports a conflict when the same key arrives with a different fingerprint", async () => { const { client } = makeClient(); const idempotency = createIdempotencyStore({ client, scope: SCOPE }); await idempotency.run("key-B", "fp-1", async () => ({ status: 200, headers: {}, body: null })); const conflict = await idempotency.run("key-B", "fp-2", async () => ({ status: 200, headers: {}, body: null })); expect(conflict.type).toBe("conflict"); }); it("fans an invalidation out across two replicas sharing one adapter", async () => { // Two SharedStore facades over one MemoryAdapter == two API replicas // pointed at the same Redis. A claim on replica A must be visible to B. const adapter = new MemoryAdapter(); const replicaA = createSharedStoreIdempotencyStorageClient({ store: createSharedStore({ namespace: "api", adapter }), }); const replicaB = createSharedStoreIdempotencyStorageClient({ store: createSharedStore({ namespace: "api", adapter }), }); const storeA = createIdempotencyStore({ client: replicaA, scope: SCOPE }); const storeB = createIdempotencyStore({ client: replicaB, scope: SCOPE }); const stored = await storeA.run("shared-key", "fp", async () => ({ status: 201, headers: {}, body: { replica: "A" }, })); const replayed = await storeB.run("shared-key", "fp", async () => ({ status: 500, headers: {}, body: { replica: "B" }, })); expect(stored.type).toBe("stored"); expect(replayed.type).toBe("replay"); if (replayed.type === "replay") { expect(replayed.response.body).toEqual({ replica: "A" }); } }); });