Skip to content

Count embed calls at the edge (phase 2 of #410) - #417

Merged
neuromechanist merged 12 commits into
stagingfrom
feature/issue-412-embed-counts
Oct 5, 2026
Merged

neuromechanist merged 12 commits into
stagingfrom
feature/issue-412-embed-counts

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Based on staging: #415 (phase 1) merged as 298674b, and this branch was rebased onto it, so the diff is phase 2 only.

Summary

Counts each embed call at the edge, so the observability dashboard (phase 4) can report which datasets are embedded, from which sites, and how.

Every GET /dataset/<id>/embed that the middleware answers with a 200 writes one Analytics Engine data point, on every serve path (passthrough, cache HIT, cache MISS, no cache storage), from one helper called once per request.

Nothing runs on a partner's page or on the visitor's device; the only input is the HTTP request the browser already made.

Refs #412, part of #410.

What changed

  • src/lib/embed-analytics.ts and its test: the pure embedDataPoint(request, datasetId) builder and embedCallPoint(request, status), which decides whether a response counts (exactly 200, the embed route's id, percent-decoded, a malformed escape counts nothing) and returns the point; a hostname over 253 characters is recorded as empty; and a test that reads wrangler.toml?raw and wrangler.test.toml?raw to pin which dataset each binds.
  • src/middleware.ts and its test: onRequest now wraps the existing handler (renamed serve, body unchanged) and calls countEmbedCall once on the response it returns, which is only the lookup, the write and the catch; src/env.d.ts types locals.runtime.env.EMBED_ANALYTICS.
  • wrangler.toml: EMBED_ANALYTICS bound to nemar_website_embeds (production) and, under [env.preview], to nemar_website_embeds_dev; wrangler.test.toml binds the staging project to nemar_website_embeds_dev.
  • ADR 0024, its index entry, an AGENTS.md architecture-map line, and a CHANGELOG entry.

What is recorded, and what is not

Recorded, exactly: indexes: [datasetId], blobs: [datasetId, embedderHost, kind], doubles: [1], plus Analytics Engine's own timestamp.

embedderHost is the lowercased hostname from Referer (no scheme, port, userinfo, path or query; empty when absent or unparseable); kind is iframe, document, none (header absent) or other, from Sec-Fetch-Dest.

Not recorded: IP address, user agent, country, cookie, query string (so not ?view= or ?theme=), or anything else about the visitor.

Not counted: any non-GET request (so HEAD), a prefetch (Sec-Purpose containing prefetch, or Purpose: prefetch), and any response that is not a 200 (the ds* to on* 301 is not counted; the 200 it leads to is).

With no binding the hook does nothing, silently on localhost, previews and staging, and with one warning per isolate on a production host (a deploy fault); a write that throws is logged once per isolate with the dataset id and never changes the response.

A 200 also covers the embed's two message pages (no published version yet, a ?view= that matches nothing), which the middleware cannot tell from a loaded viewer without reading the body; and a browser may serve the embed from its HTTP cache for 60 seconds, so rapid repeat views by one browser count once.

Gates (#410, Phase 2)

  • 1. Unit tests pin the exact data point. 45 tests over real Request objects in embed-analytics.test.ts (every branch, toStrictEqual on the whole point, a test that a request carrying a user agent, IP, cookie, query and referrer path leaks none of them, the success path through embedCallPoint, and the wrangler dataset invariants), plus 13 counting tests through the real onRequest in middleware.test.ts.
  • 2. Rows in nemar_website_embeds_dev. Open. Traffic for every required case was sent to this PR's preview and the real-browser framing was checked, but the Analytics Engine SQL query has not been run, because it needs an API token with Account Analytics Read and none is available to the agent (details below). It will be verified through the observability dashboard (phase 4), which holds an Account Analytics token.
  • 3. Latency. Median of 20 loads per deployment, interleaved, edge-cache HIT: this PR 26.6 ms vs phase 1 28.0 ms wait-for-first-byte (64.8 ms vs 69.0 ms total) in the headline round; across 8 rounds the difference in medians of wait-for-first-byte was between -6.2 and +1.4 ms, with this PR no slower than phase 1 by more than 1.4 ms. Re-measured on the post-review build (4fbc6e1a, https://1d14a483.nemar-website.pages.dev): wait-for-first-byte differences of +2.4, -0.9 and +0.2 ms over three rounds (total +2.4, -2.0 and +5.9 ms, the last one network noise on a metric the middleware does not touch).
  • 4. A missing binding makes no error in any serve path. Unit tests cover passthrough (cookie-bearing) and the no-cache-storage fallback with six shapes of absent binding; a real workerd (wrangler pages dev, real Cache API) served a MISS then a HIT with 200s and no log lines, with and without the binding.
  • bun run lint, bun run typecheck (0 errors, 0 warnings), bun run test (2989 passed, 7 skipped, 126 files) and bun run build are green, re-run after the rebase onto staging.

Gate 2 detail

Preview https://81de5f71.nemar-website.pages.dev (commit b5d08ee, before the review changes), production project's preview environment, bound to nemar_website_embeds_dev by [env.preview].

A temporary probe build (a throwaway branch, deleted) put x-debug-embed-binding on embed responses and read runtime=object;env=object;binding=object;write=function on both a MISS and a HIT, so the adapter exposes the binding at locals.runtime.env on a real Pages preview.

Requests sent with curl to /dataset/on007753/embed?view=sub-05 (UTC, 2026-10-05), all answered 200:

Case Headers Expected row
framed, localhost Sec-Fetch-Dest: iframe, Referer: http://localhost:8080/page localhost, iframe
framed, example.org Sec-Fetch-Dest: iframe, Referer: https://example.org/ example.org, iframe
referer only Referer: https://example.org/ example.org, none
direct open Sec-Fetch-Dest: document empty host, document
curl none empty host, none (two rows: a cache MISS at 09:57:06 and a HIT)
HEAD Referer: https://head-must-not-count.example/ no row
prefetch Sec-Purpose: prefetch and Purpose: prefetch, hosts prefetch-must-not-count.example and purpose-must-not-count.example no rows
same framed request twice Referer: https://repeat.example/ two repeat.example, iframe rows (both cache HITs)
cold dataset, framed twice dataset nm000292, Referer: https://miss-then-hit.example/ two rows: MISS then HIT

Real browsers, framing the preview from a Bun.serve page on 127.0.0.1:8080 and localhost:8080, recording the embed document request's own headers (Playwright 1.60, Chromium and WebKit; Firefox would not launch in the agent's sandbox):

Parent page Iframe attribute Sec-Fetch-Dest Referer
default policy referrerpolicy="origin" iframe http://127.0.0.1:8080/
<meta name="referrer" content="no-referrer"> referrerpolicy="origin" iframe http://127.0.0.1:8080/
unsafe-url, at /study/42/view?participant=7 referrerpolicy="origin" iframe http://127.0.0.1:8080/
no-referrer none iframe absent

The same results held on localhost:8080 (host localhost). So the snippet's referrerpolicy="origin" is what turns a no-referrer parent into a counted host, and it also strips a path and query that an unsafe-url parent would send. Chromium and WebKit each loaded the embed 8 times (4 pages on each of two hosts).

The query for the credentialed follow-up, over this phase's traffic window (the rows are time-stamped; the dataset also takes writes from other previews and staging, so filter by time or host). One more tagged request, host after-review.invalid, kind iframe, was sent at 10:21:59Z to the post-review preview https://1d14a483.nemar-website.pages.dev.

SELECT timestamp, index1, blob1 AS dataset, blob2 AS host, blob3 AS kind, double1 AS n, _sample_interval AS sample
FROM nemar_website_embeds_dev
WHERE timestamp >= toDateTime('2026-10-05 09:55:00') AND timestamp < toDateTime('2026-10-05 10:30:00')
ORDER BY timestamp
FORMAT JSON

Credential blocker: bunx cfman wrangler --account sccn whoami works and shows the SCCN account id, but cfman never reveals a token (it only injects CLOUDFLARE_API_TOKEN into the wrangler child process, and wrangler has no Analytics Engine SQL command), so the SQL API call cannot be made. What is needed is an API token with Account Analytics Read for the SCCN account, supplied as CF_ANALYTICS_TOKEN, with the account id as CF_ACCOUNT_ID.

Follow-ups

  • Run the gate 2 query above once a token is available, and paste the rows here before this leaves draft.
  • After the release that ships this: the smoke check in AGENTS.md step 9 (one load with Sec-Fetch-Dest: iframe and Referer: https://smoke.invalid/, then query nemar_website_embeds for blob2 = 'smoke.invalid').
  • Phase 4 queries should weight by _sample_interval (SUM(_sample_interval * double1)); Analytics Engine keeps three months, so the dashboard accumulates daily rows (ADR 0024).
  • nemarOrg/docs#60 (the privacy policy paragraph) merges before this reaches production, as planned in Epic: embeddable signal viewer, edge-counted embed calls, and Your Privacy Choices #410.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

embedDataPoint(request, datasetId) returns the one Analytics Engine
point for an embed call, or null for a non-GET request (HEAD
included), a prefetch, or an empty dataset id.

The point is exactly indexes [id], blobs [id, host, kind], doubles
[1]. Host is the lowercased Referer hostname only; kind is iframe,
document, none or other from Sec-Fetch-Dest.

Tested with real Request objects over every branch (32 tests). Not
wired to the middleware yet.
onRequest now wraps the existing handler and, on the response it
returns, writes one Analytics Engine data point for a GET
/dataset/<id>/embed answered with a 200. One helper, called once per
request, so passthrough, cache HIT, cache MISS and the no-cache
fallback cannot drift. The 301 hops are not counted.

The binding is read from locals.runtime.env.EMBED_ANALYTICS (typed in
env.d.ts). With none, it does nothing. A write that throws is logged
once with the dataset id and never changes the response.

Tested through the real onRequest with real Requests: no binding and a
junk binding both serve a byte-identical response; counted and
uncounted cases pinned. Cache HIT and MISS need a Workers runtime and
are left to the deployed-build gate.
Production binds nemar_website_embeds. The preview environment of the
same project binds nemar_website_embeds_dev, restated under
[env.preview] because Pages treats analytics_engine_datasets as a
non-inheritable key (vars is already overridden there). The staging
project binds the same development dataset, so only production writes
production rows.

Checked with wrangler 4.59.2: unstable_readConfig resolves the
top-level and production env to nemar_website_embeds and the preview
env to nemar_website_embeds_dev; wrangler pages dev lists the binding
for both files. The Pages docs list analytics_engine_datasets as a
supported key. The dataset is created on first write.
ADR 0024 records counting embed calls at the edge: exactly what is and
is not recorded, why Analytics Engine and not zone analytics, why the
snippet sets referrerpolicy="origin", the relation to ADR 0019, and
that visitors cannot opt out because nothing runs on their device.

Adds the architecture-map line and the changelog entry. Docs only, not
tested.
Collect the warnings directly instead of pushing a spread of them into
a second array. No behavior change; middleware tests still pass (78).
embedCallPoint(request, status) now holds everything the middleware
decided inline: exactly 200, the embed route's raw-path id match,
percent-decoding (a malformed escape counts nothing), then
embedDataPoint. The success path is pinned without a stand-in for the
binding.

Tested with real Requests: a decoded id lands in indexes[0] and
blobs[0]; 301, 304, 404, 500, 503 and other non-200s give null, as do
a malformed escape and every non-embed path (8 new tests, 40 in file).
The middleware is not switched over yet.
The URL parser accepts hostnames longer than DNS allows, and a Referer
can carry kilobytes of one. Past the 253-character DNS maximum the host
is recorded as empty rather than as junk in the host list.

Tested at exactly 253 (kept), 254 and 5000 characters (empty); 41
tests in the file.
countEmbedCall is now lookup, write, catch: whether a call counts and
with what id is embedCallPoint's decision.

Without EMBED_ANALYTICS on a production host (a deploy fault) it logs
once per isolate that embed calls are not being counted; localhost,
previews and staging stay silent. A write that keeps failing logs once
per isolate too, instead of on every load. resetEmbedCountWarnings
clears the two flags for the tests. onRequest gets a one-line comment
pointing at serve and countEmbedCall.

Tested through the real onRequest with real Requests (82 tests in the
file): the production-host warning once, silence elsewhere and for
requests that would not count, a failing write logged once and the
response unchanged, a malformed escape not counted. Mutating each flag
and the host rule fails a test.
Reads wrangler.toml and wrangler.test.toml with ?raw, as the OSA pin
test does, and asserts the production top level binds
nemar_website_embeds (never a _dev dataset), [env.preview] binds
nemar_website_embeds_dev, there is no [env.production] override, and
the staging file binds only the _dev dataset.

A flipped production dataset fails two tests; none of this fails a
build otherwise. 45 tests in the file.
The privacy policy (nemarOrg/docs#60) is written from this ADR, so:
the count keeps only the table's fields; Cloudflare's own
infrastructure and Workers logs are outside the record; a hostname
can identify a person, so it no longer says the fields cannot.

The id is percent-decoded. A browser may serve the embed from its HTTP
cache for 60 seconds, so rapid repeat views count once. A 200 also
covers the embed's two message pages, which the middleware cannot tell
apart without reading the body. Previews and staging both write to
the _dev dataset. The 253-character host cap, the once-per-isolate
warnings and the post-release smoke check are recorded.

Docs only, not tested.
AGENTS.md step 9 (Verify production) gains the check for the release
that ships embed counting: one iframe-style load with
Referer https://smoke.invalid/, then a query of nemar_website_embeds
for blob2 = 'smoke.invalid' (ADR 0024). The middleware.ts map line
names the embed call count, the embed-analytics.ts line its
whether-it-counts decision, and the changelog entry the production
warning.

Docs only, not tested.
ADR 0024 said it keeps every point, one sentence before saying it can
sample a busy index. It now says full resolution until an index is very
busy, matching the _sample_interval note. Docs only, not tested.
@neuromechanist
neuromechanist force-pushed the feature/issue-412-embed-counts branch from 4fbc6e1 to 52e31ec Compare October 5, 2026 10:26
@neuromechanist
neuromechanist marked this pull request as ready for review October 5, 2026 10:26
@neuromechanist
neuromechanist merged commit ce5bbea into staging Oct 5, 2026
5 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-412-embed-counts branch October 5, 2026 10:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant