carlos / platform Public

Merge remote-tracking branch 'origin/main' into billing-usage

Paul Campbell pushed by claude agent, operated by paul@keymail.dev 3f6db0c67c3a12d82b1159c74e591574d2790e77 parent c4d84bcparent 6848807
18 files changed, +801 −91
  • docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md +29 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-live.md +39 −0
  • internal/console/analyticsdisplay.go +5 −3
  • internal/console/analyticsdisplay_test.go +11 −3
  • internal/console/analyticslive.go +189 −0
  • internal/console/analyticslive_test.go +258 −0
  • internal/console/analyticsview.go +104 −28
  • internal/console/claim_invariant_fixtures_test.go +1 −0
  • internal/console/claim_invariant_probes_read_test.go +1 −0
  • internal/console/perfwalk_test.go +6 −0
  • internal/console/server.go +7 −1
  • internal/console/templates/app_analytics.html +103 −38
  • internal/console/templates/app_overview.html +2 −13
  • internal/console/templates/layout.html +12 −4
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/console/testdata/perf-budgets.txt +1 −0
  • internal/provision/analytics_live_census_test.go +31 −0
  • internal/provision/plan9_b8_census_test.go +1 −1

CI passed — run details

diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md
new file mode 100644
index 000000000..2352fe8bc
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-analytics-live-R1.md
@@ -0,0 +1,29 @@
+Reviewed `origin/main...fa2f549501` using the brief at `f924d7f9`. No tracked files changed. No P1 findings.
+
+1. **P2 — Shared-read budget is not enforced.**
+ Evidence: `internal/console/analyticsview.go:419–425` checks the memo, reads storage, then populates it without coordinating concurrent misses. Two tabs refreshing an expired key together both perform the LIST and day-file reads, contradicting “one read a minute per app and view.”
+ **Fix:** coalesce concurrent loads by memo key and add a concurrent-miss witness.
+ **Fault family:** storage request budget.
+
+2. **P2 — Returning to a visible tab can trigger requests one second apart.**
+ Evidence: `internal/console/templates/app_analytics.html:187–204`. The visibility handler calls `refresh()`, but the fixed interval does not check `lastRun`. A Node harness executing this script produced requests at 119,000 ms and 120,000 ms.
+ **Fix:** enforce the minimum interval inside `refresh()`, or reschedule one timeout after each attempt.
+ **Fault family:** browser request budget.
+
+3. **P2 — Dates and day navigation become stale across midnight.**
+ Evidence: `internal/console/templates/app_analytics.html:29–40` puts the span and day navigation outside the refreshed element; line 196 replaces only its contents. An active Today page crosses midnight and displays the new day’s counts beneath yesterday’s date. A past-day page can retain “Next day → today” after that link should name yesterday.
+ **Fix:** refresh the period label and day navigation alongside the numbers.
+ **Fault family:** displayed timeframe must match the data.
+
+4. **P2 — Past-day restart warnings incorrectly say “today.”**
+ Evidence: the new day view calls `restartNote(sum.Days)` at `internal/console/analyticsview.go:442`; `internal/console/analyticsdisplay.go:459–460` describes every single-day restart as happening today. Opening a historical day with `Restarted=true` therefore gives the wrong date.
+ **Fix:** name the actual day, or pass the current date and reserve “today” for a matching date.
+ **Fault family:** historical-day accuracy.
+
+The account gate restricts reads to a member’s account and claimed app. Rendered visitor strings use escaped templates; I found no injection or open redirect.
+
+Request cost is two settings GETs per live request. A memo miss adds a box listing, requested unsettled day files, and settled files absent from the cache. Hidden and idle pages skip new fetches, although an existing fetch can finish. The concurrency and timing findings above prevent the stronger stated budget.
+
+Targeted query, neighbour, chart, insight, timing, and memo tests passed. HTTP tests were blocked by the sandbox refusing loopback sockets; their behavior remains unverified.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-live.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-live.md
new file mode 100644
index 000000000..eaac81923
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-live.md
@@ -0,0 +1,39 @@
+# Review brief: branch analytics-live, round 1 of 3
+
+Repo carlos/platform, branch `analytics-live`, commit fa2f549501 (`git rev-parse fa2f549501` for the full sha).
+Under review: the diff `origin/main...fa2f549501` (internal/console only).
+Authorities: the console Analytics tab as merged (internal/console/analyticsview.go, analyticsdisplay.go, templates/app_analytics.html, app_overview.html), AGENTS.md (stopping rules; S3 request-cost rule: no new polling per box, state a request budget).
+
+You are an independent reviewer. Read the diff, then the code it calls, and check every claim in comments and the commit message against that code.
+
+## Fixed: do not re-argue
+
+- Paul's asks (2026-10-29): the dashboard updates itself; a bar on the Overview opens that timeframe on the Analytics tab; one tooltip at a time. The refresh is a browser poll once a minute by design (the edge writes counts every five minutes).
+
+## What to check
+
+1. The new door GET /a/{sqid}/apps/{app}/analytics/live (analyticslive.go, handleAnalyticsLive): tenant boundary (only the signed-in member's own account's app), what a signed-out or other-account request gets, caching headers, anything a crafted query (view, range, date) can make it read or render. Links it renders use r.PathValue("sqid"): any injection or open-redirect risk?
+2. The traffic memo now serves the live door for every view and the day view: key correctness (range, date, UTC day), staleness, memory bound, and whether a memo hit can show one app's or one account's numbers to another.
+3. parseAnalyticsQuery and the day view: date bounds (last 30 UTC days, today becomes the today range), the day span (whole UTC day), the memo key, dayNeighbours at the window edges, the hourly chart and insights for a past day.
+4. The page script (templates/app_analytics.html, "analyticsscript"): included on both pages, keyboard navigation re-initialised after a swap, refresh pausing (hidden, 30 min idle, pointer or focus inside), the X-Carlos-Live check with redirect "manual", what happens on errors, duplicate timers when both the card and the tab script are on one page. innerHTML of a same-origin answer: any way visitor-controlled strings (paths, referrers, event names, countries) reach it unescaped?
+5. Request budget: per open, visible, active tab one live request a minute; state what each costs (settings reads, LIST, day files) and whether anything polls with the page hidden or idle.
+6. CSS one-tooltip rule and link columns (a.an-col): keyboard focus, touch (a tap on a link column navigates), and that hourly charts keep buttons.
+7. Tests: sound witnesses (analyticslive_test.go); anything in the diff that would fail CI (darwin, windows) or break an existing test.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the area, the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks (its fault family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites; targeted `go test ./internal/console/ -run ...` is fine.
diff --git a/internal/console/analyticsdisplay.go b/internal/console/analyticsdisplay.go
index 311ace7ff..77af1e4ef 100644
--- a/internal/console/analyticsdisplay.go
+++ b/internal/console/analyticsdisplay.go
@@ -38,6 +38,8 @@ func (c *trafficChart) N() int { return len(c.Cols) }
// plot, scaled to the axis top (the rounded-up peak), not to the peak
// itself, so the gridlines mean what their labels say.
type chartCol struct {
+ Date string // the column's UTC day, on a daily chart
+ Href string // where clicking the column goes (linkChartDays), "" for none
When string // "14:00 to 15:00 UTC" or "Tue 27 Oct": the tooltip's first line
Lines []string // the tooltip's readings, value first
Label string // the whole tooltip as one sentence, for aria-label
@@ -94,7 +96,7 @@ func buildTrafficChart(rng string, sum analytics.Summary, now time.Time) *traffi
c.Unit = "day"
today := now.Format("2006-01-02")
for _, d := range sum.Days {
- col := chartCol{Value: d.PV, Partial: d.Date == today, Gap: d.Restarted}
+ col := chartCol{Date: d.Date, Value: d.PV, Partial: d.Date == today, Gap: d.Restarted}
col.When = longDay(d.Date)
pv := plural(d.PV, "page view", "page views")
if col.Partial {
@@ -444,7 +446,7 @@ func analyticsSpanText(rng string, now time.Time) string {
// had not yet saved were lost, so those days may read low. No bound is
// given: a flush runs every five minutes, but a failed flush is held for
// the next one, so a restart can lose more than one window. Up to three days are named; more are counted.
-func restartNote(days []analytics.DaySummary) string {
+func restartNote(days []analytics.DaySummary, now time.Time) string {
var hit []string
for _, d := range days {
if d.Restarted {
@@ -454,7 +456,7 @@ func restartNote(days []analytics.DaySummary) string {
switch n := len(hit); {
case n == 0:
return ""
- case n == 1 && len(days) == 1:
+ case n == 1 && len(days) == 1 && days[0].Date == now.UTC().Format("2006-01-02"):
return "The edge restarted today. Counts it had not saved yet may be missing."
case n == 1:
return "The edge restarted on " + hit[0] + ". Counts it had not saved yet may be missing for that day."
diff --git a/internal/console/analyticsdisplay_test.go b/internal/console/analyticsdisplay_test.go
index 957e40d95..d4393a34d 100644
--- a/internal/console/analyticsdisplay_test.go
+++ b/internal/console/analyticsdisplay_test.go
@@ -149,19 +149,27 @@ func TestAnalyticsInsights(t *testing.T) {
func TestRestartNote(t *testing.T) {
day := func(date string, r bool) analytics.DaySummary { return analytics.DaySummary{Date: date, Restarted: r} }
- if got := restartNote([]analytics.DaySummary{day("2026-10-27", false)}); got != "" {
+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC)
+ if got := restartNote([]analytics.DaySummary{day("2026-10-27", false)}, now); got != "" {
t.Errorf("no restarts = %q", got)
}
- if got := restartNote([]analytics.DaySummary{day("2026-10-26", true), day("2026-10-27", true)}); !strings.Contains(got, "Mon 26 Oct and Tue 27 Oct") {
+ if got := restartNote([]analytics.DaySummary{day("2026-10-26", true), day("2026-10-27", true)}, now); !strings.Contains(got, "Mon 26 Oct and Tue 27 Oct") {
t.Errorf("two restarts = %q", got)
}
var many []analytics.DaySummary
for i := 1; i <= 5; i++ {
many = append(many, day("2026-10-0"+string(rune('0'+i)), true))
}
- if got := restartNote(many); !strings.Contains(got, "on 5 of these days") {
+ if got := restartNote(many, now); !strings.Contains(got, "on 5 of these days") {
t.Errorf("five restarts = %q", got)
}
+ // One day: "today" only when it is today; a past day is named.
+ if got := restartNote([]analytics.DaySummary{day("2026-10-29", true)}, now); !strings.Contains(got, "restarted today") {
+ t.Errorf("today's restart = %q", got)
+ }
+ if got := restartNote([]analytics.DaySummary{day("2026-10-27", true)}, now); strings.Contains(got, "today") || !strings.Contains(got, "Tue 27 Oct") {
+ t.Errorf("a past day's restart = %q, want it named", got)
+ }
}
func TestShareRows(t *testing.T) {
diff --git a/internal/console/analyticslive.go b/internal/console/analyticslive.go
new file mode 100644
index 000000000..96bbdd1e7
--- /dev/null
+++ b/internal/console/analyticslive.go
@@ -0,0 +1,189 @@
+package console
+
+// The Analytics tab and the Overview's traffic card keep themselves current,
+// and a day on either chart opens that day on the tab (Paul, 2026-10-29).
+//
+// A view is a query: one of the three ranges, or one UTC day in the last 30
+// (?date=YYYY-MM-DD), which draws that day's hours. The part of each page
+// that holds numbers is rendered from an analyticsLive, by the page and by
+// the live door alike, so a refresh swaps in exactly what a reload would
+// show. The page's script asks the door once a minute while the page is
+// visible and someone has used it in the last 30 minutes; the door answers
+// through the traffic memo, so every open tab on one app shares one read a
+// minute. Request budget: no timer on the server; per visible, active tab,
+// one live request a minute, which costs the two setting reads and, at most
+// once a minute per app and view, the window's read (a LIST and today's and
+// yesterday's day file per box; settled days come from the usage cache).
+
+import (
+ "context"
+ "log"
+ "net/http"
+ "net/url"
+ "time"
+
+ "github.com/carlosframework/platform/internal/telemetry"
+)
+
+// rangeDay is the query's range when it names one day.
+const rangeDay = "day"
+
+// analyticsDays is how far back a day can be opened: the 30-day range's
+// first day, which is also as far back as the usage cache keeps days.
+const analyticsDays = 30
+
+// analyticsQuery is what one view asks for.
+type analyticsQuery struct {
+ Range string // today | 7d | 30d | day
+ Date string // YYYY-MM-DD when Range is day
+}
+
+// parseAnalyticsQuery reads ?date and ?range. A date in the last 30 UTC days
+// is that day; today's date is the today range; anything else falls back to
+// the range, and an unknown range to today. A page never 400s over its own
+// query string.
+func parseAnalyticsQuery(q url.Values, now time.Time) analyticsQuery {
+ if d := q.Get("date"); d != "" {
+ if t, err := time.Parse("2006-01-02", d); err == nil && t.Format("2006-01-02") == d {
+ today := now.UTC().Truncate(24 * time.Hour)
+ switch {
+ case t.Equal(today):
+ return analyticsQuery{Range: rangeToday}
+ case t.Before(today) && !t.Before(today.AddDate(0, 0, -(analyticsDays-1))):
+ return analyticsQuery{Range: rangeDay, Date: d}
+ }
+ }
+ }
+ if r := q.Get("range"); validRange(r) {
+ return analyticsQuery{Range: r}
+ }
+ return analyticsQuery{Range: rangeToday}
+}
+
+// values is the query as URL parameters, for the live door's address.
+func (q analyticsQuery) values() url.Values {
+ if q.Range == rangeDay {
+ return url.Values{"date": {q.Date}}
+ }
+ return url.Values{"range": {q.Range}}
+}
+
+// dayNeighbours are the days either side of date that can be opened: ""
+// where the window ends, and "today" for the day after yesterday.
+func dayNeighbours(date string, now time.Time) (prev, next string) {
+ t, err := time.Parse("2006-01-02", date)
+ if err != nil {
+ return "", ""
+ }
+ today := now.UTC().Truncate(24 * time.Hour)
+ if p := t.AddDate(0, 0, -1); !p.Before(today.AddDate(0, 0, -(analyticsDays - 1))) {
+ prev = p.Format("2006-01-02")
+ }
+ if n := t.AddDate(0, 0, 1); n.Equal(today) {
+ next = rangeToday
+ } else if n.Before(today) {
+ next = n.Format("2006-01-02")
+ }
+ return prev, next
+}
+
+// linkChartDays makes each column of a daily chart a link to that day on the
+// Analytics tab at base ("/a/<seg>/apps/<app>/analytics"). Today's column
+// opens the today range. An hourly chart has nothing to open.
+func linkChartDays(c *trafficChart, base string, now time.Time) {
+ if c == nil || c.Unit != "day" {
+ return
+ }
+ today := now.UTC().Format("2006-01-02")
+ for i := range c.Cols {
+ col := &c.Cols[i]
+ switch {
+ case col.Date == "":
+ case col.Date == today:
+ col.Href = base + "?range=today"
+ default:
+ col.Href = base + "?date=" + col.Date
+ }
+ }
+}
+
+// analyticsLive is the refreshable part of the Analytics tab (Card false)
+// or of the Overview's traffic card (Card true).
+type analyticsLive struct {
+ Win *analyticsWindow // nil: the read failed
+ Slow bool // the Overview gave up waiting for the read
+ Card bool
+ AppName string
+ Nav string // "/a/<segment>", what links use
+ Query analyticsQuery
+ Src string // the live door for this view
+ Updated string // "10:42 UTC", when these numbers were read
+}
+
+// newAnalyticsLive assembles one view's live part from a read.
+func newAnalyticsLive(win *analyticsWindow, card bool, app, nav string, q analyticsQuery, now time.Time) *analyticsLive {
+ base := nav + "/apps/" + url.PathEscape(app) + "/analytics"
+ v := q.values()
+ view := "tab"
+ if card {
+ view = "card"
+ }
+ v.Set("view", view)
+ l := &analyticsLive{Win: win, Card: card, AppName: app, Nav: nav, Query: q,
+ Src: base + "/live?" + v.Encode(), Updated: now.UTC().Format("15:04") + " UTC"}
+ if win != nil {
+ linkChartDays(win.Chart, base, now)
+ }
+ return l
+}
+
+// handleAnalyticsLive is the live door: the numbers part of the Analytics tab
+// (?view=tab with the tab's own query) or of the Overview card (?view=card),
+// for a signed-in member of the app's account, through the traffic memo. A
+// failed read answers 503 and the page keeps what it shows.
+func (s *Server) handleAnalyticsLive(w http.ResponseWriter, r *http.Request) {
+ _, _, acct, _, app, ok := s.accountApp(w, r)
+ if !ok {
+ return
+ }
+ now := time.Now()
+ card := r.URL.Query().Get("view") == "card"
+ q := parseAnalyticsQuery(r.URL.Query(), now)
+ if card {
+ q = analyticsQuery{Range: range7d}
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ win, err := s.readAnalyticsFor(ctx, acct.Sqid, app, q, now, &s.trafficMemo)
+ if err != nil {
+ log.Printf("console: analytics live %s/%s: %v", acct.Sqid, app, err)
+ http.Error(w, "analytics unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ // Links keep the account segment the page itself was opened under.
+ nav := "/a/" + url.PathEscape(r.PathValue("sqid"))
+ w.Header().Set("Cache-Control", "no-store")
+ // The page's script uses an answer only when it carries this header, so
+ // a sign-in page (or anything else a redirect lands on) is never pasted
+ // into the page.
+ w.Header().Set("X-Carlos-Live", "1")
+ name := "analyticsdata"
+ if card {
+ name = "trafficcard"
+ }
+ _ = s.writeTemplate(w, http.StatusOK, name, newAnalyticsLive(&win, card, app, nav, q, now))
+}
+
+// trafficCardLive is the Overview card's live part from handleApp's read.
+func trafficCardLive(win *analyticsWindow, slow bool, app, nav string, now time.Time) *analyticsLive {
+ l := newAnalyticsLive(win, true, app, nav, analyticsQuery{Range: range7d}, now)
+ l.Slow = slow
+ return l
+}
+
+// resolveDefaults is the setting a failed read leaves the page with: the
+// defaults a nil store resolves to.
+func resolveDefaults(ctx context.Context, sqid, app string) telemetry.Resolved {
+ res, _ := telemetry.Resolve(ctx, nil, sqid, app)
+ return res
+}
diff --git a/internal/console/analyticslive_test.go b/internal/console/analyticslive_test.go
new file mode 100644
index 000000000..fd6b3752e
--- /dev/null
+++ b/internal/console/analyticslive_test.go
@@ -0,0 +1,258 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/analytics"
+ "github.com/carlosframework/platform/internal/telemetry"
+)
+
+func TestParseAnalyticsQuery(t *testing.T) {
+ now := time.Date(2026, 10, 29, 15, 0, 0, 0, time.UTC)
+ for raw, want := range map[string]analyticsQuery{
+ "": {Range: rangeToday},
+ "range=7d": {Range: range7d},
+ "range=bogus": {Range: rangeToday},
+ "date=2026-10-28": {Range: rangeDay, Date: "2026-10-28"},
+ "date=2026-09-30": {Range: rangeDay, Date: "2026-09-30"}, // the 30-day window's first day
+ "date=2026-09-29": {Range: rangeToday}, // past the window
+ "date=2026-09-29&range=30d": {Range: range30d}, // falls back to the range
+ "date=2026-10-29": {Range: rangeToday}, // today is the today range
+ "date=2026-10-30": {Range: rangeToday}, // the future is not a day
+ "date=2026-10-28T00:00": {Range: rangeToday},
+ "date=2026-1-2": {Range: rangeToday},
+ } {
+ v, _ := url.ParseQuery(raw)
+ if got := parseAnalyticsQuery(v, now); got != want {
+ t.Errorf("parseAnalyticsQuery(%q) = %+v, want %+v", raw, got, want)
+ }
+ }
+}
+
+func TestDayNeighbours(t *testing.T) {
+ now := time.Date(2026, 10, 29, 15, 0, 0, 0, time.UTC)
+ for date, want := range map[string][2]string{
+ "2026-10-28": {"2026-10-27", rangeToday},
+ "2026-10-20": {"2026-10-19", "2026-10-21"},
+ "2026-09-30": {"", "2026-10-01"},
+ } {
+ if p, n := dayNeighbours(date, now); p != want[0] || n != want[1] {
+ t.Errorf("dayNeighbours(%s) = %q %q, want %q %q", date, p, n, want[0], want[1])
+ }
+ }
+}
+
+// A daily chart's columns open their day; today's opens the today range; an
+// hourly chart opens nothing.
+func TestLinkChartDays(t *testing.T) {
+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC)
+ days := []analytics.DaySummary{{Date: "2026-10-28", PV: 3}, {Date: "2026-10-29", PV: 1}}
+ c := buildTrafficChart(range7d, analytics.Summary{Days: days}, now)
+ linkChartDays(c, "/a/shop/apps/site/analytics", now)
+ if c.Cols[0].Href != "/a/shop/apps/site/analytics?date=2026-10-28" || c.Cols[1].Href != "/a/shop/apps/site/analytics?range=today" {
+ t.Fatalf("hrefs = %q %q", c.Cols[0].Href, c.Cols[1].Href)
+ }
+ var d analytics.DaySummary
+ d.Date, d.Hours[9] = "2026-10-29", 2
+ h := buildTrafficChart(rangeToday, analytics.Summary{Days: []analytics.DaySummary{d}}, now)
+ linkChartDays(h, "/a/shop/apps/site/analytics", now)
+ for _, col := range h.Cols {
+ if col.Href != "" {
+ t.Fatalf("an hourly column links to %q", col.Href)
+ }
+ }
+}
+
+// The live door answers the tab's or the card's numbers part, marked so the
+// page's script will use it, to a member; through the memo, so a second
+// refresh within the minute reads no day file.
+func TestAnalyticsLiveDoor(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-live")
+ seedAnalytics(t, fx, seedTime())
+ if err := telemetry.Update(context.Background(), fx.rel, telemetry.AppKey(fx.sqid, "titogo"), func(st *telemetry.Settings) {
+ st.Analytics = &telemetry.Analytics{Count: telemetry.CountEdge}
+ }); err != nil {
+ t.Fatal(err)
+ }
+ cs := &analyticsCountStore{Store: fx.rel}
+ fx.srv.cfg.Releases = cs
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-live-browser")
+
+ res, err := c.Get(fx.u("/apps/titogo/analytics/live?view=tab&range=7d"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := readBody(t, res)
+ if res.StatusCode != http.StatusOK || res.Header.Get("X-Carlos-Live") != "1" || res.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("live tab = %d live=%q cache=%q", res.StatusCode, res.Header.Get("X-Carlos-Live"), res.Header.Get("Cache-Control"))
+ }
+ for _, want := range []string{"<dt>Page views</dt>", "<dd>5</dd>", "Updated ", `class="an-chart an-chart-day"`} {
+ if !strings.Contains(body, want) {
+ t.Errorf("live tab missing %q", want)
+ }
+ }
+ if !strings.Contains(body, "/analytics?range=today") {
+ t.Error("today's column does not open the today range")
+ }
+ if strings.Contains(body, "<html") || strings.Contains(body, "an-off") || !strings.Contains(body, `<nav class="an-range" aria-label="Period">`) {
+ t.Error("live answer carries page chrome, or lacks its period row")
+ }
+ before := cs.dayReads()
+ res, err = c.Get(fx.u("/apps/titogo/analytics/live?view=tab&range=7d"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ readBody(t, res)
+ if got := cs.dayReads() - before; got != 0 {
+ t.Errorf("second refresh within the minute read %d day files, want 0 (memo)", got)
+ }
+
+ res, err = c.Get(fx.u("/apps/titogo/analytics/live?view=card"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if body := readBody(t, res); res.StatusCode != 200 || !strings.Contains(body, `class="an-chart an-chart-day"`) || strings.Contains(body, "Top pages") {
+ t.Errorf("live card = %d, want the card body only", res.StatusCode)
+ }
+
+ // Signed out: no live answer, so the script keeps what it shows.
+ anon := newBrowser(t)
+ res, err = anon.Get(fx.u("/apps/titogo/analytics/live?view=tab"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ readBody(t, res)
+ if res.StatusCode == http.StatusOK || res.Header.Get("X-Carlos-Live") == "1" {
+ t.Errorf("signed-out live = %d live=%q, want no live answer", res.StatusCode, res.Header.Get("X-Carlos-Live"))
+ }
+ // An app the account does not have: 404, as every app door answers.
+ if status, _, _ := get(t, c, fx.u("/apps/nosuch/analytics/live?view=tab")); status != http.StatusNotFound {
+ t.Errorf("live for an unknown app = %d, want 404", status)
+ }
+}
+
+// ?date= opens one day: its hours, the day's name, its neighbours, and no
+// terminal hint (the CLI has no day view).
+func TestAnalyticsTabDayView(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-day")
+ yesterday := seedTime().AddDate(0, 0, -1)
+ seedAnalytics(t, fx, yesterday)
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-day-browser")
+ date := yesterday.Format("2006-01-02")
+ status, _, body := get(t, c, fx.u("/apps/titogo/analytics?date="+date))
+ if status != http.StatusOK {
+ t.Fatalf("day view = %d", status)
+ }
+ for _, want := range []string{`class="an-chart an-chart-hour"`, fmtDate(date, "Mon 2 Jan 2006") + " UTC", "Previous day", `href="?range=today">Next day`, "Estimated.", "<dd>5</dd>"} {
+ if !strings.Contains(body, want) {
+ t.Errorf("day view missing %q", want)
+ }
+ }
+ if strings.Contains(body, "carlos analytics --app") {
+ t.Error("day view shows a terminal hint the CLI cannot follow")
+ }
+ if strings.Contains(body, `aria-current="page">Today`) {
+ t.Error("day view marks Today as the current period")
+ }
+}
+
+// One tooltip at a time: the rule that hides a focused column's tip while
+// another is hovered is in the stylesheet.
+func TestOneTooltipAtATime(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-onetip")
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-onetip-browser")
+ _, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
+ if !strings.Contains(body, ".an-cols:hover .an-col:focus:not(:hover) .an-tip { display: none; }") {
+ t.Fatal("the one-tooltip rule is missing from the page's styles")
+ }
+}
+
+func readBody(t *testing.T, res *http.Response) string {
+ t.Helper()
+ defer res.Body.Close()
+ var b strings.Builder
+ buf := make([]byte, 32<<10)
+ for {
+ n, err := res.Body.Read(buf)
+ b.Write(buf[:n])
+ if err != nil {
+ break
+ }
+ }
+ return b.String()
+}
+
+// Concurrent misses on one key make one read: the live door's budget is one
+// read a minute per app and view, however many tabs refresh at once.
+func TestAnalyticsMemoCoalescesConcurrentMisses(t *testing.T) {
+ var m analyticsMemo
+ now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC)
+ var reads atomic.Int32
+ release := make(chan struct{})
+ read := func() (analytics.Summary, error) {
+ reads.Add(1)
+ <-release
+ return analytics.Summary{PV: 9}, nil
+ }
+ var wg sync.WaitGroup
+ got := make([]int64, 8)
+ for i := range got {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ sum, err := m.load(context.Background(), "k", now, read)
+ if err != nil {
+ t.Error(err)
+ }
+ got[i] = sum.PV
+ }(i)
+ }
+ time.Sleep(50 * time.Millisecond) // let every caller arrive while the read runs
+ close(release)
+ wg.Wait()
+ if n := reads.Load(); n != 1 {
+ t.Fatalf("8 concurrent misses made %d reads, want 1", n)
+ }
+ for i, pv := range got {
+ if pv != 9 {
+ t.Fatalf("caller %d got %d, want the shared read's 9", i, pv)
+ }
+ }
+ // A waiter gives up with its own context.
+ block := make(chan struct{})
+ defer close(block)
+ go m.load(context.Background(), "slow", now, func() (analytics.Summary, error) { <-block; return analytics.Summary{}, nil })
+ time.Sleep(20 * time.Millisecond)
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if _, err := m.load(ctx, "slow", now, read); err == nil {
+ t.Fatal("a waiter outlived its context")
+ }
+}
+
+// The page script never refreshes closer than a minute apart, whatever asks
+// (the interval, or coming back to the tab).
+func TestAnalyticsScriptRefreshesAtMostOnceAMinute(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-script")
+ seedAnalytics(t, fx, seedTime())
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-script-browser")
+ _, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
+ if !strings.Contains(body, "if (Date.now() - lastRun < 55000) return;") {
+ t.Fatal("the refresh's minimum interval is missing")
+ }
+}
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go
index 8880a16d3..8a8072f95 100644
--- a/internal/console/analyticsview.go
+++ b/internal/console/analyticsview.go
@@ -248,6 +248,9 @@ type analyticsWindow struct {
Countries []shareRow
// Restarts is restartNote's sentence, "" when no edge restarted.
Restarts string
+ // Date is the day a day view shows (Range "day"), with the days either
+ // side that can be opened (dayNeighbours).
+ Date, Prev, Next string
}
// HasData reports whether the window holds anything counted. With analytics
@@ -275,8 +278,56 @@ const (
// it; someone looking at analytics gets the bucket as it is. A held
// Summary is shared between views and must not be changed.
type analyticsMemo struct {
- mu sync.Mutex
- m map[string]analyticsMemoEntry
+ mu sync.Mutex
+ m map[string]analyticsMemoEntry
+ inflight map[string]*analyticsMemoCall
+}
+
+// analyticsMemoCall is one read in progress, which every caller asking for
+// the same key while it runs waits on rather than starting its own.
+type analyticsMemoCall struct {
+ done chan struct{}
+ sum analytics.Summary
+ err error
+}
+
+// load is key's counts: from the memo when held, else from the one read
+// in progress for key, else from read, which this caller runs and keeps.
+// Concurrent misses on one key (two tabs refreshing in the same second)
+// make one read, so the budget is one read a minute per app and view
+// however many pages ask. A waiter gives up with its own context; a failed
+// read is not kept, and the next caller reads again.
+func (c *analyticsMemo) load(ctx context.Context, key string, now time.Time, read func() (analytics.Summary, error)) (analytics.Summary, error) {
+ if sum, ok := c.get(key, now); ok {
+ return sum, nil
+ }
+ c.mu.Lock()
+ if call, ok := c.inflight[key]; ok {
+ c.mu.Unlock()
+ select {
+ case <-call.done:
+ return call.sum, call.err
+ case <-ctx.Done():
+ return analytics.Summary{}, ctx.Err()
+ }
+ }
+ if c.inflight == nil {
+ c.inflight = map[string]*analyticsMemoCall{}
+ }
+ call := &analyticsMemoCall{done: make(chan struct{})}
+ c.inflight[key] = call
+ c.mu.Unlock()
+ defer func() {
+ c.mu.Lock()
+ delete(c.inflight, key)
+ c.mu.Unlock()
+ close(call.done)
+ }()
+ call.sum, call.err = read()
+ if call.err == nil {
+ c.put(key, call.sum, now)
+ }
+ return call.sum, call.err
}
type analyticsMemoEntry struct {
@@ -371,20 +422,35 @@ func analyticsSpan(rng string, now time.Time) (from, to time.Time) {
}
}
+// analyticsQuerySpan is analyticsSpan for a query: a day view covers that
+// whole UTC day, which is over (parseAnalyticsQuery makes today a range).
+func analyticsQuerySpan(q analyticsQuery, now time.Time) (from, to time.Time) {
+ if q.Range == rangeDay {
+ if d, err := time.Parse("2006-01-02", q.Date); err == nil {
+ return d, d.Add(24*time.Hour - time.Nanosecond)
+ }
+ }
+ return analyticsSpan(q.Range, now)
+}
+
// readAnalytics assembles the window. It resolves the setting first and then
// reads whichever way that came out: numbers already collected are still
// shown after an owner turns counting off, because they were collected while
// it was on and hiding them would read as data loss.
func (s *Server) readAnalytics(ctx context.Context, sqid, app, rng string, now time.Time) (analyticsWindow, error) {
- return s.readAnalyticsVia(ctx, sqid, app, rng, now, nil)
+ return s.readAnalyticsFor(ctx, sqid, app, analyticsQuery{Range: rng}, now, nil)
}
-// readAnalyticsVia is readAnalytics, with the counts taken from memo when
-// it holds them for this window (the Overview's traffic card). The setting
-// is read every time either way: an owner who turns analytics on sees it
-// on at once.
-func (s *Server) readAnalyticsVia(ctx context.Context, sqid, app, rng string, now time.Time, memo *analyticsMemo) (analyticsWindow, error) {
- out := analyticsWindow{Range: rng}
+// readAnalyticsFor is readAnalytics for any query, a day included, with the
+// counts taken from memo when it holds them for this window (the Overview's
+// traffic card and the live door). The setting is read every time either
+// way: an owner who turns analytics on sees it on at once.
+func (s *Server) readAnalyticsFor(ctx context.Context, sqid, app string, q analyticsQuery, now time.Time, memo *analyticsMemo) (analyticsWindow, error) {
+ rng := q.Range
+ out := analyticsWindow{Range: rng, Date: q.Date}
+ if rng == rangeDay {
+ out.Prev, out.Next = dayNeighbours(q.Date, now)
+ }
res, err := telemetry.Resolve(ctx, s.cfg.Releases, sqid, app)
if err != nil {
return out, err
@@ -396,25 +462,35 @@ func (s *Server) readAnalyticsVia(ctx context.Context, sqid, app, rng string, no
if s.cfg.Releases == nil {
return out, nil
}
- from, to := analyticsSpan(rng, now)
- key := sqid + "/" + app + "/" + rng + "/" + to.Format("2006-01-02")
- sum, hit := memo.get(key, now)
- if !hit {
+ from, to := analyticsQuerySpan(q, now)
+ key := sqid + "/" + app + "/" + rng + "/" + q.Date + "/" + now.UTC().Format("2006-01-02")
+ var sum analytics.Summary
+ if memo == nil {
sum, err = s.readAnalyticsRange(ctx, sqid, app, from, to, now)
- if err != nil {
- return out, err
- }
- memo.put(key, sum, now)
+ } else {
+ sum, err = memo.load(ctx, key, now, func() (analytics.Summary, error) {
+ return s.readAnalyticsRange(ctx, sqid, app, from, to, now)
+ })
+ }
+ if err != nil {
+ return out, err
}
out.Sum = sum
- out.Span = analyticsSpanText(rng, now)
- out.Chart = buildTrafficChart(rng, sum, now)
- out.Insights = analyticsInsights(rng, sum, now)
+ // A day is drawn as today is: its hours.
+ shape := rng
+ if rng == rangeDay {
+ shape = rangeToday
+ out.Span = fmtDate(q.Date, "Mon 2 Jan 2006") + " UTC"
+ } else {
+ out.Span = analyticsSpanText(rng, now)
+ }
+ out.Chart = buildTrafficChart(shape, sum, now)
+ out.Insights = analyticsInsights(shape, sum, now)
out.Pages = 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)
+ out.Restarts = restartNote(sum.Days, now)
return out, nil
}
@@ -479,14 +555,13 @@ func (s *Server) handleAppAnalytics(w http.ResponseWriter, r *http.Request) {
}
// A page never 400s over its own query string: an unknown range falls
// back to today, the way the Errors tab falls back to its default window
- // rather than refusing a URL someone mistyped.
- p.AnalyticsRange = r.URL.Query().Get("range")
- if !validRange(p.AnalyticsRange) {
- p.AnalyticsRange = rangeToday
- }
+ // rather than refusing a URL someone mistyped (parseAnalyticsQuery).
+ now := time.Now()
+ q := parseAnalyticsQuery(r.URL.Query(), now)
+ p.AnalyticsRange = q.Range
ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
defer cancel()
- win, err := s.readAnalytics(ctx, acct.Sqid, p.AppName, p.AnalyticsRange, time.Now())
+ win, err := s.readAnalyticsFor(ctx, acct.Sqid, p.AppName, q, now, nil)
if err != nil {
log.Printf("console: app analytics %s/%s: %v", acct.Sqid, p.AppName, err)
p.AnalyticsErr = "The analytics could not be read just now — try again in a moment."
@@ -494,9 +569,10 @@ func (s *Server) handleAppAnalytics(w http.ResponseWriter, r *http.Request) {
// then say counting is off "from the " with nothing after it. The
// defaults are what a nil store resolves to, so ask for them rather
// than restating them here.
- win.Setting, _ = telemetry.Resolve(ctx, nil, acct.Sqid, p.AppName)
+ win.Setting = resolveDefaults(ctx, acct.Sqid, p.AppName)
}
p.AnalyticsWin = win
+ p.AnalyticsLive = newAnalyticsLive(&p.AnalyticsWin, false, p.AppName, p.Nav, q, now)
s.render(w, http.StatusOK, "app_analytics", p)
}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 4b629fe00..03b99df60 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -798,6 +798,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /a/{sqid}/apps/{app}/account-review": claimRead("renders the route-account review card"),
"route GET /a/{sqid}/apps/{app}/activity": claimRead("renders the app's audit trail"),
"route GET /a/{sqid}/apps/{app}/analytics": claimRead("renders analytics read from the bucket"),
+ "route GET /a/{sqid}/apps/{app}/analytics/live": claimRead("renders the Analytics tab's or Overview card's numbers part, read from the bucket through the traffic memo; writes nothing"),
"route GET /a/{sqid}/apps/{app}/availability": claimRead("renders edge availability counts"),
"route GET /a/{sqid}/apps/{app}/deployments": claimRead("redirects to the releases page"),
"route GET /a/{sqid}/apps/{app}/errors": claimRead("renders grouped app errors"),
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index d47cbfe41..b1ec3ca4a 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -143,6 +143,7 @@ var claimReadProbes = map[string]claimProbe{
"route GET /a/{sqid}/apps/{app}/account-review": claimPageRead(nil, "/a/bab/apps/kass/account-review", "kass"),
"route GET /a/{sqid}/apps/{app}/activity": claimPageRead(nil, "/a/bab/apps/kass/activity", "kass"),
"route GET /a/{sqid}/apps/{app}/analytics": claimPageRead(nil, "/a/bab/apps/titogo/analytics", "titogo"),
+ "route GET /a/{sqid}/apps/{app}/analytics/live": claimPageRead(nil, "/a/bab/apps/titogo/analytics/live?view=tab", "titogo"),
"route GET /a/{sqid}/apps/{app}/availability": claimPageRead(nil, "/a/bab/apps/titogo/availability", "titogo"),
"route GET /a/{sqid}/apps/{app}/deployments": claimRedirectRead("/a/bab/apps/kass/deployments", http.StatusSeeOther, "/a/bab/apps/kass/releases"),
"route GET /a/{sqid}/apps/{app}/errors": claimPageRead(nil, "/a/bab/apps/titogo/errors", "titogo"),
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go
index b1a9336b5..c2bbe75a8 100644
--- a/internal/console/perfwalk_test.go
+++ b/internal/console/perfwalk_test.go
@@ -518,6 +518,12 @@ func perfTargets(fx *consoleFixture) map[string][]perfTarget {
"instances", "logs", "logs/data", "settings"} {
m["GET /a/{sqid}/apps/{app}/"+tab] = ok(app + "/" + tab)
}
+ // The live door (analyticslive.go): the tab's numbers part and the
+ // Overview card's, each read through the traffic memo.
+ m["GET /a/{sqid}/apps/{app}/analytics/live"] = []perfTarget{
+ {Path: app + "/analytics/live?view=tab&range=7d", Expect: http.StatusOK},
+ {Path: app + "/analytics/live?view=card", Expect: http.StatusOK},
+ }
// /deployments is a 303 to Releases; the fixture's page 2 of Versions is
// the empty-page state, which still runs the listing.
m["GET /a/{sqid}/apps/{app}/deployments"] = []perfTarget{{Path: app + "/deployments", Expect: http.StatusSeeOther}}
diff --git a/internal/console/server.go b/internal/console/server.go
index a1833e415..506f8dd84 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1856,6 +1856,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// gate the errors level does at both levels, and bumps the serial where
// the errors level does not: a box acts on whether the edge counts.
s.registerRoute("GET /a/{sqid}/apps/{app}/analytics", s.handleAppAnalytics)
+ s.registerRoute("GET /a/{sqid}/apps/{app}/analytics/live", s.handleAnalyticsLive)
s.registerRoute("POST /a/{sqid}/apps/{app}/analytics/setting", s.handleAppAnalyticsSetting)
s.registerRoute("GET /a/{sqid}/apps/{app}/activity", s.handleAppActivity)
s.registerRoute("GET /a/{sqid}/apps/{app}/settings", s.handleAppSettings)
@@ -2542,6 +2543,10 @@ type page struct {
// had not finished when the rest of the page was ready.
Traffic *analyticsWindow
TrafficSlow bool
+ // AnalyticsLive and TrafficLive are the refreshable parts of the
+ // Analytics tab and the Overview card (analyticslive.go).
+ AnalyticsLive *analyticsLive
+ TrafficLive *analyticsLive
// Action confirm interstitial (confirm.go): what is about to happen,
// carried fields and all. Nil everywhere except the confirm page.
@@ -4224,7 +4229,7 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) {
go func() {
ctx, cancel := context.WithTimeout(r.Context(), overviewTrafficTimeout)
defer cancel()
- win, err := s.readAnalyticsVia(ctx, acct.Sqid, app, range7d, time.Now(), &s.trafficMemo)
+ win, err := s.readAnalyticsFor(ctx, acct.Sqid, app, analyticsQuery{Range: range7d}, time.Now(), &s.trafficMemo)
if err != nil {
log.Printf("console: overview traffic %s/%s: %v", acct.Sqid, app, err)
traffic <- nil
@@ -4287,6 +4292,7 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) {
}
wait.Stop()
end()
+ p.TrafficLive = trafficCardLive(p.Traffic, p.TrafficSlow, p.AppName, p.Nav, time.Now())
s.render(w, http.StatusOK, "app_overview", p)
}
diff --git a/internal/console/templates/app_analytics.html b/internal/console/templates/app_analytics.html
index 36b71ab75..161c93e53 100644
--- a/internal/console/templates/app_analytics.html
+++ b/internal/console/templates/app_analytics.html
@@ -26,14 +26,28 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
{{/* The range picker always shows: numbers counted while analytics was on
stay reachable after it is switched off. Three links rather than a
select and a button: one click, and every view is a URL. */}}
-<nav class="an-range" aria-label="Period">
- <a href="?range=today"{{if eq .AnalyticsRange "today"}} aria-current="page"{{end}}>Today</a>
- <a href="?range=7d"{{if eq .AnalyticsRange "7d"}} aria-current="page"{{end}}>7 days</a>
- <a href="?range=30d"{{if eq .AnalyticsRange "30d"}} aria-current="page"{{end}}>30 days</a>
- {{if .AnalyticsWin.Span}}<span class="an-span">{{.AnalyticsWin.Span}}</span>{{end}}
-</nav>
-{{if or .AnalyticsWin.On .AnalyticsWin.HasData}}
-{{with .AnalyticsWin}}
+{{/* The period row is part of what refreshes: a page left open across
+ midnight must name the day its numbers are for. */}}
+{{with .AnalyticsLive}}{{if and .Win (or .Win.On .Win.HasData)}}
+<div class="an-live" data-live="{{.Src}}">{{template "analyticsdata" .}}</div>
+{{template "analyticsscript"}}
+{{else}}{{template "analyticsnav" .}}{{end}}{{end}}
+{{template "bottom" .}}{{end}}
+
+{{/* The numbers part of the tab: what a reload would show, and what the
+ live door (analyticslive.go) answers to the page's minute refresh. */}}
+{{define "analyticsnav"}}<nav class="an-range" aria-label="Period">
+ <a href="?range=today"{{if eq .Query.Range "today"}} aria-current="page"{{end}}>Today</a>
+ <a href="?range=7d"{{if eq .Query.Range "7d"}} aria-current="page"{{end}}>7 days</a>
+ <a href="?range=30d"{{if eq .Query.Range "30d"}} aria-current="page"{{end}}>30 days</a>
+ {{with .Win}}{{if .Span}}<span class="an-span">{{.Span}}</span>{{end}}
+ {{if eq .Range "day"}}<span class="an-daynav">
+ {{if .Prev}}<a href="?date={{.Prev}}">Previous day</a>{{end}}
+ {{if eq .Next "today"}}<a href="?range=today">Next day</a>{{else if .Next}}<a href="?date={{.Next}}">Next day</a>{{end}}
+ </span>{{end}}{{end}}
+</nav>{{end}}
+
+{{define "analyticsdata"}}{{if not .Card}}{{template "analyticsnav" .}}{{end}}{{with .Win}}
{{template "trafficfigures" .}}
{{if .Chart}}
{{template "trafficchart" .Chart}}
@@ -65,9 +79,25 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
</section>
</div>
{{end}}
-<p class="small">Times are UTC. The same view from a terminal: <code>carlos analytics --app {{.AppName}} --range {{.AnalyticsRange}}</code>.</p>
+<p class="small">Updated {{.Updated}}. Times are UTC.{{if ne .Query.Range "day"}} The same view from a terminal: <code>carlos analytics --app {{.AppName}} --range {{.Query.Range}}</code>.{{end}}</p>
+{{end}}
+
+{{/* The Overview's traffic card body, refreshed the same way. */}}
+{{define "trafficcard"}}
+{{if .Slow}}
+<p class="small">Traffic is still loading. Reload this page, or check the <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">Analytics</a> tab.</p>
+{{else}}{{with .Win}}
+{{if or .On .HasData}}
+{{template "trafficfigures" .}}
+{{if .Chart}}{{template "trafficchart" .Chart}}{{else}}<p class="an-empty">No page views in the last 7 days.</p>{{end}}
+{{if not .On}}<p class="small">Analytics is off for this app. These are the numbers counted while it was on.</p>{{end}}
+{{else}}
+<p class="small">Analytics is off for this app. Turn it on from the <a href="{{$.Nav}}/apps/{{$.AppName}}/analytics">Analytics</a> tab to see page views and visitors here.</p>
+{{end}}
+{{else}}
+<p class="small">Traffic could not be read just now. Check the <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">Analytics</a> tab.</p>
+{{end}}{{end}}
{{end}}
-{{template "bottom" .}}{{end}}
{{/* The three numbers a reader came for, then the chart. Visitors are
estimated per day, so a multi-day total is a sum of days and says so. */}}
@@ -80,7 +110,7 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
<div>
<dt>Visitors</dt>
<dd>{{count .Sum.Visitors}}</dd>
- <dd class="an-note">{{if eq .Range "today"}}Estimated.{{else}}Daily visitors are added up. One person seen on two days counts twice.{{end}}</dd>
+ <dd class="an-note">{{if eq .Range "today" "day"}}Estimated.{{else}}Daily visitors are added up. One person seen on two days counts twice.{{end}}</dd>
</div>
<div>
<dt>Data served</dt>
@@ -109,41 +139,76 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
<div class="an-plot">
<div class="an-grid" aria-hidden="true">{{range .Ticks}}<span style="bottom: {{.Pct}}%"><i>{{.Label}}</i></span>{{end}}</div>
<div class="an-cols" role="group" aria-label="Page views per {{.Unit}}">
- {{range .Cols}}{{if .Future}}<span class="an-col an-future" aria-hidden="true"></span>{{else}}<button type="button" class="an-col{{if .Partial}} an-partial{{end}}{{if .Gap}} an-gap{{end}}{{if .Edge}} an-edge-{{.Edge}}{{end}}" aria-label="{{.Label}}"><span class="an-bar" style="height: {{.HPct}}%"><span class="an-tip" aria-hidden="true"><b>{{index .Lines 0}}</b>{{range $i, $l := .Lines}}{{if $i}}<span>{{$l}}</span>{{end}}{{end}}<span class="an-when">{{.When}}</span></span></span></button>{{end}}{{end}}
+ {{range .Cols}}{{if .Future}}<span class="an-col an-future" aria-hidden="true"></span>{{else if .Href}}<a class="an-col{{if .Partial}} an-partial{{end}}{{if .Gap}} an-gap{{end}}{{if .Edge}} an-edge-{{.Edge}}{{end}}" href="{{.Href}}" aria-label="{{.Label}}">{{template "chartbar" .}}</a>{{else}}<button type="button" class="an-col{{if .Partial}} an-partial{{end}}{{if .Gap}} an-gap{{end}}{{if .Edge}} an-edge-{{.Edge}}{{end}}" aria-label="{{.Label}}">{{template "chartbar" .}}</button>{{end}}{{end}}
</div>
</div>
<div class="an-xaxis" aria-hidden="true">{{range .XLabels}}<span style="grid-column: {{.Col}}">{{.Label}}</span>{{end}}</div>
</figure>
-<script>
+{{end}}
+
+{{define "chartbar"}}<span class="an-bar" style="height: {{.HPct}}%"><span class="an-tip" aria-hidden="true"><b>{{index .Lines 0}}</b>{{range $i, $l := .Lines}}{{if $i}}<span>{{$l}}</span>{{end}}{{end}}<span class="an-when">{{.When}}</span></span></span>{{end}}
+
+{{/* One script per page, after its charts: arrow keys between a chart's
+ columns, and the minute refresh of every [data-live] part. A refresh
+ waits while a pointer is over the part or focus is in it, pauses while
+ the page is hidden, and stops after 30 minutes with no input, until
+ the next one. A refreshed part is used only if the live door answered
+ it (X-Carlos-Live), so a lapsed session never pastes a sign-in page in. */}}
+{{define "analyticsscript"}}<script>
(function () {
- // Arrow keys move between columns, Home and End jump, Escape closes. The
- // group is one Tab stop: the focused column is the only one with
- // tabindex 0. Pointer hover and tap need nothing here; CSS shows the tip.
- var groups = document.querySelectorAll(".an-cols:not([data-an])");
- groups.forEach(function (g) {
- g.setAttribute("data-an", "");
- var cols = Array.prototype.slice.call(g.querySelectorAll("button.an-col"));
- if (!cols.length) return;
- cols.forEach(function (c, i) { c.tabIndex = i === cols.length - 1 ? 0 : -1; });
- g.addEventListener("keydown", function (e) {
- var i = cols.indexOf(document.activeElement);
- if (i < 0) return;
- var j = i;
- if (e.key === "ArrowRight") j = Math.min(cols.length - 1, i + 1);
- else if (e.key === "ArrowLeft") j = Math.max(0, i - 1);
- else if (e.key === "Home") j = 0;
- else if (e.key === "End") j = cols.length - 1;
- else if (e.key === "Escape") { cols[i].blur(); return; }
- else return;
- e.preventDefault();
- cols[i].tabIndex = -1;
- cols[j].tabIndex = 0;
- cols[j].focus();
+ function initCharts(root) {
+ root.querySelectorAll(".an-cols:not([data-an])").forEach(function (g) {
+ g.setAttribute("data-an", "");
+ var cols = Array.prototype.slice.call(g.querySelectorAll(".an-col:not(.an-future)"));
+ if (!cols.length) return;
+ cols.forEach(function (c, i) { c.tabIndex = i === cols.length - 1 ? 0 : -1; });
+ g.addEventListener("keydown", function (e) {
+ var i = cols.indexOf(document.activeElement);
+ if (i < 0) return;
+ var j = i;
+ if (e.key === "ArrowRight") j = Math.min(cols.length - 1, i + 1);
+ else if (e.key === "ArrowLeft") j = Math.max(0, i - 1);
+ else if (e.key === "Home") j = 0;
+ else if (e.key === "End") j = cols.length - 1;
+ else if (e.key === "Escape") { cols[i].blur(); return; }
+ else return;
+ e.preventDefault();
+ cols[i].tabIndex = -1;
+ cols[j].tabIndex = 0;
+ cols[j].focus();
+ });
+ });
+ }
+ initCharts(document);
+ if (window.anLive || !window.fetch) return;
+ window.anLive = true;
+ var lastInput = Date.now(), lastRun = Date.now();
+ ["pointermove", "keydown", "scroll", "touchstart"].forEach(function (ev) {
+ window.addEventListener(ev, function () { lastInput = Date.now(); }, { passive: true });
+ });
+ function busy(el) { return el.matches(":hover") || el.contains(document.activeElement); }
+ function refresh() {
+ if (document.visibilityState !== "visible" || Date.now() - lastInput > 30 * 60 * 1000) return;
+ if (Date.now() - lastRun < 55000) return; // never closer than a minute, whatever asked
+ lastRun = Date.now();
+ document.querySelectorAll("[data-live]").forEach(function (el) {
+ if (busy(el)) return;
+ fetch(el.getAttribute("data-live"), { credentials: "same-origin", redirect: "manual" })
+ .then(function (r) { return r.ok && r.headers.get("X-Carlos-Live") === "1" ? r.text() : null; })
+ .then(function (html) {
+ if (html === null || busy(el)) return;
+ el.innerHTML = html;
+ initCharts(el);
+ })
+ .catch(function () {});
});
+ }
+ setInterval(refresh, 60000);
+ document.addEventListener("visibilitychange", function () {
+ if (document.visibilityState === "visible") refresh();
});
})();
-</script>
-{{end}}
+</script>{{end}}
{{define "sharelist"}}{{if .}}<ol class="an-share">{{range .}}<li{{if .Muted}} class="an-muted"{{end}}>
<span class="an-key" title="{{.Key}}">{{if .Flag}}<span class="an-flag" aria-hidden="true">{{.Flag}}</span>{{end}}{{.Label}}</span>
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html
index 9429cf1f6..965b79ebc 100644
--- a/internal/console/templates/app_overview.html
+++ b/internal/console/templates/app_overview.html
@@ -71,19 +71,8 @@
<h2 id="an-overview-head">Traffic, last 7 days</h2>
<a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">View analytics</a>
</div>
- {{if .TrafficSlow}}
- <p class="small">Traffic is still loading. Reload this page, or check the <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">Analytics</a> tab.</p>
- {{else}}{{with .Traffic}}
- {{if or .On .HasData}}
- {{template "trafficfigures" .}}
- {{if .Chart}}{{template "trafficchart" .Chart}}{{else}}<p class="an-empty">No page views in the last 7 days.</p>{{end}}
- {{if not .On}}<p class="small">Analytics is off for this app. These are the numbers counted while it was on.</p>{{end}}
- {{else}}
- <p class="small">Analytics is off for this app. Turn it on from the <a href="{{$.Nav}}/apps/{{$.AppName}}/analytics">Analytics</a> tab to see page views and visitors here.</p>
- {{end}}
- {{else}}
- <p class="small">Traffic could not be read just now. Check the <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">Analytics</a> tab.</p>
- {{end}}{{end}}
+ {{with .TrafficLive}}<div class="an-live" data-live="{{.Src}}">{{template "trafficcard" .}}</div>
+ {{template "analyticsscript"}}{{end}}
</section>
{{/* The legacy safety-delay flag: legacy-path-only, exactly as ladder.html
skips this same block in pipeline mode. A pipelined app's bake story is
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index 1d18c1832..db74d4435 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -712,6 +712,8 @@
.an-range a[aria-current="page"] { color: var(--ink); background: var(--accent-soft); font-weight: 600; }
.an-range a:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.an-span { margin-left: 0.75rem; color: var(--muted); font-size: 0.85rem; }
+ .an-daynav { display: inline-flex; gap: 0.25rem; margin-left: 0.5rem; }
+ .an-daynav a { font-size: 0.85rem; }
.an-figures { display: flex; flex-wrap: wrap; gap: 1rem 3.5rem; margin: 0 0 1.5rem; }
.an-figures dt { color: var(--muted); font-size: 0.9rem; }
.an-figures dd { margin: 0; font-size: 2.25rem; font-weight: 600; line-height: 1.15; letter-spacing: -0.01em; }
@@ -741,13 +743,16 @@
height: 100%; padding: 0 1px; margin: 0; border: 0; border-radius: 0.25rem;
background: transparent; color: inherit; font: inherit; cursor: default;
}
- button.an-col:hover, button.an-col:focus-visible { background: var(--accent-soft); }
- button.an-col:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
+ .an-col:not(.an-future):hover, .an-col:not(.an-future):focus-visible { background: var(--accent-soft); }
+ .an-col:not(.an-future):focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
+ /* A day on a daily chart is a link to that day; it reads as the column,
+ not as underlined text. */
+ a.an-col { text-decoration: none; cursor: pointer; }
.an-bar {
position: relative; display: block; width: 100%; max-width: 24px; min-height: 0;
background: var(--accent); border-radius: 4px 4px 0 0;
}
- button.an-col:hover .an-bar, button.an-col:focus-visible .an-bar { background: var(--accent-strong); }
+ .an-col:hover .an-bar, .an-col:focus-visible .an-bar { background: var(--accent-strong); }
/* The hour or day still being counted: the same hue, hatched, because the
bar will still grow. (No percentages in this sheet's own rules: the
metrics boundary tests read every "NN%" on an app page as a reading.) */
@@ -768,7 +773,10 @@
.an-tip .an-when { opacity: 0.75; margin-top: 0.15rem; }
.an-edge-start .an-tip { left: 0; transform: none; }
.an-edge-end .an-tip { left: auto; right: 0; transform: none; }
- button.an-col:hover .an-tip, button.an-col:focus .an-tip { display: block; }
+ .an-col:hover .an-tip, .an-col:focus .an-tip { display: block; }
+ /* One tooltip at a time: while the pointer is over the chart, only the
+ column under it speaks, not one left focused by an earlier click. */
+ .an-cols:hover .an-col:focus:not(:hover) .an-tip { display: none; }
/* The tip is the bar's child, so it opens just above the bar's top,
where the eye already is, and never covers the bar it describes. */
.an-future { cursor: default; }
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 6366076e0..f750d19fb 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -18,6 +18,7 @@ route GET /a/{sqid}/apps/{app}
route GET /a/{sqid}/apps/{app}/account-review
route GET /a/{sqid}/apps/{app}/activity
route GET /a/{sqid}/apps/{app}/analytics
+route GET /a/{sqid}/apps/{app}/analytics/live
route GET /a/{sqid}/apps/{app}/availability
route GET /a/{sqid}/apps/{app}/deployments
route GET /a/{sqid}/apps/{app}/errors
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt
index 6443fbadd..a2b47649e 100644
--- a/internal/console/testdata/perf-budgets.txt
+++ b/internal/console/testdata/perf-budgets.txt
@@ -63,6 +63,7 @@ GET /a/{sqid}/apps/{app}/logs/data deferred: deferred part (the Logs tab's data
# (appframe.go); the account manifest is read once per process. A cold view
# (perfColdReset) reads both: 7 S3 calls, about 80 ms.
/fleet/architecture calls 12: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (12 S3 calls warm and cold, about 390 ms)
+GET /a/{sqid}/apps/{app}/analytics/live calls 2: the live door the Analytics tab and Overview card refresh from once a minute: both telemetry settings, read on every refresh so an owner turning analytics on sees it at once; the window's counts come from the traffic memo, read at most once a minute per app and view (about 50 ms)
GET /a/{sqid}/apps/{app}/analytics calls 4: both telemetry settings, the analytics day listing and one day read (about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 190 ms)
GET /a/{sqid}/apps/{app}/availability calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms)
GET /a/{sqid}/apps/{app}/errors calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms)
diff --git a/internal/provision/analytics_live_census_test.go b/internal/provision/analytics_live_census_test.go
new file mode 100644
index 000000000..034c065ba
--- /dev/null
+++ b/internal/provision/analytics_live_census_test.go
@@ -0,0 +1,31 @@
+package provision
+
+// Record-write census entry for analytics-live (the Analytics tab's live
+// refresh and day view), layered on rootfsFleetFollowupsWriteCensusInventory
+// (main's newest at d3908d93). Reviewed by the branch author. No record write
+// is added, moved or reclassified:
+// - NewServer: registers GET /a/{sqid}/apps/{app}/analytics/live
+// (analyticslive.go), which reads the app's telemetry setting and its
+// analytics day files and renders HTML; it writes nothing. Same
+// "instances" literal: still key-site.
+func analyticsLiveWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), rootfsFleetFollowupsWriteCensusInventory()...)
+ replacements := []censusEntry{
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "d33dc8423332f17c4a02a02d3c8a42a23621b3dfdbdddf5f34a905c3cd2fd7ae"},
+ }
+ for _, r := range replacements {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("analytics-live replacement reclassifies " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("analytics-live replacement of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 0098f6133..506eb1f19 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := rootfsFleetFollowupsWriteCensusInventory()
+ inventory := analyticsLiveWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))