Console analytics: a pages view, bots by name, browsers and devices, and the pace check (Paul, 2026-10-30, after a crawler walked paulca.com's /posts/ with a browser user agent). Top pages and Referrers show 25 rows; 'See all N pages' opens ?show=pages: every page by top folder (a folder holding only its own index joins the top level; the overflow row stays its own group, last), each with its share and, over 7 or 30 days, a line of its days, with a filter the minute refresh keeps. Per-day page counts are read only for that view and stripped before the memo otherwise. Named events are removed until carlos.js exists. The edge names each bot request from a fixed list (and IsBot now matches every named bot), counts page views by browser family and device class, and stores only those names (bot_names, browsers, devices: additive day-file maps); no user agent string is stored. Pace check: per box and app, a visitor (the day's salted hash, in memory only) with 20 page views inside a minute is an Unnamed crawler from that view until 30 minutes after their latest view; those views are bot requests, not page views, visitors, pages, referrers, countries, browsers or devices; at most 50,000 visitors held, idle ones pruned. The tab gains Browsers (with Devices) and Bots cards once an edge counts them; the CLI API carries the maps. Reviews: Astra R1 READY AFTER FIXES (3 P2s fixed: named bots counted as people, overflow folded into the top level, out-of-order timestamps shortening the hold); Luna copy pass; census census-ruling-analytics-agents (internal/analytics envelope) approved by Astra on #280. Supersedes branch analytics-pages. Not released.
Squashed from analytics-agents into main.
20 files changed,
+1,020
−30
docs/superpowers/notes/census-proposal-analytics-agents.md+11 −0docs/superpowers/reviews/CODEX-FINDINGS-analytics-agents-R1.md+24 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-agents.md+38 −0internal/analytics/agents.go+91 −0internal/analytics/agents_test.go+200 −0internal/analytics/bots.go+8 −0internal/analytics/day.go+19 −0internal/analytics/meter.go+32 −8internal/analytics/pace.go+83 −0internal/analytics/read.go+15 −0internal/console/analyticsdisplay.go+165 −0internal/console/analyticslive.go+31 −2internal/console/analyticspages_test.go+157 −0internal/console/analyticsview.go+35 −9internal/console/apianalytics.go+4 −0internal/console/apianalytics_test.go+1 −1internal/console/templates/app_analytics.html+86 −10internal/console/templates/layout.html+16 −0internal/provision/testdata/plan14-root-reads-analytics-agents.tsv+3 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0
CI passed — run details
diff --git a/docs/superpowers/notes/census-proposal-analytics-agents.md b/docs/superpowers/notes/census-proposal-analytics-agents.md| new file mode 100644 |
| index 000000000..406e7d905 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-analytics-agents.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: analytics-agents |
| + |
| +Ruling `census-ruling-analytics-agents`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/analytics`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Seal: `5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64` → `5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-analytics-agents.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-analytics-agents-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-analytics-agents-R1.md| new file mode 100644 |
| index 000000000..86312d52d |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-analytics-agents-R1.md |
| @@ -0,0 +1,24 @@ |
| +Reviewed `origin/main...9e23ed3099` under the brief at `52e3ce5f`. No P1 findings. |
| + |
| +1. **P2 — Named bots are counted as people.** |
| + [agents.go:15](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/analytics-agents/internal/analytics/agents.go:15) names Google InspectionTool, ChatGPT-User, Claude-User and Meta ExternalAgent, but `IsPageview` first requires `IsBot`, whose markers omit them. Verified: each returns a bot name yet produces `pageview=true, bot=false`. Their requests inflate visitors and page-view breakdowns instead of their named bot counts. |
| + **Fix:** Make named-bot recognition part of `IsBot`, and test classification through `Observe`. |
| + **Fault family:** Consistency between bot recognition, naming and counting. |
| + |
| +2. **P2 — Overflow is incorrectly grouped as a top-level page.** |
| + At [analyticsdisplay.go:571](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/analytics-agents/internal/console/analyticsdisplay.go:571), the singleton-folder condition also matches `_other`. Verified with `/blog/a:1, _other:100`: “Top level” becomes the first section, reporting one page and 100 views. The intended separate, last overflow section disappears. |
| + **Fix:** Exclude `analytics.OtherKey` from singleton-folder folding; add an overflow grouping witness. |
| + **Fault family:** Overflow represents unattributed mass, not a page or folder. |
| + |
| +3. **P2 — Backward timestamps can prematurely release a flagged crawler.** |
| + [pace.go:64](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/analytics-agents/internal/analytics/pace.go:64) replaces `last` unconditionally. Verified: flag a visitor at noon, observe an out-of-order timestamp at 11:00, then observe 12:00:01. The visitor becomes unflagged because the hold calculation uses 11:00. |
| + **Fix:** Keep the latest timestamp monotonically increasing for hold expiry and pruning; define and test backward-time window handling separately. |
| + **Fault family:** The crawler hold lasts until 30 minutes after the latest observation. |
| + |
| +The heuristic can flag genuine reload/tab bursts and is easily evaded by changing UA or staying below the threshold. Declared prefetches are excluded. Midnight changes the visitor hash and starts fresh pace state; salt failure bypasses detection. Those are v1 limitations, not additional findings. |
| + |
| +Targeted analytics tests and server-free console tests passed. Additional witnesses ran through memory-only Go overlays; no files were edited. Console integration tests were blocked by the sandbox’s socket restriction, so their runtime behavior remains unverified. An external working-tree edit to the Bots sentence was left untouched. |
| + |
| +**Census: APPROVE** the `internal/analytics` envelope re-pin. The changed functions add counting and classification state without introducing root read paths or weakening checks on existing reads. No individual units receive new dispositions. |
| + |
| +**READY AFTER FIXES** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-agents.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-agents.md| new file mode 100644 |
| index 000000000..f2dd1169e |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-agents.md |
| @@ -0,0 +1,38 @@ |
| +# Review brief: branches analytics-pages and analytics-agents, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `analytics-agents` at commit 9e23ed3099 (`git rev-parse 9e23ed3099`). It is stacked on `analytics-pages` (08a205a0), which lands first; review the whole diff `origin/main...9e23ed3099`. |
| +Authorities: the analytics edge counting and console tab on main (internal/analytics, internal/console/analytics*.go, templates/app_analytics.html), AGENTS.md (stopping rules; S3 request-cost rules; census). |
| + |
| +You are an independent reviewer. Read the diff, then the code it calls, and check every claim in comments, commit messages and page text against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul (2026-10-30): Top pages capped at 25 with a "See all" pages view; Named events removed until carlos.js exists; bots by name and browser families; behavioural crawler detection ("seems like it would be useful anyway"). No raw user agent is stored, only names from fixed lists. |
| + |
| +## What to check |
| + |
| +1. The pace check (internal/analytics/pace.go, Meter.Observe): correctness of the window, hold and reset; that a flagged view is removed from page views, visitors, pages, referrers, countries, browsers and devices and counted as a bot; memory bound and pruning; behaviour across midnight (the visitor hash changes with the day's salt), with no salt, with clock skew (o.When going backwards), and with many apps. Can a real reader be flagged (20 page views in a minute: SPAs with prefetch, reloads, tabs)? Can a crawler evade it trivially, and is that acceptable for v1? |
| +2. Bot naming, browser family and device class (agents.go): ordering mistakes (Edge/Opera/Samsung contain Chrome; Chrome contains Safari; Android tablets), and that only fixed names reach the day file. |
| +3. Day file compatibility: new fields are additive and omitempty; a day written by an older edge, a newer edge's day read by an older console, merge bounds. |
| +4. The pages view (analyticsview.go, analyticsdisplay.go buildPageSections, analyticslive.go query parsing): per-day page counts kept only for the pages view and stripped before the memo otherwise; memo key includes the view; section grouping rules; links (html/template escaping in hrefs); the live refresh keeping filter text and open groups. |
| +5. Census: docs/superpowers/notes/census-proposal-analytics-agents.md re-pins the internal/analytics envelope. Answer its review question (approve or reject, with the reason). |
| +6. Tests: sound witnesses; anything that would fail CI (darwin, windows) or break an existing test; whether other packages' tests that send many requests from one client could now trip the pace check. |
| +7. Page text: only report text that states something false. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the area, the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks (its fault family). Then the census verdict. End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites; targeted `go test ./internal/analytics/ ./internal/console/ -run ...` is fine. |
diff --git a/internal/analytics/agents.go b/internal/analytics/agents.go| new file mode 100644 |
| index 000000000..f4eba4586 |
| --- /dev/null |
| +++ b/internal/analytics/agents.go |
| @@ -0,0 +1,91 @@ |
| +package analytics |
| + |
| +import "strings" |
| + |
| +// Who a request came from, in words from fixed lists (Paul, 2026-10-30: |
| +// which bots crawl the site, which browsers read it). A user agent is |
| +// matched and named here, at the edge, and only the name is counted: no |
| +// user agent string is stored, so nothing a visitor's browser sends lands |
| +// in a day file except one of the names below. |
| + |
| +// botNames names the bot a user agent belongs to, most specific first. The |
| +// first marker the lower-cased user agent contains wins. A user agent that |
| +// IsBot flags and none of these name is "Other bot". |
| +var botNames = []struct{ marker, name string }{ |
| + {"googlebot", "Googlebot"}, {"google-inspectiontool", "Google"}, {"adsbot-google", "Google"}, |
| + {"bingbot", "Bingbot"}, {"applebot", "Applebot"}, {"duckduckbot", "DuckDuckGo"}, |
| + {"yandex", "Yandex"}, {"baiduspider", "Baidu"}, {"slurp", "Yahoo"}, |
| + {"gptbot", "GPTBot"}, {"oai-searchbot", "OpenAI search"}, {"chatgpt-user", "ChatGPT"}, |
| + {"claudebot", "ClaudeBot"}, {"claude-user", "Claude"}, {"perplexitybot", "PerplexityBot"}, |
| + {"amazonbot", "Amazonbot"}, {"meta-externalagent", "Meta"}, {"facebookexternalhit", "Facebook"}, |
| + {"ccbot", "Common Crawl"}, {"bytespider", "Bytespider"}, {"petalbot", "PetalBot"}, |
| + {"ahrefs", "Ahrefs"}, {"semrush", "Semrush"}, {"mj12", "Majestic"}, {"dotbot", "DotBot"}, |
| + {"linkedinbot", "LinkedIn"}, {"twitterbot", "X (Twitter)"}, {"discordbot", "Discord"}, |
| + {"telegrambot", "Telegram"}, {"whatsapp", "WhatsApp"}, {"slackbot", "Slack"}, |
| + {"pingdom", "Pingdom"}, {"uptimerobot", "UptimeRobot"}, {"statuscake", "StatusCake"}, |
| + {"site24x7", "Site24x7"}, {"newrelicpinger", "New Relic"}, |
| + {"lighthouse", "Lighthouse"}, {"pagespeed", "PageSpeed"}, {"gtmetrix", "GTmetrix"}, |
| + {"headlesschrome", "Headless Chrome"}, {"phantomjs", "PhantomJS"}, |
| + {"curl/", "curl"}, {"wget/", "Wget"}, {"python-requests", "Python requests"}, |
| + {"go-http-client", "Go HTTP client"}, {"okhttp", "OkHttp"}, {"java/", "Java"}, |
| + {"libwww", "libwww"}, {"scrapy", "Scrapy"}, {"node-fetch", "node-fetch"}, {"axios/", "axios"}, |
| + {"postmanruntime", "Postman"}, {"insomnia", "Insomnia"}, {"httpclient", "HTTP client"}, |
| +} |
| + |
| +// Names the edge gives to bots that are not named by their user agent. |
| +const ( |
| + BotNoUserAgent = "No user agent" |
| + BotOther = "Other bot" |
| + // BotByPace is a visitor whose browser looked like a person's but who |
| + // read pages faster than a person does (Meter's pace check). |
| + BotByPace = "Unnamed crawler" |
| +) |
| + |
| +// BotName is the name a bot's user agent is counted under. |
| +func BotName(ua string) string { |
| + if strings.TrimSpace(ua) == "" { |
| + return BotNoUserAgent |
| + } |
| + l := strings.ToLower(ua) |
| + for _, b := range botNames { |
| + if strings.Contains(l, b.marker) { |
| + return b.name |
| + } |
| + } |
| + return BotOther |
| +} |
| + |
| +// BrowserFamily is the browser a person's user agent names. Order matters: |
| +// Edge, Opera and Samsung Internet also say Chrome, and Chrome also says |
| +// Safari. |
| +func BrowserFamily(ua string) string { |
| + l := strings.ToLower(ua) |
| + switch { |
| + case strings.Contains(l, "edg/") || strings.Contains(l, "edga/") || strings.Contains(l, "edgios/"): |
| + return "Edge" |
| + case strings.Contains(l, "opr/") || strings.Contains(l, "opera"): |
| + return "Opera" |
| + case strings.Contains(l, "samsungbrowser"): |
| + return "Samsung Internet" |
| + case strings.Contains(l, "firefox/") || strings.Contains(l, "fxios/"): |
| + return "Firefox" |
| + case strings.Contains(l, "crios/") || strings.Contains(l, "chrome/") || strings.Contains(l, "chromium/"): |
| + return "Chrome" |
| + case strings.Contains(l, "safari/") && strings.Contains(l, "version/"): |
| + return "Safari" |
| + } |
| + return "Other" |
| +} |
| + |
| +// DeviceClass is the kind of device a person's user agent says it is. |
| +func DeviceClass(ua string) string { |
| + l := strings.ToLower(ua) |
| + switch { |
| + case strings.Contains(l, "ipad") || strings.Contains(l, "tablet") || |
| + (strings.Contains(l, "android") && !strings.Contains(l, "mobile")): |
| + return "Tablet" |
| + case strings.Contains(l, "mobi") || strings.Contains(l, "iphone") || strings.Contains(l, "android"): |
| + return "Mobile" |
| + } |
| + return "Desktop" |
| +} |
diff --git a/internal/analytics/agents_test.go b/internal/analytics/agents_test.go| new file mode 100644 |
| index 000000000..87639e807 |
| --- /dev/null |
| +++ b/internal/analytics/agents_test.go |
| @@ -0,0 +1,200 @@ |
| +package analytics |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestBotName(t *testing.T) { |
| + for ua, want := range map[string]string{ |
| + "": BotNoUserAgent, |
| + " ": BotNoUserAgent, |
| + "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)": "Googlebot", |
| + "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2)": "GPTBot", |
| + "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0)": "ClaudeBot", |
| + "Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)": "Ahrefs", |
| + "curl/8.4.0": "curl", |
| + "python-requests/2.31.0": "Python requests", |
| + "SomethingBot/1.0": BotOther, |
| + } { |
| + if got := BotName(ua); got != want { |
| + t.Errorf("BotName(%q) = %q, want %q", ua, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestBrowserAndDevice(t *testing.T) { |
| + for _, tc := range []struct{ ua, browser, device string }{ |
| + {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15", "Safari", "Desktop"}, |
| + {"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1", "Safari", "Mobile"}, |
| + {"Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/120.0 Mobile/15E148 Safari/604.1", "Chrome", "Tablet"}, |
| + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36 Edg/120.0", "Edge", "Desktop"}, |
| + {"Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/23.0 Chrome/115.0 Mobile Safari/537.36", "Samsung Internet", "Mobile"}, |
| + {"Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0", "Firefox", "Desktop"}, |
| + {"Mozilla/5.0 (Linux; Android 14; Pixel Tablet) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36", "Chrome", "Tablet"}, |
| + {"Lynx/2.9.0", "Other", "Desktop"}, |
| + } { |
| + if got := BrowserFamily(tc.ua); got != tc.browser { |
| + t.Errorf("BrowserFamily(%q) = %q, want %q", tc.ua, got, tc.browser) |
| + } |
| + if got := DeviceClass(tc.ua); got != tc.device { |
| + t.Errorf("DeviceClass(%q) = %q, want %q", tc.ua, got, tc.device) |
| + } |
| + } |
| +} |
| + |
| +const safariUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15" |
| + |
| +func pageObs(path string, when time.Time, ip string) Obs { |
| + return Obs{Acct: release.OpsAccount, App: "site", Host: "site.example.com", Method: "GET", Status: 200, |
| + ContentType: "text/html", Path: path, UA: safariUA, ClientIP: ip, When: when, Bytes: 100} |
| +} |
| + |
| +// A browser that reads pages faster than a person: its first paceLimit-1 |
| +// views are page views, the rest of the minute and everything until |
| +// paceHold after its last view are an unnamed crawler's. Another visitor at |
| +// the same time is untouched. |
| +func TestPaceCountsAFastReaderAsACrawler(t *testing.T) { |
| + t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC) |
| + m := NewMeter(t.TempDir(), "box1", func() time.Time { return t0 }) |
| + for i := 0; i < 40; i++ { |
| + m.Observe(pageObs(fmt.Sprintf("/posts/%d.html", i), t0.Add(time.Duration(i)*time.Second), "203.0.113.1")) |
| + } |
| + m.Observe(pageObs("/", t0.Add(30*time.Second), "203.0.113.2")) // a person, same minute |
| + m.Observe(pageObs("/late", t0.Add(20*time.Minute), "203.0.113.1")) // inside the hold |
| + m.Observe(pageObs("/back", t0.Add(80*time.Minute), "203.0.113.1")) // after the hold |
| + d := drainOne(t, m) |
| + var pv, bots int64 |
| + for _, h := range d.Hours { |
| + pv += h.PV |
| + bots += h.Bots |
| + } |
| + if pv != paceLimit-1+1+1 || bots != 40-(paceLimit-1)+1 { |
| + t.Fatalf("page views %d bots %d, want %d and %d", pv, bots, paceLimit-1+2, 40-(paceLimit-1)+1) |
| + } |
| + if d.BotNames[BotByPace] != bots { |
| + t.Errorf("bot names = %v", d.BotNames) |
| + } |
| + if d.Pages.counts["/posts/30.html"] != 0 || d.Pages.counts["/back"] != 1 || d.Pages.counts["/late"] != 0 { |
| + t.Errorf("pages = %v", d.Pages.counts) |
| + } |
| + if d.Browsers["Safari"] != pv || d.Devices["Desktop"] != pv { |
| + t.Errorf("browsers %v devices %v, want only the page views", d.Browsers, d.Devices) |
| + } |
| +} |
| + |
| +// A steady reader (one page every 4 s, 15 a minute) is never a crawler. |
| +func TestPaceLeavesASteadyReaderAlone(t *testing.T) { |
| + t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC) |
| + m := NewMeter(t.TempDir(), "box1", func() time.Time { return t0 }) |
| + for i := 0; i < 60; i++ { |
| + m.Observe(pageObs("/p", t0.Add(time.Duration(i)*4*time.Second), "203.0.113.1")) |
| + } |
| + d := drainOne(t, m) |
| + var bots int64 |
| + for _, h := range d.Hours { |
| + bots += h.Bots |
| + } |
| + if bots != 0 { |
| + t.Fatalf("a reader at 15 pages a minute counted %d bot views", bots) |
| + } |
| +} |
| + |
| +// The pace map is bounded: past paceMaxVisitors, idle visitors are dropped, |
| +// and a new visitor goes unchecked rather than growing the map. |
| +func TestPaceMapIsBounded(t *testing.T) { |
| + t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC) |
| + m := &Meter{} |
| + for i := 0; i < paceMaxVisitors; i++ { |
| + m.tooFast(AppKey{App: "a"}, uint64(i), t0) |
| + } |
| + if m.tooFast(AppKey{App: "a"}, 1<<40, t0); len(m.paces) != paceMaxVisitors { |
| + t.Fatalf("map grew to %d", len(m.paces)) |
| + } |
| + m.tooFast(AppKey{App: "a"}, 1<<41, t0.Add(paceHold+time.Minute)) |
| + if len(m.paces) != 1 { |
| + t.Fatalf("idle visitors not dropped: %d left", len(m.paces)) |
| + } |
| +} |
| + |
| +// The new counts reach the day file and the window read, summed across |
| +// boxes, and a day file from before them still reads. |
| +func TestAgentCountsRoundTrip(t *testing.T) { |
| + store := release.NewDirStore(filepath.Join(t.TempDir(), "store")) |
| + t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC) |
| + for _, box := range []string{"box1", "box2"} { |
| + m := NewMeter(t.TempDir(), box, func() time.Time { return t0 }) |
| + m.Observe(pageObs("/", t0, "203.0.113.1")) |
| + bot := pageObs("/", t0, "203.0.113.9") |
| + bot.UA = "Mozilla/5.0 (compatible; GPTBot/1.2)" |
| + m.Observe(bot) |
| + for k, ds := range m.Drain() { |
| + for _, d := range ds { |
| + if err := UpsertDay(context.Background(), store, k.Acct, k.App, d); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + } |
| + sum, err := ReadRange(context.Background(), store, release.OpsAccount, "site", t0, t0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if sum.BotNames["GPTBot"] != 2 || sum.Browsers["Safari"] != 2 || sum.Devices["Desktop"] != 2 { |
| + t.Fatalf("bot names %v browsers %v devices %v", sum.BotNames, sum.Browsers, sum.Devices) |
| + } |
| +} |
| + |
| +func drainOne(t *testing.T, m *Meter) Delta { |
| + t.Helper() |
| + for _, ds := range m.Drain() { |
| + if len(ds) != 1 { |
| + t.Fatalf("%d deltas, want 1", len(ds)) |
| + } |
| + return ds[0] |
| + } |
| + t.Fatal("nothing drained") |
| + return Delta{} |
| +} |
| + |
| +// Every bot BotName names is a bot to IsPageview, so it is counted under its |
| +// name and never as a page view. |
| +func TestNamedBotsAreBots(t *testing.T) { |
| + for _, b := range botNames { |
| + ua := "Mozilla/5.0 (compatible; " + b.marker + "/1.0)" |
| + if !IsBot(ua) { |
| + t.Errorf("%s names %q but IsBot says person", b.marker, b.name) |
| + } |
| + } |
| + t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC) |
| + m := NewMeter(t.TempDir(), "box1", func() time.Time { return t0 }) |
| + o := pageObs("/", t0, "203.0.113.1") |
| + o.UA = "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot" |
| + m.Observe(o) |
| + d := drainOne(t, m) |
| + if d.BotNames["ChatGPT"] != 1 || d.Hours["09"].PV != 0 { |
| + t.Fatalf("ChatGPT-User: bot names %v, page views %d", d.BotNames, d.Hours["09"].PV) |
| + } |
| +} |
| + |
| +// A view stamped earlier than the latest one does not shorten the hold. |
| +func TestPaceHoldRunsFromTheLatestView(t *testing.T) { |
| + noon := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC) |
| + m := &Meter{} |
| + k := AppKey{App: "a"} |
| + for i := 0; i < paceLimit; i++ { |
| + m.tooFast(k, 1, noon) |
| + } |
| + m.tooFast(k, 1, noon.Add(-time.Hour)) // out of order |
| + if !m.tooFast(k, 1, noon.Add(time.Second)) { |
| + t.Fatal("an out-of-order view released a flagged crawler") |
| + } |
| + if m.tooFast(k, 1, noon.Add(paceHold+2*time.Second)) { |
| + t.Fatal("still flagged past the hold after the latest view") |
| + } |
| +} |
diff --git a/internal/analytics/bots.go b/internal/analytics/bots.go| index 195bfca0c..3ca63e7af 100644 |
| --- a/internal/analytics/bots.go |
| +++ b/internal/analytics/bots.go |
| @@ -28,5 +28,13 @@ func IsBot(ua string) bool { |
| return true |
| } |
| } |
| + // A bot BotName names is a bot, even when no generic marker matches |
| + // it (ChatGPT-User, Claude-User, Google-InspectionTool): naming and |
| + // counting must agree. |
| + for _, b := range botNames { |
| + if strings.Contains(l, b.marker) { |
| + return true |
| + } |
| + } |
| return false |
| } |
diff --git a/internal/analytics/day.go b/internal/analytics/day.go| index 9bbcd9c17..5828beb25 100644 |
| --- a/internal/analytics/day.go |
| +++ b/internal/analytics/day.go |
| @@ -51,6 +51,13 @@ type Day struct { |
| // spec §9): the provenance the attribution on the analytics page needs. |
| GeoSources map[string]int64 `json:"geo_sources,omitempty"` |
| Restarted bool `json:"restarted,omitempty"` |
| + // BotNames counts bot requests by who sent them (agents.go: a name |
| + // from a fixed list, never the user agent itself); Browsers and Devices |
| + // count page views by browser family and device class. Absent from a |
| + // day written by an edge before them. |
| + BotNames map[string]int64 `json:"bot_names,omitempty"` |
| + Browsers map[string]int64 `json:"browsers,omitempty"` |
| + Devices map[string]int64 `json:"devices,omitempty"` |
| } |
| // Delta is one flush batch from one box for one app-day. |
| @@ -69,6 +76,10 @@ type Delta struct { |
| // spec §9), bounded by boundedAdd. |
| Countries map[string]int64 |
| GeoSources map[string]int64 |
| + // BotNames, Browsers and Devices: see Day. |
| + BotNames map[string]int64 |
| + Browsers map[string]int64 |
| + Devices map[string]int64 |
| // requeued marks a delta that has already been through one failed |
| // flush (internal/analytics.Meter.Requeue). Not serialised: it never |
| @@ -144,6 +155,9 @@ func (d *Day) Merge(x Delta) (bool, error) { |
| d.Restarted = d.Restarted || x.Restarted |
| d.Countries = mergeCounts(d.Countries, x.Countries, maxCountryKeys, nil) |
| d.GeoSources = mergeCounts(d.GeoSources, x.GeoSources, maxGeoSourceKeys, attributed) |
| + d.BotNames = mergeCounts(d.BotNames, x.BotNames, maxBotNameKeys, nil) |
| + d.Browsers = mergeCounts(d.Browsers, x.Browsers, maxBrowserKeys, nil) |
| + d.Devices = mergeCounts(d.Devices, x.Devices, maxDeviceKeys, nil) |
| d.Seq[x.Box] = x.Seq |
| return true, nil |
| } |
| @@ -204,6 +218,11 @@ func UpsertDay(ctx context.Context, s release.Store, sqid, app string, x Delta) |
| const ( |
| maxCountryKeys = 300 |
| maxGeoSourceKeys = 8 |
| + // The agent names come from fixed lists, so these only bound a day |
| + // written by something else. |
| + maxBotNameKeys = 100 |
| + maxBrowserKeys = 20 |
| + maxDeviceKeys = 8 |
| ) |
| // attributed reports whether a database type carries an attribution the |
diff --git a/internal/analytics/meter.go b/internal/analytics/meter.go| index 3c502bf5f..58ab6d6c5 100644 |
| --- a/internal/analytics/meter.go |
| +++ b/internal/analytics/meter.go |
| @@ -108,10 +108,11 @@ type Meter struct { |
| seq int64 |
| saltDay string |
| salt []byte |
| - saltFailDay string // date DaySalt last failed for, "" once it next succeeds |
| - saltFailAt time.Time // when it failed; not retried until saltRetryDelay has passed |
| - started string // date the process started; "" once the wall clock has moved past it (see Drain) |
| - restartedFlagged map[AppKey]bool // apps whose start-day delta has already carried Restarted |
| + saltFailDay string // date DaySalt last failed for, "" once it next succeeds |
| + saltFailAt time.Time // when it failed; not retried until saltRetryDelay has passed |
| + started string // date the process started; "" once the wall clock has moved past it (see Drain) |
| + restartedFlagged map[AppKey]bool // apps whose start-day delta has already carried Restarted |
| + paces map[paceKey]*paceState // the pace check's visitors (pace.go) |
| } |
| // NewMeter returns a meter whose salts live in saltDir (the box data dir). |
| @@ -156,7 +157,8 @@ func (m *Meter) delta(k AppKey, date string) *Delta { |
| restarted := date == m.started && !m.restartedFlagged[k] |
| d = &Delta{Date: date, Box: m.box, Hours: map[string]HourRow{}, Visitors: &HLL{}, |
| Pages: NewTopK(), Referers: NewTopK(), Events: NewTopK(), Restarted: restarted, |
| - Countries: map[string]int64{}, GeoSources: map[string]int64{}} |
| + Countries: map[string]int64{}, GeoSources: map[string]int64{}, |
| + BotNames: map[string]int64{}, Browsers: map[string]int64{}, Devices: map[string]int64{}} |
| days[date] = d |
| if restarted { |
| m.restartedFlagged[k] = true // this app's start-day note is spent; a later drain's fresh delta for the same day must not repeat it |
| @@ -173,17 +175,38 @@ func (m *Meter) Observe(o Obs) { |
| path := apperr.SanitizePath(o.Path) |
| m.mu.Lock() |
| defer m.mu.Unlock() |
| - d := m.delta(AppKey{Acct: o.Acct, App: o.App}, date) |
| + k := AppKey{Acct: o.Acct, App: o.App} |
| + d := m.delta(k, date) |
| row := d.Hours[hour] |
| row.Bytes += o.Bytes |
| + botName := "" |
| + if bot { |
| + botName = BotName(o.UA) |
| + } |
| + var visitor uint64 |
| + salt := []byte(nil) |
| + if pv { |
| + salt = m.saltFor(date) |
| + } |
| + if salt != nil { |
| + visitor = VisitorHash(salt, o.Host, o.ClientIP, o.UA) |
| + // A browser that reads faster than a person is a crawler: its view |
| + // is a bot's, not a page view (pace.go). |
| + if m.tooFast(k, visitor, o.When) { |
| + pv, bot, botName = false, true, BotByPace |
| + } |
| + } |
| if bot { |
| row.Bots++ |
| + boundedAdd(d.BotNames, botName, 1, maxBotNameKeys, nil) |
| } |
| if pv { |
| row.PV++ |
| - if salt := m.saltFor(date); salt != nil { |
| - d.Visitors.Add(VisitorHash(salt, o.Host, o.ClientIP, o.UA)) |
| + if salt != nil { |
| + d.Visitors.Add(visitor) |
| } |
| + boundedAdd(d.Browsers, BrowserFamily(o.UA), 1, maxBrowserKeys, nil) |
| + boundedAdd(d.Devices, DeviceClass(o.UA), 1, maxDeviceKeys, nil) |
| d.Pages.Add(path, 1) |
| ref := o.RefererHost |
| if ref == "" { |
| @@ -218,6 +241,7 @@ func (m *Meter) Track(acct, app, name string, when time.Time) { |
| func (m *Meter) Drain() map[AppKey][]Delta { |
| m.mu.Lock() |
| defer m.mu.Unlock() |
| + m.prunePaces(m.now()) |
| out := map[AppKey][]Delta{} |
| for k, ds := range m.pending { |
| out[k] = append(out[k], ds...) |
diff --git a/internal/analytics/pace.go b/internal/analytics/pace.go| new file mode 100644 |
| index 000000000..c7a29f37e |
| --- /dev/null |
| +++ b/internal/analytics/pace.go |
| @@ -0,0 +1,83 @@ |
| +package analytics |
| + |
| +import "time" |
| + |
| +// The pace check: a crawler whose user agent looks like a browser's still |
| +// reads pages faster than a person does (paulca.com, 2026-10-28: one visitor |
| +// walked /posts/1.html to /posts/40.html, each counted as a page view). Per |
| +// box and per app, the meter counts each visitor's page views in a window of |
| +// paceWindow; from the paceLimit-th view on, that visitor's views are counted |
| +// as a bot (BotByPace) until paceHold after their last view. The first |
| +// paceLimit-1 views still count as page views: the check cannot know a |
| +// reader is a crawler before it has read too fast. |
| +// |
| +// A visitor is the day's visitor hash (VisitorHash): salted, never stored, |
| +// held only in this map. With no salt (DaySalt failing) there is no hash |
| +// and no check. The map holds at most paceMaxVisitors entries; past that, |
| +// entries idle for paceHold are dropped, and if it is still full a new |
| +// visitor goes unchecked rather than growing it. Drain prunes it too. |
| +const ( |
| + paceWindow = time.Minute |
| + paceLimit = 20 |
| + paceHold = 30 * time.Minute |
| + paceMaxVisitors = 50_000 |
| +) |
| + |
| +type paceKey struct { |
| + app AppKey |
| + visitor uint64 |
| +} |
| + |
| +type paceState struct { |
| + start time.Time // the current window's first view |
| + n int // views in the current window |
| + last time.Time // the latest view |
| + flagged bool // read too fast; held until last+paceHold |
| +} |
| + |
| +// tooFast records one page view by visitor at when and reports whether the |
| +// view, and so the visitor, is now counted as a crawler. Called with m.mu |
| +// held. |
| +func (m *Meter) tooFast(app AppKey, visitor uint64, when time.Time) bool { |
| + if m.paces == nil { |
| + m.paces = map[paceKey]*paceState{} |
| + } |
| + k := paceKey{app, visitor} |
| + p := m.paces[k] |
| + if p == nil { |
| + if len(m.paces) >= paceMaxVisitors { |
| + m.prunePaces(when) |
| + if len(m.paces) >= paceMaxVisitors { |
| + return false |
| + } |
| + } |
| + p = &paceState{start: when} |
| + m.paces[k] = p |
| + } |
| + if p.flagged && when.After(p.last) && when.Sub(p.last) > paceHold { |
| + p.flagged = false |
| + } |
| + if when.Sub(p.start) >= paceWindow || when.Before(p.start) { |
| + p.start, p.n = when, 0 |
| + } |
| + p.n++ |
| + // The hold runs from the latest view, so a request stamped earlier |
| + // (another box's clock, a slow writer) cannot shorten it. |
| + if when.After(p.last) { |
| + p.last = when |
| + } |
| + if p.n >= paceLimit { |
| + p.flagged = true |
| + } |
| + return p.flagged |
| +} |
| + |
| +// prunePaces drops visitors idle for longer than paceHold at now. Called |
| +// with m.mu held. |
| +func (m *Meter) prunePaces(now time.Time) { |
| + for k, p := range m.paces { |
| + if now.Sub(p.last) > paceHold { |
| + delete(m.paces, k) |
| + } |
| + } |
| +} |
diff --git a/internal/analytics/read.go b/internal/analytics/read.go| index af9cd99d9..c1caa84cc 100644 |
| --- a/internal/analytics/read.go |
| +++ b/internal/analytics/read.go |
| @@ -24,6 +24,10 @@ type DaySummary struct { |
| Visitors int64 `json:"visitors"` |
| Hours [24]int64 `json:"hours"` |
| Restarted bool `json:"restarted"` |
| + // Pages is the day's page views by page, merged across boxes and |
| + // folded as the window's own Pages is. The console's pages view draws |
| + // each page's days from it; the API leaves it out. |
| + Pages map[string]int64 `json:"-"` |
| } |
| // Summary is what the tab and the API render: per-day rows plus totals. |
| @@ -40,6 +44,9 @@ type Summary struct { |
| Events map[string]int64 |
| Countries map[string]int64 |
| GeoSources map[string]int64 |
| + BotNames map[string]int64 |
| + Browsers map[string]int64 |
| + Devices map[string]int64 |
| PagesApprox bool |
| ReferersApprox bool |
| EventsApprox bool |
| @@ -76,9 +83,11 @@ func ReadRange(ctx context.Context, s release.Store, sqid, app string, from, to |
| sort.Strings(sum.Boxes) |
| pages, refs, events := NewTopK(), NewTopK(), NewTopK() |
| countries, sources := map[string]int64{}, map[string]int64{} |
| + botNames, browsers, devices := map[string]int64{}, map[string]int64{}, map[string]int64{} |
| for _, date := range Dates(from, to) { |
| ds := DaySummary{Date: date} |
| vis := &HLL{} |
| + dayPages := NewTopK() |
| for _, box := range sum.Boxes { |
| key, err := DayKey(sqid, app, box, date) |
| if err != nil { |
| @@ -107,10 +116,14 @@ func ReadRange(ctx context.Context, s release.Store, sqid, app string, from, to |
| vis.Merge(v) |
| } |
| pages.Merge(TopKFrom(day.Pages)) |
| + dayPages.Merge(TopKFrom(day.Pages)) |
| refs.Merge(TopKFrom(day.Referers)) |
| events.Merge(TopKFrom(day.Events)) |
| mergeCounts(countries, day.Countries, maxCountryKeys, nil) |
| mergeCounts(sources, day.GeoSources, maxGeoSourceKeys, attributed) |
| + mergeCounts(botNames, day.BotNames, maxBotNameKeys, nil) |
| + mergeCounts(browsers, day.Browsers, maxBrowserKeys, nil) |
| + mergeCounts(devices, day.Devices, maxDeviceKeys, nil) |
| sum.Dropped.E = addDrops(sum.Dropped.E, day.Dropped.E) |
| sum.Dropped.A = addDrops(sum.Dropped.A, day.Dropped.A) |
| sum.Dropped.Flush += day.Dropped.Flush |
| @@ -119,6 +132,7 @@ func ReadRange(ctx context.Context, s release.Store, sqid, app string, from, to |
| if !vis.Empty() { |
| ds.Visitors = int64(math.Round(vis.Count())) |
| } |
| + ds.Pages = dayPages.Fold() |
| sum.Days = append(sum.Days, ds) |
| sum.PV += ds.PV |
| sum.Bots += ds.Bots |
| @@ -129,6 +143,7 @@ func ReadRange(ctx context.Context, s release.Store, sqid, app string, from, to |
| sum.Referers, sum.ReferersApprox = refs.Fold(), refs.Approximate() |
| sum.Events, sum.EventsApprox = events.Fold(), events.Approximate() |
| sum.Countries, sum.GeoSources = countries, sources |
| + sum.BotNames, sum.Browsers, sum.Devices = botNames, browsers, devices |
| return sum, nil |
| } |
diff --git a/internal/console/analyticsdisplay.go b/internal/console/analyticsdisplay.go| index 77af1e4ef..e4c108bb2 100644 |
| --- a/internal/console/analyticsdisplay.go |
| +++ b/internal/console/analyticsdisplay.go |
| @@ -15,6 +15,7 @@ package console |
| import ( |
| "fmt" |
| "math" |
| + "sort" |
| "strconv" |
| "strings" |
| "time" |
| @@ -312,6 +313,11 @@ func refererLabel(k string) (string, string, bool) { |
| return k, "", false |
| } |
| +// botLabel mutes the bots no list names: they are the ones to look into. |
| +func botLabel(k string) (string, string, bool) { |
| + return k, "", k == analytics.BotOther || k == analytics.BotNoUserAgent |
| +} |
| + |
| // countryLabel is a Countries row: the country's name and its flag, the |
| // two reserved buckets in words. |
| func countryLabel(k string) (string, string, bool) { |
| @@ -466,3 +472,162 @@ func restartNote(days []analytics.DaySummary, now time.Time) string { |
| return fmt.Sprintf("The edge restarted on %d of these days. Counts it had not saved yet may be missing for each of them. Those days are marked under the chart.", n) |
| } |
| } |
| + |
| +// topRows is how many rows the tab's Top pages and Referrers show; the |
| +// pages view shows every page. |
| +const topRows = 25 |
| + |
| +// capRows keeps the first n rows that are pages, referrers or countries, |
| +// and counts the rest (the overflow row included). The overflow row is the |
| +// last row sortedKV gives, so a cut list never shows "Everything else" for |
| +// a remainder it is not. |
| +func capRows(rows []shareRow, n int) ([]shareRow, int) { |
| + if len(rows) <= n { |
| + return rows, 0 |
| + } |
| + return rows[:n], len(rows) - n |
| +} |
| + |
| +// pageSection is one group of the pages view: the pages under one top |
| +// folder, "/" for the pages at the top level. |
| +type pageSection struct { |
| + Name string // "/blog/", or "/" for the top level |
| + Label string // what the heading says |
| + Views int64 |
| + Share string |
| + Bar float64 |
| + Pages []pageRow |
| + Count int64 // len(Pages), for the heading |
| + Open bool // shown open: small groups, and the biggest |
| +} |
| + |
| +// pageRow is one page of a section, with its views on each day of the |
| +// window as Spark, the points of a small line ("" for a one-day view). |
| +type pageRow struct { |
| + Path string |
| + Label string |
| + Views int64 |
| + Share string |
| + Spark string |
| + Muted bool |
| +} |
| + |
| +// sectionOf is the group a page belongs to: its first folder ("/blog/", |
| +// "/blog/post/" and "/blog/post.html" are all in "/blog/"), else the top |
| +// level ("/", "/ai.html"). buildPageSections folds a folder that holds only |
| +// its own index ("/faq/" alone) back into the top level. The overflow row |
| +// is a group of its own, last. |
| +func sectionOf(p string) string { |
| + if p == analytics.OtherKey { |
| + return analytics.OtherKey |
| + } |
| + rest := strings.TrimPrefix(p, "/") |
| + i := strings.IndexByte(rest, '/') |
| + if i < 0 { |
| + return "/" |
| + } |
| + return "/" + rest[:i+1] |
| +} |
| + |
| +// buildPageSections groups every page of the window by sectionOf, biggest |
| +// group first, pages biggest first within a group. daily draws each page's |
| +// line from its days (a multi-day window); a one-day view has none. |
| +func buildPageSections(sum analytics.Summary, daily bool) []pageSection { |
| + var total int64 |
| + for _, v := range sum.Pages { |
| + total += v |
| + } |
| + if total == 0 { |
| + return nil |
| + } |
| + bySection := map[string]*pageSection{} |
| + var order []string |
| + for _, kv := range sortedKV(sum.Pages) { |
| + name := sectionOf(kv.Key) |
| + sec, ok := bySection[name] |
| + if !ok { |
| + sec = &pageSection{Name: name, Label: name} |
| + switch name { |
| + case "/": |
| + sec.Label = "Top level" |
| + case analytics.OtherKey: |
| + sec.Label = "Everything else" |
| + } |
| + bySection[name] = sec |
| + order = append(order, name) |
| + } |
| + label, _, muted := pageLabel(kv.Key) |
| + row := pageRow{Path: kv.Key, Label: label, Views: kv.Value, Share: sharePct(kv.Value, total), Muted: muted} |
| + if daily && kv.Key != analytics.OtherKey { |
| + row.Spark = pageSpark(kv.Key, sum.Days) |
| + } |
| + sec.Pages = append(sec.Pages, row) |
| + sec.Views += kv.Value |
| + } |
| + out := make([]pageSection, 0, len(order)) |
| + var top *pageSection |
| + for _, name := range order { |
| + sec := bySection[name] |
| + if name != "/" && name != analytics.OtherKey && len(sec.Pages) == 1 && sec.Pages[0].Path == name { |
| + // A folder of one, its own index: a top-level page. |
| + if top = bySection["/"]; top == nil { |
| + top = &pageSection{Name: "/", Label: "Top level"} |
| + bySection["/"] = top |
| + order = append(order, "/") |
| + } |
| + top.Pages = append(top.Pages, sec.Pages[0]) |
| + top.Views += sec.Views |
| + delete(bySection, name) |
| + } |
| + } |
| + for _, name := range order { |
| + if sec, ok := bySection[name]; ok { |
| + sort.SliceStable(sec.Pages, func(i, j int) bool { return sec.Pages[i].Views > sec.Pages[j].Views }) |
| + out = append(out, *sec) |
| + } |
| + } |
| + sort.SliceStable(out, func(i, j int) bool { |
| + if a, b := out[i].Name == analytics.OtherKey, out[j].Name == analytics.OtherKey; a != b { |
| + return b |
| + } |
| + return out[i].Views > out[j].Views |
| + }) |
| + most := out[0].Views |
| + for i := range out { |
| + out[i].Count = int64(len(out[i].Pages)) |
| + out[i].Share = sharePct(out[i].Views, total) |
| + out[i].Bar = round2(float64(out[i].Views) / float64(most) * 100) |
| + out[i].Open = i == 0 || len(out[i].Pages) <= 10 |
| + } |
| + return out |
| +} |
| + |
| +// pageSpark is a page's views on each day of days as polyline points on a |
| +// 60 x 16 box, scaled to its own busiest day. A page seen on one day only |
| +// still draws a line, flat but for that day. |
| +func pageSpark(p string, days []analytics.DaySummary) string { |
| + if len(days) < 2 { |
| + return "" |
| + } |
| + var peak int64 |
| + for _, d := range days { |
| + if v := d.Pages[p]; v > peak { |
| + peak = v |
| + } |
| + } |
| + if peak == 0 { |
| + return "" |
| + } |
| + var b strings.Builder |
| + step := 60.0 / float64(len(days)-1) |
| + for i, d := range days { |
| + if i > 0 { |
| + b.WriteByte(' ') |
| + } |
| + y := 15 - float64(d.Pages[p])/float64(peak)*14 |
| + b.WriteString(strconv.FormatFloat(round2(float64(i)*step), 'f', -1, 64)) |
| + b.WriteByte(',') |
| + b.WriteString(strconv.FormatFloat(round2(y), 'f', -1, 64)) |
| + } |
| + return b.String() |
| +} |
diff --git a/internal/console/analyticslive.go b/internal/console/analyticslive.go| index 96bbdd1e7..3bcc12d4f 100644 |
| --- a/internal/console/analyticslive.go |
| +++ b/internal/console/analyticslive.go |
| @@ -36,13 +36,26 @@ const analyticsDays = 30 |
| type analyticsQuery struct { |
| Range string // today | 7d | 30d | day |
| Date string // YYYY-MM-DD when Range is day |
| + Show string // "pages" for every page in the period; "" for the tab |
| } |
| +// showPages is the Show of the pages view. |
| +const showPages = "pages" |
| + |
| // parseAnalyticsQuery reads ?date and ?range. A date in the last 30 UTC days |
| // is that day; today's date is the today range; anything else falls back to |
| // the range, and an unknown range to today. A page never 400s over its own |
| // query string. |
| func parseAnalyticsQuery(q url.Values, now time.Time) analyticsQuery { |
| + out := parsePeriod(q, now) |
| + if q.Get("show") == showPages { |
| + out.Show = showPages |
| + } |
| + return out |
| +} |
| + |
| +// parsePeriod is the period half of parseAnalyticsQuery. |
| +func parsePeriod(q url.Values, now time.Time) analyticsQuery { |
| if d := q.Get("date"); d != "" { |
| if t, err := time.Parse("2006-01-02", d); err == nil && t.Format("2006-01-02") == d { |
| today := now.UTC().Truncate(24 * time.Hour) |
| @@ -62,10 +75,26 @@ func parseAnalyticsQuery(q url.Values, now time.Time) analyticsQuery { |
| // values is the query as URL parameters, for the live door's address. |
| func (q analyticsQuery) values() url.Values { |
| + v := url.Values{"range": {q.Range}} |
| if q.Range == rangeDay { |
| - return url.Values{"date": {q.Date}} |
| + v = url.Values{"date": {q.Date}} |
| + } |
| + if q.Show != "" { |
| + v.Set("show", q.Show) |
| } |
| - return url.Values{"range": {q.Range}} |
| + return v |
| +} |
| + |
| +// PagesLink and TabLink are the query strings of this period's pages view |
| +// and of its tab, for the "See all" and "Back" links. |
| +func (q analyticsQuery) PagesLink() string { |
| + q.Show = showPages |
| + return "?" + q.values().Encode() |
| +} |
| + |
| +func (q analyticsQuery) TabLink() string { |
| + q.Show = "" |
| + return "?" + q.values().Encode() |
| } |
| // dayNeighbours are the days either side of date that can be opened: "" |
diff --git a/internal/console/analyticspages_test.go b/internal/console/analyticspages_test.go| new file mode 100644 |
| index 000000000..f3b943f51 |
| --- /dev/null |
| +++ b/internal/console/analyticspages_test.go |
| @@ -0,0 +1,157 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| +) |
| + |
| +func TestSectionOf(t *testing.T) { |
| + for p, want := range map[string]string{ |
| + "/": "/", |
| + "/ai.html": "/", |
| + "/faq/": "/faq/", |
| + "/blog/": "/blog/", |
| + "/blog/deshittification/": "/blog/", |
| + "/posts/27.html": "/posts/", |
| + analytics.OtherKey: analytics.OtherKey, |
| + } { |
| + if got := sectionOf(p); got != want { |
| + t.Errorf("sectionOf(%q) = %q, want %q", p, got, want) |
| + } |
| + } |
| +} |
| + |
| +// Pages group by top folder, biggest first; a folder holding only its own |
| +// index joins the top level; each page of a multi-day window has a line. |
| +func TestBuildPageSections(t *testing.T) { |
| + pages := map[string]int64{"/": 20, "/faq/": 2, "/ai.html": 1, "/blog/": 1, "/blog/a/": 12, "/blog/b/": 4} |
| + for i := 1; i <= 30; i++ { |
| + pages[fmt.Sprintf("/posts/%d.html", i)] = 1 |
| + } |
| + days := []analytics.DaySummary{{Date: "2026-10-28", Pages: map[string]int64{"/blog/a/": 2}}, {Date: "2026-10-29", Pages: map[string]int64{"/blog/a/": 10}}} |
| + secs := buildPageSections(analytics.Summary{Pages: pages, Days: days}, true) |
| + if len(secs) != 3 || secs[0].Name != "/posts/" || secs[1].Name != "/" || secs[2].Name != "/blog/" { |
| + t.Fatalf("sections = %v", sectionNames(secs)) |
| + } |
| + // The biggest group is open even with more than 10 pages; others that |
| + // size start closed. |
| + if secs[0].Count != 30 || secs[0].Views != 30 || !secs[0].Open { |
| + t.Errorf("/posts/ = %d pages %d views open %v, want 30, 30, open", secs[0].Count, secs[0].Views, secs[0].Open) |
| + } |
| + top := secs[1] |
| + if top.Label != "Top level" || top.Count != 3 || top.Pages[0].Path != "/" { |
| + t.Errorf("top level = %+v", top) |
| + } |
| + blog := secs[2] |
| + if blog.Count != 3 || blog.Pages[0].Path != "/blog/a/" || blog.Pages[0].Spark != "0,12.2 60,1" { |
| + t.Errorf("/blog/ = %+v", blog) |
| + } |
| + if one := buildPageSections(analytics.Summary{Pages: pages, Days: days[:1]}, false); one[2].Pages[0].Spark != "" { |
| + t.Error("a one-day view drew a line") |
| + } |
| +} |
| + |
| +// The overflow row is unattributed views, not a page: it stays its own |
| +// group, last, however small, and never joins the top level. |
| +func TestBuildPageSectionsKeepsOverflowLast(t *testing.T) { |
| + secs := buildPageSections(analytics.Summary{Pages: map[string]int64{"/blog/a": 1, analytics.OtherKey: 100}}, false) |
| + if len(secs) != 2 || secs[0].Name != "/blog/" || secs[1].Name != analytics.OtherKey || secs[1].Label != "Everything else" { |
| + t.Fatalf("sections = %v", sectionNames(secs)) |
| + } |
| +} |
| + |
| +func sectionNames(secs []pageSection) []string { |
| + var out []string |
| + for _, s := range secs { |
| + out = append(out, s.Name) |
| + } |
| + return out |
| +} |
| + |
| +// The tab shows 25 pages and a link to all of them; the pages view lists |
| +// every page by group, with a filter, and its period links keep the view. |
| +// Named events are gone from the tab. |
| +func TestAnalyticsPagesView(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-analytics-pages") |
| + when := seedTime() |
| + m := analytics.NewMeter(t.TempDir(), "box1", func() time.Time { return when }) |
| + for i := 0; i < 30; i++ { |
| + m.Observe(analytics.Obs{Acct: release.OpsAccount, App: "titogo", Host: "titogo.example.com", Method: "GET", Status: 200, |
| + ContentType: "text/html", Path: fmt.Sprintf("/posts/%d.html", i), UA: "Mozilla/5.0 Safari", ClientIP: fmt.Sprintf("203.0.113.%d", i), When: when}) |
| + } |
| + for k, ds := range m.Drain() { |
| + for _, d := range ds { |
| + if err := analytics.UpsertDay(context.Background(), fx.rel, k.Acct, k.App, d); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + if err := telemetry.Update(context.Background(), fx.rel, telemetry.AppKey(fx.sqid, "titogo"), func(st *telemetry.Settings) { |
| + st.Analytics = &telemetry.Analytics{Count: telemetry.CountEdge} |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-analytics-pages-browser") |
| + |
| + _, _, body := get(t, c, fx.u("/apps/titogo/analytics?range=7d")) |
| + if n := strings.Count(body, `<span class="an-key" title="/posts/`); n != topRows { |
| + t.Errorf("tab shows %d pages, want %d", n, topRows) |
| + } |
| + if !strings.Contains(body, `href="?range=7d&show=pages">See all 30 pages</a>`) { |
| + t.Error("tab has no See all link") |
| + } |
| + if strings.Contains(body, "Named events") { |
| + t.Error("tab still shows Named events") |
| + } |
| + |
| + _, _, body = get(t, c, fx.u("/apps/titogo/analytics?range=7d&show=pages")) |
| + for _, want := range []string{"All pages", `data-section="/posts/"`, "30 pages", `data-filter`, `href="?range=7d">Back to the summary</a>`, |
| + `href="?range=30d&show=pages"`, `data-path="/posts/29.html"`} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("pages view missing %q", want) |
| + } |
| + } |
| + if n := strings.Count(body, `<li data-path="/posts/`); n != 30 { |
| + t.Errorf("pages view lists %d pages, want 30", n) |
| + } |
| + // The live door answers the pages view too. |
| + status, _, live := get(t, c, fx.u("/apps/titogo/analytics/live?view=tab&range=7d&show=pages")) |
| + if status != 200 || !strings.Contains(live, "All pages") { |
| + t.Errorf("live pages view = %d", status) |
| + } |
| +} |
| + |
| +func TestCapRows(t *testing.T) { |
| + rows := make([]shareRow, 30) |
| + got, more := capRows(rows, 25) |
| + if len(got) != 25 || more != 5 { |
| + t.Fatalf("capRows = %d rows, %d more", len(got), more) |
| + } |
| + if got, more := capRows(rows[:3], 25); len(got) != 3 || more != 0 { |
| + t.Fatalf("short list = %d rows, %d more", len(got), more) |
| + } |
| +} |
| + |
| +// Browsers, devices and bots by name show once an edge counts them. |
| +func TestAnalyticsAgentCards(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-analytics-agents") |
| + seedAnalytics(t, fx, seedTime()) // five Safari-ish views and a Googlebot |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-analytics-agents-browser") |
| + _, _, body := get(t, c, fx.u("/apps/titogo/analytics")) |
| + for _, want := range []string{">Browsers</h3>", ">Devices</h3>", "Desktop", ">Bots</h3>", "Googlebot", "They are not counted as page views or visitors."} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("tab missing %q", want) |
| + } |
| + } |
| +} |
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go| index 8a8072f95..51fd60861 100644 |
| --- a/internal/console/analyticsview.go |
| +++ b/internal/console/analyticsview.go |
| @@ -243,7 +243,6 @@ type analyticsWindow struct { |
| Insights []string |
| Pages []shareRow |
| Referers []shareRow |
| - Events []shareRow |
| // Countries is the top 10 plus the rest (geoip spec §9). |
| Countries []shareRow |
| // Restarts is restartNote's sentence, "" when no edge restarted. |
| @@ -251,6 +250,14 @@ type analyticsWindow struct { |
| // Date is the day a day view shows (Range "day"), with the days either |
| // side that can be opened (dayNeighbours). |
| Date, Prev, Next string |
| + // PagesMore and ReferersMore are the rows past the tab's first 25, |
| + // shown in full by the pages view (Sections) or counted. |
| + PagesMore, ReferersMore int |
| + PagesTotal int64 // pages counted, not the overflow row |
| + // Browsers and Devices are page views by browser family and device |
| + // class; Bots is bot requests by name (internal/analytics agents.go). |
| + Browsers, Devices, Bots []shareRow |
| + Sections []pageSection |
| } |
| // HasData reports whether the window holds anything counted. With analytics |
| @@ -463,14 +470,23 @@ func (s *Server) readAnalyticsFor(ctx context.Context, sqid, app string, q analy |
| return out, nil |
| } |
| from, to := analyticsQuerySpan(q, now) |
| - key := sqid + "/" + app + "/" + rng + "/" + q.Date + "/" + now.UTC().Format("2006-01-02") |
| + key := sqid + "/" + app + "/" + rng + "/" + q.Date + "/" + q.Show + "/" + now.UTC().Format("2006-01-02") |
| + read := func() (analytics.Summary, error) { |
| + sum, err := s.readAnalyticsRange(ctx, sqid, app, from, to, now) |
| + // Each day's page counts are for the pages view's trends only: up |
| + // to 500 pages a day is not worth holding for any other view. |
| + if q.Show != showPages { |
| + for i := range sum.Days { |
| + sum.Days[i].Pages = nil |
| + } |
| + } |
| + return sum, err |
| + } |
| var sum analytics.Summary |
| if memo == nil { |
| - sum, err = s.readAnalyticsRange(ctx, sqid, app, from, to, now) |
| + sum, err = read() |
| } else { |
| - sum, err = memo.load(ctx, key, now, func() (analytics.Summary, error) { |
| - return s.readAnalyticsRange(ctx, sqid, app, from, to, now) |
| - }) |
| + sum, err = memo.load(ctx, key, now, read) |
| } |
| if err != nil { |
| return out, err |
| @@ -486,10 +502,20 @@ func (s *Server) readAnalyticsFor(ctx context.Context, sqid, app string, q analy |
| } |
| out.Chart = buildTrafficChart(shape, sum, now) |
| out.Insights = analyticsInsights(shape, sum, now) |
| - out.Pages = shareRows(sum.Pages, pageLabel) |
| - out.Referers = shareRows(sum.Referers, refererLabel) |
| - out.Events = shareRows(sum.Events, pageLabel) |
| + out.Pages, out.PagesMore = capRows(shareRows(sum.Pages, pageLabel), topRows) |
| + out.Referers, out.ReferersMore = capRows(shareRows(sum.Referers, refererLabel), topRows) |
| + for k := range sum.Pages { |
| + if k != analytics.OtherKey { |
| + out.PagesTotal++ |
| + } |
| + } |
| + if q.Show == showPages { |
| + out.Sections = buildPageSections(sum, rng == range7d || rng == range30d) |
| + } |
| out.Countries = shareRows(geoCountries(sum.Countries), countryLabel) |
| + out.Browsers = shareRows(sum.Browsers, nil) |
| + out.Devices = shareRows(sum.Devices, nil) |
| + out.Bots = shareRows(sum.BotNames, botLabel) |
| out.Restarts = restartNote(sum.Days, now) |
| return out, nil |
| } |
diff --git a/internal/console/apianalytics.go b/internal/console/apianalytics.go| index 97823f5e6..dd03f26c9 100644 |
| --- a/internal/console/apianalytics.go |
| +++ b/internal/console/apianalytics.go |
| @@ -36,6 +36,9 @@ type analyticsResponse struct { |
| Events map[string]int64 `json:"events"` |
| Countries map[string]int64 `json:"countries"` |
| GeoSources map[string]int64 `json:"geo_sources"` |
| + BotNames map[string]int64 `json:"bot_names,omitempty"` |
| + Browsers map[string]int64 `json:"browsers,omitempty"` |
| + Devices map[string]int64 `json:"devices,omitempty"` |
| PagesApprox bool `json:"pages_approx"` |
| ReferersApprox bool `json:"referers_approx"` |
| EventsApprox bool `json:"events_approx"` |
| @@ -78,6 +81,7 @@ func (s *Server) handleAPIAnalytics(w http.ResponseWriter, r *http.Request) { |
| PagesApprox: sum.PagesApprox, ReferersApprox: sum.ReferersApprox, EventsApprox: sum.EventsApprox, |
| Dropped: sum.Dropped, |
| Countries: topWithOther(sum.Countries, 10), GeoSources: sum.GeoSources, |
| + BotNames: sum.BotNames, Browsers: sum.Browsers, Devices: sum.Devices, |
| } |
| // "Nothing counted" is an empty object, not null — the same shape |
| // errorsResponse gives its groups, so a caller may index the answer |
diff --git a/internal/console/apianalytics_test.go b/internal/console/apianalytics_test.go| index 6abcf5a42..71aed18ae 100644 |
| --- a/internal/console/apianalytics_test.go |
| +++ b/internal/console/apianalytics_test.go |
| @@ -170,7 +170,7 @@ func TestAppAnalyticsPage(t *testing.T) { |
| t.Fatalf("%d %s", status, body) |
| } |
| // Off: the switch and the reading, and the numbers that exist already. |
| - for _, want := range []string{"Analytics is off for this app", "No JavaScript, no cookie", "/pricing", "news.ycombinator.com", "signup", `class="an-chart an-chart-hour"`} { |
| + for _, want := range []string{"Analytics is off for this app", "No JavaScript, no cookie", "/pricing", "news.ycombinator.com", `class="an-chart an-chart-hour"`} { |
| if !strings.Contains(body, want) { |
| t.Errorf("page missing %q", want) |
| } |
diff --git a/internal/console/templates/app_analytics.html b/internal/console/templates/app_analytics.html| index 161c93e53..6acc6316a 100644 |
| --- a/internal/console/templates/app_analytics.html |
| +++ b/internal/console/templates/app_analytics.html |
| @@ -37,13 +37,14 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav |
| {{/* The numbers part of the tab: what a reload would show, and what the |
| live door (analyticslive.go) answers to the page's minute refresh. */}} |
| {{define "analyticsnav"}}<nav class="an-range" aria-label="Period"> |
| - <a href="?range=today"{{if eq .Query.Range "today"}} aria-current="page"{{end}}>Today</a> |
| - <a href="?range=7d"{{if eq .Query.Range "7d"}} aria-current="page"{{end}}>7 days</a> |
| - <a href="?range=30d"{{if eq .Query.Range "30d"}} aria-current="page"{{end}}>30 days</a> |
| + {{/* The view is kept as literal text: a value spliced into a query |
| + string is escaped as data, which would turn the & into %26. */}}{{$p := eq .Query.Show "pages"}}<a href="?range=today{{if $p}}&show=pages{{end}}"{{if eq .Query.Range "today"}} aria-current="page"{{end}}>Today</a> |
| + <a href="?range=7d{{if $p}}&show=pages{{end}}"{{if eq .Query.Range "7d"}} aria-current="page"{{end}}>7 days</a> |
| + <a href="?range=30d{{if $p}}&show=pages{{end}}"{{if eq .Query.Range "30d"}} aria-current="page"{{end}}>30 days</a> |
| {{with .Win}}{{if .Span}}<span class="an-span">{{.Span}}</span>{{end}} |
| {{if eq .Range "day"}}<span class="an-daynav"> |
| - {{if .Prev}}<a href="?date={{.Prev}}">Previous day</a>{{end}} |
| - {{if eq .Next "today"}}<a href="?range=today">Next day</a>{{else if .Next}}<a href="?date={{.Next}}">Next day</a>{{end}} |
| + {{if .Prev}}<a href="?date={{.Prev}}{{if $p}}&show=pages{{end}}">Previous day</a>{{end}} |
| + {{if eq .Next "today"}}<a href="?range=today{{if $p}}&show=pages{{end}}">Next day</a>{{else if .Next}}<a href="?date={{.Next}}{{if $p}}&show=pages{{end}}">Next day</a>{{end}} |
| </span>{{end}}{{end}} |
| </nav>{{end}} |
| @@ -56,15 +57,18 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav |
| <p class="an-empty">No page views in this period.</p> |
| {{end}} |
| {{template "trafficquality" .}} |
| +{{if eq $.Query.Show "pages"}}{{template "analyticspages" $}}{{else}} |
| <div class="an-breakdowns"> |
| <section class="an-card" aria-labelledby="an-pages"> |
| <h3 id="an-pages">Top pages</h3> |
| {{template "sharelist" .Pages}} |
| + {{if .PagesMore}}<p class="an-more"><a href="{{$.Query.PagesLink}}">See all {{count .PagesTotal}} pages</a></p>{{end}} |
| {{if .Sum.PagesApprox}}<p class="small">Approximate: more than 500 different pages were viewed.</p>{{end}} |
| </section> |
| <section class="an-card" aria-labelledby="an-referers"> |
| <h3 id="an-referers">Referrers</h3> |
| {{template "sharelist" .Referers}} |
| + {{if .ReferersMore}}<p class="small">{{count .ReferersMore}} more referrer{{if ne .ReferersMore 1}}s{{end}} not shown.</p>{{end}} |
| {{if .Sum.ReferersApprox}}<p class="small">Approximate: more than 500 referrers were seen.</p>{{end}} |
| </section> |
| <section class="an-card" aria-labelledby="an-countries"> |
| @@ -72,16 +76,55 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav |
| {{if .Countries}}{{template "sharelist" .Countries}}{{else}}<p class="small">No country data for this period.</p>{{end}} |
| {{range geoAttributions .Sum.GeoSources}}<p class="small"><a href="{{.URL}}">{{.Text}}</a></p>{{end}} |
| </section> |
| - <section class="an-card" aria-labelledby="an-events"> |
| - <h3 id="an-events">Named events</h3> |
| - {{template "sharelist" .Events}} |
| - {{if .Sum.EventsApprox}}<p class="small">Approximate: more than 500 event names were seen.</p>{{end}} |
| + {{/* Browsers, devices and bots come from edges that count them; on an |
| + older edge's days there are none, and the cards stay away. */}} |
| + {{if or .Browsers .Devices}} |
| + <section class="an-card" aria-labelledby="an-browsers"> |
| + <h3 id="an-browsers">Browsers</h3> |
| + {{template "sharelist" .Browsers}} |
| + <h3 class="an-subhead">Devices</h3> |
| + {{template "sharelist" .Devices}} |
| </section> |
| -</div> |
| + {{end}} |
| + {{if .Bots}} |
| + <section class="an-card" aria-labelledby="an-bots"> |
| + <h3 id="an-bots">Bots</h3> |
| + {{template "sharelist" .Bots}} |
| + <p class="small">Requests from bots and crawlers. They are not counted as page views or visitors. An unnamed crawler sent a normal browser user agent but read 20 or more pages within a minute.</p> |
| + </section> |
| + {{end}} |
| +</div>{{end}} |
| {{end}} |
| <p class="small">Updated {{.Updated}}. Times are UTC.{{if ne .Query.Range "day"}} The same view from a terminal: <code>carlos analytics --app {{.AppName}} --range {{.Query.Range}}</code>.{{end}}</p> |
| {{end}} |
| +{{/* Every page of the period, grouped by top folder, each with its share |
| + and, over several days, a line of its days. A filter box narrows the |
| + list in place (analyticsscript). */}} |
| +{{define "analyticspages"}}{{with .Win}} |
| +<section class="an-pages" aria-labelledby="an-allpages"> |
| + <div class="an-pages-head"> |
| + <h3 id="an-allpages">All pages</h3> |
| + <a href="{{$.Query.TabLink}}">Back to the summary</a> |
| + </div> |
| + {{if .Sections}} |
| + <input type="search" class="an-filter" placeholder="Filter pages" aria-label="Filter pages" data-filter> |
| + {{range .Sections}} |
| + <details class="an-section" data-section="{{.Name}}"{{if .Open}} open{{end}}> |
| + <summary><span class="an-key">{{.Label}}</span><span class="an-val">{{count .Views}}</span><span class="an-pct">{{.Share}}</span><span class="an-count">{{count .Count}} page{{if ne .Count 1}}s{{end}}</span></summary> |
| + <ol class="an-share an-pagelist">{{range .Pages}}<li data-path="{{.Path}}"{{if .Muted}} class="an-muted"{{end}}> |
| + <span class="an-key" title="{{.Path}}">{{.Label}}</span> |
| + {{if .Spark}}<svg class="an-spark" viewBox="0 0 60 16" aria-hidden="true"><polyline points="{{.Spark}}"/></svg>{{else}}<span></span>{{end}} |
| + <span class="an-val">{{count .Views}}</span> |
| + <span class="an-pct">{{.Share}}</span> |
| + </li>{{end}}</ol> |
| + </details> |
| + {{end}} |
| + {{if .Sum.PagesApprox}}<p class="small">Approximate: more than 500 different pages were viewed.</p>{{end}} |
| + {{else}}<p class="small">Nothing yet.</p>{{end}} |
| +</section> |
| +{{end}}{{end}} |
| + |
| {{/* The Overview's traffic card body, refreshed the same way. */}} |
| {{define "trafficcard"}} |
| {{if .Slow}} |
| @@ -179,7 +222,29 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav |
| }); |
| }); |
| } |
| + // The pages view's filter: rows whose path does not contain the text are |
| + // hidden, groups with none left are hidden, groups with a match open. |
| + function initFilter(root) { |
| + var f = root.querySelector("[data-filter]"); |
| + if (!f) return; |
| + function apply() { |
| + var q = f.value.trim().toLowerCase(); |
| + root.querySelectorAll(".an-section").forEach(function (sec) { |
| + var shown = 0; |
| + sec.querySelectorAll("li[data-path]").forEach(function (li) { |
| + var hit = !q || li.getAttribute("data-path").toLowerCase().indexOf(q) >= 0; |
| + li.hidden = !hit; |
| + if (hit) shown++; |
| + }); |
| + sec.hidden = shown === 0; |
| + if (q && shown) sec.open = true; |
| + }); |
| + } |
| + f.addEventListener("input", apply); |
| + apply(); |
| + } |
| initCharts(document); |
| + initFilter(document); |
| if (window.anLive || !window.fetch) return; |
| window.anLive = true; |
| var lastInput = Date.now(), lastRun = Date.now(); |
| @@ -197,8 +262,19 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav |
| .then(function (r) { return r.ok && r.headers.get("X-Carlos-Live") === "1" ? r.text() : null; }) |
| .then(function (html) { |
| if (html === null || busy(el)) return; |
| + // Keep what the reader set: the filter text and which groups are open. |
| + var f = el.querySelector("[data-filter]"), q = f ? f.value : ""; |
| + var open = {}; |
| + el.querySelectorAll(".an-section").forEach(function (s) { open[s.getAttribute("data-section")] = s.open; }); |
| el.innerHTML = html; |
| + el.querySelectorAll(".an-section").forEach(function (s) { |
| + var k = s.getAttribute("data-section"); |
| + if (k in open) s.open = open[k]; |
| + }); |
| + var nf = el.querySelector("[data-filter]"); |
| + if (nf) nf.value = q; |
| initCharts(el); |
| + initFilter(el); |
| }) |
| .catch(function () {}); |
| }); |
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html| index db74d4435..29279a610 100644 |
| --- a/internal/console/templates/layout.html |
| +++ b/internal/console/templates/layout.html |
| @@ -799,6 +799,22 @@ |
| .an-muted .an-key { color: var(--muted); } |
| .an-muted .an-track span { background: var(--muted); opacity: 0.5; } |
| + .an-more { margin: 0.6rem 0 0; font-size: 0.9rem; } |
| + .an-card h3.an-subhead { margin-top: 1.4rem; } |
| + .an-pages { margin: 0 0 2rem; } |
| + .an-pages-head { display: flex; justify-content: space-between; align-items: baseline; gap: 1rem; margin: 0 0 0.8rem; } |
| + .an-pages-head h3 { font-size: 1rem; margin: 0; } |
| + input.an-filter { width: 100%; max-width: 24rem; margin: 0 0 1rem; } |
| + .an-section { border-bottom: 1px solid var(--rule); } |
| + .an-section summary { |
| + display: grid; grid-template-columns: minmax(0, 1fr) auto 3rem 5.5rem; column-gap: 0.75rem; |
| + align-items: baseline; padding: 0.55rem 0; cursor: pointer; font-weight: 600; |
| + } |
| + .an-section summary .an-count { color: var(--muted); font-size: 0.85rem; font-weight: 400; text-align: right; } |
| + .an-pagelist { margin: 0 0 0.75rem 1rem; } |
| + .an-pagelist li { grid-template-columns: minmax(0, 1fr) 60px auto 3rem; } |
| + .an-spark { width: 60px; height: 16px; align-self: center; } |
| + .an-spark polyline { fill: none; stroke: var(--accent); stroke-width: 1.5; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; } |
| .an-overview { margin: 0 0 2rem; padding: 1.25rem 1.4rem 1.4rem; border: 1px solid var(--rule); border-radius: 0.6rem; } |
| .an-overview-head { display: flex; justify-content: space-between; align-items: baseline; gap: 1rem; margin: 0 0 1rem; } |
| .an-overview-head h2 { font-size: 1rem; margin: 0; } |
diff --git a/internal/provision/testdata/plan14-root-reads-analytics-agents.tsv b/internal/provision/testdata/plan14-root-reads-analytics-agents.tsv| new file mode 100644 |
| index 000000000..a0526344f |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-analytics-agents.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay analytics-agents, written by census-propose (#369). census-ruling-analytics-agents, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-analytics-agents.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/analytics e246685497e4db7d774b9397fb22a62ebcde876854b3c8eb891187661fc73e27 |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index ef4e6d799..a0dbd1f36 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -38,3 +38,4 @@ plan14-root-reads-rootfs-check-volumes.tsv 042684bf5af6f61ce8b87f10b68a42b08d131 |
| plan14-root-reads-rootfs-fleet-followups.tsv 78b7e7e30ad3ada44388a4ee16f3950ef888ae03e552477dcbfbb07c51ffb83e |
| plan14-root-reads-rootfs-worker-exit.tsv 7ebc3871ee3c93ff168bfa62d23d6be5a970786c67a9b8aa813e8cc4e39b3d74 |
| plan14-root-reads-region-ha-p1b2.tsv 5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64 |
| +plan14-root-reads-analytics-agents.tsv 5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64 |