| 1 | import { describe, expect, it } from "vitest"; |
| 2 | import { MAX_QUEUED_BODY, enqueueMail, mailBatches } from "../../src/mail/send.js"; |
| 3 | import type { MailJob } from "../../src/mail/types.js"; |
| 4 | import type { Env } from "../../src/env.js"; |
| 5 | |
| 6 | const thread = (i: number, body: string): MailJob => |
| 7 | ({ kind: "thread", data: { repo: "acme/app", repoId: "r", number: 1, kind: "issue", title: "t", event: "comment", actor: "ada", url: "u", body }, to: { accountId: `u${i}` }, reason: "subscribed", at: "2026-10-14T00:00:00Z" }) as MailJob; |
| 8 | |
| 9 | describe("queueing email in batches the queue accepts", () => { |
| 10 | it("cuts batches by size, under the 256 KB sendBatch limit", () => { |
| 11 | const jobs = Array.from({ length: 200 }, (_, i) => thread(i, "x".repeat(20_000))); |
| 12 | const batches = mailBatches(jobs); |
| 13 | expect(batches.flat()).toHaveLength(200); |
| 14 | for (const b of batches) expect(new TextEncoder().encode(JSON.stringify(b.map((body) => ({ body })))).length).toBeLessThan(256_000); |
| 15 | // Small jobs still go 50 at a time. |
| 16 | expect(mailBatches(Array.from({ length: 120 }, (_, i) => thread(i, "hi"))).map((b) => b.length)).toEqual([50, 50, 20]); |
| 17 | }); |
| 18 | |
| 19 | it("shortens a body too long for one queue message", () => { |
| 20 | const [[job]] = mailBatches([thread(0, "y".repeat(500_000))]) as [[MailJob]]; |
| 21 | const body = (job as unknown as { data: { body: string } }).data.body; |
| 22 | expect(body.length).toBeLessThan(MAX_QUEUED_BODY + 10); |
| 23 | expect(body.endsWith("…")).toBe(true); |
| 24 | }); |
| 25 | |
| 26 | it("leaves out a job too large for one queue message, not the batch it would be in", () => { |
| 27 | const huge = { ...thread(1, "hi"), data: { ...(thread(1, "hi") as unknown as { data: object }).data, title: "z".repeat(200_000) } } as unknown as MailJob; |
| 28 | expect(mailBatches([thread(0, "hi"), huge, thread(2, "hi")]).flat().map((j) => j.to)).toEqual([{ accountId: "u0" }, { accountId: "u2" }]); |
| 29 | }); |
| 30 | |
| 31 | it("queues every batch even when one is refused", async () => { |
| 32 | const sent: number[] = []; |
| 33 | let calls = 0; |
| 34 | const env = { MAIL: { sendBatch: async (b: unknown[]) => { if (calls++ === 0) throw new Error("refused"); sent.push(b.length); } } } as unknown as Env; |
| 35 | await enqueueMail(env, Array.from({ length: 120 }, (_, i) => thread(i, "hi"))); |
| 36 | expect(sent).toEqual([50, 20]); |
| 37 | }); |
| 38 | }); |