@joelincc/mailroom 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +54 -8
  2. package/SECURITY.md +1 -1
  3. package/bin/mailroom.mjs +26 -0
  4. package/dist/broadcast/config.js +79 -0
  5. package/dist/broadcast/explain.js +50 -0
  6. package/dist/cli/args.js +29 -0
  7. package/dist/cli/errors.js +37 -0
  8. package/dist/cli/main.js +533 -0
  9. package/dist/compose/clicks.js +29 -0
  10. package/dist/compose/compose.js +275 -0
  11. package/dist/compose/index.js +8 -0
  12. package/dist/compose/markdown.js +1197 -0
  13. package/dist/compose/personalize.js +123 -0
  14. package/dist/compose/preflight.js +251 -0
  15. package/dist/compose/preview.js +41 -0
  16. package/dist/compose/render.js +141 -0
  17. package/dist/compose/template.js +118 -0
  18. package/docs/broadcast.md +199 -0
  19. package/docs/composing.md +156 -0
  20. package/docs/desk-commands.md +52 -0
  21. package/docs/export.md +52 -0
  22. package/docs/lists.md +68 -0
  23. package/docs/security-model.md +6 -4
  24. package/docs/ses.md +116 -0
  25. package/docs/tracking.md +102 -0
  26. package/docs/unsubscribe.md +124 -0
  27. package/docs/welcome.md +72 -0
  28. package/migrations/0004_last_error.sql +2 -0
  29. package/migrations/0005_lists.sql +41 -0
  30. package/migrations/0006_broadcast.sql +154 -0
  31. package/migrations/0007_unsubscribe.sql +12 -0
  32. package/migrations/0008_tracking.sql +5 -0
  33. package/migrations/0009_welcome.sql +17 -0
  34. package/package.json +21 -3
  35. package/src/alert.ts +123 -0
  36. package/src/aws-sigv4.ts +100 -0
  37. package/src/broadcast/audience.ts +96 -0
  38. package/src/broadcast/campaigns.ts +352 -0
  39. package/src/broadcast/config.ts +136 -0
  40. package/src/broadcast/dispatch.ts +779 -0
  41. package/src/broadcast/events.ts +110 -0
  42. package/src/broadcast/explain.ts +73 -0
  43. package/src/broadcast/freeze.ts +93 -0
  44. package/src/broadcast/index.ts +21 -0
  45. package/src/broadcast/postman.ts +229 -0
  46. package/src/broadcast/reconcile.ts +120 -0
  47. package/src/broadcast/routes.ts +181 -0
  48. package/src/broadcast/ses.ts +181 -0
  49. package/src/broadcast/stats.ts +59 -0
  50. package/src/broadcast/status.ts +60 -0
  51. package/src/broadcast/test-send.ts +88 -0
  52. package/src/broadcast/warmup.ts +150 -0
  53. package/src/broadcast/worker.ts +218 -0
  54. package/src/cf-events.ts +4 -3
  55. package/src/cli/args.ts +27 -0
  56. package/src/cli/errors.ts +39 -0
  57. package/src/cli/main.ts +515 -0
  58. package/src/compose/clicks.ts +45 -0
  59. package/src/compose/compose.ts +297 -0
  60. package/src/compose/index.ts +8 -0
  61. package/src/compose/markdown.ts +1173 -0
  62. package/src/compose/personalize.ts +130 -0
  63. package/src/compose/preflight.ts +250 -0
  64. package/src/compose/preview.ts +58 -0
  65. package/src/compose/render.ts +158 -0
  66. package/src/compose/template.ts +197 -0
  67. package/src/core.ts +45 -2
  68. package/src/export.ts +184 -0
  69. package/src/feedback.ts +128 -0
  70. package/src/http.ts +17 -0
  71. package/src/index.ts +146 -32
  72. package/src/list-routes.ts +55 -0
  73. package/src/lists.ts +381 -0
  74. package/src/ses-events.ts +426 -0
  75. package/src/track.ts +409 -0
  76. package/src/unsub-wiring.ts +64 -0
  77. package/src/unsub.ts +499 -0
  78. package/src/webhook.ts +5 -3
  79. package/src/welcome.ts +257 -0
  80. package/wrangler.example.jsonc +16 -2
@@ -0,0 +1,110 @@
1
+ // 郵差事件進來的唯一入口:正規化後的 ProviderEvent → events 表+帳本 last_event+(可注入的)退信/檢舉處理。
2
+ // 假郵差、之後的 SES(SNS 驗簽後)都呼叫 ingestEvent。同一則事件(provider_event_id)重送只處理一次。
3
+
4
+ import type { Db } from '../core.ts';
5
+ import { applyFeedback, type FeedbackEvent } from '../feedback.ts';
6
+ import { listUnsubscribe } from '../lists.ts';
7
+ import { scrubEmails } from '../export.ts';
8
+ import { EVENT_TYPES, type ProviderEvent } from './postman.ts';
9
+
10
+ /** 交給「退信/檢舉怎麼進拒收」那一層的事件(=退訂模組 feedback.ts 的 FeedbackEvent)。 */
11
+ export type FeedbackInput = FeedbackEvent;
12
+
13
+ export interface IngestOptions {
14
+ /** 退信/檢舉/送達的後續處理。沒給=預設 applyFeedback(永久退信與檢舉進拒收、檢舉者全部名單退訂、連續暫時退信升級)。 */
15
+ feedback?: (fb: FeedbackInput) => Promise<unknown>;
16
+ now?: () => Date;
17
+ }
18
+
19
+ export type IngestOutcome = 'recorded' | 'repeat' | 'rejected';
20
+
21
+ const LAST_EVENT: Partial<Record<string, string>> = { delivery: 'delivered', bounce: 'bounced', complaint: 'complained', reject: 'failed', delay: 'delayed' };
22
+ const ID = /^[\x21-\x7e]{1,200}$/;
23
+
24
+ /** bounce 的 subtype 只看開頭:Permanent → 永久;其他(Transient、Undetermined)→ 暫時。 */
25
+ export function isPermanentBounce(subtype: string | null | undefined): boolean {
26
+ return typeof subtype === 'string' && /^permanent/i.test(subtype);
27
+ }
28
+
29
+ export async function ingestEvent(db: Db, ev: ProviderEvent, opts: IngestOptions = {}): Promise<IngestOutcome> {
30
+ if (!ev || typeof ev !== 'object' || !EVENT_TYPES.includes(ev.type)) return 'rejected';
31
+ if (typeof ev.provider !== 'string' || !/^[a-z0-9-]{1,40}$/.test(ev.provider) || typeof ev.providerEventId !== 'string' || !ID.test(ev.providerEventId)) return 'rejected';
32
+ const now = (opts.now ?? (() => new Date()))();
33
+ const at = typeof ev.at === 'string' && !Number.isNaN(Date.parse(ev.at)) ? new Date(ev.at).toISOString() : now.toISOString();
34
+
35
+ // 先查有沒有處理過;處理完才記(中途出錯時重送會再處理一次,下面每一步都可重複執行)。
36
+ const seen = await db.prepare('SELECT id FROM events WHERE provider_event_id = ?').bind(ev.providerEventId).first();
37
+ if (seen) return 'repeat';
38
+
39
+ // 對到帳本列與期別/收件人:優先用郵差的信件 id,其次用事件帶的標籤。
40
+ let msg = ev.providerMessageId
41
+ ? await db.prepare('SELECT id, to_email, stream FROM messages WHERE provider_id = ? LIMIT 1').bind(String(ev.providerMessageId)).first<{ id: number; to_email: string; stream?: string }>()
42
+ : null;
43
+ let campaign = typeof ev.campaign === 'string' && ev.campaign ? ev.campaign.slice(0, 64) : null;
44
+ let contact = ev.contact !== undefined && ev.contact !== null && /^\d{1,15}$/.test(String(ev.contact)) ? Number(ev.contact) : null;
45
+ // 事件可能比「帳本記下郵差 id」更早回來;帳本列在交郵差前就建好了,用去重鍵找得到。
46
+ if (!msg && campaign && contact !== null) {
47
+ // 歡迎信的標籤是 _welcome-{名單},去重鍵是 welcome:{名單}:{聯絡人}。
48
+ const key = campaign.startsWith('_welcome-') ? `welcome:${campaign.slice('_welcome-'.length)}:${contact}` : `c:${campaign}:${contact}`;
49
+ msg = await db.prepare("SELECT id, to_email, stream FROM messages WHERE dedupe_key = ? AND stream = 'marketing' LIMIT 1").bind(key).first<{ id: number; to_email: string; stream?: string }>();
50
+ }
51
+ if (msg && (campaign === null || contact === null)) {
52
+ const r = await db.prepare('SELECT campaign_id, contact_id FROM campaign_recipients WHERE message_id = ? LIMIT 1').bind(msg.id).first<{ campaign_id: string; contact_id: number }>();
53
+ if (r) {
54
+ campaign ??= r.campaign_id;
55
+ contact ??= Number(r.contact_id);
56
+ }
57
+ }
58
+ // 事件自己有說是哪個地址、卻跟帳本列的收件人不同 → 那一列不是這則事件的(不能把別人的退信算到這位讀者頭上)。
59
+ const evEmail = typeof ev.email === 'string' ? ev.email.trim().toLowerCase() : '';
60
+ if (msg && evEmail && msg.to_email.trim().toLowerCase() !== evEmail) {
61
+ msg = null;
62
+ campaign = null;
63
+ contact = null;
64
+ }
65
+ const email = (msg?.to_email ?? evEmail).trim().toLowerCase();
66
+ const subtype = typeof ev.subtype === 'string' ? ev.subtype.slice(0, 64) : null;
67
+
68
+ // 1. 帳本列的最後狀態(送達之後的開信、點擊不覆蓋)。
69
+ const last = LAST_EVENT[ev.type];
70
+ if (last && msg) await db.prepare('UPDATE messages SET last_event = ?, updated_at = ? WHERE id = ?').bind(last, now.toISOString(), msg.id).run();
71
+
72
+ // 2. 退信/檢舉/送達的後續處理(進拒收名單等)。
73
+ // 測試信(tags.contact=test):事件照記,但不進拒收名單、不退訂任何人(測試信箱被標垃圾信不該影響名單);統計只算凍結名單裡的人,本來就不含它。
74
+ const isTest = ev.contact === 'test';
75
+ if (!isTest && email && !ev.skipFeedback && (ev.type === 'bounce' || ev.type === 'complaint' || ev.type === 'delivery')) {
76
+ const source = `${ev.provider}-event`;
77
+ const detail = ev.detail && typeof ev.detail === 'object' ? JSON.stringify(ev.detail).slice(0, 300) : null;
78
+ const fb: FeedbackInput =
79
+ ev.type === 'bounce'
80
+ ? isPermanentBounce(subtype)
81
+ ? { type: 'bounce', kind: 'permanent', email, source, detail: [subtype, detail].filter(Boolean).join(' ') || null }
82
+ : {
83
+ type: 'bounce', kind: 'transient', email, campaign, source, detail: [subtype, detail].filter(Boolean).join(' ') || null,
84
+ // 只有郵差層明說是信箱層級(mailbox)或內容(content)才帶;其他(一般性、無法判定)不帶=不累計。
85
+ ...(ev.cause === 'mailbox' || ev.cause === 'content' ? { cause: ev.cause } : {}),
86
+ }
87
+ : ev.type === 'complaint'
88
+ ? // 這裡是電子報郵差的事件:被檢舉的是電子報那類信,只擋電子報(交易信照寄)。只有對到的帳本列明確是交易類才擋全部。
89
+ { type: 'complaint', email, source, detail, scope: msg?.stream === 'transactional' ? 'all' : 'marketing' }
90
+ : { type: 'delivery', email };
91
+ if (opts.feedback) await opts.feedback(fb);
92
+ else await applyFeedback(db, fb, { now: () => now });
93
+ }
94
+
95
+ // 3. 郵差那邊回報的退訂(例:信箱商的退訂按鈕經郵差轉來):退這一期所屬的名單。對不到期別就只記事件。
96
+ if (!isTest && email && ev.type === 'unsubscribe' && campaign) {
97
+ const c = await db.prepare('SELECT list_id FROM campaigns WHERE id = ?').bind(campaign).first<{ list_id: string }>();
98
+ if (c) await listUnsubscribe(db, { list: c.list_id, email, source: 'api' }, () => now);
99
+ }
100
+
101
+ // 4. 最後才記這則事件(provider_event_id 唯一:同時兩則一樣的只會留一列)。
102
+ await db
103
+ .prepare(
104
+ `INSERT INTO events (provider, provider_event_id, message_id, provider_message_id, campaign_id, contact_id, type, subtype, at, detail)
105
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (provider_event_id) DO NOTHING`,
106
+ )
107
+ .bind(ev.provider, ev.providerEventId, msg?.id ?? null, ev.providerMessageId ? String(ev.providerMessageId).slice(0, 200) : null, campaign, contact, ev.type, subtype, at, ev.detail ? JSON.stringify(scrubEmails(ev.detail)).slice(0, 2000) : null)
108
+ .run();
109
+ return 'recorded';
110
+ }
@@ -0,0 +1,73 @@
1
+ // 把「暫停原因」翻成人看得懂的說明:哪一道門檻、當時的分子分母、建議下一步。唯讀,不改任何狀態。
2
+ // 原因字串的格式由 dispatch.ts 的 brake() 寫入(brake:hard_bounce_rate:3/200、brake:wave_gate:wave1:2/30…)。
3
+
4
+ import type { BroadcastConfig } from './config.ts';
5
+
6
+ export interface PauseExplanation {
7
+ /** 原因代碼(不含數字),例 hard_bounce_rate。 */
8
+ code: string;
9
+ /** 英文一句話,給人看。 */
10
+ summary: string;
11
+ /** 當時的分子與分母(有的話)。 */
12
+ numerator?: number;
13
+ denominator?: number;
14
+ rate?: number;
15
+ /** 這道門檻本身的設定。 */
16
+ threshold?: Record<string, number>;
17
+ /** 建議的下一步(指令名稱+要先查什麼)。 */
18
+ suggestion: string;
19
+ /** 放行前要先解除整個寄件網域停寄。 */
20
+ needsDomainRelease: boolean;
21
+ /** 這個原因能不能直接放行:false=要先修好根因(例如渲染出錯、對帳不符)。 */
22
+ resumable: boolean;
23
+ }
24
+
25
+ const ratio = (a: number, b: number) => (b > 0 ? a / b : 0);
26
+
27
+ export function explainPause(reason: string | null | undefined, cfg: BroadcastConfig): PauseExplanation | null {
28
+ if (!reason) return null;
29
+ const nd = /(\d+)\/(\d+)\s*$/.exec(reason);
30
+ const n = nd ? Number(nd[1]) : undefined;
31
+ const d = nd ? Number(nd[2]) : undefined;
32
+ const rate = n !== undefined && d !== undefined ? ratio(n, d) : undefined;
33
+ const base = { numerator: n, denominator: d, rate };
34
+ const m = /^brake:([a-z_]+)/.exec(reason);
35
+ const code = m ? m[1] : (reason.split(':')[0] ?? reason).trim();
36
+
37
+ switch (code) {
38
+ case 'hard_bounce_rate':
39
+ return { code, ...base, summary: `Hard bounces reached the issue brake: ${n} of ${d} sent.`, threshold: { hardBounceRate: cfg.brakeHardBounceRate, minSent: cfg.brakeMinSent }, suggestion: 'Check the bounce reasons and the list source; resume only if the bounces are explained (counting restarts from the resume).', needsDomainRelease: false, resumable: true };
40
+ case 'complaint_rate':
41
+ return { code, ...base, summary: `Complaints reached the issue brake: ${n} of ${d} sent.`, threshold: { complaintCount: cfg.brakeComplaintCount, complaintRate: cfg.brakeComplaintRate }, suggestion: 'Look at who complained (their segment and source) before resuming; complaints are the strongest signal to providers.', needsDomainRelease: false, resumable: true };
42
+ case 'wave_gate':
43
+ return { code, ...base, summary: `The previous wave had too many hard bounces to open the next wave: ${n} of ${d} sent.`, threshold: { waveGateBounceRate: cfg.waveGateBounceRate, waveGateMinSent: cfg.waveGateMinSent }, suggestion: 'Small waves make this brake touchy: check whether the bounces are real (same domain? typos?) and consider raising waveGateMinSent.', needsDomainRelease: false, resumable: true };
44
+ case 'domain_hold': {
45
+ const dr = /(?:bounce_rate|complaint_rate):(\d+)\/(\d+)/.exec(reason);
46
+ const dn = dr ? Number(dr[1]) : undefined;
47
+ const dd = dr ? Number(dr[2]) : undefined;
48
+ const isComplaint = reason.includes('complaint_rate');
49
+ return { code, numerator: dn, denominator: dd, rate: dn !== undefined && dd !== undefined ? ratio(dn, dd) : undefined, summary: `The sender domain is on hold: ${isComplaint ? 'complaints' : 'hard bounces'} ${dn} of ${dd} sent in the rolling window.`, threshold: isComplaint ? { complaintRate: cfg.domainComplaintRate, minSent: cfg.domainMinSent, minComplaints: cfg.domainMinComplaints } : { hardBounceRate: cfg.domainBounceRate, minSent: cfg.domainMinSent }, suggestion: 'All newsletters on the domain stopped. Check the numbers (a single complaint can trip it on a small sample), then release the domain hold and resume.', needsDomainRelease: true, resumable: true };
50
+ }
51
+ case 'queue_stalled':
52
+ return { code, summary: `Work was handed to the queue but nothing came back for ${cfg.stallMinutes} minutes.`, threshold: { stallMinutes: cfg.stallMinutes }, suggestion: 'Check the queue and consumer logs (and the dead-letter queue) first; resume once results flow again.', needsDomainRelease: false, resumable: true };
53
+ case 'provider_enforcement':
54
+ case 'provider_account_paused':
55
+ return { code, summary: `The provider reports the account is not healthy (${reason.split(':').slice(2).join(':') || code}).`, suggestion: 'Look at the provider console. Do not resume until the provider says the account is healthy again.', needsDomainRelease: false, resumable: true };
56
+ case 'start_stale':
57
+ return { code, summary: `The issue started but not one mail was handed to the provider within ${cfg.startGraceMinutes} minutes.`, threshold: { startGraceMinutes: cfg.startGraceMinutes }, suggestion: 'Usually the provider limits could not be read when it started (key or API problem) or the queue is not moving. Fix that first; resuming restarts the timer.', needsDomainRelease: false, resumable: true };
58
+ case 'permanent_streak':
59
+ return { code, summary: `Sending stopped after ${reason.split(':')[2] ?? cfg.permanentStreak} permanent failures in a row.`, suggestion: 'A run of permanent failures usually means a configuration problem (sender, domain verification, key), not bad addresses. Fix the cause before resuming.', needsDomainRelease: false, resumable: false };
60
+ case 'freeze_blocked':
61
+ return { code, summary: `The list could not be frozen: ${reason.split(':').slice(2).join(':')}.`, suggestion: 'Fix the audience or warm-up plan, then cancel and rebuild this issue.', needsDomainRelease: false, resumable: false };
62
+ case 'reconcile_mismatch':
63
+ return { code, summary: `Reconciliation does not add up: ${reason.slice(reason.indexOf(':') + 1)}.`, suggestion: 'Run the reconcile command and read the differences; do not resume until a person has explained them.', needsDomainRelease: false, resumable: false };
64
+ case 'render_error':
65
+ case 'rejected':
66
+ return { code, summary: `Sending stopped on an error: ${reason.slice(reason.indexOf(':') + 1)}.`, suggestion: 'This is a configuration or content problem, not a rate. Fix the cause before resuming.', needsDomainRelease: false, resumable: false };
67
+ case 'manual':
68
+ case 'cancelled':
69
+ return { code, summary: `Paused by a person: ${reason.slice(reason.indexOf(':') + 1).trim()}`, suggestion: 'Resume with a note when the reason no longer applies.', needsDomainRelease: false, resumable: code === 'manual' };
70
+ default:
71
+ return { code, summary: `Paused: ${reason}`, suggestion: 'Unknown reason: read the issue status before resuming.', needsDomainRelease: false, resumable: true };
72
+ }
73
+ }
@@ -0,0 +1,93 @@
1
+ // 凍結名單:開寄那一刻,把這份名單上「訂閱中」的每個人寫進 campaign_recipients。
2
+ // - 在全域拒收名單(硬退信/檢舉/全部不要)→ skipped/suppressed
3
+ // - 不在這期的收件群(暖機還沒輪到)→ skipped/warmup
4
+ // - 其他 → planned,照收件群的分波與群的順序排好(wave、rank)
5
+ // 之後名單怎麼變都不影響這一期的名單;凍結後才退訂或被拒收的人,派送當下會再查一次並跳過。
6
+ //
7
+ // 整段用幾條「整批」SQL 完成(2,000 人也只有十來條),能用 D1 batch 就一次交、整批成功或整批失敗;
8
+ // 最後一條把 frozen_at 填上——派送端只認 frozen_at 有值的期。中途斷掉重跑也安全(插入遇重複略過、更新可重複)。
9
+
10
+ import type { Stmt } from '../core.ts';
11
+ import type { ListDb } from '../lists.ts';
12
+ import type { CampaignRow } from './campaigns.ts';
13
+
14
+ export interface FrozenAudience { waves: string[][]; maxCount: number | null; plan?: string; step?: number }
15
+
16
+ async function runBatch(db: ListDb, stmts: Stmt[]): Promise<void> {
17
+ if (db.batch) {
18
+ await db.batch(stmts);
19
+ return;
20
+ }
21
+ for (const s of stmts) await s.run();
22
+ }
23
+
24
+ /** 這期每個群在第幾波、波內第幾順位的 CASE 運算式(值都用綁定參數,不拼字串)。 */
25
+ function caseFor(waves: string[][], pick: 'wave' | 'rank'): { sql: string; binds: unknown[] } {
26
+ const parts: string[] = [];
27
+ const binds: unknown[] = [];
28
+ let star: { wave: number; rank: number } | null = null;
29
+ waves.forEach((segs, wi) =>
30
+ segs.forEach((seg, si) => {
31
+ if (seg === '*') {
32
+ star = { wave: wi + 1, rank: si };
33
+ return;
34
+ }
35
+ parts.push('WHEN ? THEN ?');
36
+ binds.push(seg, pick === 'wave' ? wi + 1 : si);
37
+ }),
38
+ );
39
+ const s = star as { wave: number; rank: number } | null;
40
+ const fallback = s ? (pick === 'wave' ? s.wave : s.rank) : null;
41
+ binds.push(fallback);
42
+ return { sql: parts.length ? `CASE m.segment ${parts.join(' ')} ELSE ? END` : '?', binds };
43
+ }
44
+
45
+ export async function freezeRecipients(db: ListDb, c: CampaignRow, aud: FrozenAudience, now: Date): Promise<void> {
46
+ const t = now.toISOString();
47
+ const wave = caseFor(aud.waves, 'wave');
48
+ const rank = caseFor(aud.waves, 'rank');
49
+ const stmts: Stmt[] = [
50
+ db
51
+ .prepare(
52
+ `INSERT INTO campaign_recipients (campaign_id, contact_id, email, segment, wave, rank, state, skip_reason)
53
+ SELECT ?, c.id, c.email, m.segment, ${wave.sql}, COALESCE(${rank.sql}, 0), 'planned', NULL
54
+ FROM list_members m JOIN contacts c ON c.id = m.contact_id
55
+ WHERE m.list_id = ? AND m.status = 'subscribed'
56
+ ON CONFLICT (campaign_id, contact_id) DO NOTHING`,
57
+ )
58
+ .bind(c.id, ...wave.binds, ...rank.binds, c.list_id),
59
+ // 不在這期收件群的人:暖機還沒輪到。
60
+ db.prepare("UPDATE campaign_recipients SET state = 'skipped', skip_reason = 'warmup' WHERE campaign_id = ? AND state = 'planned' AND wave IS NULL").bind(c.id),
61
+ // 全域拒收(電子報會擋的三種原因)。拒收優先於「沒輪到」,對帳時看得出被擋的真正原因。
62
+ db
63
+ .prepare(
64
+ `UPDATE campaign_recipients SET state = 'skipped', skip_reason = 'suppressed'
65
+ WHERE campaign_id = ? AND state IN ('planned', 'skipped') AND COALESCE(skip_reason, '') IN ('', 'warmup')
66
+ AND email IN (SELECT email FROM suppressions WHERE reason IN ('hard_bounce', 'complaint', 'unsubscribe'))`,
67
+ )
68
+ .bind(c.id),
69
+ ];
70
+ if (aud.maxCount !== null) {
71
+ // 這一步最多寄幾人:照波次、順位排,超過的人記成「暖機沒輪到」。
72
+ stmts.push(
73
+ db
74
+ .prepare(
75
+ `UPDATE campaign_recipients SET state = 'skipped', skip_reason = 'warmup'
76
+ WHERE campaign_id = ? AND state = 'planned' AND contact_id IN (
77
+ SELECT contact_id FROM campaign_recipients WHERE campaign_id = ? AND state = 'planned'
78
+ ORDER BY wave, rank, contact_id LIMIT -1 OFFSET ?)`,
79
+ )
80
+ .bind(c.id, c.id, aud.maxCount),
81
+ );
82
+ }
83
+ stmts.push(
84
+ db
85
+ .prepare(
86
+ `UPDATE campaigns SET frozen_at = ?, audience_resolved = ?, last_progress_at = ?, updated_at = ?,
87
+ counts = json_set(COALESCE(counts, '{}'), '$.frozen', (SELECT COUNT(*) FROM campaign_recipients WHERE campaign_id = ?))
88
+ WHERE id = ? AND frozen_at IS NULL`,
89
+ )
90
+ .bind(t, JSON.stringify(aud), t, t, c.id, c.id),
91
+ );
92
+ await runBatch(db, stmts);
93
+ }
@@ -0,0 +1,21 @@
1
+ // 電子報群發:一期信的狀態、凍結名單、分波派送、配速、暖機梯子、兩級煞車、對帳、郵差介面與假郵差。見 docs/broadcast.md。
2
+ export { DEFAULT_BROADCAST_CONFIG, resolveConfig, type BroadcastConfig } from './config.ts';
3
+ export {
4
+ approveCampaign, cancelCampaign, canTransition, checkAudience, contentHash, getCampaign, pauseCampaign, recordPreflight, resumeCampaign, saveDraft,
5
+ scheduleCampaign, unscheduleCampaign, CAMPAIGN_STATUSES, TRANSITIONS,
6
+ type Audience, type CampaignInput, type CampaignRow, type CampaignStatus, type PreflightRecord,
7
+ } from './campaigns.ts';
8
+ export {
9
+ activeHold, consume, consumeBatch, releaseHold, resolveUncertain, retryFailed, tick,
10
+ type Alert, type BroadcastDeps, type BroadcastMessage, type BroadcastQueue, type ConsumeResult, type QueueMessageLike, type RecipientRow, type Render, type RenderResult, type TickReport,
11
+ } from './dispatch.ts';
12
+ export { ingestEvent, isPermanentBounce, type FeedbackInput, type IngestOptions, type IngestOutcome } from './events.ts';
13
+ export { freezeRecipients, type FrozenAudience } from './freeze.ts';
14
+ export { EVENT_TYPES, FakePostman, SIMULATOR_RULES, type EventType, type FakeOutcome, type FakePostmanOptions, type FakeRule, type Postman, type PostmanLimits, type PostmanMail, type PostmanOutcome, type ProviderEvent } from './postman.ts';
15
+ export { reconcileCampaign, type ReconcileReport } from './reconcile.ts';
16
+ export { campaignRates, domainRates, type CampaignRates } from './stats.ts';
17
+ export { campaignStatus, throttleStatus } from './status.ts';
18
+ export { currentStep, evaluateWarmup, planBlocked, planSteps, unblockWarmup, upsertWarmupStep, type GateResult, type StepInput, type WarmupStepRow } from './warmup.ts';
19
+ export { explainPause, type PauseExplanation } from './explain.ts';
20
+ export { parseAllowed, previewContent, sendTest, MAX_TEST_RECIPIENTS, type TestSendDeps } from './test-send.ts';
21
+ export { audiencePlan, type AudiencePlan } from './audience.ts';
@@ -0,0 +1,229 @@
1
+ // 電子報的郵差介面+內建假郵差。
2
+ //
3
+ // 郵差只做兩件事:送一封(回結果)、報上限(每秒、每天、健康狀態)。換郵差=換一個實作這個介面的物件;
4
+ // 引擎不做自動切換(一個郵差出事多半是名單或內容的問題,自動換只會把問題帶到第二個帳號)。
5
+ //
6
+ // 送一封的結果一定要分清楚「確定沒寄出」與「不知道」:
7
+ // - temporary/permanent/throttled/daily_quota/account_paused=郵差明確說沒收下(引擎可以安全地再試或停下)。
8
+ // daily_quota=郵差的 24 小時額度用完:今天停放水、明天自動恢復(不踩紅燈煞車)。
9
+ // - 丟例外=不知道有沒有寄出 → 引擎把那一位記成 uncertain、絕不自動重寄(寧可漏一封也不寄兩封)。
10
+
11
+ import type { TransientCause } from '../feedback.ts';
12
+
13
+ export type EventType = 'send' | 'delivery' | 'bounce' | 'complaint' | 'reject' | 'delay' | 'open' | 'click' | 'unsubscribe';
14
+ export const EVENT_TYPES: readonly EventType[] = ['send', 'delivery', 'bounce', 'complaint', 'reject', 'delay', 'open', 'click', 'unsubscribe'];
15
+
16
+ export interface PostmanMail {
17
+ from: string;
18
+ to: string;
19
+ subject: string;
20
+ html: string;
21
+ text: string;
22
+ replyTo?: string;
23
+ headers?: Record<string, string>;
24
+ /** 帶回事件用:事件回來時靠它對到期別與收件人(SES 的 EmailTags、其他郵差的 metadata)。 */
25
+ tags: { campaign: string; contact: string };
26
+ /** 同一封信的固定識別(站名/去重鍵);支援冪等鍵的郵差拿它防重寄。 */
27
+ idempotencyKey: string;
28
+ }
29
+
30
+ export type PostmanOutcome =
31
+ | { ok: true; providerId: string }
32
+ | { ok: false; kind: 'temporary' | 'permanent' | 'throttled' | 'daily_quota' | 'account_paused'; error: string };
33
+
34
+ export interface PostmanLimits {
35
+ /** 每秒最多幾封。 */
36
+ perSecond: number;
37
+ /** 24 小時最多幾封。 */
38
+ perDay: number;
39
+ /** 郵差說最近 24 小時已用幾封(沒有就不填)。 */
40
+ sentLast24h?: number;
41
+ /** 帳號健康狀態;不是 HEALTHY 就踩煞車。 */
42
+ enforcement: string;
43
+ /** 帳號是否已離開沙盒(有的郵差才報)。 */
44
+ production?: boolean;
45
+ }
46
+
47
+ export interface Postman {
48
+ readonly name: string;
49
+ send(mail: PostmanMail): Promise<PostmanOutcome>;
50
+ limits(): Promise<PostmanLimits>;
51
+ }
52
+
53
+ /** 郵差的事後回報,正規化之後的樣子(SES 的 SNS 事件、假郵差都轉成這個再交給 ingestEvent)。 */
54
+ export interface ProviderEvent {
55
+ provider: string;
56
+ /** 同一則事件重送時不變(SES 用 SNS MessageId;假郵差自己編)。 */
57
+ providerEventId: string;
58
+ /** 郵差那邊的信件 id(對到 messages.provider_id)。 */
59
+ providerMessageId?: string | null;
60
+ type: EventType;
61
+ /** bounce 用:Permanent/Transient/Undetermined。 */
62
+ subtype?: string | null;
63
+ /**
64
+ * 暫時退信的原因(交給 applyFeedback 決定要不要累計):只有 'mailbox'(信箱滿)會累計成「連續暫時退信」;
65
+ * 'content'(內容/附件被拒、信太大)不累計;沒給=不累計(一般性、無法判定的暫時退信都屬這類)。
66
+ */
67
+ cause?: TransientCause | null;
68
+ /**
69
+ * true=只記事件、不交給 applyFeedback(不進拒收、不退訂)。例:SES 因為收件人已在 SES 自己的帳號層級拒收名單
70
+ *(OnAccountSuppressionList)而根本沒寄——那是舊紀錄的回音,不是新的退信或檢舉。
71
+ */
72
+ skipFeedback?: boolean;
73
+ at: string;
74
+ email?: string | null;
75
+ campaign?: string | null;
76
+ contact?: string | null;
77
+ detail?: Record<string, unknown> | null;
78
+ }
79
+
80
+ // ---------- 假郵差 ----------
81
+
82
+ export type FakeOutcome =
83
+ | 'success' // 送出+送達
84
+ | 'hard_bounce' // 送出+永久退信
85
+ | 'soft_bounce' // 送出+暫時退信
86
+ | 'complaint' // 送出+送達+檢舉
87
+ | 'delay' // 送出+延遲+(之後)送達
88
+ | 'suppressed' // 送出+永久退信(郵差自己的拒收名單)
89
+ | 'temporary' // 郵差回暫時失敗(沒收下)
90
+ | 'permanent' // 郵差回永久失敗(沒收下)
91
+ | 'throttle' // 郵差回限流(沒收下)
92
+ | 'daily_quota' // 郵差說今天 24 小時額度用完(沒收下)
93
+ | 'account_paused' // 郵差說帳號被停(沒收下)
94
+ | 'crash'; // 郵差丟例外(不知道有沒有寄出)
95
+
96
+ export interface FakeRule {
97
+ /** 比對收件地址:字串=@ 前面那段完全相同(不分大小寫)或以「字串+」開頭;正規式=整個地址。 */
98
+ match: string | RegExp;
99
+ outcome: FakeOutcome;
100
+ /** 只套用前幾次(例:前 2 次限流,之後照下一條規則)。 */
101
+ times?: number;
102
+ }
103
+
104
+ export interface FakePostmanOptions {
105
+ rules?: FakeRule[];
106
+ limits?: Partial<PostmanLimits>;
107
+ /** 事件交給誰(Worker:丟進 Queue 延遲送回;測試:收進陣列)。delayMs=模擬幾秒後才回來。 */
108
+ emit?: (event: ProviderEvent, delayMs: number) => void | Promise<void>;
109
+ /** 每種事件延遲幾毫秒(模擬「退信幾分鐘內回來、檢舉晚很多」)。 */
110
+ delays?: Partial<Record<EventType, number>>;
111
+ now?: () => Date;
112
+ name?: string;
113
+ }
114
+
115
+ /**
116
+ * 模擬信箱:照 SES 信箱模擬器的地址(success@/bounce@/complaint@/ooto@/suppressionlist@ 開頭)決定結果;
117
+ * 其他地址一律成功。另外可用 rules 指定任何地址的結果(暫時失敗、限流、帳號被停、延遲、丟例外…)。
118
+ */
119
+ export const SIMULATOR_RULES: readonly FakeRule[] = [
120
+ { match: 'success', outcome: 'success' },
121
+ { match: 'bounce', outcome: 'hard_bounce' },
122
+ { match: 'complaint', outcome: 'complaint' },
123
+ { match: 'ooto', outcome: 'success' },
124
+ { match: 'suppressionlist', outcome: 'suppressed' },
125
+ ];
126
+
127
+ const DEFAULT_DELAYS: Record<EventType, number> = {
128
+ send: 0, delivery: 2_000, bounce: 3_000, complaint: 5_000, reject: 0, delay: 1_000, open: 60_000, click: 90_000, unsubscribe: 0,
129
+ };
130
+
131
+ function matches(rule: FakeRule, to: string): boolean {
132
+ if (rule.match instanceof RegExp) return rule.match.test(to);
133
+ const local = to.split('@')[0].toLowerCase();
134
+ const m = rule.match.toLowerCase();
135
+ return local === m || local.startsWith(`${m}+`);
136
+ }
137
+
138
+ export class FakePostman implements Postman {
139
+ readonly name: string;
140
+ /** 每一次「確實收下」的信(測試用來數同一人收到幾封)。 */
141
+ readonly accepted: PostmanMail[] = [];
142
+ /** 每一次呼叫(含被拒的)。 */
143
+ readonly calls: { to: string; outcome: FakeOutcome }[] = [];
144
+ private readonly rules: FakeRule[];
145
+ private readonly used = new Map<FakeRule, number>();
146
+ private seq = 0;
147
+ private limitValues: PostmanLimits;
148
+ private readonly opts: FakePostmanOptions;
149
+
150
+ constructor(opts: FakePostmanOptions = {}) {
151
+ this.opts = opts;
152
+ this.name = opts.name ?? 'fake';
153
+ this.rules = [...(opts.rules ?? []), ...SIMULATOR_RULES];
154
+ this.limitValues = { perSecond: 14, perDay: 50_000, enforcement: 'HEALTHY', ...opts.limits };
155
+ }
156
+
157
+ /** 測試中途改上限或健康狀態。 */
158
+ setLimits(l: Partial<PostmanLimits>): void {
159
+ this.limitValues = { ...this.limitValues, ...l };
160
+ }
161
+
162
+ async limits(): Promise<PostmanLimits> {
163
+ return { ...this.limitValues, sentLast24h: this.limitValues.sentLast24h };
164
+ }
165
+
166
+ outcomeFor(to: string): FakeOutcome {
167
+ for (const rule of this.rules) {
168
+ if (!matches(rule, to)) continue;
169
+ if (rule.times !== undefined) {
170
+ const n = this.used.get(rule) ?? 0;
171
+ if (n >= rule.times) continue;
172
+ this.used.set(rule, n + 1);
173
+ }
174
+ return rule.outcome;
175
+ }
176
+ return 'success';
177
+ }
178
+
179
+ async send(mail: PostmanMail): Promise<PostmanOutcome> {
180
+ const outcome = this.outcomeFor(mail.to);
181
+ this.calls.push({ to: mail.to, outcome });
182
+ switch (outcome) {
183
+ case 'temporary':
184
+ return { ok: false, kind: 'temporary', error: 'fake temporary failure' };
185
+ case 'permanent':
186
+ return { ok: false, kind: 'permanent', error: 'fake permanent failure' };
187
+ case 'throttle':
188
+ return { ok: false, kind: 'throttled', error: 'fake throttling' };
189
+ case 'daily_quota':
190
+ return { ok: false, kind: 'daily_quota', error: 'fake daily quota exceeded' };
191
+ case 'account_paused':
192
+ return { ok: false, kind: 'account_paused', error: 'fake account paused' };
193
+ case 'crash':
194
+ throw new Error('fake postman crashed');
195
+ }
196
+ this.accepted.push(mail);
197
+ const providerId = `${this.name}-${++this.seq}-${mail.tags.campaign}-${mail.tags.contact}`;
198
+ const at = (this.opts.now ?? (() => new Date()))();
199
+ const emit = async (type: EventType, subtype: string | null = null, detail: Record<string, unknown> | null = null, cause?: TransientCause) => {
200
+ if (!this.opts.emit) return;
201
+ const delay = this.opts.delays?.[type] ?? DEFAULT_DELAYS[type];
202
+ await this.opts.emit(
203
+ {
204
+ provider: this.name,
205
+ providerEventId: `${providerId}:${type}`,
206
+ providerMessageId: providerId,
207
+ type,
208
+ subtype,
209
+ at: new Date(at.getTime() + delay).toISOString(),
210
+ email: mail.to,
211
+ campaign: mail.tags.campaign,
212
+ contact: mail.tags.contact,
213
+ detail,
214
+ ...(cause ? { cause } : {}),
215
+ },
216
+ delay,
217
+ );
218
+ };
219
+ await emit('send');
220
+ if (outcome === 'hard_bounce' || outcome === 'suppressed') await emit('bounce', 'Permanent', { bounceSubType: outcome === 'suppressed' ? 'OnAccountSuppressionList' : 'General' });
221
+ else if (outcome === 'soft_bounce') await emit('bounce', 'Transient', { bounceSubType: 'MailboxFull' }, 'mailbox');
222
+ else {
223
+ if (outcome === 'delay') await emit('delay');
224
+ await emit('delivery');
225
+ if (outcome === 'complaint') await emit('complaint');
226
+ }
227
+ return { ok: true, providerId };
228
+ }
229
+ }
@@ -0,0 +1,120 @@
1
+ // 寄完對帳:凍結名單 = 寄出 + 擋下(逐類)+ 失敗 + 不確定 + 還沒寄。
2
+ // 再對帳本(每個寄出的人都有一列 sent 的帳本、帳本 sent 數=寄出數)與郵差事件(送出事件不能比寄出多、同一人不能有兩封)。
3
+ // 任何一條對不上,problems 就不是空的——派送端據此擋下「完成」狀態。
4
+ // 「事件還沒回來」(例:送出了、送達還沒回報)不算對不上,另列 awaiting。
5
+
6
+ import type { Db } from '../core.ts';
7
+ import type { BroadcastConfig } from './config.ts';
8
+
9
+ export interface ReconcileReport {
10
+ campaign: string;
11
+ ok: boolean;
12
+ frozen: number;
13
+ sent: number;
14
+ skipped: Record<string, number>;
15
+ skippedTotal: number;
16
+ failed: number;
17
+ uncertain: number;
18
+ pending: number;
19
+ ledger: { sent: number; doneWithoutLedger: number };
20
+ events: { sends: number; delivered: number; hardBounced: number; softBounced: number; complained: number; awaiting: number; duplicateSends: number };
21
+ problems: string[];
22
+ }
23
+
24
+ const KNOWN_STATES = ['planned', 'enqueued', 'done', 'skipped', 'failed', 'uncertain'];
25
+ const KNOWN_SKIPS = ['suppressed', 'unsubscribed', 'warmup', 'cancelled'];
26
+
27
+ export async function reconcileCampaign(db: Db, campaignId: string, cfg: Pick<BroadcastConfig, 'site'>): Promise<ReconcileReport> {
28
+ const problems: string[] = [];
29
+ const rows = (
30
+ await db.prepare('SELECT state, skip_reason, COUNT(*) AS n FROM campaign_recipients WHERE campaign_id = ? GROUP BY state, skip_reason').bind(campaignId).all<{ state: string; skip_reason: string | null; n: number }>()
31
+ ).results;
32
+ let frozen = 0, sent = 0, failed = 0, uncertain = 0, pending = 0, skippedTotal = 0;
33
+ const skipped: Record<string, number> = {};
34
+ for (const r of rows) {
35
+ const n = Number(r.n);
36
+ frozen += n;
37
+ if (!KNOWN_STATES.includes(r.state)) problems.push(`unknown_state:${r.state}`);
38
+ if (r.state === 'done') sent += n;
39
+ else if (r.state === 'failed') failed += n;
40
+ else if (r.state === 'uncertain') uncertain += n;
41
+ else if (r.state === 'planned' || r.state === 'enqueued') pending += n;
42
+ else if (r.state === 'skipped') {
43
+ const why = r.skip_reason ?? 'unknown';
44
+ if (!KNOWN_SKIPS.includes(why)) problems.push(`unknown_skip_reason:${why}`);
45
+ skipped[why] = (skipped[why] ?? 0) + n;
46
+ skippedTotal += n;
47
+ }
48
+ }
49
+ if (frozen === 0) problems.push('nothing_frozen');
50
+ if (frozen !== sent + skippedTotal + failed + uncertain + pending) problems.push('counts_do_not_add_up');
51
+ // 凍結當下記下的人數:之後有人憑空多出來或消失,這裡會對不上。
52
+ const stored = await db.prepare("SELECT json_extract(counts, '$.frozen') AS n FROM campaigns WHERE id = ?").bind(campaignId).first<{ n: number | null }>();
53
+ if (stored?.n === null || stored?.n === undefined) problems.push('frozen_count_missing');
54
+ else if (Number(stored.n) !== frozen) problems.push(`frozen_${stored.n}_now_${frozen}`);
55
+ if (pending > 0) problems.push(`pending:${pending}`);
56
+ if (uncertain > 0) problems.push(`uncertain:${uncertain}`);
57
+
58
+ // 帳本:這期的去重鍵是 c:{期號}:…(用範圍比較,不用 LIKE)。
59
+ const lo = `c:${campaignId}:`;
60
+ const hi = `c:${campaignId};`;
61
+ const ledger = await db
62
+ .prepare("SELECT COUNT(*) AS n FROM messages WHERE site = ? AND dedupe_key >= ? AND dedupe_key < ? AND status = 'sent'")
63
+ .bind(cfg.site, lo, hi)
64
+ .first<{ n: number }>();
65
+ const ledgerSent = Number(ledger?.n ?? 0);
66
+ if (ledgerSent !== sent) problems.push(`ledger_sent_${ledgerSent}_vs_done_${sent}`);
67
+ const orphan = await db
68
+ .prepare(
69
+ `SELECT COUNT(*) AS n FROM campaign_recipients r LEFT JOIN messages m ON m.id = r.message_id
70
+ WHERE r.campaign_id = ? AND r.state = 'done'
71
+ AND (m.id IS NULL OR m.status != 'sent' OR m.site != ? OR m.dedupe_key != 'c:' || r.campaign_id || ':' || r.contact_id)`,
72
+ )
73
+ .bind(campaignId, cfg.site)
74
+ .first<{ n: number }>();
75
+ const doneWithoutLedger = Number(orphan?.n ?? 0);
76
+ if (doneWithoutLedger > 0) problems.push(`done_without_ledger:${doneWithoutLedger}`);
77
+
78
+ // 郵差事件(以人計)。
79
+ const ev = await db
80
+ .prepare(
81
+ `SELECT
82
+ COUNT(DISTINCT CASE WHEN type = 'send' THEN contact_id END) AS sends,
83
+ COUNT(DISTINCT CASE WHEN type = 'delivery' THEN contact_id END) AS delivered,
84
+ COUNT(DISTINCT CASE WHEN type = 'bounce' AND subtype LIKE 'Permanent%' THEN contact_id END) AS hard,
85
+ COUNT(DISTINCT CASE WHEN type = 'bounce' AND (subtype IS NULL OR subtype NOT LIKE 'Permanent%') THEN contact_id END) AS soft,
86
+ COUNT(DISTINCT CASE WHEN type = 'complaint' THEN contact_id END) AS complained,
87
+ COUNT(DISTINCT CASE WHEN type IN ('delivery', 'bounce') THEN contact_id END) AS outcome
88
+ FROM events WHERE campaign_id = ?`,
89
+ )
90
+ .bind(campaignId)
91
+ .first<{ sends: number; delivered: number; hard: number; soft: number; complained: number; outcome: number }>();
92
+ const dup = await db
93
+ .prepare("SELECT COUNT(*) AS n FROM (SELECT contact_id FROM events WHERE campaign_id = ? AND type = 'send' GROUP BY contact_id HAVING COUNT(DISTINCT COALESCE(provider_message_id, provider_event_id)) > 1)")
94
+ .bind(campaignId)
95
+ .first<{ n: number }>();
96
+ const sends = Number(ev?.sends ?? 0);
97
+ const outcome = Number(ev?.outcome ?? 0);
98
+ const duplicateSends = Number(dup?.n ?? 0);
99
+ if (sends > sent) problems.push(`send_events_${sends}_exceed_sent_${sent}`);
100
+ if (duplicateSends > 0) problems.push(`duplicate_send_events:${duplicateSends}`);
101
+ // 有送出事件的郵差:送達+退信不能比送出多。
102
+ if (sends > 0 && outcome > sends) problems.push(`outcomes_${outcome}_exceed_send_events_${sends}`);
103
+
104
+ return {
105
+ campaign: campaignId,
106
+ ok: problems.length === 0,
107
+ frozen, sent, skipped, skippedTotal, failed, uncertain, pending,
108
+ ledger: { sent: ledgerSent, doneWithoutLedger },
109
+ events: {
110
+ sends,
111
+ delivered: Number(ev?.delivered ?? 0),
112
+ hardBounced: Number(ev?.hard ?? 0),
113
+ softBounced: Number(ev?.soft ?? 0),
114
+ complained: Number(ev?.complained ?? 0),
115
+ awaiting: Math.max(0, (sends > 0 ? sends : sent) - outcome),
116
+ duplicateSends,
117
+ },
118
+ problems,
119
+ };
120
+ }