Something went wrong. Try again.
Extremely basic alerting on health endpoints using Cloudflare durable objects
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import { EmailMessage } from "cloudflare:email";import { REGION_NAMES, type Check, type Region } from "./monitor";
export type AlertKind = "down" | "still down" | "recovered";
/** Sends an alert email. Returns false (and logs) on failure rather than throwing. */export async function sendAlert( env: Env, kind: AlertKind, check: Check, failingSince: number | null, failingRegions: Region[] = [],): Promise<boolean> { const host = check.endpoint.replace(/^https?:\/\//, ""); const result = check.status ? `HTTP ${check.status}` : (check.error ?? "no response"); const subject = `[monitor] ${kind.toUpperCase()}: ${host} (${result}) from ${check.region}`; const lines = [ `Endpoint: ${check.endpoint}`, `Region: ${check.region} (${REGION_NAMES[check.region]})`, `Result: ${result}`, `Checked: ${new Date(check.ts).toISOString()}`, `Latency: ${check.duration_ms} ms`, ]; if (failingSince !== null) lines.push(`Failing since: ${new Date(failingSince).toISOString()}`); if (failingRegions.length) lines.push(`Failing from: ${failingRegions.join(", ")}`); if (check.error && check.status) lines.push(`Error: ${check.error}`); lines.push( `History: ${env.PUBLIC_URL}/endpoint?url=${encodeURIComponent(check.endpoint)}`, "", "Response body:", prettyJson(check.body) ?? "(empty)", );
// Raw MIME goes out through Email Routing to the verified destination address. (The structured // builder form of send() uses Email Sending, which needs separate per-domain setup.) const raw = mimeMessage({ from: env.ALERT_FROM, to: env.ALERT_TO, subject, text: lines.join("\n") }); try { await env.EMAIL.send(new EmailMessage(env.ALERT_FROM, env.ALERT_TO, raw)); console.log("alert email sent", { endpoint: check.endpoint, kind, subject }); return true; } catch (e) { console.error("alert email failed", { endpoint: check.endpoint, kind, error: String(e) }); return false; }}
/** Pretty-prints JSON bodies; returns other bodies unchanged and null when there is no body. */export function prettyJson(body: string | null): string | null { if (!body) return null; try { return JSON.stringify(JSON.parse(body), null, 2); } catch { return body; }}
/** Builds a minimal RFC 5322 plain-text message. Subject and body are base64 so any UTF-8 is safe. */export function mimeMessage(m: { from: string; to: string; subject: string; text: string; date?: Date }): string { const domain = m.from.split("@")[1]; const headers = [ `From: Monitor <${m.from}>`, `To: ${m.to}`, `Subject: =?UTF-8?B?${base64(m.subject)}?=`, `Date: ${(m.date ?? new Date()).toUTCString()}`, `Message-ID: <${crypto.randomUUID()}@${domain}>`, "MIME-Version: 1.0", "Content-Type: text/plain; charset=utf-8", "Content-Transfer-Encoding: base64", ]; const body = base64(m.text).replace(/.{1,76}/g, "$&\r\n"); return headers.join("\r\n") + "\r\n\r\n" + body;}
function base64(s: string): string { const bytes = new TextEncoder().encode(s); let binary = ""; for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(binary);}