Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
9 changes: 6 additions & 3 deletions adrs/008-analytics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

---
Expand Down Expand Up @@ -88,8 +88,11 @@ 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.
- 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.

Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod config;
mod handlers;
mod keys;
mod location;
mod location_batch;
mod object_path;
mod pagination;
mod platform;
Expand Down Expand Up @@ -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(),
},
Expand Down
107 changes: 65 additions & 42 deletions src/location.rs
Original file line number Diff line number Diff line change
@@ -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,
}

Expand All @@ -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<Option<Pending>> = 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::<f64>(),
event.cf.longitude.parse::<f64>(),
) else {
if event.cf.colo.is_empty() {
return;
};
}

let Ok(location_ws) = env.service("PUBLIC_LOG_STREAM") else {
return;
Expand All @@ -80,21 +77,47 @@ 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())));
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,
})
);
});
}
38 changes: 38 additions & 0 deletions src/location_batch.rs
Original file line number Diff line number Diff line change
@@ -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<String, u32>,
}

/// 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<Pending>, 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
}
42 changes: 42 additions & 0 deletions tests/location_batch.rs
Original file line number Diff line number Diff line change
@@ -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));
}
Loading
Loading