Repository navigation
Count embed calls at the edge (phase 2 of #410) - #417
Merged
Merged
Conversation
Deploying nemar-website with
|
| Latest commit: |
52e31ec
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://c04e69a9.nemar-website.pages.dev |
| Branch Preview URL: | https://feature-issue-412-embed-coun.nemar-website.pages.dev |
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
force-pushed
the
feature/issue-412-embed-counts
branch
from
October 5, 2026 10:26
4fbc6e1 to
52e31ec
Compare
neuromechanist
marked this pull request as ready for review
October 5, 2026 10:26
This was referenced Oct 5, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Based on
staging: #415 (phase 1) merged as298674b, 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>/embedthat 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.tsand its test: the pureembedDataPoint(request, datasetId)builder andembedCallPoint(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 readswrangler.toml?rawandwrangler.test.toml?rawto pin which dataset each binds.src/middleware.tsand its test:onRequestnow wraps the existing handler (renamedserve, body unchanged) and callscountEmbedCallonce on the response it returns, which is only the lookup, the write and the catch;src/env.d.tstypeslocals.runtime.env.EMBED_ANALYTICS.wrangler.toml:EMBED_ANALYTICSbound tonemar_website_embeds(production) and, under[env.preview], tonemar_website_embeds_dev;wrangler.test.tomlbinds the staging project tonemar_website_embeds_dev.What is recorded, and what is not
Recorded, exactly:
indexes: [datasetId],blobs: [datasetId, embedderHost, kind],doubles: [1], plus Analytics Engine's own timestamp.embedderHostis the lowercased hostname fromReferer(no scheme, port, userinfo, path or query; empty when absent or unparseable);kindisiframe,document,none(header absent) orother, fromSec-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-
GETrequest (soHEAD), a prefetch (Sec-Purposecontainingprefetch, orPurpose: prefetch), and any response that is not a 200 (theds*toon*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)
Requestobjects inembed-analytics.test.ts(every branch,toStrictEqualon 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 throughembedCallPoint, and the wrangler dataset invariants), plus 13 counting tests through the realonRequestinmiddleware.test.ts.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.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).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) andbun run buildare green, re-run after the rebase ontostaging.Gate 2 detail
Preview
https://81de5f71.nemar-website.pages.dev(commitb5d08ee, before the review changes), production project's preview environment, bound tonemar_website_embeds_devby[env.preview].A temporary probe build (a throwaway branch, deleted) put
x-debug-embed-bindingon embed responses and readruntime=object;env=object;binding=object;write=functionon both a MISS and a HIT, so the adapter exposes the binding atlocals.runtime.envon a real Pages preview.Requests sent with
curlto/dataset/on007753/embed?view=sub-05(UTC, 2026-10-05), all answered 200:Sec-Fetch-Dest: iframe,Referer: http://localhost:8080/pagelocalhost,iframeSec-Fetch-Dest: iframe,Referer: https://example.org/example.org,iframeReferer: https://example.org/example.org,noneSec-Fetch-Dest: documentdocumentnone(two rows: a cache MISS at 09:57:06 and a HIT)Referer: https://head-must-not-count.example/Sec-Purpose: prefetchandPurpose: prefetch, hostsprefetch-must-not-count.exampleandpurpose-must-not-count.exampleReferer: https://repeat.example/repeat.example,iframerows (both cache HITs)nm000292,Referer: https://miss-then-hit.example/Real browsers, framing the preview from a
Bun.servepage on127.0.0.1:8080andlocalhost:8080, recording the embed document request's own headers (Playwright 1.60, Chromium and WebKit; Firefox would not launch in the agent's sandbox):Sec-Fetch-DestRefererreferrerpolicy="origin"iframehttp://127.0.0.1:8080/<meta name="referrer" content="no-referrer">referrerpolicy="origin"iframehttp://127.0.0.1:8080/unsafe-url, at/study/42/view?participant=7referrerpolicy="origin"iframehttp://127.0.0.1:8080/no-referreriframeThe same results held on
localhost:8080(hostlocalhost). So the snippet'sreferrerpolicy="origin"is what turns ano-referrerparent into a counted host, and it also strips a path and query that anunsafe-urlparent 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, kindiframe, was sent at 10:21:59Z to the post-review previewhttps://1d14a483.nemar-website.pages.dev.Credential blocker:
bunx cfman wrangler --account sccn whoamiworks and shows the SCCN account id, but cfman never reveals a token (it only injectsCLOUDFLARE_API_TOKENinto 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 asCF_ANALYTICS_TOKEN, with the account id asCF_ACCOUNT_ID.Follow-ups
Sec-Fetch-Dest: iframeandReferer: https://smoke.invalid/, then querynemar_website_embedsforblob2 = 'smoke.invalid')._sample_interval(SUM(_sample_interval * double1)); Analytics Engine keeps three months, so the dashboard accumulates daily rows (ADR 0024).