Console Analytics tab overhaul and an Overview traffic card. The tab leads with page views, visitors and data served in decimal units; the chart is HTML columns with tooltips on hover, focus and tap (arrow keys move), future hours undrawn and the current period hatched; busiest hour or day and the full-day average under it; pages, referrers, countries (names and flags) and events as share lists; one restart note. Overview gains Traffic, last 7 days, waiting at most 300 ms from request start (perf.Started), counts held 60 s. Analytics day files go through the settled-day cache and are read concurrently: a warm 30-day view reads 2 files per box, not 30. Perf session S3 ceiling 401 to 415 and the region-label baseline name the card's reads. Reviews: Astra UX suggestions; Luna copy pass; Astra R1 NOT READY (1 P1, 4 P2) fixed, R2 READY AFTER FIXES, 2 P2 fixed; census clean. Approved by Paul from the preview, 2026-10-29. Not released.
Squashed from console-analytics-ui into main.
20 files changed,
+1,811
−162
docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R1.md+18 −0docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R2.md+21 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-analytics-ui-R2.md+93 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-analytics-ui.md+81 −0internal/console/analytics_onramp_test.go+11 −8internal/console/analyticsdisplay.go+466 −0internal/console/analyticsdisplay_test.go+334 −0internal/console/analyticsview.go+144 −104internal/console/apianalytics_test.go+8 −5internal/console/appnav_test.go+3 −3internal/console/countrynames.go+278 −0internal/console/regionbudget_test.go+8 −5internal/console/server.go+48 −0internal/console/templates/app_analytics.html+123 −33internal/console/templates/app_overview.html+22 −0internal/console/templates/layout.html+109 −0internal/console/testdata/perf-session-s3.txt+1 −1internal/console/usagedays.go+16 −3internal/perf/middleware.go+10 −0internal/perf/middleware_test.go+17 −0
CI failed — run details
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R1.md| new file mode 100644 |
| index 000000000..3a69eaaad |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R1.md |
| @@ -0,0 +1,18 @@ |
| +1. **P1 — CI: chart tests fail before noon UTC.** |
| + [seedTime](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/apianalytics_test.go:124) seeds today’s traffic at noon. The new chart excludes future hours and returns nil when no past hour has traffic ([analyticsdisplay.go:113](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/analyticsdisplay.go:113)). Before noon, `TestAppAnalyticsPage` and `TestAnalyticsTabOffStateKeepsCountedData` therefore fail their chart assertions. **Fix:** seed an elapsed hour or inject a fixed clock shared by fixtures and handlers. **Fault family:** time-independent test fixtures. Verified by tracing the code; HTTP execution was blocked by sandbox socket restrictions. |
| + |
| +2. **P2 — Overview: the traffic card can delay the entire page by two seconds.** |
| + The handler unconditionally waits at [server.go:4243](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/server.go:4243), before rendering. If other reads finish quickly but analytics stalls, the page waits for its two-second timeout, exceeding the stated GET budgets. The comment that only the card is delayed is false. **Fix:** bound the wait within the page’s remaining latency budget and render the unavailable state on timeout. **Fault family:** optional data must respect page latency limits. |
| + |
| +3. **P2 — Missing-count message uses the wrong unit.** |
| + [app_analytics.html:97](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/templates/app_analytics.html:97) describes `Dropped.Flush` as missing page views. [Meter.Requeue](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/analytics/meter.go:265) increments it once per discarded delta batch. Losing a batch containing 1,000 views produces “1 page view … missing”; an events-only batch can produce the same message. **Fix:** describe discarded batches and leave the lost page-view count unspecified. **Fault family:** displayed units must match stored counters. |
| + |
| +4. **P2 — Bot exclusion message incorrectly includes data served.** |
| + [app_analytics.html:96](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/templates/app_analytics.html:96) says bot requests are excluded from “these numbers,” but [meter.go:178](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/analytics/meter.go:178) includes their bytes. For example, the existing fixture’s bot contributes 500 bytes to data served. **Fix:** scope the exclusion statement to page views and visitors. **Fault family:** displayed claims must match aggregation semantics. |
| + |
| +5. **P2 — Restart notes promise an unsupported five-minute loss bound.** |
| + [analyticsdisplay.go:452](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/analyticsdisplay.go:452) and the chart tooltip say at most about five minutes may be missing. A failed flush is retained for retry; restarting before that retry loses both that batch and newly accumulated traffic. Multiple restarts can lose further windows. **Fix:** describe unsaved counts without a five-minute upper bound, including in tooltips. **Fault family:** loss warnings must reflect retry and restart behavior. |
| + |
| +Twelve targeted arithmetic/cache tests passed. HTTP tests compiled but could not execute because listening sockets are prohibited. No full suites or cross-platform builds ran. No files were edited; the working tree remains clean. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R2.md| new file mode 100644 |
| index 000000000..d301d9093 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R2.md |
| @@ -0,0 +1,21 @@ |
| +Round-one findings: |
| + |
| +- P1, before-noon chart tests: **resolved**. |
| +- P2, Overview latency: **partly resolved**, carried forward below. |
| +- P2, missing-count units: **resolved**. |
| +- P2, bot exclusion claim: **resolved**. |
| +- P2, five-minute loss bound: **resolved**. |
| + |
| +1. **P2 — Overview still waits beyond the page’s remaining budget.** |
| + [server.go:4248](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/server.go:4248) starts an additional 250 ms wait after other page work finishes. A cold page otherwise ready at 400 ms can therefore take 650 ms, exceeding its 500 ms budget. The [new test:286](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/analyticsdisplay_test.go:286) only rejects durations above two seconds. |
| + **Fix:** enforce one deadline measured from request start, reserve rendering time, and test the remaining-budget case. **Fault family:** optional data must respect page latency limits. This family remains outstanding for a second round; central enforcement with a guard test is the recommended cut. |
| + |
| +2. **P2 — “Busiest hour so far” can name a future hour.** |
| + [analyticsdisplay.go:187](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/analyticsdisplay.go:187) searches all 24 hours, while the chart excludes future hours. With an ahead-of-time box clock, the insight can name an hour absent from the chart. The passing [test:142](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui/internal/console/analyticsdisplay_test.go:142) explicitly expects 14:00 as busiest at 10:00. |
| + **Fix:** exclude hours after the current UTC hour for today, matching the chart; correct the test expectation. **Fault family:** chart and insight must use the same eligible time window. |
| + |
| +No P1 findings. Eleven targeted arithmetic/cache tests passed. HTTP-backed tests were blocked by prohibited listening sockets, including the analytics cache witness. No full suites or cross-platform builds ran. No files were edited. |
| + |
| +Fix the P2s without reopening review. |
| + |
| +**READY AFTER FIXES** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-analytics-ui-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-analytics-ui-R2.md| new file mode 100644 |
| index 000000000..b71cff56e |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-analytics-ui-R2.md |
| @@ -0,0 +1,93 @@ |
| +# Review brief: branch console-analytics-ui, round 2 of 3 |
| + |
| +Repo carlos/platform, branch `console-analytics-ui`, commit 5de6a68c3ecefcfe4c060f09e8a43abf847c2472. |
| +Under review: the diff `803c6800..5de6a68c` (internal/console only). |
| +Authorities: the errors and analytics design |
| +(docs/superpowers/specs/2026-09-07-errors-and-analytics-design.md, if |
| +present on main), the console UX and perf work (150 ms warm / 500 ms cold |
| +GET budgets), AGENTS.md (stopping rules, request-cost rules). Do not |
| +review against unmerged branches. |
| + |
| +You are an independent reviewer. Read the diff, then the code it calls, |
| +and check every claim in comments and in the commit message against that |
| +code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul asked for: a UI overhaul of the Analytics tab, an analytics preview |
| + on the Overview tab, tooltips on the bar chart, country names instead of |
| + codes, bytes in KB/MB/GB, and that it be very performant. |
| +- Copy has had a Luna pass on Paul's house rules (no em dashes, sentence |
| + case). Report copy only where it states something false. |
| +- The chart is HTML, not SVG, by design. The Overview card shows the |
| + 7-day window. |
| + |
| +## What to check |
| + |
| +1. The settled-day cache (internal/console/usagedays.go). usageDayDate now |
| + recognises analytics day keys (`apps/<sqid>/<app>/analytics/<box>/days/<date>.json`). |
| + Can a key a tenant or box can influence (app name, box label) be |
| + mistaken for another family's key, or another account's? Is the |
| + settled horizon (date+2) safe for analytics, given failed flushes are |
| + re-queued (internal/host/usage_loop.go, analytics.Meter.Requeue)? Did |
| + widening usageDayFirstKept change anything for the economics sweep? |
| +2. readAnalyticsRange runs analytics.ReadRange through readConcurrently |
| + (internal/console/hotreads.go) with a "{}" dry body. Does the dry pass |
| + ask for exactly the keys the real pass reads? Can an error, a timeout |
| + or an over-cap file now yield a silently wrong total rather than an |
| + error? Is TestAnalyticsReadsSettledDaysOnce a sound witness? |
| +3. handleApp (internal/console/server.go) now starts a goroutine for the |
| + traffic card. Leaks, races on the page struct, a request context used |
| + after the handler returns, and the worst-case added latency. |
| +4. Tenant boundary: the card and the tab read only the requesting |
| + account's app. Paths, referrers and event names are tenant- or |
| + visitor-controlled strings: check every place they reach the HTML |
| + (titles, aria-label, style attributes) is escaped by html/template, and |
| + that nothing visitor-controlled lands in a style or script context. |
| +5. Arithmetic in internal/console/analyticsdisplay.go: niceCeil, bar |
| + heights, share percentages, humanBytes rounding at unit boundaries, |
| + the average that excludes today, future and partial hours at the UTC |
| + day boundary, x-axis labels for 7 and 30 days. |
| +6. The inline keyboard script in app_analytics.html: correct when two |
| + charts are on one page, harmless without JavaScript. |
| +7. Anything in the diff that would fail CI (darwin and windows builds |
| + included) or break an existing test that I did not update. |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: round 1, docs/superpowers/reviews/CODEX-FINDINGS-console-analytics-ui-R1.md |
| +(1 P1, 4 P2; fixes in commit 5de6a68c). |
| + |
| +First give one line per P1 and P2 from round 1: resolved, partly, or not. |
| +Carry every unresolved or partly resolved finding forward at its current |
| +severity, then add new findings, looking hardest at the fix diff |
| +`933b227d..5de6a68c`. The verdict covers everything outstanding. HTTP tests |
| +need listening sockets; if your sandbox forbids them, say so rather than |
| +guessing. |
| + |
| +## 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 -run` on |
| +internal/console is fine. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-analytics-ui.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-analytics-ui.md| new file mode 100644 |
| index 000000000..301812198 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-analytics-ui.md |
| @@ -0,0 +1,81 @@ |
| +# Review brief: branch console-analytics-ui, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `console-analytics-ui`, commit 40fbb508c0148fd84ac407c3c6b6d8a10b81f5e1. |
| +Under review: the diff `803c6800..40fbb508` (internal/console only). |
| +Authorities: the errors and analytics design |
| +(docs/superpowers/specs/2026-09-07-errors-and-analytics-design.md, if |
| +present on main), the console UX and perf work (150 ms warm / 500 ms cold |
| +GET budgets), AGENTS.md (stopping rules, request-cost rules). Do not |
| +review against unmerged branches. |
| + |
| +You are an independent reviewer. Read the diff, then the code it calls, |
| +and check every claim in comments and in the commit message against that |
| +code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul asked for: a UI overhaul of the Analytics tab, an analytics preview |
| + on the Overview tab, tooltips on the bar chart, country names instead of |
| + codes, bytes in KB/MB/GB, and that it be very performant. |
| +- Copy has had a Luna pass on Paul's house rules (no em dashes, sentence |
| + case). Report copy only where it states something false. |
| +- The chart is HTML, not SVG, by design. The Overview card shows the |
| + 7-day window. |
| + |
| +## What to check |
| + |
| +1. The settled-day cache (internal/console/usagedays.go). usageDayDate now |
| + recognises analytics day keys (`apps/<sqid>/<app>/analytics/<box>/days/<date>.json`). |
| + Can a key a tenant or box can influence (app name, box label) be |
| + mistaken for another family's key, or another account's? Is the |
| + settled horizon (date+2) safe for analytics, given failed flushes are |
| + re-queued (internal/host/usage_loop.go, analytics.Meter.Requeue)? Did |
| + widening usageDayFirstKept change anything for the economics sweep? |
| +2. readAnalyticsRange runs analytics.ReadRange through readConcurrently |
| + (internal/console/hotreads.go) with a "{}" dry body. Does the dry pass |
| + ask for exactly the keys the real pass reads? Can an error, a timeout |
| + or an over-cap file now yield a silently wrong total rather than an |
| + error? Is TestAnalyticsReadsSettledDaysOnce a sound witness? |
| +3. handleApp (internal/console/server.go) now starts a goroutine for the |
| + traffic card. Leaks, races on the page struct, a request context used |
| + after the handler returns, and the worst-case added latency. |
| +4. Tenant boundary: the card and the tab read only the requesting |
| + account's app. Paths, referrers and event names are tenant- or |
| + visitor-controlled strings: check every place they reach the HTML |
| + (titles, aria-label, style attributes) is escaped by html/template, and |
| + that nothing visitor-controlled lands in a style or script context. |
| +5. Arithmetic in internal/console/analyticsdisplay.go: niceCeil, bar |
| + heights, share percentages, humanBytes rounding at unit boundaries, |
| + the average that excludes today, future and partial hours at the UTC |
| + day boundary, x-axis labels for 7 and 30 days. |
| +6. The inline keyboard script in app_analytics.html: correct when two |
| + charts are on one page, harmless without JavaScript. |
| +7. Anything in the diff that would fail CI (darwin and windows builds |
| + included) or break an existing test that I did not update. |
| + |
| +## 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 -run` on |
| +internal/console is fine. |
diff --git a/internal/console/analytics_onramp_test.go b/internal/console/analytics_onramp_test.go| index 523e17858..b348be4dd 100644 |
| --- a/internal/console/analytics_onramp_test.go |
| +++ b/internal/console/analytics_onramp_test.go |
| @@ -26,9 +26,12 @@ const ( |
| onrampMemberOff = "An account owner can turn on analytics." |
| ) |
| -// onrampDataMarkers are the tab's data sections: the summary table, the |
| -// top-keys tables' empty rows, and the terminal hint under them. |
| -var onrampDataMarkers = []string{"<th>Page views</th>", "Nothing yet.", "<h3>Top pages", "carlos analytics --app titogo"} |
| +// onrampDataMarkers are the tab's data sections: the headline figures, the |
| +// breakdown lists' empty rows, and the terminal hint under them. |
| +var onrampDataMarkers = []string{"<dt>Page views</dt>", "Nothing yet.", ">Top pages</h3>", "carlos analytics --app titogo"} |
| + |
| +// onrampRangePicker is the period picker, which shows in every state. |
| +const onrampRangePicker = `<nav class="an-range" aria-label="Period">` |
| func TestAnalyticsTabOffStateOwner(t *testing.T) { |
| fx, _ := instanceFixture(t, "code-onramp-tab-owner") |
| @@ -79,7 +82,7 @@ func TestAnalyticsTabOffStateOwner(t *testing.T) { |
| if strings.Contains(body, onrampOffLead) || strings.Contains(body, onrampTurnOn) { |
| t.Error("the off state still shows after turning on") |
| } |
| - for _, want := range append([]string{`<form method="get" class="toolbar">`}, onrampDataMarkers...) { |
| + for _, want := range append([]string{onrampRangePicker}, onrampDataMarkers...) { |
| if !strings.Contains(body, want) { |
| t.Errorf("on: the tab is missing the data section %q", want) |
| } |
| @@ -144,7 +147,7 @@ func TestAnalyticsTabOffStateKeepsRangePickerForOlderData(t *testing.T) { |
| c := newBrowser(t) |
| signUp(t, fx, c, "code-onramp-tab-older-browser") |
| _, _, body := get(t, c, fx.u("/apps/titogo/analytics")) |
| - for _, want := range []string{onrampOffLead, onrampTurnOn, `<form method="get" class="toolbar">`, `<option value="7d">`} { |
| + for _, want := range []string{onrampOffLead, onrampTurnOn, onrampRangePicker, `<a href="?range=7d">`} { |
| if !strings.Contains(body, want) { |
| t.Errorf("off, data only before today: default tab missing %q", want) |
| } |
| @@ -155,8 +158,8 @@ func TestAnalyticsTabOffStateKeepsRangePickerForOlderData(t *testing.T) { |
| } |
| } |
| _, _, body = get(t, c, fx.u("/apps/titogo/analytics?range=7d")) |
| - for _, want := range []string{onrampOffLead, `<form method="get" class="toolbar">`, `<option value="7d" selected>`, |
| - "<th>Page views</th>", "<td>5</td>", "/pricing"} { |
| + for _, want := range []string{onrampOffLead, onrampRangePicker, `<a href="?range=7d" aria-current="page">`, |
| + "<dt>Page views</dt>", "<dd>5</dd>", "/pricing"} { |
| if !strings.Contains(body, want) { |
| t.Errorf("?range=7d with older data: missing %q", want) |
| } |
| @@ -170,7 +173,7 @@ func TestAnalyticsTabOffStateKeepsCountedData(t *testing.T) { |
| c := newBrowser(t) |
| signUp(t, fx, c, "code-onramp-tab-data-browser") |
| _, _, body := get(t, c, fx.u("/apps/titogo/analytics")) |
| - for _, want := range []string{onrampOffLead, onrampTurnOn, "<th>Page views</th>", "/pricing", `aria-label="Page views"`} { |
| + for _, want := range []string{onrampOffLead, onrampTurnOn, "<dt>Page views</dt>", "/pricing", `aria-label="Page views per hour"`} { |
| if !strings.Contains(body, want) { |
| t.Errorf("off with counted data: missing %q", want) |
| } |
diff --git a/internal/console/analyticsdisplay.go b/internal/console/analyticsdisplay.go| new file mode 100644 |
| index 000000000..311ace7ff |
| --- /dev/null |
| +++ b/internal/console/analyticsdisplay.go |
| @@ -0,0 +1,466 @@ |
| +package console |
| + |
| +// What the Analytics tab and the Overview's traffic card draw from one |
| +// analyticsWindow: the chart's columns with their tooltips, the axis, the |
| +// two insight lines and the share rows of the breakdown tables. Everything |
| +// here is arithmetic on a Summary already read; nothing here reads the |
| +// store. |
| +// |
| +// The chart is HTML, not SVG. The old SVG scaled its viewBox to the column |
| +// it landed in, so its caption grew with the window (a 1,900 px wide page |
| +// drew 40 px text) and its one bar filled the plot. Columns in a CSS grid |
| +// keep text at text size at every width, and each column is a button, so |
| +// the tooltip is reachable by pointer, keyboard and touch alike. |
| + |
| +import ( |
| + "fmt" |
| + "math" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| +) |
| + |
| +// trafficChart is one plotted window: a column per hour (today) or per day. |
| +type trafficChart struct { |
| + Cols []chartCol |
| + Ticks []chartTick |
| + XLabels []chartXLabel |
| + // Unit is "hour" or "day", for the caption and the CSS. |
| + Unit string |
| +} |
| + |
| +// N is the column count, for the grid template. |
| +func (c *trafficChart) N() int { return len(c.Cols) } |
| + |
| +// chartCol is one column. HPct is the bar's height as a percentage of the |
| +// 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 { |
| + 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 |
| + Value int64 |
| + HPct float64 |
| + Partial bool // the current hour or today: still being counted |
| + Future bool // has not happened yet: no bar and no target |
| + Gap bool // the edge restarted that day: counts may be missing |
| + Edge string |
| +} |
| + |
| +// chartTick is one horizontal gridline, Pct up from the baseline. |
| +type chartTick struct { |
| + Pct float64 |
| + Label string |
| +} |
| + |
| +// chartXLabel names the column at Col (1-based, a grid column). |
| +type chartXLabel struct { |
| + Col int |
| + Label string |
| +} |
| + |
| +// buildTrafficChart lays out the window's page views. Nothing counted in the |
| +// window returns nil: the page says so in words rather than drawing a flat |
| +// line under an axis that tops out at one. |
| +func buildTrafficChart(rng string, sum analytics.Summary, now time.Time) *trafficChart { |
| + now = now.UTC() |
| + var c trafficChart |
| + if rng == rangeToday { |
| + c.Unit = "hour" |
| + if len(sum.Days) == 0 { |
| + return nil |
| + } |
| + d := sum.Days[len(sum.Days)-1] |
| + isToday := d.Date == now.Format("2006-01-02") |
| + date := shortDate(d.Date) |
| + for h := 0; h < 24; h++ { |
| + col := chartCol{Value: d.Hours[h]} |
| + col.Future = isToday && h > now.Hour() |
| + col.Partial = isToday && h == now.Hour() |
| + col.When = fmt.Sprintf("%s, %02d:00 to %02d:00 UTC", date, h, (h+1)%24) |
| + reading := plural(d.Hours[h], "page view", "page views") |
| + if col.Partial { |
| + reading += " so far" |
| + } |
| + col.Lines = []string{reading} |
| + c.Cols = append(c.Cols, col) |
| + } |
| + for _, h := range []int{0, 6, 12, 18} { |
| + c.XLabels = append(c.XLabels, chartXLabel{Col: h + 1, Label: fmt.Sprintf("%02d:00", h)}) |
| + } |
| + } else { |
| + 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.When = longDay(d.Date) |
| + pv := plural(d.PV, "page view", "page views") |
| + if col.Partial { |
| + pv += " so far" |
| + } |
| + col.Lines = []string{pv, plural(d.Visitors, "visitor", "visitors"), humanBytes(d.Bytes) + " served"} |
| + if d.Restarted { |
| + col.Lines = append(col.Lines, "The edge restarted that day. Some counts may be missing.") |
| + } |
| + c.Cols = append(c.Cols, col) |
| + } |
| + c.XLabels = dayXLabels(sum.Days) |
| + } |
| + var peak int64 |
| + for _, col := range c.Cols { |
| + if !col.Future && col.Value > peak { |
| + peak = col.Value |
| + } |
| + } |
| + if peak == 0 { |
| + return nil |
| + } |
| + top := niceCeil(peak) |
| + for i := range c.Cols { |
| + col := &c.Cols[i] |
| + if col.Value > 0 { |
| + col.HPct = round2(float64(col.Value) / float64(top) * 100) |
| + } |
| + col.Label = col.When + ": " + strings.Join(col.Lines, ", ") |
| + // The first and last few columns anchor their tooltip to that side, |
| + // so it never spills off the chart. |
| + switch n := len(c.Cols); { |
| + case i < n/6: |
| + col.Edge = "start" |
| + case i >= n-n/6: |
| + col.Edge = "end" |
| + } |
| + } |
| + c.Ticks = []chartTick{{Pct: 0, Label: "0"}, {Pct: 100, Label: compactCount(top)}} |
| + if top%2 == 0 { |
| + c.Ticks = []chartTick{c.Ticks[0], {Pct: 50, Label: compactCount(top / 2)}, c.Ticks[1]} |
| + } |
| + return &c |
| +} |
| + |
| +// dayXLabels labels a multi-day axis: every day of a week, every seventh day |
| +// of a month counted back from today, so today always carries its date. |
| +func dayXLabels(days []analytics.DaySummary) []chartXLabel { |
| + var out []chartXLabel |
| + if len(days) <= 7 { |
| + for i, d := range days { |
| + out = append(out, chartXLabel{Col: i + 1, Label: weekdayDay(d.Date)}) |
| + } |
| + return out |
| + } |
| + for i := len(days) - 1; i >= 0; i -= 7 { |
| + out = append([]chartXLabel{{Col: i + 1, Label: shortDate(days[i].Date)}}, out...) |
| + } |
| + return out |
| +} |
| + |
| +// niceCeil rounds v up to 1, 2, 4 or 5 times a power of ten: an axis top a |
| +// reader can halve in their head. |
| +func niceCeil(v int64) int64 { |
| + if v <= 1 { |
| + return 1 |
| + } |
| + pow := int64(math.Pow(10, math.Floor(math.Log10(float64(v))))) |
| + for _, m := range []int64{1, 2, 4, 5, 10} { |
| + if m*pow >= v { |
| + return m * pow |
| + } |
| + } |
| + return 10 * pow |
| +} |
| + |
| +// analyticsInsights is the line under the chart: the busiest hour or day, |
| +// and for a multi-day window the daily average over the days that are over. |
| +// Today is left out of the average because it is not over, and an average |
| +// that counts half a day reads as a drop. |
| +func analyticsInsights(rng string, sum analytics.Summary, now time.Time) []string { |
| + var out []string |
| + today := now.UTC().Format("2006-01-02") |
| + if rng == rangeToday { |
| + if len(sum.Days) == 0 { |
| + return nil |
| + } |
| + d := sum.Days[len(sum.Days)-1] |
| + best, at := int64(0), 0 |
| + for h, v := range d.Hours { |
| + // The chart's hours: none after the current one, which a box |
| + // with a fast clock could have written. |
| + if d.Date == today && h > now.UTC().Hour() { |
| + break |
| + } |
| + if v > best { |
| + best, at = v, h |
| + } |
| + } |
| + if best > 0 { |
| + lead := "Busiest hour" |
| + if d.Date == today { |
| + lead = "Busiest hour so far" |
| + } |
| + out = append(out, fmt.Sprintf("%s: %02d:00 UTC, with %s.", lead, at, plural(best, "page view", "page views"))) |
| + } |
| + return out |
| + } |
| + var best analytics.DaySummary |
| + var done, donePV int64 |
| + for _, d := range sum.Days { |
| + if d.PV > best.PV { |
| + best = d |
| + } |
| + if d.Date != today { |
| + done++ |
| + donePV += d.PV |
| + } |
| + } |
| + if best.PV > 0 { |
| + out = append(out, fmt.Sprintf("Busiest day: %s, with %s.", longDay(best.Date), plural(best.PV, "page view", "page views"))) |
| + } |
| + if done > 0 && donePV > 0 { |
| + out = append(out, fmt.Sprintf("An average of %s per day over the last %d full days.", averageViews(donePV, done), done)) |
| + } |
| + return out |
| +} |
| + |
| +// averageViews is a daily average worded for its size: one decimal under |
| +// ten, so two views over seven days is not "0 page views a day". |
| +func averageViews(total, days int64) string { |
| + avg := float64(total) / float64(days) |
| + if avg < 10 { |
| + s := strconv.FormatFloat(math.Round(avg*10)/10, 'f', -1, 64) |
| + if s == "1" { |
| + return "1 page view" |
| + } |
| + return s + " page views" |
| + } |
| + return plural(int64(math.Round(avg)), "page view", "page views") |
| +} |
| + |
| +// shareRow is one row of a breakdown table: what, how many, and its share |
| +// of the table's total. Bar is the row's length against the table's |
| +// biggest row, so the longest bar is always full width. |
| +type shareRow struct { |
| + Key string |
| + Label string |
| + Flag string |
| + Value int64 |
| + Share string |
| + Bar float64 |
| + Muted bool // "other" and "unknown": not a page, a referrer or a country |
| +} |
| + |
| +// shareRows orders m as sortedKV does and works out each row's share. |
| +// label turns a key into what the row says; nil shows the key. |
| +func shareRows(m map[string]int64, label func(string) (text, flag string, muted bool)) []shareRow { |
| + if len(m) == 0 { |
| + return nil |
| + } |
| + var total, top int64 |
| + for _, v := range m { |
| + total += v |
| + if v > top { |
| + top = v |
| + } |
| + } |
| + out := make([]shareRow, 0, len(m)) |
| + for _, kv := range sortedKV(m) { |
| + r := shareRow{Key: kv.Key, Label: kv.Key, Value: kv.Value} |
| + if label != nil { |
| + r.Label, r.Flag, r.Muted = label(kv.Key) |
| + } |
| + if total > 0 { |
| + r.Share = sharePct(kv.Value, total) |
| + } |
| + if top > 0 { |
| + r.Bar = round2(float64(kv.Value) / float64(top) * 100) |
| + } |
| + out = append(out, r) |
| + } |
| + return out |
| +} |
| + |
| +// sharePct is a share as a whole percentage, with "<1%" for a share that |
| +// rounds to nothing: a row that was counted never reads as 0%. |
| +func sharePct(v, total int64) string { |
| + p := float64(v) / float64(total) * 100 |
| + if p > 0 && p < 0.5 { |
| + return "<1%" |
| + } |
| + return strconv.Itoa(int(math.Round(p))) + "%" |
| +} |
| + |
| +// pageLabel words the overflow row of a pages or events table. |
| +func pageLabel(k string) (string, string, bool) { |
| + if k == analytics.OtherKey { |
| + return "Everything else", "", true |
| + } |
| + return k, "", false |
| +} |
| + |
| +// refererLabel words the referrers table: a page view with no Referer |
| +// header is counted as "direct". |
| +func refererLabel(k string) (string, string, bool) { |
| + switch k { |
| + case analytics.OtherKey: |
| + return "Everything else", "", true |
| + case "direct": |
| + return "Direct or unknown", "", true |
| + } |
| + return k, "", false |
| +} |
| + |
| +// 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) { |
| + switch k { |
| + case "_unknown": |
| + return "Unknown", "", true |
| + case "_other": |
| + return "Other countries", "", true |
| + } |
| + return countryName(k), countryFlag(k), false |
| +} |
| + |
| +// countryName is an ISO 3166-1 alpha-2 code's English name, or the code. |
| +func countryName(code string) string { |
| + if n, ok := countryNames[strings.ToUpper(code)]; ok { |
| + return n |
| + } |
| + return code |
| +} |
| + |
| +// countryFlag is the code as a flag emoji: the two regional indicator |
| +// letters, which the reader's own system draws. No image is fetched. A |
| +// code that is not two letters has no flag. |
| +func countryFlag(code string) string { |
| + if len(code) != 2 { |
| + return "" |
| + } |
| + var b strings.Builder |
| + for _, r := range strings.ToUpper(code) { |
| + if r < 'A' || r > 'Z' { |
| + return "" |
| + } |
| + b.WriteRune(0x1F1E6 + (r - 'A')) |
| + } |
| + return b.String() |
| +} |
| + |
| +// humanBytes is a byte count in decimal units, the way a person says it: |
| +// 812 B, 1.6 MB, 16 MB, 160 MB. One decimal below ten, none above. |
| +func humanBytes(n int64) string { |
| + if n < 1000 { |
| + return strconv.FormatInt(n, 10) + " B" |
| + } |
| + v := float64(n) |
| + for _, unit := range []string{"KB", "MB", "GB", "TB", "PB"} { |
| + v /= 1000 |
| + if v < 999.5 || unit == "PB" { |
| + if v < 9.95 { |
| + return strconv.FormatFloat(v, 'f', 1, 64) + " " + unit |
| + } |
| + return strconv.FormatFloat(math.Round(v), 'f', 0, 64) + " " + unit |
| + } |
| + } |
| + return strconv.FormatInt(n, 10) + " B" |
| +} |
| + |
| +// groupedCount is n with thousands separators: 1,284. |
| +func groupedCount(n int64) string { |
| + s := strconv.FormatInt(n, 10) |
| + neg := strings.HasPrefix(s, "-") |
| + s = strings.TrimPrefix(s, "-") |
| + var b strings.Builder |
| + for i, r := range s { |
| + if i > 0 && (len(s)-i)%3 == 0 { |
| + b.WriteByte(',') |
| + } |
| + b.WriteRune(r) |
| + } |
| + if neg { |
| + return "-" + b.String() |
| + } |
| + return b.String() |
| +} |
| + |
| +// compactCount is an axis label: 0, 5, 400, 1.2K, 40K, 3M. |
| +func compactCount(n int64) string { |
| + switch { |
| + case n < 1000: |
| + return strconv.FormatInt(n, 10) |
| + case n < 1_000_000: |
| + return trimZero(float64(n)/1000) + "K" |
| + default: |
| + return trimZero(float64(n)/1_000_000) + "M" |
| + } |
| +} |
| + |
| +func trimZero(f float64) string { |
| + if f >= 10 { |
| + return strconv.FormatFloat(math.Round(f), 'f', 0, 64) |
| + } |
| + return strconv.FormatFloat(math.Round(f*10)/10, 'f', -1, 64) |
| +} |
| + |
| +// plural is n and the word for it, n grouped: "1 visitor", "1,284 visitors". |
| +func plural(n int64, one, many string) string { |
| + if n == 1 { |
| + return "1 " + one |
| + } |
| + return groupedCount(n) + " " + many |
| +} |
| + |
| +// The date forms the tab uses. A date that does not parse is shown as it |
| +// came, which only a corrupt day file could produce. |
| +func shortDate(date string) string { return fmtDate(date, "2 Jan") } |
| +func longDay(date string) string { return fmtDate(date, "Mon 2 Jan") } |
| +func weekdayDay(date string) string { |
| + return fmtDate(date, "Mon 2") |
| +} |
| + |
| +func fmtDate(date, layout string) string { |
| + t, err := time.Parse("2006-01-02", date) |
| + if err != nil { |
| + return date |
| + } |
| + return t.Format(layout) |
| +} |
| + |
| +// analyticsSpanText says which days the window covers: "Today, 28 Oct |
| +// 2026 UTC" or "22 Oct to 28 Oct 2026 UTC". |
| +func analyticsSpanText(rng string, now time.Time) string { |
| + from, to := analyticsSpan(rng, now) |
| + if rng == rangeToday { |
| + return "Today, " + to.Format("2 Jan 2006") + " UTC" |
| + } |
| + if from.Year() != to.Year() { |
| + return from.Format("2 Jan 2006") + " to " + to.Format("2 Jan 2006") + " UTC" |
| + } |
| + return from.Format("2 Jan") + " to " + to.Format("2 Jan 2006") + " UTC" |
| +} |
| + |
| +// restartNote is the note for the days an edge restarted: the counts it |
| +// 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 { |
| + var hit []string |
| + for _, d := range days { |
| + if d.Restarted { |
| + hit = append(hit, longDay(d.Date)) |
| + } |
| + } |
| + switch n := len(hit); { |
| + case n == 0: |
| + return "" |
| + case n == 1 && len(days) == 1: |
| + 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." |
| + case n <= 3: |
| + return "The edge restarted on " + strings.Join(hit[:n-1], ", ") + " and " + hit[n-1] + ". Counts it had not saved yet may be missing for those days." |
| + default: |
| + 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) |
| + } |
| +} |
diff --git a/internal/console/analyticsdisplay_test.go b/internal/console/analyticsdisplay_test.go| new file mode 100644 |
| index 000000000..957e40d95 |
| --- /dev/null |
| +++ b/internal/console/analyticsdisplay_test.go |
| @@ -0,0 +1,334 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| +) |
| + |
| +func TestHumanBytes(t *testing.T) { |
| + for n, want := range map[int64]string{ |
| + 0: "0 B", 999: "999 B", 1000: "1.0 KB", 1595351: "1.6 MB", 9_949_999: "9.9 MB", |
| + 9_950_000: "10 MB", 16_400_000: "16 MB", 999_400_000: "999 MB", 999_600_000: "1.0 GB", |
| + 846_000_000: "846 MB", 3_200_000_000_000: "3.2 TB", |
| + } { |
| + if got := humanBytes(n); got != want { |
| + t.Errorf("humanBytes(%d) = %q, want %q", n, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestGroupedAndCompactCounts(t *testing.T) { |
| + for n, want := range map[int64]string{0: "0", 999: "999", 1000: "1,000", 1284: "1,284", 1234567: "1,234,567", -1234: "-1,234"} { |
| + if got := groupedCount(n); got != want { |
| + t.Errorf("groupedCount(%d) = %q, want %q", n, got, want) |
| + } |
| + } |
| + for n, want := range map[int64]string{5: "5", 400: "400", 1200: "1.2K", 40000: "40K", 2_000_000: "2M"} { |
| + if got := compactCount(n); got != want { |
| + t.Errorf("compactCount(%d) = %q, want %q", n, got, want) |
| + } |
| + } |
| + if got := plural(1, "visitor", "visitors"); got != "1 visitor" { |
| + t.Errorf("plural(1) = %q", got) |
| + } |
| + if got := plural(1284, "visitor", "visitors"); got != "1,284 visitors" { |
| + t.Errorf("plural(1284) = %q", got) |
| + } |
| +} |
| + |
| +func TestCountryLabel(t *testing.T) { |
| + for code, want := range map[string]string{"IE": "Ireland", "AS": "American Samoa", "GB": "United Kingdom", "MK": "North Macedonia", "ZY": "ZY"} { |
| + if got, _, _ := countryLabel(code); got != want { |
| + t.Errorf("countryLabel(%q) = %q, want %q", code, got, want) |
| + } |
| + } |
| + if _, flag, _ := countryLabel("IE"); flag != "\U0001F1EE\U0001F1EA" { |
| + t.Errorf("IE flag = %q", flag) |
| + } |
| + for _, k := range []string{"_unknown", "_other"} { |
| + if _, flag, muted := countryLabel(k); flag != "" || !muted { |
| + t.Errorf("%s: flag %q muted %v, want no flag and muted", k, flag, muted) |
| + } |
| + } |
| +} |
| + |
| +func TestNiceCeil(t *testing.T) { |
| + for v, want := range map[int64]int64{0: 1, 1: 1, 2: 2, 3: 4, 5: 5, 6: 10, 11: 20, 292: 400, 401: 500, 1000: 1000, 1001: 2000} { |
| + if got := niceCeil(v); got != want { |
| + t.Errorf("niceCeil(%d) = %d, want %d", v, got, want) |
| + } |
| + } |
| +} |
| + |
| +// Today's chart: hours after now are not plotted and not targets, the |
| +// current hour is marked as still counting, and bars scale to the axis top. |
| +func TestTrafficChartToday(t *testing.T) { |
| + now := time.Date(2026, 10, 28, 14, 30, 0, 0, time.UTC) |
| + var d analytics.DaySummary |
| + d.Date = "2026-10-28" |
| + d.Hours[9], d.Hours[14] = 3, 1 |
| + c := buildTrafficChart(rangeToday, analytics.Summary{Days: []analytics.DaySummary{d}}, now) |
| + if c == nil || c.N() != 24 || c.Unit != "hour" { |
| + t.Fatalf("chart = %+v", c) |
| + } |
| + if !c.Cols[15].Future || c.Cols[14].Future || !c.Cols[14].Partial { |
| + t.Errorf("future/partial wrong: 14 %+v 15 %+v", c.Cols[14], c.Cols[15]) |
| + } |
| + // Peak 3 rounds up to an axis of 4: 75% tall, ticks 0, 2, 4. |
| + if c.Cols[9].HPct != 75 || len(c.Ticks) != 3 || c.Ticks[2].Label != "4" { |
| + t.Errorf("scale: bar %v ticks %+v", c.Cols[9].HPct, c.Ticks) |
| + } |
| + if want := "28 Oct, 09:00 to 10:00 UTC: 3 page views"; c.Cols[9].Label != want { |
| + t.Errorf("label = %q, want %q", c.Cols[9].Label, want) |
| + } |
| + if !strings.HasSuffix(c.Cols[14].Label, "1 page view so far") { |
| + t.Errorf("current hour label = %q", c.Cols[14].Label) |
| + } |
| + if buildTrafficChart(rangeToday, analytics.Summary{Days: []analytics.DaySummary{{Date: "2026-10-28"}}}, now) != nil { |
| + t.Error("a day with nothing counted drew a chart") |
| + } |
| +} |
| + |
| +func TestTrafficChartDays(t *testing.T) { |
| + now := time.Date(2026, 10, 28, 10, 0, 0, 0, time.UTC) |
| + var days []analytics.DaySummary |
| + for i := 0; i < 30; i++ { |
| + date := now.AddDate(0, 0, i-29).Format("2006-01-02") |
| + days = append(days, analytics.DaySummary{Date: date, PV: int64(i + 1), Visitors: 1, Bytes: 1_600_000, Restarted: i == 3}) |
| + } |
| + c := buildTrafficChart(range30d, analytics.Summary{Days: days}, now) |
| + if c == nil || c.N() != 30 || c.Unit != "day" { |
| + t.Fatalf("chart = %+v", c) |
| + } |
| + last := c.Cols[29] |
| + if !last.Partial || !strings.Contains(last.Label, "30 page views so far") || !strings.Contains(last.Label, "1.6 MB served") { |
| + t.Errorf("today's column = %+v", last) |
| + } |
| + if !c.Cols[3].Gap || c.Cols[2].Gap { |
| + t.Error("restart marker on the wrong day") |
| + } |
| + // Labels every seventh day back from today, so today has one. |
| + if got := c.XLabels[len(c.XLabels)-1]; got.Col != 30 || got.Label != "28 Oct" { |
| + t.Errorf("last x label = %+v", got) |
| + } |
| + if c.Cols[0].Edge != "start" || c.Cols[29].Edge != "end" || c.Cols[15].Edge != "" { |
| + t.Error("tooltip anchoring wrong") |
| + } |
| +} |
| + |
| +// The average leaves today out: half a day would read as a drop. |
| +func TestAnalyticsInsights(t *testing.T) { |
| + now := time.Date(2026, 10, 28, 10, 0, 0, 0, time.UTC) |
| + days := []analytics.DaySummary{{Date: "2026-10-26", PV: 10}, {Date: "2026-10-27", PV: 30}, {Date: "2026-10-28", PV: 1}} |
| + got := analyticsInsights(range7d, analytics.Summary{Days: days}, now) |
| + want := []string{"Busiest day: Tue 27 Oct, with 30 page views.", "An average of 20 page views per day over the last 2 full days."} |
| + if strings.Join(got, "|") != strings.Join(want, "|") { |
| + t.Errorf("insights = %q, want %q", got, want) |
| + } |
| + if got := averageViews(2, 7); got != "0.3 page views" { |
| + t.Errorf("averageViews(2, 7) = %q", got) |
| + } |
| + // 14:00 is after now (10:00), so it is not a candidate: the chart does |
| + // not draw it either. |
| + var d analytics.DaySummary |
| + d.Date, d.Hours[9], d.Hours[14] = "2026-10-28", 2, 3 |
| + if got := analyticsInsights(rangeToday, analytics.Summary{Days: []analytics.DaySummary{d}}, now); len(got) != 1 || got[0] != "Busiest hour so far: 09:00 UTC, with 2 page views." { |
| + t.Errorf("today insights = %q", got) |
| + } |
| +} |
| + |
| +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 != "" { |
| + 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") { |
| + 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") { |
| + t.Errorf("five restarts = %q", got) |
| + } |
| +} |
| + |
| +func TestShareRows(t *testing.T) { |
| + rows := shareRows(map[string]int64{"/": 300, "/a": 1, analytics.OtherKey: 400, "/b": 299}, pageLabel) |
| + if len(rows) != 4 || rows[0].Key != "/" || rows[3].Key != analytics.OtherKey || !rows[3].Muted || rows[3].Label != "Everything else" { |
| + t.Fatalf("rows = %+v", rows) |
| + } |
| + // The biggest row is the full bar even when "everything else" is bigger |
| + // still: bars compare rows, and the overflow row is pinned last. |
| + if rows[0].Share != "30%" || rows[2].Share != "<1%" || rows[3].Bar != 100 { |
| + t.Errorf("shares = %+v", rows) |
| + } |
| +} |
| + |
| +// The analytics day files go through the settled-day cache: a day that is |
| +// over is read once, and a second view of 30 days reads only today's and |
| +// yesterday's file per box. This is the request budget the tab promises. |
| +func TestAnalyticsReadsSettledDaysOnce(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-analytics-cache") |
| + now := time.Now().UTC() |
| + for _, d := range []int{0, 1, 5, 20} { |
| + seedAnalytics(t, fx, now.Truncate(24*time.Hour).AddDate(0, 0, -d).Add(time.Hour)) |
| + } |
| + cs := &analyticsCountStore{Store: fx.rel} |
| + fx.srv.cfg.Releases = cs |
| + read := func() analyticsWindow { |
| + win, err := fx.srv.readAnalytics(context.Background(), fx.sqid, "titogo", range30d, now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return win |
| + } |
| + first := read() |
| + if first.Sum.PV != 20 { |
| + t.Fatalf("30 days = %d page views, want 20", first.Sum.PV) |
| + } |
| + cold := cs.dayReads() |
| + if cold != 30 { |
| + t.Fatalf("cold view read %d day files, want 30 (one box, 30 days)", cold) |
| + } |
| + second := read() |
| + if second.Sum.PV != first.Sum.PV { |
| + t.Fatalf("warm view = %d page views, cold %d", second.Sum.PV, first.Sum.PV) |
| + } |
| + if warm := cs.dayReads() - cold; warm != 2 { |
| + t.Fatalf("warm view read %d day files, want 2 (today and yesterday)", warm) |
| + } |
| +} |
| + |
| +type analyticsCountStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + reads int |
| +} |
| + |
| +func (c *analyticsCountStore) count(key string) { |
| + if strings.Contains(key, "/analytics/") && strings.HasSuffix(key, ".json") { |
| + c.mu.Lock() |
| + c.reads++ |
| + c.mu.Unlock() |
| + } |
| +} |
| + |
| +func (c *analyticsCountStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + c.count(key) |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +func (c *analyticsCountStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + c.count(key) |
| + return release.OpenObject(ctx, c.Store, key) |
| +} |
| + |
| +func (c *analyticsCountStore) dayReads() int { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.reads |
| +} |
| + |
| +// The Overview's traffic card: the week's numbers and chart when counting is |
| +// on, the way to turn it on when it is off. |
| +func TestOverviewTrafficCard(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-analytics-overview") |
| + seedAnalytics(t, fx, seedTime()) |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-analytics-overview-browser") |
| + status, _, body := get(t, c, fx.u("/apps/titogo")) |
| + if status != http.StatusOK { |
| + t.Fatalf("overview = %d", status) |
| + } |
| + for _, want := range []string{"Traffic, last 7 days", "Analytics is off for this app. These are the numbers counted while it was on.", "<dd>5</dd>", `class="an-chart an-chart-day"`} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("overview (off, counted) missing %q", want) |
| + } |
| + } |
| + 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) |
| + } |
| + _, _, body = get(t, c, fx.u("/apps/titogo")) |
| + if strings.Contains(body, "Analytics is off") || !strings.Contains(body, "/analytics?range=7d") { |
| + t.Error("overview (on) still says off, or has no link to the tab") |
| + } |
| +} |
| + |
| +// A slow analytics read costs the card, not the page: the Overview renders |
| +// once the grace runs out, with the card saying it is still loading. |
| +func TestOverviewTrafficCardSlowRead(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-analytics-overview-slow") |
| + seedAnalytics(t, fx, seedTime()) |
| + release := make(chan struct{}) |
| + defer close(release) |
| + fx.srv.cfg.Releases = &hookStore{Store: fx.rel, onGet: func(key string) { |
| + if strings.Contains(key, "/analytics/") { |
| + <-release |
| + } |
| + }} |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-analytics-overview-slow-browser") |
| + start := time.Now() |
| + status, _, body := get(t, c, fx.u("/apps/titogo")) |
| + if took := time.Since(start); took >= overviewTrafficTimeout { |
| + t.Fatalf("overview took %v: it waited for the traffic read", took) |
| + } |
| + if status != http.StatusOK || !strings.Contains(body, "Traffic is still loading.") { |
| + t.Fatalf("overview = %d, want the card's still-loading line:\n%s", status, body) |
| + } |
| +} |
| + |
| +// The wait is what is left of one budget counted from the start of the |
| +// page's reads: a page that already spent it does not wait at all. |
| +func TestTrafficWait(t *testing.T) { |
| + t0 := time.Date(2026, 10, 28, 10, 0, 0, 0, time.UTC) |
| + for elapsed, want := range map[time.Duration]time.Duration{ |
| + 0: overviewTrafficBudget, 100 * time.Millisecond: overviewTrafficBudget - 100*time.Millisecond, |
| + overviewTrafficBudget: 0, 450 * time.Millisecond: 0, |
| + } { |
| + if got := trafficWait(t0, t0.Add(elapsed)); got != want { |
| + t.Errorf("after %v: wait %v, want %v", elapsed, got, want) |
| + } |
| + } |
| +} |
| + |
| +// The traffic card's memo answers for a minute, then not; a nil memo (the |
| +// Analytics tab, the CLI) never holds anything. |
| +func TestAnalyticsMemo(t *testing.T) { |
| + t0 := time.Date(2026, 10, 28, 10, 0, 0, 0, time.UTC) |
| + var m analyticsMemo |
| + m.put("k", analytics.Summary{PV: 7}, t0) |
| + if got, ok := m.get("k", t0.Add(59*time.Second)); !ok || got.PV != 7 { |
| + t.Fatalf("within the minute: %+v %v", got, ok) |
| + } |
| + if _, ok := m.get("k", t0.Add(analyticsMemoTTL)); ok { |
| + t.Fatal("held past its minute") |
| + } |
| + var none *analyticsMemo |
| + none.put("k", analytics.Summary{PV: 1}, t0) |
| + if _, ok := none.get("k", t0); ok { |
| + t.Fatal("a nil memo held something") |
| + } |
| + for i := 0; i < analyticsMemoMax+5; i++ { |
| + m.put(strconv.Itoa(i), analytics.Summary{}, t0.Add(time.Duration(i)*time.Millisecond)) |
| + } |
| + if len(m.m) > analyticsMemoMax { |
| + t.Fatalf("memo holds %d entries, cap %d", len(m.m), analyticsMemoMax) |
| + } |
| +} |
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go| index c7b1a143c..8880a16d3 100644 |
| --- a/internal/console/analyticsview.go |
| +++ b/internal/console/analyticsview.go |
| @@ -10,16 +10,17 @@ package console |
| import ( |
| "context" |
| "crypto/subtle" |
| - "fmt" |
| "log" |
| "math" |
| "net/http" |
| "net/url" |
| "sort" |
| + "sync" |
| "time" |
| "github.com/carlosframework/platform/internal/analytics" |
| "github.com/carlosframework/platform/internal/geoip" |
| + "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/telemetry" |
| ) |
| @@ -231,14 +232,22 @@ func analyticsAudit(count, door string) string { |
| // analyticsWindow is one assembled read: the summary, the range it covers, |
| // the resolved setting (so the page can say counting is off, and where that |
| -// came from), and the chart geometry the template plots. |
| +// came from), and what the page draws from it (analyticsdisplay.go). |
| type analyticsWindow struct { |
| - Sum analytics.Summary |
| - Range string |
| - On bool |
| - Setting telemetry.Resolved |
| - ChartBars []chartBar |
| - ChartMax int64 |
| + Sum analytics.Summary |
| + Range string |
| + On bool |
| + Setting telemetry.Resolved |
| + Span string |
| + Chart *trafficChart |
| + 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 |
| } |
| // HasData reports whether the window holds anything counted. With analytics |
| @@ -251,16 +260,6 @@ func (w analyticsWindow) HasData() bool { |
| len(s.Pages) > 0 || len(s.Referers) > 0 || len(s.Events) > 0 || len(s.Countries) > 0 |
| } |
| -// chartBar is one plotted column: the reading, and the rectangle that draws |
| -// it. The geometry is computed here rather than in the template because a |
| -// template cannot divide, and because the scaling is the part worth testing. |
| -type chartBar struct { |
| - Label string |
| - Value int64 |
| - X, Y, W float64 |
| - H float64 |
| -} |
| - |
| // The three windows the tab and the API accept. Anything else is a mistake |
| // worth naming at the API and worth ignoring at the page. |
| const ( |
| @@ -269,6 +268,90 @@ const ( |
| range30d = "30d" |
| ) |
| +// analyticsMemo holds the Overview traffic card's counts per app for |
| +// analyticsMemoTTL, so an Overview opened again within a minute reads no |
| +// day files at all: the edge writes them every five minutes, so a minute |
| +// old is as fresh as the bucket. The Analytics tab and the CLI do not use |
| +// 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 |
| +} |
| + |
| +type analyticsMemoEntry struct { |
| + at time.Time |
| + sum analytics.Summary |
| +} |
| + |
| +const ( |
| + analyticsMemoTTL = time.Minute |
| + analyticsMemoMax = 512 |
| +) |
| + |
| +// get is key's counts when they were read less than analyticsMemoTTL ago. |
| +// A nil memo holds nothing. |
| +func (c *analyticsMemo) get(key string, now time.Time) (analytics.Summary, bool) { |
| + if c == nil { |
| + return analytics.Summary{}, false |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + e, ok := c.m[key] |
| + if !ok || now.Sub(e.at) >= analyticsMemoTTL || now.Before(e.at) { |
| + return analytics.Summary{}, false |
| + } |
| + return e.sum, true |
| +} |
| + |
| +// put keeps key's counts, read at now. Expired entries go first; past |
| +// analyticsMemoMax the oldest goes. |
| +func (c *analyticsMemo) put(key string, sum analytics.Summary, now time.Time) { |
| + if c == nil { |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.m == nil { |
| + c.m = map[string]analyticsMemoEntry{} |
| + } |
| + for k, e := range c.m { |
| + if now.Sub(e.at) >= analyticsMemoTTL { |
| + delete(c.m, k) |
| + } |
| + } |
| + for len(c.m) >= analyticsMemoMax { |
| + oldest := "" |
| + for k, e := range c.m { |
| + if oldest == "" || e.at.Before(c.m[oldest].at) { |
| + oldest = k |
| + } |
| + } |
| + delete(c.m, oldest) |
| + } |
| + c.m[key] = analyticsMemoEntry{at: now, sum: sum} |
| +} |
| + |
| +// overviewTrafficTimeout bounds the Overview's traffic card read, and |
| +// overviewTrafficBudget is the latest, counted from the start of the |
| +// request (perf.Started), that the Overview waits for it (handleApp): |
| +// inside the 500 ms cold budget with room to render. A warm |
| +// read takes a few concurrent GETs, well inside it; a cold one past it |
| +// shows the card as still loading, and leaves its settled days in the |
| +// cache for the next view. |
| +const ( |
| + overviewTrafficTimeout = 2 * time.Second |
| + overviewTrafficBudget = 300 * time.Millisecond |
| +) |
| + |
| +// trafficWait is how long the Overview may still wait for the traffic card |
| +// at now, for a request that started at start: what is left of |
| +// overviewTrafficBudget, never negative. A page whose other reads already |
| +// used the budget does not wait at all. |
| +func trafficWait(start, now time.Time) time.Duration { |
| + return max(0, overviewTrafficBudget-now.Sub(start)) |
| +} |
| + |
| func validRange(s string) bool { return s == rangeToday || s == range7d || s == range30d } |
| // analyticsSpan turns a range name into a UTC span. Truncate(24h) lands on |
| @@ -288,19 +371,19 @@ func analyticsSpan(rng string, now time.Time) (from, to time.Time) { |
| } |
| } |
| -// chartWidth and chartHeight are the plot's viewBox units — not pixels: the |
| -// SVG scales to whatever column it lands in, so these fix only the aspect |
| -// and the resolution of the geometry. |
| -const ( |
| - chartWidth = 480.0 |
| - chartHeight = 120.0 |
| -) |
| - |
| // 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) |
| +} |
| + |
| +// 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} |
| res, err := telemetry.Resolve(ctx, s.cfg.Releases, sqid, app) |
| if err != nil { |
| @@ -314,89 +397,46 @@ func (s *Server) readAnalytics(ctx context.Context, sqid, app, rng string, now t |
| return out, nil |
| } |
| from, to := analyticsSpan(rng, now) |
| - sum, err := analytics.ReadRange(ctx, s.cfg.Releases, sqid, app, from, to) |
| - if err != nil { |
| - return out, err |
| + 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 |
| + } |
| + memo.put(key, sum, now) |
| } |
| out.Sum = sum |
| - vals, labels := chartSeries(rng, sum) |
| - out.ChartBars, out.ChartMax = chartBars(vals, labels, chartWidth, chartHeight) |
| + 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) |
| + out.Countries = shareRows(geoCountries(sum.Countries), countryLabel) |
| + out.Restarts = restartNote(sum.Days) |
| return out, nil |
| } |
| -// chartSeries picks what the bars plot: today is the 24 hourly page-view |
| -// counts, a multi-day window is one bar per day. A day the range covers but |
| -// no box wrote a file for is a zero rather than a gap — ReadRange returns |
| -// one DaySummary per date either way, so the axis stays evenly spaced. |
| -func chartSeries(rng string, sum analytics.Summary) (vals []int64, labels []string) { |
| - if rng == rangeToday { |
| - if len(sum.Days) == 0 { |
| - return nil, nil |
| - } |
| - // The last row, not the first: today's span is one date, and taking |
| - // the tail keeps this right if a caller ever passes a wider one. |
| - d := sum.Days[len(sum.Days)-1] |
| - for h := 0; h < 24; h++ { |
| - vals = append(vals, d.Hours[h]) |
| - labels = append(labels, fmt.Sprintf("%02d", h)) |
| - } |
| - return vals, labels |
| - } |
| - for _, d := range sum.Days { |
| - vals = append(vals, d.PV) |
| - labels = append(labels, dayLabel(d.Date)) |
| - } |
| - return vals, labels |
| -} |
| - |
| -// dayLabel shortens a UTC date to MM-DD: thirty bars cannot each carry a |
| -// year, and the window's own dates are printed in full beside the chart. |
| -func dayLabel(date string) string { |
| - if len(date) == len("2006-01-02") { |
| - return date[5:] |
| - } |
| - return date |
| -} |
| - |
| -// chartBars scales vals onto a w x h box: one column per reading, two units |
| -// of gap between columns, height proportional to the largest reading in the |
| -// window — returned as the second value, so the template can say what the |
| -// peak was rather than leaving the axis unlabelled. |
| -// |
| -// Nothing to plot — no readings, or nothing but zeros — returns no bars at |
| -// all: a row of flat rectangles under a "peak 0" caption is noise, and the |
| -// template renders no chart rather than an empty one. Coordinates are |
| -// rounded to two decimals for the reason sparkPoints rounds its own: the |
| -// trailing digits of a binary fraction are bytes on every page view that |
| -// change nothing anyone can see. |
| -func chartBars(vals []int64, labels []string, w, h float64) ([]chartBar, int64) { |
| - var max int64 |
| - for _, v := range vals { |
| - if v > max { |
| - max = v |
| - } |
| - } |
| - if len(vals) == 0 || max <= 0 { |
| - return nil, max |
| - } |
| - step := w / float64(len(vals)) |
| - bw := step - 2 |
| - if bw <= 0 { |
| - bw = step // more columns than gaps will fit: draw them touching |
| - } |
| - out := make([]chartBar, 0, len(vals)) |
| - for i, v := range vals { |
| - b := chartBar{Value: v, X: round2(float64(i) * step), W: round2(bw)} |
| - if i < len(labels) { |
| - b.Label = labels[i] |
| - } |
| - if v > 0 { |
| - b.H = round2(float64(v) / float64(max) * h) |
| - } |
| - b.Y = round2(h - b.H) |
| - out = append(out, b) |
| - } |
| - return out, max |
| +// readAnalyticsRange is analytics.ReadRange through the settled-day cache |
| +// (usagedays.go), with its reads made concurrently (hotreads.go). A day |
| +// file stops changing a day after the day ends, so a warm 30-day view reads |
| +// one listing and today's and yesterday's file per box; before this, every |
| +// view read every box's file for every day of the window, one after |
| +// another. Request budget: nothing on a timer; per view, one LIST of the |
| +// app's boxes plus two GETs per box, and one GET per box per settled day |
| +// at most every usageDayMaxAge. |
| +func (s *Server) readAnalyticsRange(ctx context.Context, sqid, app string, from, to, now time.Time) (analytics.Summary, error) { |
| + type read struct { |
| + sum analytics.Summary |
| + err error |
| + } |
| + // "{}" is an empty day file, which ReadRange folds in as nothing. |
| + r := readConcurrently(ctx, s.usageDayReader(now), []byte("{}"), usageDayLimit, func(st release.Store) read { |
| + sum, err := analytics.ReadRange(ctx, st, sqid, app, from, to) |
| + return read{sum, err} |
| + }) |
| + return r.sum, r.err |
| } |
| func round2(f float64) float64 { return math.Round(f*100) / 100 } |
diff --git a/internal/console/apianalytics_test.go b/internal/console/apianalytics_test.go| index de501fd3a..6abcf5a42 100644 |
| --- a/internal/console/apianalytics_test.go |
| +++ b/internal/console/apianalytics_test.go |
| @@ -120,8 +120,11 @@ func seedAnalytics(t *testing.T, fx *consoleFixture, when time.Time) { |
| } |
| } |
| -// seedTime is the stamp seedAnalytics uses — midday of the current UTC day. |
| -func seedTime() time.Time { return time.Now().UTC().Truncate(24 * time.Hour).Add(12 * time.Hour) } |
| +// seedTime is the stamp seedAnalytics uses: the start of the current UTC |
| +// hour, which is always today and never in the future. (Midday was in the |
| +// future every morning, and the chart does not draw hours that have not |
| +// happened.) |
| +func seedTime() time.Time { return time.Now().UTC().Truncate(time.Hour) } |
| func TestAPIAnalyticsSummary(t *testing.T) { |
| fx, token := instanceFixture(t, "code-analytics-api") |
| @@ -167,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", "<svg"} { |
| + 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"`} { |
| if !strings.Contains(body, want) { |
| t.Errorf("page missing %q", want) |
| } |
| @@ -178,7 +181,7 @@ func TestAppAnalyticsPage(t *testing.T) { |
| t.Fatal(err) |
| } |
| _, _, body = get(t, c, fx.u("/apps/titogo/analytics?range=7d")) |
| - if strings.Contains(body, "Analytics is off") || !strings.Contains(body, "daily visitors, summed") || !strings.Contains(body, "carlos analytics --app titogo") { |
| + if strings.Contains(body, "Analytics is off") || !strings.Contains(body, "Daily visitors are added up.") || !strings.Contains(body, "carlos analytics --app titogo") { |
| t.Fatal("on + 7d page") |
| } |
| } |
| @@ -211,7 +214,7 @@ func TestAppAnalyticsPageCountriesAndAttribution(t *testing.T) { |
| } |
| } |
| _, _, body = get(t, c, fx.u("/apps/titogo/analytics")) |
| - for _, want := range []string{"<h3>Countries</h3>", "<td>GB</td><td>2</td>", "<td>unknown</td><td>1</td>", |
| + for _, want := range []string{">Countries</h3>", "United Kingdom</span>\n <span class=\"an-val\">2</span>", "Unknown</span>\n <span class=\"an-val\">1</span>", |
| `href="https://db-ip.com">IP Geolocation by DB-IP</a>`, "GeoLite2 data created by MaxMind"} { |
| if !strings.Contains(body, want) { |
| t.Errorf("page lacks %q", want) |
diff --git a/internal/console/appnav_test.go b/internal/console/appnav_test.go| index 5da00e6ee..b98a7f786 100644 |
| --- a/internal/console/appnav_test.go |
| +++ b/internal/console/appnav_test.go |
| @@ -208,9 +208,9 @@ func TestRunningLeftoversNameTheTab(t *testing.T) { |
| func TestLogsToolbar(t *testing.T) { |
| fx := newConsoleFixture(t) |
| c := signInPaul(t, fx) |
| - // Analytics is off for kass and nothing is counted, so its tab hides the |
| - // range picker on today (the on-ramp's off state); any other range keeps it. |
| - for _, tab := range []string{"logs", "errors", "availability", "analytics?range=7d"} { |
| + // The Analytics tab's period picker is three links, not a filter form |
| + // (TestAnalyticsTabOffState*), so it is not one of the toolbars here. |
| + for _, tab := range []string{"logs", "errors", "availability"} { |
| status, _, body := get(t, c, fx.u("/apps/kass/"+tab)) |
| if status != 200 { |
| t.Fatalf("GET /apps/kass/%s = %d", tab, status) |
diff --git a/internal/console/countrynames.go b/internal/console/countrynames.go| new file mode 100644 |
| index 000000000..3524d886f |
| --- /dev/null |
| +++ b/internal/console/countrynames.go |
| @@ -0,0 +1,278 @@ |
| +package console |
| + |
| +// countryNames gives the Countries table words for the ISO 3166-1 alpha-2 |
| +// codes GeoIP answers with. Generated once from golang.org/x/text's English |
| +// region names (language/display, which is too large to link for one |
| +// table), with the dated ones brought up to the names countries use now. |
| +// A code missing here is shown as the code itself. |
| +var countryNames = map[string]string{ |
| + "AD": "Andorra", |
| + "AE": "United Arab Emirates", |
| + "AF": "Afghanistan", |
| + "AG": "Antigua & Barbuda", |
| + "AI": "Anguilla", |
| + "AL": "Albania", |
| + "AM": "Armenia", |
| + "AO": "Angola", |
| + "AQ": "Antarctica", |
| + "AR": "Argentina", |
| + "AS": "American Samoa", |
| + "AT": "Austria", |
| + "AU": "Australia", |
| + "AW": "Aruba", |
| + "AX": "Åland Islands", |
| + "AZ": "Azerbaijan", |
| + "BA": "Bosnia & Herzegovina", |
| + "BB": "Barbados", |
| + "BD": "Bangladesh", |
| + "BE": "Belgium", |
| + "BF": "Burkina Faso", |
| + "BG": "Bulgaria", |
| + "BH": "Bahrain", |
| + "BI": "Burundi", |
| + "BJ": "Benin", |
| + "BL": "St. Barthélemy", |
| + "BM": "Bermuda", |
| + "BN": "Brunei", |
| + "BO": "Bolivia", |
| + "BQ": "Caribbean Netherlands", |
| + "BR": "Brazil", |
| + "BS": "Bahamas", |
| + "BT": "Bhutan", |
| + "BU": "Myanmar", |
| + "BV": "Bouvet Island", |
| + "BW": "Botswana", |
| + "BY": "Belarus", |
| + "BZ": "Belize", |
| + "CA": "Canada", |
| + "CC": "Cocos (Keeling) Islands", |
| + "CD": "DR Congo", |
| + "CF": "Central African Republic", |
| + "CG": "Republic of the Congo", |
| + "CH": "Switzerland", |
| + "CI": "Côte d’Ivoire", |
| + "CK": "Cook Islands", |
| + "CL": "Chile", |
| + "CM": "Cameroon", |
| + "CN": "China", |
| + "CO": "Colombia", |
| + "CR": "Costa Rica", |
| + "CT": "Kiribati", |
| + "CU": "Cuba", |
| + "CV": "Cape Verde", |
| + "CW": "Curaçao", |
| + "CX": "Christmas Island", |
| + "CY": "Cyprus", |
| + "CZ": "Czechia", |
| + "DD": "Germany", |
| + "DE": "Germany", |
| + "DJ": "Djibouti", |
| + "DK": "Denmark", |
| + "DM": "Dominica", |
| + "DO": "Dominican Republic", |
| + "DY": "Benin", |
| + "DZ": "Algeria", |
| + "EC": "Ecuador", |
| + "EE": "Estonia", |
| + "EG": "Egypt", |
| + "EH": "Western Sahara", |
| + "ER": "Eritrea", |
| + "ES": "Spain", |
| + "ET": "Ethiopia", |
| + "FI": "Finland", |
| + "FJ": "Fiji", |
| + "FK": "Falkland Islands", |
| + "FM": "Micronesia", |
| + "FO": "Faroe Islands", |
| + "FR": "France", |
| + "FX": "France", |
| + "GA": "Gabon", |
| + "GB": "United Kingdom", |
| + "GD": "Grenada", |
| + "GE": "Georgia", |
| + "GF": "French Guiana", |
| + "GG": "Guernsey", |
| + "GH": "Ghana", |
| + "GI": "Gibraltar", |
| + "GL": "Greenland", |
| + "GM": "Gambia", |
| + "GN": "Guinea", |
| + "GP": "Guadeloupe", |
| + "GQ": "Equatorial Guinea", |
| + "GR": "Greece", |
| + "GS": "South Georgia & South Sandwich Islands", |
| + "GT": "Guatemala", |
| + "GU": "Guam", |
| + "GW": "Guinea-Bissau", |
| + "GY": "Guyana", |
| + "HK": "Hong Kong", |
| + "HM": "Heard & McDonald Islands", |
| + "HN": "Honduras", |
| + "HR": "Croatia", |
| + "HT": "Haiti", |
| + "HU": "Hungary", |
| + "HV": "Burkina Faso", |
| + "ID": "Indonesia", |
| + "IE": "Ireland", |
| + "IL": "Israel", |
| + "IM": "Isle of Man", |
| + "IN": "India", |
| + "IO": "British Indian Ocean Territory", |
| + "IQ": "Iraq", |
| + "IR": "Iran", |
| + "IS": "Iceland", |
| + "IT": "Italy", |
| + "JE": "Jersey", |
| + "JM": "Jamaica", |
| + "JO": "Jordan", |
| + "JP": "Japan", |
| + "JT": "U.S. Outlying Islands", |
| + "KE": "Kenya", |
| + "KG": "Kyrgyzstan", |
| + "KH": "Cambodia", |
| + "KI": "Kiribati", |
| + "KM": "Comoros", |
| + "KN": "St. Kitts & Nevis", |
| + "KP": "North Korea", |
| + "KR": "South Korea", |
| + "KW": "Kuwait", |
| + "KY": "Cayman Islands", |
| + "KZ": "Kazakhstan", |
| + "LA": "Laos", |
| + "LB": "Lebanon", |
| + "LC": "St. Lucia", |
| + "LI": "Liechtenstein", |
| + "LK": "Sri Lanka", |
| + "LR": "Liberia", |
| + "LS": "Lesotho", |
| + "LT": "Lithuania", |
| + "LU": "Luxembourg", |
| + "LV": "Latvia", |
| + "LY": "Libya", |
| + "MA": "Morocco", |
| + "MC": "Monaco", |
| + "MD": "Moldova", |
| + "ME": "Montenegro", |
| + "MF": "St. Martin", |
| + "MG": "Madagascar", |
| + "MH": "Marshall Islands", |
| + "MI": "U.S. Outlying Islands", |
| + "MK": "North Macedonia", |
| + "ML": "Mali", |
| + "MM": "Myanmar", |
| + "MN": "Mongolia", |
| + "MO": "Macau SAR China", |
| + "MP": "Northern Mariana Islands", |
| + "MQ": "Martinique", |
| + "MR": "Mauritania", |
| + "MS": "Montserrat", |
| + "MT": "Malta", |
| + "MU": "Mauritius", |
| + "MV": "Maldives", |
| + "MW": "Malawi", |
| + "MX": "Mexico", |
| + "MY": "Malaysia", |
| + "MZ": "Mozambique", |
| + "NA": "Namibia", |
| + "NC": "New Caledonia", |
| + "NE": "Niger", |
| + "NF": "Norfolk Island", |
| + "NG": "Nigeria", |
| + "NH": "Vanuatu", |
| + "NI": "Nicaragua", |
| + "NL": "Netherlands", |
| + "NO": "Norway", |
| + "NP": "Nepal", |
| + "NQ": "Antarctica", |
| + "NR": "Nauru", |
| + "NU": "Niue", |
| + "NZ": "New Zealand", |
| + "OM": "Oman", |
| + "PA": "Panama", |
| + "PE": "Peru", |
| + "PF": "French Polynesia", |
| + "PG": "Papua New Guinea", |
| + "PH": "Philippines", |
| + "PK": "Pakistan", |
| + "PL": "Poland", |
| + "PM": "St. Pierre & Miquelon", |
| + "PN": "Pitcairn Islands", |
| + "PR": "Puerto Rico", |
| + "PS": "Palestinian Territories", |
| + "PT": "Portugal", |
| + "PU": "U.S. Outlying Islands", |
| + "PW": "Palau", |
| + "PY": "Paraguay", |
| + "PZ": "Panama", |
| + "QA": "Qatar", |
| + "RE": "Réunion", |
| + "RH": "Zimbabwe", |
| + "RO": "Romania", |
| + "RS": "Serbia", |
| + "RU": "Russia", |
| + "RW": "Rwanda", |
| + "SA": "Saudi Arabia", |
| + "SB": "Solomon Islands", |
| + "SC": "Seychelles", |
| + "SD": "Sudan", |
| + "SE": "Sweden", |
| + "SG": "Singapore", |
| + "SH": "St. Helena", |
| + "SI": "Slovenia", |
| + "SJ": "Svalbard & Jan Mayen", |
| + "SK": "Slovakia", |
| + "SL": "Sierra Leone", |
| + "SM": "San Marino", |
| + "SN": "Senegal", |
| + "SO": "Somalia", |
| + "SR": "Suriname", |
| + "SS": "South Sudan", |
| + "ST": "São Tomé & Príncipe", |
| + "SV": "El Salvador", |
| + "SX": "Sint Maarten", |
| + "SY": "Syria", |
| + "SZ": "Eswatini", |
| + "TC": "Turks & Caicos Islands", |
| + "TD": "Chad", |
| + "TF": "French Southern Territories", |
| + "TG": "Togo", |
| + "TH": "Thailand", |
| + "TJ": "Tajikistan", |
| + "TK": "Tokelau", |
| + "TL": "Timor-Leste", |
| + "TM": "Turkmenistan", |
| + "TN": "Tunisia", |
| + "TO": "Tonga", |
| + "TP": "Timor-Leste", |
| + "TR": "Turkey", |
| + "TT": "Trinidad & Tobago", |
| + "TV": "Tuvalu", |
| + "TW": "Taiwan", |
| + "TZ": "Tanzania", |
| + "UA": "Ukraine", |
| + "UG": "Uganda", |
| + "UK": "United Kingdom", |
| + "UM": "U.S. Outlying Islands", |
| + "US": "United States", |
| + "UY": "Uruguay", |
| + "UZ": "Uzbekistan", |
| + "VA": "Vatican City", |
| + "VC": "St. Vincent & Grenadines", |
| + "VD": "Vietnam", |
| + "VE": "Venezuela", |
| + "VG": "British Virgin Islands", |
| + "VI": "U.S. Virgin Islands", |
| + "VN": "Vietnam", |
| + "VU": "Vanuatu", |
| + "WF": "Wallis & Futuna", |
| + "WK": "U.S. Outlying Islands", |
| + "WS": "Samoa", |
| + "XK": "Kosovo", |
| + "YD": "Yemen", |
| + "YE": "Yemen", |
| + "YT": "Mayotte", |
| + "ZA": "South Africa", |
| + "ZM": "Zambia", |
| + "ZR": "DR Congo", |
| + "ZW": "Zimbabwe", |
| +} |
diff --git a/internal/console/regionbudget_test.go b/internal/console/regionbudget_test.go| index da63d591b..2ba2bc7a0 100644 |
| --- a/internal/console/regionbudget_test.go |
| +++ b/internal/console/regionbudget_test.go |
| @@ -152,11 +152,14 @@ var regionBudgetBaseline = map[string]map[string]int{ |
| "CLI /api/cli/apps/{sqid}/shop/regions": {"Get apps": 1, "Get control": 9, "Get status": 4, "List control": 3, "List status": 2}, |
| "CLI /api/cli/apps/{sqid}/shop/routes": {"Get status": 2, "List status": 1}, |
| "GET /a/{sqid}/": {"Get apps": 5, "Get status": 2, "List apps": 2, "List status": 1}, |
| - "GET /a/{sqid}/apps/shop": {"Get accounts": 1, "Get apps": 4, "Get metrics": 48, "List alerts": 1, "List apps": 2, "List metrics": 1}, |
| - "GET /a/{sqid}/apps/shop/releases": {"Get accounts": 1, "Get apps": 6, "List apps": 3}, |
| - "GET /a/{sqid}/apps/shop/instances": {"Get accounts": 1, "Get apps": 4, "Get control": 3, "Get status": 2, "List apps": 1, "List control": 1, "List status": 1}, |
| - "GET /a/{sqid}/apps/shop/instances/eu.shop.example.com": {"Get accounts": 1, "Get apps": 3, "List apps": 1}, |
| - "GET /a/{sqid}/apps/shop/settings": {"Get accounts": 1, "Get apps": 10, "Get status": 2, "List apps": 5, "List control": 1, "List domains": 1, "List status": 1}, |
| + // The Overview's traffic card (console-analytics-ui, 2026-10-28) adds the |
| + // account's analytics setting and the listing of the app's analytics |
| + // boxes; the labels add nothing. |
| + "GET /a/{sqid}/apps/shop": {"Get accounts": 2, "Get apps": 4, "Get metrics": 48, "List alerts": 1, "List apps": 2, "ListDirs apps": 1, "List metrics": 1}, |
| + "GET /a/{sqid}/apps/shop/releases": {"Get accounts": 1, "Get apps": 6, "List apps": 3}, |
| + "GET /a/{sqid}/apps/shop/instances": {"Get accounts": 1, "Get apps": 4, "Get control": 3, "Get status": 2, "List apps": 1, "List control": 1, "List status": 1}, |
| + "GET /a/{sqid}/apps/shop/instances/eu.shop.example.com": {"Get accounts": 1, "Get apps": 3, "List apps": 1}, |
| + "GET /a/{sqid}/apps/shop/settings": {"Get accounts": 1, "Get apps": 10, "Get status": 2, "List apps": 5, "List control": 1, "List domains": 1, "List status": 1}, |
| } |
| // TestRegionLabelsAddNoStoreReads (spec §7, labels R2-1): no request makes a |
diff --git a/internal/console/server.go b/internal/console/server.go| index fbb878fca..cb240d491 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -166,6 +166,10 @@ var templates = template.Must(template.New("").Funcs(template.FuncMap{ |
| "geoCountries": geoCountries, |
| "geoLabel": geoLabel, |
| "geoAttributions": geoAttributions, |
| + // count and dataSize: the Analytics tab's numbers as a person reads |
| + // them (1,284 and 1.6 MB, decimal units, analyticsdisplay.go). |
| + "count": groupedCount, |
| + "dataSize": humanBytes, |
| // bytesOrDash renders a byte count in the smallest unit that keeps it |
| // readable; nil (no reading, from a unit that reported CPU but not |
| // memory/IO that tick) is "—", never a fabricated 0 B. |
| @@ -1169,6 +1173,9 @@ type Server struct { |
| // reads (usagedays.go), so a cold view reads only today and yesterday; |
| // the hourly economics pass fills it as it reads. |
| usageDays usageDayCache |
| + // trafficMemo holds the Overview traffic card's counts for a minute |
| + // (analyticsview.go, analyticsMemo). |
| + trafficMemo analyticsMemo |
| // storeSizer is the storage pass's test seam for sizing a provisioned |
| // tenant object store: nil means "use the real S3 sizer" |
| // (sizeProvisionedStore, economicspass.go); tests inject a fake so a |
| @@ -2508,6 +2515,11 @@ type page struct { |
| AnalyticsWin analyticsWindow |
| AnalyticsRange string // "today" | "7d" | "30d" |
| AnalyticsErr string |
| + // Traffic is the Overview's traffic card: the Analytics tab's 7-day |
| + // window, read the same way; nil when the read failed. TrafficSlow: it |
| + // had not finished when the rest of the page was ready. |
| + Traffic *analyticsWindow |
| + TrafficSlow bool |
| // Action confirm interstitial (confirm.go): what is about to happen, |
| // carried fields and all. Nil everywhere except the confirm page. |
| @@ -4175,6 +4187,29 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| app := p.Detail.App |
| + // The traffic card reads beside everything else this page reads. The |
| + // page waits for it only until overviewTrafficBudget after the request |
| + // started (trafficWait), then renders the card as still loading: a slow |
| + // bucket costs the card its numbers, never the page its budget. |
| + // The read is under the request's context, so it stops when the |
| + // handler returns, and the channel is buffered, so a late result is |
| + // dropped, not leaked. |
| + start, measured := perf.Started(r.Context()) |
| + if !measured { |
| + start = time.Now() |
| + } |
| + traffic := make(chan *analyticsWindow, 1) |
| + go func() { |
| + ctx, cancel := context.WithTimeout(r.Context(), overviewTrafficTimeout) |
| + defer cancel() |
| + win, err := s.readAnalyticsVia(ctx, acct.Sqid, app, range7d, time.Now(), &s.trafficMemo) |
| + if err != nil { |
| + log.Printf("console: overview traffic %s/%s: %v", acct.Sqid, app, err) |
| + traffic <- nil |
| + return |
| + } |
| + traffic <- &win |
| + }() |
| versions, err := Versions(r.Context(), s.cfg.Releases, acct.Sqid, app) |
| if err != nil { |
| log.Printf("console: versions %s: %v", app, err) |
| @@ -4217,6 +4252,19 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) { |
| // EXECUTION will require, not the one they were proposed under. |
| p.Pending = s.pendingChangeViews(pcs, p.Detail.Pipeline) |
| } |
| + end = perf.Span(r, "s3") |
| + wait := time.NewTimer(trafficWait(start, time.Now())) |
| + select { |
| + case p.Traffic = <-traffic: |
| + case <-wait.C: |
| + select { |
| + case p.Traffic = <-traffic: |
| + default: |
| + p.TrafficSlow = true |
| + } |
| + } |
| + wait.Stop() |
| + end() |
| 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 712ee6623..36b71ab75 100644 |
| --- a/internal/console/templates/app_analytics.html |
| +++ b/internal/console/templates/app_analytics.html |
| @@ -8,6 +8,7 @@ |
| {{/* A failed read resolves to the defaults, which say "off": offering the |
| switch then would be a guess, so the error stands alone. */}} |
| {{if and (not .AnalyticsErr) (not .AnalyticsWin.On)}} |
| +<div class="an-off"> |
| <p><strong>Analytics is off for this app.</strong> |
| When analytics is on, the edge counts HTML page views and daily visitors. No JavaScript, no cookie, no stored IP.</p> |
| {{if .IsOwner}} |
| @@ -20,44 +21,133 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav |
| {{else}} |
| <p class="small">An account owner can turn on analytics.</p> |
| {{end}} |
| +</div> |
| {{end}} |
| {{/* The range picker always shows: numbers counted while analytics was on |
| - stay reachable after it is switched off. With nothing counted in the |
| - window there are no empty tables, chart or "Nothing yet" rows. */}} |
| -<form method="get" class="toolbar"> |
| - <label>range |
| - <select name="range"> |
| - <option value="today"{{if eq .AnalyticsRange "today"}} selected{{end}}>today</option> |
| - <option value="7d"{{if eq .AnalyticsRange "7d"}} selected{{end}}>7 days</option> |
| - <option value="30d"{{if eq .AnalyticsRange "30d"}} selected{{end}}>30 days</option> |
| - </select> |
| - </label> |
| - <button type="submit" class="btn-sm">Update</button> |
| -</form> |
| + 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}} |
| -<div class="tablewrap"><table> |
| - <tr><th>Page views</th><th>Visitors{{if ne $.AnalyticsRange "today"}} (daily visitors, summed){{end}}</th><th>Bytes served</th><th>Bots excluded</th><th>Dropped</th></tr> |
| - <tr><td>{{.Sum.PV}}</td><td>{{.Sum.Visitors}}</td><td>{{.Sum.Bytes}}</td><td>{{.Sum.Bots}}</td><td>{{.Sum.Dropped.Flush}}</td></tr> |
| -</table></div> |
| -{{if .ChartBars}} |
| -<svg viewBox="0 0 480 140" width="100%" role="img" aria-label="Page views"> |
| - {{range .ChartBars}}<rect x="{{.X}}" y="{{.Y}}" width="{{.W}}" height="{{.H}}" fill="currentColor"><title>{{.Label}}: {{.Value}}</title></rect>{{end}} |
| - <text x="0" y="136" class="small">{{if eq $.AnalyticsRange "today"}}per hour, UTC{{else}}per day{{end}}; peak {{.ChartMax}}</text> |
| -</svg> |
| -{{end}} |
| -{{range .Sum.Days}}{{if .Restarted}}<p class="small">{{.Date}}: counts since the last flush may be missing (the edge restarted that day).</p>{{end}}{{end}} |
| -<h3>Top pages{{if .Sum.PagesApprox}} <span class="small">approximate: more than 500 distinct keys</span>{{end}}</h3> |
| -{{template "kvtable" .Sum.Pages}} |
| -<h3>Top referers{{if .Sum.ReferersApprox}} <span class="small">approximate</span>{{end}}</h3> |
| -{{template "kvtable" .Sum.Referers}} |
| -<h3>Named events{{if .Sum.EventsApprox}} <span class="small">approximate</span>{{end}}</h3> |
| -{{template "kvtable" .Sum.Events}} |
| -<h3>Countries</h3> |
| -{{with geoCountries .Sum.Countries}}<div class="tablewrap"><table>{{range sortedKV .}}<tr><td>{{geoLabel .Key}}</td><td>{{.Value}}</td></tr>{{end}}</table></div>{{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}} |
| +{{template "trafficfigures" .}} |
| +{{if .Chart}} |
| +{{template "trafficchart" .Chart}} |
| +{{if .Insights}}<p class="an-insights">{{range $i, $s := .Insights}}{{if $i}} {{end}}{{$s}}{{end}}</p>{{end}} |
| +{{else}} |
| +<p class="an-empty">No page views in this period.</p> |
| +{{end}} |
| +{{template "trafficquality" .}} |
| +<div class="an-breakdowns"> |
| + <section class="an-card" aria-labelledby="an-pages"> |
| + <h3 id="an-pages">Top pages</h3> |
| + {{template "sharelist" .Pages}} |
| + {{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 .Sum.ReferersApprox}}<p class="small">Approximate: more than 500 referrers were seen.</p>{{end}} |
| + </section> |
| + <section class="an-card" aria-labelledby="an-countries"> |
| + <h3 id="an-countries">Countries</h3> |
| + {{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}} |
| + </section> |
| +</div> |
| {{end}} |
| <p class="small">Times are UTC. The same view from a terminal: <code>carlos analytics --app {{.AppName}} --range {{.AnalyticsRange}}</code>.</p> |
| {{end}} |
| {{template "bottom" .}}{{end}} |
| -{{define "kvtable"}}{{if .}}<div class="tablewrap"><table>{{range sortedKV .}}<tr><td>{{.Key}}</td><td>{{.Value}}</td></tr>{{end}}</table></div>{{else}}<p class="small">Nothing yet.</p>{{end}}{{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. */}} |
| +{{define "trafficfigures"}} |
| +<dl class="an-figures"> |
| + <div> |
| + <dt>Page views</dt> |
| + <dd>{{count .Sum.PV}}</dd> |
| + </div> |
| + <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> |
| + </div> |
| + <div> |
| + <dt>Data served</dt> |
| + <dd><span title="{{count .Sum.Bytes}} bytes">{{dataSize .Sum.Bytes}}</span></dd> |
| + </div> |
| +</dl> |
| +{{end}} |
| + |
| +{{/* What could make a number low: bots left out on purpose, counts the |
| + edge dropped, days an edge restarted before it flushed. Said once. */}} |
| +{{define "trafficquality"}} |
| +<p class="an-quality small"> |
| + {{if .Sum.Bots}}{{count .Sum.Bots}} bot request{{if ne .Sum.Bots 1}}s are{{else}} is{{end}} not included in page views or visitors.{{else}}No bots detected.{{end}} |
| + {{if .Sum.Dropped.Flush}} Some counts could not be saved and are missing.{{end}} |
| + {{with .Restarts}} {{.}}{{end}} |
| +</p> |
| +{{end}} |
| + |
| +{{/* The chart: one button per hour or day, so a tooltip opens on hover, |
| + on keyboard focus and on tap. Each button's aria-label says the whole |
| + reading; the visible tooltip says it in lines. Without the script every |
| + column is still a focusable button with its reading. */}} |
| +{{define "trafficchart"}} |
| +<figure class="an-chart an-chart-{{.Unit}}" style="--an-cols: {{.N}}"> |
| + <figcaption class="visually-hidden">Page views per {{.Unit}}, UTC</figcaption> |
| + <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}} |
| + </div> |
| + </div> |
| + <div class="an-xaxis" aria-hidden="true">{{range .XLabels}}<span style="grid-column: {{.Col}}">{{.Label}}</span>{{end}}</div> |
| +</figure> |
| +<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(); |
| + }); |
| + }); |
| +})(); |
| +</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> |
| + <span class="an-val">{{count .Value}}</span> |
| + <span class="an-pct">{{.Share}}</span> |
| + <span class="an-track" aria-hidden="true"><span style="width: {{.Bar}}%"></span></span> |
| +</li>{{end}}</ol>{{else}}<p class="small">Nothing yet.</p>{{end}}{{end}} |
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html| index d3baa211f..9429cf1f6 100644 |
| --- a/internal/console/templates/app_overview.html |
| +++ b/internal/console/templates/app_overview.html |
| @@ -63,6 +63,28 @@ |
| </a> |
| </section> |
| {{end}} |
| +{{/* Traffic: the Analytics tab's 7-day window, read beside the rest of this |
| + page under its own deadline (handleApp). Off shows where to turn it on; |
| + a failed read says so rather than showing zeros. */}} |
| +<section class="an-overview" aria-labelledby="an-overview-head"> |
| + <div class="an-overview-head"> |
| + <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}} |
| +</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 |
| its own per-channel windows (spec §3) — this global on/off line would |
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html| index 20b5604da..31cda574c 100644 |
| --- a/internal/console/templates/layout.html |
| +++ b/internal/console/templates/layout.html |
| @@ -673,6 +673,115 @@ |
| } |
| .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; } |
| + |
| + /* Analytics (app_analytics.html, and the Overview's traffic card). The |
| + chart is the page's one loud element; everything around it stays in |
| + text ink and hairlines. */ |
| + .an-off { margin: 0 0 1.5rem; } |
| + .an-range { display: flex; flex-wrap: wrap; align-items: center; gap: 0.25rem; margin: 0 0 1.75rem; } |
| + .an-range a { |
| + padding: 0.3rem 0.75rem; border-radius: 999px; color: var(--muted); |
| + text-decoration: none; font-size: 0.9rem; |
| + } |
| + .an-range a:hover { color: var(--ink); background: var(--accent-soft); } |
| + .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-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; } |
| + .an-figures dd.an-note { font-size: 0.8rem; font-weight: 400; color: var(--muted); max-width: 16rem; line-height: 1.4; margin-top: 0.3rem; letter-spacing: 0; } |
| + .an-empty { color: var(--muted); padding: 2.5rem 0; border-top: 1px solid var(--rule); border-bottom: 1px solid var(--rule); max-width: none; } |
| + .an-insights { color: var(--ink); font-size: 0.95rem; margin: 0.75rem 0 0.5rem; max-width: none; } |
| + .an-quality { margin: 0 0 2rem; max-width: 48rem; } |
| + |
| + .an-chart { margin: 0; padding-left: 2.25rem; } |
| + .an-plot { position: relative; height: 14rem; } |
| + .an-overview .an-plot { height: 7rem; } |
| + .an-grid span { |
| + position: absolute; left: 0; right: 0; height: 0; |
| + border-top: 1px solid var(--rule); |
| + } |
| + .an-grid i { |
| + position: absolute; right: calc(100% + 0.5rem); top: -0.6em; |
| + font-style: normal; font-size: 0.75rem; color: var(--muted); |
| + font-variant-numeric: tabular-nums; white-space: nowrap; |
| + } |
| + .an-cols, .an-xaxis { display: grid; grid-template-columns: repeat(var(--an-cols), minmax(0, 1fr)); } |
| + .an-cols { position: absolute; inset: 0; } |
| + /* A column is the hit target, full height, so a zero hour still answers |
| + a hover; the bar inside it is capped at 24px and never fills the slot. */ |
| + button.an-col, .an-col { |
| + position: relative; display: flex; align-items: flex-end; justify-content: center; |
| + 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-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); } |
| + /* 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.) */ |
| + .an-partial .an-bar { background: repeating-linear-gradient(135deg, var(--accent) 0 3px, var(--accent-soft) 3px 6px); } |
| + .an-gap::after { |
| + content: ""; position: absolute; bottom: -0.55rem; left: 50%; width: 5px; height: 5px; |
| + margin-left: -2.5px; border-radius: 50%; background: var(--warn); |
| + } |
| + .an-tip { |
| + display: none; position: absolute; z-index: 2; bottom: calc(100% + 0.4rem); left: 50%; |
| + transform: translateX(-50%); width: max-content; max-width: 15rem; |
| + padding: 0.5rem 0.7rem; border-radius: 0.4rem; text-align: left; |
| + background: var(--ink); color: var(--bg); font-size: 0.8rem; line-height: 1.45; |
| + box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18); pointer-events: none; |
| + } |
| + .an-tip b { display: block; font-size: 0.95rem; font-weight: 600; } |
| + .an-tip span { display: block; } |
| + .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; } |
| + /* 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; } |
| + .an-xaxis { margin-top: 0.35rem; font-size: 0.75rem; color: var(--muted); white-space: nowrap; } |
| + .an-xaxis span { justify-self: center; } |
| + |
| + .an-breakdowns { display: grid; grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr)); gap: 2rem 3rem; margin: 0 0 2rem; } |
| + .an-card h3 { font-size: 1rem; margin: 0 0 0.6rem; } |
| + .an-share { list-style: none; margin: 0 0 0.5rem; } |
| + .an-share li { |
| + display: grid; grid-template-columns: minmax(0, 1fr) auto 3rem; column-gap: 0.75rem; |
| + align-items: baseline; padding: 0.4rem 0 0.45rem; border-bottom: 1px solid var(--rule); |
| + } |
| + .an-key { overflow-wrap: anywhere; } |
| + .an-flag { margin-right: 0.4rem; } |
| + .an-val { font-variant-numeric: tabular-nums; text-align: right; } |
| + .an-pct { font-variant-numeric: tabular-nums; text-align: right; color: var(--muted); font-size: 0.85rem; } |
| + .an-track { grid-column: 1 / -1; display: block; height: 3px; margin-top: 0.3rem; border-radius: 2px; background: var(--accent-soft); } |
| + .an-track span { display: block; height: 100%; border-radius: 2px; background: var(--accent); } |
| + .an-muted .an-key { color: var(--muted); } |
| + .an-muted .an-track span { background: var(--muted); opacity: 0.5; } |
| + |
| + .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; } |
| + .an-overview .an-figures { gap: 0.75rem 2.5rem; margin-bottom: 1rem; } |
| + .an-overview .an-figures dd:not(.an-note) { font-size: 1.6rem; } |
| + .an-overview .an-empty { padding: 1.5rem 0; } |
| + @media (max-width: 40rem) { |
| + .an-figures { gap: 1rem 2rem; } |
| + .an-figures dd:not(.an-note) { font-size: 1.75rem; } |
| + .an-plot { height: 11rem; } |
| + .an-span { flex-basis: 100%; margin: 0.4rem 0 0 0.75rem; } |
| + } |
| + @media (forced-colors: active) { |
| + .an-bar, .an-track span { background: CanvasText; } |
| + .an-tip { border: 1px solid CanvasText; } |
| + } |
| .buy-foot { margin: 1.75rem 0 0; } |
| .buy-foot button { padding: 0.7rem 1.5rem; } |
| .billing-upgrades { margin-top: 1.25rem; } |
diff --git a/internal/console/testdata/perf-session-s3.txt b/internal/console/testdata/perf-session-s3.txt| index 090b46a84..1e73bcc33 100644 |
| --- a/internal/console/testdata/perf-session-s3.txt |
| +++ b/internal/console/testdata/perf-session-s3.txt |
| @@ -1 +1 @@ |
| -401 after console-perf-hot-routes, 2026-10-27: the fixture now has seven boxes, six edges files and four live apps, one with 30 instances (320 before on the old fixture); the concurrent reads add no request |
| +415 after console-analytics-ui, 2026-10-28: the Overview's traffic card reads the app's analytics (one listing, the week's day files through the settled-day cache, the two settings objects); its counts are held a minute, so each later Overview view adds only the two settings reads (401 before) |
diff --git a/internal/console/usagedays.go b/internal/console/usagedays.go| index 353bfafba..aa2cc0605 100644 |
| --- a/internal/console/usagedays.go |
| +++ b/internal/console/usagedays.go |
| @@ -12,6 +12,7 @@ import ( |
| "sync" |
| "time" |
| + "github.com/carlosframework/platform/internal/analytics" |
| "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/usage" |
| @@ -133,6 +134,13 @@ func usageDayDate(key string) (date string, ok bool) { |
| if box, ok := daysDirBox(dir, usage.EdgeBoxesPrefix); ok { |
| return date, key == usage.EdgeDayKey(box, date) |
| } |
| + // An app's analytics day file (analytics.DayKey), which the Analytics |
| + // tab and the Overview's traffic card read through the same cache: |
| + // apps/<sqid>/<app>/analytics/<box>/days/<date>.json. |
| + if parts := strings.Split(dir, "/"); len(parts) == 6 && parts[0] == "apps" && parts[3] == "analytics" && parts[5] == "days" { |
| + want, err := analytics.DayKey(parts[1], parts[2], parts[4], date) |
| + return date, err == nil && key == want |
| + } |
| return "", false |
| } |
| @@ -189,11 +197,16 @@ func usageDaySettled(date string, now time.Time) bool { |
| } |
| // usageDayFirstKept is the oldest date the cache keeps at now: the first of |
| -// last month, the oldest day any period the page offers starts on. |
| +// last month, the oldest day any economics period starts on, or the first |
| +// day of the Analytics tab's 30 days when that is older (early March, when |
| +// last month is February). |
| func usageDayFirstKept(now time.Time) string { |
| now = now.UTC() |
| - first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC) |
| - return usage.DayOf(first.AddDate(0, -1, 0)) |
| + first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -1, 0) |
| + if a := now.Truncate(24*time.Hour).AddDate(0, 0, -29); a.Before(first) { |
| + first = a |
| + } |
| + return usage.DayOf(first) |
| } |
| // get is key's entry, when it was read less than usageDayMaxAge before now. |
diff --git a/internal/perf/middleware.go b/internal/perf/middleware.go| index 5bf4eee26..bc8b6cee0 100644 |
| --- a/internal/perf/middleware.go |
| +++ b/internal/perf/middleware.go |
| @@ -161,6 +161,16 @@ func fromContext(ctx context.Context) *writer { |
| return q |
| } |
| +// Started is when the middleware began measuring the request: what a |
| +// handler holding part of its page to a latency budget counts from. ok is |
| +// false on a request the middleware did not measure. |
| +func Started(ctx context.Context) (t time.Time, ok bool) { |
| + if q := fromContext(ctx); q != nil { |
| + return q.start, true |
| + } |
| + return time.Time{}, false |
| +} |
| + |
| // Span starts timing one named part of the request's work and returns |
| // the func that ends it; call it with defer. Spans of the same name add |
| // up, so a loop of queries is one "db" span. Each name becomes a |
diff --git a/internal/perf/middleware_test.go b/internal/perf/middleware_test.go| index 469ef8161..22556f6fb 100644 |
| --- a/internal/perf/middleware_test.go |
| +++ b/internal/perf/middleware_test.go |
| @@ -971,3 +971,20 @@ func TestFlushAndHijackStillWork(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +func TestStarted(t *testing.T) { |
| + if _, ok := perf.Started(context.Background()); ok { |
| + t.Fatal("an unmeasured context reported a start") |
| + } |
| + var c perf.Recorder |
| + var got time.Time |
| + var ok bool |
| + h := perf.Middleware(&c, perf.Options{Logger: quiet})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + got, ok = perf.Started(r.Context()) |
| + })) |
| + before := time.Now() |
| + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/apps", nil)) |
| + if !ok || got.Before(before.Add(-time.Second)) || got.After(time.Now()) { |
| + t.Fatalf("Started = %v, %v", got, ok) |
| + } |
| +} |