import { describe, expect, mock, test } from "bun:test"; import { Database } from "bun:sqlite"; import { applyCombinedSchema } from "../test-schema.test-helper"; mock.module("cloudflare:workers", () => ({ env: { PUBLIC_URL: "https://forge.example.com" }, waitUntil: () => undefined, DurableObject: class {}, WorkflowEntrypoint: class {}, })); const db = new Database(":memory:"); applyCombinedSchema(db); mock.module("../db", () => ({ first: async (sql: string, ...params: unknown[]) => db.query(sql).get(...(params as never[])) ?? null, all: async (sql: string, ...params: unknown[]) => db.query(sql).all(...(params as never[])), run: async (sql: string, ...params: unknown[]) => ({ meta: { changes: db.query(sql).run(...(params as never[])).changes }, }), batch: async () => [], stmt: (sql: string, ...params: unknown[]) => ({ sql, params }), placeholders: (count: number) => Array(count).fill("?").join(", "), chunks: (items: T[]) => [items], MAX_IN_LIST: 90, })); const { memoryScopes } = await import("../scoped-db/testing"); const scopes = memoryScopes(); mock.module("../scoped-db", () => scopes.module); const { deliverOnce } = await import("./deliver"); const { emailDeliveryId } = await import("../events/consumer"); describe("deliverOnce (notification email retry dedupe)", () => { test("a retried queue message does not resend an email that already went out", async () => { let sent = 0; const send = async () => void sent++; const id = emailDeliveryId("msg-1"); expect(await deliverOnce(id, "u1", send)).toBe(true); expect(await deliverOnce(id, "u1", send)).toBe(false); expect(await deliverOnce(id, "u2", send)).toBe(true); expect(sent).toBe(2); }); test("a failed send releases the marker so the retry delivers it", async () => { const id = emailDeliveryId("msg-2"); await expect( deliverOnce(id, "u1", async () => { throw new Error("queue down"); }), ).rejects.toThrow("queue down"); let sent = 0; expect(await deliverOnce(id, "u1", async () => void sent++)).toBe(true); expect(sent).toBe(1); }); test("fan-out email markers never collide with a direct notification's message id", () => { expect(emailDeliveryId("abc")).not.toBe("abc"); }); });