diff --git a/README.md b/README.md index 78a560f..c6789d3 100644 --- a/README.md +++ b/README.md @@ -65,9 +65,19 @@ schema 的唯一可信源是 `worker/src/db/migrations.ts` 里按前缀参数化 | 表名生成入口 | 只经 `worker/src/types.ts` 的 `migrationsTable(prefix)` 一处生成,严禁散落拼接 | | 账本结构 | `name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch())` | -**历史已塌缩**:someday 无生产数据,历史不逐级展开,`schema_v1` = 当前业务 schema -(6 表 + 4 索引)。`schema_v2` 起为增量迁移(当前:`{prefix}waker_executions`,waker 回调的 -执行幂等账本,见下“waker 回调入口”)。 +**历史已塌缩**:someday 无生产数据,历史不逐级展开,`schema_v1` = 业务 schema 基线 +(6 表 + 4 索引)。`schema_v2` 起为增量迁移: + +| 迁移 | 内容 | +| --- | --- | +| `schema_v2` | `{prefix}waker_executions`(waker 回调的执行幂等账本,见下“waker 回调入口”) | +| `schema_v3` | `letters.next_attempt_at`(限流退避的下次可尝试时刻) | +| `schema_v4` | `letters.throttle_attempts`(限流计数器,不占用 `attempts`) | +| `schema_v5` | `letter_recipients.message_id`(每收件人副本的 Message-ID) | +| `schema_v6` | 索引 `(status, next_attempt_at, send_at)`(到期扫描的退避过滤) | + +`schema_v3`–`v6` 每条**只含一条 DDL**:账本只在整条迁移成功后落账、失败项重跑会重放整条 SQL, +而 `ALTER TABLE ADD COLUMN` 本身不幂等——单语句拆分才能保证重跑只重试失败的那一条。 **runner 语义**(`worker/src/lib/migrations-runner.ts`,两处 setup 入口共用): @@ -113,13 +123,31 @@ schema 的唯一可信源是 `worker/src/db/migrations.ts` 里按前缀参数化 | 回调地址 | `https://someday.oneboy.app/_waker/execute`(SDK 的 `CALLBACK_MOUNT_PATH` + `/execute`) | | 任务名 | `deliver-due-letters`(`worker/src/services/waker-callback.ts` 的 `DUE_LETTERS_JOB`,须与 waker 平台里注册的 job 名逐字一致) | | 验签 | HMAC-SHA256 覆盖 `timestamp + executionId + jobId + rawBody`,300s 时间窗,由 SDK receiver 完成;未带签名/篡改/过期 → 401,缺 signing key → 500(fail closed) | -| 执行语义 | handler `await processDueLetters(env)` 跑完才回 2xx,响应体带 `{ stats }`(`scanned` / `delivered` / `partialFailed` / `gaveUp`,口径同 `processDueLetters`);抛错/DB 不可用 → 5xx,平台重试 | +| 执行语义 | handler `await processDueLetters(env, { timeoutSeconds })` 跑完才回 2xx,响应体带 `{ stats }`(`scanned` / `claimed` / `delivered` / `partialFailed` / `failed` / `throttled` / `deferred_by_cap` / `paused_until`,口径同 `processDueLetters`);抛错/DB 不可用 → 5xx,平台重试 | +| 单轮预算 | 预算取自回调体 `timeoutSeconds`(waker 任务策略,现配置 120 秒),留 10 秒收尾余量;预算或单轮收件人上限用尽即顺延到下一轮,本轮首封必发 | | 幂等 | executionId 由 SDK 的 D1 账本去重(`{prefix}waker_executions`,`schema_v2`),重复投递回 2xx + `duplicate:true` + 首响应回放;业务防重仍是 letters 状态抢占(最终防线,未改) | SDK 是**源码拷贝**(`worker/src/waker/`,来源与版本见该目录 `README.md`),不手改;升级回 waker 仓库改完再整目录重拷。 签名密钥 `WAKER_SIGNING_KEY` 只走 secrets:线上配 GitHub repository secret,Deploy workflow 写进 `--secrets-file` 注入;本地放 `worker/.dev.vars`(自生成的测试 key)。 -**上线先后**:部署后需由管理员跑一次 `POST /api/admin/db-upgrade` 应用 `schema_v2`(新建 `{prefix}waker_executions`);未跑之前回调会因账本表缺失回 500(cron 仍在,投递不受影响)。 +**上线先后**:部署后需由管理员跑一次 `POST /api/admin/db-upgrade` 应用未落账的迁移(`schema_v2` 新建 `{prefix}waker_executions`;`schema_v3`–`v6` 为发信节流补的新列与索引)。**未跑之前投递扫描会因缺列报错、回调回 5xx**,所以部署后第一件事就是跑一次升级。 + +### 发信节流(THROTTLING-ADDENDUM §3) + +waker 每 5 分钟回调一次,节流把「一轮爆发」摊成「多轮细流」,参数与运行状态都在 +`{prefix}system_settings`: + +| 键 | 内容 | +| --- | --- | +| `send_throttle_config` | JSON:`interval_ms`(默认 4000,0–30000)、`jitter_ms`(默认 2000,0–10000)、`max_recipients_per_run`(默认 10,1–100)。缺失/字段缺失逐项回默认;非法值回默认并 warn(投递不崩) | +| `send_paused_until` | 熔断截止时刻(UTC ISO);未过期时触发的扫描直接跳过发送、不抢占任何信 | + +- **间隔 + 单轮上限**:逐收件人串行,本轮第一封不等待,其后每封前等 `interval_ms + random(0, jitter_ms)`(运行时原生 `setTimeout`);单轮最多处理 `max_recipients_per_run` 个收件人,额度在**抢占之前**生效。信只发了一部分时未发收件人保持 `pending`、信回 `scheduled`(`attempts` 与 `last_error` 不动),绝不卡在 `sending`。 +- **限流退避**:SMTP 回复码 421/450/451/452 或命中限流关键词 → 收件人记 `[throttle:452] ...`、信 `attempts` 不增加、`throttle_attempts+1`、`next_attempt_at` 按 15 → 30 → 60 分钟递增(封顶 60);退避时刻超过 `send_at + 24h` 直接置 `failed`。第一例限流即停掉本轮剩余发送并写 `send_paused_until`(只由限流类触发)。 +- **永久错误**(550/551/553 等)走原路径:计 `attempts`、达 3 次置 `failed`,不熔断。 +- **成功即清零**:整封发完置 `sent` 并清 `next_attempt_at` / `throttle_attempts`;`POST /api/letters/:id/resend` 也一并清空。 +- **防去重**:每收件人副本一个 Message-ID ``(成功后落 `letter_recipients.message_id`),邮件头带 `X-Someday-Letter-Id`,落款追加「信件编号:{letter_id}」。 +- **参数接口**:`GET/PUT /api/admin/settings/send-throttle`(管理员会话,v1 无设置页 UI;PUT 越界/非整数 400,未提供的字段保持当前值)。管理员「发送测试邮件」不走队列,不受上限、间隔与 `send_paused_until` 影响。 ## 校验命令(CI 同款) diff --git a/worker/src/db/migrations.ts b/worker/src/db/migrations.ts index 5ebce35..67765c5 100644 --- a/worker/src/db/migrations.ts +++ b/worker/src/db/migrations.ts @@ -153,5 +153,29 @@ CREATE TABLE IF NOT EXISTS ${t("waker_executions")} ( ); `, }, + // ── 发信节流补遗(THROTTLING-ADDENDUM §3.5)──────────────────────────── + // schema_v3–v6 每条**只含一条 DDL**:账本只在整条迁移成功后落账,失败项重跑时 + // 会重放整条 SQL;SQLite 的 ADD COLUMN 本身不幂等,拆成单语句才能保证 + // 「重跑只重试失败的那一条」而不是撞在已加好的列上。 + { + name: "schema_v3", + // 限流退避的下次可尝试时刻(UTC ISO,可空;空 = 可尝试) + sql: `ALTER TABLE ${t("letters")} ADD COLUMN next_attempt_at TEXT;`, + }, + { + name: "schema_v4", + // 限流类错误计数(只按限流退避递增,不占用 attempts) + sql: `ALTER TABLE ${t("letters")} ADD COLUMN throttle_attempts INTEGER NOT NULL DEFAULT 0;`, + }, + { + name: "schema_v5", + // 每收件人副本的唯一 Message-ID(成功投递后落库,供事后追溯) + sql: `ALTER TABLE ${t("letter_recipients")} ADD COLUMN message_id TEXT;`, + }, + { + name: "schema_v6", + // 到期扫描新增的退避过滤条件:按 (status, next_attempt_at, send_at) 取 + sql: `CREATE INDEX IF NOT EXISTS idx_${t("letters")}_status_next_attempt ON ${t("letters")}(status, next_attempt_at, send_at);`, + }, ]; } diff --git a/worker/src/db/queries/letters.ts b/worker/src/db/queries/letters.ts index 43a76fc..f3d3ef4 100644 --- a/worker/src/db/queries/letters.ts +++ b/worker/src/db/queries/letters.ts @@ -26,6 +26,10 @@ export type LetterUpdate = Partial<{ attempts: number; last_error: string | null; sent_at: string | null; + /** 节流补遗 §3.2:限流退避的下次可尝试时刻(UTC ISO,可空) */ + next_attempt_at: string | null; + /** 节流补遗 §3.2:限流退避计数 */ + throttle_attempts: number; }>; const LETTER_UPDATE_COLS = new Set([ @@ -39,6 +43,8 @@ const LETTER_UPDATE_COLS = new Set([ "attempts", "last_error", "sent_at", + "next_attempt_at", + "throttle_attempts", ]); export async function listLettersByUser( diff --git a/worker/src/index.ts b/worker/src/index.ts index 9cfcc35..f28bb71 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -11,6 +11,7 @@ import { lettersRoutes } from "./routes/letters"; import { contactsRoutes } from "./routes/contacts"; import { publicRoutes } from "./routes/public"; import { adminSmtpRoutes } from "./routes/admin-smtp"; +import { adminSendThrottleRoutes } from "./routes/admin-send-throttle"; import { adminSystemRoutes } from "./routes/admin-system"; import { wakerCallbackRoutes } from "./routes/waker-callback"; import { processDueLetters } from "./services/scheduler"; @@ -61,6 +62,8 @@ app.route("/api/letters", lettersRoutes); app.route("/api/contacts", contactsRoutes); app.route("/api/public", publicRoutes); app.route("/api/admin/settings", adminSmtpRoutes); +// 发信节流参数(节流补遗 §3.1.4):v1 无设置页 UI,只开后端接口。 +app.route("/api/admin/settings", adminSendThrottleRoutes); // ONE-319 管理后台维护接口:升级数据库 + setup 页面开关(管理员会话鉴权)。 app.route("/api/admin", adminSystemRoutes); app.route("/api/admin", adminRoutes); @@ -90,8 +93,9 @@ app.get("*", async (c) => { }); /** - * 定时任务入口(cron 每 5 分钟一次,见 wrangler.toml)。 + * 原生 cron 入口(当前已无 [triggers],保留给重新启用定时触发的场景)。 * SPEC §5:扫 status='scheduled' AND send_at<=now,D1 状态抢占 + 逐收件人投递。 + * 无平台回调上下文,单轮预算走 scheduler 的 30 秒兜底(节流补遗 §3.1.3)。 */ export async function handleScheduled(env: Env): Promise { try { diff --git a/worker/src/routes/admin-send-throttle.ts b/worker/src/routes/admin-send-throttle.ts new file mode 100644 index 0000000..cfbe829 --- /dev/null +++ b/worker/src/routes/admin-send-throttle.ts @@ -0,0 +1,65 @@ +import { Hono } from "hono"; +import type { HonoEnv } from "../types"; +import { getTablePrefix } from "../types"; +import { authMiddleware, adminMiddleware } from "../middleware/auth"; +import { setSetting } from "../db/queries/users"; +import { + SEND_THROTTLE_KEY, + SEND_THROTTLE_LIMITS, + readSendThrottleConfig, + validateSendThrottleField, + type SendThrottleConfig, +} from "../services/send-throttle"; + +// 发信节流参数的后台接口(节流补遗 §3.1.4):GET/PUT /api/admin/settings/send-throttle。 +// +// v1 不做设置页 UI,管理员可直接改这个接口(与 SMTP 配置同一张表、同一套鉴权口径)。 +// 读取一侧永远宽容(库里被写坏 → 逐项回默认 + warn),写入一侧严格(越界/非整数 400), +// 保证经本接口落库的值一定在合法范围内。 + +export const adminSendThrottleRoutes = new Hono(); +adminSendThrottleRoutes.use("*", authMiddleware); +adminSendThrottleRoutes.use("*", adminMiddleware); + +const THROTTLE_KEYS = [ + "interval_ms", + "jitter_ms", + "max_recipients_per_run", +] as const; + +adminSendThrottleRoutes.get("/send-throttle", async (c) => { + const config = await readSendThrottleConfig(c.env.DB, getTablePrefix(c.env)); + return c.json(config); +}); + +adminSendThrottleRoutes.put("/send-throttle", async (c) => { + const body = await c.req.json>().catch(() => null); + if (!body || typeof body !== "object" || Array.isArray(body)) { + return c.json({ error: "Invalid request body" }, 400); + } + + // 未提供的字段保持当前生效值(部分更新),提供的字段必须合法。 + const next: SendThrottleConfig = await readSendThrottleConfig( + c.env.DB, + getTablePrefix(c.env), + ); + + for (const key of THROTTLE_KEYS) { + if (!(key in body)) continue; + const value = validateSendThrottleField(key, body[key]); + if (value === null) { + const { min, max } = SEND_THROTTLE_LIMITS[key]; + return c.json({ error: `${key} 需为 ${min}–${max} 的整数` }, 400); + } + next[key] = value; + } + + await setSetting( + c.env.DB, + getTablePrefix(c.env), + SEND_THROTTLE_KEY, + JSON.stringify(next), + ); + + return c.json(next); +}); diff --git a/worker/src/routes/letters.ts b/worker/src/routes/letters.ts index 66a337f..b42538c 100644 --- a/worker/src/routes/letters.ts +++ b/worker/src/routes/letters.ts @@ -583,10 +583,13 @@ lettersRoutes.post("/:id/resend", async (c) => { } // attempts 归零回 scheduled;只补发失败的收件人(已成功的保留,不重复投递)。 + // 节流补遗 §3.2.2:手动重发同时清空限流退避状态,与清 attempts 同口径。 await updateLetter(c.env.DB, getTablePrefix(c.env), id, { status: "scheduled", attempts: 0, last_error: null, + next_attempt_at: null, + throttle_attempts: 0, }); await resetFailedRecipientsForResend(c.env.DB, getTablePrefix(c.env), id); diff --git a/worker/src/services/email.ts b/worker/src/services/email.ts index 19e2536..e189cfa 100644 --- a/worker/src/services/email.ts +++ b/worker/src/services/email.ts @@ -1,7 +1,11 @@ import type { Env } from "../types"; import { getTablePrefix } from "../types"; import { getSetting } from "../db/queries/users"; -import { sendSmtpMessage } from "./smtp-transport"; +import { + defaultMessageId, + senderDomain, + sendSmtpMessage, +} from "./smtp-transport"; // 系统邮件抽象(SPEC §2/§5,照 eNotify 现行 main `services/email.ts` 的系统邮件路径)。 // 配置读 D1 `system_settings` 的 `smtp_config`(JSON:host/port/username/password/from/from_name)。 @@ -22,6 +26,47 @@ export interface EmailOptions { html: string; from?: string; fromName?: string; + /** + * 节流补遗 §3.3:给定信件/收件人 id 时生成 ``。 + * 不传(如管理员测试邮件)则走 `` 的通用形态。 + */ + letterId?: string; + recipientId?: string; +} + +export interface SendEmailResult { + success: boolean; + error?: string; + /** 本次投递实际使用的 Message-ID(成功时有值,调用方负责落库) */ + messageId?: string; + /** 失败时的 SMTP 回复码(用于限流分类) */ + code?: number; + /** 失败时的 SMTP 回复原文 */ + response?: string; +} + +/** id 直接进邮件头,只允许安全字符(杜绝头注入与奇怪的 Message-ID)。 */ +const HEADER_ID_RE = /^[A-Za-z0-9_-]+$/; + +/** + * 构建每收件人副本的唯一 Message-ID(补遗 §3.3.1):随机串每次投递唯一, + * 同一封信不同收件人、以及补发都不会复用。 + */ +export function buildMessageId( + from: string, + letterId?: string, + recipientId?: string, +): string { + if ( + letterId !== undefined && + recipientId !== undefined && + HEADER_ID_RE.test(letterId) && + HEADER_ID_RE.test(recipientId) + ) { + const rand = Math.random().toString(36).slice(2, 10); + return ``; + } + return defaultMessageId(from); } export interface SMTPConfig { @@ -64,7 +109,7 @@ export function isValidSmtpHost(host: string): boolean { export async function sendEmail( env: Env, options: EmailOptions, -): Promise<{ success: boolean; error?: string }> { +): Promise { const to = clean(options.to); if (!to) { return { success: false, error: "Invalid recipient email address" }; @@ -117,8 +162,14 @@ export async function sendEmail( // transport 层(connect 在 try 外)可能同步抛错(如非法参数), // 这里兜底成 { success: false },保证调用方永远拿到结果、不会把信卡在 sending。 + const messageId = buildMessageId(from, options.letterId, options.recipientId); + const extraHeaders: Record = + options.letterId !== undefined && HEADER_ID_RE.test(options.letterId) + ? { "X-Someday-Letter-Id": options.letterId } + : {}; + try { - return await sendSmtpMessage( + const result = await sendSmtpMessage( { host, port, username, password }, { to, @@ -126,8 +177,20 @@ export async function sendEmail( html: options.html, from, fromName: fromName || undefined, + messageId, + extraHeaders, }, ); + + if (!result.success) { + return { + success: false, + error: result.error, + ...(result.code === undefined ? {} : { code: result.code }), + ...(result.response === undefined ? {} : { response: result.response }), + }; + } + return { success: true, messageId }; } catch (err) { return { success: false, diff --git a/worker/src/services/scheduler.ts b/worker/src/services/scheduler.ts index 4bf36d4..c5bf283 100644 --- a/worker/src/services/scheduler.ts +++ b/worker/src/services/scheduler.ts @@ -1,72 +1,214 @@ import type { Env, Letter, LetterRecipient } from "../types"; -import { tables } from "../types"; +import { getTablePrefix, tables } from "../types"; +import { getSetting, setSetting } from "../db/queries/users"; import { sendEmail } from "./email"; import { sanitizeBodyHtml } from "./sanitize"; +import { + SEND_PAUSED_KEY, + classifySendFailure, + formatDeliveryError, + readSendThrottleConfig, + sendGapMs, + sleepMs, + throttleBackoffMs, + type SendFailureClassification, + type SendThrottleConfig, +} from "./send-throttle"; -// cron 调度与逐收件人投递(SPEC §5)。 +// cron 调度与逐收件人投递(SPEC §5 + 发信节流补遗 §3)。 // 防重复用 D1 状态抢占(不用 KV dedupe): // UPDATE {prefix}letters SET status='sending' WHERE id=? AND status='scheduled' // 影响行数为 1 才发送;同一封信被并发 cron 抢占时只有一方会拿到行数=1。 // 逐收件人单独发一封(独立 RCPT,收件人之间互不可见);全部成功 → letters 置 sent; // 部分失败 → 失败者记录 error,letters attempts+1 回到 scheduled,下个周期只补发失败收件人; // attempts 达 3 次仍失败 → letters 置 failed、last_error 汇总。 +// +// 节流补遗叠加的三件事(不影响上面的抢占与补发口径): +// 1. 间隔 + 单轮收件人上限:本轮最多处理 max_recipients_per_run 个收件人,封与封之间 +// interval+jitter;额度用尽/接近平台回调超时就不再抢占,剩余信留 scheduled 下轮继续; +// 信只发了一部分时未发收件人保持 pending、信回 scheduled(绝不卡在 sending)。 +// 2. 限流感知退避:421/450/451/452 或限流关键词 → attempts 不加、throttle_attempts+1、 +// next_attempt_at 按 15/30/60 分钟递增退避,并写 send_paused_until 熔断整轮。 +// 3. 每收件人副本唯一 Message-ID(成功后落库 message_id),落款带信件编号。 const MAX_ATTEMPTS = 3; const BATCH_SIZE = 50; +/** 没有回调上下文(如原生 cron 入口)时的单轮预算:waker 任务的默认超时。 */ +const DEFAULT_RUN_TIMEOUT_SECONDS = 30; +/** 运行预算里给收尾(DB 写入、SDK 返回)留的余量。 */ +const RUN_DEADLINE_RESERVE_MS = 10_000; +/** 单封 SMTP 事务本身的余量:剩余时间不够发下一封就顺延,不硬塞。 */ +const ONE_MESSAGE_RESERVE_MS = 10_000; +/** 限流退避窗口:退避时刻超过 send_at + 24 小时即置 failed。 */ +const THROTTLE_WINDOW_MS = 24 * 60 * 60 * 1000; export interface DeliveryStats { + /** 本轮扫到的到期信数(受 BATCH_SIZE 限制) */ scanned: number; + /** 本轮抢占成功的信数 */ + claimed: number; + /** 本轮全部收件人发送成功的信数 */ delivered: number; + /** 本轮部分收件人失败、信回到 scheduled 的次数 */ partialFailed: number; - gaveUp: number; + /** 本轮被置 failed 的信数(attempts 达 3 次,或限流退避超过 24 小时) */ + failed: number; + /** 本轮命中限流类的收件人数 */ + throttled: number; + /** 因单轮上限/运行预算顺延到下一轮的收件人数 */ + deferred_by_cap: number; + /** 熔断截止时刻(UTC ISO):本轮处于熔断中(入口即熔断或本轮触发)时有值 */ + paused_until: string | null; } -export async function processDueLetters(env: Env): Promise { - const T = tables(env); - const now = new Date().toISOString(); - const stats: DeliveryStats = { +export interface DeliveryRunOptions { + /** 平台回调带来的单次执行超时(秒);缺省按 waker 默认 30 秒。 */ + timeoutSeconds?: number; +} + +/** 单轮运行的共享状态:配置、时间预算、收件人额度、统计。 */ +interface RunState { + config: SendThrottleConfig; + /** 不再开始新投递的时刻(epoch ms) */ + deadline: number; + /** 剩余可投递的收件人数 */ + budget: number; + /** 本轮已完成的 SMTP 投递事务数(首封不等待,其后每封前等待间隔) */ + sentInRun: number; + /** 本轮触发了熔断(限流类):立即停止剩余发送 */ + paused: boolean; + pauseUntil: string | null; + stats: DeliveryStats; +} + +function emptyStats(): DeliveryStats { + return { scanned: 0, + claimed: 0, delivered: 0, partialFailed: 0, - gaveUp: 0, + failed: 0, + throttled: 0, + deferred_by_cap: 0, + paused_until: null, }; +} + +function createRunState( + config: SendThrottleConfig, + timeoutSeconds: number, + stats: DeliveryStats = emptyStats(), +): RunState { + const seconds = + Number.isFinite(timeoutSeconds) && timeoutSeconds > 0 + ? timeoutSeconds + : DEFAULT_RUN_TIMEOUT_SECONDS; + return { + config, + deadline: Date.now() + seconds * 1000 - RUN_DEADLINE_RESERVE_MS, + budget: config.max_recipients_per_run, + sentInRun: 0, + paused: false, + pauseUntil: null, + stats, + }; +} + +/** 本轮是否还该开始一次新的投递(首封必发,保证每轮都有进展)。 */ +function canStartAnotherSend(run: RunState, gapMs: number): boolean { + if (run.sentInRun === 0) return true; + return Date.now() + gapMs + ONE_MESSAGE_RESERVE_MS <= run.deadline; +} + +export async function processDueLetters( + env: Env, + options: DeliveryRunOptions = {}, +): Promise { + const T = tables(env); + const prefix = getTablePrefix(env); + const now = new Date().toISOString(); + const stats = emptyStats(); + + // 熔断期内触发的扫描:直接跳过发送,不抢占任何信(补遗 §3.2.4)。 + // 值被写坏(不可解析的时刻)时按「未熔断」处理:宁可发信,也不永久卡死投递。 + const pausedUntil = await getSetting(env.DB, prefix, SEND_PAUSED_KEY); + if (pausedUntil !== null) { + const pausedUntilMs = Date.parse(pausedUntil); + if (Number.isFinite(pausedUntilMs) && pausedUntilMs > Date.now()) { + stats.paused_until = pausedUntil; + return stats; + } + } + + const config = await readSendThrottleConfig(env.DB, prefix); + const run = createRunState(config, options.timeoutSeconds ?? DEFAULT_RUN_TIMEOUT_SECONDS, stats); const due = await env.DB.prepare( - `SELECT id FROM ${T.letters} - WHERE status = 'scheduled' AND send_at IS NOT NULL AND send_at <= ? - ORDER BY send_at ASC, id ASC - LIMIT ?`, + `SELECT l.id AS id, + (SELECT COUNT(*) FROM ${T.letter_recipients} r + WHERE r.letter_id = l.id AND r.status <> 'sent') AS pending + FROM ${T.letters} l + WHERE l.status = 'scheduled' AND l.send_at IS NOT NULL AND l.send_at <= ? + AND (l.next_attempt_at IS NULL OR l.next_attempt_at <= ?) + ORDER BY l.send_at ASC, l.id ASC + LIMIT ?`, ) - .bind(now, BATCH_SIZE) - .all<{ id: string }>(); + .bind(now, now, BATCH_SIZE) + .all<{ id: string; pending: number }>(); stats.scanned = due.results.length; - for (const { id } of due.results) { + for (const row of due.results) { + if (run.paused) break; // 熔断:本轮剩余发送立即停止 + const pending = Number(row.pending ?? 0); + + // 计数在抢占之前生效:额度/时间用尽则不改状态,自然顺延到下一轮。 + if ( + run.budget <= 0 || + (run.sentInRun > 0 && Date.now() >= run.deadline) + ) { + stats.deferred_by_cap += pending; + continue; + } + try { - const outcome = await deliverLetter(env, id); - if (outcome === "delivered") stats.delivered++; - else if (outcome === "partial") stats.partialFailed++; - else if (outcome === "gaveUp") stats.gaveUp++; - // "skipped"/"error" 不计入投递结果 + await deliverLetterWithRun(env, row.id, run); } catch (err) { - console.error(`Delivery error for letter ${id}:`, err); + console.error(`Delivery error for letter ${row.id}:`, err); } } + if (run.pauseUntil !== null) stats.paused_until = run.pauseUntil; + return stats; } type DeliverOutcome = | "delivered" | "partial" - | "gaveUp" + | "failed" + | "throttled" + | "deferred" | "skipped" | "error"; +/** + * 单封信投递(保留原签名):用默认配置与预算构造一次独立运行。 + * 批量路径(processDueLetters)复用同一实现,只是共享 run 的额度与预算。 + */ export async function deliverLetter( env: Env, letterId: string, +): Promise { + const config = await readSendThrottleConfig(env.DB, getTablePrefix(env)); + const run = createRunState(config, DEFAULT_RUN_TIMEOUT_SECONDS); + return deliverLetterWithRun(env, letterId, run); +} + +async function deliverLetterWithRun( + env: Env, + letterId: string, + run: RunState, ): Promise { const T = tables(env); const now = new Date().toISOString(); @@ -81,9 +223,10 @@ export async function deliverLetter( if (!claim.meta?.changes || claim.meta.changes !== 1) { return "skipped"; } + run.stats.claimed++; try { - return await deliverClaimedLetter(env, letterId); + return await deliverClaimedLetter(env, letterId, run); } catch (err) { // 意外异常:把信退回 scheduled,避免永久卡在 sending(attempts 不变,下个周期重试)。 console.error(`Delivery error for letter ${letterId}:`, err); @@ -103,6 +246,7 @@ export async function deliverLetter( async function deliverClaimedLetter( env: Env, letterId: string, + run: RunState, ): Promise { const T = tables(env); const letter = await env.DB.prepare(`SELECT * FROM ${T.letters} WHERE id = ?`) @@ -122,45 +266,100 @@ async function deliverClaimedLetter( if (todo.length === 0) { // 没有需要发送的收件人(如全部已成功但 letters 仍停留在 sending):收尾置 sent。 await markLetterSent(env, letterId); + run.stats.delivered++; return "delivered"; } const failures: { email: string; error: string }[] = []; + const html = buildLetterHtml(letter); + let deferred = 0; + + for (let i = 0; i < todo.length; i++) { + const recipient = todo[i]!; + + // 额度用尽 / 剩余时间不够下一封 → 未发收件人保持 pending,信按「半发」回 scheduled。 + const gapMs = sendGapMs(run.config); + if (run.budget <= 0 || !canStartAnotherSend(run, gapMs)) { + deferred = todo.length - i; + break; + } - for (const recipient of todo) { - const html = buildLetterHtml(letter); + if (run.sentInRun > 0) { + await sleepMs(gapMs); + } + + const sentAt = new Date().toISOString(); const result = await sendEmail(env, { to: recipient.email, subject: letter.title, html, + letterId: letter.id, + recipientId: recipient.id, + }); + run.sentInRun++; + run.budget--; + + console.info("delivery send:", { + letter: letter.id, + recipient: recipient.id, + at: sentAt, + waitMs: run.sentInRun > 1 ? gapMs : 0, + ok: result.success, }); if (result.success) { await env.DB.prepare( - `UPDATE ${T.letter_recipients} SET status = 'sent', error = NULL, sent_at = ? WHERE id = ?`, + `UPDATE ${T.letter_recipients} SET status = 'sent', error = NULL, sent_at = ?, message_id = ? WHERE id = ?`, ) - .bind(new Date().toISOString(), recipient.id) - .run(); - } else { - const error = result.error ?? "SMTP error"; - failures.push({ email: recipient.email, error }); - await env.DB.prepare( - `UPDATE ${T.letter_recipients} SET status = 'failed', error = ?, sent_at = NULL WHERE id = ?`, - ) - .bind(error, recipient.id) + .bind(new Date().toISOString(), result.messageId ?? null, recipient.id) .run(); + continue; } + + const classification = classifySendFailure({ + code: result.code ?? null, + text: result.error ?? "SMTP error", + }); + + await env.DB.prepare( + `UPDATE ${T.letter_recipients} SET status = 'failed', error = ?, sent_at = NULL WHERE id = ?`, + ) + .bind(formatDeliveryError(classification), recipient.id) + .run(); + + if (classification.kind === "throttle") { + run.stats.throttled++; + await handleThrottledLetter(env, letter, recipient, classification, run); + return "throttled"; + } + + failures.push({ + email: recipient.email, + error: formatDeliveryError(classification), + }); } - if (failures.length === 0) { + if (failures.length === 0 && deferred === 0) { await markLetterSent(env, letterId); + run.stats.delivered++; return "delivered"; } + if (failures.length === 0) { + // 只发了其中一部分(单轮上限/运行预算):不算失败,attempts 与 last_error 不动。 + run.stats.deferred_by_cap += deferred; + await env.DB.prepare( + `UPDATE ${T.letters} SET status = 'scheduled', updated_at = ? WHERE id = ?`, + ) + .bind(new Date().toISOString(), letterId) + .run(); + return "deferred"; + } + + if (deferred > 0) run.stats.deferred_by_cap += deferred; + const attempts = letter.attempts + 1; - const lastError = failures - .map((f) => `${f.email}: ${f.error}`) - .join("; "); + const lastError = failures.map((f) => `${f.email}: ${f.error}`).join("; "); if (attempts >= MAX_ATTEMPTS) { await env.DB.prepare( @@ -168,7 +367,8 @@ async function deliverClaimedLetter( ) .bind(attempts, lastError, new Date().toISOString(), letterId) .run(); - return "gaveUp"; + run.stats.failed++; + return "failed"; } // 部分失败:回到 scheduled,下个 cron 周期只补发失败收件人(sent 的不会重发)。 @@ -177,14 +377,75 @@ async function deliverClaimedLetter( ) .bind(attempts, lastError, new Date().toISOString(), letterId) .run(); + run.stats.partialFailed++; return "partial"; } +/** + * 限流类错误:不动 attempts,按 throttle_attempts 递增退避,并熔断整轮(补遗 §3.2)。 + * 退避时刻超过 `send_at + 24h` 则直接置 failed(用户可手动重发,重发会清空节流字段)。 + */ +async function handleThrottledLetter( + env: Env, + letter: Letter, + recipient: LetterRecipient, + classification: SendFailureClassification, + run: RunState, +): Promise { + const T = tables(env); + const nowMs = Date.now(); + const throttleAttempts = (letter.throttle_attempts ?? 0) + 1; + const backoffMs = throttleBackoffMs(throttleAttempts); + const nextAttemptAt = new Date(nowMs + backoffMs).toISOString(); + const pausedUntil = new Date(nowMs + backoffMs).toISOString(); + const detail = formatDeliveryError(classification); + + // 熔断:本轮剩余发送立即停止(不再逐封硬撞)。 + await setSetting(env.DB, getTablePrefix(env), SEND_PAUSED_KEY, pausedUntil); + run.paused = true; + run.pauseUntil = pausedUntil; + + const windowEnd = letterWindowEnd(letter); + const overWindow = windowEnd !== null && Date.parse(nextAttemptAt) > windowEnd; + const lastError = overWindow + ? `${recipient.email}: ${detail}(限流退避至 ${nextAttemptAt},已超过 send_at + 24 小时,置失败)` + : `${recipient.email}: ${detail}(限流退避至 ${nextAttemptAt},第 ${throttleAttempts} 次)`; + + await env.DB.prepare( + `UPDATE ${T.letters} + SET status = ?, throttle_attempts = ?, next_attempt_at = ?, last_error = ?, updated_at = ? + WHERE id = ?`, + ) + .bind( + overWindow ? "failed" : "scheduled", + throttleAttempts, + nextAttemptAt, + lastError, + new Date().toISOString(), + letter.id, + ) + .run(); + + if (overWindow) run.stats.failed++; +} + +/** `send_at + 24h` 的 epoch ms;send_at 缺失/不可解析时 null(不套用窗口)。 */ +function letterWindowEnd(letter: Letter): number | null { + if (!letter.send_at) return null; + const sendAt = Date.parse(letter.send_at); + if (Number.isNaN(sendAt)) return null; + return sendAt + THROTTLE_WINDOW_MS; +} + async function markLetterSent(env: Env, letterId: string): Promise { const T = tables(env); const now = new Date().toISOString(); + // 成功即清零(补遗 §3.2.5):退避状态随成功一并清掉。 await env.DB.prepare( - `UPDATE ${T.letters} SET status = 'sent', sent_at = ?, last_error = NULL, updated_at = ? WHERE id = ?`, + `UPDATE ${T.letters} + SET status = 'sent', sent_at = ?, last_error = NULL, next_attempt_at = NULL, + throttle_attempts = 0, updated_at = ? + WHERE id = ?`, ) .bind(now, now, letterId) .run(); @@ -215,8 +476,9 @@ function formatWrittenDate(createdAtIso: string, timezone: string): string { } /** - * 简洁信件模板:标题 + 消毒后的正文 + 落款「这封信写于 YYYY-MM-DD,由时光邮局送达」。 + * 简洁信件模板:标题 + 消毒后的正文 + 落款「这封信写于 YYYY-MM-DD,由时光邮局送达」+「信件编号:{id}」。 * 标题单独 HTML 转义(不经过 body 白名单,避免标题里的标签注入)。 + * 信件编号只进落款,绝不改用户的正文/标题(补遗 §3.3.3)。 */ export function buildLetterHtml(letter: Letter): string { const body = sanitizeBodyHtml(letter.body_html); @@ -225,12 +487,14 @@ export function buildLetterHtml(letter: Letter): string { const signature = writtenDate ? `这封信写于 ${writtenDate},由时光邮局送达` : "由时光邮局送达"; + const letterNo = `

信件编号:${escapeHtml(letter.id)}

`; return ( `
` + `${title ? `

${title}

` : ""}` + `${body}` + `

${signature}

` + + letterNo + `
` ); } diff --git a/worker/src/services/send-throttle.ts b/worker/src/services/send-throttle.ts new file mode 100644 index 0000000..9f0f0b8 --- /dev/null +++ b/worker/src/services/send-throttle.ts @@ -0,0 +1,251 @@ +import { getSetting } from "../db/queries/users"; + +// 发信节流补遗(THROTTLING-ADDENDUM §3.1/§3.2):节流参数、限流分类、退避时长的唯一定义处。 +// +// 参数存 `{prefix}system_settings` 的 `send_throttle_config`(JSON,与 `smtp_config` 同表同路), +// 缺失/字段缺失逐项回默认;非法值(非整数、越界、类型不对)回默认并 warn——投递链路不因配置坏掉而崩。 +// `send_paused_until` 是熔断截止时刻(UTC ISO),也放同一张表,本文件只提供键名与读写常量。 +// +// 等待一律用运行时原生 `setTimeout`(不是手搓轮询);分类函数集中在此,发送层只负责把 +// SMTP 回复码与原文带回来(见 smtp-transport.ts 的 SmtpResponseError)。 + +export const SEND_THROTTLE_KEY = "send_throttle_config"; +export const SEND_PAUSED_KEY = "send_paused_until"; + +export interface SendThrottleConfig { + /** 封间隔基数(毫秒):上一封投递事务结束后、下一封开始前等待 */ + interval_ms: number; + /** 在基数上叠加的随机抖动上限(毫秒) */ + jitter_ms: number; + /** 单轮扫描最多处理的收件人数(按收件人计,不按信计) */ + max_recipients_per_run: number; +} + +/** 补遗 §3.1 的默认值(小圈子量级;实测后按日志再调)。 */ +export const DEFAULT_SEND_THROTTLE_CONFIG: SendThrottleConfig = { + interval_ms: 4000, + jitter_ms: 2000, + max_recipients_per_run: 10, +}; + +/** 补遗 §3.1 的合法范围(含端点;越界视为非法值)。 */ +export const SEND_THROTTLE_LIMITS: Record< + keyof SendThrottleConfig, + { min: number; max: number } +> = { + interval_ms: { min: 0, max: 30_000 }, + jitter_ms: { min: 0, max: 10_000 }, + max_recipients_per_run: { min: 1, max: 100 }, +}; + +const THROTTLE_KEYS: (keyof SendThrottleConfig)[] = [ + "interval_ms", + "jitter_ms", + "max_recipients_per_run", +]; + +export interface SendThrottleConfigIssue { + key: keyof SendThrottleConfig; + reason: string; +} + +export interface ParsedSendThrottleConfig { + config: SendThrottleConfig; + /** 被判为非法、已回退默认值的字段(缺失字段不算问题,静默回默认) */ + issues: SendThrottleConfigIssue[]; + /** 整段 JSON 不可解析(此时全部字段回默认) */ + invalidJson: boolean; +} + +/** 单字段校验:整数且在合法范围内才返回该值,否则 null。 */ +export function validateSendThrottleField( + key: keyof SendThrottleConfig, + raw: unknown, +): number | null { + if (typeof raw !== "number" || !Number.isInteger(raw)) return null; + const { min, max } = SEND_THROTTLE_LIMITS[key]; + if (raw < min || raw > max) return null; + return raw; +} + +/** + * 解析存储值:缺失 → 全默认;字段缺失 → 该项默认(静默);非法 → 该项默认并记入 issues。 + * 管理接口(PUT)复用同一份校验,保证库里不会落非法值。 + */ +export function parseSendThrottleConfig( + raw: string | null, +): ParsedSendThrottleConfig { + const config: SendThrottleConfig = { ...DEFAULT_SEND_THROTTLE_CONFIG }; + const issues: SendThrottleConfigIssue[] = []; + + if (raw === null || raw.trim() === "") { + return { config, issues, invalidJson: false }; + } + + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return { config, issues, invalidJson: true }; + } + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { + return { config, issues, invalidJson: true }; + } + + const obj = parsed as Record; + for (const key of THROTTLE_KEYS) { + if (!(key in obj) || obj[key] === undefined || obj[key] === null) continue; + const value = validateSendThrottleField(key, obj[key]); + if (value === null) { + issues.push({ key, reason: `非法值 ${JSON.stringify(obj[key])},回退默认` }); + continue; + } + config[key] = value; + } + + return { config, issues, invalidJson: false }; +} + +/** 读生效配置:库里的 `send_throttle_config` → 逐项校验 → 默认值兜底(非法项 warn)。 */ +export async function readSendThrottleConfig( + db: D1Database, + prefix: string, +): Promise { + const raw = await getSetting(db, prefix, SEND_THROTTLE_KEY); + const { config, issues, invalidJson } = parseSendThrottleConfig(raw); + + if (invalidJson) { + console.warn( + `[send-throttle] ${SEND_THROTTLE_KEY} 不是合法 JSON 对象,全部字段回退默认值`, + ); + } + for (const issue of issues) { + console.warn(`[send-throttle] ${issue.key}: ${issue.reason}`); + } + + return config; +} + +// ─── 限流分类(补遗 §3.2.1)───────────────────────────────────────────────── + +export type SendFailureKind = "throttle" | "permanent" | "other"; + +/** 限流类回复码:临时性拒绝/限流(4yz,421 = 服务暂不可用)。 */ +const THROTTLE_CODES = new Set([421, 450, 451, 452]); + +/** 永久类回复码:收件人/地址类 5xx,重试无意义。 */ +const PERMANENT_CODES = new Set([550, 551, 553]); + +/** 限流关键词(大小写不敏感);集中维护,判类只走本文件。 */ +export const THROTTLE_KEYWORDS = [ + "rate", + "limit", + "too many", + "too frequent", + "temporarily", + "频繁", + "限流", + "超过上限", +] as const; + +export interface SendFailureInput { + /** 发送层带回的 SMTP 回复码(没有则从原文里回解) */ + code?: number | null; + /** 错误原文(SMTP 回复文本 + 前置说明) */ + text?: string | null; +} + +export interface SendFailureClassification { + kind: SendFailureKind; + /** 判定所用的回复码(解析不出则为 null) */ + code: number | null; + /** 错误原文(用于 `letter_recipients.error`) */ + text: string; +} + +/** + * 从错误原文里回解回复码:优先取 `got 452`(trans-protocol 现用错误串形态), + * 其次取首个 4xx/5xx 三位码。绝不取 `expected 250` 这种期望码——否则会把 + * 「期待 250 实际 550」误读成成功码。 + */ +export function extractSmtpCode(text: string): number | null { + const got = /\bgot\s+(\d{3})\b/i.exec(text); + if (got?.[1] !== undefined) return Number(got[1]); + const any = /\b([45]\d{2})\b/.exec(text); + if (any?.[1] !== undefined) return Number(any[1]); + return null; +} + +/** + * 错误分类(补遗 §3.2.1): + * 1. 回复码优先:421/450/451/452 → throttle;550/551/553 → permanent(码比文本权威); + * 2. 无码或码不在两表内,再看关键词(含中文)→ throttle; + * 3. 其余 → other(维持主规格原有路径:计 attempts,含 `SMTP not configured` 这类配置问题)。 + */ +export function classifySendFailure( + input: SendFailureInput, +): SendFailureClassification { + const text = String(input.text ?? ""); + const code = + typeof input.code === "number" && Number.isInteger(input.code) + ? input.code + : extractSmtpCode(text); + + if (code !== null && THROTTLE_CODES.has(code)) { + return { kind: "throttle", code, text }; + } + if (code !== null && PERMANENT_CODES.has(code)) { + return { kind: "permanent", code, text }; + } + + const lower = text.toLowerCase(); + if (THROTTLE_KEYWORDS.some((word) => lower.includes(word))) { + return { kind: "throttle", code, text }; + } + + return { kind: "other", code, text }; +} + +/** `[throttle:452] 原文` / `[permanent:550] 原文` / `[other] 原文`。 */ +export function formatDeliveryError( + classification: Pick, +): string { + const tag = + classification.code === null + ? `[${classification.kind}]` + : `[${classification.kind}:${classification.code}]`; + return `${tag} ${classification.text}`; +} + +// ─── 退避时长(补遗 §3.2.2)───────────────────────────────────────────────── + +/** 退避序列:15 → 30 → 60 分钟,第 3 次之后封顶 60 分钟重复。 */ +export const THROTTLE_BACKOFF_MINUTES = [15, 30, 60] as const; + +/** `throttleAttempts` = 本次退避后的计数(从 1 起)。 */ +export function throttleBackoffMs(throttleAttempts: number): number { + const index = Math.min( + Math.max(Math.trunc(throttleAttempts), 1), + THROTTLE_BACKOFF_MINUTES.length, + ) - 1; + return THROTTLE_BACKOFF_MINUTES[index]! * 60_000; +} + +// ─── 间隔等待 / 配置校验辅助 ───────────────────────────────────────────────── + +/** 原生定时器等待;0 或负数直接返回(配置允许 interval/jitter 为 0)。 */ +export function sleepMs(ms: number): Promise { + if (!(ms > 0)) return Promise.resolve(); + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + +/** 本封与下一封之间的间隔:`interval_ms + random(0, jitter_ms)`。 */ +export function sendGapMs( + config: Pick, + random: () => number = Math.random, +): number { + const jitter = Math.floor(random() * (config.jitter_ms + 1)); + return config.interval_ms + Math.min(Math.max(jitter, 0), config.jitter_ms); +} diff --git a/worker/src/services/smtp-transport.ts b/worker/src/services/smtp-transport.ts index 5daf319..7c6500c 100644 --- a/worker/src/services/smtp-transport.ts +++ b/worker/src/services/smtp-transport.ts @@ -23,12 +23,44 @@ export interface SmtpMessage { from: string; /** Display name for the From header (optional). */ fromName?: string; + /** + * 显式 Message-ID(含尖括号)。节流补遗 §3.3 要求每收件人副本一个唯一值, + * 由 services/email.ts 生成后传下;不传时退回 ``。 + */ + messageId?: string; + /** 附加邮件头(如 `X-Someday-Letter-Id`);头名与头值里的 CRLF 会被剔除。 */ + extraHeaders?: Record; +} + +/** + * SMTP 回复码不符合预期时抛出:把回复码与原文一并带回,供限流分类 + * (services/send-throttle.ts 的 classifySendFailure)使用,不靠解析错误串猜。 + */ +export class SmtpResponseError extends Error { + readonly code: number; + readonly response: string; + + constructor(expected: number, actual: number, response: string) { + super(`SMTP: expected ${expected}, got ${actual} — ${response}`); + this.name = "SmtpResponseError"; + this.code = actual; + this.response = response; + } +} + +export interface SmtpSendResult { + success: boolean; + error?: string; + /** 失败时的 SMTP 回复码(对话层拒绝才有) */ + code?: number; + /** 失败时的 SMTP 回复原文 */ + response?: string; } export async function sendSmtpMessage( config: SmtpTransportConfig, message: SmtpMessage, -): Promise<{ success: boolean; error?: string }> { +): Promise { const from = message.from || "noreply@example.com"; const fromName = (message.fromName || "someday").replace(/[\r\n]/g, ""); const isImplicitTls = config.port === 465; @@ -63,14 +95,24 @@ export async function sendSmtpMessage( message.to, message.subject, message.html, + { messageId: message.messageId, extraHeaders: message.extraHeaders }, ); await session.quit(); return { success: true }; } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + if (err instanceof SmtpResponseError) { + return { + success: false, + error: `SMTP error: ${detail}`, + code: err.code, + response: err.response, + }; + } return { success: false, - error: `SMTP error: ${err instanceof Error ? err.message : String(err)}`, + error: `SMTP error: ${detail}`, }; } finally { await socket.close().catch(() => {}); @@ -124,6 +166,10 @@ export class SmtpSession { to: string, subject: string, html: string, + options: { + messageId?: string; + extraHeaders?: Record; + } = {}, ): Promise { await this.cmd(`MAIL FROM:<${from}>`); await this.expect(250); @@ -133,7 +179,8 @@ export class SmtpSession { await this.expect(354); const date = new Date().toUTCString(); - const msgId = `<${Date.now()}.${Math.random().toString(36).slice(2)}@post>`; + const msgId = options.messageId ?? defaultMessageId(from); + const extraHeaders = formatExtraHeaders(options.extraHeaders); const b64Body = wrapBase64(encodeUtf8Base64(html)); const encodedSubject = `=?UTF-8?B?${encodeUtf8Base64(subject)}?=`; @@ -143,6 +190,7 @@ export class SmtpSession { `Subject: ${encodedSubject}\r\n` + `Date: ${date}\r\n` + `Message-ID: ${msgId}\r\n` + + extraHeaders + `MIME-Version: 1.0\r\n` + `Content-Type: text/html; charset=UTF-8\r\n` + `Content-Transfer-Encoding: base64\r\n` + @@ -165,9 +213,7 @@ export class SmtpSession { async expect(code: number): Promise { const resp = await this.readResponse(); if (resp.code !== code) { - throw new Error( - `SMTP: expected ${code}, got ${resp.code} — ${resp.message}`, - ); + throw new SmtpResponseError(code, resp.code, resp.message); } } @@ -206,3 +252,34 @@ export function encodeUtf8Base64(str: string): string { export function wrapBase64(b64: string): string { return b64.match(/.{1,76}/g)?.join("\r\n") ?? b64; } + +/** From 地址的域名部分(拿不到时回退 localhost,避免生成 `@` 结尾的畸形 ID)。 */ +export function senderDomain(from: string): string { + const at = from.lastIndexOf("@"); + const domain = at >= 0 ? from.slice(at + 1).trim() : ""; + return domain || "localhost"; +} + +/** 未显式给 Message-ID 时的默认形态(域名取 From 地址域名,不用写死的值)。 */ +export function defaultMessageId(from: string): string { + return `<${Date.now()}.${Math.random().toString(36).slice(2)}@${senderDomain(from)}>`; +} + +const HEADER_NAME_RE = /^[A-Za-z0-9-]+$/; + +/** 附加头序列化:剔除 CRLF,非法头名直接丢弃(防头注入)。 */ +export function formatExtraHeaders( + headers: Record | undefined, +): string { + if (headers === undefined) return ""; + let out = ""; + for (const [name, value] of Object.entries(headers)) { + if (!HEADER_NAME_RE.test(name)) continue; + const clean = String(value ?? "") + .replace(/[\r\n]+/g, " ") + .trim(); + if (!clean) continue; + out += `${name}: ${clean}\r\n`; + } + return out; +} diff --git a/worker/src/services/waker-callback.ts b/worker/src/services/waker-callback.ts index 3521260..f46332f 100644 --- a/worker/src/services/waker-callback.ts +++ b/worker/src/services/waker-callback.ts @@ -8,7 +8,8 @@ // - **幂等**:executionId 由 SDK 的 D1 账本去重,落 someday 自己的 D1(`{prefix}waker_executions`, // 见 db/migrations.ts 的 schema_v2);业务层的 letterId 层状态抢占保持原样,仍是防重最终防线。 // -// 投递语义一个字都没动:批次 50、重试上限 3 次、逐收件人独立 RCPT 全在 scheduler.ts 里。 +// 投递语义(节流补遗 §3):单轮收件人上限 + 封间隔、限流退避与全局熔断、每收件人唯一 +// Message-ID,均在 scheduler.ts;本文件只负责把平台回调的超时预算传下去。 import { getTablePrefix, tbl, type Env } from "../types"; import { @@ -44,9 +45,13 @@ export type DueLettersJobOutcome = WakerJobOutcome & { stats: DeliveryStats }; export function createWakerCallbackReceiver(env: Env) { return createWakerReceiver({ jobs: { - [DUE_LETTERS_JOB]: async (): Promise => { + [DUE_LETTERS_JOB]: async (context): Promise => { // 同步跑完再返回:SDK 只在这之后回 2xx,平台据此判定本次执行成功。 - const stats = await processDueLetters(env); + // timeoutSeconds 来自平台任务策略(回调体自带),用来算本轮的时间预算: + // 不在被平台判定超时前一刻还在发信(节流补遗 §3.1.3)。 + const stats = await processDueLetters(env, { + timeoutSeconds: context.timeoutSeconds, + }); console.info("waker callback delivery run:", stats); return { stats }; }, diff --git a/worker/src/types.ts b/worker/src/types.ts index ba908bb..0a5591a 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -79,6 +79,10 @@ export interface Letter { attempts: number; last_error: string | null; sent_at: string | null; + /** 节流补遗 §3.2:限流退避的下次可尝试时刻(UTC ISO,可空);空 = 可尝试 */ + next_attempt_at: string | null; + /** 节流补遗 §3.2:限流类错误计数(不退避计入 attempts) */ + throttle_attempts: number; created_at: string; updated_at: string; } @@ -93,6 +97,8 @@ export interface LetterRecipient { status: "pending" | "sent" | "failed"; error: string | null; sent_at: string | null; + /** 节流补遗 §3.3:该副本投递时使用的 Message-ID(成功后落库,可空) */ + message_id: string | null; } export interface Contact { diff --git a/worker/test/admin-send-throttle.test.ts b/worker/test/admin-send-throttle.test.ts new file mode 100644 index 0000000..02be571 --- /dev/null +++ b/worker/test/admin-send-throttle.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from "vitest"; +import { tables } from "../src/types"; +import { + cookieHeader, + doSetup, + jsonInit, + loginAndGetCookies, + makeEnv, + request, +} from "./helpers"; + +// 发信节流参数的后台接口(节流补遗 §3.1.4):GET/PUT /api/admin/settings/send-throttle。 +// v1 不做设置页 UI,接口可改即可;写入严格校验、读取逐项回退。 + +async function adminEnv() { + const env = makeEnv(); + await doSetup(env, "admin@example.com", "adminpass123"); + const cookies = await loginAndGetCookies(env, "admin@example.com", "adminpass123"); + return { + env, + admin: cookieHeader(["access_token", cookies.access_token]), + }; +} + +async function storedConfig(env: Awaited>["env"]) { + const row = await env.DB.prepare( + `SELECT value FROM ${tables(env).system_settings} WHERE key = 'send_throttle_config'`, + ).first<{ value: string }>(); + return row === null ? null : (JSON.parse(row.value) as Record); +} + +describe("发信节流参数后台接口(节流补遗 §3.1.4)", () => { + it("未登录不可访问;GET 返回默认参数", async () => { + const { env, admin } = await adminEnv(); + expect((await request(env, "/api/admin/settings/send-throttle")).status).toBe(401); + + const res = await request(env, "/api/admin/settings/send-throttle", { + headers: admin, + }); + expect(res.status).toBe(200); + expect(res.body).toEqual({ + interval_ms: 4000, + jitter_ms: 2000, + max_recipients_per_run: 10, + }); + }); + + it("PUT 合法值 → 落库并回显;GET 读到生效值", async () => { + const { env, admin } = await adminEnv(); + + const put = await request( + env, + "/api/admin/settings/send-throttle", + jsonInit("PUT", { interval_ms: 5000, jitter_ms: 1000 }, admin), + ); + expect(put.status).toBe(200); + expect(put.body).toEqual({ + interval_ms: 5000, + jitter_ms: 1000, + max_recipients_per_run: 10, // 未提供的字段保持当前生效值 + }); + expect(await storedConfig(env)).toEqual(put.body); + + const get = await request(env, "/api/admin/settings/send-throttle", { + headers: admin, + }); + expect(get.body).toEqual(put.body); + }); + + it("PUT 非法值(负数/非整数/越界)→ 400 且不落库", async () => { + const { env, admin } = await adminEnv(); + + for (const body of [ + { interval_ms: -1 }, + { jitter_ms: 1.5 }, + { max_recipients_per_run: 0 }, + { max_recipients_per_run: 101 }, + { interval_ms: "4000" }, + ]) { + const res = await request( + env, + "/api/admin/settings/send-throttle", + jsonInit("PUT", body, admin), + ); + expect(res.status, JSON.stringify(body)).toBe(400); + } + + expect(await storedConfig(env)).toBeNull(); + }); + + it("库里被直接写坏时 GET 仍返回默认参数(读取侧宽容)", async () => { + const { env, admin } = await adminEnv(); + await env.DB.prepare( + `INSERT INTO ${tables(env).system_settings} (key, value, updated_at) + VALUES ('send_throttle_config', 'not-json', '2026-01-01')`, + ).run(); + + const res = await request(env, "/api/admin/settings/send-throttle", { + headers: admin, + }); + expect(res.status).toBe(200); + expect(res.body).toEqual({ + interval_ms: 4000, + jitter_ms: 2000, + max_recipients_per_run: 10, + }); + }); +}); diff --git a/worker/test/email.test.ts b/worker/test/email.test.ts index 7644e3d..08ccf16 100644 --- a/worker/test/email.test.ts +++ b/worker/test/email.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { makeEnv } from "./helpers"; import { tables, type Env } from "../src/types"; import { + buildMessageId, isValidEmail, isValidSmtpHost, parsePort, @@ -155,7 +156,8 @@ describe("sendEmail 输入校验(照 email-notify.ts)", () => { const result = await sendEmail(env, OPTIONS); - expect(result).toEqual({ success: true }); + expect(result.success).toBe(true); + expect(result.messageId).toBeTruthy(); expect(server.connectCalls[0].address).toEqual({ hostname: "smtp.example.com", port: 465, @@ -196,3 +198,71 @@ describe("校验工具函数", () => { expect(parsePort(undefined)).toBeNull(); }); }); + +// ─── 发信节流补遗 §3.3:每收件人唯一 Message-ID ───────────────────────────── + +describe("Message-ID(节流补遗 §3.3)", () => { + it("带 letterId/recipientId 时按 生成并带回", async () => { + const env = makeEnv(); + await setSmtpConfig(env, GOOD_CONFIG); + const server = new FakeSmtpServer(); + server.install(); + + const result = await sendEmail(env, { + ...OPTIONS, + letterId: "letter-1", + recipientId: "rec-1", + }); + + expect(result.success).toBe(true); + expect(result.messageId).toMatch( + /^$/, + ); + expect(server.message).toContain(`Message-ID: ${result.messageId}`); + expect(server.message).toContain("X-Someday-Letter-Id: letter-1"); + }); + + it("同一封信不同收件人的副本 Message-ID 不同", async () => { + const env = makeEnv(); + await setSmtpConfig(env, GOOD_CONFIG); + const server = new FakeSmtpServer(); + server.install(); + + const first = await sendEmail(env, { ...OPTIONS, letterId: "l1", recipientId: "r1" }); + const second = await sendEmail(env, { ...OPTIONS, letterId: "l1", recipientId: "r2" }); + + expect(first.messageId).not.toBe(second.messageId); + }); + + it("无信件的调用(管理员测试邮件)用通用形态、不带 X-Someday 头", async () => { + const env = makeEnv(); + await setSmtpConfig(env, GOOD_CONFIG); + const server = new FakeSmtpServer(); + server.install(); + + const result = await sendEmail(env, OPTIONS); + + expect(result.messageId).toMatch(/^<[^@]+@example\.com>$/); + expect(server.message).not.toContain("X-Someday-Letter-Id"); + }); + + it("buildMessageId:id 含非法字符时退回通用形态(防头注入)", () => { + expect(buildMessageId("a@b.com", "l1", "r1")).toMatch(/^$/); + expect(buildMessageId("a@b.com", "l\r\n1", "r1")).toMatch(/^<[^@]+@b\.com>$/); + expect(buildMessageId("a@b.com")).toMatch(/^<[^@]+@b\.com>$/); + }); + + it("限流类拒收(452)把 code/response 带到上层,供分类使用", async () => { + const env = makeEnv(); + await setSmtpConfig(env, GOOD_CONFIG); + const server = new FakeSmtpServer({ recipientReject: "452 4.7.0 too many messages" }); + server.install(); + + const result = await sendEmail(env, OPTIONS); + + expect(result.success).toBe(false); + expect(result.code).toBe(452); + expect(result.response).toBe("4.7.0 too many messages"); + expect(result.messageId).toBeUndefined(); + }); +}); diff --git a/worker/test/fake-smtp.ts b/worker/test/fake-smtp.ts index 0c25f71..2a16529 100644 --- a/worker/test/fake-smtp.ts +++ b/worker/test/fake-smtp.ts @@ -6,6 +6,8 @@ export interface FakeSmtpOptions { supportsStartTls?: boolean; rejectAuth?: boolean; rejectRecipient?: boolean; + /** 覆盖 RCPT TO 的回复行(如 `452 4.7.0 too many messages`,造限流类临时拒收)。 */ + recipientReject?: string; } export class FakeSmtpServer { @@ -135,7 +137,8 @@ export class FakeSmtpServer { } if (upper.startsWith("RCPT TO")) { this.push( - this.opts.rejectRecipient ? "550 5.1.1 no such user" : "250 2.1.5 ok", + this.opts.recipientReject ?? + (this.opts.rejectRecipient ? "550 5.1.1 no such user" : "250 2.1.5 ok"), ); return; } diff --git a/worker/test/helpers.ts b/worker/test/helpers.ts index 5e1c3b2..fdf3006 100644 --- a/worker/test/helpers.ts +++ b/worker/test/helpers.ts @@ -7,6 +7,7 @@ import { import { getTablePrefix, migrationsTable, + tables, type Env, } from "../src/types"; @@ -84,6 +85,41 @@ export function jsonInit( }; } +/** + * 写入发信节流参数(`{prefix}system_settings.send_throttle_config`)。 + * 单测默认把间隔归零(否则一次多收件人投递要真等 4–6 秒),需要验证间隔的用例自行覆盖。 + */ +export async function setSendThrottleConfig( + env: Env, + config: Partial<{ + interval_ms: number; + jitter_ms: number; + max_recipients_per_run: number; + }> = {}, +): Promise { + const value = { + interval_ms: 0, + jitter_ms: 0, + max_recipients_per_run: 10, + ...config, + }; + await setRawSetting(env, "send_throttle_config", JSON.stringify(value)); +} + +/** 直接写任意 `system_settings` 键(用例里造熔断时刻等)。 */ +export async function setRawSetting( + env: Env, + key: string, + value: string, +): Promise { + await env.DB.prepare( + `INSERT INTO ${tables(env).system_settings} (key, value, updated_at) VALUES (?, ?, '2026-01-01') + ON CONFLICT(key) DO UPDATE SET value = excluded.value`, + ) + .bind(key, value) + .run(); +} + /** 从 Set-Cookie 里取出指定 cookie 值 */ export function cookieValue(res: Response, name: string): string | undefined { const cookies = res.headers.getSetCookie(); diff --git a/worker/test/letters.test.ts b/worker/test/letters.test.ts index 3f13f6f..45fa57f 100644 --- a/worker/test/letters.test.ts +++ b/worker/test/letters.test.ts @@ -328,6 +328,36 @@ describe("letters CRUD 与状态流转(ONE-176)", () => { expect(resend.body.last_error).toBeNull(); }); + it("resend 同时清空限流退避状态(next_attempt_at / throttle_attempts)", async () => { + const { env, user } = await setupWithUser(); + + const failedLetter = await request(env, "/api/letters", jsonInit("POST", payload(), user)); + await env.DB.prepare( + `UPDATE ${tables(env).letters} + SET status = 'failed', attempts = 0, throttle_attempts = 2, + next_attempt_at = '2999-01-01T00:00:00.000Z', + last_error = '[throttle:452] too many' + WHERE id = ?`, + ) + .bind(failedLetter.body.id) + .run(); + + const resend = await request(env, `/api/letters/${failedLetter.body.id}/resend`, { + method: "POST", + headers: user, + }); + expect(resend.status).toBe(200); + expect(resend.body.status).toBe("scheduled"); + + const row = await env.DB.prepare( + `SELECT next_attempt_at, throttle_attempts FROM ${tables(env).letters} WHERE id = ?`, + ) + .bind(failedLetter.body.id) + .first<{ next_attempt_at: string | null; throttle_attempts: number }>(); + expect(row!.next_attempt_at).toBeNull(); + expect(row!.throttle_attempts).toBe(0); + }); + it("PATCH is_public 任何状态可切(sent 信关闭即时下墙)", async () => { const { env, user } = await setupWithUser(); const created = await request(env, "/api/letters", jsonInit("POST", payload(), user)); diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index af1524a..1226846 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -76,7 +76,7 @@ describe("migrationsTable() 命名三态", () => { // ─── runner 语义 ───────────────────────────────────────────────────────────── describe("runMigrations(空库首跑 / 重跑)", () => { - it("空库首跑:全部 applied,账本按序记下 schema_v1 / schema_v2,表与索引建好", async () => { + it("空库首跑:全部 applied,账本按序记下 schema_v1–schema_v6,表与索引建好", async () => { const { env, sqlite } = emptyEnv(); const result = await runMigrations(env); @@ -84,11 +84,15 @@ describe("runMigrations(空库首跑 / 重跑)", () => { expect(result.migrations).toEqual([ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, + { name: "schema_v5", status: "applied" }, + { name: "schema_v6", status: "applied" }, ]); // 账本按序记下两条迁移 expect(tableNames(sqlite)).toContain("_post_schema_migrations"); - expect(ledgerNames(sqlite, "post_")).toEqual(["schema_v1", "schema_v2"]); + expect(ledgerNames(sqlite, "post_")).toEqual(["schema_v1", "schema_v2", "schema_v3", "schema_v4", "schema_v5", "schema_v6"]); // 业务表 + 索引都建出来了 const names = tableNames(sqlite); @@ -111,9 +115,24 @@ describe("runMigrations(空库首跑 / 重跑)", () => { expect(indexes.sort()).toEqual([ "idx_post_contacts_user_email", "idx_post_letter_recipients_letter", + "idx_post_letters_status_next_attempt", "idx_post_letters_status_send_at", "idx_post_letters_user_status", ]); + + // schema_v3–v6:节流补遗的新列(迁移后用 PRAGMA 核实列真实存在) + const letterCols = sqlite.db + .prepare("PRAGMA table_info(post_letters)") + .all() + .map((r) => (r as { name: string }).name); + expect(letterCols).toEqual( + expect.arrayContaining(["next_attempt_at", "throttle_attempts"]), + ); + const recipientCols = sqlite.db + .prepare("PRAGMA table_info(post_letter_recipients)") + .all() + .map((r) => (r as { name: string }).name); + expect(recipientCols).toContain("message_id"); }); it("第二跑:全部 skipped,且 schema 无任何变化", async () => { @@ -124,20 +143,24 @@ describe("runMigrations(空库首跑 / 重跑)", () => { expect(result.migrations).toEqual([ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "skipped" }, + { name: "schema_v5", status: "skipped" }, + { name: "schema_v6", status: "skipped" }, ]); expect(schemaSnapshot(sqlite)).toBe(before); - expect(ledgerNames(sqlite, "post_")).toEqual(["schema_v1", "schema_v2"]); + expect(ledgerNames(sqlite, "post_")).toEqual(["schema_v1", "schema_v2", "schema_v3", "schema_v4", "schema_v5", "schema_v6"]); }); it("自定义前缀与显式空前缀同样走账本", async () => { const custom = await emptyEnv("kp_"); expect((await runMigrations(custom.env)).prefix).toBe("kp_"); - expect(ledgerNames(custom.sqlite, "kp_")).toEqual(["schema_v1", "schema_v2"]); + expect(ledgerNames(custom.sqlite, "kp_")).toEqual(["schema_v1", "schema_v2", "schema_v3", "schema_v4", "schema_v5", "schema_v6"]); const none = await emptyEnv(""); expect((await runMigrations(none.env)).prefix).toBe(""); expect(tableNames(none.sqlite)).toContain("_schema_migrations"); - expect(ledgerNames(none.sqlite, "")).toEqual(["schema_v1", "schema_v2"]); + expect(ledgerNames(none.sqlite, "")).toEqual(["schema_v1", "schema_v2", "schema_v3", "schema_v4", "schema_v5", "schema_v6"]); expect(tableNames(none.sqlite)).toContain("users"); }); }); @@ -177,6 +200,10 @@ describe("runMigrations 防静默切换(前缀冲突)", () => { expect(result.migrations).toEqual([ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "skipped" }, + { name: "schema_v5", status: "skipped" }, + { name: "schema_v6", status: "skipped" }, ]); }); @@ -196,6 +223,10 @@ describe("runMigrations 防静默切换(前缀冲突)", () => { expect(result.migrations).toEqual([ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, + { name: "schema_v5", status: "applied" }, + { name: "schema_v6", status: "applied" }, ]); }); }); diff --git a/worker/test/scheduler.test.ts b/worker/test/scheduler.test.ts index 9671165..b03ca62 100644 --- a/worker/test/scheduler.test.ts +++ b/worker/test/scheduler.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { makeEnv } from "./helpers"; -import { tables, type Env, type Letter } from "../src/types"; +import { makeEnv, setRawSetting, setSendThrottleConfig } from "./helpers"; +import { tables, type Env, type Letter, type LetterRecipient } from "../src/types"; import { buildLetterHtml, deliverLetter, processDueLetters } from "../src/services/scheduler"; const sendEmailMock = vi.hoisted(() => vi.fn()); @@ -58,10 +58,37 @@ async function recipientsOf(env: Env, letterId: string) { `SELECT * FROM ${tables(env).letter_recipients} WHERE letter_id = ? ORDER BY id ASC`, ) .bind(letterId) - .all<{ id: string; email: string; status: string; error: string | null }>(); + .all(); return res.results; } +/** 把「现在」写成 24 小时窗口内的 send_at(限流退避用例必须如此,否则退避直接超窗置 failed)。 */ +function recentSendAt(): string { + return new Date().toISOString(); +} + +/** 解除熔断:把 send_paused_until 写成过去时刻(等价于熔断期过完)。 */ +async function clearPause(env: Env): Promise { + await setRawSetting(env, "send_paused_until", "2000-01-01T00:00:00.000Z"); +} + +/** 把某封信的退避时刻挪到过去(等价于 next_attempt_at 已过期)。 */ +async function makeLetterDue(env: Env, letterId: string): Promise { + await env.DB.prepare( + `UPDATE ${tables(env).letters} SET next_attempt_at = '2000-01-01T00:00:00.000Z' WHERE id = ?`, + ) + .bind(letterId) + .run(); +} + +/** 452 限流类失败(经发送层带回回复码与原文)。 */ +const THROTTLE_RESULT = { + success: false, + error: "SMTP error: expected 250, got 452 — 4.7.0 too many messages", + code: 452, + response: "4.7.0 too many messages", +}; + beforeEach(() => { sendEmailMock.mockReset(); }); @@ -121,6 +148,7 @@ describe("processDueLetters 抢占(SPEC §5)", () => { describe("逐收件人投递(互不可见)", () => { it("每个收件人独立发一封,正文不含其他收件人地址", async () => { const env = makeEnv(); + await setSendThrottleConfig(env); await seedLetter(env, [ { id: "r1", email: "alice@example.com" }, { id: "r2", email: "bob@example.com" }, @@ -153,6 +181,7 @@ describe("逐收件人投递(互不可见)", () => { describe("部分失败与重试", () => { it("部分失败:失败者记 error,信回 scheduled + attempts+1,下个周期只补发失败收件人", async () => { const env = makeEnv(); + await setSendThrottleConfig(env); await seedLetter(env, [ { id: "r1", email: "bad@example.com" }, { id: "r2", email: "good@example.com" }, @@ -207,7 +236,7 @@ describe("部分失败与重试", () => { expect(letter!.attempts).toBe(2); const stats = await processDueLetters(env); // attempts 3 → failed - expect(stats.gaveUp).toBe(1); + expect(stats.failed).toBe(1); letter = await letterById(env, "l1"); expect(letter!.status).toBe("failed"); expect(letter!.attempts).toBe(3); @@ -271,3 +300,383 @@ describe("buildLetterHtml 模板", () => { expect(html).toContain("这封信写于 2024-05-06,由时光邮局送达"); }); }); + +// ─── 发信节流补遗 §3.1:单轮上限 + 间隔 ───────────────────────────────────── + +async function seedLettersWithCounts( + env: Env, + groups: { id: string; count: number; send_at?: string }[], +): Promise { + for (const group of groups) { + await seedLetter( + env, + Array.from({ length: group.count }, (_, i) => ({ + id: `${group.id}-r${i + 1}`, + email: `${group.id}-r${i + 1}@example.com`, + })), + { id: group.id, send_at: group.send_at ?? PAST }, + ); + } +} + +describe("节流:单轮收件人上限(补遗 §3.1.2)", () => { + it("25 个收件人同刻到期 → 首轮恰 10 封,余者仍 scheduled,逐轮补完且不重复", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env, { max_recipients_per_run: 10 }); + await seedLettersWithCounts(env, [ + { id: "l1", count: 10 }, + { id: "l2", count: 10 }, + { id: "l3", count: 5 }, + ]); + sendEmailMock.mockResolvedValue({ success: true, messageId: "" }); + + const first = await processDueLetters(env, { timeoutSeconds: 120 }); + expect(first.scanned).toBe(3); + expect(first.claimed).toBe(1); + expect(first.delivered).toBe(1); + expect(first.deferred_by_cap).toBe(15); + expect(sendEmailMock).toHaveBeenCalledTimes(10); + expect((await letterById(env, "l1"))!.status).toBe("sent"); + expect((await letterById(env, "l2"))!.status).toBe("scheduled"); + expect((await letterById(env, "l3"))!.status).toBe("scheduled"); + + const second = await processDueLetters(env, { timeoutSeconds: 120 }); + expect(second.delivered).toBe(1); + expect(second.deferred_by_cap).toBe(5); + expect(sendEmailMock).toHaveBeenCalledTimes(20); + + const third = await processDueLetters(env, { timeoutSeconds: 120 }); + expect(third.delivered).toBe(1); + expect(third.deferred_by_cap).toBe(0); + expect(sendEmailMock).toHaveBeenCalledTimes(25); + + // 无一封重复 + const sent = sendEmailMock.mock.calls.map((c) => c[1].to as string); + expect(new Set(sent).size).toBe(25); + expect((await letterById(env, "l3"))!.status).toBe("sent"); + }); + + it("相邻两封的实际发送间隔 ≥ interval_ms(以发送时刻计)", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env, { interval_ms: 4000, jitter_ms: 0 }); + await seedLetter( + env, + [ + { id: "r1", email: "a@example.com" }, + { id: "r2", email: "b@example.com" }, + { id: "r3", email: "c@example.com" }, + ], + { id: "l1" }, + ); + + const stamps: number[] = []; + sendEmailMock.mockImplementation(async () => { + stamps.push(Date.now()); + return { success: true, messageId: "" }; + }); + + vi.useFakeTimers(); + try { + const run = processDueLetters(env, { timeoutSeconds: 120 }); + await vi.advanceTimersByTimeAsync(30_000); + await run; + } finally { + vi.useRealTimers(); + } + + expect(stamps).toHaveLength(3); + expect(stamps[1]! - stamps[0]!).toBeGreaterThanOrEqual(4000); + expect(stamps[2]! - stamps[1]!).toBeGreaterThanOrEqual(4000); + }); + + it("运行预算不足时不再抢占:首封仍发,其余按上限顺延", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env); + await seedLettersWithCounts(env, [ + { id: "l1", count: 1 }, + { id: "l2", count: 1 }, + { id: "l3", count: 1 }, + ]); + sendEmailMock.mockResolvedValue({ success: true, messageId: "" }); + + const stats = await processDueLetters(env, { timeoutSeconds: 1 }); + + expect(stats.claimed).toBe(1); + expect(sendEmailMock).toHaveBeenCalledTimes(1); + expect(stats.deferred_by_cap).toBe(2); + expect((await letterById(env, "l2"))!.status).toBe("scheduled"); + expect((await letterById(env, "l3"))!.status).toBe("scheduled"); + }); +}); + +describe("节流:半发续发(补遗 §3.1.2)", () => { + it("一封 15 收件人:首轮发满上限后信不卡 sending,下轮只补剩余 5 人", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env, { max_recipients_per_run: 10 }); + await seedLettersWithCounts(env, [{ id: "l1", count: 15 }]); + sendEmailMock.mockResolvedValue({ success: true, messageId: "" }); + + const first = await processDueLetters(env, { timeoutSeconds: 120 }); + expect(sendEmailMock).toHaveBeenCalledTimes(10); + expect(first.deferred_by_cap).toBe(5); + let letter = await letterById(env, "l1"); + expect(letter!.status).toBe("scheduled"); + expect(letter!.attempts).toBe(0); // 顺延不算失败 + + const second = await processDueLetters(env, { timeoutSeconds: 120 }); + expect(sendEmailMock).toHaveBeenCalledTimes(15); + letter = await letterById(env, "l1"); + expect(letter!.status).toBe("sent"); + + const sent = sendEmailMock.mock.calls.map((c) => c[1].to as string); + expect(new Set(sent).size).toBe(15); + const recipients = await recipientsOf(env, "l1"); + expect(recipients.every((r) => r.status === "sent")).toBe(true); + }); +}); + +// ─── 发信节流补遗 §3.2:限流退避 + 全局熔断 ──────────────────────────────── + +describe("限流退避与熔断(补遗 §3.2)", () => { + it("452 → attempts 不变、throttle_attempts+1、next_attempt_at≈+15 分钟、本轮停手", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env); + const base = Date.now(); + await seedLetter(env, [{ id: "r1", email: "a@example.com" }], { + id: "l1", + send_at: new Date(base - 3000).toISOString(), + }); + await seedLetter(env, [{ id: "r2", email: "b@example.com" }], { + id: "l2", + send_at: new Date(base - 2000).toISOString(), + }); + await seedLetter(env, [{ id: "r3", email: "c@example.com" }], { + id: "l3", + send_at: new Date(base - 1000).toISOString(), + }); + sendEmailMock.mockImplementation(async (_env: Env, o: { to: string }) => + o.to === "b@example.com" ? THROTTLE_RESULT : { success: true, messageId: "" }, + ); + + const startedAt = Date.now(); + const first = await processDueLetters(env, { timeoutSeconds: 120 }); + + expect(first.throttled).toBe(1); + expect(first.paused_until).toBeTruthy(); + expect(sendEmailMock).toHaveBeenCalledTimes(2); // l1 一发 + l2 命中限流后停手 + const l2 = await letterById(env, "l2"); + expect(l2!.status).toBe("scheduled"); + expect(l2!.attempts).toBe(0); // 退避不烧 attempts + expect(l2!.throttle_attempts).toBe(1); + const backoff = Date.parse(l2!.next_attempt_at!) - startedAt; + expect(backoff).toBeGreaterThanOrEqual(14 * 60_000); + expect(backoff).toBeLessThanOrEqual(16 * 60_000); + expect(l2!.last_error).toContain("[throttle:452]"); + // 熔断后同轮不再抢占后面的信 + expect((await letterById(env, "l3"))!.status).toBe("scheduled"); + + const throttledRecipient = (await recipientsOf(env, "l2"))[0]!; + expect(throttledRecipient.status).toBe("failed"); + expect(throttledRecipient.error).toContain("[throttle:452]"); + expect(throttledRecipient.message_id).toBeNull(); + + // 熔断期内再触发:零发送,只带 paused_until 回来 + sendEmailMock.mockClear(); + const second = await processDueLetters(env, { timeoutSeconds: 120 }); + expect(sendEmailMock).not.toHaveBeenCalled(); + expect(second.scanned).toBe(0); + expect(second.paused_until).toBe(first.paused_until); + }); + + it("单封信部分收件人命中限流:已成功者不重发,未发/命中者退避后补发", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env); + await seedLetter( + env, + [ + { id: "r1", email: "a@example.com" }, + { id: "r2", email: "b@example.com" }, + { id: "r3", email: "c@example.com" }, + ], + { id: "l1", send_at: recentSendAt() }, + ); + sendEmailMock.mockImplementation(async (_env: Env, o: { to: string }) => + o.to === "b@example.com" ? THROTTLE_RESULT : { success: true, messageId: "" }, + ); + + await processDueLetters(env, { timeoutSeconds: 120 }); + // 命中限流即停:a 已发成功、b 记限流、c 还没发 + expect(sendEmailMock).toHaveBeenCalledTimes(2); + let rows = await recipientsOf(env, "l1"); + expect(rows.find((r) => r.id === "r1")!.status).toBe("sent"); + expect(rows.find((r) => r.id === "r2")!.status).toBe("failed"); + expect(rows.find((r) => r.id === "r3")!.status).toBe("pending"); + expect((await letterById(env, "l1"))!.status).toBe("scheduled"); + + // 退避过后:只补 b、c,a 不重发 + await clearPause(env); + await makeLetterDue(env, "l1"); + sendEmailMock.mockClear(); + sendEmailMock.mockResolvedValue({ success: true, messageId: "" }); + const stats = await processDueLetters(env, { timeoutSeconds: 120 }); + + expect(stats.delivered).toBe(1); + const resent = sendEmailMock.mock.calls.map((c) => c[1].to as string).sort(); + expect(resent).toEqual(["b@example.com", "c@example.com"]); + rows = await recipientsOf(env, "l1"); + expect(rows.every((r) => r.status === "sent")).toBe(true); + expect((await letterById(env, "l1"))!.status).toBe("sent"); + }); + + it("退避期过后自动补发成功,并清空 throttle_attempts / next_attempt_at", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env); + await seedLetter(env, [{ id: "r1", email: "a@example.com" }], { id: "l1", send_at: recentSendAt() }); + sendEmailMock.mockResolvedValue(THROTTLE_RESULT); + + await processDueLetters(env, { timeoutSeconds: 120 }); + expect((await letterById(env, "l1"))!.throttle_attempts).toBe(1); + + await clearPause(env); + await makeLetterDue(env, "l1"); + sendEmailMock.mockResolvedValue({ success: true, messageId: "" }); + + const stats = await processDueLetters(env, { timeoutSeconds: 120 }); + expect(stats.delivered).toBe(1); + const letter = await letterById(env, "l1"); + expect(letter!.status).toBe("sent"); + expect(letter!.throttle_attempts).toBe(0); + expect(letter!.next_attempt_at).toBeNull(); + }); + + it("连续命中:退避 15 → 30 → 60 分钟,之后封顶 60 分钟", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env); + await seedLetter(env, [{ id: "r1", email: "a@example.com" }], { id: "l1", send_at: recentSendAt() }); + sendEmailMock.mockResolvedValue(THROTTLE_RESULT); + + const minutes: number[] = []; + for (let round = 0; round < 4; round++) { + await clearPause(env); + await makeLetterDue(env, "l1"); + const startedAt = Date.now(); + await processDueLetters(env, { timeoutSeconds: 120 }); + const letter = await letterById(env, "l1"); + minutes.push(Math.round((Date.parse(letter!.next_attempt_at!) - startedAt) / 60_000)); + } + + expect(minutes).toEqual([15, 30, 60, 60]); + }); + + it("退避时刻超过 send_at + 24 小时 → 直接置 failed 并注明限流超时", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env); + const sendAt = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(); + await seedLetter(env, [{ id: "r1", email: "a@example.com" }], { id: "l1", send_at: sendAt }); + sendEmailMock.mockResolvedValue(THROTTLE_RESULT); + + const stats = await processDueLetters(env, { timeoutSeconds: 120 }); + + const letter = await letterById(env, "l1"); + expect(letter!.status).toBe("failed"); + expect(letter!.attempts).toBe(0); + expect(letter!.throttle_attempts).toBe(1); + expect(letter!.last_error).toContain("限流退避"); + expect(stats.failed).toBe(1); + }); +}); + +describe("永久错误不退避(补遗 §3.2.1)", () => { + it("550 → 计 attempts、不触发熔断、同轮其他信照发", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env); + await seedLetter(env, [{ id: "r1", email: "gone@example.com" }], { id: "l1" }); + await seedLetter(env, [{ id: "r2", email: "ok@example.com" }], { id: "l2" }); + sendEmailMock.mockImplementation(async (_env: Env, o: { to: string }) => + o.to === "gone@example.com" + ? { + success: false, + error: "SMTP error: expected 250, got 550 — 5.1.1 no such user", + code: 550, + response: "5.1.1 no such user", + } + : { success: true, messageId: "" }, + ); + + const stats = await processDueLetters(env, { timeoutSeconds: 120 }); + + expect(stats.paused_until).toBeNull(); + expect(stats.throttled).toBe(0); + expect(stats.delivered).toBe(1); + expect(sendEmailMock).toHaveBeenCalledTimes(2); + const failedLetter = await letterById(env, "l1"); + expect(failedLetter!.status).toBe("scheduled"); + expect(failedLetter!.attempts).toBe(1); + expect(failedLetter!.throttle_attempts).toBe(0); + expect(failedLetter!.next_attempt_at).toBeNull(); + expect(failedLetter!.last_error).toContain("[permanent:550]"); + expect((await letterById(env, "l2"))!.status).toBe("sent"); + }); +}); + +// ─── 发信节流补遗 §3.3:Message-ID 与信件编号 ────────────────────────────── + +describe("Message-ID 与落款(补遗 §3.3)", () => { + it("同一封信两个收件人:Message-ID 不同且都已落库", async () => { + const env = makeEnv(); + await setSendThrottleConfig(env); + await seedLetter( + env, + [ + { id: "r1", email: "a@example.com" }, + { id: "r2", email: "b@example.com" }, + ], + { id: "l1" }, + ); + sendEmailMock.mockImplementation( + async (_env: Env, o: { letterId?: string; recipientId?: string }) => ({ + success: true, + messageId: ``, + }), + ); + + await processDueLetters(env, { timeoutSeconds: 120 }); + + // 信件/收件人 id 传给了发送层(Message-ID 由 email.ts 据此生成) + const call = sendEmailMock.mock.calls[0]![1] as { letterId?: string; recipientId?: string }; + expect(call.letterId).toBe("l1"); + expect(call.recipientId).toBe("r1"); + + const recipients = await recipientsOf(env, "l1"); + const ids = recipients.map((r) => r.message_id).filter((v): v is string => !!v); + expect(ids).toHaveLength(2); + expect(new Set(ids).size).toBe(2); + }); + + it("落款追加信件编号(不改用户正文与标题)", () => { + const letter = { + id: "l-no-1", + user_id: "u1", + title: "标题", + body_html: "

正文

", + body_json: "", + send_at: PAST, + timezone: "Asia/Shanghai", + status: "scheduled", + is_public: 0, + attempts: 0, + last_error: null, + sent_at: null, + next_attempt_at: null, + throttle_attempts: 0, + created_at: "2024-05-06T10:00:00.000Z", + updated_at: "2026-01-01", + } as Letter; + + const html = buildLetterHtml(letter); + expect(html).toContain("这封信写于 2024-05-06,由时光邮局送达"); + expect(html).toContain("信件编号:l-no-1"); + expect(html).toContain("

正文

"); + expect(html).toContain("

标题

"); + }); +}); diff --git a/worker/test/schema.test.ts b/worker/test/schema.test.ts index 378580f..5e01705 100644 --- a/worker/test/schema.test.ts +++ b/worker/test/schema.test.ts @@ -88,6 +88,8 @@ describe("schema_v1 迁移(历史塌缩后的最终 schema)", () => { it("按生效前缀参数化表名(不含裸表名)", () => { const sql = schemaSql("post_"); + // 迁移里不含裸表名/裸索引名 + expect(sql).not.toMatch(/ALTER TABLE (letters|letter_recipients)\b/); expect(sql).not.toMatch( /CREATE TABLE IF NOT EXISTS (users|user_2fa|letters|letter_recipients|contacts|system_settings)[ (]/, ); @@ -119,14 +121,32 @@ describe("schema_v1 迁移(历史塌缩后的最终 schema)", () => { expect(names("index", true)).toEqual([ "idx_post_contacts_user_email", "idx_post_letter_recipients_letter", + "idx_post_letters_status_next_attempt", "idx_post_letters_status_send_at", "idx_post_letters_user_status", ]); }); - it("幂等(CREATE IF NOT EXISTS 可重复执行)", () => { - const db = freshDb("post_"); - expect(() => db.exec(schemaSql("post_"))).not.toThrow(); + it("schema_v1 的建表语句可重复执行;增量 ALTER 列由账本保证只跑一次", () => { + const v1 = getMigrations("post_")[0]!; + const db = new DatabaseSync(":memory:"); + db.exec("PRAGMA foreign_keys = ON"); + db.exec(v1.sql); + expect(() => db.exec(v1.sql)).not.toThrow(); + + // ALTER TABLE ADD COLUMN 本身不幂等 —— 幂等由迁移账本承担 + // (见 migrations.test.ts 的「第二跑:全部 skipped,且 schema 无任何变化」)。 + const incremental = getMigrations("post_").slice(1); + expect(incremental.map((m) => m.name)).toEqual([ + "schema_v2", + "schema_v3", + "schema_v4", + "schema_v5", + "schema_v6", + ]); + for (const migration of incremental) { + expect(migration.sql.trim().endsWith(";")).toBe(true); + } }); it("外键级联与 CHECK 约束在带前缀建表下仍生效", () => { @@ -160,6 +180,10 @@ describe("迁移建出的表名与 queries 引用的表名一致", () => { expect(result.migrations).toEqual([ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, + { name: "schema_v5", status: "applied" }, + { name: "schema_v6", status: "applied" }, ]); const created = (env.DB as unknown as SqliteD1).db diff --git a/worker/test/send-throttle.test.ts b/worker/test/send-throttle.test.ts new file mode 100644 index 0000000..6152893 --- /dev/null +++ b/worker/test/send-throttle.test.ts @@ -0,0 +1,224 @@ +import { describe, expect, it, vi } from "vitest"; +import { makeEnv, setRawSetting } from "./helpers"; +import { + DEFAULT_SEND_THROTTLE_CONFIG, + SEND_THROTTLE_LIMITS, + classifySendFailure, + extractSmtpCode, + formatDeliveryError, + parseSendThrottleConfig, + readSendThrottleConfig, + sendGapMs, + sleepMs, + throttleBackoffMs, + validateSendThrottleField, +} from "../src/services/send-throttle"; + +// 发信节流补遗 §3.1.4 / §3.2.1:配置回退、限流分类、退避序列。 + +describe("节流配置解析与回退(补遗 §3.1.4)", () => { + it("缺失 → 全默认值,且不产生 issues", () => { + const parsed = parseSendThrottleConfig(null); + expect(parsed.config).toEqual(DEFAULT_SEND_THROTTLE_CONFIG); + expect(parsed.issues).toEqual([]); + expect(parsed.invalidJson).toBe(false); + }); + + it("默认值与补遗 §3.1.3 的表格逐项一致", () => { + expect(DEFAULT_SEND_THROTTLE_CONFIG).toEqual({ + interval_ms: 4000, + jitter_ms: 2000, + max_recipients_per_run: 10, + }); + expect(SEND_THROTTLE_LIMITS).toEqual({ + interval_ms: { min: 0, max: 30_000 }, + jitter_ms: { min: 0, max: 10_000 }, + max_recipients_per_run: { min: 1, max: 100 }, + }); + }); + + it("字段缺失 → 该项回默认(不算问题)", () => { + const parsed = parseSendThrottleConfig(JSON.stringify({ interval_ms: 1000 })); + expect(parsed.config.interval_ms).toBe(1000); + expect(parsed.config.jitter_ms).toBe(DEFAULT_SEND_THROTTLE_CONFIG.jitter_ms); + expect(parsed.config.max_recipients_per_run).toBe( + DEFAULT_SEND_THROTTLE_CONFIG.max_recipients_per_run, + ); + expect(parsed.issues).toEqual([]); + }); + + it("非法值(负数 / 越界 / 小数 / 字符串)逐项回默认并记 issue", () => { + const parsed = parseSendThrottleConfig( + JSON.stringify({ + interval_ms: -1, + jitter_ms: "2000", + max_recipients_per_run: 1.5, + }), + ); + expect(parsed.config).toEqual(DEFAULT_SEND_THROTTLE_CONFIG); + expect(parsed.issues.map((i) => i.key)).toEqual([ + "interval_ms", + "jitter_ms", + "max_recipients_per_run", + ]); + }); + + it("整段不是 JSON 对象 → invalidJson + 全默认", () => { + for (const raw of ["not json", "[]", "42", "null"]) { + const parsed = parseSendThrottleConfig(raw); + expect(parsed.invalidJson).toBe(true); + expect(parsed.config).toEqual(DEFAULT_SEND_THROTTLE_CONFIG); + } + }); + + it("readSendThrottleConfig:库里值合法则生效,写坏则回默认并 warn", async () => { + const env = makeEnv(); + await setRawSetting( + env, + "send_throttle_config", + JSON.stringify({ interval_ms: 1500, jitter_ms: 500, max_recipients_per_run: 3 }), + ); + expect(await readSendThrottleConfig(env.DB, "post_")).toEqual({ + interval_ms: 1500, + jitter_ms: 500, + max_recipients_per_run: 3, + }); + + await setRawSetting(env, "send_throttle_config", JSON.stringify({ interval_ms: -5 })); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(await readSendThrottleConfig(env.DB, "post_")).toEqual( + DEFAULT_SEND_THROTTLE_CONFIG, + ); + expect(warn).toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } + }); + + it("validateSendThrottleField:接受范围内整数、拒绝其余", () => { + expect(validateSendThrottleField("interval_ms", 0)).toBe(0); + expect(validateSendThrottleField("interval_ms", 30_000)).toBe(30_000); + expect(validateSendThrottleField("interval_ms", 30_001)).toBeNull(); + expect(validateSendThrottleField("interval_ms", 1.2)).toBeNull(); + expect(validateSendThrottleField("interval_ms", "1000")).toBeNull(); + expect(validateSendThrottleField("max_recipients_per_run", 0)).toBeNull(); + expect(validateSendThrottleField("max_recipients_per_run", 100)).toBe(100); + expect(validateSendThrottleField("jitter_ms", 10_001)).toBeNull(); + }); +}); + +describe("限流分类(补遗 §3.2.1)", () => { + it("限流类回复码 421/450/451/452 → throttle", () => { + for (const code of [421, 450, 451, 452]) { + const result = classifySendFailure({ code, text: `SMTP error: got ${code}` }); + expect(result.kind).toBe("throttle"); + expect(result.code).toBe(code); + } + }); + + it("永久类回复码 550/551/553 → permanent", () => { + for (const code of [550, 551, 553]) { + expect(classifySendFailure({ code, text: `SMTP error: got ${code}` }).kind).toBe( + "permanent", + ); + } + }); + + it("没有回复码时按关键词判定限流(含中文),大小写不敏感", () => { + const cases = [ + "Rate limited, try later", + "TOO MANY connections", + "Too Frequent", + "service TEMPORARILY unavailable", + "发送过于频繁", + "触发限流", + "已超过上限", + ]; + for (const text of cases) { + const result = classifySendFailure({ text }); + expect(result.kind, text).toBe("throttle"); + expect(result.code).toBeNull(); + } + }); + + it("配置类/地址类错误维持原路径(other),不退避", () => { + for (const text of [ + "SMTP not configured", + "Invalid recipient email address", + "SMTP error: auth failed", + "SMTP: connection closed unexpectedly", + ]) { + expect(classifySendFailure({ text }).kind, text).toBe("other"); + } + }); + + it("从错误原文回解回复码:取 got 后的码,不把 expected 250 当结果", () => { + expect(extractSmtpCode("SMTP: expected 250, got 452 — too many")).toBe(452); + expect(extractSmtpCode("SMTP: expected 250, got 550 — no such user")).toBe(550); + expect(extractSmtpCode("452 4.7.0 too many recipients")).toBe(452); + expect(extractSmtpCode("SMTP not configured")).toBeNull(); + // expected 250 + 无 got:不能被当成 250 命中分类表 + expect(classifySendFailure({ text: "SMTP: expected 250, got something odd" }).kind).toBe( + "other", + ); + }); + + it("回归口径:旧测试里的 550 / 4xx 错误串仍被正确分类", () => { + expect( + classifySendFailure({ text: "SMTP error: expected 250, got 550 — no such user" }).kind, + ).toBe("permanent"); + expect( + classifySendFailure({ text: "SMTP error: expected 250, got 452 — try later" }).kind, + ).toBe("throttle"); + }); + + it("error 前缀:带码与不带码两种形态", () => { + expect( + formatDeliveryError(classifySendFailure({ code: 452, text: "too many" })), + ).toBe("[throttle:452] too many"); + expect( + formatDeliveryError(classifySendFailure({ text: "SMTP not configured" })), + ).toBe("[other] SMTP not configured"); + }); +}); + +describe("退避与等待(补遗 §3.2.2 / §3.1.1)", () => { + it("退避序列 15 → 30 → 60 分钟,之后封顶 60 分钟", () => { + expect([1, 2, 3, 4, 5].map((n) => throttleBackoffMs(n) / 60_000)).toEqual([ + 15, 30, 60, 60, 60, + ]); + // 异常输入兜底成第一档 + expect(throttleBackoffMs(0) / 60_000).toBe(15); + }); + + it("sendGapMs = interval + random(0, jitter)", () => { + expect(sendGapMs({ interval_ms: 4000, jitter_ms: 0 }, () => 0.99)).toBe(4000); + expect(sendGapMs({ interval_ms: 4000, jitter_ms: 2000 }, () => 0)).toBe(4000); + expect(sendGapMs({ interval_ms: 4000, jitter_ms: 2000 }, () => 1)).toBe(6000); + }); + + it("sleepMs(0) 不排定时器,sleepMs(n) 走原生定时器", async () => { + vi.useFakeTimers(); + try { + let resolved = false; + const immediate = sleepMs(0).then(() => { + resolved = true; + }); + await immediate; + expect(resolved).toBe(true); + + let after = false; + const pending = sleepMs(1000).then(() => { + after = true; + }); + await vi.advanceTimersByTimeAsync(999); + expect(after).toBe(false); + await vi.advanceTimersByTimeAsync(1); + await pending; + expect(after).toBe(true); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/worker/test/smtp-transport.test.ts b/worker/test/smtp-transport.test.ts index 7547bcc..864d17e 100644 --- a/worker/test/smtp-transport.test.ts +++ b/worker/test/smtp-transport.test.ts @@ -1,7 +1,9 @@ import { afterEach, describe, expect, it } from "vitest"; import { encodeUtf8Base64, + formatExtraHeaders, sendSmtpMessage, + senderDomain, wrapBase64, } from "../src/services/smtp-transport"; import { setConnectFactory } from "./stubs/sockets"; @@ -110,3 +112,75 @@ describe("sendSmtpMessage(465 隐式 TLS / STARTTLS / 拒绝明文)", () => ); }); }); + +// ─── 发信节流补遗 §3.3:Message-ID 与附加头 ──────────────────────────────── + +describe("Message-ID 与附加头(节流补遗 §3.3)", () => { + it("显式 messageId 与附加头原样进信头", async () => { + const server = new FakeSmtpServer(); + server.install(); + + const result = await sendSmtpMessage(CONFIG, { + ...MESSAGE, + messageId: "", + extraHeaders: { "X-Someday-Letter-Id": "letter-1" }, + }); + + expect(result).toEqual({ success: true }); + expect(server.message).toContain("Message-ID: "); + expect(server.message).toContain("X-Someday-Letter-Id: letter-1"); + }); + + it("未给 messageId 时默认形态用 From 地址域名(不再写死域名)", async () => { + const server = new FakeSmtpServer(); + server.install(); + + await sendSmtpMessage(CONFIG, MESSAGE); + + const line = server.message + .split("\r\n") + .find((l) => l.startsWith("Message-ID:")); + expect(line).toBeDefined(); + expect(line!).toMatch(/^Message-ID: <[^@]+@example\.com>$/); + expect(senderDomain("notify@example.com")).toBe("example.com"); + expect(senderDomain("no-at-sign")).toBe("localhost"); + }); + + it("附加头里的 CRLF 被剔除,非法头名被丢弃(防头注入)", () => { + expect( + formatExtraHeaders({ + "X-Someday-Letter-Id": "l1\r\nBcc: evil@example.com", + "Bad Header": "x", + Good: " ", + }), + ).toBe("X-Someday-Letter-Id: l1 Bcc: evil@example.com\r\n"); + expect(formatExtraHeaders(undefined)).toBe(""); + }); + + it("限流类拒收(452)把回复码与原文一并带回", async () => { + const server = new FakeSmtpServer({ + recipientReject: "452 4.7.0 too many messages", + }); + server.install(); + + const result = await sendSmtpMessage(CONFIG, MESSAGE); + + expect(result.success).toBe(false); + expect(result.code).toBe(452); + expect(result.response).toBe("4.7.0 too many messages"); + expect(result.error).toContain("got 452"); + }); + + it("永久类拒收(550)同样带回回复码,error 文案与改造前一致", async () => { + const server = new FakeSmtpServer({ rejectRecipient: true }); + server.install(); + + const result = await sendSmtpMessage(CONFIG, MESSAGE); + + expect(result.code).toBe(550); + expect(result.response).toBe("5.1.1 no such user"); + expect(result.error).toBe( + "SMTP error: SMTP: expected 250, got 550 \u2014 5.1.1 no such user", + ); + }); +}); diff --git a/worker/test/waker-callback.test.ts b/worker/test/waker-callback.test.ts index 7e313cb..2423d33 100644 --- a/worker/test/waker-callback.test.ts +++ b/worker/test/waker-callback.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { makeEnv } from "./helpers"; +import { makeEnv, setSendThrottleConfig } from "./helpers"; import { app } from "../src/index"; import { tables, type Env, type Letter } from "../src/types"; import { DUE_LETTERS_JOB, wakerExecutionsTable } from "../src/services/waker-callback"; @@ -287,9 +287,13 @@ describe("waker 回调:同步执行 processDueLetters 并返回统计", () => // 统计口径 = processDueLetters 的返回值 expect(body.stats).toEqual({ scanned: 1, + claimed: 1, delivered: 1, partialFailed: 0, - gaveUp: 0, + failed: 0, + throttled: 0, + deferred_by_cap: 0, + paused_until: null, }); // 业务真的跑完了:SMTP 被调用、信已置 sent(不是「先 2xx 再异步发」) expect(sendEmailMock).toHaveBeenCalledTimes(1); @@ -304,6 +308,7 @@ describe("waker 回调:同步执行 processDueLetters 并返回统计", () => it("多封信 + 部分失败:统计与口一致(scanned / delivered / partialFailed)", async () => { const env = signingEnv(); + await setSendThrottleConfig(env); await seedLetter(env, [{ id: "r1", email: "good@example.com" }], { id: "l-ok" }); await seedLetter( env, @@ -324,15 +329,36 @@ describe("waker 回调:同步执行 processDueLetters 并返回统计", () => expect(status).toBe(200); expect(body.stats).toEqual({ scanned: 2, + claimed: 2, delivered: 1, partialFailed: 1, - gaveUp: 0, + failed: 0, + throttled: 0, + deferred_by_cap: 0, + paused_until: null, }); expect(await letterStatus(env, "l-ok")).toBe("sent"); // 部分失败的信回到 scheduled,attempts+1(投递语义未改) expect(await letterStatus(env, "l-partial")).toBe("scheduled"); }); + it("回调体里的 timeoutSeconds 决定本轮预算:预算不够时只发首封、其余顺延", async () => { + const env = signingEnv(); + await setSendThrottleConfig(env); + await seedLetter(env, [{ id: "r1", email: "first@example.com" }], { id: "l1" }); + await seedLetter(env, [{ id: "r2", email: "second@example.com" }], { id: "l2" }); + + const { status, body } = await postCallback(env, { + bodyOverrides: { timeoutSeconds: 1 }, + }); + + expect(status).toBe(200); + expect(body.stats.claimed).toBe(1); + expect(body.stats.deferred_by_cap).toBe(1); + expect(sendEmailMock).toHaveBeenCalledTimes(1); + expect(await letterStatus(env, "l2")).toBe("scheduled"); + }); + it("未到期的信不会被这次回调发出去(扫描口径不变)", async () => { const env = signingEnv(); await seedLetter(env, [{ id: "r1", email: "future@example.com" }], {