@joelincc/mailroom 0.0.0-stage → 0.3.0
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.
- package/LICENSE +21 -0
- package/README.md +207 -2
- package/SECURITY.md +11 -0
- package/bin/mailroom.mjs +26 -0
- package/dist/broadcast/config.js +79 -0
- package/dist/broadcast/explain.js +50 -0
- package/dist/cli/args.js +29 -0
- package/dist/cli/errors.js +31 -0
- package/dist/cli/main.js +475 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +224 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +637 -0
- package/dist/compose/personalize.js +123 -0
- package/dist/compose/preflight.js +251 -0
- package/dist/compose/preview.js +41 -0
- package/dist/compose/render.js +136 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +135 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +51 -0
- package/docs/lists.md +66 -0
- package/docs/security-model.md +82 -0
- package/docs/ses.md +116 -0
- package/docs/unsubscribe.md +117 -0
- package/migrations/0001_init.sql +42 -0
- package/migrations/0002_tier.sql +4 -0
- package/migrations/0003_rate.sql +9 -0
- package/migrations/0004_last_error.sql +2 -0
- package/migrations/0005_lists.sql +41 -0
- package/migrations/0006_broadcast.sql +154 -0
- package/migrations/0007_unsubscribe.sql +12 -0
- package/package.json +64 -4
- package/src/alert.ts +123 -0
- package/src/aws-sigv4.ts +100 -0
- package/src/broadcast/audience.ts +96 -0
- package/src/broadcast/campaigns.ts +339 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +766 -0
- package/src/broadcast/events.ts +107 -0
- package/src/broadcast/explain.ts +73 -0
- package/src/broadcast/freeze.ts +93 -0
- package/src/broadcast/index.ts +21 -0
- package/src/broadcast/postman.ts +229 -0
- package/src/broadcast/reconcile.ts +120 -0
- package/src/broadcast/routes.ts +181 -0
- package/src/broadcast/ses.ts +181 -0
- package/src/broadcast/stats.ts +59 -0
- package/src/broadcast/status.ts +60 -0
- package/src/broadcast/test-send.ts +88 -0
- package/src/broadcast/warmup.ts +150 -0
- package/src/broadcast/worker.ts +177 -0
- package/src/cf-events.ts +84 -0
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +33 -0
- package/src/cli/main.ts +466 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +257 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +624 -0
- package/src/compose/personalize.ts +130 -0
- package/src/compose/preflight.ts +250 -0
- package/src/compose/preview.ts +58 -0
- package/src/compose/render.ts +153 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +328 -0
- package/src/export.ts +184 -0
- package/src/feedback.ts +111 -0
- package/src/http.ts +17 -0
- package/src/index.ts +378 -0
- package/src/list-routes.ts +42 -0
- package/src/lists.ts +370 -0
- package/src/ses-events.ts +426 -0
- package/src/transport.ts +193 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +101 -0
- package/wrangler.example.jsonc +56 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// 暖機梯子:每一步寫「這期寄給哪幾群(分波)、最多幾人、過關條件」。
|
|
2
|
+
// 目前這一步=已放行的最高一步(第一步不用放行)。上一期過關才放行下一步;不過關=下一期維持同一步;
|
|
3
|
+
// 連續 gateMaxFails 期不過關=這條梯子鎖住,開寄時直接擋下,要明確解鎖(寫原因)才繼續。
|
|
4
|
+
// 過關比的是「同一批人」在換郵差前的開信率基準(由分析端算好傳進來),不比全名單。
|
|
5
|
+
|
|
6
|
+
import type { Db } from '../core.ts';
|
|
7
|
+
import { checkWaves, CAMPAIGN_ID, getCampaign } from './campaigns.ts';
|
|
8
|
+
import type { BroadcastConfig } from './config.ts';
|
|
9
|
+
import { campaignRates } from './stats.ts';
|
|
10
|
+
|
|
11
|
+
export interface WarmupStepRow {
|
|
12
|
+
plan_id: string; step: number; segments: string; max_count: number | null; gate: string | null;
|
|
13
|
+
released_at: string | null; blocked_reason: string | null; fails: number; last_eval: string | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface GateOverrides { bounceRate?: number; complaintRate?: number; openDrop?: number; waitHours?: number }
|
|
17
|
+
|
|
18
|
+
export interface StepInput { plan: string; step: number; waves: string[][]; maxCount?: number | null; gate?: GateOverrides }
|
|
19
|
+
|
|
20
|
+
const nowIso = (now?: () => Date) => (now ?? (() => new Date()))().toISOString();
|
|
21
|
+
|
|
22
|
+
export async function upsertWarmupStep(db: Db, input: StepInput): Promise<{ ok: true } | { ok: false; reason: string }> {
|
|
23
|
+
if (!input || typeof input.plan !== 'string' || !CAMPAIGN_ID.test(input.plan)) return { ok: false, reason: 'bad_plan' };
|
|
24
|
+
if (!Number.isInteger(input.step) || input.step < 1 || input.step > 100) return { ok: false, reason: 'bad_step' };
|
|
25
|
+
const waves = checkWaves(input.waves);
|
|
26
|
+
if (!waves) return { ok: false, reason: 'bad_waves' };
|
|
27
|
+
if (input.maxCount !== undefined && input.maxCount !== null && !(Number.isInteger(input.maxCount) && input.maxCount > 0)) return { ok: false, reason: 'bad_max_count' };
|
|
28
|
+
let gate: string | null = null;
|
|
29
|
+
if (input.gate !== undefined) {
|
|
30
|
+
const g: GateOverrides = {};
|
|
31
|
+
for (const k of ['bounceRate', 'complaintRate', 'openDrop'] as const) {
|
|
32
|
+
const v = input.gate[k];
|
|
33
|
+
if (v === undefined) continue;
|
|
34
|
+
if (typeof v !== 'number' || !(v >= 0 && v <= 1)) return { ok: false, reason: 'bad_gate' };
|
|
35
|
+
g[k] = v;
|
|
36
|
+
}
|
|
37
|
+
if (input.gate.waitHours !== undefined) {
|
|
38
|
+
if (typeof input.gate.waitHours !== 'number' || !(input.gate.waitHours > 0)) return { ok: false, reason: 'bad_gate' };
|
|
39
|
+
g.waitHours = input.gate.waitHours;
|
|
40
|
+
}
|
|
41
|
+
gate = JSON.stringify(g);
|
|
42
|
+
}
|
|
43
|
+
// 已放行/已鎖住的狀態不因改設定而清掉。
|
|
44
|
+
await db
|
|
45
|
+
.prepare(
|
|
46
|
+
`INSERT INTO warmup_steps (plan_id, step, segments, max_count, gate) VALUES (?, ?, ?, ?, ?)
|
|
47
|
+
ON CONFLICT (plan_id, step) DO UPDATE SET segments = excluded.segments, max_count = excluded.max_count, gate = excluded.gate`,
|
|
48
|
+
)
|
|
49
|
+
.bind(input.plan, input.step, JSON.stringify(waves), input.maxCount ?? null, gate)
|
|
50
|
+
.run();
|
|
51
|
+
return { ok: true };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function planSteps(db: Db, plan: string): Promise<WarmupStepRow[]> {
|
|
55
|
+
return (await db.prepare('SELECT * FROM warmup_steps WHERE plan_id = ? ORDER BY step').bind(plan).all<WarmupStepRow>()).results;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 目前這一步:已放行的最高一步;都沒放行就是最低那一步。 */
|
|
59
|
+
export async function currentStep(db: Db, plan: string): Promise<WarmupStepRow | null> {
|
|
60
|
+
const steps = await planSteps(db, plan);
|
|
61
|
+
if (steps.length === 0) return null;
|
|
62
|
+
const released = steps.filter((s) => s.released_at !== null);
|
|
63
|
+
return released.length ? released[released.length - 1] : steps[0];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 這條梯子有沒有被鎖住(任何一步有 blocked_reason)。 */
|
|
67
|
+
export async function planBlocked(db: Db, plan: string): Promise<string | null> {
|
|
68
|
+
const row = await db.prepare('SELECT blocked_reason FROM warmup_steps WHERE plan_id = ? AND blocked_reason IS NOT NULL LIMIT 1').bind(plan).first<{ blocked_reason: string }>();
|
|
69
|
+
return row?.blocked_reason ?? null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type GateResult =
|
|
73
|
+
| { result: 'pass'; step: number; advancedTo: number | null; rates: Record<string, number> }
|
|
74
|
+
| { result: 'fail'; step: number; reasons: string[]; fails: number; blocked: boolean; rates: Record<string, number> }
|
|
75
|
+
| { result: 'not_ready'; reasons: string[] }
|
|
76
|
+
| { result: 'already_evaluated'; last: unknown };
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 評一期信能不能讓梯子往上一步(上一期滿 waitHours 小時後評)。
|
|
80
|
+
* baselineOpenRate=這期收件的那幾群,在換郵差前 4 期的平均開信率(0~1,由分析端提供);沒給=不評(不放量)。
|
|
81
|
+
* 同一期只算一次(重複呼叫回 already_evaluated,不會重複累計不過關次數)。
|
|
82
|
+
*/
|
|
83
|
+
export async function evaluateWarmup(
|
|
84
|
+
db: Db,
|
|
85
|
+
plan: string,
|
|
86
|
+
campaignId: string,
|
|
87
|
+
baselineOpenRate: number | null | undefined,
|
|
88
|
+
cfg: BroadcastConfig,
|
|
89
|
+
now?: () => Date,
|
|
90
|
+
): Promise<GateResult> {
|
|
91
|
+
const step = await currentStep(db, plan);
|
|
92
|
+
if (!step) return { result: 'not_ready', reasons: ['unknown_plan'] };
|
|
93
|
+
if (step.last_eval) {
|
|
94
|
+
try {
|
|
95
|
+
const last = JSON.parse(step.last_eval) as { campaign?: string };
|
|
96
|
+
if (last.campaign === campaignId) return { result: 'already_evaluated', last };
|
|
97
|
+
} catch {
|
|
98
|
+
/* 壞掉的紀錄當沒評過 */
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const c = await getCampaign(db, campaignId);
|
|
102
|
+
if (!c) return { result: 'not_ready', reasons: ['unknown_campaign'] };
|
|
103
|
+
let resolved: { plan?: string; step?: number } = {};
|
|
104
|
+
try {
|
|
105
|
+
resolved = JSON.parse(c.audience_resolved ?? '{}');
|
|
106
|
+
} catch {
|
|
107
|
+
/* 下面擋 */
|
|
108
|
+
}
|
|
109
|
+
if (resolved.plan !== plan || resolved.step !== step.step) return { result: 'not_ready', reasons: ['campaign_not_on_current_step'] };
|
|
110
|
+
if (c.status !== 'done' || !c.finished_at) return { result: 'not_ready', reasons: ['campaign_not_done'] };
|
|
111
|
+
const gate: GateOverrides = step.gate ? JSON.parse(step.gate) : {};
|
|
112
|
+
const waitHours = gate.waitHours ?? cfg.gateWaitHours;
|
|
113
|
+
const t = (now ?? (() => new Date()))();
|
|
114
|
+
if (t.getTime() - Date.parse(c.finished_at) < waitHours * 3_600_000) return { result: 'not_ready', reasons: [`wait_${waitHours}h`] };
|
|
115
|
+
if (typeof baselineOpenRate !== 'number' || !(baselineOpenRate >= 0 && baselineOpenRate <= 1)) return { result: 'not_ready', reasons: ['baseline_missing'] };
|
|
116
|
+
|
|
117
|
+
const r = await campaignRates(db, campaignId);
|
|
118
|
+
const rates = { sent: r.sent, hardBounceRate: r.hardBounceRate, complaintRate: r.complaintRate, openRate: r.openRate, baselineOpenRate };
|
|
119
|
+
const reasons: string[] = [];
|
|
120
|
+
if (r.sent === 0) reasons.push('nothing_sent');
|
|
121
|
+
if (r.hardBounceRate > (gate.bounceRate ?? cfg.gateBounceRate)) reasons.push('bounce_rate');
|
|
122
|
+
if (r.complaintRate > (gate.complaintRate ?? cfg.gateComplaintRate)) reasons.push('complaint_rate');
|
|
123
|
+
if (r.openRate < baselineOpenRate - (gate.openDrop ?? cfg.gateOpenDrop)) reasons.push('open_rate_below_baseline');
|
|
124
|
+
// 對帳對不上也不放下一步。
|
|
125
|
+
const counts = c.counts ? (JSON.parse(c.counts) as { reconcileOk?: boolean }) : {};
|
|
126
|
+
if (counts.reconcileOk !== true) reasons.push('reconcile_not_ok');
|
|
127
|
+
|
|
128
|
+
const at = nowIso(now);
|
|
129
|
+
if (reasons.length === 0) {
|
|
130
|
+
const steps = await planSteps(db, plan);
|
|
131
|
+
const next = steps.find((s) => s.step > step.step) ?? null;
|
|
132
|
+
await db.prepare('UPDATE warmup_steps SET fails = 0, last_eval = ? WHERE plan_id = ? AND step = ?').bind(JSON.stringify({ campaign: campaignId, result: 'pass', at, rates }), plan, step.step).run();
|
|
133
|
+
if (next) await db.prepare('UPDATE warmup_steps SET released_at = ? WHERE plan_id = ? AND step = ? AND released_at IS NULL').bind(at, plan, next.step).run();
|
|
134
|
+
return { result: 'pass', step: step.step, advancedTo: next?.step ?? null, rates };
|
|
135
|
+
}
|
|
136
|
+
const fails = step.fails + 1;
|
|
137
|
+
const blocked = fails >= cfg.gateMaxFails;
|
|
138
|
+
await db
|
|
139
|
+
.prepare('UPDATE warmup_steps SET fails = ?, last_eval = ?, blocked_reason = CASE WHEN ? THEN COALESCE(blocked_reason, ?) ELSE blocked_reason END WHERE plan_id = ? AND step = ?')
|
|
140
|
+
.bind(fails, JSON.stringify({ campaign: campaignId, result: 'fail', at, reasons, rates }), blocked ? 1 : 0, `failed ${fails} gates in a row: ${reasons.join(',')}`, plan, step.step)
|
|
141
|
+
.run();
|
|
142
|
+
return { result: 'fail', step: step.step, reasons, fails, blocked, rates };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 解鎖:要寫查過什麼。清掉鎖與連續不過關次數,梯子停在原本那一步。 */
|
|
146
|
+
export async function unblockWarmup(db: Db, plan: string, note: string): Promise<{ ok: true; cleared: number } | { ok: false; reason: string }> {
|
|
147
|
+
if (typeof note !== 'string' || !note.trim()) return { ok: false, reason: 'note_required' };
|
|
148
|
+
const r = await db.prepare('UPDATE warmup_steps SET blocked_reason = NULL, fails = 0, last_eval = json_set(COALESCE(last_eval, \'{}\'), \'$.unblockNote\', ?) WHERE plan_id = ? AND blocked_reason IS NOT NULL').bind(note.trim().slice(0, 300), plan).run();
|
|
149
|
+
return { ok: true, cleared: r.meta.changes ?? 0 };
|
|
150
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Worker 端的接線:從環境變數組出群發要的東西(郵差、Queue、設定、個人化)。index.ts 只呼叫這裡的三個函式。
|
|
2
|
+
|
|
3
|
+
import { personalize } from '../compose/personalize.ts';
|
|
4
|
+
import { unsubscribeLinks, unsubSecrets } from '../unsub.ts';
|
|
5
|
+
import type { ListDb } from '../lists.ts';
|
|
6
|
+
import type { CampaignRow } from './campaigns.ts';
|
|
7
|
+
import { consumeBatch, tick, type BroadcastDeps, type BroadcastMessage, type QueueMessageLike, type RecipientRow, type RenderResult } from './dispatch.ts';
|
|
8
|
+
import type { IngestOptions } from './events.ts';
|
|
9
|
+
import { FakePostman, type FakeRule, type Postman } from './postman.ts';
|
|
10
|
+
import { parseAllowed, type TestSendDeps } from './test-send.ts';
|
|
11
|
+
import { SesPostman } from './ses.ts';
|
|
12
|
+
|
|
13
|
+
export interface BroadcastEnv {
|
|
14
|
+
DB: D1Database;
|
|
15
|
+
/** 電子報的寄件網域(例 mail.example.com)。沒設=群發整個關閉。 */
|
|
16
|
+
MARKETING_DOMAIN?: string;
|
|
17
|
+
/** 群發 Queue 的 producer 綁定。 */
|
|
18
|
+
BROADCAST?: Queue<BroadcastMessage>;
|
|
19
|
+
/** 群發 Queue 的名字(consumer 收到的 batch.queue),預設 mailroom-broadcast。 */
|
|
20
|
+
BROADCAST_QUEUE_NAME?: string;
|
|
21
|
+
/** 群發設定(JSON,只寫想改的欄位,見 docs/broadcast.md)。 */
|
|
22
|
+
BROADCAST_CONFIG?: string | Record<string, unknown>;
|
|
23
|
+
/** 自己的每日上限(覆寫 BROADCAST_CONFIG 的 maxPerDay)。 */
|
|
24
|
+
NEWSLETTER_MAX_PER_DAY?: string | number;
|
|
25
|
+
/** 電子報的郵差:"ses"(Amazon SES)或 "fake"(開發與演習用,不真的寄)。沒設=群發關閉。 */
|
|
26
|
+
NEWSLETTER_POSTMAN?: string;
|
|
27
|
+
/** SES 地區(例 us-east-1)。郵差與事件入口共用。 */
|
|
28
|
+
SES_REGION?: string;
|
|
29
|
+
/** SES 寄信鑰匙(Secret):IAM 只給 ses:SendEmail 與 ses:GetAccount。 */
|
|
30
|
+
SES_ACCESS_KEY_ID?: string;
|
|
31
|
+
SES_SECRET_ACCESS_KEY?: string;
|
|
32
|
+
/** SES 設定組(事件發布到 SNS)。 */
|
|
33
|
+
SES_CONFIGURATION_SET?: string;
|
|
34
|
+
/** 假郵差設定(JSON):{ "rules": [{ "match": "bounce", "outcome": "hard_bounce" }], "limits": { "perSecond": 1, "perDay": 200 } }。 */
|
|
35
|
+
FAKE_POSTMAN?: string | Record<string, unknown>;
|
|
36
|
+
/** 退訂券(與退訂模組共用):每封信的退訂連結與一鍵退訂標頭靠它們產生;沒設=每期都會因 render_error 暫停。 */
|
|
37
|
+
UNSUB_TOKEN_SECRET?: string;
|
|
38
|
+
UNSUB_TOKEN_SECRET_PREVIOUS?: string;
|
|
39
|
+
UNSUB_BASE_URL?: string;
|
|
40
|
+
UNSUB_MAILTO?: string;
|
|
41
|
+
/** 允許收測試信的內部信箱(JSON 陣列或逗號分隔)。沒設=測試信功能關閉。 */
|
|
42
|
+
TEST_RECIPIENTS?: string | string[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_BROADCAST_QUEUE = 'mailroom-broadcast';
|
|
46
|
+
|
|
47
|
+
function jsonObject(v: unknown): Record<string, unknown> {
|
|
48
|
+
if (v && typeof v === 'object' && !Array.isArray(v)) return v as Record<string, unknown>;
|
|
49
|
+
if (typeof v !== 'string' || !v.trim()) return {};
|
|
50
|
+
try {
|
|
51
|
+
const p = JSON.parse(v);
|
|
52
|
+
return p && typeof p === 'object' && !Array.isArray(p) ? p : {};
|
|
53
|
+
} catch {
|
|
54
|
+
console.error('bad broadcast json var');
|
|
55
|
+
return {};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function postmanFor(env: BroadcastEnv): Postman | null {
|
|
60
|
+
if (env.NEWSLETTER_POSTMAN === 'fake') {
|
|
61
|
+
const cfg = jsonObject(env.FAKE_POSTMAN);
|
|
62
|
+
const rules = Array.isArray(cfg.rules) ? (cfg.rules as FakeRule[]).filter((r) => r && typeof r.match === 'string' && typeof r.outcome === 'string') : [];
|
|
63
|
+
return new FakePostman({
|
|
64
|
+
rules,
|
|
65
|
+
limits: jsonObject(cfg.limits) as never,
|
|
66
|
+
// 假事件丟回同一個 Queue,延遲幾秒回來(模擬郵差的事後回報)。
|
|
67
|
+
emit: async (event, delayMs) => {
|
|
68
|
+
await env.BROADCAST?.send({ kind: 'event', event }, { delaySeconds: Math.max(1, Math.min(43_200, Math.ceil(delayMs / 1000))) });
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
if (env.NEWSLETTER_POSTMAN === 'ses') {
|
|
73
|
+
if (!env.SES_REGION || !env.SES_ACCESS_KEY_ID || !env.SES_SECRET_ACCESS_KEY || !env.SES_CONFIGURATION_SET) {
|
|
74
|
+
console.error('ses postman needs SES_REGION, SES_ACCESS_KEY_ID, SES_SECRET_ACCESS_KEY, SES_CONFIGURATION_SET; broadcasting disabled');
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
return new SesPostman({
|
|
79
|
+
region: env.SES_REGION,
|
|
80
|
+
credentials: { accessKeyId: env.SES_ACCESS_KEY_ID, secretAccessKey: env.SES_SECRET_ACCESS_KEY },
|
|
81
|
+
configurationSet: env.SES_CONFIGURATION_SET,
|
|
82
|
+
});
|
|
83
|
+
} catch (e) {
|
|
84
|
+
console.error('ses postman config error, broadcasting disabled', e instanceof Error ? e.message : 'unknown');
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (env.NEWSLETTER_POSTMAN) console.error('unknown NEWSLETTER_POSTMAN, broadcasting disabled');
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
type Links = { unsubscribe_url: string; unsubscribe_mailto?: string | null };
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 預設的個人化:compose 的 personalize({{name}} {{email}} {{unsubscribe_url}} {{unsubscribe_mailto}} {{web_url}},標頭一起填)。
|
|
96
|
+
* 退訂連結由 links 提供;拿不到=丟例外(這期會被暫停,不寄出沒有退訂連結的信)。
|
|
97
|
+
*/
|
|
98
|
+
export function personalizeRender(links?: (c: CampaignRow, r: RecipientRow) => Links | null | Promise<Links | null>, track?: Parameters<typeof personalize>[2]) {
|
|
99
|
+
return async (c: CampaignRow, r: RecipientRow & { name: string | null }): Promise<RenderResult> => {
|
|
100
|
+
const l = await links?.(c, r);
|
|
101
|
+
if (!l) throw new Error('unsubscribe links not configured');
|
|
102
|
+
if (!c.web_url) throw new Error('campaign has no web_url');
|
|
103
|
+
let headers: Record<string, string> = {};
|
|
104
|
+
try {
|
|
105
|
+
headers = c.headers ? (JSON.parse(c.headers) as Record<string, string>) : {};
|
|
106
|
+
} catch {
|
|
107
|
+
throw new Error('bad campaign headers');
|
|
108
|
+
}
|
|
109
|
+
return personalize({ html: c.html, text: c.text, headers }, { name: r.name, email: r.email, web_url: c.web_url, ...l }, track);
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 退訂券產生的連結(每位收件人一張券,綁名單、聯絡人、期別)。 */
|
|
114
|
+
export function unsubLinksFromEnv(env: BroadcastEnv) {
|
|
115
|
+
return async (c: CampaignRow, r: RecipientRow): Promise<Links | null> => {
|
|
116
|
+
const secrets = unsubSecrets(env.UNSUB_TOKEN_SECRET, env.UNSUB_TOKEN_SECRET_PREVIOUS);
|
|
117
|
+
if (!secrets.length || !env.UNSUB_BASE_URL) return null;
|
|
118
|
+
const l = await unsubscribeLinks(secrets, { baseUrl: env.UNSUB_BASE_URL, mailtoAddress: env.UNSUB_MAILTO }, { list: c.list_id, contactId: r.contact_id, campaign: c.id });
|
|
119
|
+
return { unsubscribe_url: l.url, unsubscribe_mailto: l.mailto };
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface BroadcastWiring {
|
|
124
|
+
render?: BroadcastDeps['render'];
|
|
125
|
+
feedback?: IngestOptions['feedback'];
|
|
126
|
+
alert?: BroadcastDeps['alert'];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function broadcastDeps(env: BroadcastEnv, wiring: BroadcastWiring = {}): BroadcastDeps | null {
|
|
130
|
+
if (!env.MARKETING_DOMAIN || !env.BROADCAST) return null;
|
|
131
|
+
const postman = postmanFor(env);
|
|
132
|
+
if (!postman) return null;
|
|
133
|
+
const config = jsonObject(env.BROADCAST_CONFIG);
|
|
134
|
+
if (env.NEWSLETTER_MAX_PER_DAY !== undefined && env.NEWSLETTER_MAX_PER_DAY !== '') config.maxPerDay = env.NEWSLETTER_MAX_PER_DAY;
|
|
135
|
+
return {
|
|
136
|
+
db: env.DB as unknown as ListDb,
|
|
137
|
+
postman,
|
|
138
|
+
domain: env.MARKETING_DOMAIN.toLowerCase(),
|
|
139
|
+
queue: env.BROADCAST as unknown as BroadcastDeps['queue'],
|
|
140
|
+
config,
|
|
141
|
+
render: wiring.render ?? personalizeRender(unsubLinksFromEnv(env)),
|
|
142
|
+
feedback: wiring.feedback,
|
|
143
|
+
alert: wiring.alert ?? ((a) => (a.level === 'info' ? console.log : console.warn)('broadcast', a.level, a.code, a.campaign ?? '-', a.message)),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 管理入口的測試信設定(郵差、個人化、白名單)。群發沒開=undefined。 */
|
|
148
|
+
export function testSendDeps(env: BroadcastEnv, wiring: BroadcastWiring = {}): Omit<TestSendDeps, 'domain' | 'now'> | undefined {
|
|
149
|
+
const d = broadcastDeps(env, wiring);
|
|
150
|
+
return d ? { postman: d.postman, render: d.render, allowed: parseAllowed(env.TEST_RECIPIENTS) } : undefined;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 排程每分鐘呼叫。沒設定群發就什麼都不做。 */
|
|
154
|
+
export async function broadcastTick(env: BroadcastEnv, wiring?: BroadcastWiring): Promise<void> {
|
|
155
|
+
const deps = broadcastDeps(env, wiring);
|
|
156
|
+
if (!deps) return;
|
|
157
|
+
const r = await tick(deps);
|
|
158
|
+
const released = Object.values(r.released).reduce((a, b) => a + b, 0);
|
|
159
|
+
if (released || r.started.length || r.paused.length || r.finished.length) {
|
|
160
|
+
console.log('broadcast tick', JSON.stringify({ started: r.started, released, paused: r.paused, finished: r.finished }));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 這一批是不是群發 Queue 的。 */
|
|
165
|
+
export function isBroadcastBatch(env: BroadcastEnv, queueName: string): boolean {
|
|
166
|
+
return queueName === (env.BROADCAST_QUEUE_NAME || DEFAULT_BROADCAST_QUEUE);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function broadcastQueue(env: BroadcastEnv, messages: readonly QueueMessageLike[], wiring?: BroadcastWiring): Promise<void> {
|
|
170
|
+
const deps = broadcastDeps(env, wiring);
|
|
171
|
+
if (!deps) {
|
|
172
|
+
// 群發關掉了:訊息留著(重送),不要默默丟掉。
|
|
173
|
+
for (const m of messages) m.retry({ delaySeconds: 300 });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
await consumeBatch(deps, messages);
|
|
177
|
+
}
|
package/src/cf-events.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Cloudflare 寄信的事後回報:Cloudflare 把寄件網域的送達/退信/檢舉事件放進 Queue
|
|
2
|
+
// (官方 event-subscriptions,來源 Email Sending,每個寄件網域一份訂閱),郵務室當消費者讀進來。
|
|
3
|
+
// 跟 Resend 的 webhook 進同一份拒收名單、同一張帳本(messages.provider_id=Cloudflare 回的 messageId)。
|
|
4
|
+
// 文件:https://developers.cloudflare.com/email-service/reference/event-subscriptions/(2026-11-04 查)
|
|
5
|
+
|
|
6
|
+
import { type Db } from './core.ts';
|
|
7
|
+
import { applyFeedback } from './feedback.ts';
|
|
8
|
+
|
|
9
|
+
interface CfEmailEvent {
|
|
10
|
+
type?: string;
|
|
11
|
+
source?: { type?: string; domain?: string };
|
|
12
|
+
payload?: {
|
|
13
|
+
eventId?: string;
|
|
14
|
+
messageId?: string;
|
|
15
|
+
recipient?: string;
|
|
16
|
+
terminal?: boolean;
|
|
17
|
+
delivery?: { status?: string; smtpStatusCode?: string; smtpResponse?: string };
|
|
18
|
+
bounce?: { type?: string; classification?: string; reason?: string };
|
|
19
|
+
failure?: { reason?: string };
|
|
20
|
+
rejection?: { reason?: string; party?: string; detail?: string };
|
|
21
|
+
complaint?: { type?: string };
|
|
22
|
+
};
|
|
23
|
+
metadata?: { eventTimestamp?: string };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const PREFIX = 'cf.email.sending.message.';
|
|
27
|
+
/** 事件 → 帳本 last_event(跟 Resend 那邊同一套字)。 */
|
|
28
|
+
const LAST_EVENT: Record<string, string> = {
|
|
29
|
+
delivered: 'delivered',
|
|
30
|
+
deferred: 'delayed',
|
|
31
|
+
bounced: 'bounced',
|
|
32
|
+
failed: 'failed',
|
|
33
|
+
rejected: 'rejected',
|
|
34
|
+
complained: 'complained',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** 處理一則 Cloudflare 寄信事件;回傳做了什麼(給 log/測試看)。同一則事件(eventId)只處理一次。 */
|
|
38
|
+
export async function handleCfEvent(db: Db, raw: unknown, now = new Date()): Promise<string> {
|
|
39
|
+
const ev = (typeof raw === 'string' ? safeParse(raw) : raw) as CfEmailEvent | null;
|
|
40
|
+
if (!ev || typeof ev !== 'object') return 'bad_event';
|
|
41
|
+
const type = String(ev.type ?? '');
|
|
42
|
+
if (ev.source?.type !== 'email.sending' || !type.startsWith(PREFIX)) return 'ignored';
|
|
43
|
+
const name = type.slice(PREFIX.length);
|
|
44
|
+
const p = ev.payload ?? {};
|
|
45
|
+
const eventKey = `cf:${p.eventId || `${p.messageId ?? '-'}:${name}:${ev.metadata?.eventTimestamp ?? ''}`}`;
|
|
46
|
+
// 先查有沒有處理過;處理完才記「已處理」(中途出錯時郵差重送還會再處理一次)。下面每一步都可重複執行不出錯。
|
|
47
|
+
const seen = await db.prepare('SELECT 1 AS x FROM webhook_events WHERE id = ?').bind(eventKey).first();
|
|
48
|
+
if (seen) return 'repeat';
|
|
49
|
+
const outcome = await applyEvent(db, ev, name, now);
|
|
50
|
+
await db.prepare('INSERT INTO webhook_events (id, type, received_at) VALUES (?, ?, ?) ON CONFLICT (id) DO NOTHING').bind(eventKey, type, now.toISOString()).run();
|
|
51
|
+
return outcome;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function applyEvent(db: Db, ev: CfEmailEvent, name: string, now: Date): Promise<string> {
|
|
55
|
+
const p = ev.payload ?? {};
|
|
56
|
+
|
|
57
|
+
const last = LAST_EVENT[name];
|
|
58
|
+
if (last && p.messageId) {
|
|
59
|
+
await db.prepare("UPDATE messages SET last_event = ?, updated_at = ? WHERE provider_id = ? AND route = 'cloudflare'").bind(last, now.toISOString(), p.messageId).run();
|
|
60
|
+
}
|
|
61
|
+
const email = String(p.recipient ?? '').trim().toLowerCase();
|
|
62
|
+
|
|
63
|
+
if (name === 'bounced') {
|
|
64
|
+
// 只有硬退信(信箱不存在、網域收不到)才進拒收名單;暫時性重試用完的 soft 不擋。
|
|
65
|
+
if (p.bounce?.type !== 'hard' || !email) return `bounce_${String(p.bounce?.type ?? 'unknown').toLowerCase()}`;
|
|
66
|
+
const detail = [p.bounce.classification, p.bounce.reason, p.delivery?.smtpStatusCode].filter(Boolean).join(': ');
|
|
67
|
+
await applyFeedback(db, { type: 'bounce', kind: 'permanent', email, source: 'cloudflare-event', detail: detail || null }, { now: () => now });
|
|
68
|
+
return 'hard_bounce:1';
|
|
69
|
+
}
|
|
70
|
+
if (name === 'complained') {
|
|
71
|
+
if (!email) return 'complaint:0';
|
|
72
|
+
await applyFeedback(db, { type: 'complaint', email, source: 'cloudflare-event', detail: p.complaint?.type ?? null }, { now: () => now });
|
|
73
|
+
return 'complaint:1';
|
|
74
|
+
}
|
|
75
|
+
return last ? `event:${last}` : 'ignored';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function safeParse(s: string): unknown {
|
|
79
|
+
try {
|
|
80
|
+
return JSON.parse(s);
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
package/src/cli/args.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// 指令列參數:--key value、--key=value、--flag。不收未知旗標(打錯字不能被默默吞掉)。
|
|
2
|
+
|
|
3
|
+
export interface ParsedArgs { positional: string[]; flags: Record<string, string | true> }
|
|
4
|
+
|
|
5
|
+
export function parseArgs(argv: readonly string[], spec: { values: readonly string[]; booleans: readonly string[] }): ParsedArgs | { error: string } {
|
|
6
|
+
const values = new Set(spec.values);
|
|
7
|
+
const booleans = new Set(spec.booleans);
|
|
8
|
+
const out: ParsedArgs = { positional: [], flags: {} };
|
|
9
|
+
for (let i = 0; i < argv.length; i++) {
|
|
10
|
+
const a = argv[i];
|
|
11
|
+
if (!a.startsWith('--')) {
|
|
12
|
+
out.positional.push(a);
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
const eq = a.indexOf('=');
|
|
16
|
+
const key = a.slice(2, eq === -1 ? undefined : eq);
|
|
17
|
+
if (booleans.has(key)) {
|
|
18
|
+
if (eq !== -1) return { error: `--${key} does not take a value` };
|
|
19
|
+
out.flags[key] = true;
|
|
20
|
+
} else if (values.has(key)) {
|
|
21
|
+
const v = eq !== -1 ? a.slice(eq + 1) : argv[++i];
|
|
22
|
+
if (v === undefined || (eq === -1 && v.startsWith('--'))) return { error: `--${key} needs a value` };
|
|
23
|
+
out.flags[key] = v;
|
|
24
|
+
} else return { error: `unknown option --${key}` };
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// 引擎回的失敗原因 → 人看得懂的一句話+下一步。找不到對照的,照實印原因代碼。
|
|
2
|
+
|
|
3
|
+
const TABLE: Record<string, [string, string]> = {
|
|
4
|
+
not_found: ['No such issue.', 'Check the issue id with `campaign status <id>`; create it with `campaign create` first.'],
|
|
5
|
+
illegal_transition: ['The issue is not in a state where this is allowed.', 'Run `campaign status <id>` to see the current state and what comes next.'],
|
|
6
|
+
illegal_state: ['The issue is not in a state where this is allowed (retry-failed works only while it is sending or paused; a finished (done) issue is closed for good: recipients that failed are recorded with their reason).', 'Run `campaign status <id>` to see the current state.'],
|
|
7
|
+
locked: ['The content is locked: sending has started.', 'Pause the issue first if it must change; a sent issue cannot be edited.'],
|
|
8
|
+
changed_meanwhile: ['The issue changed while the command ran.', 'Run `campaign status <id>` and try again.'],
|
|
9
|
+
conflict: ['An issue with this id already exists.', 'Use a different id or look at the existing one.'],
|
|
10
|
+
domain_held: ['The sender domain is on hold: every newsletter is stopped.', 'Read `campaign status <id>`, then release it with `hold release --note "..." --yes` (or, when this issue paused because of the hold: `campaign release <id> --release-domain`).'],
|
|
11
|
+
preview_required: ['This content has not been previewed yet (or it changed after the preview).', 'Run `campaign preview <id> --yes`, let the owner look at it, then approve.'],
|
|
12
|
+
duplicate_content: ['The same content already exists under another id.', 'Use the existing issue (or see the line above for what to change).'],
|
|
13
|
+
note_required: ['A note is required: who said yes, when, where.', 'Add --note "..."'],
|
|
14
|
+
reason_required: ['A reason is required.', 'Add --reason "..."'],
|
|
15
|
+
not_approved: ['The approval does not match the current content.', 'Preview and approve the current content again.'],
|
|
16
|
+
preflight_not_passed: ['The pre-send check has not passed for the current content.', 'Run `campaign create` again (or fix the source) until the check passes.'],
|
|
17
|
+
web_url_required: ['The issue has no web version URL.', 'Recreate it with --web-url.'],
|
|
18
|
+
bad_time: ['The time could not be understood.', 'Use "YYYY-MM-DD HH:MM" (local time) or a full ISO time.'],
|
|
19
|
+
unknown_plan: ['The warm-up plan does not exist.', 'Define it with the warm-up API before scheduling.'],
|
|
20
|
+
unknown_list: ['The list does not exist.', 'Check the list id.'],
|
|
21
|
+
recipient_not_allowed: ['That address is not on the test recipient list.', 'Test mail only goes to the addresses configured as TEST_RECIPIENTS.'],
|
|
22
|
+
test_recipients_not_configured: ['Test mail is not enabled on this deployment.', 'Set TEST_RECIPIENTS on the Worker.'],
|
|
23
|
+
bad_recipients: ['Give 1 to 10 test addresses.', 'Use --to a@example.com,b@example.com'],
|
|
24
|
+
bad_prefix: ['The subject prefix is not valid.', 'At most 20 characters, no line breaks.'],
|
|
25
|
+
not_uncertain: ['That recipient is not in the "uncertain" state.', 'Run `campaign status <id>` to see who is.'],
|
|
26
|
+
bad_json: ['The request body was not valid JSON.', 'This is a bug in the command: report it.'],
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export function friendly(reason: string, extra?: string): string {
|
|
30
|
+
const t = TABLE[reason];
|
|
31
|
+
const head = t ? `${t[0]} (${reason})` : `Refused: ${reason}`;
|
|
32
|
+
return [head, extra, t ? `Next: ${t[1]}` : 'Next: read the reason above; `campaign status <id>` shows the current state.'].filter(Boolean).join('\n');
|
|
33
|
+
}
|