From ce5e94657b469db0768cb06e04d0aea2e674bee4 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Thu, 3 Dec 2026 17:57:15 -0800 Subject: [PATCH] Record how each scheduled email run went, and retry refused reminders The Worker keeps no logs, so a failing cron looked the same as a quiet one. Each run of the reminder and the Monday summary now writes cronRuns/{job}, and the Owner page shows it. A reminder batch the email provider refused (4xx) no longer counts as sent: the records are removed and the next run tries again. After a timeout or 5xx they stay, so nobody gets two. --- public/js/deck/owner.js | 7 +++++++ test/worker/winback.test.mjs | 35 +++++++++++++++++++++++++++++++++++ worker/cron-log.js | 36 ++++++++++++++++++++++++++++++++++++ worker/winback.js | 16 ++++++++++++---- worker/worker.js | 4 ++-- 5 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 worker/cron-log.js diff --git a/public/js/deck/owner.js b/public/js/deck/owner.js index ee635f67..9d9bb685 100644 --- a/public/js/deck/owner.js +++ b/public/js/deck/owner.js @@ -293,6 +293,12 @@ function paintInbox() { ${ib.errors && ib.errors.length > 20 ? `

Showing the newest 20 of ${ib.errors.length}.

` : ""}`; } +// How a scheduled email job last went (worker/cron-log.js) +function runLine(label, r) { + if (!r) return `

${label}: none recorded yet.

`; + return r.ok ? `

${label}: ${E(ago(r.at))}, ${r.sent} sent.

` : `

${label}: failed ${E(ago(r.at))}. ${E(r.note)}

`; +} + // The one-time reminder email to people who came once (worker/winback.js). function paintWb() { const host = S.el.querySelector("#ownWb"); if (!host) return; @@ -312,6 +318,7 @@ function paintWb() {
Next run${next.length ? next.length + (next.length === 1 ? " person" : " people") : "No one"}
${next.length ? `

${next.map(E).join(", ")}

` : ""} + ${runLine("Last reminder run", (w.runs || {}).winback)}${runLine("Last Monday summary run", (w.runs || {}).digest)}
`; } diff --git a/test/worker/winback.test.mjs b/test/worker/winback.test.mjs index 81c8db3c..e0acfef6 100644 --- a/test/worker/winback.test.mjs +++ b/test/worker/winback.test.mjs @@ -3,6 +3,7 @@ import { test, group, assert } from "../harness.mjs"; import { pickWinBack, buildWinBack, ownDomain, MAX_PER_RUN, runWinBack, handleWinBackStop } from "../../worker/winback.js"; import { matchRoute, authorize } from "../../worker/auth.js"; import { cronJob, WINBACK_CRON } from "../../worker/worker.js"; +import { runRecord, runJob } from "../../worker/cron-log.js"; import { KEYED_BY_UID } from "../../worker/account-delete.js"; const NOW = Date.parse("2026-11-29T15:00:00Z"); @@ -155,4 +156,38 @@ group("winback/runWinBack end to end", () => { assert.equal(calls.patch, null); } finally { globalThis.fetch = real; } }); + // Resend answers `status`; returns the calls made + const failing = async (status) => { + const calls = []; const real = globalThis.fetch, base = stub(calls); + globalThis.fetch = async (url, o = {}) => { + const u = String(url); + if (u === "https://api.resend.com/emails/batch") return { ok: false, status, json: async () => ({ message: "refused" }) }; + if (u.includes("/documents/cronRuns/")) { calls.run = JSON.parse(o.body).fields; return ok({}); } + return base(url, o); + }; + const err = console.error; console.error = () => {}; + const realDel = []; + try { + const env = await mkEnv(calls); + const inner = globalThis.fetch; + globalThis.fetch = async (url, o = {}) => { if (o.method === "DELETE") { realDel.push(String(url).split("/documents/")[1]); return ok({}); } return inner(url, o); }; + await runJob({ name: "winback", run: runWinBack }, env); + } finally { globalThis.fetch = real; console.error = err; } + return { run: calls.run, deleted: realDel }; + }; + test("a refused batch is retried next time and recorded as a failed run", async () => { + const r = await failing(422); + assert.deepEqual(r.deleted, ["winback/once"]); + assert.equal(r.run.ok.booleanValue, false); + assert.ok(r.run.note.stringValue.includes("422")); + }); + test("after a server error it may have gone out, so it is never sent again", async () => { + const r = await failing(500); + assert.deepEqual(r.deleted, []); + assert.equal(r.run.ok.booleanValue, false); + }); + test("a job switched off on this server records nothing", () => { + assert.equal(runRecord({ skipped: "off" }), null); + assert.deepEqual(runRecord({ sent: 2 }, 5), { at: 5, ok: true, sent: 2, note: "" }); + }); }); diff --git a/worker/cron-log.js b/worker/cron-log.js new file mode 100644 index 00000000..339118dc --- /dev/null +++ b/worker/cron-log.js @@ -0,0 +1,36 @@ +// How the last run of each scheduled email job went: Firestore cronRuns/{job} = { at, ok, sent, +// note }. The Worker keeps no logs, so without this a failing cron looks the same as a quiet one. +// Only this Worker writes it (no client rules, so clients are denied); the Owner page shows it. +import { googleToken } from "./digest.js"; +import { firestore, plainFields } from "./account-delete.js"; + +// result: what the job returned, or the Error it threw -> the record, or null for a job that is +// switched off on this server (staging). +export function runRecord(result, now = Date.now()) { + if (result instanceof Error) return { at: now, ok: false, sent: 0, note: result.message.slice(0, 200) }; + if (!result || result.skipped) return null; + return { at: now, ok: true, sent: Number(result.sent) || 0, note: "" }; +} + +export async function recordRun(env, job, result, now = Date.now()) { + const rec = runRecord(result, now); + if (!rec) return; + const token = await googleToken(env); + const fields = { at: { integerValue: String(rec.at) }, ok: { booleanValue: rec.ok }, sent: { integerValue: String(rec.sent) }, note: { stringValue: rec.note } }; + const r = await fetch("https://firestore.googleapis.com/v1/" + firestore(env, token).name("cronRuns/" + job), { method: "PATCH", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" }, body: JSON.stringify({ fields }) }); + if (!r.ok) throw new Error("run record " + r.status); +} + +// -> { winback: {...}, digest: {...} }, only the jobs that have run +export async function lastRuns(fs) { + return Object.fromEntries((await fs.list("cronRuns")).map((d) => [d.path.split("/").pop(), plainFields(d.fields)])); +} + +// Run a job and record the outcome. Never throws: a cron has no one to throw to. +export async function runJob(job, env) { + const log = (type, e) => console.error(JSON.stringify({ type, message: String((e && e.message) || e).slice(0, 300) })); + let result; + try { result = await job.run(env); } + catch (e) { result = e instanceof Error ? e : new Error(String(e)); log(job.name + "-error", e); } + try { await recordRun(env, job.name, result); } catch (e) { log("cron-log-error", e); } +} diff --git a/worker/winback.js b/worker/winback.js index 486154a3..f2513e31 100644 --- a/worker/winback.js +++ b/worker/winback.js @@ -16,6 +16,7 @@ import { SITE, FROM, googleToken, unsubToken, unsubSecret } from "./digest.js"; import { firestore, plainFields, doList } from "./account-delete.js"; import { listAuthAccounts } from "./admin-users.js"; +import { lastRuns } from "./cron-log.js"; import { personOf, isOwnerRow } from "../public/js/deck/owner-stats.js"; const DAY = 86400000; @@ -112,7 +113,7 @@ async function stopUrl(env, uid) { async function resend(env, path, payload) { const r = await fetch("https://api.resend.com" + path, { method: "POST", headers: { Authorization: "Bearer " + env.RESEND_KEY, "Content-Type": "application/json" }, body: JSON.stringify(payload) }); const d = await r.json().catch(() => ({})); - if (!r.ok) throw new Error("Email provider error (" + r.status + "): " + String(d.message || d.error || "").slice(0, 160)); + if (!r.ok) throw Object.assign(new Error("Email provider error (" + r.status + "): " + String(d.message || d.error || "").slice(0, 160)), { status: r.status }); return d; } const mail = (to, d, url) => ({ from: FROM, to: [to], subject: d.subject, html: d.html, text: d.text, @@ -146,7 +147,9 @@ async function eligible(env, data, now) { return out; } -// Cron. Records each reminder before sending it, so a failure can never send one twice. +// Cron. Records each reminder before sending it, so a failure can never send one twice. When the +// provider refused the batch (4xx) nothing went out, so the records are removed and the next run +// tries again; after a timeout or a 5xx it may have gone out, so they stay. export async function runWinBack(env, now = Date.now()) { if (env.WINBACK_CRON !== "on") return { skipped: "WINBACK_CRON is not on" }; if (!ready(env)) return { skipped: "not configured" }; @@ -160,7 +163,11 @@ export async function runWinBack(env, now = Date.now()) { if (!r.ok) throw new Error("winback record " + r.status); const out = []; for (const c of picks) { const url = await stopUrl(env, c.uid); out.push(mail(c.email, buildWinBack({ email: c.email, joined: c.joined, stopUrl: url, now }), url)); } - await resend(env, "/emails/batch", out); + try { await resend(env, "/emails/batch", out); } + catch (e) { + if (e.status >= 400 && e.status < 500) for (const c of picks) await data.fs.del("winback/" + c.uid); + throw e; + } console.log(JSON.stringify({ type: "winback", sent: out.length })); return { sent: out.length }; } @@ -181,11 +188,12 @@ export async function handleAdminWinBack(request, env, json, principal) { return json({ ok: true, to }); } const data = await gather(env, token); - const next = await eligible(env, data, Date.now()); + const [next, runs] = await Promise.all([eligible(env, data, Date.now()), lastRuns(data.fs)]); return json({ on: env.WINBACK_CRON === "on", sent: [...data.sent].map(([uid, w]) => ({ uid, sentAt: Number(w.sentAt) || null, off: !!w.off })), next: next.map((c) => c.uid), + runs, }); } catch (e) { return json({ error: String((e && e.message) || e).slice(0, 200) }, 502); } } diff --git a/worker/worker.js b/worker/worker.js index 8b12e67c..0e240ee7 100644 --- a/worker/worker.js +++ b/worker/worker.js @@ -30,6 +30,7 @@ import { GEMINI_MODELS, CLAUDE_PLAN, userTier, planDenied } from "./plan.js"; import { chargeQuota, refundQuota, quotaMessage } from "./quota.js"; import { handleDigest, handleUnsubscribe, runDigest } from "./digest.js"; import { handleAdminUsers } from "./admin-users.js"; +import { runJob } from "./cron-log.js"; import { runWinBack, handleAdminWinBack, handleWinBackStop, STOP_PATH as WINBACK_STOP_PATH } from "./winback.js"; import { handleAccountDelete, handleAccountExport, handleAdminDeletions } from "./account-delete.js"; import { handleUsage } from "./usage.js"; @@ -749,8 +750,7 @@ export default { // Crons in wrangler.toml, production only: the Monday digest (DIGEST_CRON) and the daily // one-time reminder (WINBACK_CRON). async scheduled(event, env, ctx) { - const job = cronJob(event.cron); - ctx.waitUntil(job.run(env).catch((e) => console.error(JSON.stringify({ type: job.name + "-error", message: String((e && e.message) || e).slice(0, 300) })))); + ctx.waitUntil(runJob(cronJob(event.cron), env)); }, };