Skip to content

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.

Build the full D1 + Queues pulse app: dashboard, load generator, dead letters, percentiles, docs8a65841
TypeScript43 lines1.9 KB
import * as Q from "./lib/sql";import { json, err, log, readText, type Env } from "./env"; type Dead = { id: number; body: string }; export async function dlq(req: Request, url: URL, env: Env): Promise<Response> {  if (url.pathname === "/api/dlq" && req.method === "GET") {    const r = await env.DB.prepare(Q.DLQ_LIST).all();    return json({ items: r.results, count: r.results.length });  }  if (url.pathname === "/api/dlq" && req.method === "DELETE") {    const r = await env.DB.prepare(Q.DLQ_DELETE_ALL).run();    log("dlq_purge", { deleted: r.meta?.changes ?? 0 });    return json({ deleted: r.meta?.changes ?? 0 });  }  if (url.pathname === "/api/dlq/replay" && req.method === "POST") {    let id: number | undefined;    const text = await readText(req);    if (text instanceof Response) return text;    if (text.trim()) {      try { const b = JSON.parse(text) as { id?: unknown } | null; if (b && b.id !== undefined) id = Number(b.id); }      catch { return err(400, "invalid_json", "invalid JSON"); }      if (id !== undefined && !Number.isInteger(id)) return err(400, "invalid_id", "id must be an integer");    }    const rows = id !== undefined      ? (await env.DB.prepare(Q.DLQ_ONE).bind(id).all<Dead>()).results      : (await env.DB.prepare(Q.DLQ_ALL).all<Dead>()).results;    if (id !== undefined && !rows.length) return err(404, "not_found", "dead letter not found");    const msgs: { body: unknown }[] = [];    const ids: number[] = [];    for (const r of rows) {      try { msgs.push({ body: JSON.parse(r.body) }); ids.push(r.id); } catch { /* unparsable stays */ }    }    if (msgs.length) {      await env.EVENTS.sendBatch(msgs);      await env.DB.batch(ids.map((i) => env.DB.prepare(Q.DLQ_DELETE_ONE).bind(i)));    }    log("dlq_replay", { replayed: msgs.length });    return json({ replayed: msgs.length });  }  return err(405, "method_not_allowed", "method not allowed");}