From a222be66aa6d1e5cef6bb6978651ebf3c65a6227 Mon Sep 17 00:00:00 2001 From: Anthony Lukach Date: Thu, 19 Nov 2026 22:00:07 -0700 Subject: [PATCH 1/3] perf(log-stream): batch live-globe posts per isolate The proxy posted one event per public read to a single global Durable Object (~370 req/s at peak): about $145/month of Durable Object requests and CPU, plus overload exceptions in the busiest hours. An isolate runs in one datacenter, so each isolate now gathers its public reads for 3 s and posts one batch of exact per-product counts. A busy datacenter collapses into few posts; a quiet one still reports its first request. The hub adds the counts as posted, so the tick payload is unchanged. Only the colo and product counts leave the proxy now (no coordinates, city, country or key), and the hub still accepts the old one-request-per-post form for rollout. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.toml | 4 + adrs/008-analytics.md | 5 +- src/lib.rs | 3 +- src/location.rs | 86 ++++++++++--------- src/location_batch.rs | 38 ++++++++ tests/location_batch.rs | 42 +++++++++ workers/public-log-stream/src/aggregate.mjs | 25 ++++++ .../public-log-stream/src/aggregate.test.mjs | 24 +++++- workers/public-log-stream/src/location-hub.ts | 20 ++--- 9 files changed, 192 insertions(+), 55 deletions(-) create mode 100644 src/location_batch.rs create mode 100644 tests/location_batch.rs diff --git a/Cargo.toml b/Cargo.toml index 8b16ec15..ee7a207c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,10 @@ path = "tests/keys.rs" name = "trace" path = "tests/trace.rs" +[[test]] +name = "location_batch" +path = "tests/location_batch.rs" + [dependencies] # Multistore multistore = { version = "0.8.0", features = ["azure", "gcp"] } diff --git a/adrs/008-analytics.md b/adrs/008-analytics.md index db755bab..b0f3dc6a 100644 --- a/adrs/008-analytics.md +++ b/adrs/008-analytics.md @@ -88,8 +88,9 @@ A separate Worker (`workers/public-log-stream`) holds a Durable Object that fans - Only **GETs of public products returning a status below 400** are broadcast. Non-product paths, errors, and writes are excluded; note that a 3xx (for example a 304) counts as success, and HEAD reads are never broadcast. - The broadcast is fire-and-forget inside `wait_until`, so it never blocks the response. -- The proxy posts Cloudflare-derived geolocation (latitude, longitude, city, colo) from the request's `cf` object, the country from `cf-ipcountry`, plus account, product, and key. **The Durable Object reads only `colo`, `account_id`, and `product_id`** — latitude, longitude, city, country, and key are discarded on arrival and never reach a subscriber. Requester geolocation finer than the datacenter is therefore never published, by the receiver's contract rather than by the sender's restraint. (The proxy also drops the event entirely when latitude/longitude fail to parse, even though the receiver would not have used them.) -- Activity is **aggregated by datacenter** rather than emitted per request, which bounds fan-out cost and coarsens location before it is ever made public. +- The proxy posts only the datacenter (`colo`, from the request's `cf` object) and a count per `account/product`. No coordinates, city, country, or key leave the proxy, so requester geolocation finer than the datacenter is never published. The Durable Object also ignores any other field it receives. (Proxies that predate batching posted one event per request with latitude, longitude, city, country, and key; the Durable Object discarded those on arrival and still accepts the bare `account_id`/`product_id` form.) +- Activity is **batched by datacenter** rather than emitted per request. An isolate runs in one datacenter, so each isolate gathers its public reads for three seconds and posts one batch of exact counts. A busy datacenter collapses into few posts, a quiet one still reports its first request, and nothing is sampled away. Each post is a billed Durable Object request plus the CPU of both Workers (a service-binding call is not billed as a separate Worker request). Posting per request cost about $145 a month (Oct 16–Nov 15: $132 of Durable Object requests, about $14 of CPU) and overloaded the single global Durable Object at peak. +- Counts held by an isolate that is evicted before its window ends are lost, which is acceptable for a decorative display. Broadcasting a coarse datacenter location for a public-product read is a deliberately narrower disclosure than the request event stored in Analytics Engine: nothing user-identifying crosses into the public stream. diff --git a/src/lib.rs b/src/lib.rs index 933180a6..bc7c6523 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,6 +16,7 @@ mod config; mod handlers; mod keys; mod location; +mod location_batch; mod object_path; mod pagination; mod platform; @@ -534,10 +535,8 @@ async fn handle( &env, location::LocationEvent { cf: location::CfProperties::from_request(&req), - country: header_str(&parts.headers, "cf-ipcountry").to_string(), account: acct.to_string(), product: prod.to_string(), - key: key.unwrap_or("").to_string(), api_base_url: config.api_base_url.clone(), api_auth: api_auth.clone(), }, diff --git a/src/location.rs b/src/location.rs index 628d6a31..75c0a03b 100644 --- a/src/location.rs +++ b/src/location.rs @@ -1,17 +1,25 @@ -//! Live location broadcasting: push each public product request's geolocation -//! to the public-log-stream WebSocket service. Fire-and-forget inside -//! `wait_until`, so it never blocks the response. +//! Live location broadcasting for the public activity globe. +//! +//! Public product reads are batched per isolate and posted to the +//! public-log-stream service at most once per [`WINDOW_MS`]. An isolate runs in +//! a single datacenter, so batching in the isolate is batching by datacenter: +//! a busy colo collapses into one message carrying exact counts, while a quiet +//! colo still reports its first request. Nothing is sampled away; only the +//! number of posts shrinks (each post is a billed Durable Object request plus +//! the CPU of both Workers). Runs inside `wait_until`, so it never blocks the +//! response. -use worker::{Context, Env}; +use std::cell::RefCell; +use std::time::Duration; +use worker::{Context, Delay, Env}; + +use crate::location_batch::{record, Pending, WINDOW_MS}; use crate::source_api::{self, ApiAuth}; /// Properties extracted from the Cloudflare `request.cf` object. #[derive(Default)] pub(crate) struct CfProperties { - latitude: String, - longitude: String, - city: String, colo: String, } @@ -22,43 +30,32 @@ impl CfProperties { if cf.is_undefined() || cf.is_null() { return Self::default(); } - let get = |key: &str| -> String { - js_sys::Reflect::get(&cf, &wasm_bindgen::JsValue::from_str(key)) - .ok() - .map(|v| { - v.as_string() - .unwrap_or_else(|| v.as_f64().map(|n| n.to_string()).unwrap_or_default()) - }) - .unwrap_or_default() - }; - Self { - latitude: get("latitude"), - longitude: get("longitude"), - city: get("city"), - colo: get("colo"), - } + let colo = js_sys::Reflect::get(&cf, &wasm_bindgen::JsValue::from_str("colo")) + .ok() + .and_then(|v| v.as_string()) + .unwrap_or_default(); + Self { colo } } } pub(crate) struct LocationEvent { pub cf: CfProperties, - pub country: String, pub account: String, pub product: String, - pub key: String, pub api_base_url: String, pub api_auth: ApiAuth, } -/// Broadcast the request's geolocation to WebSocket viewers via the public-log-stream service. -/// Runs entirely inside `wait_until` so it never blocks the response. +thread_local! { + // Workers are single-threaded; this is the isolate's current batch. + static PENDING: RefCell> = const { RefCell::new(None) }; +} + +/// Count this request toward the live globe. Only public products are counted. pub(crate) fn maybe_broadcast_location(ctx: &Context, env: &Env, event: LocationEvent) { - let (Ok(lat), Ok(lon)) = ( - event.cf.latitude.parse::(), - event.cf.longitude.parse::(), - ) else { + if event.cf.colo.is_empty() { return; - }; + } let Ok(location_ws) = env.service("PUBLIC_LOG_STREAM") else { return; @@ -80,16 +77,25 @@ pub(crate) fn maybe_broadcast_location(ctx: &Context, env: &Env, event: Location return; } - let body = serde_json::json!({ - "lat": lat, - "lon": lon, - "city": event.cf.city, - "country": event.country, - "colo": event.cf.colo, - "account_id": event.account, - "product_id": event.product, - "path": event.key, + let product = format!("{}/{}", event.account, event.product); + let leader = PENDING.with(|s| { + record( + &mut s.borrow_mut(), + &event.cf.colo, + product, + js_sys::Date::now(), + ) }); + if !leader { + return; + } + + Delay::from(Duration::from_millis(WINDOW_MS as u64)).await; + let Some(batch) = PENDING.with(|s| s.borrow_mut().take()) else { + return; + }; + + let body = serde_json::json!({ "colo": batch.colo, "products": batch.products }); let mut init = worker::RequestInit::new(); init.with_method(worker::Method::Post); init.with_body(Some(wasm_bindgen::JsValue::from_str(&body.to_string()))); diff --git a/src/location_batch.rs b/src/location_batch.rs new file mode 100644 index 00000000..77fedd94 --- /dev/null +++ b/src/location_batch.rs @@ -0,0 +1,38 @@ +//! The wasm-free half of live location broadcasting: how an isolate gathers +//! public reads into one batch and decides who flushes it. Kept apart from +//! `location.rs` so it is covered by native tests (the lib itself is `cdylib` +//! with `test = false`). + +use std::collections::HashMap; + +/// How long an isolate gathers requests before posting them as one batch. The +/// globe ticks every 500 ms, so this only bounds how stale a datacenter's +/// activity can be when it appears. +pub const WINDOW_MS: f64 = 3000.0; + +/// Requests gathered since the batch opened. +pub struct Pending { + pub colo: String, + pub opened_at: f64, + pub products: HashMap, +} + +/// Add one request to the batch. Returns true when the caller must flush it +/// after the window: it opened the batch, or the leader that did is long gone +/// (an evicted `wait_until` would otherwise strand the batch forever). +pub fn record(slot: &mut Option, colo: &str, product: String, now: f64) -> bool { + let stale = slot + .as_ref() + .is_some_and(|p| now - p.opened_at > 2.0 * WINDOW_MS); + let leader = slot.is_none() || stale; + let p = slot.get_or_insert_with(|| Pending { + colo: colo.to_string(), + opened_at: now, + products: HashMap::new(), + }); + if stale { + p.opened_at = now; + } + *p.products.entry(product).or_default() += 1; + leader +} diff --git a/tests/location_batch.rs b/tests/location_batch.rs new file mode 100644 index 00000000..53006742 --- /dev/null +++ b/tests/location_batch.rs @@ -0,0 +1,42 @@ +//! Native unit tests for the wasm-free `location_batch` module, included via +//! `#[path]` (the lib itself is `cdylib` with `test = false`). + +#[path = "../src/location_batch.rs"] +mod location_batch; + +use location_batch::{record, WINDOW_MS}; + +#[test] +fn first_request_leads_and_the_rest_join_its_batch() { + let mut slot = None; + assert!(record(&mut slot, "EWR", "a/x".into(), 0.0)); + assert!(!record(&mut slot, "EWR", "a/x".into(), 100.0)); + assert!(!record(&mut slot, "EWR", "a/y".into(), 200.0)); + let p = slot.unwrap(); + assert_eq!(p.colo, "EWR"); + assert_eq!(p.products["a/x"], 2); + assert_eq!(p.products["a/y"], 1); +} + +#[test] +fn a_stranded_batch_gets_a_new_leader_and_keeps_its_counts() { + let mut slot = None; + record(&mut slot, "EWR", "a/x".into(), 0.0); + // The leader's wait_until never ran; a later request takes over. + assert!(record( + &mut slot, + "EWR", + "a/x".into(), + 2.0 * WINDOW_MS + 1.0 + )); + let p = slot.unwrap(); + assert_eq!(p.products["a/x"], 2); + assert_eq!(p.opened_at, 2.0 * WINDOW_MS + 1.0); +} + +#[test] +fn a_batch_inside_twice_the_window_is_not_stale() { + let mut slot = None; + record(&mut slot, "EWR", "a/x".into(), 0.0); + assert!(!record(&mut slot, "EWR", "a/x".into(), 2.0 * WINDOW_MS)); +} diff --git a/workers/public-log-stream/src/aggregate.mjs b/workers/public-log-stream/src/aggregate.mjs index fec0712a..5d1fd78b 100644 --- a/workers/public-log-stream/src/aggregate.mjs +++ b/workers/public-log-stream/src/aggregate.mjs @@ -11,6 +11,31 @@ export function topProducts(products, k) { return [...products.entries()].sort((a, b) => b[1] - a[1]).slice(0, k); } +/** + * Fold one posted event into the per-colo accumulator and return how many + * requests it carried. The proxy posts a batch, `{colo, products: {key: n}}`; + * a bare `{colo, account_id, product_id}` (older proxy) counts as one request. + * @param {Map}>} colos + * @param {{colo?: string, products?: Record, account_id?: string, product_id?: string}} event + * @returns {number} + */ +export function addEvent(colos, event) { + if (!event.colo) return 0; + const entries = event.products + ? Object.entries(event.products) + : [[`${event.account_id ?? ""}/${event.product_id ?? ""}`, 1]]; + const colo = colos.get(event.colo) ?? { n: 0, products: new Map() }; + let total = 0; + for (const [product, count] of entries) { + if (!Number.isInteger(count) || count <= 0) continue; + colo.n += count; + colo.products.set(product, (colo.products.get(product) ?? 0) + count); + total += count; + } + if (total > 0) colos.set(event.colo, colo); + return total; +} + /** * Shape the per-colo accumulator into the wire payload: one entry per * datacenter with its request count and top products this window. diff --git a/workers/public-log-stream/src/aggregate.test.mjs b/workers/public-log-stream/src/aggregate.test.mjs index 31027a5d..281127cf 100644 --- a/workers/public-log-stream/src/aggregate.test.mjs +++ b/workers/public-log-stream/src/aggregate.test.mjs @@ -1,6 +1,28 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { topProducts, buildLocs } from "./aggregate.mjs"; +import { topProducts, buildLocs, addEvent } from "./aggregate.mjs"; + +test("addEvent: a batch adds its exact counts to the colo", () => { + const colos = new Map(); + assert.equal(addEvent(colos, { colo: "EWR", products: { "a/x": 3, "a/y": 1 } }), 4); + assert.equal(addEvent(colos, { colo: "EWR", products: { "a/x": 2 } }), 2); + const e = colos.get("EWR"); + assert.equal(e.n, 6); + assert.deepEqual([...e.products], [["a/x", 5], ["a/y", 1]]); +}); + +test("addEvent: a bare event from an older proxy counts as one request", () => { + const colos = new Map(); + assert.equal(addEvent(colos, { colo: "SJC", account_id: "nasa", product_id: "l8" }), 1); + assert.deepEqual([...colos.get("SJC").products], [["nasa/l8", 1]]); +}); + +test("addEvent: no colo or no valid counts leaves the accumulator untouched", () => { + const colos = new Map(); + assert.equal(addEvent(colos, { products: { "a/x": 1 } }), 0); + assert.equal(addEvent(colos, { colo: "EWR", products: { "a/x": -1, "a/y": 1.5, "a/z": "3" } }), 0); + assert.equal(colos.size, 0); +}); test("topProducts: highest counts first, capped at k", () => { const m = new Map([ diff --git a/workers/public-log-stream/src/location-hub.ts b/workers/public-log-stream/src/location-hub.ts index 2e5c4432..45368048 100644 --- a/workers/public-log-stream/src/location-hub.ts +++ b/workers/public-log-stream/src/location-hub.ts @@ -1,5 +1,5 @@ import { DurableObject } from "cloudflare:workers"; -import { buildLocs } from "./aggregate.mjs"; +import { addEvent, buildLocs } from "./aggregate.mjs"; export interface Env { LOCATION_HUB: DurableObjectNamespace; @@ -8,11 +8,14 @@ export interface Env { CORS_ORIGIN: string; } -// Posted by the proxy per successful public-product GET. Only the datacenter -// (colo) and the product are used; requester geolocation is intentionally -// never forwarded to viewers. +// Posted by the proxy: one batch of public-product GETs seen by one isolate, +// i.e. one datacenter. `products` maps "account/product" to its request count. +// The bare `account_id`/`product_id` form is one request from an older proxy. +// Only the datacenter and the products are used; requester geolocation is +// intentionally never forwarded to viewers. export interface LocationEvent { colo?: string; + products?: Record; account_id?: string; product_id?: string; } @@ -73,13 +76,10 @@ export class LocationHub extends DurableObject { return new Response("ok"); } - const colo = this.colos.get(event.colo) ?? { n: 0, products: new Map() }; - colo.n++; - const product = `${event.account_id ?? ""}/${event.product_id ?? ""}`; - colo.products.set(product, (colo.products.get(product) ?? 0) + 1); - this.colos.set(event.colo, colo); + const added = addEvent(this.colos, event); + if (added === 0) return new Response("ok"); - this.requestCount++; + this.requestCount += added; this.sentIdle = false; await this.ensureAlarm(); return new Response("ok"); From 7d0e5f8cf7be7e92b0299f25eff8af398b33cdc5 Mon Sep 17 00:00:00 2001 From: Anthony Lukach Date: Thu, 19 Nov 2026 22:48:07 -0700 Subject: [PATCH 2/3] fix(log-stream): log a live-globe batch the hub did not accept A failed or rejected post dropped its whole batch without a trace. Say so at info level (not WARN, so a failing globe never counts toward the WARN alerts); a Durable Object past its request limit now shows up in the logs. Also list location_batch.rs in ADR-008 and note the up-to-3-second delay. Co-Authored-By: Claude Sonnet 5.5 --- adrs/008-analytics.md | 4 ++-- src/location.rs | 21 +++++++++++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/adrs/008-analytics.md b/adrs/008-analytics.md index b0f3dc6a..e84e4ccf 100644 --- a/adrs/008-analytics.md +++ b/adrs/008-analytics.md @@ -4,7 +4,7 @@ **Date:** 2026-08-09 **RFC:** RFC-001 §10, §12 **Depends on:** ADR-002 -**Implementation:** `src/analytics.rs`, `src/location.rs`, `workers/public-log-stream/` +**Implementation:** `src/analytics.rs`, `src/location.rs`, `src/location_batch.rs`, `workers/public-log-stream/` **Implemented by:** #119 (Analytics Engine request logging), #120 (account/product sampling index), #153 (request duration and hashed client IP), #122 (real-time public log stream via Durable Objects), #171 (aggregate live-globe activity by datacenter) --- @@ -89,7 +89,7 @@ A separate Worker (`workers/public-log-stream`) holds a Durable Object that fans - Only **GETs of public products returning a status below 400** are broadcast. Non-product paths, errors, and writes are excluded; note that a 3xx (for example a 304) counts as success, and HEAD reads are never broadcast. - The broadcast is fire-and-forget inside `wait_until`, so it never blocks the response. - The proxy posts only the datacenter (`colo`, from the request's `cf` object) and a count per `account/product`. No coordinates, city, country, or key leave the proxy, so requester geolocation finer than the datacenter is never published. The Durable Object also ignores any other field it receives. (Proxies that predate batching posted one event per request with latitude, longitude, city, country, and key; the Durable Object discarded those on arrival and still accepts the bare `account_id`/`product_id` form.) -- Activity is **batched by datacenter** rather than emitted per request. An isolate runs in one datacenter, so each isolate gathers its public reads for three seconds and posts one batch of exact counts. A busy datacenter collapses into few posts, a quiet one still reports its first request, and nothing is sampled away. Each post is a billed Durable Object request plus the CPU of both Workers (a service-binding call is not billed as a separate Worker request). Posting per request cost about $145 a month (Oct 16–Nov 15: $132 of Durable Object requests, about $14 of CPU) and overloaded the single global Durable Object at peak. +- Activity is **batched by datacenter** rather than emitted per request. An isolate runs in one datacenter, so each isolate gathers its public reads for three seconds and posts one batch of exact counts. A busy datacenter collapses into few posts, a quiet one still reports its first request, and nothing is sampled away. A datacenter's activity can therefore reach viewers up to three seconds after the requests. Each post is a billed Durable Object request plus the CPU of both Workers (a service-binding call is not billed as a separate Worker request). Posting per request cost about $145 a month (Oct 16–Nov 15: $132 of Durable Object requests, about $14 of CPU) and overloaded the single global Durable Object at peak. - Counts held by an isolate that is evicted before its window ends are lost, which is acceptable for a decorative display. Broadcasting a coarse datacenter location for a public-product read is a deliberately narrower disclosure than the request event stored in Analytics Engine: nothing user-identifying crosses into the public stream. diff --git a/src/location.rs b/src/location.rs index 75c0a03b..1a16fff5 100644 --- a/src/location.rs +++ b/src/location.rs @@ -99,8 +99,25 @@ pub(crate) fn maybe_broadcast_location(ctx: &Context, env: &Env, event: Location let mut init = worker::RequestInit::new(); init.with_method(worker::Method::Post); init.with_body(Some(wasm_bindgen::JsValue::from_str(&body.to_string()))); - let _ = location_ws + // The batch is dropped on failure (it is a decorative display), but say + // so: a Durable Object past its request limit shows up here. Console + // rather than `tracing::warn!`, so a failing globe never counts toward + // the WARN alerts. + let failure = match location_ws .fetch("https://public-log-stream/location", Some(init)) - .await; + .await + { + Ok(resp) if resp.status().as_u16() < 400 => return, + Ok(resp) => format!("status {}", resp.status().as_u16()), + Err(e) => e.to_string(), + }; + worker::console_log!( + "{}", + serde_json::json!({ + "message": "live-globe batch not delivered", + "colo": batch.colo, + "error": failure, + }) + ); }); } From 0b76c5d85d8e5237d7be0bdbe56bd68253284df7 Mon Sep 17 00:00:00 2001 From: Anthony Lukach Date: Thu, 19 Nov 2026 22:53:45 -0700 Subject: [PATCH 3/3] feat(log-stream): spread batches over ticks and replay recent activity The hub emitted each proxy batch in a single tick, so a datacenter's dots arrived as a burst every few seconds, and a new viewer saw nothing until the next live tick. Batches are now spread over the next six 500 ms ticks (conserving counts, with a rotating cursor for the remainders), keyed by absolute tick so a late alarm catches up. The idle tick is sent only once nothing is queued. A viewer who connects gets one replay message (type "tick" with replay: true) of the last three seconds already emitted, so it never overlaps the live ticks. The alarm runs only while someone watches or activity is queued, so an idle hub still stops. Batches are capped at 100 product keys without losing the datacenter's count. Co-Authored-By: Claude Sonnet 5.5 --- adrs/008-analytics.md | 6 +- workers/public-log-stream/src/aggregate.mjs | 164 +++++++++++++--- .../public-log-stream/src/aggregate.test.mjs | 179 ++++++++++++++++-- workers/public-log-stream/src/location-hub.ts | 147 +++++++++----- 4 files changed, 408 insertions(+), 88 deletions(-) diff --git a/adrs/008-analytics.md b/adrs/008-analytics.md index e84e4ccf..233d159a 100644 --- a/adrs/008-analytics.md +++ b/adrs/008-analytics.md @@ -89,8 +89,10 @@ A separate Worker (`workers/public-log-stream`) holds a Durable Object that fans - Only **GETs of public products returning a status below 400** are broadcast. Non-product paths, errors, and writes are excluded; note that a 3xx (for example a 304) counts as success, and HEAD reads are never broadcast. - The broadcast is fire-and-forget inside `wait_until`, so it never blocks the response. - The proxy posts only the datacenter (`colo`, from the request's `cf` object) and a count per `account/product`. No coordinates, city, country, or key leave the proxy, so requester geolocation finer than the datacenter is never published. The Durable Object also ignores any other field it receives. (Proxies that predate batching posted one event per request with latitude, longitude, city, country, and key; the Durable Object discarded those on arrival and still accepts the bare `account_id`/`product_id` form.) -- Activity is **batched by datacenter** rather than emitted per request. An isolate runs in one datacenter, so each isolate gathers its public reads for three seconds and posts one batch of exact counts. A busy datacenter collapses into few posts, a quiet one still reports its first request, and nothing is sampled away. A datacenter's activity can therefore reach viewers up to three seconds after the requests. Each post is a billed Durable Object request plus the CPU of both Workers (a service-binding call is not billed as a separate Worker request). Posting per request cost about $145 a month (Oct 16–Nov 15: $132 of Durable Object requests, about $14 of CPU) and overloaded the single global Durable Object at peak. -- Counts held by an isolate that is evicted before its window ends are lost, which is acceptable for a decorative display. +- Activity is **batched by datacenter** rather than emitted per request. An isolate runs in one datacenter, so each isolate gathers its public reads for three seconds and posts one batch of exact counts. A busy datacenter collapses into few posts, a quiet one still reports its first request, and nothing is sampled away. Each post is a billed Durable Object request plus the CPU of both Workers (a service-binding call is not billed as a separate Worker request). Posting per request cost about $145 a month (Oct 16–Nov 15: $132 of Durable Object requests, about $14 of CPU) and overloaded the single global Durable Object at peak. +- The Durable Object **spreads each batch over the next six 500 ms ticks** (three seconds) rather than emitting it in one tick, so viewers see a steady trickle instead of a burst each time a proxy isolate flushes. Counts are conserved, and every emitted datacenter entry has a count of at least one. Together with the proxy's three-second window, activity can reach viewers up to about six seconds after the requests. Ticks are numbered by absolute time, so an alarm that fires late catches up on the ticks it missed. The one empty "idle" tick that lets the globe fade out is sent only once nothing is queued. +- A viewer who connects receives **one replay message** straight away: the last three seconds of already-emitted activity, merged, in the shape of a tick with `replay: true` and `windowMs`. It re-sends data already public and never overlaps what the viewer then receives live. The alarm runs only while someone is watching or activity is queued, so an idle hub still stops and hibernates. +- Counts held by an isolate that is evicted before its window ends, and activity queued in a Durable Object that is evicted, are lost, which is acceptable for a decorative display. Broadcasting a coarse datacenter location for a public-product read is a deliberately narrower disclosure than the request event stored in Analytics Engine: nothing user-identifying crosses into the public stream. diff --git a/workers/public-log-stream/src/aggregate.mjs b/workers/public-log-stream/src/aggregate.mjs index 5d1fd78b..af032637 100644 --- a/workers/public-log-stream/src/aggregate.mjs +++ b/workers/public-log-stream/src/aggregate.mjs @@ -1,5 +1,17 @@ // Pure, runtime-free shaping helpers — kept as plain JS so `node --test` can // exercise them without a TS build step or extra deps. Imported by the DO. +// +// Activity arrives as batches (one per proxy isolate, i.e. one datacenter) and +// is spread over the next few ticks so viewers get a steady trickle rather than +// a burst. Ticks are numbered by absolute index, floor(ms / interval), and each +// tick's activity lives in a "slot": Map. + +/** Ticks a batch is spread over: 6 x 500 ms = 3 s, the proxy's batching window. */ +export const SPREAD_SLOTS = 6; + +// A batch names a few products per datacenter; these only bound a bad sender. +const MAX_PRODUCT_KEYS = 100; +const MAX_KEY_LENGTH = 128; /** * Top-k products by request count, count descending. @@ -12,41 +24,143 @@ export function topProducts(products, k) { } /** - * Fold one posted event into the per-colo accumulator and return how many - * requests it carried. The proxy posts a batch, `{colo, products: {key: n}}`; - * a bare `{colo, account_id, product_id}` (older proxy) counts as one request. + * Shape a colo accumulator into the wire payload: one entry per datacenter + * with its request count and top products. * @param {Map}>} colos + * @param {number} maxProducts + * @returns {{colo: string, n: number, p: [string, number][]}[]} + */ +export function buildLocs(colos, maxProducts) { + return [...colos.entries()].map(([colo, e]) => ({ + colo, + n: e.n, + p: topProducts(e.products, maxProducts), + })); +} + +/** + * Total requests across a colo accumulator. + * @param {Map} colos + */ +export function totalRequests(colos) { + let total = 0; + for (const e of colos.values()) total += e.n; + return total; +} + +/** + * Split `count` into `k` near-equal parts (they differ by at most 1). The extra + * units go to consecutive slots starting at `cursor`, and the cursor moves on, + * so a run of count-1 batches fills the slots round-robin. + * @param {number} count + * @param {number} k + * @param {number} cursor + * @returns {{parts: number[], cursor: number}} + */ +export function spreadCount(count, k, cursor) { + const parts = new Array(k).fill(Math.floor(count / k)); + const rem = count % k; + for (let i = 0; i < rem; i++) parts[(cursor + i) % k]++; + return { parts, cursor: (cursor + rem) % k }; +} + +function addTo(slots, idx, colo, n, product) { + const slot = slots.get(idx) ?? new Map(); + const e = slot.get(colo) ?? { n: 0, products: new Map() }; + e.n += n; + if (product !== null) { + e.products.set(product, (e.products.get(product) ?? 0) + n); + } + slot.set(colo, e); + slots.set(idx, slot); +} + +/** + * Spread one posted event over the ticks after `nowTick`. The proxy posts a + * batch, `{colo, products: {key: n}}`; a bare `{colo, account_id, product_id}` + * (older proxy) counts as one request. Counts are conserved: a colo's `n` + * always includes products dropped by the key cap. + * @param {Map}>>} slots * @param {{colo?: string, products?: Record, account_id?: string, product_id?: string}} event - * @returns {number} + * @param {number} nowTick + * @param {number} k + * @param {number} cursor + * @returns {{total: number, cursor: number}} */ -export function addEvent(colos, event) { - if (!event.colo) return 0; - const entries = event.products +export function addBatchSpread(slots, event, nowTick, k, cursor) { + if (!event.colo || typeof event.colo !== "string") return { total: 0, cursor }; + const raw = event.products ? Object.entries(event.products) : [[`${event.account_id ?? ""}/${event.product_id ?? ""}`, 1]]; - const colo = colos.get(event.colo) ?? { n: 0, products: new Map() }; + const valid = raw + .filter(([, count]) => Number.isSafeInteger(count) && count > 0) + .map(([key, count]) => [key.slice(0, MAX_KEY_LENGTH), count]) + .sort((a, b) => b[1] - a[1]); + + const place = (count, product) => { + const spread = spreadCount(count, k, cursor); + cursor = spread.cursor; + spread.parts.forEach((n, j) => { + if (n > 0) addTo(slots, nowTick + 1 + j, event.colo, n, product); + }); + }; + let total = 0; - for (const [product, count] of entries) { - if (!Number.isInteger(count) || count <= 0) continue; - colo.n += count; - colo.products.set(product, (colo.products.get(product) ?? 0) + count); + let other = 0; + valid.forEach(([key, count], i) => { total += count; + if (i < MAX_PRODUCT_KEYS) place(count, key); + else other += count; + }); + if (other > 0) place(other, null); + return { total, cursor }; +} + +/** + * Merge several slots into one colo accumulator. + * @param {Iterable}>>} slotMaps + */ +export function mergeSlots(slotMaps) { + const out = new Map(); + for (const slot of slotMaps) { + for (const [colo, e] of slot) { + const t = out.get(colo) ?? { n: 0, products: new Map() }; + t.n += e.n; + for (const [p, c] of e.products) { + t.products.set(p, (t.products.get(p) ?? 0) + c); + } + out.set(colo, t); + } } - if (total > 0) colos.set(event.colo, colo); - return total; + return out; } /** - * Shape the per-colo accumulator into the wire payload: one entry per - * datacenter with its request count and top products this window. - * @param {Map}>} colos - * @param {number} maxProducts - * @returns {{colo: string, n: number, p: [string, number][]}[]} + * Activity of ticks in (afterIdx, uptoIdx], merged. A late alarm passes the + * gap it missed and catches up in one tick. */ -export function buildLocs(colos, maxProducts) { - return [...colos.entries()].map(([colo, e]) => ({ - colo, - n: e.n, - p: topProducts(e.products, maxProducts), - })); +export function dueSlots(slots, afterIdx, uptoIdx) { + return mergeSlots( + [...slots].filter(([i]) => i > afterIdx && i <= uptoIdx).map(([, m]) => m), + ); +} + +/** + * The last `k` emitted ticks, merged, for a viewer who has just connected. + * Never includes a tick after `lastEmitted`, so it cannot overlap what the + * viewer receives live. + */ +export function replayWindow(slots, lastEmitted, k) { + return dueSlots(slots, lastEmitted - k, lastEmitted); +} + +/** Drop ticks at or before `uptoIdx`. */ +export function pruneSlots(slots, uptoIdx) { + for (const i of [...slots.keys()]) if (i <= uptoIdx) slots.delete(i); +} + +/** True while activity is queued for a tick after `nowTick`. */ +export function hasPending(slots, nowTick) { + for (const i of slots.keys()) if (i > nowTick) return true; + return false; } diff --git a/workers/public-log-stream/src/aggregate.test.mjs b/workers/public-log-stream/src/aggregate.test.mjs index 281127cf..56bb7572 100644 --- a/workers/public-log-stream/src/aggregate.test.mjs +++ b/workers/public-log-stream/src/aggregate.test.mjs @@ -1,27 +1,172 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { topProducts, buildLocs, addEvent } from "./aggregate.mjs"; +import { + SPREAD_SLOTS as K, + topProducts, + buildLocs, + totalRequests, + spreadCount, + addBatchSpread, + mergeSlots, + dueSlots, + replayWindow, + pruneSlots, + hasPending, +} from "./aggregate.mjs"; -test("addEvent: a batch adds its exact counts to the colo", () => { - const colos = new Map(); - assert.equal(addEvent(colos, { colo: "EWR", products: { "a/x": 3, "a/y": 1 } }), 4); - assert.equal(addEvent(colos, { colo: "EWR", products: { "a/x": 2 } }), 2); - const e = colos.get("EWR"); - assert.equal(e.n, 6); - assert.deepEqual([...e.products], [["a/x", 5], ["a/y", 1]]); +const sum = (xs) => xs.reduce((a, b) => a + b, 0); +// Total n and per-product counts for a colo across every slot. +const across = (slots, colo) => { + const m = mergeSlots(slots.values()); + return m.get(colo); +}; + +test("spreadCount: parts sum to the count and differ by at most 1", () => { + for (let count = 0; count <= 50; count++) { + for (let cursor = 0; cursor < K; cursor++) { + const { parts } = spreadCount(count, K, cursor); + assert.equal(parts.length, K); + assert.equal(sum(parts), count); + assert.ok(Math.max(...parts) - Math.min(...parts) <= 1); + } + } +}); + +test("spreadCount: a count of 1 lands on exactly one slot, at the cursor", () => { + const { parts, cursor } = spreadCount(1, K, 4); + assert.deepEqual(parts, [0, 0, 0, 0, 1, 0]); + assert.equal(cursor, 5); +}); + +test("spreadCount: the cursor wraps and count-1 calls fill slots round-robin", () => { + let cursor = 4; + const hits = []; + for (let i = 0; i < K; i++) { + const r = spreadCount(1, K, cursor); + hits.push(r.parts.indexOf(1)); + cursor = r.cursor; + } + assert.deepEqual(hits.sort(), [0, 1, 2, 3, 4, 5]); + assert.equal(cursor, 4); +}); + +test("addBatchSpread: counts are conserved across slots and start next tick", () => { + const slots = new Map(); + const { total } = addBatchSpread( + slots, + { colo: "EWR", products: { "a/x": 40, "a/y": 3 } }, + 10, + K, + 0, + ); + assert.equal(total, 43); + assert.deepEqual([...slots.keys()].sort((a, b) => a - b), [11, 12, 13, 14, 15, 16]); + const e = across(slots, "EWR"); + assert.equal(e.n, 43); + assert.deepEqual([...e.products].sort(), [["a/x", 40], ["a/y", 3]]); +}); + +test("addBatchSpread: a bare event from an older proxy counts as one request", () => { + const slots = new Map(); + const { total } = addBatchSpread( + slots, + { colo: "SJC", account_id: "nasa", product_id: "l8" }, + 0, + K, + 0, + ); + assert.equal(total, 1); + assert.equal(slots.size, 1); + assert.deepEqual([...across(slots, "SJC").products], [["nasa/l8", 1]]); +}); + +test("addBatchSpread: rejects a missing colo and bad counts", () => { + const slots = new Map(); + assert.equal(addBatchSpread(slots, { products: { "a/x": 1 } }, 0, K, 0).total, 0); + const bad = { "a/x": 0, "a/y": -1, "a/z": 1.5, "a/w": "3", "a/v": Number.MAX_SAFE_INTEGER + 2 }; + assert.equal(addBatchSpread(slots, { colo: "EWR", products: bad }, 0, K, 0).total, 0); + assert.equal(slots.size, 0); +}); + +test("addBatchSpread: the key cap drops products but keeps n whole", () => { + const slots = new Map(); + const products = {}; + for (let i = 0; i < 150; i++) products[`a/p${i}`] = 6; + const { total } = addBatchSpread(slots, { colo: "EWR", products }, 0, K, 0); + assert.equal(total, 900); + const e = across(slots, "EWR"); + assert.equal(e.n, 900); + assert.equal(e.products.size, 100); +}); + +test("addBatchSpread: no slot ever carries a zero count", () => { + const slots = new Map(); + addBatchSpread(slots, { colo: "EWR", products: { "a/x": 2 } }, 0, K, 0); + for (const slot of slots.values()) { + for (const e of slot.values()) assert.ok(e.n >= 1); + } }); -test("addEvent: a bare event from an older proxy counts as one request", () => { - const colos = new Map(); - assert.equal(addEvent(colos, { colo: "SJC", account_id: "nasa", product_id: "l8" }), 1); - assert.deepEqual([...colos.get("SJC").products], [["nasa/l8", 1]]); +test("mergeSlots then top-k differs from truncating each slot", () => { + const slots = new Map([ + [1, new Map([["EWR", { n: 3, products: new Map([["a/x", 2], ["a/y", 1]]) }]])], + [2, new Map([["EWR", { n: 3, products: new Map([["a/z", 2], ["a/y", 1]]) }]])], + [3, new Map([["EWR", { n: 3, products: new Map([["a/w", 2], ["a/y", 1]]) }]])], + ]); + const merged = mergeSlots(slots.values()); + assert.deepEqual(topProducts(merged.get("EWR").products, 1), [["a/y", 3]]); +}); + +test("dueSlots: a late alarm catches up on every missed tick, once", () => { + const slots = new Map([ + [11, new Map([["EWR", { n: 1, products: new Map([["a/x", 1]]) }]])], + [12, new Map([["EWR", { n: 2, products: new Map([["a/x", 2]]) }]])], + [14, new Map([["EWR", { n: 4, products: new Map([["a/x", 4]]) }]])], + ]); + assert.equal(dueSlots(slots, 10, 13).get("EWR").n, 3); + assert.equal(dueSlots(slots, 13, 14).get("EWR").n, 4); + assert.equal(dueSlots(slots, 14, 14).size, 0); }); -test("addEvent: no colo or no valid counts leaves the accumulator untouched", () => { - const colos = new Map(); - assert.equal(addEvent(colos, { products: { "a/x": 1 } }), 0); - assert.equal(addEvent(colos, { colo: "EWR", products: { "a/x": -1, "a/y": 1.5, "a/z": "3" } }), 0); - assert.equal(colos.size, 0); +test("replayWindow: only ticks already emitted and at most k old", () => { + const slot = (n) => new Map([["EWR", { n, products: new Map([["a/x", n]]) }]]); + const slots = new Map([ + [3, slot(1)], // older than the window + [5, slot(2)], + [10, slot(4)], + [11, slot(8)], // not yet emitted: must not be replayed + ]); + const r = replayWindow(slots, 10, 6); + assert.equal(r.get("EWR").n, 6); +}); + +test("replayWindow: nothing recent gives an empty result", () => { + assert.equal(replayWindow(new Map(), 10, K).size, 0); +}); + +test("pruneSlots bounds the map and hasPending sees only future ticks", () => { + const slots = new Map(); + for (let i = 1; i <= 20; i++) slots.set(i, new Map()); + pruneSlots(slots, 14); + assert.deepEqual([...slots.keys()], [15, 16, 17, 18, 19, 20]); + assert.equal(hasPending(slots, 19), true); + assert.equal(hasPending(slots, 20), false); +}); + +test("a sparse trickle leaves later slots pending until the last is due", () => { + const slots = new Map(); + addBatchSpread(slots, { colo: "EWR", products: { "a/x": 1 } }, 10, K, 0); + // The single request landed on one slot; ticks before it are empty but pending. + for (let tick = 10; tick < 11; tick++) assert.equal(hasPending(slots, tick), true); + assert.equal(hasPending(slots, 11), false); +}); + +test("totalRequests sums n across colos", () => { + const colos = new Map([ + ["EWR", { n: 5, products: new Map() }], + ["SJC", { n: 2, products: new Map() }], + ]); + assert.equal(totalRequests(colos), 7); }); test("topProducts: highest counts first, capped at k", () => { diff --git a/workers/public-log-stream/src/location-hub.ts b/workers/public-log-stream/src/location-hub.ts index 45368048..89a0af7b 100644 --- a/workers/public-log-stream/src/location-hub.ts +++ b/workers/public-log-stream/src/location-hub.ts @@ -1,5 +1,14 @@ import { DurableObject } from "cloudflare:workers"; -import { addEvent, buildLocs } from "./aggregate.mjs"; +import { + SPREAD_SLOTS, + addBatchSpread, + buildLocs, + dueSlots, + hasPending, + pruneSlots, + replayWindow, + totalRequests, +} from "./aggregate.mjs"; export interface Env { LOCATION_HUB: DurableObjectNamespace; @@ -20,15 +29,20 @@ export interface LocationEvent { product_id?: string; } -// One datacenter's activity within the current window. +// One datacenter's activity within one tick. interface ColoStats { n: number; products: Map; } export class LocationHub extends DurableObject { - private colos = new Map(); - private requestCount = 0; + // Activity queued per tick, keyed by absolute tick index (see tickOf). A + // batch is spread over the next SPREAD_SLOTS ticks so viewers get a steady + // trickle instead of one burst per proxy flush. Lost on eviction, which only + // forfeits the last few seconds of a decorative display. + private slots = new Map>(); + private cursor = 0; + private lastEmitted: number; private sentIdle = false; private emitInterval: number; private maxProducts: number; @@ -37,6 +51,15 @@ export class LocationHub extends DurableObject { super(ctx, env); this.emitInterval = parseInt(env.EMIT_INTERVAL_MS) || 500; this.maxProducts = parseInt(env.MAX_PRODUCTS_PER_COLO) || 5; + this.lastEmitted = this.tickOf(Date.now()); + } + + private tickOf(ms: number): number { + return Math.floor(ms / this.emitInterval); + } + + private nextBoundary(ms: number): number { + return (this.tickOf(ms) + 1) * this.emitInterval; } async fetch(request: Request): Promise { @@ -63,23 +86,48 @@ export class LocationHub extends DurableObject { const [client, server] = Object.values(pair); this.ctx.acceptWebSocket(server); + this.replay(server); await this.ensureAlarm(); return new Response(null, { status: 101, webSocket: client }); } + // Show a new viewer the last few seconds at once, so the globe is not empty + // until the next live tick. Only ticks already emitted, so it never overlaps + // what the viewer receives live. Same shape as a tick plus `replay`, so + // clients that read only ticks need no change. Does not touch `sentIdle`. + private replay(server: WebSocket): void { + const recent = replayWindow(this.slots, this.lastEmitted, SPREAD_SLOTS); + if (recent.size === 0) return; + try { + server.send( + JSON.stringify({ + type: "tick", + replay: true, + windowMs: SPREAD_SLOTS * this.emitInterval, + requestsPerWindow: totalRequests(recent), + viewers: this.ctx.getWebSockets().length, + locations: buildLocs(recent, this.maxProducts), + }), + ); + } catch { + // The socket closed already; cleaned up in webSocketClose + } + } + private async handleLocation(request: Request): Promise { const event: LocationEvent = await request.json(); - // No datacenter → can't place it on the globe; drop it. - if (!event.colo) { - return new Response("ok"); - } + const { total, cursor } = addBatchSpread( + this.slots, + event, + this.tickOf(Date.now()), + SPREAD_SLOTS, + this.cursor, + ); + this.cursor = cursor; + if (total === 0) return new Response("ok"); - const added = addEvent(this.colos, event); - if (added === 0) return new Response("ok"); - - this.requestCount += added; this.sentIdle = false; await this.ensureAlarm(); return new Response("ok"); @@ -87,50 +135,61 @@ export class LocationHub extends DurableObject { // Storage is the source of truth for a pending alarm; a cached flag can drift. // An alarm long past due is not going to fire, so it is replaced, not trusted. + // Alarms are aligned to tick boundaries so slots are emitted on their tick. private async ensureAlarm(): Promise { + const now = Date.now(); const at = await this.ctx.storage.getAlarm(); - if (at == null || at < Date.now() - 10 * this.emitInterval) { - await this.ctx.storage.setAlarm(Date.now() + this.emitInterval); + if (at == null || at < now - 10 * this.emitInterval) { + await this.ctx.storage.setAlarm(this.nextBoundary(now)); } } async alarm(): Promise { + const now = Date.now(); + const tick = this.tickOf(now); const clients = this.ctx.getWebSockets(); - // Nobody watching → let the alarm stop (re-armed on next connect/POST). - if (clients.length === 0) { - this.colos.clear(); - this.requestCount = 0; - return; - } - - const hasActivity = this.colos.size > 0; - - // Emit while there's activity, plus one final tick when going idle so the - // globe can fade out, then stay quiet until activity resumes. - if (hasActivity || !this.sentIdle) { - const message = JSON.stringify({ - type: "tick", - requestsPerWindow: this.requestCount, - viewers: clients.length, - locations: buildLocs(this.colos, this.maxProducts), - }); - - for (const ws of clients) { - try { - ws.send(message); - } catch { - // Cleaned up in webSocketClose - } + // Everything now due, merged, so an alarm that fires late catches up on + // the ticks it missed instead of emitting them one by one. + const due = dueSlots(this.slots, this.lastEmitted, tick); + this.lastEmitted = Math.max(this.lastEmitted, tick); + pruneSlots(this.slots, tick - SPREAD_SLOTS); + const pending = hasPending(this.slots, tick); + + if (clients.length > 0) { + if (due.size > 0) { + this.send(clients, due); + this.sentIdle = false; + } else if (!pending && !this.sentIdle) { + // Going idle: one empty tick so the globe can fade out, then quiet + // until activity resumes. Not while later ticks still hold activity. + this.send(clients, due); + this.sentIdle = true; } + } - this.sentIdle = !hasActivity; + // Keep ticking while someone watches or activity is still queued; with + // neither, let the alarm stop (re-armed on the next connect or post). + if (clients.length > 0 || pending) { + await this.ctx.storage.setAlarm(this.nextBoundary(now)); } + } - // Reset for the next window and keep the alarm running while clients remain. - this.colos.clear(); - this.requestCount = 0; - await this.ctx.storage.setAlarm(Date.now() + this.emitInterval); + private send(clients: WebSocket[], colos: Map): void { + const message = JSON.stringify({ + type: "tick", + requestsPerWindow: totalRequests(colos), + viewers: clients.length, + locations: buildLocs(colos, this.maxProducts), + }); + + for (const ws of clients) { + try { + ws.send(message); + } catch { + // Cleaned up in webSocketClose + } + } } async webSocketMessage(