carlos / platform Public

console: Analytics tab overhaul and a traffic card on Overview

The tab leads with page views, visitors and data served (decimal units:
1.6 MB, not 1595351). The chart is HTML columns rather than a scaled SVG,
whose caption grew with the window: each hour or day is a button with a
tooltip on hover, focus and tap, arrow keys move between columns, future
hours are not drawn, and the hour or day still counting is hatched. Under
it: the busiest hour or day and the average over full days. Top pages,
referrers, countries and named events are share lists with bars; countries
show their names and flags, not ISO codes. Restart notes collapse into one
sentence. The period picker is three links.

Overview gains a "Traffic, last 7 days" card from the same read, run
beside the page's other reads under a 2 s deadline.

Analytics day files now go through the settled-day usage cache and are
read concurrently (readConcurrently): a warm 30-day view reads two files
per box instead of thirty (TestAnalyticsReadsSettledDaysOnce). No timer,
no new polling.

Copy: Luna pass on Paul's house rules; Astra UX suggestions informed the
layout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 40fbb508c0148fd84ac407c3c6b6d8a10b81f5e1 parent 803c680
12 files changed, +1,363 −152
  • internal/console/analytics_onramp_test.go +11 −8
  • internal/console/analyticsdisplay.go +460 −0
  • internal/console/analyticsdisplay_test.go +267 −0
  • internal/console/analyticsview.go +48 −102
  • internal/console/apianalytics_test.go +3 −3
  • internal/console/appnav_test.go +3 −3
  • internal/console/countrynames.go +278 −0
  • internal/console/server.go +25 −0
  • internal/console/templates/app_analytics.html +123 −33
  • internal/console/templates/app_overview.html +20 −0
  • internal/console/templates/layout.html +109 −0
  • internal/console/usagedays.go +16 −3

CI cancelled — superseded by a newer push — run details

Intent

Human

<task-notification> <task-id>bg3chm21p</task-id> <tool-use-id>toolu_01DCT3worUEf47Xr32WARFgV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ce90495f-c7a7-490e-9b84-a6251050e87f/tasks/bg3chm21p.output</output-file> <status>completed</status> <summary>Background command "/home/paulca/.cache/tmp/claude-1001/analytics-ui/run-astra.sh" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bjr66q0py</task-id> <tool-use-id>toolu_01D55ooWm1A2zbcpdgg2Xkmi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ce90495f-c7a7-490e-9b84-a6251050e87f/tasks/bjr66q0py.output</output-file> <status>completed</status> <summary>Background command "/home/paulca/.cache/tmp/claude-1001/analytics-ui/run-luna.sh" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bbdump7zq</task-id> <tool-use-id>toolu_01VLTZpT4FS1hKY5uNLqLApL</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ce90495f-c7a7-490e-9b84-a6251050e87f/tasks/bbdump7zq.output</output-file> <status>completed</status> <summary>Background command "cd /home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-analytics-ui; TMPDIR=/tmp/g nice -n 19 go test ./internal/console/ -count=1 2&gt;&amp;1 | grep -E '^(--- FAIL|FAIL|ok|panic)|_test.go:[0-9]+' | head -60 &gt; /home/paulca/.cache/tmp/claude-1001/analytics-ui/console-tests.txt; echo done &gt;&gt; /home/paulca/.cache/tmp/claude-1001/analytics-ui/console-tests.txt" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>b5usulnkw</task-id> <tool-use-id>toolu_01SA9g4rfvwVEB5YcttqSNfs</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ce90495f-c7a7-490e-9b84-a6251050e87f/tasks/b5usulnkw.output</output-file> <status>completed</status> <summary>Monitor "Luna copy pass and console tests finishing" stream ended</summary> <event>luna and tests done</event> </task-notification>

Human

<task-notification> <task-id>b40riebcp</task-id> <tool-use-id>toolu_01BBvp4RykJYcA17Jb461W9E</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ce90495f-c7a7-490e-9b84-a6251050e87f/tasks/b40riebcp.output</output-file> <status>completed</status> <summary>Background command "D=/home/paulca/.cache/tmp/claude-1001/analytics-ui; until [ -f $D/luna.done ] &amp;&amp; grep -q '^done' $D/console-tests.txt 2&gt;/dev/null; do sleep 10; done; cat $D/COPY-RESULT.md; echo ====; cat $D/console-tests.txt" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/console/analytics_onramp_test.go b/internal/console/analytics_onramp_test.go
index 523e17858..b348be4dd 100644
--- a/internal/console/analytics_onramp_test.go
+++ b/internal/console/analytics_onramp_test.go
@@ -26,9 +26,12 @@ const (
onrampMemberOff = "An account owner can turn on analytics."
)
-// onrampDataMarkers are the tab's data sections: the summary table, the
-// top-keys tables' empty rows, and the terminal hint under them.
-var onrampDataMarkers = []string{"<th>Page views</th>", "Nothing yet.", "<h3>Top pages", "carlos analytics --app titogo"}
+// onrampDataMarkers are the tab's data sections: the headline figures, the
+// breakdown lists' empty rows, and the terminal hint under them.
+var onrampDataMarkers = []string{"<dt>Page views</dt>", "Nothing yet.", ">Top pages</h3>", "carlos analytics --app titogo"}
+
+// onrampRangePicker is the period picker, which shows in every state.
+const onrampRangePicker = `<nav class="an-range" aria-label="Period">`
func TestAnalyticsTabOffStateOwner(t *testing.T) {
fx, _ := instanceFixture(t, "code-onramp-tab-owner")
@@ -79,7 +82,7 @@ func TestAnalyticsTabOffStateOwner(t *testing.T) {
if strings.Contains(body, onrampOffLead) || strings.Contains(body, onrampTurnOn) {
t.Error("the off state still shows after turning on")
}
- for _, want := range append([]string{`<form method="get" class="toolbar">`}, onrampDataMarkers...) {
+ for _, want := range append([]string{onrampRangePicker}, onrampDataMarkers...) {
if !strings.Contains(body, want) {
t.Errorf("on: the tab is missing the data section %q", want)
}
@@ -144,7 +147,7 @@ func TestAnalyticsTabOffStateKeepsRangePickerForOlderData(t *testing.T) {
c := newBrowser(t)
signUp(t, fx, c, "code-onramp-tab-older-browser")
_, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
- for _, want := range []string{onrampOffLead, onrampTurnOn, `<form method="get" class="toolbar">`, `<option value="7d">`} {
+ for _, want := range []string{onrampOffLead, onrampTurnOn, onrampRangePicker, `<a href="?range=7d">`} {
if !strings.Contains(body, want) {
t.Errorf("off, data only before today: default tab missing %q", want)
}
@@ -155,8 +158,8 @@ func TestAnalyticsTabOffStateKeepsRangePickerForOlderData(t *testing.T) {
}
}
_, _, body = get(t, c, fx.u("/apps/titogo/analytics?range=7d"))
- for _, want := range []string{onrampOffLead, `<form method="get" class="toolbar">`, `<option value="7d" selected>`,
- "<th>Page views</th>", "<td>5</td>", "/pricing"} {
+ for _, want := range []string{onrampOffLead, onrampRangePicker, `<a href="?range=7d" aria-current="page">`,
+ "<dt>Page views</dt>", "<dd>5</dd>", "/pricing"} {
if !strings.Contains(body, want) {
t.Errorf("?range=7d with older data: missing %q", want)
}
@@ -170,7 +173,7 @@ func TestAnalyticsTabOffStateKeepsCountedData(t *testing.T) {
c := newBrowser(t)
signUp(t, fx, c, "code-onramp-tab-data-browser")
_, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
- for _, want := range []string{onrampOffLead, onrampTurnOn, "<th>Page views</th>", "/pricing", `aria-label="Page views"`} {
+ for _, want := range []string{onrampOffLead, onrampTurnOn, "<dt>Page views</dt>", "/pricing", `aria-label="Page views per hour"`} {
if !strings.Contains(body, want) {
t.Errorf("off with counted data: missing %q", want)
}
diff --git a/internal/console/analyticsdisplay.go b/internal/console/analyticsdisplay.go
new file mode 100644
index 000000000..f94e4e4db
--- /dev/null
+++ b/internal/console/analyticsdisplay.go
@@ -0,0 +1,460 @@
+package console
+
+// What the Analytics tab and the Overview's traffic card draw from one
+// analyticsWindow: the chart's columns with their tooltips, the axis, the
+// two insight lines and the share rows of the breakdown tables. Everything
+// here is arithmetic on a Summary already read; nothing here reads the
+// store.
+//
+// The chart is HTML, not SVG. The old SVG scaled its viewBox to the column
+// it landed in, so its caption grew with the window (a 1,900 px wide page
+// drew 40 px text) and its one bar filled the plot. Columns in a CSS grid
+// keep text at text size at every width, and each column is a button, so
+// the tooltip is reachable by pointer, keyboard and touch alike.
+
+import (
+ "fmt"
+ "math"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/analytics"
+)
+
+// trafficChart is one plotted window: a column per hour (today) or per day.
+type trafficChart struct {
+ Cols []chartCol
+ Ticks []chartTick
+ XLabels []chartXLabel
+ // Unit is "hour" or "day", for the caption and the CSS.
+ Unit string
+}
+
+// N is the column count, for the grid template.
+func (c *trafficChart) N() int { return len(c.Cols) }
+
+// chartCol is one column. HPct is the bar's height as a percentage of the
+// plot, scaled to the axis top (the rounded-up peak), not to the peak
+// itself, so the gridlines mean what their labels say.
+type chartCol struct {
+ When string // "14:00 to 15:00 UTC" or "Tue 27 Oct": the tooltip's first line
+ Lines []string // the tooltip's readings, value first
+ Label string // the whole tooltip as one sentence, for aria-label
+ Value int64
+ HPct float64
+ Partial bool // the current hour or today: still being counted
+ Future bool // has not happened yet: no bar and no target
+ Gap bool // the edge restarted that day: counts may be missing
+ Edge string
+}
+
+// chartTick is one horizontal gridline, Pct up from the baseline.
+type chartTick struct {
+ Pct float64
+ Label string
+}
+
+// chartXLabel names the column at Col (1-based, a grid column).
+type chartXLabel struct {
+ Col int
+ Label string
+}
+
+// buildTrafficChart lays out the window's page views. Nothing counted in the
+// window returns nil: the page says so in words rather than drawing a flat
+// line under an axis that tops out at one.
+func buildTrafficChart(rng string, sum analytics.Summary, now time.Time) *trafficChart {
+ now = now.UTC()
+ var c trafficChart
+ if rng == rangeToday {
+ c.Unit = "hour"
+ if len(sum.Days) == 0 {
+ return nil
+ }
+ d := sum.Days[len(sum.Days)-1]
+ isToday := d.Date == now.Format("2006-01-02")
+ date := shortDate(d.Date)
+ for h := 0; h < 24; h++ {
+ col := chartCol{Value: d.Hours[h]}
+ col.Future = isToday && h > now.Hour()
+ col.Partial = isToday && h == now.Hour()
+ col.When = fmt.Sprintf("%s, %02d:00 to %02d:00 UTC", date, h, (h+1)%24)
+ reading := plural(d.Hours[h], "page view", "page views")
+ if col.Partial {
+ reading += " so far"
+ }
+ col.Lines = []string{reading}
+ c.Cols = append(c.Cols, col)
+ }
+ for _, h := range []int{0, 6, 12, 18} {
+ c.XLabels = append(c.XLabels, chartXLabel{Col: h + 1, Label: fmt.Sprintf("%02d:00", h)})
+ }
+ } else {
+ c.Unit = "day"
+ today := now.Format("2006-01-02")
+ for _, d := range sum.Days {
+ col := chartCol{Value: d.PV, Partial: d.Date == today, Gap: d.Restarted}
+ col.When = longDay(d.Date)
+ pv := plural(d.PV, "page view", "page views")
+ if col.Partial {
+ pv += " so far"
+ }
+ col.Lines = []string{pv, plural(d.Visitors, "visitor", "visitors"), humanBytes(d.Bytes) + " served"}
+ if d.Restarted {
+ col.Lines = append(col.Lines, "The edge restarted that day. Up to about five minutes may be missing.")
+ }
+ c.Cols = append(c.Cols, col)
+ }
+ c.XLabels = dayXLabels(sum.Days)
+ }
+ var peak int64
+ for _, col := range c.Cols {
+ if !col.Future && col.Value > peak {
+ peak = col.Value
+ }
+ }
+ if peak == 0 {
+ return nil
+ }
+ top := niceCeil(peak)
+ for i := range c.Cols {
+ col := &c.Cols[i]
+ if col.Value > 0 {
+ col.HPct = round2(float64(col.Value) / float64(top) * 100)
+ }
+ col.Label = col.When + ": " + strings.Join(col.Lines, ", ")
+ // The first and last few columns anchor their tooltip to that side,
+ // so it never spills off the chart.
+ switch n := len(c.Cols); {
+ case i < n/6:
+ col.Edge = "start"
+ case i >= n-n/6:
+ col.Edge = "end"
+ }
+ }
+ c.Ticks = []chartTick{{Pct: 0, Label: "0"}, {Pct: 100, Label: compactCount(top)}}
+ if top%2 == 0 {
+ c.Ticks = []chartTick{c.Ticks[0], {Pct: 50, Label: compactCount(top / 2)}, c.Ticks[1]}
+ }
+ return &c
+}
+
+// dayXLabels labels a multi-day axis: every day of a week, every seventh day
+// of a month counted back from today, so today always carries its date.
+func dayXLabels(days []analytics.DaySummary) []chartXLabel {
+ var out []chartXLabel
+ if len(days) <= 7 {
+ for i, d := range days {
+ out = append(out, chartXLabel{Col: i + 1, Label: weekdayDay(d.Date)})
+ }
+ return out
+ }
+ for i := len(days) - 1; i >= 0; i -= 7 {
+ out = append([]chartXLabel{{Col: i + 1, Label: shortDate(days[i].Date)}}, out...)
+ }
+ return out
+}
+
+// niceCeil rounds v up to 1, 2, 4 or 5 times a power of ten: an axis top a
+// reader can halve in their head.
+func niceCeil(v int64) int64 {
+ if v <= 1 {
+ return 1
+ }
+ pow := int64(math.Pow(10, math.Floor(math.Log10(float64(v)))))
+ for _, m := range []int64{1, 2, 4, 5, 10} {
+ if m*pow >= v {
+ return m * pow
+ }
+ }
+ return 10 * pow
+}
+
+// analyticsInsights is the line under the chart: the busiest hour or day,
+// and for a multi-day window the daily average over the days that are over.
+// Today is left out of the average because it is not over, and an average
+// that counts half a day reads as a drop.
+func analyticsInsights(rng string, sum analytics.Summary, now time.Time) []string {
+ var out []string
+ today := now.UTC().Format("2006-01-02")
+ if rng == rangeToday {
+ if len(sum.Days) == 0 {
+ return nil
+ }
+ d := sum.Days[len(sum.Days)-1]
+ best, at := int64(0), 0
+ for h, v := range d.Hours {
+ if v > best {
+ best, at = v, h
+ }
+ }
+ if best > 0 {
+ lead := "Busiest hour"
+ if d.Date == today {
+ lead = "Busiest hour so far"
+ }
+ out = append(out, fmt.Sprintf("%s: %02d:00 UTC, with %s.", lead, at, plural(best, "page view", "page views")))
+ }
+ return out
+ }
+ var best analytics.DaySummary
+ var done, donePV int64
+ for _, d := range sum.Days {
+ if d.PV > best.PV {
+ best = d
+ }
+ if d.Date != today {
+ done++
+ donePV += d.PV
+ }
+ }
+ if best.PV > 0 {
+ out = append(out, fmt.Sprintf("Busiest day: %s, with %s.", longDay(best.Date), plural(best.PV, "page view", "page views")))
+ }
+ if done > 0 && donePV > 0 {
+ out = append(out, fmt.Sprintf("An average of %s per day over the last %d full days.", averageViews(donePV, done), done))
+ }
+ return out
+}
+
+// averageViews is a daily average worded for its size: one decimal under
+// ten, so two views over seven days is not "0 page views a day".
+func averageViews(total, days int64) string {
+ avg := float64(total) / float64(days)
+ if avg < 10 {
+ s := strconv.FormatFloat(math.Round(avg*10)/10, 'f', -1, 64)
+ if s == "1" {
+ return "1 page view"
+ }
+ return s + " page views"
+ }
+ return plural(int64(math.Round(avg)), "page view", "page views")
+}
+
+// shareRow is one row of a breakdown table: what, how many, and its share
+// of the table's total. Bar is the row's length against the table's
+// biggest row, so the longest bar is always full width.
+type shareRow struct {
+ Key string
+ Label string
+ Flag string
+ Value int64
+ Share string
+ Bar float64
+ Muted bool // "other" and "unknown": not a page, a referrer or a country
+}
+
+// shareRows orders m as sortedKV does and works out each row's share.
+// label turns a key into what the row says; nil shows the key.
+func shareRows(m map[string]int64, label func(string) (text, flag string, muted bool)) []shareRow {
+ if len(m) == 0 {
+ return nil
+ }
+ var total, top int64
+ for _, v := range m {
+ total += v
+ if v > top {
+ top = v
+ }
+ }
+ out := make([]shareRow, 0, len(m))
+ for _, kv := range sortedKV(m) {
+ r := shareRow{Key: kv.Key, Label: kv.Key, Value: kv.Value}
+ if label != nil {
+ r.Label, r.Flag, r.Muted = label(kv.Key)
+ }
+ if total > 0 {
+ r.Share = sharePct(kv.Value, total)
+ }
+ if top > 0 {
+ r.Bar = round2(float64(kv.Value) / float64(top) * 100)
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+// sharePct is a share as a whole percentage, with "<1%" for a share that
+// rounds to nothing: a row that was counted never reads as 0%.
+func sharePct(v, total int64) string {
+ p := float64(v) / float64(total) * 100
+ if p > 0 && p < 0.5 {
+ return "<1%"
+ }
+ return strconv.Itoa(int(math.Round(p))) + "%"
+}
+
+// pageLabel words the overflow row of a pages or events table.
+func pageLabel(k string) (string, string, bool) {
+ if k == analytics.OtherKey {
+ return "Everything else", "", true
+ }
+ return k, "", false
+}
+
+// refererLabel words the referrers table: a page view with no Referer
+// header is counted as "direct".
+func refererLabel(k string) (string, string, bool) {
+ switch k {
+ case analytics.OtherKey:
+ return "Everything else", "", true
+ case "direct":
+ return "Direct or unknown", "", true
+ }
+ return k, "", false
+}
+
+// countryLabel is a Countries row: the country's name and its flag, the
+// two reserved buckets in words.
+func countryLabel(k string) (string, string, bool) {
+ switch k {
+ case "_unknown":
+ return "Unknown", "", true
+ case "_other":
+ return "Other countries", "", true
+ }
+ return countryName(k), countryFlag(k), false
+}
+
+// countryName is an ISO 3166-1 alpha-2 code's English name, or the code.
+func countryName(code string) string {
+ if n, ok := countryNames[strings.ToUpper(code)]; ok {
+ return n
+ }
+ return code
+}
+
+// countryFlag is the code as a flag emoji: the two regional indicator
+// letters, which the reader's own system draws. No image is fetched. A
+// code that is not two letters has no flag.
+func countryFlag(code string) string {
+ if len(code) != 2 {
+ return ""
+ }
+ var b strings.Builder
+ for _, r := range strings.ToUpper(code) {
+ if r < 'A' || r > 'Z' {
+ return ""
+ }
+ b.WriteRune(0x1F1E6 + (r - 'A'))
+ }
+ return b.String()
+}
+
+// humanBytes is a byte count in decimal units, the way a person says it:
+// 812 B, 1.6 MB, 16 MB, 160 MB. One decimal below ten, none above.
+func humanBytes(n int64) string {
+ if n < 1000 {
+ return strconv.FormatInt(n, 10) + " B"
+ }
+ v := float64(n)
+ for _, unit := range []string{"KB", "MB", "GB", "TB", "PB"} {
+ v /= 1000
+ if v < 999.5 || unit == "PB" {
+ if v < 9.95 {
+ return strconv.FormatFloat(v, 'f', 1, 64) + " " + unit
+ }
+ return strconv.FormatFloat(math.Round(v), 'f', 0, 64) + " " + unit
+ }
+ }
+ return strconv.FormatInt(n, 10) + " B"
+}
+
+// groupedCount is n with thousands separators: 1,284.
+func groupedCount(n int64) string {
+ s := strconv.FormatInt(n, 10)
+ neg := strings.HasPrefix(s, "-")
+ s = strings.TrimPrefix(s, "-")
+ var b strings.Builder
+ for i, r := range s {
+ if i > 0 && (len(s)-i)%3 == 0 {
+ b.WriteByte(',')
+ }
+ b.WriteRune(r)
+ }
+ if neg {
+ return "-" + b.String()
+ }
+ return b.String()
+}
+
+// compactCount is an axis label: 0, 5, 400, 1.2K, 40K, 3M.
+func compactCount(n int64) string {
+ switch {
+ case n < 1000:
+ return strconv.FormatInt(n, 10)
+ case n < 1_000_000:
+ return trimZero(float64(n)/1000) + "K"
+ default:
+ return trimZero(float64(n)/1_000_000) + "M"
+ }
+}
+
+func trimZero(f float64) string {
+ if f >= 10 {
+ return strconv.FormatFloat(math.Round(f), 'f', 0, 64)
+ }
+ return strconv.FormatFloat(math.Round(f*10)/10, 'f', -1, 64)
+}
+
+// plural is n and the word for it, n grouped: "1 visitor", "1,284 visitors".
+func plural(n int64, one, many string) string {
+ if n == 1 {
+ return "1 " + one
+ }
+ return groupedCount(n) + " " + many
+}
+
+// The date forms the tab uses. A date that does not parse is shown as it
+// came, which only a corrupt day file could produce.
+func shortDate(date string) string { return fmtDate(date, "2 Jan") }
+func longDay(date string) string { return fmtDate(date, "Mon 2 Jan") }
+func weekdayDay(date string) string {
+ return fmtDate(date, "Mon 2")
+}
+
+func fmtDate(date, layout string) string {
+ t, err := time.Parse("2006-01-02", date)
+ if err != nil {
+ return date
+ }
+ return t.Format(layout)
+}
+
+// analyticsSpanText says which days the window covers: "Today, 28 Oct
+// 2026 UTC" or "22 Oct to 28 Oct 2026 UTC".
+func analyticsSpanText(rng string, now time.Time) string {
+ from, to := analyticsSpan(rng, now)
+ if rng == rangeToday {
+ return "Today, " + to.Format("2 Jan 2006") + " UTC"
+ }
+ if from.Year() != to.Year() {
+ return from.Format("2 Jan 2006") + " to " + to.Format("2 Jan 2006") + " UTC"
+ }
+ return from.Format("2 Jan") + " to " + to.Format("2 Jan 2006") + " UTC"
+}
+
+// restartNote is the note for the days an edge restarted: the counts it
+// had not yet saved (a flush runs every five minutes) were lost, so those
+// days may read a little low. Up to three days are named; more are counted.
+func restartNote(days []analytics.DaySummary) string {
+ var hit []string
+ for _, d := range days {
+ if d.Restarted {
+ hit = append(hit, longDay(d.Date))
+ }
+ }
+ switch n := len(hit); {
+ case n == 0:
+ return ""
+ case n == 1 && len(days) == 1:
+ return "The edge restarted today. Up to about five minutes of counts may be missing."
+ case n == 1:
+ return "The edge restarted on " + hit[0] + ". Up to about five minutes of counts may be missing that day."
+ case n <= 3:
+ return "The edge restarted on " + strings.Join(hit[:n-1], ", ") + " and " + hit[n-1] + ". Up to about five minutes of counts may be missing on each day."
+ default:
+ return fmt.Sprintf("The edge restarted on %d of these days. Up to about five minutes of counts may be missing on each day. Those days are marked under the chart.", n)
+ }
+}
diff --git a/internal/console/analyticsdisplay_test.go b/internal/console/analyticsdisplay_test.go
new file mode 100644
index 000000000..2e8448813
--- /dev/null
+++ b/internal/console/analyticsdisplay_test.go
@@ -0,0 +1,267 @@
+package console
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/analytics"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/telemetry"
+)
+
+func TestHumanBytes(t *testing.T) {
+ for n, want := range map[int64]string{
+ 0: "0 B", 999: "999 B", 1000: "1.0 KB", 1595351: "1.6 MB", 9_949_999: "9.9 MB",
+ 9_950_000: "10 MB", 16_400_000: "16 MB", 999_400_000: "999 MB", 999_600_000: "1.0 GB",
+ 846_000_000: "846 MB", 3_200_000_000_000: "3.2 TB",
+ } {
+ if got := humanBytes(n); got != want {
+ t.Errorf("humanBytes(%d) = %q, want %q", n, got, want)
+ }
+ }
+}
+
+func TestGroupedAndCompactCounts(t *testing.T) {
+ for n, want := range map[int64]string{0: "0", 999: "999", 1000: "1,000", 1284: "1,284", 1234567: "1,234,567", -1234: "-1,234"} {
+ if got := groupedCount(n); got != want {
+ t.Errorf("groupedCount(%d) = %q, want %q", n, got, want)
+ }
+ }
+ for n, want := range map[int64]string{5: "5", 400: "400", 1200: "1.2K", 40000: "40K", 2_000_000: "2M"} {
+ if got := compactCount(n); got != want {
+ t.Errorf("compactCount(%d) = %q, want %q", n, got, want)
+ }
+ }
+ if got := plural(1, "visitor", "visitors"); got != "1 visitor" {
+ t.Errorf("plural(1) = %q", got)
+ }
+ if got := plural(1284, "visitor", "visitors"); got != "1,284 visitors" {
+ t.Errorf("plural(1284) = %q", got)
+ }
+}
+
+func TestCountryLabel(t *testing.T) {
+ for code, want := range map[string]string{"IE": "Ireland", "AS": "American Samoa", "GB": "United Kingdom", "MK": "North Macedonia", "ZY": "ZY"} {
+ if got, _, _ := countryLabel(code); got != want {
+ t.Errorf("countryLabel(%q) = %q, want %q", code, got, want)
+ }
+ }
+ if _, flag, _ := countryLabel("IE"); flag != "\U0001F1EE\U0001F1EA" {
+ t.Errorf("IE flag = %q", flag)
+ }
+ for _, k := range []string{"_unknown", "_other"} {
+ if _, flag, muted := countryLabel(k); flag != "" || !muted {
+ t.Errorf("%s: flag %q muted %v, want no flag and muted", k, flag, muted)
+ }
+ }
+}
+
+func TestNiceCeil(t *testing.T) {
+ for v, want := range map[int64]int64{0: 1, 1: 1, 2: 2, 3: 4, 5: 5, 6: 10, 11: 20, 292: 400, 401: 500, 1000: 1000, 1001: 2000} {
+ if got := niceCeil(v); got != want {
+ t.Errorf("niceCeil(%d) = %d, want %d", v, got, want)
+ }
+ }
+}
+
+// Today's chart: hours after now are not plotted and not targets, the
+// current hour is marked as still counting, and bars scale to the axis top.
+func TestTrafficChartToday(t *testing.T) {
+ now := time.Date(2026, 10, 28, 14, 30, 0, 0, time.UTC)
+ var d analytics.DaySummary
+ d.Date = "2026-10-28"
+ d.Hours[9], d.Hours[14] = 3, 1
+ c := buildTrafficChart(rangeToday, analytics.Summary{Days: []analytics.DaySummary{d}}, now)
+ if c == nil || c.N() != 24 || c.Unit != "hour" {
+ t.Fatalf("chart = %+v", c)
+ }
+ if !c.Cols[15].Future || c.Cols[14].Future || !c.Cols[14].Partial {
+ t.Errorf("future/partial wrong: 14 %+v 15 %+v", c.Cols[14], c.Cols[15])
+ }
+ // Peak 3 rounds up to an axis of 4: 75% tall, ticks 0, 2, 4.
+ if c.Cols[9].HPct != 75 || len(c.Ticks) != 3 || c.Ticks[2].Label != "4" {
+ t.Errorf("scale: bar %v ticks %+v", c.Cols[9].HPct, c.Ticks)
+ }
+ if want := "28 Oct, 09:00 to 10:00 UTC: 3 page views"; c.Cols[9].Label != want {
+ t.Errorf("label = %q, want %q", c.Cols[9].Label, want)
+ }
+ if !strings.HasSuffix(c.Cols[14].Label, "1 page view so far") {
+ t.Errorf("current hour label = %q", c.Cols[14].Label)
+ }
+ if buildTrafficChart(rangeToday, analytics.Summary{Days: []analytics.DaySummary{{Date: "2026-10-28"}}}, now) != nil {
+ t.Error("a day with nothing counted drew a chart")
+ }
+}
+
+func TestTrafficChartDays(t *testing.T) {
+ now := time.Date(2026, 10, 28, 10, 0, 0, 0, time.UTC)
+ var days []analytics.DaySummary
+ for i := 0; i < 30; i++ {
+ date := now.AddDate(0, 0, i-29).Format("2006-01-02")
+ days = append(days, analytics.DaySummary{Date: date, PV: int64(i + 1), Visitors: 1, Bytes: 1_600_000, Restarted: i == 3})
+ }
+ c := buildTrafficChart(range30d, analytics.Summary{Days: days}, now)
+ if c == nil || c.N() != 30 || c.Unit != "day" {
+ t.Fatalf("chart = %+v", c)
+ }
+ last := c.Cols[29]
+ if !last.Partial || !strings.Contains(last.Label, "30 page views so far") || !strings.Contains(last.Label, "1.6 MB served") {
+ t.Errorf("today's column = %+v", last)
+ }
+ if !c.Cols[3].Gap || c.Cols[2].Gap {
+ t.Error("restart marker on the wrong day")
+ }
+ // Labels every seventh day back from today, so today has one.
+ if got := c.XLabels[len(c.XLabels)-1]; got.Col != 30 || got.Label != "28 Oct" {
+ t.Errorf("last x label = %+v", got)
+ }
+ if c.Cols[0].Edge != "start" || c.Cols[29].Edge != "end" || c.Cols[15].Edge != "" {
+ t.Error("tooltip anchoring wrong")
+ }
+}
+
+// The average leaves today out: half a day would read as a drop.
+func TestAnalyticsInsights(t *testing.T) {
+ now := time.Date(2026, 10, 28, 10, 0, 0, 0, time.UTC)
+ days := []analytics.DaySummary{{Date: "2026-10-26", PV: 10}, {Date: "2026-10-27", PV: 30}, {Date: "2026-10-28", PV: 1}}
+ got := analyticsInsights(range7d, analytics.Summary{Days: days}, now)
+ want := []string{"Busiest day: Tue 27 Oct, with 30 page views.", "An average of 20 page views per day over the last 2 full days."}
+ if strings.Join(got, "|") != strings.Join(want, "|") {
+ t.Errorf("insights = %q, want %q", got, want)
+ }
+ if got := averageViews(2, 7); got != "0.3 page views" {
+ t.Errorf("averageViews(2, 7) = %q", got)
+ }
+ var d analytics.DaySummary
+ d.Date, d.Hours[14] = "2026-10-28", 3
+ if got := analyticsInsights(rangeToday, analytics.Summary{Days: []analytics.DaySummary{d}}, now); len(got) != 1 || got[0] != "Busiest hour so far: 14:00 UTC, with 3 page views." {
+ t.Errorf("today insights = %q", got)
+ }
+}
+
+func TestRestartNote(t *testing.T) {
+ day := func(date string, r bool) analytics.DaySummary { return analytics.DaySummary{Date: date, Restarted: r} }
+ if got := restartNote([]analytics.DaySummary{day("2026-10-27", false)}); got != "" {
+ t.Errorf("no restarts = %q", got)
+ }
+ if got := restartNote([]analytics.DaySummary{day("2026-10-26", true), day("2026-10-27", true)}); !strings.Contains(got, "Mon 26 Oct and Tue 27 Oct") {
+ t.Errorf("two restarts = %q", got)
+ }
+ var many []analytics.DaySummary
+ for i := 1; i <= 5; i++ {
+ many = append(many, day("2026-10-0"+string(rune('0'+i)), true))
+ }
+ if got := restartNote(many); !strings.Contains(got, "on 5 of these days") {
+ t.Errorf("five restarts = %q", got)
+ }
+}
+
+func TestShareRows(t *testing.T) {
+ rows := shareRows(map[string]int64{"/": 300, "/a": 1, analytics.OtherKey: 400, "/b": 299}, pageLabel)
+ if len(rows) != 4 || rows[0].Key != "/" || rows[3].Key != analytics.OtherKey || !rows[3].Muted || rows[3].Label != "Everything else" {
+ t.Fatalf("rows = %+v", rows)
+ }
+ // The biggest row is the full bar even when "everything else" is bigger
+ // still: bars compare rows, and the overflow row is pinned last.
+ if rows[0].Share != "30%" || rows[2].Share != "<1%" || rows[3].Bar != 100 {
+ t.Errorf("shares = %+v", rows)
+ }
+}
+
+// The analytics day files go through the settled-day cache: a day that is
+// over is read once, and a second view of 30 days reads only today's and
+// yesterday's file per box. This is the request budget the tab promises.
+func TestAnalyticsReadsSettledDaysOnce(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-cache")
+ now := time.Now().UTC()
+ for _, d := range []int{0, 1, 5, 20} {
+ seedAnalytics(t, fx, now.Truncate(24*time.Hour).AddDate(0, 0, -d).Add(time.Hour))
+ }
+ cs := &analyticsCountStore{Store: fx.rel}
+ fx.srv.cfg.Releases = cs
+ read := func() analyticsWindow {
+ win, err := fx.srv.readAnalytics(context.Background(), fx.sqid, "titogo", range30d, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return win
+ }
+ first := read()
+ if first.Sum.PV != 20 {
+ t.Fatalf("30 days = %d page views, want 20", first.Sum.PV)
+ }
+ cold := cs.dayReads()
+ if cold != 30 {
+ t.Fatalf("cold view read %d day files, want 30 (one box, 30 days)", cold)
+ }
+ second := read()
+ if second.Sum.PV != first.Sum.PV {
+ t.Fatalf("warm view = %d page views, cold %d", second.Sum.PV, first.Sum.PV)
+ }
+ if warm := cs.dayReads() - cold; warm != 2 {
+ t.Fatalf("warm view read %d day files, want 2 (today and yesterday)", warm)
+ }
+}
+
+type analyticsCountStore struct {
+ release.Store
+ mu sync.Mutex
+ reads int
+}
+
+func (c *analyticsCountStore) count(key string) {
+ if strings.Contains(key, "/analytics/") && strings.HasSuffix(key, ".json") {
+ c.mu.Lock()
+ c.reads++
+ c.mu.Unlock()
+ }
+}
+
+func (c *analyticsCountStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ c.count(key)
+ return c.Store.Get(ctx, key)
+}
+
+func (c *analyticsCountStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ c.count(key)
+ return release.OpenObject(ctx, c.Store, key)
+}
+
+func (c *analyticsCountStore) dayReads() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.reads
+}
+
+// The Overview's traffic card: the week's numbers and chart when counting is
+// on, the way to turn it on when it is off.
+func TestOverviewTrafficCard(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-overview")
+ seedAnalytics(t, fx, seedTime())
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-overview-browser")
+ status, _, body := get(t, c, fx.u("/apps/titogo"))
+ if status != http.StatusOK {
+ t.Fatalf("overview = %d", status)
+ }
+ for _, want := range []string{"Traffic, last 7 days", "Analytics is off for this app. These are the numbers counted while it was on.", "<dd>5</dd>", `class="an-chart an-chart-day"`} {
+ if !strings.Contains(body, want) {
+ t.Errorf("overview (off, counted) missing %q", want)
+ }
+ }
+ if err := telemetry.Update(context.Background(), fx.rel, telemetry.AppKey(fx.sqid, "titogo"), func(st *telemetry.Settings) {
+ st.Analytics = &telemetry.Analytics{Count: telemetry.CountEdge}
+ }); err != nil {
+ t.Fatal(err)
+ }
+ _, _, body = get(t, c, fx.u("/apps/titogo"))
+ if strings.Contains(body, "Analytics is off") || !strings.Contains(body, "/analytics?range=7d") {
+ t.Error("overview (on) still says off, or has no link to the tab")
+ }
+}
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go
index c7b1a143c..f647f152d 100644
--- a/internal/console/analyticsview.go
+++ b/internal/console/analyticsview.go
@@ -10,7 +10,6 @@ package console
import (
"context"
"crypto/subtle"
- "fmt"
"log"
"math"
"net/http"
@@ -20,6 +19,7 @@ import (
"github.com/carlosframework/platform/internal/analytics"
"github.com/carlosframework/platform/internal/geoip"
+ "github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/telemetry"
)
@@ -231,14 +231,22 @@ func analyticsAudit(count, door string) string {
// analyticsWindow is one assembled read: the summary, the range it covers,
// the resolved setting (so the page can say counting is off, and where that
-// came from), and the chart geometry the template plots.
+// came from), and what the page draws from it (analyticsdisplay.go).
type analyticsWindow struct {
- Sum analytics.Summary
- Range string
- On bool
- Setting telemetry.Resolved
- ChartBars []chartBar
- ChartMax int64
+ Sum analytics.Summary
+ Range string
+ On bool
+ Setting telemetry.Resolved
+ Span string
+ Chart *trafficChart
+ Insights []string
+ Pages []shareRow
+ Referers []shareRow
+ Events []shareRow
+ // Countries is the top 10 plus the rest (geoip spec §9).
+ Countries []shareRow
+ // Restarts is restartNote's sentence, "" when no edge restarted.
+ Restarts string
}
// HasData reports whether the window holds anything counted. With analytics
@@ -251,16 +259,6 @@ func (w analyticsWindow) HasData() bool {
len(s.Pages) > 0 || len(s.Referers) > 0 || len(s.Events) > 0 || len(s.Countries) > 0
}
-// chartBar is one plotted column: the reading, and the rectangle that draws
-// it. The geometry is computed here rather than in the template because a
-// template cannot divide, and because the scaling is the part worth testing.
-type chartBar struct {
- Label string
- Value int64
- X, Y, W float64
- H float64
-}
-
// The three windows the tab and the API accept. Anything else is a mistake
// worth naming at the API and worth ignoring at the page.
const (
@@ -269,6 +267,10 @@ const (
range30d = "30d"
)
+// overviewTrafficTimeout bounds the Overview's traffic card read. Past it
+// the card says the numbers could not be read; the page is not held up.
+const overviewTrafficTimeout = 2 * time.Second
+
func validRange(s string) bool { return s == rangeToday || s == range7d || s == range30d }
// analyticsSpan turns a range name into a UTC span. Truncate(24h) lands on
@@ -288,14 +290,6 @@ func analyticsSpan(rng string, now time.Time) (from, to time.Time) {
}
}
-// chartWidth and chartHeight are the plot's viewBox units — not pixels: the
-// SVG scales to whatever column it lands in, so these fix only the aspect
-// and the resolution of the geometry.
-const (
- chartWidth = 480.0
- chartHeight = 120.0
-)
-
// readAnalytics assembles the window. It resolves the setting first and then
// reads whichever way that came out: numbers already collected are still
// shown after an owner turns counting off, because they were collected while
@@ -314,89 +308,41 @@ func (s *Server) readAnalytics(ctx context.Context, sqid, app, rng string, now t
return out, nil
}
from, to := analyticsSpan(rng, now)
- sum, err := analytics.ReadRange(ctx, s.cfg.Releases, sqid, app, from, to)
+ sum, err := s.readAnalyticsRange(ctx, sqid, app, from, to, now)
if err != nil {
return out, err
}
out.Sum = sum
- vals, labels := chartSeries(rng, sum)
- out.ChartBars, out.ChartMax = chartBars(vals, labels, chartWidth, chartHeight)
+ out.Span = analyticsSpanText(rng, now)
+ out.Chart = buildTrafficChart(rng, sum, now)
+ out.Insights = analyticsInsights(rng, sum, now)
+ out.Pages = shareRows(sum.Pages, pageLabel)
+ out.Referers = shareRows(sum.Referers, refererLabel)
+ out.Events = shareRows(sum.Events, pageLabel)
+ out.Countries = shareRows(geoCountries(sum.Countries), countryLabel)
+ out.Restarts = restartNote(sum.Days)
return out, nil
}
-// chartSeries picks what the bars plot: today is the 24 hourly page-view
-// counts, a multi-day window is one bar per day. A day the range covers but
-// no box wrote a file for is a zero rather than a gap — ReadRange returns
-// one DaySummary per date either way, so the axis stays evenly spaced.
-func chartSeries(rng string, sum analytics.Summary) (vals []int64, labels []string) {
- if rng == rangeToday {
- if len(sum.Days) == 0 {
- return nil, nil
- }
- // The last row, not the first: today's span is one date, and taking
- // the tail keeps this right if a caller ever passes a wider one.
- d := sum.Days[len(sum.Days)-1]
- for h := 0; h < 24; h++ {
- vals = append(vals, d.Hours[h])
- labels = append(labels, fmt.Sprintf("%02d", h))
- }
- return vals, labels
- }
- for _, d := range sum.Days {
- vals = append(vals, d.PV)
- labels = append(labels, dayLabel(d.Date))
- }
- return vals, labels
-}
-
-// dayLabel shortens a UTC date to MM-DD: thirty bars cannot each carry a
-// year, and the window's own dates are printed in full beside the chart.
-func dayLabel(date string) string {
- if len(date) == len("2006-01-02") {
- return date[5:]
- }
- return date
-}
-
-// chartBars scales vals onto a w x h box: one column per reading, two units
-// of gap between columns, height proportional to the largest reading in the
-// window — returned as the second value, so the template can say what the
-// peak was rather than leaving the axis unlabelled.
-//
-// Nothing to plot — no readings, or nothing but zeros — returns no bars at
-// all: a row of flat rectangles under a "peak 0" caption is noise, and the
-// template renders no chart rather than an empty one. Coordinates are
-// rounded to two decimals for the reason sparkPoints rounds its own: the
-// trailing digits of a binary fraction are bytes on every page view that
-// change nothing anyone can see.
-func chartBars(vals []int64, labels []string, w, h float64) ([]chartBar, int64) {
- var max int64
- for _, v := range vals {
- if v > max {
- max = v
- }
- }
- if len(vals) == 0 || max <= 0 {
- return nil, max
- }
- step := w / float64(len(vals))
- bw := step - 2
- if bw <= 0 {
- bw = step // more columns than gaps will fit: draw them touching
- }
- out := make([]chartBar, 0, len(vals))
- for i, v := range vals {
- b := chartBar{Value: v, X: round2(float64(i) * step), W: round2(bw)}
- if i < len(labels) {
- b.Label = labels[i]
- }
- if v > 0 {
- b.H = round2(float64(v) / float64(max) * h)
- }
- b.Y = round2(h - b.H)
- out = append(out, b)
- }
- return out, max
+// readAnalyticsRange is analytics.ReadRange through the settled-day cache
+// (usagedays.go), with its reads made concurrently (hotreads.go). A day
+// file stops changing a day after the day ends, so a warm 30-day view reads
+// one listing and today's and yesterday's file per box; before this, every
+// view read every box's file for every day of the window, one after
+// another. Request budget: nothing on a timer; per view, one LIST of the
+// app's boxes plus two GETs per box, and one GET per box per settled day
+// at most every usageDayMaxAge.
+func (s *Server) readAnalyticsRange(ctx context.Context, sqid, app string, from, to, now time.Time) (analytics.Summary, error) {
+ type read struct {
+ sum analytics.Summary
+ err error
+ }
+ // "{}" is an empty day file, which ReadRange folds in as nothing.
+ r := readConcurrently(ctx, s.usageDayReader(now), []byte("{}"), usageDayLimit, func(st release.Store) read {
+ sum, err := analytics.ReadRange(ctx, st, sqid, app, from, to)
+ return read{sum, err}
+ })
+ return r.sum, r.err
}
func round2(f float64) float64 { return math.Round(f*100) / 100 }
diff --git a/internal/console/apianalytics_test.go b/internal/console/apianalytics_test.go
index de501fd3a..2c7c7dbf1 100644
--- a/internal/console/apianalytics_test.go
+++ b/internal/console/apianalytics_test.go
@@ -167,7 +167,7 @@ func TestAppAnalyticsPage(t *testing.T) {
t.Fatalf("%d %s", status, body)
}
// Off: the switch and the reading, and the numbers that exist already.
- for _, want := range []string{"Analytics is off for this app", "No JavaScript, no cookie", "/pricing", "news.ycombinator.com", "signup", "<svg"} {
+ for _, want := range []string{"Analytics is off for this app", "No JavaScript, no cookie", "/pricing", "news.ycombinator.com", "signup", `class="an-chart an-chart-hour"`} {
if !strings.Contains(body, want) {
t.Errorf("page missing %q", want)
}
@@ -178,7 +178,7 @@ func TestAppAnalyticsPage(t *testing.T) {
t.Fatal(err)
}
_, _, body = get(t, c, fx.u("/apps/titogo/analytics?range=7d"))
- if strings.Contains(body, "Analytics is off") || !strings.Contains(body, "daily visitors, summed") || !strings.Contains(body, "carlos analytics --app titogo") {
+ if strings.Contains(body, "Analytics is off") || !strings.Contains(body, "Daily visitors are added up.") || !strings.Contains(body, "carlos analytics --app titogo") {
t.Fatal("on + 7d page")
}
}
@@ -211,7 +211,7 @@ func TestAppAnalyticsPageCountriesAndAttribution(t *testing.T) {
}
}
_, _, body = get(t, c, fx.u("/apps/titogo/analytics"))
- for _, want := range []string{"<h3>Countries</h3>", "<td>GB</td><td>2</td>", "<td>unknown</td><td>1</td>",
+ for _, want := range []string{">Countries</h3>", "United Kingdom</span>\n <span class=\"an-val\">2</span>", "Unknown</span>\n <span class=\"an-val\">1</span>",
`href="https://db-ip.com">IP Geolocation by DB-IP</a>`, "GeoLite2 data created by MaxMind"} {
if !strings.Contains(body, want) {
t.Errorf("page lacks %q", want)
diff --git a/internal/console/appnav_test.go b/internal/console/appnav_test.go
index 5da00e6ee..b98a7f786 100644
--- a/internal/console/appnav_test.go
+++ b/internal/console/appnav_test.go
@@ -208,9 +208,9 @@ func TestRunningLeftoversNameTheTab(t *testing.T) {
func TestLogsToolbar(t *testing.T) {
fx := newConsoleFixture(t)
c := signInPaul(t, fx)
- // Analytics is off for kass and nothing is counted, so its tab hides the
- // range picker on today (the on-ramp's off state); any other range keeps it.
- for _, tab := range []string{"logs", "errors", "availability", "analytics?range=7d"} {
+ // The Analytics tab's period picker is three links, not a filter form
+ // (TestAnalyticsTabOffState*), so it is not one of the toolbars here.
+ for _, tab := range []string{"logs", "errors", "availability"} {
status, _, body := get(t, c, fx.u("/apps/kass/"+tab))
if status != 200 {
t.Fatalf("GET /apps/kass/%s = %d", tab, status)
diff --git a/internal/console/countrynames.go b/internal/console/countrynames.go
new file mode 100644
index 000000000..3524d886f
--- /dev/null
+++ b/internal/console/countrynames.go
@@ -0,0 +1,278 @@
+package console
+
+// countryNames gives the Countries table words for the ISO 3166-1 alpha-2
+// codes GeoIP answers with. Generated once from golang.org/x/text's English
+// region names (language/display, which is too large to link for one
+// table), with the dated ones brought up to the names countries use now.
+// A code missing here is shown as the code itself.
+var countryNames = map[string]string{
+ "AD": "Andorra",
+ "AE": "United Arab Emirates",
+ "AF": "Afghanistan",
+ "AG": "Antigua & Barbuda",
+ "AI": "Anguilla",
+ "AL": "Albania",
+ "AM": "Armenia",
+ "AO": "Angola",
+ "AQ": "Antarctica",
+ "AR": "Argentina",
+ "AS": "American Samoa",
+ "AT": "Austria",
+ "AU": "Australia",
+ "AW": "Aruba",
+ "AX": "Åland Islands",
+ "AZ": "Azerbaijan",
+ "BA": "Bosnia & Herzegovina",
+ "BB": "Barbados",
+ "BD": "Bangladesh",
+ "BE": "Belgium",
+ "BF": "Burkina Faso",
+ "BG": "Bulgaria",
+ "BH": "Bahrain",
+ "BI": "Burundi",
+ "BJ": "Benin",
+ "BL": "St. Barthélemy",
+ "BM": "Bermuda",
+ "BN": "Brunei",
+ "BO": "Bolivia",
+ "BQ": "Caribbean Netherlands",
+ "BR": "Brazil",
+ "BS": "Bahamas",
+ "BT": "Bhutan",
+ "BU": "Myanmar",
+ "BV": "Bouvet Island",
+ "BW": "Botswana",
+ "BY": "Belarus",
+ "BZ": "Belize",
+ "CA": "Canada",
+ "CC": "Cocos (Keeling) Islands",
+ "CD": "DR Congo",
+ "CF": "Central African Republic",
+ "CG": "Republic of the Congo",
+ "CH": "Switzerland",
+ "CI": "Côte d’Ivoire",
+ "CK": "Cook Islands",
+ "CL": "Chile",
+ "CM": "Cameroon",
+ "CN": "China",
+ "CO": "Colombia",
+ "CR": "Costa Rica",
+ "CT": "Kiribati",
+ "CU": "Cuba",
+ "CV": "Cape Verde",
+ "CW": "Curaçao",
+ "CX": "Christmas Island",
+ "CY": "Cyprus",
+ "CZ": "Czechia",
+ "DD": "Germany",
+ "DE": "Germany",
+ "DJ": "Djibouti",
+ "DK": "Denmark",
+ "DM": "Dominica",
+ "DO": "Dominican Republic",
+ "DY": "Benin",
+ "DZ": "Algeria",
+ "EC": "Ecuador",
+ "EE": "Estonia",
+ "EG": "Egypt",
+ "EH": "Western Sahara",
+ "ER": "Eritrea",
+ "ES": "Spain",
+ "ET": "Ethiopia",
+ "FI": "Finland",
+ "FJ": "Fiji",
+ "FK": "Falkland Islands",
+ "FM": "Micronesia",
+ "FO": "Faroe Islands",
+ "FR": "France",
+ "FX": "France",
+ "GA": "Gabon",
+ "GB": "United Kingdom",
+ "GD": "Grenada",
+ "GE": "Georgia",
+ "GF": "French Guiana",
+ "GG": "Guernsey",
+ "GH": "Ghana",
+ "GI": "Gibraltar",
+ "GL": "Greenland",
+ "GM": "Gambia",
+ "GN": "Guinea",
+ "GP": "Guadeloupe",
+ "GQ": "Equatorial Guinea",
+ "GR": "Greece",
+ "GS": "South Georgia & South Sandwich Islands",
+ "GT": "Guatemala",
+ "GU": "Guam",
+ "GW": "Guinea-Bissau",
+ "GY": "Guyana",
+ "HK": "Hong Kong",
+ "HM": "Heard & McDonald Islands",
+ "HN": "Honduras",
+ "HR": "Croatia",
+ "HT": "Haiti",
+ "HU": "Hungary",
+ "HV": "Burkina Faso",
+ "ID": "Indonesia",
+ "IE": "Ireland",
+ "IL": "Israel",
+ "IM": "Isle of Man",
+ "IN": "India",
+ "IO": "British Indian Ocean Territory",
+ "IQ": "Iraq",
+ "IR": "Iran",
+ "IS": "Iceland",
+ "IT": "Italy",
+ "JE": "Jersey",
+ "JM": "Jamaica",
+ "JO": "Jordan",
+ "JP": "Japan",
+ "JT": "U.S. Outlying Islands",
+ "KE": "Kenya",
+ "KG": "Kyrgyzstan",
+ "KH": "Cambodia",
+ "KI": "Kiribati",
+ "KM": "Comoros",
+ "KN": "St. Kitts & Nevis",
+ "KP": "North Korea",
+ "KR": "South Korea",
+ "KW": "Kuwait",
+ "KY": "Cayman Islands",
+ "KZ": "Kazakhstan",
+ "LA": "Laos",
+ "LB": "Lebanon",
+ "LC": "St. Lucia",
+ "LI": "Liechtenstein",
+ "LK": "Sri Lanka",
+ "LR": "Liberia",
+ "LS": "Lesotho",
+ "LT": "Lithuania",
+ "LU": "Luxembourg",
+ "LV": "Latvia",
+ "LY": "Libya",
+ "MA": "Morocco",
+ "MC": "Monaco",
+ "MD": "Moldova",
+ "ME": "Montenegro",
+ "MF": "St. Martin",
+ "MG": "Madagascar",
+ "MH": "Marshall Islands",
+ "MI": "U.S. Outlying Islands",
+ "MK": "North Macedonia",
+ "ML": "Mali",
+ "MM": "Myanmar",
+ "MN": "Mongolia",
+ "MO": "Macau SAR China",
+ "MP": "Northern Mariana Islands",
+ "MQ": "Martinique",
+ "MR": "Mauritania",
+ "MS": "Montserrat",
+ "MT": "Malta",
+ "MU": "Mauritius",
+ "MV": "Maldives",
+ "MW": "Malawi",
+ "MX": "Mexico",
+ "MY": "Malaysia",
+ "MZ": "Mozambique",
+ "NA": "Namibia",
+ "NC": "New Caledonia",
+ "NE": "Niger",
+ "NF": "Norfolk Island",
+ "NG": "Nigeria",
+ "NH": "Vanuatu",
+ "NI": "Nicaragua",
+ "NL": "Netherlands",
+ "NO": "Norway",
+ "NP": "Nepal",
+ "NQ": "Antarctica",
+ "NR": "Nauru",
+ "NU": "Niue",
+ "NZ": "New Zealand",
+ "OM": "Oman",
+ "PA": "Panama",
+ "PE": "Peru",
+ "PF": "French Polynesia",
+ "PG": "Papua New Guinea",
+ "PH": "Philippines",
+ "PK": "Pakistan",
+ "PL": "Poland",
+ "PM": "St. Pierre & Miquelon",
+ "PN": "Pitcairn Islands",
+ "PR": "Puerto Rico",
+ "PS": "Palestinian Territories",
+ "PT": "Portugal",
+ "PU": "U.S. Outlying Islands",
+ "PW": "Palau",
+ "PY": "Paraguay",
+ "PZ": "Panama",
+ "QA": "Qatar",
+ "RE": "Réunion",
+ "RH": "Zimbabwe",
+ "RO": "Romania",
+ "RS": "Serbia",
+ "RU": "Russia",
+ "RW": "Rwanda",
+ "SA": "Saudi Arabia",
+ "SB": "Solomon Islands",
+ "SC": "Seychelles",
+ "SD": "Sudan",
+ "SE": "Sweden",
+ "SG": "Singapore",
+ "SH": "St. Helena",
+ "SI": "Slovenia",
+ "SJ": "Svalbard & Jan Mayen",
+ "SK": "Slovakia",
+ "SL": "Sierra Leone",
+ "SM": "San Marino",
+ "SN": "Senegal",
+ "SO": "Somalia",
+ "SR": "Suriname",
+ "SS": "South Sudan",
+ "ST": "São Tomé & Príncipe",
+ "SV": "El Salvador",
+ "SX": "Sint Maarten",
+ "SY": "Syria",
+ "SZ": "Eswatini",
+ "TC": "Turks & Caicos Islands",
+ "TD": "Chad",
+ "TF": "French Southern Territories",
+ "TG": "Togo",
+ "TH": "Thailand",
+ "TJ": "Tajikistan",
+ "TK": "Tokelau",
+ "TL": "Timor-Leste",
+ "TM": "Turkmenistan",
+ "TN": "Tunisia",
+ "TO": "Tonga",
+ "TP": "Timor-Leste",
+ "TR": "Turkey",
+ "TT": "Trinidad & Tobago",
+ "TV": "Tuvalu",
+ "TW": "Taiwan",
+ "TZ": "Tanzania",
+ "UA": "Ukraine",
+ "UG": "Uganda",
+ "UK": "United Kingdom",
+ "UM": "U.S. Outlying Islands",
+ "US": "United States",
+ "UY": "Uruguay",
+ "UZ": "Uzbekistan",
+ "VA": "Vatican City",
+ "VC": "St. Vincent & Grenadines",
+ "VD": "Vietnam",
+ "VE": "Venezuela",
+ "VG": "British Virgin Islands",
+ "VI": "U.S. Virgin Islands",
+ "VN": "Vietnam",
+ "VU": "Vanuatu",
+ "WF": "Wallis & Futuna",
+ "WK": "U.S. Outlying Islands",
+ "WS": "Samoa",
+ "XK": "Kosovo",
+ "YD": "Yemen",
+ "YE": "Yemen",
+ "YT": "Mayotte",
+ "ZA": "South Africa",
+ "ZM": "Zambia",
+ "ZR": "DR Congo",
+ "ZW": "Zimbabwe",
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index fbb878fca..63761c9d3 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -166,6 +166,10 @@ var templates = template.Must(template.New("").Funcs(template.FuncMap{
"geoCountries": geoCountries,
"geoLabel": geoLabel,
"geoAttributions": geoAttributions,
+ // count and dataSize: the Analytics tab's numbers as a person reads
+ // them (1,284 and 1.6 MB, decimal units, analyticsdisplay.go).
+ "count": groupedCount,
+ "dataSize": humanBytes,
// bytesOrDash renders a byte count in the smallest unit that keeps it
// readable; nil (no reading, from a unit that reported CPU but not
// memory/IO that tick) is "—", never a fabricated 0 B.
@@ -2508,6 +2512,10 @@ type page struct {
AnalyticsWin analyticsWindow
AnalyticsRange string // "today" | "7d" | "30d"
AnalyticsErr string
+ // Traffic is the Overview's traffic card: the Analytics tab's 7-day
+ // window, read the same way. nil when the read failed or timed out,
+ // which costs the card its numbers, never the page.
+ Traffic *analyticsWindow
// Action confirm interstitial (confirm.go): what is about to happen,
// carried fields and all. Nil everywhere except the confirm page.
@@ -4175,6 +4183,20 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) {
return
}
app := p.Detail.App
+ // The traffic card reads beside everything else this page reads, under
+ // its own deadline, so a slow bucket delays nothing but the card.
+ traffic := make(chan *analyticsWindow, 1)
+ go func() {
+ ctx, cancel := context.WithTimeout(r.Context(), overviewTrafficTimeout)
+ defer cancel()
+ win, err := s.readAnalytics(ctx, acct.Sqid, app, range7d, time.Now())
+ if err != nil {
+ log.Printf("console: overview traffic %s/%s: %v", acct.Sqid, app, err)
+ traffic <- nil
+ return
+ }
+ traffic <- &win
+ }()
versions, err := Versions(r.Context(), s.cfg.Releases, acct.Sqid, app)
if err != nil {
log.Printf("console: versions %s: %v", app, err)
@@ -4217,6 +4239,9 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) {
// EXECUTION will require, not the one they were proposed under.
p.Pending = s.pendingChangeViews(pcs, p.Detail.Pipeline)
}
+ end = perf.Span(r, "s3")
+ p.Traffic = <-traffic
+ end()
s.render(w, http.StatusOK, "app_overview", p)
}
diff --git a/internal/console/templates/app_analytics.html b/internal/console/templates/app_analytics.html
index 712ee6623..fcdaf69fc 100644
--- a/internal/console/templates/app_analytics.html
+++ b/internal/console/templates/app_analytics.html
@@ -8,6 +8,7 @@
{{/* A failed read resolves to the defaults, which say "off": offering the
switch then would be a guess, so the error stands alone. */}}
{{if and (not .AnalyticsErr) (not .AnalyticsWin.On)}}
+<div class="an-off">
<p><strong>Analytics is off for this app.</strong>
When analytics is on, the edge counts HTML page views and daily visitors. No JavaScript, no cookie, no stored IP.</p>
{{if .IsOwner}}
@@ -20,44 +21,133 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
{{else}}
<p class="small">An account owner can turn on analytics.</p>
{{end}}
+</div>
{{end}}
{{/* The range picker always shows: numbers counted while analytics was on
- stay reachable after it is switched off. With nothing counted in the
- window there are no empty tables, chart or "Nothing yet" rows. */}}
-<form method="get" class="toolbar">
- <label>range
- <select name="range">
- <option value="today"{{if eq .AnalyticsRange "today"}} selected{{end}}>today</option>
- <option value="7d"{{if eq .AnalyticsRange "7d"}} selected{{end}}>7 days</option>
- <option value="30d"{{if eq .AnalyticsRange "30d"}} selected{{end}}>30 days</option>
- </select>
- </label>
- <button type="submit" class="btn-sm">Update</button>
-</form>
+ stay reachable after it is switched off. Three links rather than a
+ select and a button: one click, and every view is a URL. */}}
+<nav class="an-range" aria-label="Period">
+ <a href="?range=today"{{if eq .AnalyticsRange "today"}} aria-current="page"{{end}}>Today</a>
+ <a href="?range=7d"{{if eq .AnalyticsRange "7d"}} aria-current="page"{{end}}>7 days</a>
+ <a href="?range=30d"{{if eq .AnalyticsRange "30d"}} aria-current="page"{{end}}>30 days</a>
+ {{if .AnalyticsWin.Span}}<span class="an-span">{{.AnalyticsWin.Span}}</span>{{end}}
+</nav>
{{if or .AnalyticsWin.On .AnalyticsWin.HasData}}
{{with .AnalyticsWin}}
-<div class="tablewrap"><table>
- <tr><th>Page views</th><th>Visitors{{if ne $.AnalyticsRange "today"}} (daily visitors, summed){{end}}</th><th>Bytes served</th><th>Bots excluded</th><th>Dropped</th></tr>
- <tr><td>{{.Sum.PV}}</td><td>{{.Sum.Visitors}}</td><td>{{.Sum.Bytes}}</td><td>{{.Sum.Bots}}</td><td>{{.Sum.Dropped.Flush}}</td></tr>
-</table></div>
-{{if .ChartBars}}
-<svg viewBox="0 0 480 140" width="100%" role="img" aria-label="Page views">
- {{range .ChartBars}}<rect x="{{.X}}" y="{{.Y}}" width="{{.W}}" height="{{.H}}" fill="currentColor"><title>{{.Label}}: {{.Value}}</title></rect>{{end}}
- <text x="0" y="136" class="small">{{if eq $.AnalyticsRange "today"}}per hour, UTC{{else}}per day{{end}}; peak {{.ChartMax}}</text>
-</svg>
-{{end}}
-{{range .Sum.Days}}{{if .Restarted}}<p class="small">{{.Date}}: counts since the last flush may be missing (the edge restarted that day).</p>{{end}}{{end}}
-<h3>Top pages{{if .Sum.PagesApprox}} <span class="small">approximate: more than 500 distinct keys</span>{{end}}</h3>
-{{template "kvtable" .Sum.Pages}}
-<h3>Top referers{{if .Sum.ReferersApprox}} <span class="small">approximate</span>{{end}}</h3>
-{{template "kvtable" .Sum.Referers}}
-<h3>Named events{{if .Sum.EventsApprox}} <span class="small">approximate</span>{{end}}</h3>
-{{template "kvtable" .Sum.Events}}
-<h3>Countries</h3>
-{{with geoCountries .Sum.Countries}}<div class="tablewrap"><table>{{range sortedKV .}}<tr><td>{{geoLabel .Key}}</td><td>{{.Value}}</td></tr>{{end}}</table></div>{{else}}<p class="small">No country data for this period.</p>{{end}}
-{{range geoAttributions .Sum.GeoSources}}<p class="small"><a href="{{.URL}}">{{.Text}}</a></p>{{end}}
+{{template "trafficfigures" .}}
+{{if .Chart}}
+{{template "trafficchart" .Chart}}
+{{if .Insights}}<p class="an-insights">{{range $i, $s := .Insights}}{{if $i}} {{end}}{{$s}}{{end}}</p>{{end}}
+{{else}}
+<p class="an-empty">No page views in this period.</p>
+{{end}}
+{{template "trafficquality" .}}
+<div class="an-breakdowns">
+ <section class="an-card" aria-labelledby="an-pages">
+ <h3 id="an-pages">Top pages</h3>
+ {{template "sharelist" .Pages}}
+ {{if .Sum.PagesApprox}}<p class="small">Approximate: more than 500 different pages were viewed.</p>{{end}}
+ </section>
+ <section class="an-card" aria-labelledby="an-referers">
+ <h3 id="an-referers">Referrers</h3>
+ {{template "sharelist" .Referers}}
+ {{if .Sum.ReferersApprox}}<p class="small">Approximate: more than 500 referrers were seen.</p>{{end}}
+ </section>
+ <section class="an-card" aria-labelledby="an-countries">
+ <h3 id="an-countries">Countries</h3>
+ {{if .Countries}}{{template "sharelist" .Countries}}{{else}}<p class="small">No country data for this period.</p>{{end}}
+ {{range geoAttributions .Sum.GeoSources}}<p class="small"><a href="{{.URL}}">{{.Text}}</a></p>{{end}}
+ </section>
+ <section class="an-card" aria-labelledby="an-events">
+ <h3 id="an-events">Named events</h3>
+ {{template "sharelist" .Events}}
+ {{if .Sum.EventsApprox}}<p class="small">Approximate: more than 500 event names were seen.</p>{{end}}
+ </section>
+</div>
{{end}}
<p class="small">Times are UTC. The same view from a terminal: <code>carlos analytics --app {{.AppName}} --range {{.AnalyticsRange}}</code>.</p>
{{end}}
{{template "bottom" .}}{{end}}
-{{define "kvtable"}}{{if .}}<div class="tablewrap"><table>{{range sortedKV .}}<tr><td>{{.Key}}</td><td>{{.Value}}</td></tr>{{end}}</table></div>{{else}}<p class="small">Nothing yet.</p>{{end}}{{end}}
+
+{{/* The three numbers a reader came for, then the chart. Visitors are
+ estimated per day, so a multi-day total is a sum of days and says so. */}}
+{{define "trafficfigures"}}
+<dl class="an-figures">
+ <div>
+ <dt>Page views</dt>
+ <dd>{{count .Sum.PV}}</dd>
+ </div>
+ <div>
+ <dt>Visitors</dt>
+ <dd>{{count .Sum.Visitors}}</dd>
+ <dd class="an-note">{{if eq .Range "today"}}Estimated.{{else}}Daily visitors are added up. One person seen on two days counts twice.{{end}}</dd>
+ </div>
+ <div>
+ <dt>Data served</dt>
+ <dd><span title="{{count .Sum.Bytes}} bytes">{{dataSize .Sum.Bytes}}</span></dd>
+ </div>
+</dl>
+{{end}}
+
+{{/* What could make a number low: bots left out on purpose, counts the
+ edge dropped, days an edge restarted before it flushed. Said once. */}}
+{{define "trafficquality"}}
+<p class="an-quality small">
+ {{if .Sum.Bots}}{{count .Sum.Bots}} bot request{{if ne .Sum.Bots 1}}s are{{else}} is{{end}} not included in these numbers.{{else}}No bots detected.{{end}}
+ {{if .Sum.Dropped.Flush}} {{count .Sum.Dropped.Flush}} page view{{if ne .Sum.Dropped.Flush 1}}s are{{else}} is{{end}} missing because {{if ne .Sum.Dropped.Flush 1}}they{{else}}it{{end}} could not be saved.{{end}}
+ {{with .Restarts}} {{.}}{{end}}
+</p>
+{{end}}
+
+{{/* The chart: one button per hour or day, so a tooltip opens on hover,
+ on keyboard focus and on tap. Each button's aria-label says the whole
+ reading; the visible tooltip says it in lines. Without the script every
+ column is still a focusable button with its reading. */}}
+{{define "trafficchart"}}
+<figure class="an-chart an-chart-{{.Unit}}" style="--an-cols: {{.N}}">
+ <figcaption class="visually-hidden">Page views per {{.Unit}}, UTC</figcaption>
+ <div class="an-plot">
+ <div class="an-grid" aria-hidden="true">{{range .Ticks}}<span style="bottom: {{.Pct}}%"><i>{{.Label}}</i></span>{{end}}</div>
+ <div class="an-cols" role="group" aria-label="Page views per {{.Unit}}">
+ {{range .Cols}}{{if .Future}}<span class="an-col an-future" aria-hidden="true"></span>{{else}}<button type="button" class="an-col{{if .Partial}} an-partial{{end}}{{if .Gap}} an-gap{{end}}{{if .Edge}} an-edge-{{.Edge}}{{end}}" aria-label="{{.Label}}"><span class="an-bar" style="height: {{.HPct}}%"><span class="an-tip" aria-hidden="true"><b>{{index .Lines 0}}</b>{{range $i, $l := .Lines}}{{if $i}}<span>{{$l}}</span>{{end}}{{end}}<span class="an-when">{{.When}}</span></span></span></button>{{end}}{{end}}
+ </div>
+ </div>
+ <div class="an-xaxis" aria-hidden="true">{{range .XLabels}}<span style="grid-column: {{.Col}}">{{.Label}}</span>{{end}}</div>
+</figure>
+<script>
+(function () {
+ // Arrow keys move between columns, Home and End jump, Escape closes. The
+ // group is one Tab stop: the focused column is the only one with
+ // tabindex 0. Pointer hover and tap need nothing here; CSS shows the tip.
+ var groups = document.querySelectorAll(".an-cols:not([data-an])");
+ groups.forEach(function (g) {
+ g.setAttribute("data-an", "");
+ var cols = Array.prototype.slice.call(g.querySelectorAll("button.an-col"));
+ if (!cols.length) return;
+ cols.forEach(function (c, i) { c.tabIndex = i === cols.length - 1 ? 0 : -1; });
+ g.addEventListener("keydown", function (e) {
+ var i = cols.indexOf(document.activeElement);
+ if (i < 0) return;
+ var j = i;
+ if (e.key === "ArrowRight") j = Math.min(cols.length - 1, i + 1);
+ else if (e.key === "ArrowLeft") j = Math.max(0, i - 1);
+ else if (e.key === "Home") j = 0;
+ else if (e.key === "End") j = cols.length - 1;
+ else if (e.key === "Escape") { cols[i].blur(); return; }
+ else return;
+ e.preventDefault();
+ cols[i].tabIndex = -1;
+ cols[j].tabIndex = 0;
+ cols[j].focus();
+ });
+ });
+})();
+</script>
+{{end}}
+
+{{define "sharelist"}}{{if .}}<ol class="an-share">{{range .}}<li{{if .Muted}} class="an-muted"{{end}}>
+ <span class="an-key" title="{{.Key}}">{{if .Flag}}<span class="an-flag" aria-hidden="true">{{.Flag}}</span>{{end}}{{.Label}}</span>
+ <span class="an-val">{{count .Value}}</span>
+ <span class="an-pct">{{.Share}}</span>
+ <span class="an-track" aria-hidden="true"><span style="width: {{.Bar}}%"></span></span>
+</li>{{end}}</ol>{{else}}<p class="small">Nothing yet.</p>{{end}}{{end}}
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html
index d3baa211f..f5533f5c0 100644
--- a/internal/console/templates/app_overview.html
+++ b/internal/console/templates/app_overview.html
@@ -63,6 +63,26 @@
</a>
</section>
{{end}}
+{{/* Traffic: the Analytics tab's 7-day window, read beside the rest of this
+ page under its own deadline (handleApp). Off shows where to turn it on;
+ a failed read says so rather than showing zeros. */}}
+<section class="an-overview" aria-labelledby="an-overview-head">
+ <div class="an-overview-head">
+ <h2 id="an-overview-head">Traffic, last 7 days</h2>
+ <a href="{{.Nav}}/apps/{{.AppName}}/analytics?range=7d">View analytics</a>
+ </div>
+ {{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}}
+</section>
{{/* The legacy safety-delay flag: legacy-path-only, exactly as ladder.html
skips this same block in pipeline mode. A pipelined app's bake story is
its own per-channel windows (spec §3) — this global on/off line would
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index de040377d..dc50dd31b 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -673,6 +673,115 @@
}
.packs input[type=number]:hover { border-color: var(--ink); }
.packs input[type=number]:focus-visible { border-color: var(--accent); outline: 2px solid var(--accent); outline-offset: 1px; }
+
+ /* Analytics (app_analytics.html, and the Overview's traffic card). The
+ chart is the page's one loud element; everything around it stays in
+ text ink and hairlines. */
+ .an-off { margin: 0 0 1.5rem; }
+ .an-range { display: flex; flex-wrap: wrap; align-items: center; gap: 0.25rem; margin: 0 0 1.75rem; }
+ .an-range a {
+ padding: 0.3rem 0.75rem; border-radius: 999px; color: var(--muted);
+ text-decoration: none; font-size: 0.9rem;
+ }
+ .an-range a:hover { color: var(--ink); background: var(--accent-soft); }
+ .an-range a[aria-current="page"] { color: var(--ink); background: var(--accent-soft); font-weight: 600; }
+ .an-range a:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .an-span { margin-left: 0.75rem; color: var(--muted); font-size: 0.85rem; }
+ .an-figures { display: flex; flex-wrap: wrap; gap: 1rem 3.5rem; margin: 0 0 1.5rem; }
+ .an-figures dt { color: var(--muted); font-size: 0.9rem; }
+ .an-figures dd { margin: 0; font-size: 2.25rem; font-weight: 600; line-height: 1.15; letter-spacing: -0.01em; }
+ .an-figures dd.an-note { font-size: 0.8rem; font-weight: 400; color: var(--muted); max-width: 16rem; line-height: 1.4; margin-top: 0.3rem; letter-spacing: 0; }
+ .an-empty { color: var(--muted); padding: 2.5rem 0; border-top: 1px solid var(--rule); border-bottom: 1px solid var(--rule); max-width: none; }
+ .an-insights { color: var(--ink); font-size: 0.95rem; margin: 0.75rem 0 0.5rem; max-width: none; }
+ .an-quality { margin: 0 0 2rem; max-width: 48rem; }
+
+ .an-chart { margin: 0; padding-left: 2.25rem; }
+ .an-plot { position: relative; height: 14rem; }
+ .an-overview .an-plot { height: 7rem; }
+ .an-grid span {
+ position: absolute; left: 0; right: 0; height: 0;
+ border-top: 1px solid var(--rule);
+ }
+ .an-grid i {
+ position: absolute; right: calc(100% + 0.5rem); top: -0.6em;
+ font-style: normal; font-size: 0.75rem; color: var(--muted);
+ font-variant-numeric: tabular-nums; white-space: nowrap;
+ }
+ .an-cols, .an-xaxis { display: grid; grid-template-columns: repeat(var(--an-cols), minmax(0, 1fr)); }
+ .an-cols { position: absolute; inset: 0; }
+ /* A column is the hit target, full height, so a zero hour still answers
+ a hover; the bar inside it is capped at 24px and never fills the slot. */
+ button.an-col, .an-col {
+ position: relative; display: flex; align-items: flex-end; justify-content: center;
+ height: 100%; padding: 0 1px; margin: 0; border: 0; border-radius: 0.25rem;
+ background: transparent; color: inherit; font: inherit; cursor: default;
+ }
+ button.an-col:hover, button.an-col:focus-visible { background: var(--accent-soft); }
+ button.an-col:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
+ .an-bar {
+ position: relative; display: block; width: 100%; max-width: 24px; min-height: 0;
+ background: var(--accent); border-radius: 4px 4px 0 0;
+ }
+ button.an-col:hover .an-bar, button.an-col:focus-visible .an-bar { background: var(--accent-strong); }
+ /* The hour or day still being counted: the same hue, hatched, because the
+ bar will still grow. (No percentages in this sheet's own rules: the
+ metrics boundary tests read every "NN%" on an app page as a reading.) */
+ .an-partial .an-bar { background: repeating-linear-gradient(135deg, var(--accent) 0 3px, var(--accent-soft) 3px 6px); }
+ .an-gap::after {
+ content: ""; position: absolute; bottom: -0.55rem; left: 50%; width: 5px; height: 5px;
+ margin-left: -2.5px; border-radius: 50%; background: var(--warn);
+ }
+ .an-tip {
+ display: none; position: absolute; z-index: 2; bottom: calc(100% + 0.4rem); left: 50%;
+ transform: translateX(-50%); width: max-content; max-width: 15rem;
+ padding: 0.5rem 0.7rem; border-radius: 0.4rem; text-align: left;
+ background: var(--ink); color: var(--bg); font-size: 0.8rem; line-height: 1.45;
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18); pointer-events: none;
+ }
+ .an-tip b { display: block; font-size: 0.95rem; font-weight: 600; }
+ .an-tip span { display: block; }
+ .an-tip .an-when { opacity: 0.75; margin-top: 0.15rem; }
+ .an-edge-start .an-tip { left: 0; transform: none; }
+ .an-edge-end .an-tip { left: auto; right: 0; transform: none; }
+ button.an-col:hover .an-tip, button.an-col:focus .an-tip { display: block; }
+ /* The tip is the bar's child, so it opens just above the bar's top,
+ where the eye already is, and never covers the bar it describes. */
+ .an-future { cursor: default; }
+ .an-xaxis { margin-top: 0.35rem; font-size: 0.75rem; color: var(--muted); white-space: nowrap; }
+ .an-xaxis span { justify-self: center; }
+
+ .an-breakdowns { display: grid; grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr)); gap: 2rem 3rem; margin: 0 0 2rem; }
+ .an-card h3 { font-size: 1rem; margin: 0 0 0.6rem; }
+ .an-share { list-style: none; margin: 0 0 0.5rem; }
+ .an-share li {
+ display: grid; grid-template-columns: minmax(0, 1fr) auto 3rem; column-gap: 0.75rem;
+ align-items: baseline; padding: 0.4rem 0 0.45rem; border-bottom: 1px solid var(--rule);
+ }
+ .an-key { overflow-wrap: anywhere; }
+ .an-flag { margin-right: 0.4rem; }
+ .an-val { font-variant-numeric: tabular-nums; text-align: right; }
+ .an-pct { font-variant-numeric: tabular-nums; text-align: right; color: var(--muted); font-size: 0.85rem; }
+ .an-track { grid-column: 1 / -1; display: block; height: 3px; margin-top: 0.3rem; border-radius: 2px; background: var(--accent-soft); }
+ .an-track span { display: block; height: 100%; border-radius: 2px; background: var(--accent); }
+ .an-muted .an-key { color: var(--muted); }
+ .an-muted .an-track span { background: var(--muted); opacity: 0.5; }
+
+ .an-overview { margin: 0 0 2rem; padding: 1.25rem 1.4rem 1.4rem; border: 1px solid var(--rule); border-radius: 0.6rem; }
+ .an-overview-head { display: flex; justify-content: space-between; align-items: baseline; gap: 1rem; margin: 0 0 1rem; }
+ .an-overview-head h2 { font-size: 1rem; margin: 0; }
+ .an-overview .an-figures { gap: 0.75rem 2.5rem; margin-bottom: 1rem; }
+ .an-overview .an-figures dd:not(.an-note) { font-size: 1.6rem; }
+ .an-overview .an-empty { padding: 1.5rem 0; }
+ @media (max-width: 40rem) {
+ .an-figures { gap: 1rem 2rem; }
+ .an-figures dd:not(.an-note) { font-size: 1.75rem; }
+ .an-plot { height: 11rem; }
+ .an-span { flex-basis: 100%; margin: 0.4rem 0 0 0.75rem; }
+ }
+ @media (forced-colors: active) {
+ .an-bar, .an-track span { background: CanvasText; }
+ .an-tip { border: 1px solid CanvasText; }
+ }
.buy-foot { margin: 1.75rem 0 0; }
.buy-foot button { padding: 0.7rem 1.5rem; }
.billing-upgrades { margin-top: 1.25rem; }
diff --git a/internal/console/usagedays.go b/internal/console/usagedays.go
index 353bfafba..aa2cc0605 100644
--- a/internal/console/usagedays.go
+++ b/internal/console/usagedays.go
@@ -12,6 +12,7 @@ import (
"sync"
"time"
+ "github.com/carlosframework/platform/internal/analytics"
"github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/usage"
@@ -133,6 +134,13 @@ func usageDayDate(key string) (date string, ok bool) {
if box, ok := daysDirBox(dir, usage.EdgeBoxesPrefix); ok {
return date, key == usage.EdgeDayKey(box, date)
}
+ // An app's analytics day file (analytics.DayKey), which the Analytics
+ // tab and the Overview's traffic card read through the same cache:
+ // apps/<sqid>/<app>/analytics/<box>/days/<date>.json.
+ if parts := strings.Split(dir, "/"); len(parts) == 6 && parts[0] == "apps" && parts[3] == "analytics" && parts[5] == "days" {
+ want, err := analytics.DayKey(parts[1], parts[2], parts[4], date)
+ return date, err == nil && key == want
+ }
return "", false
}
@@ -189,11 +197,16 @@ func usageDaySettled(date string, now time.Time) bool {
}
// usageDayFirstKept is the oldest date the cache keeps at now: the first of
-// last month, the oldest day any period the page offers starts on.
+// last month, the oldest day any economics period starts on, or the first
+// day of the Analytics tab's 30 days when that is older (early March, when
+// last month is February).
func usageDayFirstKept(now time.Time) string {
now = now.UTC()
- first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
- return usage.DayOf(first.AddDate(0, -1, 0))
+ first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -1, 0)
+ if a := now.Truncate(24*time.Hour).AddDate(0, 0, -29); a.Before(first) {
+ first = a
+ }
+ return usage.DayOf(first)
}
// get is key's entry, when it was read less than usageDayMaxAge before now.