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
TypeScript50 lines1.9 KB
export interface LoadPlan { rate: number; durationSec: number; mix: Record<string, number>; poisonPct: number } export function clampPlan(p: Partial<LoadPlan>): LoadPlan {  const c = (n: unknown, lo: number, hi: number, d: number) => {    const x = typeof n === "number" && Number.isFinite(n) ? n : d;    return Math.min(Math.max(x, lo), hi);  };  return {    rate: Math.round(c(p.rate, 1, 500, 10)),    durationSec: Math.round(c(p.durationSec, 1, 600, 10)),    mix: p.mix && Object.keys(p.mix).length ? p.mix : { pageview: 1 },    poisonPct: c(p.poisonPct, 0, 100, 0),  };} /** Events to send in tick number `tick` (1s granularity split into `tickMs` ticks), carrying remainder. */export function eventsForTick(rate: number, tickMs: number, carry: number): { n: number; carry: number } {  const total = (rate * tickMs) / 1000 + carry;  const n = Math.floor(total);  return { n, carry: total - n };} /** Split n events into API batches of at most max (100). */export function splitBatches(n: number, max = 100): number[] {  const out: number[] = [];  for (let left = n; left > 0; left -= max) out.push(Math.min(max, left));  return out;} export function pickType(mix: Record<string, number>, rnd: number): string {  const e = Object.entries(mix).filter(([, w]) => w > 0);  const tot = e.reduce((a, [, w]) => a + w, 0);  if (!tot) return "pageview";  let r = rnd * tot;  for (const [k, w] of e) { if ((r -= w) < 0) return k; }  return e[e.length - 1][0];} export function makeEvent(plan: LoadPlan, rnd: () => number, now: number): Record<string, unknown> {  if (rnd() * 100 < plan.poisonPct) return { poison: true, type: 42, ts: now };  const countries = ["US", "DE", "BR", "IN", "JP", "GB"];  return {    type: pickType(plan.mix, rnd()),    path: ["/", "/docs", "/pricing", "/blog"][Math.floor(rnd() * 4)],    country: countries[Math.floor(rnd() * countries.length)],    value: Math.round(rnd() * 1000),    ts: now,  };}