gitflarePublicPartly agent-ready50
cf-d1-queues-pulse
Event analytics on Cloudflare D1 and Queues: ingestion API, batched consumer, rollups, live dashboard, load generator, dead-letter view.
- LicenseApache-2.0
- LanguageTypeScript
- Last landed
8a65841Oct 20, 2026
Build the full D1 + Queues pulse app: dashboard, load generator, dead letters, percentiles, docs
8a65841import { validateBatch } from "./lib/validate";import { json, err, log, readText, type Env } from "./env";import { stats } from "./stats";import { dlq } from "./dlq"; const HEADERS = { "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "x-frame-options": "DENY", "content-security-policy": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; frame-ancestors 'none'",};export const isPoison = (x: unknown) => !!x && typeof x === "object" && (x as Record<string, unknown>).poison === true; export async function route(req: Request, env: Env): Promise<Response> { const url = new URL(req.url); const p = url.pathname; if (p === "/health") return json({ ok: true }); if (p === "/api/events") { if (req.method !== "POST") return err(405, "method_not_allowed", "use POST"); const text = await readText(req); if (text instanceof Response) return text; let v: unknown; try { v = JSON.parse(text); } catch { return err(400, "invalid_json", "invalid JSON"); } const items = Array.isArray(v) ? v : [v]; if (items.length > 100) return err(400, "too_many_events", "too many events (max 100)"); const poison = items.filter(isPoison); const r = validateBatch(items.filter((i) => !isPoison(i)), Date.now()); if ("error" in r) return err(400, "too_many_events", String(r.error)); const send = [...r.accepted, ...poison]; if (send.length) await env.EVENTS.sendBatch(send.map((x) => ({ body: x }))); log("events_accepted", { accepted: send.length, rejected: r.rejected }); return json({ accepted: send.length, rejected: r.rejected }, 202); } if (p === "/api/stats") { if (req.method !== "GET") return err(405, "method_not_allowed", "use GET"); return json(await stats(url, env)); } if (p === "/api/dlq" || p === "/api/dlq/replay") return dlq(req, url, env); if (p.startsWith("/api/")) return err(404, "not_found", "not found"); const res = await env.ASSETS.fetch(req); if ((res.headers.get("content-type") ?? "").includes("text/html")) { const h = new Headers(res.headers); for (const [k, v] of Object.entries(HEADERS)) h.set(k, v); return new Response(res.body, { status: res.status, headers: h }); } return res;}