Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Queue finalize participant emails and send them in batches (#3429)
Luke Vella41ef4811b73a
diff --git a/apps/docs/workflow/schedule.mdx b/apps/docs/workflow/schedule.mdxindex a5e7eed7e..c9afea3fe 100644--- a/apps/docs/workflow/schedule.mdx+++ b/apps/docs/workflow/schedule.mdx@@ -45,7 +45,8 @@ invite to the participants you choose and closes the poll to new responses.This will:1. Send a calendar invite to you by email.- 2. Send a calendar invite to the participants you selected.+ 2. Send a calendar invite to the participants you selected. Invites go out+ in batches, so on a large poll the last ones can take a few minutes.3. Close the poll to new responses.<Frame>diff --git a/apps/web/.env.test b/apps/web/.env.testindex 8061ceade..279d76408 100644--- a/apps/web/.env.test+++ b/apps/web/.env.test@@ -24,3 +24,4 @@ CONFERENCING_ENABLED=trueZOOM_CLIENT_ID=test-zoomZOOM_CLIENT_SECRET=test-zoom-secretZOOM_WEBHOOK_SECRET_TOKEN=test-zoom-webhook-secret+EMAIL_QUEUE_SCHEDULER_ENABLED=falsediff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 339e4ddb1..2a6700aef 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -389,7 +389,7 @@"finalizePollDescription": "Pick the date that works best.","finalizePollError": "Failed to finalize poll","finalizeSuccessDate": "Your event is booked for <date></date>.",- "finalizeSuccessNotified": "{count, plural, =0 {No participants were notified.} one {# participant has been notified.} other {# participants have been notified.}}",+ "finalizeSuccessNotified": "{count, plural, =0 {No participants were notified.} one {# participant will be notified.} other {# participants will be notified.}}","finalizeSuccessTitle": "Date scheduled","finalizeSummaryDescription": "Check the details before you finalize.","finalizeSummaryTitle": "Summary",diff --git a/apps/web/src/app/api/house-keeping/[...method]/route.ts b/apps/web/src/app/api/house-keeping/[...method]/route.tsindex 3901b54cc..1ad3c1b15 100644--- a/apps/web/src/app/api/house-keeping/[...method]/route.ts+++ b/apps/web/src/app/api/house-keeping/[...method]/route.ts@@ -3,6 +3,7 @@ import { Effect } from "effect";import { Hono } from "hono";import { bearerAuth } from "hono/bearer-auth";import { handle } from "hono/vercel";+import { runQueuedEmailDelivery } from "@/emails/queue";import {cancelUserSubscriptions,deleteStripeCustomer,@@ -231,4 +232,20 @@ app.get("/deliver-webhooks", async (c) => {return c.json({ success: true, summary });});+app.get("/send-queued-emails", async (c) => {+ // The scheduled drain behind each action's own first batch. Each run+ // sends one batch, so a large fan-out goes out at that rate.+ const summary = await runQueuedEmailDelivery({});++ // Runs every minute and most runs find nothing.+ if (summary.attempted > 0 || summary.abandoned > 0) {+ logger.info(+ { task: "send-queued-emails", ...summary },+ "Sent queued emails",+ );+ }++ return c.json({ success: true, summary });+});+export const GET = handle(app);diff --git a/apps/web/src/emails/queue.ts b/apps/web/src/emails/queue.tsnew file mode 100644index 000000000..c8c396329--- /dev/null+++ b/apps/web/src/emails/queue.ts@@ -0,0 +1,110 @@+import "server-only";++import { createLogger } from "@rallly/logger";+import { Effect, Layer } from "effect";+import { after } from "next/server";+import { env } from "@/env";+import {+ QUEUED_EMAIL_BATCH_SIZE,+ QUEUED_EMAIL_IMMEDIATE_BATCH_SIZE,+} from "@/features/email-queue/constants";+import { deliverQueuedEmails } from "@/features/email-queue/mutations";+import {+ QueuedEmailHandlers,+ SendRateLimiter,+} from "@/features/email-queue/service";+import { sendScheduledEventInviteEmail } from "@/features/scheduled-event/mutations";+import { runtime } from "@/lib/effect/runtime";++const logger = createLogger("email-queue");++/**+ * Every kind's handler. Built here, outside the features, because the+ * features that queue email depend on the queue; the queue depending back+ * on them would be a cycle.+ */+const queuedEmailLayer = Layer.mergeAll(+ Layer.succeed(+ QueuedEmailHandlers,+ QueuedEmailHandlers.of({+ scheduled_event_invite: sendScheduledEventInviteEmail,+ }),+ ),+ SendRateLimiter.layer,+);++/**+ * One delivery run. The scheduled run claims a full batch across every+ * action; a run for one action's batch claims only its immediate share.+ */+export function runQueuedEmailDelivery({+ batchId,+ limit = batchId ? QUEUED_EMAIL_IMMEDIATE_BATCH_SIZE : QUEUED_EMAIL_BATCH_SIZE,+}: {+ batchId?: string;+ limit?: number;+}) {+ return runtime.runPromise(+ deliverQueuedEmails({ now: new Date(), limit, batchId }).pipe(+ Effect.provide(queuedEmailLayer),+ ),+ );+}++/**+ * Sends the first emails an action queued once its response is out, so a+ * typical fan-out lands within seconds. The rest, and any retry, is left to+ * the scheduled runs. Needs a request scope for `after`.+ */+export function scheduleQueuedEmailDelivery({ batchId }: { batchId: string }) {+ after(async () => {+ try {+ await runQueuedEmailDelivery({ batchId });+ } catch (error) {+ logger.error({ batchId, error }, "Queued email delivery failed");+ }+ });+}++const SCHEDULER_INTERVAL_MS = 60_000;++const schedulerState = globalThis as typeof globalThis & {+ queuedEmailScheduler?: ReturnType<typeof setInterval>;+};++/**+ * Runs the queue every minute inside this server process, the same run the+ * house-keeping cron triggers on Vercel. For long-lived servers only: `next+ * dev` and the self-hosted image. A tick that finds the previous run still+ * going is skipped, and the timer is kept on `globalThis` so a dev reload+ * cannot start a second one. Several processes can each run one; claims do+ * not overlap.+ */+export function startQueuedEmailScheduler() {+ if (+ env.EMAIL_QUEUE_SCHEDULER_ENABLED === "false" ||+ schedulerState.queuedEmailScheduler+ ) {+ return;+ }++ let running = false;+ const timer = setInterval(async () => {+ if (running) {+ return;+ }+ running = true;+ try {+ const summary = await runQueuedEmailDelivery({});+ if (summary.attempted > 0 || summary.abandoned > 0) {+ logger.info(summary, "Sent queued emails");+ }+ } catch (error) {+ logger.error({ error }, "Scheduled queued email delivery failed");+ } finally {+ running = false;+ }+ }, SCHEDULER_INTERVAL_MS);+ timer.unref();+ schedulerState.queuedEmailScheduler = timer;+}diff --git a/apps/web/src/env.ts b/apps/web/src/env.tsindex 17641f9f0..cf8550940 100644--- a/apps/web/src/env.ts+++ b/apps/web/src/env.ts@@ -169,6 +169,12 @@ export const env = createEnv({* @default "true"*/RATE_LIMIT_ENABLED: z.enum(["true", "false"]).default("true"),+ /**+ * Run the queued email scheduler inside the server process. Off where a+ * test needs to control exactly when the queue runs.+ * @default "true"+ */+ EMAIL_QUEUE_SCHEDULER_ENABLED: z.enum(["true", "false"]).default("true"),/*** Take the app offline for scheduled maintenance. Page traffic is@@ -320,6 +326,7 @@ export const env = createEnv({APP_NAME: process.env.APP_NAME,HIDE_ATTRIBUTION: process.env.HIDE_ATTRIBUTION,RATE_LIMIT_ENABLED: process.env.RATE_LIMIT_ENABLED,+ EMAIL_QUEUE_SCHEDULER_ENABLED: process.env.EMAIL_QUEUE_SCHEDULER_ENABLED,MAINTENANCE_MODE: process.env.MAINTENANCE_MODE,MAINTENANCE_BYPASS_TOKEN: process.env.MAINTENANCE_BYPASS_TOKEN,TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY,diff --git a/apps/web/src/features/email-queue/constants.ts b/apps/web/src/features/email-queue/constants.tsnew file mode 100644index 000000000..72c40fa1d--- /dev/null+++ b/apps/web/src/features/email-queue/constants.ts@@ -0,0 +1,47 @@+export const QUEUED_EMAIL_KINDS = ["scheduled_event_invite"] as const;++/**+ * Emails an action sends from its own request, right after the response.+ * Scheduled polls have had at most 32 participants, with the 99th+ * percentile between 13 and 30, so this covers almost every booking; the+ * rest waits for the scheduler.+ */+export const QUEUED_EMAIL_IMMEDIATE_BATCH_SIZE = 25;++/**+ * Emails a scheduled run claims. The shared send rate, not this, sets the+ * pace: at that rate a full batch takes about half a minute, inside the minute+ * between runs and well inside the claim timeout.+ */+export const QUEUED_EMAIL_BATCH_SIZE = 500;++/**+ * Queued email shares the SES account's send rate (50 per second) with+ * every email sent directly, login codes included. Capping the queue well+ * below it keeps a large fan-out from getting those throttled.+ */+export const QUEUED_EMAIL_SENDS_PER_SECOND = 20;++/**+ * How long one send waits for a slot under the shared rate before the+ * attempt counts as failed and is retried later.+ */+export const QUEUED_EMAIL_RATE_WAIT_MS = 30_000;++export const QUEUED_EMAIL_CONCURRENCY = 5;++/**+ * A claim older than this is abandoned: the run died, or the send failed+ * and the email waits out this long before its next attempt.+ */+export const QUEUED_EMAIL_CLAIM_TIMEOUT_MS = 10 * 60_000;++export const MAX_QUEUED_EMAIL_ATTEMPTS = 3;++/**+ * A run stops starting sends after this long and hands the rest of its+ * claims back. Together with the rate wait it bounds how late a run can+ * send, which keeps every send inside its claim: an email reclaimed by+ * another run while this one still sends it would go out twice.+ */+export const QUEUED_EMAIL_RUN_BUDGET_MS = 2 * 60_000;diff --git a/apps/web/src/features/email-queue/data.ts b/apps/web/src/features/email-queue/data.tsnew file mode 100644index 000000000..f7c893c1f--- /dev/null+++ b/apps/web/src/features/email-queue/data.ts@@ -0,0 +1,16 @@+import "server-only";++import { prisma } from "@rallly/database";++export function listQueuedEmails({ ids }: { ids: string[] }) {+ return prisma.queuedEmail.findMany({+ where: { id: { in: ids } },+ select: {+ id: true,+ kind: true,+ subjectId: true,+ attempts: true,+ user: { select: { banned: true } },+ },+ });+}diff --git a/apps/web/src/features/email-queue/mutations.test.ts b/apps/web/src/features/email-queue/mutations.test.tsnew file mode 100644index 000000000..d2abf22ca--- /dev/null+++ b/apps/web/src/features/email-queue/mutations.test.ts@@ -0,0 +1,71 @@+import { Effect, Layer } from "effect";+import { describe, expect, it, vi } from "vitest";++// `@/env` validates at import and refuses to run under jsdom; the handlers+// under test never read it.+vi.mock("@/env", () => ({ env: {} }));++import { attemptQueuedEmail } from "./mutations";+import type { QueuedEmailHandler } from "./service";+import {+ QueuedEmailFailed,+ QueuedEmailHandlers,+ QueuedEmailSkipped,+} from "./service";++function attemptWith(handler: QueuedEmailHandler, banned = false) {+ return Effect.runPromise(+ attemptQueuedEmail({+ id: "q_1",+ kind: "scheduled_event_invite",+ subjectId: "invite_1",+ attempts: 1,+ user: { banned },+ }).pipe(+ Effect.provide(+ Layer.succeed(+ QueuedEmailHandlers,+ QueuedEmailHandlers.of({ scheduled_event_invite: handler }),+ ),+ ),+ ),+ );+}++describe("attemptQueuedEmail", () => {+ it("reports a handled email as sent", async () => {+ expect(await attemptWith(() => Effect.void)).toEqual({ ok: true });+ });++ it("skips without calling the handler when the queuing account is banned", async () => {+ const handler = vi.fn(() => Effect.void);+ expect(await attemptWith(handler, true)).toEqual({+ ok: false,+ skip: true,+ reason: "Queued by a banned account",+ });+ expect(handler).not.toHaveBeenCalled();+ });++ it("folds a skip and a failure into results", async () => {+ expect(+ await attemptWith(() => new QueuedEmailSkipped({ reason: "Gone" })),+ ).toEqual({ ok: false, skip: true, reason: "Gone" });+ expect(+ await attemptWith(() => new QueuedEmailFailed({ message: "SMTP 451" })),+ ).toEqual({ ok: false, skip: false, error: "SMTP 451" });+ });++ it("folds a handler that throws into a failed attempt", async () => {+ const result = await attemptWith(() =>+ Effect.sync(() => {+ throw new RangeError("Incorrect locale information provided");+ }),+ );+ expect(result).toEqual({+ ok: false,+ skip: false,+ error: "Incorrect locale information provided",+ });+ });+});diff --git a/apps/web/src/features/email-queue/mutations.ts b/apps/web/src/features/email-queue/mutations.tsnew file mode 100644index 000000000..3d97f66ac--- /dev/null+++ b/apps/web/src/features/email-queue/mutations.ts@@ -0,0 +1,323 @@+import "server-only";++import type { Prisma } from "@rallly/database";+import { Prisma as PrismaRuntime, prisma } from "@rallly/database";+import { createLogger } from "@rallly/logger";+import { Clock, Effect } from "effect";+import type { DatabaseError } from "@/lib/effect/db";+import { fromPrisma } from "@/lib/effect/db";+import {+ MAX_QUEUED_EMAIL_ATTEMPTS,+ QUEUED_EMAIL_CLAIM_TIMEOUT_MS,+ QUEUED_EMAIL_CONCURRENCY,+ QUEUED_EMAIL_KINDS,+ QUEUED_EMAIL_RUN_BUDGET_MS,+} from "./constants";+import { listQueuedEmails } from "./data";+import { QueuedEmailHandlers, SendRateLimiter } from "./service";+import type { QueuedEmailKind } from "./types";++const logger = createLogger("email-queue");++/**+ * Queues one email per subject inside the caller's transaction, so the+ * emails exist exactly when the change they announce does.+ */+export async function queueEmails(+ tx: Prisma.TransactionClient,+ {+ kind,+ userId,+ batchId,+ subjectIds,+ }: {+ kind: QueuedEmailKind;+ userId: string;+ batchId: string;+ subjectIds: string[];+ },+) {+ if (subjectIds.length === 0) {+ return;+ }+ await tx.queuedEmail.createMany({+ data: subjectIds.map((subjectId) => ({+ kind,+ userId,+ batchId,+ subjectId,+ })),+ });+}++/**+ * Pending emails whose final attempt was claimed by a run that never+ * recorded an outcome. Every other exhausted email is marked failed when+ * its last attempt fails.+ */+export const failAbandonedQueuedEmails = Effect.fn(+ "emailQueue.failAbandonedQueuedEmails",+)(function* ({ now }: { now: Date }) {+ const { count } = yield* fromPrisma(() =>+ prisma.queuedEmail.updateMany({+ where: {+ status: "pending",+ attempts: { gte: MAX_QUEUED_EMAIL_ATTEMPTS },+ claimedAt: {+ lt: new Date(now.getTime() - QUEUED_EMAIL_CLAIM_TIMEOUT_MS),+ },+ },+ data: {+ status: "failed",+ claimedAt: null,+ lastError: "Delivery run did not finish",+ },+ }),+ );+ return count;+});++/**+ * Claims a batch of pending emails in one statement. SKIP LOCKED lets+ * overlapping runs claim disjoint batches instead of queueing behind each+ * other, and the attempt is counted at claim time so an email whose send+ * keeps killing the run still exhausts. Only kinds this build has a handler+ * for are claimed: a process on older code, mid upgrade or sharing a dev+ * database, would otherwise spend the attempts of kinds it cannot send.+ */+export const claimQueuedEmails = Effect.fn("emailQueue.claimQueuedEmails")(+ function* ({+ now,+ limit,+ batchId,+ }: {+ now: Date;+ limit: number;+ batchId?: string;+ }) {+ const staleBefore = new Date(now.getTime() - QUEUED_EMAIL_CLAIM_TIMEOUT_MS);+ const rows = yield* fromPrisma(+ () => prisma.$queryRaw<{ id: string }[]>`+ UPDATE queued_emails+ SET claimed_at = ${now},+ attempts = attempts + 1,+ updated_at = ${now}+ WHERE id IN (+ SELECT id FROM queued_emails+ WHERE status = 'pending'+ AND kind::text = ANY(${[...QUEUED_EMAIL_KINDS]})+ AND attempts < ${MAX_QUEUED_EMAIL_ATTEMPTS}+ AND (claimed_at IS NULL OR claimed_at < ${staleBefore})+ ${batchId ? PrismaRuntime.sql`AND batch_id = ${batchId}` : PrismaRuntime.empty}+ ORDER BY created_at, id+ LIMIT ${limit}+ FOR UPDATE SKIP LOCKED+ )+ RETURNING id`,+ );+ return rows.map((row) => row.id);+ },+);++type QueuedEmail = Awaited<ReturnType<typeof listQueuedEmails>>[number];++type QueuedEmailAttempt =+ | { ok: true }+ | { ok: false; skip: true; reason: string }+ | { ok: false; skip: false; error: string };++export type QueuedEmailOutcome =+ | "sent"+ | "skipped"+ | "retrying"+ | "failed"+ | "deferred";++/**+ * Hands one claimed email to its kind's handler. An email queued by an+ * account banned since is skipped without building it. A failure is data+ * here: the email is claimed, and an error escaping would leave it to the+ * claim timeout.+ */+export const attemptQueuedEmail = Effect.fn("emailQueue.attemptQueuedEmail")(+ function* (email: QueuedEmail) {+ if (email.user.banned) {+ return {+ ok: false,+ skip: true,+ reason: "Queued by a banned account",+ } satisfies QueuedEmailAttempt as QueuedEmailAttempt;+ }+ const handlers = yield* QueuedEmailHandlers;+ yield* handlers[email.kind]({ id: email.id, subjectId: email.subjectId });+ return { ok: true } satisfies QueuedEmailAttempt as QueuedEmailAttempt;+ },+ Effect.catchTags({+ QueuedEmailSkipped: (error) =>+ Effect.succeed<QueuedEmailAttempt>({+ ok: false,+ skip: true,+ reason: error.reason,+ }),+ QueuedEmailFailed: (error) =>+ Effect.succeed<QueuedEmailAttempt>({+ ok: false,+ skip: false,+ error: error.message,+ }),+ }),+ // A handler that throws (bad stored data reaching Intl, a template bug)+ // fails its own email, not the whole batch it was claimed with.+ Effect.catchDefect((defect) =>+ Effect.succeed<QueuedEmailAttempt>({+ ok: false,+ skip: false,+ error: defect instanceof Error ? defect.message : "Unexpected error",+ }),+ ),+);++/**+ * Records an attempt. A failure with attempts left keeps its claim, so the+ * email waits out the claim timeout before a scheduled run tries again. Every write+ * is conditional on the email still being pending under this claim's+ * attempt, so it cannot undo a skip applied while the send was in flight,+ * nor overwrite a newer claim taken after this one timed out.+ */+export const recordQueuedEmailResult = Effect.fn(+ "emailQueue.recordQueuedEmailResult",+)(function* ({+ id,+ attempts,+ result,+ now,+}: {+ id: string;+ attempts: number;+ result: QueuedEmailAttempt;+ now: Date;+}) {+ const where = { id, status: "pending", attempts } as const;+ if (result.ok) {+ yield* fromPrisma(() =>+ prisma.queuedEmail.updateMany({+ where,+ data: { status: "sent", sentAt: now, claimedAt: null, lastError: null },+ }),+ );+ return "sent" satisfies QueuedEmailOutcome as QueuedEmailOutcome;+ }+ if (result.skip) {+ yield* fromPrisma(() =>+ prisma.queuedEmail.updateMany({+ where,+ data: { status: "skipped", claimedAt: null, lastError: result.reason },+ }),+ );+ return "skipped" satisfies QueuedEmailOutcome as QueuedEmailOutcome;+ }+ logger.warn({ id, attempts, error: result.error }, "Queued email failed");+ if (attempts < MAX_QUEUED_EMAIL_ATTEMPTS) {+ yield* fromPrisma(() =>+ prisma.queuedEmail.updateMany({+ where,+ data: { lastError: result.error },+ }),+ );+ return "retrying" satisfies QueuedEmailOutcome as QueuedEmailOutcome;+ }+ yield* fromPrisma(() =>+ prisma.queuedEmail.updateMany({+ where,+ data: { status: "failed", claimedAt: null, lastError: result.error },+ }),+ );+ return "failed" satisfies QueuedEmailOutcome as QueuedEmailOutcome;+});++/**+ * Hands an unattempted claim back: the claim is cleared and its attempt+ * uncounted, so the next run takes it at once and it costs no attempt.+ * Conditional on the claim, like every result write.+ */+export const releaseQueuedEmail = Effect.fn("emailQueue.releaseQueuedEmail")(+ function* ({ id, attempts }: { id: string; attempts: number }) {+ yield* fromPrisma(() =>+ prisma.queuedEmail.updateMany({+ where: { id, status: "pending", attempts },+ data: { claimedAt: null, attempts: { decrement: 1 } },+ }),+ );+ return "deferred" satisfies QueuedEmailOutcome as QueuedEmailOutcome;+ },+);++export type DeliverQueuedEmailsSummary = Record<+ QueuedEmailOutcome | "attempted" | "abandoned",+ number+>;++/**+ * One run: fail abandoned final attempts, claim a batch, send it a few at a+ * time under the shared send rate and record every outcome. The scheduled+ * run covers every batch; a run triggered by the action that queued the+ * emails is limited to that action's batch so its first emails go out at+ * once. Past the run budget, or when the shared rate has no slot in time,+ * the remaining claims are handed back for the next run.+ */+export const deliverQueuedEmails = Effect.fn("emailQueue.deliverQueuedEmails")(+ function* ({+ now,+ limit,+ batchId,+ }: {+ now: Date;+ limit: number;+ batchId?: string;+ }): Effect.fn.Return<+ DeliverQueuedEmailsSummary,+ DatabaseError,+ QueuedEmailHandlers | SendRateLimiter+ > {+ const abandoned = batchId ? 0 : yield* failAbandonedQueuedEmails({ now });+ const ids = yield* claimQueuedEmails({ now, limit, batchId });+ const emails =+ ids.length > 0 ? yield* fromPrisma(() => listQueuedEmails({ ids })) : [];+ const deadline = now.getTime() + QUEUED_EMAIL_RUN_BUDGET_MS;+ const rate = yield* SendRateLimiter;++ const outcomes = yield* Effect.forEach(+ emails,+ Effect.fn("emailQueue.deliverQueuedEmail")(function* (email) {+ const claim = { id: email.id, attempts: email.attempts };+ if ((yield* Clock.currentTimeMillis) > deadline) {+ return yield* releaseQueuedEmail(claim);+ }+ if (!(yield* rate.acquire())) {+ return yield* releaseQueuedEmail(claim);+ }+ const result = yield* attemptQueuedEmail(email);+ return yield* recordQueuedEmailResult({+ ...claim,+ result,+ now: new Date(yield* Clock.currentTimeMillis),+ });+ }),+ { concurrency: QUEUED_EMAIL_CONCURRENCY },+ );++ const summary: DeliverQueuedEmailsSummary = {+ abandoned,+ attempted: emails.length,+ sent: 0,+ skipped: 0,+ retrying: 0,+ failed: 0,+ deferred: 0,+ };+ for (const outcome of outcomes) {+ summary[outcome]++;+ }+ return summary;+ },+);diff --git a/apps/web/src/features/email-queue/service.ts b/apps/web/src/features/email-queue/service.tsnew file mode 100644index 000000000..f6e556be8--- /dev/null+++ b/apps/web/src/features/email-queue/service.ts@@ -0,0 +1,71 @@+import "server-only";++import { createLogger } from "@rallly/logger";+import { Context, Data, Effect, Layer } from "effect";+import { createSharedRate } from "@/lib/rate-limit";+import {+ QUEUED_EMAIL_RATE_WAIT_MS,+ QUEUED_EMAIL_SENDS_PER_SECOND,+} from "./constants";+import type { QueuedEmailKind } from "./types";++const logger = createLogger("email-queue");++/** The subject is gone, or no longer warrants the email. Not retried. */+export class QueuedEmailSkipped extends Data.TaggedError("QueuedEmailSkipped")<{+ reason: string;+}> {}++/** The attempt failed and may be retried. `message` lands in `lastError`. */+export class QueuedEmailFailed extends Data.TaggedError("QueuedEmailFailed")<{+ message: string;+}> {}++/** Builds one email from its subject, as the subject is now, and sends it. */+export type QueuedEmailHandler = (email: {+ id: string;+ subjectId: string;+}) => Effect.Effect<void, QueuedEmailSkipped | QueuedEmailFailed>;++/**+ * One handler per kind. The queue knows nothing about what it sends: each+ * feature that queues email owns its handler, and the layer that collects+ * them is built outside the features so none of them imports another.+ */+export class QueuedEmailHandlers extends Context.Service<+ QueuedEmailHandlers,+ Record<QueuedEmailKind, QueuedEmailHandler>+>()("rallly/email-queue/QueuedEmailHandlers") {}++/**+ * The send rate every queue run shares, across processes. `acquire` waits+ * for a slot and answers false if none freed up in time. Without Redis+ * there is no shared rate and every send goes ahead; a failure to reach+ * Redis does the same, logged, rather than stalling the queue.+ */+export class SendRateLimiter extends Context.Service<+ SendRateLimiter,+ { acquire(): Effect.Effect<boolean> }+>()("rallly/email-queue/SendRateLimiter") {+ static readonly layer = Layer.sync(SendRateLimiter, () => {+ const rate = createSharedRate(QUEUED_EMAIL_SENDS_PER_SECOND, "1 s");+ return SendRateLimiter.of({+ acquire: () =>+ rate+ ? Effect.tryPromise(() =>+ rate.acquire("email-queue:send", QUEUED_EMAIL_RATE_WAIT_MS),+ ).pipe(+ Effect.catch((error) =>+ Effect.sync(() => {+ logger.error(+ { error },+ "Shared send rate unavailable, sending unthrottled",+ );+ return true;+ }),+ ),+ )+ : Effect.succeed(true),+ });+ });+}diff --git a/apps/web/src/features/email-queue/types.ts b/apps/web/src/features/email-queue/types.tsnew file mode 100644index 000000000..84c2ef432--- /dev/null+++ b/apps/web/src/features/email-queue/types.ts@@ -0,0 +1,3 @@+import type { QUEUED_EMAIL_KINDS } from "./constants";++export type QueuedEmailKind = (typeof QUEUED_EMAIL_KINDS)[number];diff --git a/apps/web/src/features/poll/components/finalize-poll-dialog.tsx b/apps/web/src/features/poll/components/finalize-poll-dialog.tsxindex fc9af6b85..302136250 100644--- a/apps/web/src/features/poll/components/finalize-poll-dialog.tsx+++ b/apps/web/src/features/poll/components/finalize-poll-dialog.tsx@@ -631,7 +631,7 @@ function FinalizeWizard({ onClose }: { onClose: () => void }) {/>{" "}<Transi18nKey="finalizeSuccessNotified"- defaults="{count, plural, =0 {No participants were notified.} one {# participant has been notified.} other {# participants have been notified.}}"+ defaults="{count, plural, =0 {No participants were notified.} one {# participant will be notified.} other {# participants will be notified.}}"values={{ count: notifyIds.size }}/></DialogDescription>diff --git a/apps/web/src/features/scheduled-event/data.ts b/apps/web/src/features/scheduled-event/data.tsindex 010117539..9510885ef 100644--- a/apps/web/src/features/scheduled-event/data.ts+++ b/apps/web/src/features/scheduled-event/data.ts@@ -557,3 +557,50 @@ export const getEventsChronological = async ({return getUpcomingEvents({ ...commonParams, timeZone });}};++// Everything an invite email is built from, read at send time so the email+// describes the event as it is when it goes out. The poll owner is the+// organizer and host, as on the confirmation the host receives.+export function getInviteEmailData({ uid }: { uid: string }) {+ return prisma.scheduledEventInvite.findUnique({+ where: { uid },+ select: {+ inviteeEmail: true,+ inviteeLocale: true,+ inviteeTimeZone: true,+ scheduledEvent: {+ select: {+ id: true,+ uid: true,+ sequence: true,+ title: true,+ description: true,+ location: true,+ conferencing: true,+ start: true,+ end: true,+ allDay: true,+ timeZone: true,+ status: true,+ deletedAt: true,+ space: {+ select: {+ tier: true,+ showBranding: true,+ hideAttribution: true,+ primaryColor: true,+ image: true,+ },+ },+ polls: {+ take: 1,+ select: {+ id: true,+ user: { select: { name: true, email: true, banned: true } },+ },+ },+ },+ },+ },+ });+}diff --git a/apps/web/src/features/scheduled-event/mutations.ts b/apps/web/src/features/scheduled-event/mutations.tsindex d65993dba..3021206a1 100644--- a/apps/web/src/features/scheduled-event/mutations.ts+++ b/apps/web/src/features/scheduled-event/mutations.ts@@ -2,9 +2,25 @@ import "server-only";import type { ScheduledEventInviteStatus } from "@rallly/database";import { Prisma, prisma } from "@rallly/database";+import { sendFinalizeParticipantEmail } from "@rallly/emails/templates/finalized-participant";+import { shortUrl } from "@rallly/utils/absolute-url";import { nanoid } from "@rallly/utils/nanoid";+import { Effect } from "effect";import { updateTag } from "next/cache";+import { getSpaceBranding } from "@/emails/branding";+import { toEmailConferencing } from "@/emails/conferencing";+import { parseConferencing } from "@/features/conferencing/data";+import { getConferencingUri } from "@/features/conferencing/utils";+import {+ QueuedEmailFailed,+ QueuedEmailSkipped,+} from "@/features/email-queue/service";+import { parseLocation } from "@/features/location/data";+import { formatLocationText } from "@/features/location/utils";import { scheduledEventTag } from "@/features/scheduled-event/constants";+import { createIcsEvent } from "@/lib/utils/ics";+import { getInviteEmailData } from "./data";+import { formatEventDateTime } from "./utils";export async function createRsvp({eventId,@@ -75,3 +91,117 @@ export async function cancelRsvp({ inviteUid }: { inviteUid: string }) {return { ok: true } as const;}++const failWith = (message: string) => () => new QueuedEmailFailed({ message });++/**+ * The queue handler for `scheduled_event_invite`: tells one invitee their+ * event is booked, built from the invite (the subject, by uid) and its event+ * as they are now. A canceled or deleted event, or a poll owner banned since+ * the booking, skips the email.+ */+export const sendScheduledEventInviteEmail = Effect.fn(+ "scheduledEvent.sendScheduledEventInviteEmail",+)(function* ({ subjectId }: { id: string; subjectId: string }) {+ const invite = yield* Effect.tryPromise({+ try: () => getInviteEmailData({ uid: subjectId }),+ catch: failWith("Failed to load the invite"),+ });+ const event = invite?.scheduledEvent;+ const poll = event?.polls[0];+ const host = poll?.user;+ if (!invite || !event || !poll || !host) {+ return yield* new QueuedEmailSkipped({ reason: "Invite no longer exists" });+ }+ if (event.deletedAt || event.status === "canceled") {+ return yield* new QueuedEmailSkipped({ reason: "Event was canceled" });+ }+ if (host.banned) {+ return yield* new QueuedEmailSkipped({ reason: "Poll owner is banned" });+ }++ const location = parseLocation(event.location, {+ scheduledEventId: event.id,+ });+ const conferencing = parseConferencing(event.conferencing, {+ scheduledEventId: event.id,+ });+ const locationText = location ? formatLocationText(location) : undefined;+ const conferencingUri = conferencing+ ? getConferencingUri(conferencing)+ : undefined;++ // The same event the host's confirmation carries: one UID, one organizer,+ // so every copy lands as the same calendar entry.+ const ics = createIcsEvent({+ uid: event.uid,+ sequence: event.sequence,+ title: event.title,+ location: locationText || conferencingUri,+ description:+ [event.description, conferencingUri].filter(Boolean).join("\n\n") ||+ undefined,+ start: event.start,+ end: event.end,+ allDay: event.allDay,+ timeZone: event.timeZone ?? undefined,+ organizer: { name: host.name, email: host.email },+ });+ if (ics.error || !ics.value) {+ return yield* new QueuedEmailFailed({+ message: ics.error?.message ?? "Failed to generate ics",+ });+ }+ const icsContent = ics.value;++ const locale = invite.inviteeLocale ?? undefined;+ const { date, time } = formatEventDateTime({+ start: event.start,+ end: event.end,+ allDay: event.allDay,+ timeZone: event.timeZone,+ inviteeTimeZone: invite.inviteeTimeZone,+ locale,+ });+ const branding = yield* Effect.tryPromise({+ try: () => getSpaceBranding(event.space),+ catch: failWith("Failed to load branding"),+ });++ // The mailer logs and swallows transport failures, so its result is what+ // tells a sent email from a failed one. A render error throws.+ const sent = yield* Effect.tryPromise({+ try: () =>+ sendFinalizeParticipantEmail({+ to: invite.inviteeEmail,+ locale,+ branding,+ icalEvent: {+ filename: "invite.ics",+ method: "request",+ content: icsContent,+ },+ props: {+ pollUrl: shortUrl(`/invite/${poll.id}`),+ title: event.title,+ hostName: host.name,+ location: locationText,+ conferencing: conferencing+ ? toEmailConferencing(conferencing)+ : undefined,+ date,+ time,+ },+ }),+ catch: (cause) =>+ new QueuedEmailFailed({+ message:+ cause instanceof Error ? cause.message : "Email failed to render",+ }),+ });+ if (!sent) {+ return yield* new QueuedEmailFailed({+ message: "Transport rejected the email",+ });+ }+});diff --git a/apps/web/src/instrumentation.ts b/apps/web/src/instrumentation.tsindex 85569497b..f6d0d5e9e 100644--- a/apps/web/src/instrumentation.ts+++ b/apps/web/src/instrumentation.ts@@ -11,6 +11,17 @@ export async function register() {setupOutboundProxy();await import("../sentry.server.config");++ // On Vercel the house-keeping cron runs the email queue; everywhere else+ // (dev, the self-hosted image) a long-lived server runs it itself. Never+ // during a build, which must not touch the database.+ if (+ !process.env.VERCEL &&+ process.env.NEXT_PHASE !== "phase-production-build"+ ) {+ const { startQueuedEmailScheduler } = await import("@/emails/queue");+ startQueuedEmailScheduler();+ }}if (process.env.NEXT_RUNTIME === "edge") {diff --git a/apps/web/src/lib/rate-limit/index.ts b/apps/web/src/lib/rate-limit/index.tsindex 96c04e558..af5c6902e 100644--- a/apps/web/src/lib/rate-limit/index.ts+++ b/apps/web/src/lib/rate-limit/index.ts@@ -79,3 +79,28 @@ export function createRatelimit(requests: number, duration: Duration) {return createMemoryLimiter(requests, duration);}++/**+ * A rate shared by every process, for work that should wait its turn rather+ * than be refused. `acquire` resolves true once a slot is free, false if+ * none freed up within the timeout. Needs Redis: a per-process counter+ * shares nothing across serverless instances, so without Redis (or with+ * rate limiting off) there is no limiter and callers go unthrottled.+ */+export function createSharedRate(requests: number, duration: Duration) {+ if (!isRateLimitEnabled || !redis) {+ return null;+ }++ const limiter = new Ratelimit({+ redis,+ limiter: Ratelimit.slidingWindow(requests, duration),+ });++ return {+ async acquire(key: string, timeoutMs: number) {+ const res = await limiter.blockUntilReady(key, timeoutMs);+ return res.success;+ },+ };+}diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex 2d8b0ddc0..52586d894 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -1,14 +1,14 @@import { Prisma, prisma } from "@rallly/database";import { sendFinalizeHostEmail } from "@rallly/emails/templates/finalized-host";-import { sendFinalizeParticipantEmail } from "@rallly/emails/templates/finalized-participant";import { sendNewPollEmail } from "@rallly/emails/templates/new-poll";import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";import { nanoid } from "@rallly/utils/nanoid";import { TRPCError } from "@trpc/server";import { after } from "next/server";import * as z from "zod";-import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";+import { getInstanceBranding } from "@/emails/branding";import { toEmailConferencing } from "@/emails/conferencing";+import { scheduleQueuedEmailDelivery } from "@/emails/queue";import { recordPollActivities } from "@/features/activity/mutations";import { getPollChanges } from "@/features/activity/utils";import { resolveSpaceTier } from "@/features/billing/utils";@@ -27,6 +27,7 @@ import {getConferencingUri,moderatedLinkText,} from "@/features/conferencing/utils";+import { queueEmails } from "@/features/email-queue/mutations";import { getInstancePolicy } from "@/features/instance-policy/data";import { moderateContent } from "@/features/moderation/mutations";import {@@ -1109,15 +1110,7 @@ export const polls = router({description: true,spaceId: true,hideParticipants: true,- space: {- select: {- tier: true,- showBranding: true,- hideAttribution: true,- primaryColor: true,- image: true,- },- },+ space: { select: { tier: true } },user: {select: {id: true,@@ -1294,9 +1287,17 @@ export const polls = router({inviteeName: string;inviteeEmail: string;inviteeTimeZone: string | null | undefined;+ inviteeLocale: string | null;status: (typeof inviteStatusByVote)[keyof typeof inviteStatusByVote];}>();+ // An address is emailed when any participant behind it was selected.+ const notifyIds = new Set(input.notifyParticipantIds);+ const notifyEmails = new Set(+ poll.participants.flatMap((p) =>+ p.email && notifyIds.has(p.id) ? [p.email.trim().toLowerCase()] : [],+ ),+ );for (const p of poll.participants) {if (!p.email) continue;const status =@@ -1316,10 +1317,14 @@ export const polls = router({inviteeName: p.name,inviteeEmail: p.email,inviteeTimeZone: p.user?.timeZone ?? p.timeZone ?? poll.timeZone,+ inviteeLocale: p.locale,status,});}const inviteData = Array.from(invitesByEmail.values());+ const notifyInviteUids = Array.from(invitesByEmail)+ .filter(([key]) => notifyEmails.has(key))+ .map(([, invite]) => invite.uid);const scheduledEvent = await prisma.$transaction(async (tx) => {// create scheduled event@@ -1372,6 +1377,14 @@ export const polls = router({},},]);+ // Queued with the event so the selection is kept even if the+ // request dies before anything is sent.+ await queueEmails(tx, {+ kind: "scheduled_event_invite",+ userId: ctx.user.id,+ batchId: event.id,+ subjectIds: notifyInviteUids,+ });scheduleWebhookDispatch({ pollId: poll.id });return event;@@ -1390,20 +1403,6 @@ export const polls = router({message: "Failed to generate ics",});} else {- const notifyIds = new Set(input.notifyParticipantIds);- const participantsToEmail = poll.participants.flatMap((p) =>- notifyIds.has(p.id) && p.email- ? [- {- name: p.name,- email: p.email,- locale: p.locale ?? undefined,- timeZone: p.timeZone,- },- ]- : [],- );-const hostEmail = poll.user.email;const hostName = poll.user.name;const hostLocale = poll.user.locale ?? undefined;@@ -1417,7 +1416,6 @@ export const polls = router({timeFormat: poll.user.timeFormat,});- const space = poll.space;after(async () =>sendFinalizeHostEmail({to: hostEmail,@@ -1447,39 +1445,7 @@ export const polls = router({}),);- for (const p of participantsToEmail) {- const { date, time } = formatEventDateTime({- start: scheduledEvent.start,- end: scheduledEvent.end,- allDay: scheduledEvent.allDay,- timeZone: scheduledEvent.timeZone,- inviteeTimeZone: p.timeZone,- locale: p.locale,- });- after(async () =>- sendFinalizeParticipantEmail({- to: p.email,- locale: p.locale ?? undefined,- branding: space- ? await getSpaceBranding(space)- : await getInstanceBranding(),- icalEvent: {- filename: "invite.ics",- method: "request",- content: event.value,- },- props: {- pollUrl: shortUrl(`/invite/${poll.id}`),- title: poll.title,- hostName: poll.user?.name ?? "",- location: poll.location || undefined,- conferencing: emailConferencing,- date,- time,- },- }),- );- }+ scheduleQueuedEmailDelivery({ batchId: scheduledEvent.id });track(ctx.user, {event: "poll_schedule",diff --git a/apps/web/tests/invite-emails.spec.ts b/apps/web/tests/invite-emails.spec.tsnew file mode 100644index 000000000..7ffca9c98--- /dev/null+++ b/apps/web/tests/invite-emails.spec.ts@@ -0,0 +1,381 @@+import type { APIRequestContext } from "@playwright/test";+import { expect, test } from "@playwright/test";+import { prisma } from "@rallly/database";+import {+ captureOne,+ deleteAllMessages,+ getAttachmentText,+ getMessages,+} from "@rallly/test-helpers";+import { createSpaceInDb, createUserInDb, loginWithEmail } from "./test-utils";++/**+ * Booking a poll queues one email per invite the organizer chose to notify;+ * the booking sends its first batch and the minute cron drains the queue.+ * The first suite seeds a booked event with a queued email, runs the cron+ * and asserts on mailpit and the queue row; the second books through the+ * finalize wizard.+ */++const CRON_SECRET = process.env.CRON_SECRET;+const EVENT_ID = "invite-email-event";+const EVENT_UID = "[email protected]";+const POLL_ID = "invite-email-poll";+const TITLE = "Invite Email Test Event";+const HOST_EMAIL = "[email protected]";+const QUEUED_INVITE_UID = "invite-email-queued";++const YEAR = new Date().getFullYear() + 1;++async function runCron(request: APIRequestContext) {+ const response = await request.get("/api/house-keeping/send-queued-emails", {+ headers: { Authorization: `Bearer ${CRON_SECRET}` },+ });+ expect(response.ok()).toBeTruthy();+ const data = await response.json();+ expect(data.success).toBe(true);+ return data.summary as Record<string, number>;+}++async function cleanup() {+ await prisma.poll.deleteMany({ where: { id: POLL_ID } });+ await prisma.scheduledEvent.deleteMany({ where: { id: EVENT_ID } });+ // Queued emails go with the user that queued them.+ await prisma.user.deleteMany({ where: { email: HOST_EMAIL } });+}++async function seed({+ status = "confirmed",+ banned = false,+}: {+ status?: "confirmed" | "canceled";+ banned?: boolean;+} = {}) {+ await cleanup();+ const user = await createUserInDb({+ email: HOST_EMAIL,+ name: "Invite Email Host",+ });+ if (banned) {+ await prisma.user.update({ where: { id: user.id }, data: { banned } });+ }+ const space = await createSpaceInDb({+ name: "Invite Email Space",+ ownerId: user.id,+ tier: "hobby",+ });+ await prisma.scheduledEvent.create({+ data: {+ id: EVENT_ID,+ uid: EVENT_UID,+ userId: user.id,+ spaceId: space.id,+ title: TITLE,+ status,+ timeZone: "Europe/London",+ location: { provider: "custom", address: "100 Fish Street, London" },+ start: new Date(`${YEAR}-09-10T16:00:00.000Z`),+ end: new Date(`${YEAR}-09-10T17:00:00.000Z`),+ invites: {+ createMany: {+ data: [+ {+ uid: QUEUED_INVITE_UID,+ inviteeName: "Queued Invitee",+ inviteeEmail: "[email protected]",+ inviteeTimeZone: "America/New_York",+ inviteeLocale: "en",+ status: "accepted",+ },+ {+ uid: "invite-email-not-queued",+ inviteeName: "Not Queued Invitee",+ inviteeEmail: "[email protected]",+ status: "accepted",+ },+ ],+ },+ },+ },+ });+ await prisma.poll.create({+ data: {+ id: POLL_ID,+ title: TITLE,+ userId: user.id,+ spaceId: space.id,+ status: "scheduled",+ scheduledEventId: EVENT_ID,+ },+ });+ return prisma.queuedEmail.create({+ data: {+ kind: "scheduled_event_invite",+ subjectId: QUEUED_INVITE_UID,+ batchId: EVENT_ID,+ userId: user.id,+ },+ });+}++function findQueued(id: string) {+ return prisma.queuedEmail.findUniqueOrThrow({ where: { id } });+}++test.describe("Queued invite emails", () => {+ test.beforeEach(async () => {+ await deleteAllMessages();+ });++ test.afterAll(async () => {+ await cleanup();+ await deleteAllMessages();+ });++ test("sends a queued invite once and nothing to invites not queued", async ({+ request,+ }) => {+ const queued = await seed();++ const summary = await runCron(request);+ expect(summary.sent).toBeGreaterThanOrEqual(1);++ const { email } = await captureOne("[email protected]");+ expect(email.Subject).toBe(`Date booked for ${TITLE}`);+ expect(email.Text).toContain("Invite Email Host");+ expect(email.Attachments).toHaveLength(1);+ const ics = (+ await getAttachmentText(email.ID, email.Attachments[0].PartID)+ ).replace(/\r?\n[ \t]/g, "");+ expect(ics).toContain(`UID:${EVENT_UID}`);+ expect(ics).toContain("LOCATION:100 Fish Street\\, London");++ const sent = await findQueued(queued.id);+ expect(sent.status).toBe("sent");+ expect(sent.sentAt).not.toBeNull();+ expect(sent.attempts).toBe(1);+ expect(sent.claimedAt).toBeNull();++ // A second run finds nothing left to send.+ await deleteAllMessages();+ await runCron(request);+ const { messages } = await getMessages();+ expect(+ messages.filter((m) =>+ m.To.some((t) => t.Address.endsWith("@example.com")),+ ),+ ).toHaveLength(0);+ });++ test("skips an invite whose event was canceled", async ({ request }) => {+ const queued = await seed({ status: "canceled" });++ await runCron(request);++ const row = await findQueued(queued.id);+ expect(row.status).toBe("skipped");+ expect(row.lastError).toBe("Event was canceled");+ const { messages } = await getMessages();+ expect(messages).toHaveLength(0);+ });++ test("skips emails queued by an account banned since", async ({+ request,+ }) => {+ const queued = await seed({ banned: true });++ await runCron(request);++ const row = await findQueued(queued.id);+ expect(row.status).toBe("skipped");+ expect(row.lastError).toBe("Queued by a banned account");+ const { messages } = await getMessages();+ expect(messages).toHaveLength(0);+ });++ test("does not claim an email another run claimed recently", async ({+ request,+ }) => {+ const queued = await seed();+ await prisma.queuedEmail.update({+ where: { id: queued.id },+ data: { claimedAt: new Date(), attempts: 1 },+ });++ await runCron(request);++ const row = await findQueued(queued.id);+ expect(row.status).toBe("pending");+ expect(row.attempts).toBe(1);+ });++ test("fails an email whose final claim was abandoned", async ({+ request,+ }) => {+ const queued = await seed();+ await prisma.queuedEmail.update({+ where: { id: queued.id },+ data: {+ claimedAt: new Date(Date.now() - 60 * 60_000),+ attempts: 3,+ },+ });++ const summary = await runCron(request);+ expect(summary.abandoned).toBeGreaterThanOrEqual(1);++ const row = await findQueued(queued.id);+ expect(row.status).toBe("failed");+ });+});++test.describe("Booking a poll", () => {+ const BOOKING_POLL_ID = "invite-email-booking-poll";+ const BOOKING_HOST_EMAIL = "[email protected]";+ const ALICE = "[email protected]";+ const BOB = "[email protected]";++ async function cleanupBooking() {+ const poll = await prisma.poll.findUnique({+ where: { id: BOOKING_POLL_ID },+ select: { scheduledEventId: true },+ });+ await prisma.poll.deleteMany({ where: { id: BOOKING_POLL_ID } });+ if (poll?.scheduledEventId) {+ await prisma.scheduledEvent.deleteMany({+ where: { id: poll.scheduledEventId },+ });+ }+ await prisma.user.deleteMany({ where: { email: BOOKING_HOST_EMAIL } });+ }++ test.beforeEach(async () => {+ await cleanupBooking();+ await deleteAllMessages();+ });++ test.afterAll(async () => {+ await cleanupBooking();+ await deleteAllMessages();+ });++ test("queues the selected participants and sends them after the response", async ({+ page,+ }) => {+ const user = await createUserInDb({+ email: BOOKING_HOST_EMAIL,+ name: "Booking Host",+ });+ const space = await prisma.space.findFirstOrThrow({+ where: { ownerId: user.id },+ });+ const poll = await prisma.poll.create({+ data: {+ id: BOOKING_POLL_ID,+ title: "Booking Path Poll",+ userId: user.id,+ spaceId: space.id,+ timeZone: "Europe/London",+ options: {+ create: {+ startTime: new Date(`${YEAR}-09-10T16:00:00.000Z`),+ duration: 60,+ },+ },+ },+ include: { options: true },+ });+ const optionId = poll.options[0].id;+ const participants = [+ // Two responses behind one address: selecting either emails it once.+ { name: "Alice", email: ALICE, vote: "yes" },+ { name: "Alice Again", email: ALICE, vote: "no" },+ { name: "Bob", email: BOB, vote: "ifNeedBe" },+ { name: "Carol", email: null, vote: "yes" },+ ] as const;+ for (const [index, p] of participants.entries()) {+ await prisma.participant.create({+ data: {+ name: p.name,+ email: p.email,+ locale: "en",+ token: `invite-booking-token-${index}-${Date.now()}`,+ pollId: poll.id,+ votes: {+ create: { optionId, pollId: poll.id, type: p.vote },+ },+ },+ });+ }++ await loginWithEmail(page, { email: BOOKING_HOST_EMAIL });+ await page.goto(`/poll/${poll.id}`);+ await page.getByRole("button", { name: "Finalize" }).click();++ const dialog = page.getByRole("dialog");+ await dialog.getByRole("button", { name: /September/ }).click();++ // Everyone with an email starts selected; keep only the first Alice.+ await dialog.getByLabel("Alice Again").uncheck();+ await dialog.getByLabel("Bob").uncheck();+ await dialog.getByRole("button", { name: "Next" }).click();+ await dialog+ .getByRole("button", { name: "Finalize and notify 1 participant" })+ .click();+ await expect(+ dialog.getByText("1 participant will be notified."),+ ).toBeVisible();++ // No cron run: the booking's own after() sends the first batch.+ const { email } = await captureOne(ALICE);+ expect(email.Subject).toBe("Date booked for Booking Path Poll");+ expect(email.Text).toContain("Booking Host");+ expect(email.Attachments).toHaveLength(1);++ const { scheduledEventId } = await prisma.poll.findUniqueOrThrow({+ where: { id: poll.id },+ select: { scheduledEventId: true },+ });+ const invites = await prisma.scheduledEventInvite.findMany({+ where: { scheduledEventId: scheduledEventId ?? "" },+ orderBy: { inviteeEmail: "asc" },+ });+ expect(+ invites.map((i) => ({+ email: i.inviteeEmail,+ status: i.status,+ locale: i.inviteeLocale,+ })),+ ).toEqual([+ { email: ALICE, status: "accepted", locale: "en" },+ { email: BOB, status: "tentative", locale: "en" },+ ]);++ // Only the selected address was queued, and the booking sent it.+ const queued = await prisma.queuedEmail.findMany({+ where: { batchId: scheduledEventId ?? "" },+ });+ expect(+ queued.map((q) => ({+ kind: q.kind,+ subjectId: q.subjectId,+ status: q.status,+ attempts: q.attempts,+ })),+ ).toEqual([+ {+ kind: "scheduled_event_invite",+ subjectId: invites[0].uid,+ status: "sent",+ attempts: 1,+ },+ ]);++ // Exactly one participant email went out: none to Bob, none twice.+ const { messages } = await getMessages();+ const recipients = messages.flatMap((m) => m.To.map((t) => t.Address));+ expect(recipients.filter((r) => r === ALICE)).toHaveLength(1);+ expect(recipients).not.toContain(BOB);+ expect(recipients).toContain(BOOKING_HOST_EMAIL);+ });+});diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex 43447c569..c9a140454 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -30,6 +30,10 @@{"path": "/api/house-keeping/deliver-webhooks","schedule": "* * * * *"+ },+ {+ "path": "/api/house-keeping/send-queued-emails",+ "schedule": "* * * * *"}]}diff --git a/packages/database/prisma/migrations/20261002120000_add_queued_emails/migration.sql b/packages/database/prisma/migrations/20261002120000_add_queued_emails/migration.sqlnew file mode 100644index 000000000..35459bae8--- /dev/null+++ b/packages/database/prisma/migrations/20261002120000_add_queued_emails/migration.sql@@ -0,0 +1,36 @@+-- CreateEnum+CREATE TYPE "queued_email_kind" AS ENUM ('scheduled_event_invite');++-- CreateEnum+CREATE TYPE "queued_email_status" AS ENUM ('pending', 'sent', 'skipped', 'failed');++-- CreateTable+CREATE TABLE "queued_emails" (+ "id" TEXT NOT NULL,+ "kind" "queued_email_kind" NOT NULL,+ "subject_id" TEXT NOT NULL,+ "batch_id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "status" "queued_email_status" NOT NULL DEFAULT 'pending',+ "attempts" INTEGER NOT NULL DEFAULT 0,+ "claimed_at" TIMESTAMP(3),+ "sent_at" TIMESTAMP(3),+ "last_error" TEXT,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "queued_emails_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "queued_emails_status_created_at_idx" ON "queued_emails"("status", "created_at");++-- CreateIndex+CREATE INDEX "queued_emails_batch_id_idx" ON "queued_emails"("batch_id");++-- CreateIndex+CREATE INDEX "queued_emails_user_id_status_idx" ON "queued_emails"("user_id", "status");++-- AddForeignKey+ALTER TABLE "queued_emails" ADD CONSTRAINT "queued_emails_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;+diff --git a/packages/database/prisma/models/email-queue.prisma b/packages/database/prisma/models/email-queue.prismanew file mode 100644index 000000000..f563f5e0b--- /dev/null+++ b/packages/database/prisma/models/email-queue.prisma@@ -0,0 +1,45 @@+enum QueuedEmailKind {+ scheduled_event_invite++ @@map("queued_email_kind")+}++enum QueuedEmailStatus {+ pending+ sent+ skipped+ failed++ @@map("queued_email_status")+}++/// An email waiting to be sent by the queue, one row per recipient. The+/// email is built when it is sent, from the row its subject points at.+model QueuedEmail {+ id String @id @default(cuid())+ kind QueuedEmailKind+ /// The row the email is about, interpreted by the kind. Not a foreign key:+ /// kinds point at different tables, and a subject deleted before the send+ /// makes its handler skip the email.+ subjectId String @map("subject_id")+ /// Groups the emails one action queued, so the action can send its own+ /// first batch at once and its progress can be read back.+ batchId String @map("batch_id")+ /// The account whose action queued the email. Banning it skips whatever+ /// is still pending.+ userId String @map("user_id")+ status QueuedEmailStatus @default(pending)+ attempts Int @default(0)+ claimedAt DateTime? @map("claimed_at")+ sentAt DateTime? @map("sent_at")+ lastError String? @map("last_error")+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @updatedAt @map("updated_at")++ user User @relation(fields: [userId], references: [id], onDelete: Cascade)++ @@index([status, createdAt])+ @@index([batchId])+ @@index([userId, status])+ @@map("queued_emails")+}diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prismaindex fb2c53c7d..5b12e5602 100644--- a/packages/database/prisma/models/user.prisma+++ b/packages/database/prisma/models/user.prisma@@ -66,6 +66,7 @@ model User {comments Comment[]polls Poll[]notificationPreferences UserNotificationPreferences?+ queuedEmails QueuedEmail[]accounts Account[]participants Participant[]paymentMethods PaymentMethod[]diff --git a/packages/emails/src/send.tsx b/packages/emails/src/send.tsxindex e8ceec1cb..2f64b0e67 100644--- a/packages/emails/src/send.tsx+++ b/packages/emails/src/send.tsx@@ -155,10 +155,16 @@ function buildSesOptions(): Record<string, unknown> | undefined {return { FeedbackForwardingEmailAddress: feedbackAddress };}+/**+ * Resolves true once the transport accepted the message, or when the+ * instance has no email configured and there is nothing to send. False is a+ * transport failure, already logged; callers that keep delivery state retry+ * on it, everyone else can ignore it.+ */async function dispatch(options: DispatchOptions) {if (!process.env.SUPPORT_EMAIL) {logger.info("SUPPORT_EMAIL not configured - skipping email send");- return;+ return true;}try {@@ -184,6 +190,7 @@ async function dispatch(options: DispatchOptions) {},`Sent email: ${options.errorLabel}`,);+ return true;} catch (e) {// Operational (SMTP/transport) failures are logged, not thrown — sending is// fire-and-forget. Render/template (code) errors are NOT caught here, so they@@ -198,6 +205,7 @@ async function dispatch(options: DispatchOptions) {},`Failed to send email: ${options.errorLabel}`,);+ return false;}}@@ -220,7 +228,7 @@ export async function sendRenderedEmail(options: {render(options.element, { plainText: true }),]);- await dispatch({+ return dispatch({to: options.to,from: options.from,replyTo: options.replyTo,@@ -251,5 +259,5 @@ export type SendRawEmailOptions = {* For the rare app-specific cases that don't warrant a React template.*/export async function sendRawEmail(options: SendRawEmailOptions) {- await dispatch({ ...options, errorLabel: options.subject });+ return dispatch({ ...options, errorLabel: options.subject });}diff --git a/packages/emails/src/templates/finalized-participant.tsx b/packages/emails/src/templates/finalized-participant.tsxindex 8ae0430a1..b7909c770 100644--- a/packages/emails/src/templates/finalized-participant.tsx+++ b/packages/emails/src/templates/finalized-participant.tsx@@ -132,7 +132,7 @@ export async function sendFinalizeParticipantEmail({...rest}: SendArgs<FinalizeParticipantEmailProps>) {const { t } = await createEmailI18n(locale);- await sendRenderedEmail({+ return sendRenderedEmail({to,subject: t("finalizeParticipant_subject", {defaultValue: "Date booked for {title}",diff --git a/scripts/check-user-cascade-relations.mjs b/scripts/check-user-cascade-relations.mjsindex 6c22ccf56..3cae34c56 100644--- a/scripts/check-user-cascade-relations.mjs+++ b/scripts/check-user-cascade-relations.mjs@@ -48,6 +48,10 @@ const IGNORED_RELATIONS = new Map(["notificationPreferences","Per-user settings, meaningless once the account is gone.",],+ [+ "queuedEmails",+ "Delivery state for emails the account's actions queued, sent within minutes and carrying no user-authored content. Once the account is gone, what it queued should not go out.",+ ],["nonprofitApplications","Audit record of a space's automated nonprofit review (retired; the table keeps past decisions). Only a space owner can apply, and guests cannot own a space (the purge already retains anyone with `spaces`), so a guest never has one.",