carlos / platform Public

Merge remote-tracking branch 'origin/main' into region-ha-dead-holder-backoff

# Conflicts:
#	internal/provision/testdata/plan14-root-reads-chain.tsv
claude agent, operated by paul@keymail.dev 68c172fc16d3f62695b7ec5abd29b79eac0a6224 parent c88f58aparent 16a55c9
41 files changed, +2,480 −129
  • docs/superpowers/notes/census-proposal-analytics-agents.md +11 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-analytics-agents-R1.md +24 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md +29 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-agents.md +38 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-live.md +39 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-usage.md +29 −0
  • internal/analytics/agents.go +91 −0
  • internal/analytics/agents_test.go +200 −0
  • internal/analytics/bots.go +8 −0
  • internal/analytics/day.go +19 −0
  • internal/analytics/meter.go +32 −8
  • internal/analytics/pace.go +83 −0
  • internal/analytics/read.go +15 −0
  • internal/console/analyticsdisplay.go +170 −3
  • internal/console/analyticsdisplay_test.go +11 −3
  • internal/console/analyticslive.go +218 −0
  • internal/console/analyticslive_test.go +258 −0
  • internal/console/analyticspages_test.go +157 −0
  • internal/console/analyticsview.go +134 −32
  • internal/console/apianalytics.go +4 −0
  • internal/console/apianalytics_test.go +1 −1
  • internal/console/billingpage.go +29 −9
  • internal/console/billingpage_copy.go +14 −0
  • internal/console/billingpage_test.go +8 −1
  • internal/console/billingsync_test.go +8 −1
  • internal/console/billingusage.go +197 −0
  • internal/console/billingusage_test.go +338 −0
  • internal/console/claim_invariant_fixtures_test.go +1 −0
  • internal/console/claim_invariant_probes_read_test.go +1 −0
  • internal/console/perfwalk_test.go +6 −0
  • internal/console/server.go +7 −1
  • internal/console/templates/app_analytics.html +184 −43
  • internal/console/templates/app_overview.html +2 −13
  • internal/console/templates/billing.html +21 −7
  • internal/console/templates/layout.html +55 −6
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/console/testdata/perf-budgets.txt +1 −0
  • internal/provision/analytics_live_census_test.go +31 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-analytics-agents.tsv +3 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0

CI cancelled — superseded by a newer push — run details

Intent

Attributed to this commit: 21.4 g CO₂e (2,521,205 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-dead-holder-backoff, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

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-FINDINGS-analytics-live-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md
new file mode 100644
index 000000000..2352fe8bc
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md
@@ -0,0 +1,29 @@
+Reviewed `origin/main...fa2f549501` using the brief at `f924d7f9`. No tracked files changed. No P1 findings.
+
+1. **P2 — Shared-read budget is not enforced.**
+ Evidence: `internal/console/analyticsview.go:419–425` checks the memo, reads storage, then populates it without coordinating concurrent misses. Two tabs refreshing an expired key together both perform the LIST and day-file reads, contradicting “one read a minute per app and view.”
+ **Fix:** coalesce concurrent loads by memo key and add a concurrent-miss witness.
+ **Fault family:** storage request budget.
+
+2. **P2 — Returning to a visible tab can trigger requests one second apart.**
+ Evidence: `internal/console/templates/app_analytics.html:187–204`. The visibility handler calls `refresh()`, but the fixed interval does not check `lastRun`. A Node harness executing this script produced requests at 119,000 ms and 120,000 ms.
+ **Fix:** enforce the minimum interval inside `refresh()`, or reschedule one timeout after each attempt.
+ **Fault family:** browser request budget.
+
+3. **P2 — Dates and day navigation become stale across midnight.**
+ Evidence: `internal/console/templates/app_analytics.html:29–40` puts the span and day navigation outside the refreshed element; line 196 replaces only its contents. An active Today page crosses midnight and displays the new day’s counts beneath yesterday’s date. A past-day page can retain “Next day → today” after that link should name yesterday.
+ **Fix:** refresh the period label and day navigation alongside the numbers.
+ **Fault family:** displayed timeframe must match the data.
+
+4. **P2 — Past-day restart warnings incorrectly say “today.”**
+ Evidence: the new day view calls `restartNote(sum.Days)` at `internal/console/analyticsview.go:442`; `internal/console/analyticsdisplay.go:459–460` describes every single-day restart as happening today. Opening a historical day with `Restarted=true` therefore gives the wrong date.
+ **Fix:** name the actual day, or pass the current date and reserve “today” for a matching date.
+ **Fault family:** historical-day accuracy.
+
+The account gate restricts reads to a member’s account and claimed app. Rendered visitor strings use escaped templates; I found no injection or open redirect.
+
+Request cost is two settings GETs per live request. A memo miss adds a box listing, requested unsettled day files, and settled files absent from the cache. Hidden and idle pages skip new fetches, although an existing fetch can finish. The concurrency and timing findings above prevent the stronger stated budget.
+
+Targeted query, neighbour, chart, insight, timing, and memo tests passed. HTTP tests were blocked by the sandbox refusing loopback sockets; their behavior remains unverified.
+
+**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/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-live.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-live.md
new file mode 100644
index 000000000..eaac81923
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-live.md
@@ -0,0 +1,39 @@
+# Review brief: branch analytics-live, round 1 of 3
+
+Repo carlos/platform, branch `analytics-live`, commit fa2f549501 (`git rev-parse fa2f549501` for the full sha).
+Under review: the diff `origin/main...fa2f549501` (internal/console only).
+Authorities: the console Analytics tab as merged (internal/console/analyticsview.go, analyticsdisplay.go, templates/app_analytics.html, app_overview.html), AGENTS.md (stopping rules; S3 request-cost rule: no new polling per box, state a request budget).
+
+You are an independent reviewer. Read the diff, then the code it calls, and check every claim in comments and the commit message against that code.
+
+## Fixed: do not re-argue
+
+- Paul's asks (2026-10-29): the dashboard updates itself; a bar on the Overview opens that timeframe on the Analytics tab; one tooltip at a time. The refresh is a browser poll once a minute by design (the edge writes counts every five minutes).
+
+## What to check
+
+1. The new door GET /a/{sqid}/apps/{app}/analytics/live (analyticslive.go, handleAnalyticsLive): tenant boundary (only the signed-in member's own account's app), what a signed-out or other-account request gets, caching headers, anything a crafted query (view, range, date) can make it read or render. Links it renders use r.PathValue("sqid"): any injection or open-redirect risk?
+2. The traffic memo now serves the live door for every view and the day view: key correctness (range, date, UTC day), staleness, memory bound, and whether a memo hit can show one app's or one account's numbers to another.
+3. parseAnalyticsQuery and the day view: date bounds (last 30 UTC days, today becomes the today range), the day span (whole UTC day), the memo key, dayNeighbours at the window edges, the hourly chart and insights for a past day.
+4. The page script (templates/app_analytics.html, "analyticsscript"): included on both pages, keyboard navigation re-initialised after a swap, refresh pausing (hidden, 30 min idle, pointer or focus inside), the X-Carlos-Live check with redirect "manual", what happens on errors, duplicate timers when both the card and the tab script are on one page. innerHTML of a same-origin answer: any way visitor-controlled strings (paths, referrers, event names, countries) reach it unescaped?
+5. Request budget: per open, visible, active tab one live request a minute; state what each costs (settings reads, LIST, day files) and whether anything polls with the page hidden or idle.
+6. CSS one-tooltip rule and link columns (a.an-col): keyboard focus, touch (a tap on a link column navigates), and that hourly charts keep buttons.
+7. Tests: sound witnesses (analyticslive_test.go); anything in the diff that would fail CI (darwin, windows) or break an existing test.
+
+## 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). 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/console/ -run ...` is fine.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-usage.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-usage.md
new file mode 100644
index 000000000..80f6aa5b8
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-billing-usage.md
@@ -0,0 +1,29 @@
+# Review brief: branch billing-usage, round 1 of 3
+
+Repo carlos/platform, branch `billing-usage`, the commit that adds this brief (named in your prompt).
+Under review: the diff `origin/main...HEAD`: the console billing page shows the account's current usage beside the pack rows and plan cards, read from the plan-limits pass's stored measurements (`plan_cap_state`), with a "Usage as of" line. Copy approved by Paul on 2026-10-30.
+
+## Fixed: do not re-argue
+
+- The design and the approved copy.
+- Rule: no new S3, provider or bucket request on a page view (Paul's S3-cost rule).
+
+## What to check
+
+1. No new external request on a page view; the only addition is console-database reads. A failing or missing measurement never shows as zero; a stale period (email per UTC day, bandwidth and awake hours per UTC month) shows as unknown.
+2. Used vs limit is compared against the right limit: the account's effective limit today (packs and team seats included) for pack rows, each plan's own limit on plan cards; near (>= 80%) and over thresholds are right, including limit zero/unlimited.
+3. Members see usage read-only with no forms; nothing leaks another account's rows (the account id comes from the authorised page's account).
+4. Existing invariants: currency/prices guard, action order, CSRF on POST forms, success-screen behaviour, billing lints.
+5. Contrast of the near/over emphasis in both themes; 390 px layout.
+
+## 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.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
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 311ace7ff..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"
@@ -38,6 +39,8 @@ func (c *trafficChart) N() int { return len(c.Cols) }
// plot, scaled to the axis top (the rounded-up peak), not to the peak
// itself, so the gridlines mean what their labels say.
type chartCol struct {
+ Date string // the column's UTC day, on a daily chart
+ Href string // where clicking the column goes (linkChartDays), "" for none
When string // "14:00 to 15:00 UTC" or "Tue 27 Oct": the tooltip's first line
Lines []string // the tooltip's readings, value first
Label string // the whole tooltip as one sentence, for aria-label
@@ -94,7 +97,7 @@ func buildTrafficChart(rng string, sum analytics.Summary, now time.Time) *traffi
c.Unit = "day"
today := now.Format("2006-01-02")
for _, d := range sum.Days {
- col := chartCol{Value: d.PV, Partial: d.Date == today, Gap: d.Restarted}
+ col := chartCol{Date: d.Date, Value: d.PV, Partial: d.Date == today, Gap: d.Restarted}
col.When = longDay(d.Date)
pv := plural(d.PV, "page view", "page views")
if col.Partial {
@@ -310,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) {
@@ -444,7 +452,7 @@ func analyticsSpanText(rng string, now time.Time) string {
// had not yet saved were lost, so those days may read low. No bound is
// given: a flush runs every five minutes, but a failed flush is held for
// the next one, so a restart can lose more than one window. Up to three days are named; more are counted.
-func restartNote(days []analytics.DaySummary) string {
+func restartNote(days []analytics.DaySummary, now time.Time) string {
var hit []string
for _, d := range days {
if d.Restarted {
@@ -454,7 +462,7 @@ func restartNote(days []analytics.DaySummary) string {
switch n := len(hit); {
case n == 0:
return ""
- case n == 1 && len(days) == 1:
+ case n == 1 && len(days) == 1 && days[0].Date == now.UTC().Format("2006-01-02"):
return "The edge restarted today. Counts it had not saved yet may be missing."
case n == 1:
return "The edge restarted on " + hit[0] + ". Counts it had not saved yet may be missing for that day."
@@ -464,3 +472,162 @@ func restartNote(days []analytics.DaySummary) 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/analyticsdisplay_test.go b/internal/console/analyticsdisplay_test.go
index 957e40d95..d4393a34d 100644
--- a/internal/console/analyticsdisplay_test.go
+++ b/internal/console/analyticsdisplay_test.go
@@ -149,19 +149,27 @@ func TestAnalyticsInsights(t *testing.T) {
func TestRestartNote(t *testing.T) {
day := func(date string, r bool) analytics.DaySummary { return analytics.DaySummary{Date: date, Restarted: r} }
- if got := restartNote([]analytics.DaySummary{day("2026-10-27", false)}); got != "" {
+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC)
+ if got := restartNote([]analytics.DaySummary{day("2026-10-27", false)}, now); got != "" {
t.Errorf("no restarts = %q", got)
}
- if got := restartNote([]analytics.DaySummary{day("2026-10-26", true), day("2026-10-27", true)}); !strings.Contains(got, "Mon 26 Oct and Tue 27 Oct") {
+ if got := restartNote([]analytics.DaySummary{day("2026-10-26", true), day("2026-10-27", true)}, now); !strings.Contains(got, "Mon 26 Oct and Tue 27 Oct") {
t.Errorf("two restarts = %q", got)
}
var many []analytics.DaySummary
for i := 1; i <= 5; i++ {
many = append(many, day("2026-10-0"+string(rune('0'+i)), true))
}
- if got := restartNote(many); !strings.Contains(got, "on 5 of these days") {
+ if got := restartNote(many, now); !strings.Contains(got, "on 5 of these days") {
t.Errorf("five restarts = %q", got)
}
+ // One day: "today" only when it is today; a past day is named.
+ if got := restartNote([]analytics.DaySummary{day("2026-10-29", true)}, now); !strings.Contains(got, "restarted today") {
+ t.Errorf("today's restart = %q", got)
+ }
+ if got := restartNote([]analytics.DaySummary{day("2026-10-27", true)}, now); strings.Contains(got, "today") || !strings.Contains(got, "Tue 27 Oct") {
+ t.Errorf("a past day's restart = %q, want it named", got)
+ }
}
func TestShareRows(t *testing.T) {
diff --git a/internal/console/analyticslive.go b/internal/console/analyticslive.go
new file mode 100644
index 000000000..3bcc12d4f
--- /dev/null
+++ b/internal/console/analyticslive.go
@@ -0,0 +1,218 @@
+package console
+
+// The Analytics tab and the Overview's traffic card keep themselves current,
+// and a day on either chart opens that day on the tab (Paul, 2026-10-29).
+//
+// A view is a query: one of the three ranges, or one UTC day in the last 30
+// (?date=YYYY-MM-DD), which draws that day's hours. The part of each page
+// that holds numbers is rendered from an analyticsLive, by the page and by
+// the live door alike, so a refresh swaps in exactly what a reload would
+// show. The page's script asks the door once a minute while the page is
+// visible and someone has used it in the last 30 minutes; the door answers
+// through the traffic memo, so every open tab on one app shares one read a
+// minute. Request budget: no timer on the server; per visible, active tab,
+// one live request a minute, which costs the two setting reads and, at most
+// once a minute per app and view, the window's read (a LIST and today's and
+// yesterday's day file per box; settled days come from the usage cache).
+
+import (
+ "context"
+ "log"
+ "net/http"
+ "net/url"
+ "time"
+
+ "github.com/carlosframework/platform/internal/telemetry"
+)
+
+// rangeDay is the query's range when it names one day.
+const rangeDay = "day"
+
+// analyticsDays is how far back a day can be opened: the 30-day range's
+// first day, which is also as far back as the usage cache keeps days.
+const analyticsDays = 30
+
+// analyticsQuery is what one view asks for.
+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)
+ switch {
+ case t.Equal(today):
+ return analyticsQuery{Range: rangeToday}
+ case t.Before(today) && !t.Before(today.AddDate(0, 0, -(analyticsDays-1))):
+ return analyticsQuery{Range: rangeDay, Date: d}
+ }
+ }
+ }
+ if r := q.Get("range"); validRange(r) {
+ return analyticsQuery{Range: r}
+ }
+ return analyticsQuery{Range: rangeToday}
+}
+
+// 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 {
+ v = url.Values{"date": {q.Date}}
+ }
+ if q.Show != "" {
+ v.Set("show", q.Show)
+ }
+ 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: ""
+// where the window ends, and "today" for the day after yesterday.
+func dayNeighbours(date string, now time.Time) (prev, next string) {
+ t, err := time.Parse("2006-01-02", date)
+ if err != nil {
+ return "", ""
+ }
+ today := now.UTC().Truncate(24 * time.Hour)
+ if p := t.AddDate(0, 0, -1); !p.Before(today.AddDate(0, 0, -(analyticsDays - 1))) {
+ prev = p.Format("2006-01-02")
+ }
+ if n := t.AddDate(0, 0, 1); n.Equal(today) {
+ next = rangeToday
+ } else if n.Before(today) {
+ next = n.Format("2006-01-02")
+ }
+ return prev, next
+}
+
+// linkChartDays makes each column of a daily chart a link to that day on the
+// Analytics tab at base ("/a/<seg>/apps/<app>/analytics"). Today's column
+// opens the today range. An hourly chart has nothing to open.
+func linkChartDays(c *trafficChart, base string, now time.Time) {
+ if c == nil || c.Unit != "day" {
+ return
+ }
+ today := now.UTC().Format("2006-01-02")
+ for i := range c.Cols {
+ col := &c.Cols[i]
+ switch {
+ case col.Date == "":
+ case col.Date == today:
+ col.Href = base + "?range=today"
+ default:
+ col.Href = base + "?date=" + col.Date
+ }
+ }
+}
+
+// analyticsLive is the refreshable part of the Analytics tab (Card false)
+// or of the Overview's traffic card (Card true).
+type analyticsLive struct {
+ Win *analyticsWindow // nil: the read failed
+ Slow bool // the Overview gave up waiting for the read
+ Card bool
+ AppName string
+ Nav string // "/a/<segment>", what links use
+ Query analyticsQuery
+ Src string // the live door for this view
+ Updated string // "10:42 UTC", when these numbers were read
+}
+
+// newAnalyticsLive assembles one view's live part from a read.
+func newAnalyticsLive(win *analyticsWindow, card bool, app, nav string, q analyticsQuery, now time.Time) *analyticsLive {
+ base := nav + "/apps/" + url.PathEscape(app) + "/analytics"
+ v := q.values()
+ view := "tab"
+ if card {
+ view = "card"
+ }
+ v.Set("view", view)
+ l := &analyticsLive{Win: win, Card: card, AppName: app, Nav: nav, Query: q,
+ Src: base + "/live?" + v.Encode(), Updated: now.UTC().Format("15:04") + " UTC"}
+ if win != nil {
+ linkChartDays(win.Chart, base, now)
+ }
+ return l
+}
+
+// handleAnalyticsLive is the live door: the numbers part of the Analytics tab
+// (?view=tab with the tab's own query) or of the Overview card (?view=card),
+// for a signed-in member of the app's account, through the traffic memo. A
+// failed read answers 503 and the page keeps what it shows.
+func (s *Server) handleAnalyticsLive(w http.ResponseWriter, r *http.Request) {
+ _, _, acct, _, app, ok := s.accountApp(w, r)
+ if !ok {
+ return
+ }
+ now := time.Now()
+ card := r.URL.Query().Get("view") == "card"
+ q := parseAnalyticsQuery(r.URL.Query(), now)
+ if card {
+ q = analyticsQuery{Range: range7d}
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ win, err := s.readAnalyticsFor(ctx, acct.Sqid, app, q, now, &s.trafficMemo)
+ if err != nil {
+ log.Printf("console: analytics live %s/%s: %v", acct.Sqid, app, err)
+ http.Error(w, "analytics unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ // Links keep the account segment the page itself was opened under.
+ nav := "/a/" + url.PathEscape(r.PathValue("sqid"))
+ w.Header().Set("Cache-Control", "no-store")
+ // The page's script uses an answer only when it carries this header, so
+ // a sign-in page (or anything else a redirect lands on) is never pasted
+ // into the page.
+ w.Header().Set("X-Carlos-Live", "1")
+ name := "analyticsdata"
+ if card {
+ name = "trafficcard"
+ }
+ _ = s.writeTemplate(w, http.StatusOK, name, newAnalyticsLive(&win, card, app, nav, q, now))
+}
+
+// trafficCardLive is the Overview card's live part from handleApp's read.
+func trafficCardLive(win *analyticsWindow, slow bool, app, nav string, now time.Time) *analyticsLive {
+ l := newAnalyticsLive(win, true, app, nav, analyticsQuery{Range: range7d}, now)
+ l.Slow = slow
+ return l
+}
+
+// resolveDefaults is the setting a failed read leaves the page with: the
+// defaults a nil store resolves to.
+func resolveDefaults(ctx context.Context, sqid, app string) telemetry.Resolved {
+ res, _ := telemetry.Resolve(ctx, nil, sqid, app)
+ return res
+}
diff --git a/internal/console/analyticslive_test.go b/internal/console/analyticslive_test.go
new file mode 100644
index 000000000..fd6b3752e
--- /dev/null
+++ b/internal/console/analyticslive_test.go
@@ -0,0 +1,258 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/analytics"
+ "github.com/carlosframework/platform/internal/telemetry"
+)
+
+func TestParseAnalyticsQuery(t *testing.T) {
+ now := time.Date(2026, 10, 29, 15, 0, 0, 0, time.UTC)
+ for raw, want := range map[string]analyticsQuery{
+ "": {Range: rangeToday},
+ "range=7d": {Range: range7d},
+ "range=bogus": {Range: rangeToday},
+ "date=2026-10-28": {Range: rangeDay, Date: "2026-10-28"},
+ "date=2026-09-30": {Range: rangeDay, Date: "2026-09-30"}, // the 30-day window's first day
+ "date=2026-09-29": {Range: rangeToday}, // past the window
+ "date=2026-09-29&range=30d": {Range: range30d}, // falls back to the range
+ "date=2026-10-29": {Range: rangeToday}, // today is the today range
+ "date=2026-10-30": {Range: rangeToday}, // the future is not a day
+ "date=2026-10-28T00:00": {Range: rangeToday},
+ "date=2026-1-2": {Range: rangeToday},
+ } {
+ v, _ := url.ParseQuery(raw)
+ if got := parseAnalyticsQuery(v, now); got != want {
+ t.Errorf("parseAnalyticsQuery(%q) = %+v, want %+v", raw, got, want)
+ }
+ }
+}
+
+func TestDayNeighbours(t *testing.T) {
+ now := time.Date(2026, 10, 29, 15, 0, 0, 0, time.UTC)
+ for date, want := range map[string][2]string{
+ "2026-10-28": {"2026-10-27", rangeToday},
+ "2026-10-20": {"2026-10-19", "2026-10-21"},
+ "2026-09-30": {"", "2026-10-01"},
+ } {
+ if p, n := dayNeighbours(date, now); p != want[0] || n != want[1] {
+ t.Errorf("dayNeighbours(%s) = %q %q, want %q %q", date, p, n, want[0], want[1])
+ }
+ }
+}
+
+// A daily chart's columns open their day; today's opens the today range; an
+// hourly chart opens nothing.
+func TestLinkChartDays(t *testing.T) {
+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC)
+ days := []analytics.DaySummary{{Date: "2026-10-28", PV: 3}, {Date: "2026-10-29", PV: 1}}
+ c := buildTrafficChart(range7d, analytics.Summary{Days: days}, now)
+ linkChartDays(c, "/a/shop/apps/site/analytics", now)
+ if c.Cols[0].Href != "/a/shop/apps/site/analytics?date=2026-10-28" || c.Cols[1].Href != "/a/shop/apps/site/analytics?range=today" {
+ t.Fatalf("hrefs = %q %q", c.Cols[0].Href, c.Cols[1].Href)
+ }
+ var d analytics.DaySummary
+ d.Date, d.Hours[9] = "2026-10-29", 2
+ h := buildTrafficChart(rangeToday, analytics.Summary{Days: []analytics.DaySummary{d}}, now)
+ linkChartDays(h, "/a/shop/apps/site/analytics", now)
+ for _, col := range h.Cols {
+ if col.Href != "" {
+ t.Fatalf("an hourly column links to %q", col.Href)
+ }
+ }
+}
+
+// The live door answers the tab's or the card's numbers part, marked so the
+// page's script will use it, to a member; through the memo, so a second
+// refresh within the minute reads no day file.
+func TestAnalyticsLiveDoor(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-live")
+ seedAnalytics(t, fx, seedTime())
+ 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)
+ }
+ cs := &analyticsCountStore{Store: fx.rel}
+ fx.srv.cfg.Releases = cs
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-live-browser")
+
+ res, err := c.Get(fx.u("/apps/titogo/analytics/live?view=tab&range=7d"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := readBody(t, res)
+ if res.StatusCode != http.StatusOK || res.Header.Get("X-Carlos-Live") != "1" || res.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("live tab = %d live=%q cache=%q", res.StatusCode, res.Header.Get("X-Carlos-Live"), res.Header.Get("Cache-Control"))
+ }
+ for _, want := range []string{"<dt>Page views</dt>", "<dd>5</dd>", "Updated ", `class="an-chart an-chart-day"`} {
+ if !strings.Contains(body, want) {
+ t.Errorf("live tab missing %q", want)
+ }
+ }
+ if !strings.Contains(body, "/analytics?range=today") {
+ t.Error("today's column does not open the today range")
+ }
+ if strings.Contains(body, "<html") || strings.Contains(body, "an-off") || !strings.Contains(body, `<nav class="an-range" aria-label="Period">`) {
+ t.Error("live answer carries page chrome, or lacks its period row")
+ }
+ before := cs.dayReads()
+ res, err = c.Get(fx.u("/apps/titogo/analytics/live?view=tab&range=7d"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ readBody(t, res)
+ if got := cs.dayReads() - before; got != 0 {
+ t.Errorf("second refresh within the minute read %d day files, want 0 (memo)", got)
+ }
+
+ res, err = c.Get(fx.u("/apps/titogo/analytics/live?view=card"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if body := readBody(t, res); res.StatusCode != 200 || !strings.Contains(body, `class="an-chart an-chart-day"`) || strings.Contains(body, "Top pages") {
+ t.Errorf("live card = %d, want the card body only", res.StatusCode)
+ }
+
+ // Signed out: no live answer, so the script keeps what it shows.
+ anon := newBrowser(t)
+ res, err = anon.Get(fx.u("/apps/titogo/analytics/live?view=tab"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ readBody(t, res)
+ if res.StatusCode == http.StatusOK || res.Header.Get("X-Carlos-Live") == "1" {
+ t.Errorf("signed-out live = %d live=%q, want no live answer", res.StatusCode, res.Header.Get("X-Carlos-Live"))
+ }
+ // An app the account does not have: 404, as every app door answers.
+ if status, _, _ := get(t, c, fx.u("/apps/nosuch/analytics/live?view=tab")); status != http.StatusNotFound {
+ t.Errorf("live for an unknown app = %d, want 404", status)
+ }
+}
+
+// ?date= opens one day: its hours, the day's name, its neighbours, and no
+// terminal hint (the CLI has no day view).
+func TestAnalyticsTabDayView(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-day")
+ yesterday := seedTime().AddDate(0, 0, -1)
+ seedAnalytics(t, fx, yesterday)
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-day-browser")
+ date := yesterday.Format("2006-01-02")
+ status, _, body := get(t, c, fx.u("/apps/titogo/analytics?date="+date))
+ if status != http.StatusOK {
+ t.Fatalf("day view = %d", status)
+ }
+ for _, want := range []string{`class="an-chart an-chart-hour"`, fmtDate(date, "Mon 2 Jan 2006") + " UTC", "Previous day", `href="?range=today">Next day`, "Estimated.", "<dd>5</dd>"} {
+ if !strings.Contains(body, want) {
+ t.Errorf("day view missing %q", want)
+ }
+ }
+ if strings.Contains(body, "carlos analytics --app") {
+ t.Error("day view shows a terminal hint the CLI cannot follow")
+ }
+ if strings.Contains(body, `aria-current="page">Today`) {
+ t.Error("day view marks Today as the current period")
+ }
+}
+
+// One tooltip at a time: the rule that hides a focused column's tip while
+// another is hovered is in the stylesheet.
+func TestOneTooltipAtATime(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-onetip")
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-onetip-browser")
+ _, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
+ if !strings.Contains(body, ".an-cols:hover .an-col:focus:not(:hover) .an-tip { display: none; }") {
+ t.Fatal("the one-tooltip rule is missing from the page's styles")
+ }
+}
+
+func readBody(t *testing.T, res *http.Response) string {
+ t.Helper()
+ defer res.Body.Close()
+ var b strings.Builder
+ buf := make([]byte, 32<<10)
+ for {
+ n, err := res.Body.Read(buf)
+ b.Write(buf[:n])
+ if err != nil {
+ break
+ }
+ }
+ return b.String()
+}
+
+// Concurrent misses on one key make one read: the live door's budget is one
+// read a minute per app and view, however many tabs refresh at once.
+func TestAnalyticsMemoCoalescesConcurrentMisses(t *testing.T) {
+ var m analyticsMemo
+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC)
+ var reads atomic.Int32
+ release := make(chan struct{})
+ read := func() (analytics.Summary, error) {
+ reads.Add(1)
+ <-release
+ return analytics.Summary{PV: 9}, nil
+ }
+ var wg sync.WaitGroup
+ got := make([]int64, 8)
+ for i := range got {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ sum, err := m.load(context.Background(), "k", now, read)
+ if err != nil {
+ t.Error(err)
+ }
+ got[i] = sum.PV
+ }(i)
+ }
+ time.Sleep(50 * time.Millisecond) // let every caller arrive while the read runs
+ close(release)
+ wg.Wait()
+ if n := reads.Load(); n != 1 {
+ t.Fatalf("8 concurrent misses made %d reads, want 1", n)
+ }
+ for i, pv := range got {
+ if pv != 9 {
+ t.Fatalf("caller %d got %d, want the shared read's 9", i, pv)
+ }
+ }
+ // A waiter gives up with its own context.
+ block := make(chan struct{})
+ defer close(block)
+ go m.load(context.Background(), "slow", now, func() (analytics.Summary, error) { <-block; return analytics.Summary{}, nil })
+ time.Sleep(20 * time.Millisecond)
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if _, err := m.load(ctx, "slow", now, read); err == nil {
+ t.Fatal("a waiter outlived its context")
+ }
+}
+
+// The page script never refreshes closer than a minute apart, whatever asks
+// (the interval, or coming back to the tab).
+func TestAnalyticsScriptRefreshesAtMostOnceAMinute(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-script")
+ seedAnalytics(t, fx, seedTime())
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-script-browser")
+ _, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
+ if !strings.Contains(body, "if (Date.now() - lastRun < 55000) return;") {
+ t.Fatal("the refresh's minimum interval is missing")
+ }
+}
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&amp;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 8880a16d3..51fd60861 100644
--- a/internal/console/analyticsview.go
+++ b/internal/console/analyticsview.go
@@ -243,11 +243,21 @@ 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.
Restarts string
+ // 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
@@ -275,8 +285,56 @@ const (
// it; someone looking at analytics gets the bucket as it is. A held
// Summary is shared between views and must not be changed.
type analyticsMemo struct {
- mu sync.Mutex
- m map[string]analyticsMemoEntry
+ mu sync.Mutex
+ m map[string]analyticsMemoEntry
+ inflight map[string]*analyticsMemoCall
+}
+
+// analyticsMemoCall is one read in progress, which every caller asking for
+// the same key while it runs waits on rather than starting its own.
+type analyticsMemoCall struct {
+ done chan struct{}
+ sum analytics.Summary
+ err error
+}
+
+// load is key's counts: from the memo when held, else from the one read
+// in progress for key, else from read, which this caller runs and keeps.
+// Concurrent misses on one key (two tabs refreshing in the same second)
+// make one read, so the budget is one read a minute per app and view
+// however many pages ask. A waiter gives up with its own context; a failed
+// read is not kept, and the next caller reads again.
+func (c *analyticsMemo) load(ctx context.Context, key string, now time.Time, read func() (analytics.Summary, error)) (analytics.Summary, error) {
+ if sum, ok := c.get(key, now); ok {
+ return sum, nil
+ }
+ c.mu.Lock()
+ if call, ok := c.inflight[key]; ok {
+ c.mu.Unlock()
+ select {
+ case <-call.done:
+ return call.sum, call.err
+ case <-ctx.Done():
+ return analytics.Summary{}, ctx.Err()
+ }
+ }
+ if c.inflight == nil {
+ c.inflight = map[string]*analyticsMemoCall{}
+ }
+ call := &analyticsMemoCall{done: make(chan struct{})}
+ c.inflight[key] = call
+ c.mu.Unlock()
+ defer func() {
+ c.mu.Lock()
+ delete(c.inflight, key)
+ c.mu.Unlock()
+ close(call.done)
+ }()
+ call.sum, call.err = read()
+ if call.err == nil {
+ c.put(key, call.sum, now)
+ }
+ return call.sum, call.err
}
type analyticsMemoEntry struct {
@@ -371,20 +429,35 @@ func analyticsSpan(rng string, now time.Time) (from, to time.Time) {
}
}
+// analyticsQuerySpan is analyticsSpan for a query: a day view covers that
+// whole UTC day, which is over (parseAnalyticsQuery makes today a range).
+func analyticsQuerySpan(q analyticsQuery, now time.Time) (from, to time.Time) {
+ if q.Range == rangeDay {
+ if d, err := time.Parse("2006-01-02", q.Date); err == nil {
+ return d, d.Add(24*time.Hour - time.Nanosecond)
+ }
+ }
+ return analyticsSpan(q.Range, now)
+}
+
// readAnalytics assembles the window. It resolves the setting first and then
// reads whichever way that came out: numbers already collected are still
// shown after an owner turns counting off, because they were collected while
// it was on and hiding them would read as data loss.
func (s *Server) readAnalytics(ctx context.Context, sqid, app, rng string, now time.Time) (analyticsWindow, error) {
- return s.readAnalyticsVia(ctx, sqid, app, rng, now, nil)
+ return s.readAnalyticsFor(ctx, sqid, app, analyticsQuery{Range: rng}, now, nil)
}
-// readAnalyticsVia is readAnalytics, with the counts taken from memo when
-// it holds them for this window (the Overview's traffic card). The setting
-// is read every time either way: an owner who turns analytics on sees it
-// on at once.
-func (s *Server) readAnalyticsVia(ctx context.Context, sqid, app, rng string, now time.Time, memo *analyticsMemo) (analyticsWindow, error) {
- out := analyticsWindow{Range: rng}
+// readAnalyticsFor is readAnalytics for any query, a day included, with the
+// counts taken from memo when it holds them for this window (the Overview's
+// traffic card and the live door). The setting is read every time either
+// way: an owner who turns analytics on sees it on at once.
+func (s *Server) readAnalyticsFor(ctx context.Context, sqid, app string, q analyticsQuery, now time.Time, memo *analyticsMemo) (analyticsWindow, error) {
+ rng := q.Range
+ out := analyticsWindow{Range: rng, Date: q.Date}
+ if rng == rangeDay {
+ out.Prev, out.Next = dayNeighbours(q.Date, now)
+ }
res, err := telemetry.Resolve(ctx, s.cfg.Releases, sqid, app)
if err != nil {
return out, err
@@ -396,25 +469,54 @@ func (s *Server) readAnalyticsVia(ctx context.Context, sqid, app, rng string, no
if s.cfg.Releases == nil {
return out, nil
}
- from, to := analyticsSpan(rng, now)
- key := sqid + "/" + app + "/" + rng + "/" + to.Format("2006-01-02")
- sum, hit := memo.get(key, now)
- if !hit {
- sum, err = s.readAnalyticsRange(ctx, sqid, app, from, to, now)
- if err != nil {
- return out, err
+ from, to := analyticsQuerySpan(q, now)
+ 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
+ }
}
- memo.put(key, sum, now)
+ return sum, err
+ }
+ var sum analytics.Summary
+ if memo == nil {
+ sum, err = read()
+ } else {
+ sum, err = memo.load(ctx, key, now, read)
+ }
+ if err != nil {
+ return out, err
}
out.Sum = sum
- out.Span = analyticsSpanText(rng, now)
- out.Chart = buildTrafficChart(rng, sum, now)
- out.Insights = analyticsInsights(rng, sum, now)
- out.Pages = shareRows(sum.Pages, pageLabel)
- out.Referers = shareRows(sum.Referers, refererLabel)
- out.Events = shareRows(sum.Events, pageLabel)
+ // A day is drawn as today is: its hours.
+ shape := rng
+ if rng == rangeDay {
+ shape = rangeToday
+ out.Span = fmtDate(q.Date, "Mon 2 Jan 2006") + " UTC"
+ } else {
+ out.Span = analyticsSpanText(rng, now)
+ }
+ out.Chart = buildTrafficChart(shape, sum, now)
+ out.Insights = analyticsInsights(shape, sum, now)
+ 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.Restarts = restartNote(sum.Days)
+ 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
}
@@ -479,14 +581,13 @@ func (s *Server) handleAppAnalytics(w http.ResponseWriter, r *http.Request) {
}
// A page never 400s over its own query string: an unknown range falls
// back to today, the way the Errors tab falls back to its default window
- // rather than refusing a URL someone mistyped.
- p.AnalyticsRange = r.URL.Query().Get("range")
- if !validRange(p.AnalyticsRange) {
- p.AnalyticsRange = rangeToday
- }
+ // rather than refusing a URL someone mistyped (parseAnalyticsQuery).
+ now := time.Now()
+ q := parseAnalyticsQuery(r.URL.Query(), now)
+ p.AnalyticsRange = q.Range
ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
defer cancel()
- win, err := s.readAnalytics(ctx, acct.Sqid, p.AppName, p.AnalyticsRange, time.Now())
+ win, err := s.readAnalyticsFor(ctx, acct.Sqid, p.AppName, q, now, nil)
if err != nil {
log.Printf("console: app analytics %s/%s: %v", acct.Sqid, p.AppName, err)
p.AnalyticsErr = "The analytics could not be read just now — try again in a moment."
@@ -494,9 +595,10 @@ func (s *Server) handleAppAnalytics(w http.ResponseWriter, r *http.Request) {
// then say counting is off "from the " with nothing after it. The
// defaults are what a nil store resolves to, so ask for them rather
// than restating them here.
- win.Setting, _ = telemetry.Resolve(ctx, nil, acct.Sqid, p.AppName)
+ win.Setting = resolveDefaults(ctx, acct.Sqid, p.AppName)
}
p.AnalyticsWin = win
+ p.AnalyticsLive = newAnalyticsLive(&p.AnalyticsWin, false, p.AppName, p.Nav, q, now)
s.render(w, http.StatusOK, "app_analytics", p)
}
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/billingpage.go b/internal/console/billingpage.go
index b035c7df6..4357f028e 100644
--- a/internal/console/billingpage.go
+++ b/internal/console/billingpage.go
@@ -50,6 +50,9 @@ type billingPageInput struct {
Problems []string // open problem reasons
Retiring, Ready, Owner bool
Now time.Time
+ // Caps is the plan-limits pass's rows for the account (plan_cap_state),
+ // the usage the page shows (billingusage.go).
+ Caps []capState
}
// billingPageState is the page's decision: a billingCopy notice key ("" for
@@ -200,9 +203,12 @@ type billingView struct {
// it gives the account today.
Plan string
Facts []string
- Includes []string
+ Includes []billingInclude
limits *plans.Limits // the limits Includes lists, nil for none
Offers billingOffers
+ // Usage is the account's use as the plan-limits pass last measured it,
+ // nil when it has measured nothing this period (addUsage).
+ Usage *billingUsageView
// Success is the screen that replaces the page after a completed
// purchase, nil for none (billingSuccessFor).
Success *billingSuccess
@@ -262,7 +268,15 @@ type billingPlanOption struct {
Prices, Totals []billingPrice
// Includes is a few of the plan's limits for this account today
// (planIncludes).
- Includes []string
+ Includes []billingInclude
+}
+
+// billingInclude is one limit a plan card or the summary lists, and on a
+// plan card's apps and instances the account's use beside it (addUsage).
+type billingInclude struct {
+ Text string
+ Use *billingUse
+ running bool // the apps and instances line
}
type billingPackInput struct {
@@ -270,6 +284,7 @@ type billingPackInput struct {
Label, Adds string // the pack as the page names it, and what one adds
Prices []billingPrice // the purchase form's, one per currency it can submit
Max, Value int
+ Use *billingUse // the account's use of the limit the pack raises (addUsage)
}
type billingCurrencyOption struct {
@@ -308,6 +323,9 @@ func (s *Server) billingPageInputFor(acct *Account, role string, now time.Time)
if in.Retiring, err = s.store.BillingRetiring(acct.ID, now); err != nil {
return in, err
}
+ if in.Caps, err = s.store.CapStates(acct.ID); err != nil {
+ return in, err
+ }
return in, nil
}
@@ -448,6 +466,7 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing
if v.Offers.Change && b != nil {
v.Change = billingChange(cat, book, plan, packs, b.Currency)
}
+ addUsage(v, cat, in.Caps, members, in.Now)
if v.Offers.StartOver && in.Intent != nil {
ci := in.Intent
v.StartOver = []billingField{{"plan", ci.Plan}, {"currency", ci.Currency}}
@@ -702,22 +721,23 @@ func billingDate(t time.Time) string { return t.UTC().Format("2 January 2006") }
// words `carlos accounts plan` uses: apps and instances, sleeps after,
// disk per app, custom domains, and the member cap of a plan that has one
// (maxMembers, 0 for none). A limit of 0 is left out.
-func planIncludes(l plans.Limits, maxMembers int) []string {
- var out []string
+func planIncludes(l plans.Limits, maxMembers int) []billingInclude {
+ var out []billingInclude
+ add := func(text string) { out = append(out, billingInclude{Text: text}) }
if l.RunningThings > 0 {
- out = append(out, fmt.Sprintf(billingCopy["limit.running"], billingCount(int64(l.RunningThings))))
+ out = append(out, billingInclude{Text: fmt.Sprintf(billingCopy["limit.running"], billingCount(int64(l.RunningThings))), running: true})
}
if l.IdleSeconds > 0 {
- out = append(out, fmt.Sprintf(billingCopy["limit.idle"], billingDuration(l.IdleSeconds)))
+ add(fmt.Sprintf(billingCopy["limit.idle"], billingDuration(l.IdleSeconds)))
}
if l.DiskBytes > 0 {
- out = append(out, fmt.Sprintf(billingCopy["limit.disk"], billingBytes(l.DiskBytes)))
+ add(fmt.Sprintf(billingCopy["limit.disk"], billingBytes(l.DiskBytes)))
}
if l.CustomDomains {
- out = append(out, billingCopy["limit.domains"])
+ add(billingCopy["limit.domains"])
}
if maxMembers > 0 {
- out = append(out, fmt.Sprintf(billingCopy["limit.members"], maxMembers))
+ add(fmt.Sprintf(billingCopy["limit.members"], maxMembers))
}
return out
}
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index be796d5f0..9594d9d13 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -163,4 +163,18 @@ var billingCopy = map[string]string{
"done.packs.title": "Your packs are ready",
"done.packs.lede": "Your packs are ready to use on %s.",
"done.packs.flash": "Your packs are ready to use.",
+
+ // The account's usage beside the packs and plan cards, from the
+ // plan-limits pass (2026-10-29). copy approved by Paul 2026-10-30.
+ "usage.of": "%s of %s used",
+ "usage.of_today": "%s of %s used today",
+ "usage.of_month": "%s of %s used this month",
+ "usage.unknown": "Usage not known yet",
+ "usage.disk": "Up to %s per app",
+ "usage.you_use": "You use %s",
+ "usage.as_of": "Usage as of %s",
+ "usage.label.running": "Apps and instances",
+ "usage.label.storage": "Object storage",
+ "usage.label.email": "Email",
+ "usage.label.bandwidth": "Bandwidth",
}
diff --git a/internal/console/billingpage_test.go b/internal/console/billingpage_test.go
index 71aa259c5..cd4008699 100644
--- a/internal/console/billingpage_test.go
+++ b/internal/console/billingpage_test.go
@@ -137,7 +137,14 @@ type billingPageFixture struct {
func newBillingPageFixture(t *testing.T) *billingPageFixture {
t.Helper()
- bf := newBillingFixture(t)
+ return newBillingPageFixtureWith(t, consoleFixtureOptions{WithKey: true})
+}
+
+// newBillingPageFixtureWith is newBillingPageFixture over the console
+// fixture o describes.
+func newBillingPageFixtureWith(t *testing.T, o consoleFixtureOptions) *billingPageFixture {
+ t.Helper()
+ bf := newBillingFixtureWith(t, o)
bf.srv.billing.ready.Store(true)
bf.setUser("owner" + bf.acct.Sqid + "@example.com")
c := newBrowser(t)
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go
index a52b1f45f..2c7b1017d 100644
--- a/internal/console/billingsync_test.go
+++ b/internal/console/billingsync_test.go
@@ -260,7 +260,14 @@ func testPersonalSub(id, customer, sqid, status string, packs map[string]int64)
// account bound to customer cus_1.
func newBillingFixture(t *testing.T) *billingFixture {
t.Helper()
- fx := newConsoleFixture(t)
+ return newBillingFixtureWith(t, consoleFixtureOptions{WithKey: true})
+}
+
+// newBillingFixtureWith is newBillingFixture over the console fixture o
+// describes.
+func newBillingFixtureWith(t *testing.T, o consoleFixtureOptions) *billingFixture {
+ t.Helper()
+ fx := newConsoleFixtureWith(t, o)
fake := enableBilling(t, fx.srv)
acct := planAccount(t, fx, 501)
if err := fx.st.SetBillingCustomer(acct.ID, "cus_1", billingNow); err != nil {
diff --git a/internal/console/billingusage.go b/internal/console/billingusage.go
new file mode 100644
index 000000000..4f3f7a949
--- /dev/null
+++ b/internal/console/billingusage.go
@@ -0,0 +1,197 @@
+package console
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// The billing page's usage (2026-10-29): an owner deciding on packs or an
+// upgrade sees what the account uses beside each limit. The figures are
+// the plan-limits pass's (plangracepass.go): every hour it measures every
+// cap the account's limits offer and stores one plan_cap_state row per
+// cap, at every level. The page reads those rows from the console
+// database and nothing else: a page view measures nothing and makes no
+// bucket or provider request.
+//
+// A row counts only in its own period: an email row from an earlier UTC
+// day, or a bandwidth row from an earlier UTC month, is not this period's
+// use, so it shows as not known, never as its old figure or as zero.
+// Disk is a per-app limit nothing measures centrally: its limit alone.
+
+// usageCaps are the caps the page shows, in order: the ones a pack raises.
+var usageCaps = []capID{capRunningThings, capStorage, capEmail, capBandwidth}
+
+// billingUse is a use beside a limit as the page shows it. Level is ""
+// below 80% of the limit, "warn" from 80% up to it, "over" past it.
+type billingUse struct {
+ Text, Level string
+}
+
+// billingUsageRow is one line of the summary's usage list.
+type billingUsageRow struct {
+ Label string
+ Use *billingUse
+}
+
+// billingUsageView is the account's usage on the page. AsOf is the "Usage
+// as of" line, at the oldest measurement shown. Rows is the summary's
+// list, set only when no pack row carries the usage (a member, or a page
+// with no packs to change).
+type billingUsageView struct {
+ AsOf string
+ Rows []billingUsageRow
+}
+
+// accountUsage is the account's use per cap, from rows measured in their
+// cap's current period, and the oldest such measurement. Nothing current
+// is (nil, zero).
+func accountUsage(rows []capState, now time.Time) (map[capID]int64, time.Time) {
+ var used map[capID]int64
+ var oldest time.Time
+ for _, st := range rows {
+ shown := false
+ for _, c := range usageCaps {
+ shown = shown || st.Cap == c
+ }
+ if !shown || st.Period != capPeriod(st.Cap, now) || st.UpdatedAt.IsZero() {
+ continue
+ }
+ if used == nil {
+ used = map[capID]int64{}
+ }
+ used[st.Cap] = st.Used
+ if oldest.IsZero() || st.UpdatedAt.Before(oldest) {
+ oldest = st.UpdatedAt
+ }
+ }
+ return used, oldest
+}
+
+// capLimit is l's limit for c, 0 for none.
+func capLimit(l plans.Limits, c capID) int64 {
+ switch c {
+ case capRunningThings:
+ return int64(l.RunningThings)
+ case capStorage:
+ return l.StorageBytes
+ case capEmail:
+ return int64(l.EmailPerDay)
+ case capBandwidth:
+ return l.BandwidthBytesMonth
+ }
+ return 0
+}
+
+// capAmount is an amount of c as the page writes it: a count or a size.
+func capAmount(c capID, n int64) string {
+ if c == capStorage || c == capBandwidth {
+ return billingBytes(n)
+ }
+ return billingCount(n)
+}
+
+// useLevel is the emphasis for used against limit: levelOf's, at the limit
+// shown (which may be a pack or plan away from the one the pass measured
+// against).
+func useLevel(c capID, used, limit int64) string {
+ switch l := levelOf(c, used, limit); {
+ case l.over():
+ return "over"
+ case l == levelWarn:
+ return "warn"
+ }
+ return ""
+}
+
+// useOfLimit is "12 of 35 used" for c against limit, "today" or "this
+// month" for a cap counted per UTC day or month; not known when the pass
+// has no current row; nil when there is no limit to show it beside.
+func useOfLimit(used map[capID]int64, c capID, limit int64) *billingUse {
+ if limit <= 0 {
+ return nil
+ }
+ n, ok := used[c]
+ if !ok {
+ return &billingUse{Text: billingCopy["usage.unknown"]}
+ }
+ key := "usage.of"
+ switch c {
+ case capEmail:
+ key = "usage.of_today"
+ case capBandwidth:
+ key = "usage.of_month"
+ }
+ return &billingUse{Text: fmt.Sprintf(billingCopy[key], capAmount(c, n), capAmount(c, limit)), Level: useLevel(c, n, limit)}
+}
+
+// packUse is a pack row's use: of the limit the pack raises, at the
+// account's limits today, or disk's limit alone; nil when the pack raises
+// nothing the page measures.
+func packUse(used map[capID]int64, adds, limits plans.Limits) *billingUse {
+ for _, c := range usageCaps {
+ if capLimit(adds, c) > 0 {
+ return useOfLimit(used, c, capLimit(limits, c))
+ }
+ }
+ if adds.DiskBytes > 0 && limits.DiskBytes > 0 {
+ return &billingUse{Text: fmt.Sprintf(billingCopy["usage.disk"], billingBytes(limits.DiskBytes))}
+ }
+ return nil
+}
+
+// addUsage puts the account's usage on v: each pack row's, beside each
+// plan card's apps and instances, and the as-of line; in the summary when
+// no pack row carries it. Nothing measured this period leaves v as it was.
+func addUsage(v *billingView, cat *plans.Catalog, rows []capState, members int, now time.Time) {
+ used, oldest := accountUsage(rows, now)
+ if used == nil || v.limits == nil {
+ return
+ }
+ u := &billingUsageView{AsOf: fmt.Sprintf(billingCopy["usage.as_of"], oldest.UTC().Format("2006-01-02 15:04 UTC"))}
+ inPacks := false
+ packs := func(ps []billingPackInput) {
+ for i := range ps {
+ if ps[i].Use = packUse(used, cat.Packs[ps[i].Name].Adds, *v.limits); ps[i].Use != nil {
+ inPacks = true
+ }
+ }
+ }
+ if v.Buy != nil {
+ packs(v.Buy.Packs)
+ if n, ok := used[capRunningThings]; ok {
+ for i := range v.Buy.Plans {
+ opt := &v.Buy.Plans[i]
+ l, err := cat.Effective(opt.Name, nil, nil, members)
+ if err != nil || l.RunningThings <= 0 {
+ continue
+ }
+ for j := range opt.Includes {
+ if opt.Includes[j].running {
+ opt.Includes[j].Use = &billingUse{Text: fmt.Sprintf(billingCopy["usage.you_use"], billingCount(n)),
+ Level: useLevel(capRunningThings, n, int64(l.RunningThings))}
+ }
+ }
+ }
+ }
+ }
+ if v.Change != nil {
+ packs(v.Change.Packs)
+ }
+ if !inPacks {
+ // No pack row carries it (a member, or no packs to change): the
+ // summary lists it instead.
+ labels := map[capID]string{capRunningThings: "usage.label.running", capStorage: "usage.label.storage",
+ capEmail: "usage.label.email", capBandwidth: "usage.label.bandwidth"}
+ for _, c := range usageCaps {
+ if use := useOfLimit(used, c, capLimit(*v.limits, c)); use != nil {
+ u.Rows = append(u.Rows, billingUsageRow{Label: billingCopy[labels[c]], Use: use})
+ }
+ }
+ if len(u.Rows) == 0 {
+ return
+ }
+ }
+ v.Usage = u
+}
diff --git a/internal/console/billingusage_test.go b/internal/console/billingusage_test.go
new file mode 100644
index 000000000..80b63f05e
--- /dev/null
+++ b/internal/console/billingusage_test.go
@@ -0,0 +1,338 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "regexp"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The billing page's usage (2026-10-29): what the plan-limits pass last
+// stored in plan_cap_state, beside the packs, the plan cards and, where no
+// pack row carries it, in the summary. Read from the console database
+// only; a page view measures nothing.
+
+const gib = int64(1) << 30
+
+// putCapRows stores the plan-limits pass's rows for the fixture's account.
+func putCapRows(t *testing.T, pf *billingPageFixture, rows ...capState) {
+ t.Helper()
+ for _, st := range rows {
+ st.AccountID = pf.acct.ID
+ if st.Level == "" {
+ st.Level = levelOK
+ }
+ if err := pf.st.PutCapState(st); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// usageRow is a row for c measured at `at`, in at's period.
+func usageRow(c capID, used int64, at time.Time) capState {
+ return capState{Cap: c, Period: capPeriod(c, at), Used: used, UpdatedAt: at}
+}
+
+// changeRow is the paid view's pack row for name.
+func changeRow(t *testing.T, body, name string) string {
+ t.Helper()
+ m := regexp.MustCompile(`(?s)<tr data-pack="` + name + `">(.*?)</tr>`).FindStringSubmatch(body)
+ if m == nil {
+ t.Fatalf("no pack row %q:\n%s", name, body)
+ }
+ return m[1]
+}
+
+// useSpan is the usage element a row or card carries, "" for none.
+var useSpan = regexp.MustCompile(`<(?:span|dd) class="[^"]*\buse\b[^"]*">[^<]*</(?:span|dd)>`)
+
+func useOf(t *testing.T, markup string) string {
+ t.Helper()
+ return useSpan.FindString(markup)
+}
+
+func usageAsOf(at time.Time) string {
+ return fmt.Sprintf(billingCopy["usage.as_of"], at.UTC().Format("2006-01-02 15:04 UTC"))
+}
+
+// TestBillingPageUsageFromCapRows: a paid Personal account with packs sees,
+// on each pack row, its use of the limit that pack raises, from the pass's
+// rows: low plain, 80% and up warned, past the limit over; disk the limit
+// alone; and one "as of" line, the oldest measurement shown.
+func TestBillingPageUsageFromCapRows(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ pf.payFor(t, "personal", map[string]int{"apps": 2, "email": 1}, nil)
+ now := time.Now().UTC()
+ older := now.Add(-50 * time.Minute)
+ bandwidth := usageRow(capBandwidth, 60*gib, older) // 60 GB of 50 GB: over
+ bandwidth.Period = capPeriod(capBandwidth, now) // measured this month, an earlier pass
+ putCapRows(t, pf,
+ usageRow(capRunningThings, 12, now), // 12 of 35: low
+ usageRow(capEmail, 1700, now), // 1,700 of 2,000: 85%, near
+ bandwidth,
+ usageRow(capStorage, 3*gib, now), // 3 GB of 25 GB: low
+ usageRow(capAwakeHours, 10, now), // no pack raises it
+ )
+ _, body := pf.page(t, "")
+
+ for _, c := range []struct {
+ pack, text, class string
+ }{
+ {"apps", fmt.Sprintf(billingCopy["usage.of"], "12", "35"), "use"},
+ {"email", fmt.Sprintf(billingCopy["usage.of_today"], "1,700", "2,000"), "use use-warn"},
+ {"bandwidth", fmt.Sprintf(billingCopy["usage.of_month"], "60 GB", "50 GB"), "use use-over"},
+ {"storage", fmt.Sprintf(billingCopy["usage.of"], "3 GB", "25 GB"), "use"},
+ } {
+ got := useOf(t, changeRow(t, body, c.pack))
+ want := `<span class="small ` + c.class + `">` + esc(c.text) + `</span>`
+ if got != want {
+ t.Errorf("pack %s: usage %q, want %q", c.pack, got, want)
+ }
+ }
+ // Disk per app is not measured centrally: its limit alone.
+ disk := changeRow(t, body, "disk")
+ if got, want := useOf(t, disk), `<span class="small use">`+esc(fmt.Sprintf(billingCopy["usage.disk"], "10 GB"))+`</span>`; got != want {
+ t.Errorf("disk: usage %q, want %q", got, want)
+ }
+ if strings.Contains(disk, esc(" used")) {
+ t.Errorf("disk shows a use it has no measure of:\n%s", disk)
+ }
+ // One "as of" line, at the oldest row shown.
+ if n := strings.Count(body, esc(usageAsOf(older))); n != 1 {
+ t.Errorf("want one %q, got %d", usageAsOf(older), n)
+ }
+ if strings.Contains(body, esc(usageAsOf(now))) {
+ t.Error("the as-of line names the newest row, not the oldest")
+ }
+ // Pack rows carry it, so the summary does not repeat it.
+ if strings.Contains(body, `class="billing-usage"`) {
+ t.Error("the summary repeats the usage the pack rows show")
+ }
+}
+
+// TestBillingPageUsageStalePeriodUnknown: a row from an earlier UTC day
+// (email) or month (bandwidth) is not this period's use: it shows as not
+// known, never as its old figure or as zero. A cap with no row is not
+// known either.
+func TestBillingPageUsageStalePeriodUnknown(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ pf.payFor(t, "personal", map[string]int{}, nil)
+ now := time.Now().UTC()
+ lastMonth := time.Date(now.Year(), now.Month(), 1, 12, 0, 0, 0, time.UTC).AddDate(0, -1, 0)
+ yesterday := now.AddDate(0, 0, -1)
+ putCapRows(t, pf,
+ usageRow(capRunningThings, 4, now),
+ usageRow(capEmail, 999, yesterday),
+ usageRow(capBandwidth, 70*gib, lastMonth),
+ )
+ _, body := pf.page(t, "")
+ unknown := `<span class="small use">` + esc(billingCopy["usage.unknown"]) + `</span>`
+ for _, pack := range []string{"email", "bandwidth", "storage"} {
+ row := changeRow(t, body, pack)
+ if got := useOf(t, row); got != unknown {
+ t.Errorf("%s: usage %q, want %q", pack, got, unknown)
+ }
+ if strings.Contains(row, "999") || strings.Contains(row, "70 GB") || strings.Contains(row, esc(fmt.Sprintf(billingCopy["usage.of_today"], "0", "1,000"))) {
+ t.Errorf("%s: a stale row shows as a figure:\n%s", pack, row)
+ }
+ }
+ if got, want := useOf(t, changeRow(t, body, "apps")), `<span class="small use">`+esc(fmt.Sprintf(billingCopy["usage.of"], "4", "25"))+`</span>`; got != want {
+ t.Errorf("apps: usage %q, want %q", got, want)
+ }
+ // The as-of line names only what is shown: the fresh row.
+ if !strings.Contains(body, esc(usageAsOf(now))) || strings.Contains(body, esc(usageAsOf(lastMonth))) || strings.Contains(body, esc(usageAsOf(yesterday))) {
+ t.Errorf("as-of line wrong:\n%s", body)
+ }
+
+ // Every row stale: nothing is known, so the page shows no usage at all.
+ pf2 := newBillingPageFixture(t)
+ pf2.payFor(t, "personal", map[string]int{}, nil)
+ putCapRows(t, pf2, usageRow(capEmail, 5, yesterday))
+ _, body = pf2.page(t, "")
+ if useOf(t, body) != "" || strings.Contains(body, esc(fmt.Sprintf(billingCopy["usage.as_of"], ""))) {
+ t.Errorf("only stale rows: want no usage:\n%s", body)
+ }
+}
+
+// TestBillingPageUsageNoRowsNoUsage: before the pass has measured anything
+// the page is as it was: no usage, no as-of line.
+func TestBillingPageUsageNoRowsNoUsage(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ pf.payFor(t, "personal", map[string]int{"apps": 1}, nil)
+ _, body := pf.page(t, "")
+ if useOf(t, body) != "" || strings.Contains(body, `class="small usage-asof"`) {
+ t.Errorf("no rows: want no usage:\n%s", body)
+ }
+}
+
+// TestBillingPageUsageBuyView: a free account choosing a plan sees its use
+// against the free plan's limits on the pack rows, and beside each plan
+// card's apps and instances, at that plan's limit: near Personal's 25 at
+// 22, and plain against a larger plan's.
+func TestBillingPageUsageBuyView(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ now := time.Now().UTC()
+ putCapRows(t, pf, usageRow(capRunningThings, 22, now), usageRow(capEmail, 10, now))
+ _, body := pf.page(t, "")
+ form := htmlForm(body, `<form class="buy"`)
+ if form == "" {
+ t.Fatalf("no purchase form:\n%s", body)
+ }
+ // Pack rows: against the account's limits today (free: 3, 50 a day).
+ if got, want := useOf(t, changeRow(t, form, "apps")), `<span class="small use use-over">`+esc(fmt.Sprintf(billingCopy["usage.of"], "22", "3"))+`</span>`; got != want {
+ t.Errorf("apps: usage %q, want %q", got, want)
+ }
+ if got, want := useOf(t, changeRow(t, form, "email")), `<span class="small use">`+esc(fmt.Sprintf(billingCopy["usage.of_today"], "10", "50"))+`</span>`; got != want {
+ t.Errorf("email: usage %q, want %q", got, want)
+ }
+ // Plan cards: beside the plan's own apps and instances.
+ cards := regexp.MustCompile(`(?s)<div class="plan-card">(.*?)</ul>`).FindAllStringSubmatch(form, -1)
+ if len(cards) == 0 {
+ t.Fatalf("no plan cards:\n%s", form)
+ }
+ youUse := esc(fmt.Sprintf(billingCopy["usage.you_use"], "22"))
+ seen := map[string]string{}
+ for _, c := range cards {
+ name := regexp.MustCompile(`data-plan="([^"]+)"`).FindStringSubmatch(c[1])[1]
+ seen[name] = useOf(t, c[1])
+ }
+ if got, want := seen["personal"], `<span class="small use use-warn">`+youUse+`</span>`; got != want {
+ t.Errorf("personal card: usage %q, want %q", got, want)
+ }
+ for name, got := range seen {
+ if name == "personal" {
+ continue
+ }
+ if got != `<span class="small use">`+youUse+`</span>` {
+ t.Errorf("%s card: usage %q, want plain %q", name, got, youUse)
+ }
+ }
+ if n := strings.Count(body, `class="small usage-asof"`); n != 1 {
+ t.Errorf("want one as-of line, got %d", n)
+ }
+ // The usage spans never read as prices to the currency rules.
+ assertBuyFormPriced(t, pf, body, 1)
+}
+
+// TestBillingPageUsageMember: a member sees the account's usage, in the
+// summary since no pack row is theirs, with no form to change anything.
+func TestBillingPageUsageMember(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ pf.payFor(t, "personal", map[string]int{"apps": 2}, nil)
+ now := time.Now().UTC()
+ putCapRows(t, pf, usageRow(capRunningThings, 34, now), usageRow(capStorage, 30*gib, now))
+ if err := pf.st.AddMember(pf.acct.ID, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ member, _ := signInAs(t, pf.consoleFixture, "member@example.com", "code-billing-usage-member")
+ _, _, body := get(t, member, pf.ts.URL+pf.billingPath(""))
+ i := strings.Index(body, `class="billing-usage"`)
+ if i < 0 {
+ t.Fatalf("a member sees no usage:\n%s", body)
+ }
+ strip := body[i:]
+ strip = strip[:strings.Index(strip, "</dl>")]
+ for _, want := range []string{
+ esc(billingCopy["usage.label.running"]),
+ `<dd class="use use-warn">` + esc(fmt.Sprintf(billingCopy["usage.of"], "34", "35")) + `</dd>`,
+ esc(billingCopy["usage.label.storage"]),
+ `<dd class="use use-over">` + esc(fmt.Sprintf(billingCopy["usage.of"], "30 GB", "25 GB")) + `</dd>`,
+ esc(billingCopy["usage.label.email"]),
+ `<dd class="use">` + esc(billingCopy["usage.unknown"]) + `</dd>`,
+ } {
+ if !strings.Contains(strip, want) {
+ t.Errorf("member's usage is missing %q:\n%s", want, strip)
+ }
+ }
+ if !strings.Contains(body, esc(usageAsOf(now))) {
+ t.Errorf("member's page has no as-of line:\n%s", body)
+ }
+ for _, refused := range []string{`/billing/change"`, `/billing/checkout"`, `/billing/renewal"`, `name="pack"`, `name="quantity"`, `type="number"`} {
+ if strings.Contains(body, refused) {
+ t.Errorf("a member's billing page carries %q", refused)
+ }
+ }
+}
+
+// billingReadCounter counts every deployment-store request once armed.
+type billingReadCounter struct {
+ release.Store
+ armed atomic.Bool
+ mu sync.Mutex
+ calls []string
+}
+
+func (c *billingReadCounter) note(op, key string) {
+ if c.armed.Load() {
+ c.mu.Lock()
+ c.calls = append(c.calls, op+" "+key)
+ c.mu.Unlock()
+ }
+}
+
+func (c *billingReadCounter) Get(ctx context.Context, key string) ([]byte, string, error) {
+ c.note("get", key)
+ return c.Store.Get(ctx, key)
+}
+
+func (c *billingReadCounter) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ c.note("put", key)
+ return c.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (c *billingReadCounter) List(ctx context.Context, prefix string) ([]string, error) {
+ c.note("list", prefix)
+ return c.Store.List(ctx, prefix)
+}
+
+func (c *billingReadCounter) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ c.note("listdirs", prefix)
+ return c.Store.ListDirs(ctx, prefix)
+}
+
+func (c *billingReadCounter) Delete(ctx context.Context, key string) error {
+ c.note("delete", key)
+ return c.Store.Delete(ctx, key)
+}
+
+// TestBillingPageUsageMakesNoRequests: a page view showing usage makes no
+// provider request and no deployment-store request: the figures are the
+// pass's rows, never a fresh measure.
+func TestBillingPageUsageMakesNoRequests(t *testing.T) {
+ counter := &billingReadCounter{}
+ pf := newBillingPageFixtureWith(t, consoleFixtureOptions{WithKey: true, WrapReleases: func(s release.Store) release.Store {
+ counter.Store = s
+ return counter
+ }})
+ pf.payFor(t, "personal", map[string]int{"apps": 2, "storage": 1}, nil)
+ now := time.Now().UTC()
+ putCapRows(t, pf, usageRow(capRunningThings, 30, now), usageRow(capStorage, 80*gib, now),
+ usageRow(capEmail, 3, now), usageRow(capBandwidth, gib, now))
+ pf.fake.Lock()
+ pf.fake.CallsBy = map[string]int{}
+ pf.fake.Unlock()
+ counter.armed.Store(true)
+ _, body := pf.page(t, "")
+ counter.armed.Store(false)
+ if useOf(t, body) == "" {
+ t.Fatalf("the page shows no usage:\n%s", body)
+ }
+ pf.fake.Lock()
+ for k, n := range pf.fake.CallsBy {
+ if n != 0 {
+ t.Errorf("the billing page made %d %s provider requests, want none", n, k)
+ }
+ }
+ pf.fake.Unlock()
+ counter.mu.Lock()
+ defer counter.mu.Unlock()
+ if len(counter.calls) != 0 {
+ t.Errorf("the billing page made %d deployment-store requests, want none: %v", len(counter.calls), counter.calls)
+ }
+}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 4b629fe00..03b99df60 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -798,6 +798,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /a/{sqid}/apps/{app}/account-review": claimRead("renders the route-account review card"),
"route GET /a/{sqid}/apps/{app}/activity": claimRead("renders the app's audit trail"),
"route GET /a/{sqid}/apps/{app}/analytics": claimRead("renders analytics read from the bucket"),
+ "route GET /a/{sqid}/apps/{app}/analytics/live": claimRead("renders the Analytics tab's or Overview card's numbers part, read from the bucket through the traffic memo; writes nothing"),
"route GET /a/{sqid}/apps/{app}/availability": claimRead("renders edge availability counts"),
"route GET /a/{sqid}/apps/{app}/deployments": claimRead("redirects to the releases page"),
"route GET /a/{sqid}/apps/{app}/errors": claimRead("renders grouped app errors"),
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index d47cbfe41..b1ec3ca4a 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -143,6 +143,7 @@ var claimReadProbes = map[string]claimProbe{
"route GET /a/{sqid}/apps/{app}/account-review": claimPageRead(nil, "/a/bab/apps/kass/account-review", "kass"),
"route GET /a/{sqid}/apps/{app}/activity": claimPageRead(nil, "/a/bab/apps/kass/activity", "kass"),
"route GET /a/{sqid}/apps/{app}/analytics": claimPageRead(nil, "/a/bab/apps/titogo/analytics", "titogo"),
+ "route GET /a/{sqid}/apps/{app}/analytics/live": claimPageRead(nil, "/a/bab/apps/titogo/analytics/live?view=tab", "titogo"),
"route GET /a/{sqid}/apps/{app}/availability": claimPageRead(nil, "/a/bab/apps/titogo/availability", "titogo"),
"route GET /a/{sqid}/apps/{app}/deployments": claimRedirectRead("/a/bab/apps/kass/deployments", http.StatusSeeOther, "/a/bab/apps/kass/releases"),
"route GET /a/{sqid}/apps/{app}/errors": claimPageRead(nil, "/a/bab/apps/titogo/errors", "titogo"),
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go
index b1a9336b5..c2bbe75a8 100644
--- a/internal/console/perfwalk_test.go
+++ b/internal/console/perfwalk_test.go
@@ -518,6 +518,12 @@ func perfTargets(fx *consoleFixture) map[string][]perfTarget {
"instances", "logs", "logs/data", "settings"} {
m["GET /a/{sqid}/apps/{app}/"+tab] = ok(app + "/" + tab)
}
+ // The live door (analyticslive.go): the tab's numbers part and the
+ // Overview card's, each read through the traffic memo.
+ m["GET /a/{sqid}/apps/{app}/analytics/live"] = []perfTarget{
+ {Path: app + "/analytics/live?view=tab&range=7d", Expect: http.StatusOK},
+ {Path: app + "/analytics/live?view=card", Expect: http.StatusOK},
+ }
// /deployments is a 303 to Releases; the fixture's page 2 of Versions is
// the empty-page state, which still runs the listing.
m["GET /a/{sqid}/apps/{app}/deployments"] = []perfTarget{{Path: app + "/deployments", Expect: http.StatusSeeOther}}
diff --git a/internal/console/server.go b/internal/console/server.go
index a1833e415..506f8dd84 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1856,6 +1856,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// gate the errors level does at both levels, and bumps the serial where
// the errors level does not: a box acts on whether the edge counts.
s.registerRoute("GET /a/{sqid}/apps/{app}/analytics", s.handleAppAnalytics)
+ s.registerRoute("GET /a/{sqid}/apps/{app}/analytics/live", s.handleAnalyticsLive)
s.registerRoute("POST /a/{sqid}/apps/{app}/analytics/setting", s.handleAppAnalyticsSetting)
s.registerRoute("GET /a/{sqid}/apps/{app}/activity", s.handleAppActivity)
s.registerRoute("GET /a/{sqid}/apps/{app}/settings", s.handleAppSettings)
@@ -2542,6 +2543,10 @@ type page struct {
// had not finished when the rest of the page was ready.
Traffic *analyticsWindow
TrafficSlow bool
+ // AnalyticsLive and TrafficLive are the refreshable parts of the
+ // Analytics tab and the Overview card (analyticslive.go).
+ AnalyticsLive *analyticsLive
+ TrafficLive *analyticsLive
// Action confirm interstitial (confirm.go): what is about to happen,
// carried fields and all. Nil everywhere except the confirm page.
@@ -4224,7 +4229,7 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) {
go func() {
ctx, cancel := context.WithTimeout(r.Context(), overviewTrafficTimeout)
defer cancel()
- win, err := s.readAnalyticsVia(ctx, acct.Sqid, app, range7d, time.Now(), &s.trafficMemo)
+ win, err := s.readAnalyticsFor(ctx, acct.Sqid, app, analyticsQuery{Range: range7d}, time.Now(), &s.trafficMemo)
if err != nil {
log.Printf("console: overview traffic %s/%s: %v", acct.Sqid, app, err)
traffic <- nil
@@ -4287,6 +4292,7 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) {
}
wait.Stop()
end()
+ p.TrafficLive = trafficCardLive(p.Traffic, p.TrafficSlow, p.AppName, p.Nav, time.Now())
s.render(w, http.StatusOK, "app_overview", p)
}
diff --git a/internal/console/templates/app_analytics.html b/internal/console/templates/app_analytics.html
index 36b71ab75..6acc6316a 100644
--- a/internal/console/templates/app_analytics.html
+++ b/internal/console/templates/app_analytics.html
@@ -26,14 +26,29 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
{{/* The range picker always shows: numbers counted while analytics was on
stay reachable after it is switched off. Three links rather than a
select and a button: one click, and every view is a URL. */}}
-<nav class="an-range" aria-label="Period">
- <a href="?range=today"{{if eq .AnalyticsRange "today"}} aria-current="page"{{end}}>Today</a>
- <a href="?range=7d"{{if eq .AnalyticsRange "7d"}} aria-current="page"{{end}}>7 days</a>
- <a href="?range=30d"{{if eq .AnalyticsRange "30d"}} aria-current="page"{{end}}>30 days</a>
- {{if .AnalyticsWin.Span}}<span class="an-span">{{.AnalyticsWin.Span}}</span>{{end}}
-</nav>
-{{if or .AnalyticsWin.On .AnalyticsWin.HasData}}
-{{with .AnalyticsWin}}
+{{/* The period row is part of what refreshes: a page left open across
+ midnight must name the day its numbers are for. */}}
+{{with .AnalyticsLive}}{{if and .Win (or .Win.On .Win.HasData)}}
+<div class="an-live" data-live="{{.Src}}">{{template "analyticsdata" .}}</div>
+{{template "analyticsscript"}}
+{{else}}{{template "analyticsnav" .}}{{end}}{{end}}
+{{template "bottom" .}}{{end}}
+
+{{/* 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">
+ {{/* 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}}{{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}}
+
+{{define "analyticsdata"}}{{if not .Card}}{{template "analyticsnav" .}}{{end}}{{with .Win}}
{{template "trafficfigures" .}}
{{if .Chart}}
{{template "trafficchart" .Chart}}
@@ -42,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">
@@ -58,16 +76,71 @@ 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">Times are UTC. The same view from a terminal: <code>carlos analytics --app {{.AppName}} --range {{.AnalyticsRange}}</code>.</p>
+<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}}
+<p class="small">Traffic is still loading. Reload this page, or check the <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">Analytics</a> tab.</p>
+{{else}}{{with .Win}}
+{{if or .On .HasData}}
+{{template "trafficfigures" .}}
+{{if .Chart}}{{template "trafficchart" .Chart}}{{else}}<p class="an-empty">No page views in the last 7 days.</p>{{end}}
+{{if not .On}}<p class="small">Analytics is off for this app. These are the numbers counted while it was on.</p>{{end}}
+{{else}}
+<p class="small">Analytics is off for this app. Turn it on from the <a href="{{$.Nav}}/apps/{{$.AppName}}/analytics">Analytics</a> tab to see page views and visitors here.</p>
+{{end}}
+{{else}}
+<p class="small">Traffic could not be read just now. Check the <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">Analytics</a> tab.</p>
+{{end}}{{end}}
{{end}}
-{{template "bottom" .}}{{end}}
{{/* The three numbers a reader came for, then the chart. Visitors are
estimated per day, so a multi-day total is a sum of days and says so. */}}
@@ -80,7 +153,7 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
<div>
<dt>Visitors</dt>
<dd>{{count .Sum.Visitors}}</dd>
- <dd class="an-note">{{if eq .Range "today"}}Estimated.{{else}}Daily visitors are added up. One person seen on two days counts twice.{{end}}</dd>
+ <dd class="an-note">{{if eq .Range "today" "day"}}Estimated.{{else}}Daily visitors are added up. One person seen on two days counts twice.{{end}}</dd>
</div>
<div>
<dt>Data served</dt>
@@ -109,41 +182,109 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
<div class="an-plot">
<div class="an-grid" aria-hidden="true">{{range .Ticks}}<span style="bottom: {{.Pct}}%"><i>{{.Label}}</i></span>{{end}}</div>
<div class="an-cols" role="group" aria-label="Page views per {{.Unit}}">
- {{range .Cols}}{{if .Future}}<span class="an-col an-future" aria-hidden="true"></span>{{else}}<button type="button" class="an-col{{if .Partial}} an-partial{{end}}{{if .Gap}} an-gap{{end}}{{if .Edge}} an-edge-{{.Edge}}{{end}}" aria-label="{{.Label}}"><span class="an-bar" style="height: {{.HPct}}%"><span class="an-tip" aria-hidden="true"><b>{{index .Lines 0}}</b>{{range $i, $l := .Lines}}{{if $i}}<span>{{$l}}</span>{{end}}{{end}}<span class="an-when">{{.When}}</span></span></span></button>{{end}}{{end}}
+ {{range .Cols}}{{if .Future}}<span class="an-col an-future" aria-hidden="true"></span>{{else if .Href}}<a class="an-col{{if .Partial}} an-partial{{end}}{{if .Gap}} an-gap{{end}}{{if .Edge}} an-edge-{{.Edge}}{{end}}" href="{{.Href}}" aria-label="{{.Label}}">{{template "chartbar" .}}</a>{{else}}<button type="button" class="an-col{{if .Partial}} an-partial{{end}}{{if .Gap}} an-gap{{end}}{{if .Edge}} an-edge-{{.Edge}}{{end}}" aria-label="{{.Label}}">{{template "chartbar" .}}</button>{{end}}{{end}}
</div>
</div>
<div class="an-xaxis" aria-hidden="true">{{range .XLabels}}<span style="grid-column: {{.Col}}">{{.Label}}</span>{{end}}</div>
</figure>
-<script>
+{{end}}
+
+{{define "chartbar"}}<span class="an-bar" style="height: {{.HPct}}%"><span class="an-tip" aria-hidden="true"><b>{{index .Lines 0}}</b>{{range $i, $l := .Lines}}{{if $i}}<span>{{$l}}</span>{{end}}{{end}}<span class="an-when">{{.When}}</span></span></span>{{end}}
+
+{{/* One script per page, after its charts: arrow keys between a chart's
+ columns, and the minute refresh of every [data-live] part. A refresh
+ waits while a pointer is over the part or focus is in it, pauses while
+ the page is hidden, and stops after 30 minutes with no input, until
+ the next one. A refreshed part is used only if the live door answered
+ it (X-Carlos-Live), so a lapsed session never pastes a sign-in page in. */}}
+{{define "analyticsscript"}}<script>
(function () {
- // Arrow keys move between columns, Home and End jump, Escape closes. The
- // group is one Tab stop: the focused column is the only one with
- // tabindex 0. Pointer hover and tap need nothing here; CSS shows the tip.
- var groups = document.querySelectorAll(".an-cols:not([data-an])");
- groups.forEach(function (g) {
- g.setAttribute("data-an", "");
- var cols = Array.prototype.slice.call(g.querySelectorAll("button.an-col"));
- if (!cols.length) return;
- cols.forEach(function (c, i) { c.tabIndex = i === cols.length - 1 ? 0 : -1; });
- g.addEventListener("keydown", function (e) {
- var i = cols.indexOf(document.activeElement);
- if (i < 0) return;
- var j = i;
- if (e.key === "ArrowRight") j = Math.min(cols.length - 1, i + 1);
- else if (e.key === "ArrowLeft") j = Math.max(0, i - 1);
- else if (e.key === "Home") j = 0;
- else if (e.key === "End") j = cols.length - 1;
- else if (e.key === "Escape") { cols[i].blur(); return; }
- else return;
- e.preventDefault();
- cols[i].tabIndex = -1;
- cols[j].tabIndex = 0;
- cols[j].focus();
+ function initCharts(root) {
+ root.querySelectorAll(".an-cols:not([data-an])").forEach(function (g) {
+ g.setAttribute("data-an", "");
+ var cols = Array.prototype.slice.call(g.querySelectorAll(".an-col:not(.an-future)"));
+ if (!cols.length) return;
+ cols.forEach(function (c, i) { c.tabIndex = i === cols.length - 1 ? 0 : -1; });
+ g.addEventListener("keydown", function (e) {
+ var i = cols.indexOf(document.activeElement);
+ if (i < 0) return;
+ var j = i;
+ if (e.key === "ArrowRight") j = Math.min(cols.length - 1, i + 1);
+ else if (e.key === "ArrowLeft") j = Math.max(0, i - 1);
+ else if (e.key === "Home") j = 0;
+ else if (e.key === "End") j = cols.length - 1;
+ else if (e.key === "Escape") { cols[i].blur(); return; }
+ else return;
+ e.preventDefault();
+ cols[i].tabIndex = -1;
+ cols[j].tabIndex = 0;
+ cols[j].focus();
+ });
});
+ }
+ // 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();
+ ["pointermove", "keydown", "scroll", "touchstart"].forEach(function (ev) {
+ window.addEventListener(ev, function () { lastInput = Date.now(); }, { passive: true });
+ });
+ function busy(el) { return el.matches(":hover") || el.contains(document.activeElement); }
+ function refresh() {
+ if (document.visibilityState !== "visible" || Date.now() - lastInput > 30 * 60 * 1000) return;
+ if (Date.now() - lastRun < 55000) return; // never closer than a minute, whatever asked
+ lastRun = Date.now();
+ document.querySelectorAll("[data-live]").forEach(function (el) {
+ if (busy(el)) return;
+ fetch(el.getAttribute("data-live"), { credentials: "same-origin", redirect: "manual" })
+ .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 () {});
+ });
+ }
+ setInterval(refresh, 60000);
+ document.addEventListener("visibilitychange", function () {
+ if (document.visibilityState === "visible") refresh();
});
})();
-</script>
-{{end}}
+</script>{{end}}
{{define "sharelist"}}{{if .}}<ol class="an-share">{{range .}}<li{{if .Muted}} class="an-muted"{{end}}>
<span class="an-key" title="{{.Key}}">{{if .Flag}}<span class="an-flag" aria-hidden="true">{{.Flag}}</span>{{end}}{{.Label}}</span>
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html
index 9429cf1f6..965b79ebc 100644
--- a/internal/console/templates/app_overview.html
+++ b/internal/console/templates/app_overview.html
@@ -71,19 +71,8 @@
<h2 id="an-overview-head">Traffic, last 7 days</h2>
<a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">View analytics</a>
</div>
- {{if .TrafficSlow}}
- <p class="small">Traffic is still loading. Reload this page, or check the <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">Analytics</a> tab.</p>
- {{else}}{{with .Traffic}}
- {{if or .On .HasData}}
- {{template "trafficfigures" .}}
- {{if .Chart}}{{template "trafficchart" .Chart}}{{else}}<p class="an-empty">No page views in the last 7 days.</p>{{end}}
- {{if not .On}}<p class="small">Analytics is off for this app. These are the numbers counted while it was on.</p>{{end}}
- {{else}}
- <p class="small">Analytics is off for this app. Turn it on from the <a href="{{$.Nav}}/apps/{{$.AppName}}/analytics">Analytics</a> tab to see page views and visitors here.</p>
- {{end}}
- {{else}}
- <p class="small">Traffic could not be read just now. Check the <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">Analytics</a> tab.</p>
- {{end}}{{end}}
+ {{with .TrafficLive}}<div class="an-live" data-live="{{.Src}}">{{template "trafficcard" .}}</div>
+ {{template "analyticsscript"}}{{end}}
</section>
{{/* The legacy safety-delay flag: legacy-path-only, exactly as ladder.html
skips this same block in pipeline mode. A pipelined app's bake story is
diff --git a/internal/console/templates/billing.html b/internal/console/templates/billing.html
index bc195aff5..06a195640 100644
--- a/internal/console/templates/billing.html
+++ b/internal/console/templates/billing.html
@@ -19,9 +19,17 @@
</ul>{{end}}
</div>
{{if .Includes}}<ul class="billing-includes">
- {{range .Includes}}<li>{{icon "check"}}<span>{{.}}</span></li>
+ {{range .Includes}}<li>{{icon "check"}}<span>{{.Text}}</span></li>
{{end}}
</ul>{{end}}
+ {{/* The usage, here only when no pack row carries it (billingusage.go). */}}
+ {{with .Usage}}{{if .Rows}}<div class="billing-usage">
+ <dl>
+ {{range .Rows}}<div><dt>{{.Label}}</dt><dd class="use{{if .Use.Level}} use-{{.Use.Level}}{{end}}">{{.Use.Text}}</dd></div>
+ {{end}}
+ </dl>
+ <p class="small usage-asof">{{.AsOf}}</p>
+ </div>{{end}}{{end}}
</section>
{{/* The offered actions, in decideBillingPage's order. */}}
{{range .Actions}}
@@ -76,17 +84,20 @@
{{end}}</span>
</p>
{{if .Includes}}<ul class="plan-incl" id="plan-{{.Name}}-incl">
- {{range .Includes}}<li>{{icon "check"}}<span>{{.}}</span></li>
+ {{range .Includes}}<li>{{icon "check"}}<span>{{.Text}}</span>{{with .Use}}<span class="small use{{if .Level}} use-{{.Level}}{{end}}">{{.Text}}</span>{{end}}</li>
{{end}}
</ul>{{end}}
</div>
{{end}}</fieldset>
- {{if .Packs}}<h3 id="packs-title">{{billingText "packs.title"}}</h3>
+ {{if .Packs}}<div class="packs-head">
+ <h3 id="packs-title">{{billingText "packs.title"}}</h3>
+ {{with $.Billing.Usage}}{{if not .Rows}}<p class="small usage-asof">{{.AsOf}}</p>{{end}}{{end}}
+ </div>
<p class="small">{{billingText "packs.lede"}}</p>
<div class="tablewrap">
<table class="packs" aria-labelledby="packs-title">
{{range .Packs}}<tr data-pack="{{.Name}}">
- <td><label for="pack-{{.Name}}">{{.Label}}</label>{{if .Adds}}<span class="small" id="pack-{{.Name}}-adds">{{.Adds}}</span>{{end}}</td>
+ <td><label for="pack-{{.Name}}">{{.Label}}</label>{{if .Adds}}<span class="small" id="pack-{{.Name}}-adds">{{.Adds}}</span>{{end}}{{with .Use}}<span class="small use{{if .Level}} use-{{.Level}}{{end}}">{{.Text}}</span>{{end}}</td>
<td><input type="number" id="pack-{{.Name}}" name="pack_{{.Name}}" min="0" max="{{.Max}}" step="1" value="{{.Value}}" inputmode="numeric" data-select{{if .Adds}} aria-describedby="pack-{{.Name}}-adds"{{end}}></td>
<td>{{range .Prices}}<span class="small price price-{{.Code}}" data-currency="{{.Code}}">{{.Text}}</span>
{{end}}</td>
@@ -100,11 +111,14 @@
</form>
{{end}}{{end}}
{{if eq . "change"}}{{with $.Billing.Change}}
-{{if .Packs}}<h2 id="packs-title">{{billingText "packs.title"}}</h2>
+{{if .Packs}}<div class="sectionhead packs-head">
+ <h2 id="packs-title">{{billingText "packs.title"}}</h2>
+ {{with $.Billing.Usage}}{{if not .Rows}}<p class="small usage-asof">{{.AsOf}}</p>{{end}}{{end}}
+</div>
<div class="tablewrap">
<table class="packs packs-change" aria-labelledby="packs-title">
- {{range .Packs}}<tr>
- <td><label for="change-{{.Name}}">{{.Label}}</label>{{if .Adds}}<span class="small" id="change-{{.Name}}-adds">{{.Adds}}</span>{{end}}</td>
+ {{range .Packs}}<tr data-pack="{{.Name}}">
+ <td><label for="change-{{.Name}}">{{.Label}}</label>{{if .Adds}}<span class="small" id="change-{{.Name}}-adds">{{.Adds}}</span>{{end}}{{with .Use}}<span class="small use{{if .Level}} use-{{.Level}}{{end}}">{{.Text}}</span>{{end}}</td>
<td class="small">{{.Price}}</td>
<td><form method="post" action="{{$.Base}}/billing/change">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index ac5827eeb..29279a610 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -653,8 +653,9 @@
.plan-card:has(input:checked) .plan-incl { border-top-color: var(--accent-soft); }
/* Packs: one row each, the name and what one adds, a quantity, a price.
The quantity box is wide enough for its maximum and steps by one. */
- .buy h3 { margin: 0 0 0.2rem; }
- .buy h3 + .small { margin: 0 0 0.75rem; }
+ .buy h3 { margin: 0; }
+ .buy .packs-head { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 0.2rem 1rem; margin: 0 0 0.2rem; }
+ .buy .packs-head + .small { margin: 0 0 0.75rem; }
table.packs { margin: 0; }
.packs tr:first-child td { border-top: 1px solid var(--rule); }
.packs td { padding: 0.75rem 1.25rem 0.75rem 0; vertical-align: middle; }
@@ -673,6 +674,30 @@
}
.packs input[type=number]:hover { border-color: var(--ink); }
.packs input[type=number]:focus-visible { border-color: var(--accent); outline: 2px solid var(--accent); outline-offset: 1px; }
+ /* Usage beside a limit (billingusage.go), as the plan-limits pass last
+ measured it: quiet figures in the muted ink. From 80% of the limit the
+ figure takes the ink and a warn dot; past it, the bad ink and a bad
+ dot. The weight and the dot carry it as well as the colour. */
+ .use { font-variant-numeric: tabular-nums; }
+ .use-warn, .use-over { font-weight: 600; }
+ .use-warn { color: var(--ink); }
+ .use-over { color: var(--bad); }
+ .use-warn::before, .use-over::before {
+ content: ""; display: inline-block; width: 0.45rem; height: 0.45rem; margin: 0 0.4rem 0.1em 0;
+ border-radius: 50%; background: var(--warn); vertical-align: middle;
+ }
+ .use-over::before { background: var(--bad); }
+ .packs td:first-child .use { margin-top: 0.15rem; }
+ .plan-incl .use { margin-left: auto; padding-left: 0.5rem; white-space: nowrap; }
+ .usage-asof { margin: 0; }
+ .packs-head .usage-asof { font-size: 0.82rem; }
+ /* The summary's usage, when no pack row carries it: a row of figures
+ under the plan, its as-of line beneath. */
+ .billing-usage { flex: 1 1 100%; padding: 0.9rem 0 0; border-top: 1px solid var(--rule); }
+ .billing-usage dl { display: flex; flex-wrap: wrap; gap: 0.6rem 2.75rem; margin: 0 0 0.6rem; }
+ .billing-usage dt { font-size: 0.82rem; color: var(--muted); }
+ .billing-usage dd { margin: 0; font-size: 0.95rem; }
+ .billing-usage .usage-asof { font-size: 0.82rem; }
/* Analytics (app_analytics.html, and the Overview's traffic card). The
chart is the page's one loud element; everything around it stays in
@@ -687,6 +712,8 @@
.an-range a[aria-current="page"] { color: var(--ink); background: var(--accent-soft); font-weight: 600; }
.an-range a:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.an-span { margin-left: 0.75rem; color: var(--muted); font-size: 0.85rem; }
+ .an-daynav { display: inline-flex; gap: 0.25rem; margin-left: 0.5rem; }
+ .an-daynav a { font-size: 0.85rem; }
.an-figures { display: flex; flex-wrap: wrap; gap: 1rem 3.5rem; margin: 0 0 1.5rem; }
.an-figures dt { color: var(--muted); font-size: 0.9rem; }
.an-figures dd { margin: 0; font-size: 2.25rem; font-weight: 600; line-height: 1.15; letter-spacing: -0.01em; }
@@ -716,13 +743,16 @@
height: 100%; padding: 0 1px; margin: 0; border: 0; border-radius: 0.25rem;
background: transparent; color: inherit; font: inherit; cursor: default;
}
- button.an-col:hover, button.an-col:focus-visible { background: var(--accent-soft); }
- button.an-col:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
+ .an-col:not(.an-future):hover, .an-col:not(.an-future):focus-visible { background: var(--accent-soft); }
+ .an-col:not(.an-future):focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
+ /* A day on a daily chart is a link to that day; it reads as the column,
+ not as underlined text. */
+ a.an-col { text-decoration: none; cursor: pointer; }
.an-bar {
position: relative; display: block; width: 100%; max-width: 24px; min-height: 0;
background: var(--accent); border-radius: 4px 4px 0 0;
}
- button.an-col:hover .an-bar, button.an-col:focus-visible .an-bar { background: var(--accent-strong); }
+ .an-col:hover .an-bar, .an-col:focus-visible .an-bar { background: var(--accent-strong); }
/* The hour or day still being counted: the same hue, hatched, because the
bar will still grow. (No percentages in this sheet's own rules: the
metrics boundary tests read every "NN%" on an app page as a reading.) */
@@ -743,7 +773,10 @@
.an-tip .an-when { opacity: 0.75; margin-top: 0.15rem; }
.an-edge-start .an-tip { left: 0; transform: none; }
.an-edge-end .an-tip { left: auto; right: 0; transform: none; }
- button.an-col:hover .an-tip, button.an-col:focus .an-tip { display: block; }
+ .an-col:hover .an-tip, .an-col:focus .an-tip { display: block; }
+ /* One tooltip at a time: while the pointer is over the chart, only the
+ column under it speaks, not one left focused by an earlier click. */
+ .an-cols:hover .an-col:focus:not(:hover) .an-tip { display: none; }
/* The tip is the bar's child, so it opens just above the bar's top,
where the eye already is, and never covers the bar it describes. */
.an-future { cursor: default; }
@@ -766,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/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 6366076e0..f750d19fb 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -18,6 +18,7 @@ route GET /a/{sqid}/apps/{app}
route GET /a/{sqid}/apps/{app}/account-review
route GET /a/{sqid}/apps/{app}/activity
route GET /a/{sqid}/apps/{app}/analytics
+route GET /a/{sqid}/apps/{app}/analytics/live
route GET /a/{sqid}/apps/{app}/availability
route GET /a/{sqid}/apps/{app}/deployments
route GET /a/{sqid}/apps/{app}/errors
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt
index 6443fbadd..a2b47649e 100644
--- a/internal/console/testdata/perf-budgets.txt
+++ b/internal/console/testdata/perf-budgets.txt
@@ -63,6 +63,7 @@ GET /a/{sqid}/apps/{app}/logs/data deferred: deferred part (the Logs tab's data
# (appframe.go); the account manifest is read once per process. A cold view
# (perfColdReset) reads both: 7 S3 calls, about 80 ms.
/fleet/architecture calls 12: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (12 S3 calls warm and cold, about 390 ms)
+GET /a/{sqid}/apps/{app}/analytics/live calls 2: the live door the Analytics tab and Overview card refresh from once a minute: both telemetry settings, read on every refresh so an owner turning analytics on sees it at once; the window's counts come from the traffic memo, read at most once a minute per app and view (about 50 ms)
GET /a/{sqid}/apps/{app}/analytics calls 4: both telemetry settings, the analytics day listing and one day read (about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 190 ms)
GET /a/{sqid}/apps/{app}/availability calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms)
GET /a/{sqid}/apps/{app}/errors calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms)
diff --git a/internal/provision/analytics_live_census_test.go b/internal/provision/analytics_live_census_test.go
new file mode 100644
index 000000000..034c065ba
--- /dev/null
+++ b/internal/provision/analytics_live_census_test.go
@@ -0,0 +1,31 @@
+package provision
+
+// Record-write census entry for analytics-live (the Analytics tab's live
+// refresh and day view), layered on rootfsFleetFollowupsWriteCensusInventory
+// (main's newest at d3908d93). Reviewed by the branch author. No record write
+// is added, moved or reclassified:
+// - NewServer: registers GET /a/{sqid}/apps/{app}/analytics/live
+// (analyticslive.go), which reads the app's telemetry setting and its
+// analytics day files and renders HTML; it writes nothing. Same
+// "instances" literal: still key-site.
+func analyticsLiveWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), rootfsFleetFollowupsWriteCensusInventory()...)
+ replacements := []censusEntry{
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "d33dc8423332f17c4a02a02d3c8a42a23621b3dfdbdddf5f34a905c3cd2fd7ae"},
+ }
+ for _, r := range replacements {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("analytics-live replacement reclassifies " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("analytics-live replacement of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 0098f6133..506eb1f19 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := rootfsFleetFollowupsWriteCensusInventory()
+ inventory := analyticsLiveWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
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 8822f252f..12f796b46 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -38,4 +38,5 @@ 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
plan14-root-reads-region-ha-dead-holder-backoff.tsv 8f6a1865b0abcea9d4fb68232cc2a25263a106ec87f73bd4b3f2fb388971ebe5