Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions public/js/deck/owner.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,12 @@ function paintInbox() {
${ib.errors && ib.errors.length > 20 ? `<p class="own-empty">Showing the newest 20 of ${ib.errors.length}.</p>` : ""}`;
}

// How a scheduled email job last went (worker/cron-log.js)
function runLine(label, r) {
if (!r) return `<p class="own-empty">${label}: none recorded yet.</p>`;
return r.ok ? `<p class="own-empty">${label}: ${E(ago(r.at))}, ${r.sent} sent.</p>` : `<p class="own-err">${label}: failed ${E(ago(r.at))}. ${E(r.note)}</p>`;
}

// The one-time reminder email to people who came once (worker/winback.js).
function paintWb() {
const host = S.el.querySelector("#ownWb"); if (!host) return;
Expand All @@ -312,6 +318,7 @@ function paintWb() {
<div><span>Next run</span><b>${next.length ? next.length + (next.length === 1 ? " person" : " people") : "No one"}</b></div>
</div>
${next.length ? `<p class="own-note" style="margin-top:8px">${next.map(E).join(", ")}</p>` : ""}
${runLine("Last reminder run", (w.runs || {}).winback)}${runLine("Last Monday summary run", (w.runs || {}).digest)}
<div class="own-row"><button class="own-btn" data-act="wbtest">Send me a test</button></div>`;
}

Expand Down
35 changes: 35 additions & 0 deletions test/worker/winback.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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: "" });
});
});
36 changes: 36 additions & 0 deletions worker/cron-log.js
Original file line number Diff line number Diff line change
@@ -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); }
}
16 changes: 12 additions & 4 deletions worker/winback.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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" };
Expand All @@ -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 };
}
Expand All @@ -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); }
}
Expand Down
4 changes: 2 additions & 2 deletions worker/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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));
},
};

Expand Down
Loading