console analytics: live refresh, day click-through, one tooltip at a time
Paul, 2026-10-29: the Analytics dashboard should update itself, a bar on
the Overview should open that timeframe on the Analytics tab, and only
one tooltip should show at a time.
- Live: the tab's numbers part and the Overview card refresh once a minute
from a new door, GET /a/{sqid}/apps/{app}/analytics/live (?view=tab with
the tab's query, or ?view=card), while the page is visible and has had
input in the last 30 minutes, and never under a pointer or focus. The
door answers through the traffic memo (one read a minute per app and
view however many tabs are open), with no-store and X-Carlos-Live: 1;
the script uses only answers carrying that header, so a lapsed session's
sign-in page is never pasted in. Pages and door render one template.
- Day view: ?date=YYYY-MM-DD (the last 30 UTC days) shows that day's hours
with Previous day / Next day; today's date is the today range; anything
else falls back. Every daily bar, on the Overview card and the 7- and
30-day charts, links to its day (today's to the today range).
- One tooltip: a column left focused by a click no longer shows its tip
while another is hovered.
Checked in Chromium (Playwright, scratch harness): one tip after click and
hover elsewhere; an Overview bar opens ?date=; a refresh 60 s later showed
new counts without a reload.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+543
−69
internal/console/analyticsdisplay.go+3 −1internal/console/analyticslive.go+189 −0internal/console/analyticslive_test.go+194 −0internal/console/analyticsview.go+44 −19internal/console/server.go+7 −1internal/console/templates/app_analytics.html+92 −31internal/console/templates/app_overview.html+2 −13internal/console/templates/layout.html+12 −4
CI cancelled — superseded by a newer push — run details
Intent
diff --git a/internal/console/analyticsdisplay.go b/internal/console/analyticsdisplay.go| index 311ace7ff..3c8129a57 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 { |
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..47ce0aec8 |
| --- /dev/null |
| +++ b/internal/console/analyticslive_test.go |
| @@ -0,0 +1,194 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "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, "<nav") { |
| + t.Error("live answer carries page chrome") |
| + } |
| + 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() |
| +} |
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go| index 8880a16d3..ede62e1c7 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 |
| @@ -371,20 +374,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,8 +414,8 @@ 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") |
| + from, to := analyticsQuerySpan(q, now) |
| + key := sqid + "/" + app + "/" + rng + "/" + q.Date + "/" + now.UTC().Format("2006-01-02") |
| sum, hit := memo.get(key, now) |
| if !hit { |
| sum, err = s.readAnalyticsRange(ctx, sqid, app, from, to, now) |
| @@ -407,9 +425,16 @@ func (s *Server) readAnalyticsVia(ctx context.Context, sqid, app, rng string, no |
| memo.put(key, sum, now) |
| } |
| 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) |
| @@ -479,14 +504,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 +518,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/server.go b/internal/console/server.go| index 69c6d7218..afa361e42 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) |
| @@ -2533,6 +2534,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. |
| @@ -4215,7 +4220,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 |
| @@ -4278,6 +4283,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..5d3c19218 100644 |
| --- a/internal/console/templates/app_analytics.html |
| +++ b/internal/console/templates/app_analytics.html |
| @@ -31,9 +31,20 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav |
| <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}} |
| + {{with .AnalyticsWin}}{{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> |
| {{if or .AnalyticsWin.On .AnalyticsWin.HasData}} |
| -{{with .AnalyticsWin}} |
| +{{with .AnalyticsLive}}<div class="an-live" data-live="{{.Src}}">{{template "analyticsdata" .}}</div> |
| +{{template "analyticsscript"}}{{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 "analyticsdata"}}{{with .Win}} |
| {{template "trafficfigures" .}} |
| {{if .Chart}} |
| {{template "trafficchart" .Chart}} |
| @@ -65,9 +76,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 +107,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 +136,75 @@ 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; |
| + 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" && Date.now() - lastRun > 60000) 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 31cda574c..9e75b6887 100644 |
| --- a/internal/console/templates/layout.html |
| +++ b/internal/console/templates/layout.html |
| @@ -687,6 +687,8 @@ |
| .an-range a[aria-current="page"] { color: var(--ink); background: var(--accent-soft); font-weight: 600; } |
| .an-range a:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } |
| .an-span { margin-left: 0.75rem; color: var(--muted); font-size: 0.85rem; } |
| + .an-daynav { display: inline-flex; gap: 0.25rem; margin-left: 0.5rem; } |
| + .an-daynav a { font-size: 0.85rem; } |
| .an-figures { display: flex; flex-wrap: wrap; gap: 1rem 3.5rem; margin: 0 0 1.5rem; } |
| .an-figures dt { color: var(--muted); font-size: 0.9rem; } |
| .an-figures dd { margin: 0; font-size: 2.25rem; font-weight: 600; line-height: 1.15; letter-spacing: -0.01em; } |
| @@ -716,13 +718,16 @@ |
| height: 100%; padding: 0 1px; margin: 0; border: 0; border-radius: 0.25rem; |
| background: transparent; color: inherit; font: inherit; cursor: default; |
| } |
| - button.an-col:hover, button.an-col:focus-visible { background: var(--accent-soft); } |
| - button.an-col:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } |
| + .an-col:not(.an-future):hover, .an-col:not(.an-future):focus-visible { background: var(--accent-soft); } |
| + .an-col:not(.an-future):focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } |
| + /* A day on a daily chart is a link to that day; it reads as the column, |
| + not as underlined text. */ |
| + a.an-col { text-decoration: none; cursor: pointer; } |
| .an-bar { |
| position: relative; display: block; width: 100%; max-width: 24px; min-height: 0; |
| background: var(--accent); border-radius: 4px 4px 0 0; |
| } |
| - button.an-col:hover .an-bar, button.an-col:focus-visible .an-bar { background: var(--accent-strong); } |
| + .an-col:hover .an-bar, .an-col:focus-visible .an-bar { background: var(--accent-strong); } |
| /* The hour or day still being counted: the same hue, hatched, because the |
| bar will still grow. (No percentages in this sheet's own rules: the |
| metrics boundary tests read every "NN%" on an app page as a reading.) */ |
| @@ -743,7 +748,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; } |