carlos / platform Public

analytics: bots by name, browsers and devices, and the pace check

Paul, 2026-10-30: which bots crawl the site, which browsers read it, and
catch the crawler that walked paulca.com's /posts/ with a browser's user
agent.

- The edge names each bot request from a fixed list (Googlebot, GPTBot,
  ClaudeBot, Ahrefs, curl...; "Other bot", "No user agent") and counts page
  views by browser family and device class. Only those names reach the day
  file (bot_names, browsers, devices, additive and omitted when empty); no
  user agent string is stored.
- The pace check (pace.go): per box and app, a visitor (the day's salted
  visitor hash, held in memory only) with 20 page views inside a minute is
  an "Unnamed crawler" from that view until 30 minutes after their last:
  those views are bot requests, not page views, visitors, pages, referrers
  or countries. The first 19 still count. At most 50,000 visitors held;
  idle ones pruned on every flush and when full; a new visitor past that
  goes unchecked. No salt, no check.
- The tab gains Browsers (with Devices) and Bots cards, shown once an edge
  counts them; the CLI's API carries the three maps.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0c048288e7e2f526f25034a3bee40a577d3807e3 parent 3d93a9c
12 files changed, +441 −9
  • internal/analytics/agents.go +91 −0
  • internal/analytics/agents_test.go +163 −0
  • internal/analytics/day.go +19 −0
  • internal/analytics/meter.go +32 −8
  • internal/analytics/pace.go +79 −0
  • internal/analytics/read.go +8 −0
  • internal/console/analyticsdisplay.go +5 −0
  • internal/console/analyticspages_test.go +16 −1
  • internal/console/analyticsview.go +6 −0
  • internal/console/apianalytics.go +4 −0
  • internal/console/templates/app_analytics.html +17 −0
  • internal/console/templates/layout.html +1 −0

Intent

Human

<task-notification> <task-id>bnlkdscee</task-id> <tool-use-id>toolu_01KDtgBpdtLGYDXHE4H26U5q</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ce90495f-c7a7-490e-9b84-a6251050e87f/tasks/bnlkdscee.output</output-file> <status>completed</status> <summary>Background command "until s=$(amadan ci status carlos/platform -branch analytics-live 2&gt;&amp;1); echo "$s" | head -1 | grep -q 'b1ae6f2d\|'"$(cd /home/paulca/amadan.net/carlos/platform/.claude/worktrees/analytics-live &amp;&amp; git rev-parse --short=8 HEAD)" &amp;&amp; echo "$s" | head -1 | grep -q -E 'CI (passed|failed)'; do sleep 60; done; echo "$s" | head -1; echo "$s" | grep -A14 -E 'Failure summary|timed out' | head -25" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/analytics/agents.go b/internal/analytics/agents.go
new file mode 100644
index 000000000..f4eba4586
--- /dev/null
+++ b/internal/analytics/agents.go
@@ -0,0 +1,91 @@
+package analytics
+
+import "strings"
+
+// Who a request came from, in words from fixed lists (Paul, 2026-10-30:
+// which bots crawl the site, which browsers read it). A user agent is
+// matched and named here, at the edge, and only the name is counted: no
+// user agent string is stored, so nothing a visitor's browser sends lands
+// in a day file except one of the names below.
+
+// botNames names the bot a user agent belongs to, most specific first. The
+// first marker the lower-cased user agent contains wins. A user agent that
+// IsBot flags and none of these name is "Other bot".
+var botNames = []struct{ marker, name string }{
+ {"googlebot", "Googlebot"}, {"google-inspectiontool", "Google"}, {"adsbot-google", "Google"},
+ {"bingbot", "Bingbot"}, {"applebot", "Applebot"}, {"duckduckbot", "DuckDuckGo"},
+ {"yandex", "Yandex"}, {"baiduspider", "Baidu"}, {"slurp", "Yahoo"},
+ {"gptbot", "GPTBot"}, {"oai-searchbot", "OpenAI search"}, {"chatgpt-user", "ChatGPT"},
+ {"claudebot", "ClaudeBot"}, {"claude-user", "Claude"}, {"perplexitybot", "PerplexityBot"},
+ {"amazonbot", "Amazonbot"}, {"meta-externalagent", "Meta"}, {"facebookexternalhit", "Facebook"},
+ {"ccbot", "Common Crawl"}, {"bytespider", "Bytespider"}, {"petalbot", "PetalBot"},
+ {"ahrefs", "Ahrefs"}, {"semrush", "Semrush"}, {"mj12", "Majestic"}, {"dotbot", "DotBot"},
+ {"linkedinbot", "LinkedIn"}, {"twitterbot", "X (Twitter)"}, {"discordbot", "Discord"},
+ {"telegrambot", "Telegram"}, {"whatsapp", "WhatsApp"}, {"slackbot", "Slack"},
+ {"pingdom", "Pingdom"}, {"uptimerobot", "UptimeRobot"}, {"statuscake", "StatusCake"},
+ {"site24x7", "Site24x7"}, {"newrelicpinger", "New Relic"},
+ {"lighthouse", "Lighthouse"}, {"pagespeed", "PageSpeed"}, {"gtmetrix", "GTmetrix"},
+ {"headlesschrome", "Headless Chrome"}, {"phantomjs", "PhantomJS"},
+ {"curl/", "curl"}, {"wget/", "Wget"}, {"python-requests", "Python requests"},
+ {"go-http-client", "Go HTTP client"}, {"okhttp", "OkHttp"}, {"java/", "Java"},
+ {"libwww", "libwww"}, {"scrapy", "Scrapy"}, {"node-fetch", "node-fetch"}, {"axios/", "axios"},
+ {"postmanruntime", "Postman"}, {"insomnia", "Insomnia"}, {"httpclient", "HTTP client"},
+}
+
+// Names the edge gives to bots that are not named by their user agent.
+const (
+ BotNoUserAgent = "No user agent"
+ BotOther = "Other bot"
+ // BotByPace is a visitor whose browser looked like a person's but who
+ // read pages faster than a person does (Meter's pace check).
+ BotByPace = "Unnamed crawler"
+)
+
+// BotName is the name a bot's user agent is counted under.
+func BotName(ua string) string {
+ if strings.TrimSpace(ua) == "" {
+ return BotNoUserAgent
+ }
+ l := strings.ToLower(ua)
+ for _, b := range botNames {
+ if strings.Contains(l, b.marker) {
+ return b.name
+ }
+ }
+ return BotOther
+}
+
+// BrowserFamily is the browser a person's user agent names. Order matters:
+// Edge, Opera and Samsung Internet also say Chrome, and Chrome also says
+// Safari.
+func BrowserFamily(ua string) string {
+ l := strings.ToLower(ua)
+ switch {
+ case strings.Contains(l, "edg/") || strings.Contains(l, "edga/") || strings.Contains(l, "edgios/"):
+ return "Edge"
+ case strings.Contains(l, "opr/") || strings.Contains(l, "opera"):
+ return "Opera"
+ case strings.Contains(l, "samsungbrowser"):
+ return "Samsung Internet"
+ case strings.Contains(l, "firefox/") || strings.Contains(l, "fxios/"):
+ return "Firefox"
+ case strings.Contains(l, "crios/") || strings.Contains(l, "chrome/") || strings.Contains(l, "chromium/"):
+ return "Chrome"
+ case strings.Contains(l, "safari/") && strings.Contains(l, "version/"):
+ return "Safari"
+ }
+ return "Other"
+}
+
+// DeviceClass is the kind of device a person's user agent says it is.
+func DeviceClass(ua string) string {
+ l := strings.ToLower(ua)
+ switch {
+ case strings.Contains(l, "ipad") || strings.Contains(l, "tablet") ||
+ (strings.Contains(l, "android") && !strings.Contains(l, "mobile")):
+ return "Tablet"
+ case strings.Contains(l, "mobi") || strings.Contains(l, "iphone") || strings.Contains(l, "android"):
+ return "Mobile"
+ }
+ return "Desktop"
+}
diff --git a/internal/analytics/agents_test.go b/internal/analytics/agents_test.go
new file mode 100644
index 000000000..d07ea2bdb
--- /dev/null
+++ b/internal/analytics/agents_test.go
@@ -0,0 +1,163 @@
+package analytics
+
+import (
+ "context"
+ "fmt"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestBotName(t *testing.T) {
+ for ua, want := range map[string]string{
+ "": BotNoUserAgent,
+ " ": BotNoUserAgent,
+ "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)": "Googlebot",
+ "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2)": "GPTBot",
+ "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0)": "ClaudeBot",
+ "Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)": "Ahrefs",
+ "curl/8.4.0": "curl",
+ "python-requests/2.31.0": "Python requests",
+ "SomethingBot/1.0": BotOther,
+ } {
+ if got := BotName(ua); got != want {
+ t.Errorf("BotName(%q) = %q, want %q", ua, got, want)
+ }
+ }
+}
+
+func TestBrowserAndDevice(t *testing.T) {
+ for _, tc := range []struct{ ua, browser, device string }{
+ {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15", "Safari", "Desktop"},
+ {"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1", "Safari", "Mobile"},
+ {"Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/120.0 Mobile/15E148 Safari/604.1", "Chrome", "Tablet"},
+ {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36 Edg/120.0", "Edge", "Desktop"},
+ {"Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/23.0 Chrome/115.0 Mobile Safari/537.36", "Samsung Internet", "Mobile"},
+ {"Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0", "Firefox", "Desktop"},
+ {"Mozilla/5.0 (Linux; Android 14; Pixel Tablet) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36", "Chrome", "Tablet"},
+ {"Lynx/2.9.0", "Other", "Desktop"},
+ } {
+ if got := BrowserFamily(tc.ua); got != tc.browser {
+ t.Errorf("BrowserFamily(%q) = %q, want %q", tc.ua, got, tc.browser)
+ }
+ if got := DeviceClass(tc.ua); got != tc.device {
+ t.Errorf("DeviceClass(%q) = %q, want %q", tc.ua, got, tc.device)
+ }
+ }
+}
+
+const safariUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15"
+
+func pageObs(path string, when time.Time, ip string) Obs {
+ return Obs{Acct: release.OpsAccount, App: "site", Host: "site.example.com", Method: "GET", Status: 200,
+ ContentType: "text/html", Path: path, UA: safariUA, ClientIP: ip, When: when, Bytes: 100}
+}
+
+// A browser that reads pages faster than a person: its first paceLimit-1
+// views are page views, the rest of the minute and everything until
+// paceHold after its last view are an unnamed crawler's. Another visitor at
+// the same time is untouched.
+func TestPaceCountsAFastReaderAsACrawler(t *testing.T) {
+ t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC)
+ m := NewMeter(t.TempDir(), "box1", func() time.Time { return t0 })
+ for i := 0; i < 40; i++ {
+ m.Observe(pageObs(fmt.Sprintf("/posts/%d.html", i), t0.Add(time.Duration(i)*time.Second), "203.0.113.1"))
+ }
+ m.Observe(pageObs("/", t0.Add(30*time.Second), "203.0.113.2")) // a person, same minute
+ m.Observe(pageObs("/late", t0.Add(20*time.Minute), "203.0.113.1")) // inside the hold
+ m.Observe(pageObs("/back", t0.Add(80*time.Minute), "203.0.113.1")) // after the hold
+ d := drainOne(t, m)
+ var pv, bots int64
+ for _, h := range d.Hours {
+ pv += h.PV
+ bots += h.Bots
+ }
+ if pv != paceLimit-1+1+1 || bots != 40-(paceLimit-1)+1 {
+ t.Fatalf("page views %d bots %d, want %d and %d", pv, bots, paceLimit-1+2, 40-(paceLimit-1)+1)
+ }
+ if d.BotNames[BotByPace] != bots {
+ t.Errorf("bot names = %v", d.BotNames)
+ }
+ if d.Pages.counts["/posts/30.html"] != 0 || d.Pages.counts["/back"] != 1 || d.Pages.counts["/late"] != 0 {
+ t.Errorf("pages = %v", d.Pages.counts)
+ }
+ if d.Browsers["Safari"] != pv || d.Devices["Desktop"] != pv {
+ t.Errorf("browsers %v devices %v, want only the page views", d.Browsers, d.Devices)
+ }
+}
+
+// A steady reader (one page every 4 s, 15 a minute) is never a crawler.
+func TestPaceLeavesASteadyReaderAlone(t *testing.T) {
+ t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC)
+ m := NewMeter(t.TempDir(), "box1", func() time.Time { return t0 })
+ for i := 0; i < 60; i++ {
+ m.Observe(pageObs("/p", t0.Add(time.Duration(i)*4*time.Second), "203.0.113.1"))
+ }
+ d := drainOne(t, m)
+ var bots int64
+ for _, h := range d.Hours {
+ bots += h.Bots
+ }
+ if bots != 0 {
+ t.Fatalf("a reader at 15 pages a minute counted %d bot views", bots)
+ }
+}
+
+// The pace map is bounded: past paceMaxVisitors, idle visitors are dropped,
+// and a new visitor goes unchecked rather than growing the map.
+func TestPaceMapIsBounded(t *testing.T) {
+ t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC)
+ m := &Meter{}
+ for i := 0; i < paceMaxVisitors; i++ {
+ m.tooFast(AppKey{App: "a"}, uint64(i), t0)
+ }
+ if m.tooFast(AppKey{App: "a"}, 1<<40, t0); len(m.paces) != paceMaxVisitors {
+ t.Fatalf("map grew to %d", len(m.paces))
+ }
+ m.tooFast(AppKey{App: "a"}, 1<<41, t0.Add(paceHold+time.Minute))
+ if len(m.paces) != 1 {
+ t.Fatalf("idle visitors not dropped: %d left", len(m.paces))
+ }
+}
+
+// The new counts reach the day file and the window read, summed across
+// boxes, and a day file from before them still reads.
+func TestAgentCountsRoundTrip(t *testing.T) {
+ store := release.NewDirStore(filepath.Join(t.TempDir(), "store"))
+ t0 := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC)
+ for _, box := range []string{"box1", "box2"} {
+ m := NewMeter(t.TempDir(), box, func() time.Time { return t0 })
+ m.Observe(pageObs("/", t0, "203.0.113.1"))
+ bot := pageObs("/", t0, "203.0.113.9")
+ bot.UA = "Mozilla/5.0 (compatible; GPTBot/1.2)"
+ m.Observe(bot)
+ for k, ds := range m.Drain() {
+ for _, d := range ds {
+ if err := UpsertDay(context.Background(), store, k.Acct, k.App, d); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ }
+ sum, err := ReadRange(context.Background(), store, release.OpsAccount, "site", t0, t0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if sum.BotNames["GPTBot"] != 2 || sum.Browsers["Safari"] != 2 || sum.Devices["Desktop"] != 2 {
+ t.Fatalf("bot names %v browsers %v devices %v", sum.BotNames, sum.Browsers, sum.Devices)
+ }
+}
+
+func drainOne(t *testing.T, m *Meter) Delta {
+ t.Helper()
+ for _, ds := range m.Drain() {
+ if len(ds) != 1 {
+ t.Fatalf("%d deltas, want 1", len(ds))
+ }
+ return ds[0]
+ }
+ t.Fatal("nothing drained")
+ return Delta{}
+}
diff --git a/internal/analytics/day.go b/internal/analytics/day.go
index 9bbcd9c17..5828beb25 100644
--- a/internal/analytics/day.go
+++ b/internal/analytics/day.go
@@ -51,6 +51,13 @@ type Day struct {
// spec §9): the provenance the attribution on the analytics page needs.
GeoSources map[string]int64 `json:"geo_sources,omitempty"`
Restarted bool `json:"restarted,omitempty"`
+ // BotNames counts bot requests by who sent them (agents.go: a name
+ // from a fixed list, never the user agent itself); Browsers and Devices
+ // count page views by browser family and device class. Absent from a
+ // day written by an edge before them.
+ BotNames map[string]int64 `json:"bot_names,omitempty"`
+ Browsers map[string]int64 `json:"browsers,omitempty"`
+ Devices map[string]int64 `json:"devices,omitempty"`
}
// Delta is one flush batch from one box for one app-day.
@@ -69,6 +76,10 @@ type Delta struct {
// spec §9), bounded by boundedAdd.
Countries map[string]int64
GeoSources map[string]int64
+ // BotNames, Browsers and Devices: see Day.
+ BotNames map[string]int64
+ Browsers map[string]int64
+ Devices map[string]int64
// requeued marks a delta that has already been through one failed
// flush (internal/analytics.Meter.Requeue). Not serialised: it never
@@ -144,6 +155,9 @@ func (d *Day) Merge(x Delta) (bool, error) {
d.Restarted = d.Restarted || x.Restarted
d.Countries = mergeCounts(d.Countries, x.Countries, maxCountryKeys, nil)
d.GeoSources = mergeCounts(d.GeoSources, x.GeoSources, maxGeoSourceKeys, attributed)
+ d.BotNames = mergeCounts(d.BotNames, x.BotNames, maxBotNameKeys, nil)
+ d.Browsers = mergeCounts(d.Browsers, x.Browsers, maxBrowserKeys, nil)
+ d.Devices = mergeCounts(d.Devices, x.Devices, maxDeviceKeys, nil)
d.Seq[x.Box] = x.Seq
return true, nil
}
@@ -204,6 +218,11 @@ func UpsertDay(ctx context.Context, s release.Store, sqid, app string, x Delta)
const (
maxCountryKeys = 300
maxGeoSourceKeys = 8
+ // The agent names come from fixed lists, so these only bound a day
+ // written by something else.
+ maxBotNameKeys = 100
+ maxBrowserKeys = 20
+ maxDeviceKeys = 8
)
// attributed reports whether a database type carries an attribution the
diff --git a/internal/analytics/meter.go b/internal/analytics/meter.go
index 3c502bf5f..58ab6d6c5 100644
--- a/internal/analytics/meter.go
+++ b/internal/analytics/meter.go
@@ -108,10 +108,11 @@ type Meter struct {
seq int64
saltDay string
salt []byte
- saltFailDay string // date DaySalt last failed for, "" once it next succeeds
- saltFailAt time.Time // when it failed; not retried until saltRetryDelay has passed
- started string // date the process started; "" once the wall clock has moved past it (see Drain)
- restartedFlagged map[AppKey]bool // apps whose start-day delta has already carried Restarted
+ saltFailDay string // date DaySalt last failed for, "" once it next succeeds
+ saltFailAt time.Time // when it failed; not retried until saltRetryDelay has passed
+ started string // date the process started; "" once the wall clock has moved past it (see Drain)
+ restartedFlagged map[AppKey]bool // apps whose start-day delta has already carried Restarted
+ paces map[paceKey]*paceState // the pace check's visitors (pace.go)
}
// NewMeter returns a meter whose salts live in saltDir (the box data dir).
@@ -156,7 +157,8 @@ func (m *Meter) delta(k AppKey, date string) *Delta {
restarted := date == m.started && !m.restartedFlagged[k]
d = &Delta{Date: date, Box: m.box, Hours: map[string]HourRow{}, Visitors: &HLL{},
Pages: NewTopK(), Referers: NewTopK(), Events: NewTopK(), Restarted: restarted,
- Countries: map[string]int64{}, GeoSources: map[string]int64{}}
+ Countries: map[string]int64{}, GeoSources: map[string]int64{},
+ BotNames: map[string]int64{}, Browsers: map[string]int64{}, Devices: map[string]int64{}}
days[date] = d
if restarted {
m.restartedFlagged[k] = true // this app's start-day note is spent; a later drain's fresh delta for the same day must not repeat it
@@ -173,17 +175,38 @@ func (m *Meter) Observe(o Obs) {
path := apperr.SanitizePath(o.Path)
m.mu.Lock()
defer m.mu.Unlock()
- d := m.delta(AppKey{Acct: o.Acct, App: o.App}, date)
+ k := AppKey{Acct: o.Acct, App: o.App}
+ d := m.delta(k, date)
row := d.Hours[hour]
row.Bytes += o.Bytes
+ botName := ""
+ if bot {
+ botName = BotName(o.UA)
+ }
+ var visitor uint64
+ salt := []byte(nil)
+ if pv {
+ salt = m.saltFor(date)
+ }
+ if salt != nil {
+ visitor = VisitorHash(salt, o.Host, o.ClientIP, o.UA)
+ // A browser that reads faster than a person is a crawler: its view
+ // is a bot's, not a page view (pace.go).
+ if m.tooFast(k, visitor, o.When) {
+ pv, bot, botName = false, true, BotByPace
+ }
+ }
if bot {
row.Bots++
+ boundedAdd(d.BotNames, botName, 1, maxBotNameKeys, nil)
}
if pv {
row.PV++
- if salt := m.saltFor(date); salt != nil {
- d.Visitors.Add(VisitorHash(salt, o.Host, o.ClientIP, o.UA))
+ if salt != nil {
+ d.Visitors.Add(visitor)
}
+ boundedAdd(d.Browsers, BrowserFamily(o.UA), 1, maxBrowserKeys, nil)
+ boundedAdd(d.Devices, DeviceClass(o.UA), 1, maxDeviceKeys, nil)
d.Pages.Add(path, 1)
ref := o.RefererHost
if ref == "" {
@@ -218,6 +241,7 @@ func (m *Meter) Track(acct, app, name string, when time.Time) {
func (m *Meter) Drain() map[AppKey][]Delta {
m.mu.Lock()
defer m.mu.Unlock()
+ m.prunePaces(m.now())
out := map[AppKey][]Delta{}
for k, ds := range m.pending {
out[k] = append(out[k], ds...)
diff --git a/internal/analytics/pace.go b/internal/analytics/pace.go
new file mode 100644
index 000000000..08ff1e741
--- /dev/null
+++ b/internal/analytics/pace.go
@@ -0,0 +1,79 @@
+package analytics
+
+import "time"
+
+// The pace check: a crawler whose user agent looks like a browser's still
+// reads pages faster than a person does (paulca.com, 2026-10-28: one visitor
+// walked /posts/1.html to /posts/40.html, each counted as a page view). Per
+// box and per app, the meter counts each visitor's page views in a window of
+// paceWindow; from the paceLimit-th view on, that visitor's views are counted
+// as a bot (BotByPace) until paceHold after their last view. The first
+// paceLimit-1 views still count as page views: the check cannot know a
+// reader is a crawler before it has read too fast.
+//
+// A visitor is the day's visitor hash (VisitorHash): salted, never stored,
+// held only in this map. With no salt (DaySalt failing) there is no hash
+// and no check. The map holds at most paceMaxVisitors entries; past that,
+// entries idle for paceHold are dropped, and if it is still full a new
+// visitor goes unchecked rather than growing it. Drain prunes it too.
+const (
+ paceWindow = time.Minute
+ paceLimit = 20
+ paceHold = 30 * time.Minute
+ paceMaxVisitors = 50_000
+)
+
+type paceKey struct {
+ app AppKey
+ visitor uint64
+}
+
+type paceState struct {
+ start time.Time // the current window's first view
+ n int // views in the current window
+ last time.Time // the latest view
+ flagged bool // read too fast; held until last+paceHold
+}
+
+// tooFast records one page view by visitor at when and reports whether the
+// view, and so the visitor, is now counted as a crawler. Called with m.mu
+// held.
+func (m *Meter) tooFast(app AppKey, visitor uint64, when time.Time) bool {
+ if m.paces == nil {
+ m.paces = map[paceKey]*paceState{}
+ }
+ k := paceKey{app, visitor}
+ p := m.paces[k]
+ if p == nil {
+ if len(m.paces) >= paceMaxVisitors {
+ m.prunePaces(when)
+ if len(m.paces) >= paceMaxVisitors {
+ return false
+ }
+ }
+ p = &paceState{start: when}
+ m.paces[k] = p
+ }
+ if p.flagged && when.Sub(p.last) > paceHold {
+ p.flagged = false
+ }
+ if when.Sub(p.start) >= paceWindow || when.Before(p.start) {
+ p.start, p.n = when, 0
+ }
+ p.n++
+ p.last = when
+ if p.n >= paceLimit {
+ p.flagged = true
+ }
+ return p.flagged
+}
+
+// prunePaces drops visitors idle for longer than paceHold at now. Called
+// with m.mu held.
+func (m *Meter) prunePaces(now time.Time) {
+ for k, p := range m.paces {
+ if now.Sub(p.last) > paceHold {
+ delete(m.paces, k)
+ }
+ }
+}
diff --git a/internal/analytics/read.go b/internal/analytics/read.go
index 255104ca3..c1caa84cc 100644
--- a/internal/analytics/read.go
+++ b/internal/analytics/read.go
@@ -44,6 +44,9 @@ type Summary struct {
Events map[string]int64
Countries map[string]int64
GeoSources map[string]int64
+ BotNames map[string]int64
+ Browsers map[string]int64
+ Devices map[string]int64
PagesApprox bool
ReferersApprox bool
EventsApprox bool
@@ -80,6 +83,7 @@ func ReadRange(ctx context.Context, s release.Store, sqid, app string, from, to
sort.Strings(sum.Boxes)
pages, refs, events := NewTopK(), NewTopK(), NewTopK()
countries, sources := map[string]int64{}, map[string]int64{}
+ botNames, browsers, devices := map[string]int64{}, map[string]int64{}, map[string]int64{}
for _, date := range Dates(from, to) {
ds := DaySummary{Date: date}
vis := &HLL{}
@@ -117,6 +121,9 @@ func ReadRange(ctx context.Context, s release.Store, sqid, app string, from, to
events.Merge(TopKFrom(day.Events))
mergeCounts(countries, day.Countries, maxCountryKeys, nil)
mergeCounts(sources, day.GeoSources, maxGeoSourceKeys, attributed)
+ mergeCounts(botNames, day.BotNames, maxBotNameKeys, nil)
+ mergeCounts(browsers, day.Browsers, maxBrowserKeys, nil)
+ mergeCounts(devices, day.Devices, maxDeviceKeys, nil)
sum.Dropped.E = addDrops(sum.Dropped.E, day.Dropped.E)
sum.Dropped.A = addDrops(sum.Dropped.A, day.Dropped.A)
sum.Dropped.Flush += day.Dropped.Flush
@@ -136,6 +143,7 @@ func ReadRange(ctx context.Context, s release.Store, sqid, app string, from, to
sum.Referers, sum.ReferersApprox = refs.Fold(), refs.Approximate()
sum.Events, sum.EventsApprox = events.Fold(), events.Approximate()
sum.Countries, sum.GeoSources = countries, sources
+ sum.BotNames, sum.Browsers, sum.Devices = botNames, browsers, devices
return sum, nil
}
diff --git a/internal/console/analyticsdisplay.go b/internal/console/analyticsdisplay.go
index c29435826..45207e3a1 100644
--- a/internal/console/analyticsdisplay.go
+++ b/internal/console/analyticsdisplay.go
@@ -313,6 +313,11 @@ func refererLabel(k string) (string, string, bool) {
return k, "", false
}
+// botLabel mutes the bots no list names: they are the ones to look into.
+func botLabel(k string) (string, string, bool) {
+ return k, "", k == analytics.BotOther || k == analytics.BotNoUserAgent
+}
+
// countryLabel is a Countries row: the country's name and its flag, the
// two reserved buckets in words.
func countryLabel(k string) (string, string, bool) {
diff --git a/internal/console/analyticspages_test.go b/internal/console/analyticspages_test.go
index c06886ca8..268629b43 100644
--- a/internal/console/analyticspages_test.go
+++ b/internal/console/analyticspages_test.go
@@ -75,7 +75,7 @@ func TestAnalyticsPagesView(t *testing.T) {
m := analytics.NewMeter(t.TempDir(), "box1", func() time.Time { return when })
for i := 0; i < 30; i++ {
m.Observe(analytics.Obs{Acct: release.OpsAccount, App: "titogo", Host: "titogo.example.com", Method: "GET", Status: 200,
- ContentType: "text/html", Path: fmt.Sprintf("/posts/%d.html", i), UA: "Mozilla/5.0 Safari", ClientIP: "203.0.113.9", When: when})
+ ContentType: "text/html", Path: fmt.Sprintf("/posts/%d.html", i), UA: "Mozilla/5.0 Safari", ClientIP: fmt.Sprintf("203.0.113.%d", i), When: when})
}
for k, ds := range m.Drain() {
for _, d := range ds {
@@ -131,3 +131,18 @@ func TestCapRows(t *testing.T) {
t.Fatalf("short list = %d rows, %d more", len(got), more)
}
}
+
+// Browsers, devices and bots by name show once an edge counts them.
+func TestAnalyticsAgentCards(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-analytics-agents")
+ seedAnalytics(t, fx, seedTime()) // five Safari-ish views and a Googlebot
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-analytics-agents-browser")
+ _, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
+ for _, want := range []string{">Browsers</h3>", ">Devices</h3>", "Desktop", ">Bots</h3>", "Googlebot", "An unnamed crawler is a browser that read pages faster than a person does."} {
+ if !strings.Contains(body, want) {
+ t.Errorf("tab missing %q", want)
+ }
+ }
+}
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go
index d47fc1acb..51fd60861 100644
--- a/internal/console/analyticsview.go
+++ b/internal/console/analyticsview.go
@@ -254,6 +254,9 @@ type analyticsWindow struct {
// shown in full by the pages view (Sections) or counted.
PagesMore, ReferersMore int
PagesTotal int64 // pages counted, not the overflow row
+ // Browsers and Devices are page views by browser family and device
+ // class; Bots is bot requests by name (internal/analytics agents.go).
+ Browsers, Devices, Bots []shareRow
Sections []pageSection
}
@@ -510,6 +513,9 @@ func (s *Server) readAnalyticsFor(ctx context.Context, sqid, app string, q analy
out.Sections = buildPageSections(sum, rng == range7d || rng == range30d)
}
out.Countries = shareRows(geoCountries(sum.Countries), countryLabel)
+ out.Browsers = shareRows(sum.Browsers, nil)
+ out.Devices = shareRows(sum.Devices, nil)
+ out.Bots = shareRows(sum.BotNames, botLabel)
out.Restarts = restartNote(sum.Days, now)
return out, nil
}
diff --git a/internal/console/apianalytics.go b/internal/console/apianalytics.go
index 97823f5e6..dd03f26c9 100644
--- a/internal/console/apianalytics.go
+++ b/internal/console/apianalytics.go
@@ -36,6 +36,9 @@ type analyticsResponse struct {
Events map[string]int64 `json:"events"`
Countries map[string]int64 `json:"countries"`
GeoSources map[string]int64 `json:"geo_sources"`
+ BotNames map[string]int64 `json:"bot_names,omitempty"`
+ Browsers map[string]int64 `json:"browsers,omitempty"`
+ Devices map[string]int64 `json:"devices,omitempty"`
PagesApprox bool `json:"pages_approx"`
ReferersApprox bool `json:"referers_approx"`
EventsApprox bool `json:"events_approx"`
@@ -78,6 +81,7 @@ func (s *Server) handleAPIAnalytics(w http.ResponseWriter, r *http.Request) {
PagesApprox: sum.PagesApprox, ReferersApprox: sum.ReferersApprox, EventsApprox: sum.EventsApprox,
Dropped: sum.Dropped,
Countries: topWithOther(sum.Countries, 10), GeoSources: sum.GeoSources,
+ BotNames: sum.BotNames, Browsers: sum.Browsers, Devices: sum.Devices,
}
// "Nothing counted" is an empty object, not null — the same shape
// errorsResponse gives its groups, so a caller may index the answer
diff --git a/internal/console/templates/app_analytics.html b/internal/console/templates/app_analytics.html
index 9daaa2149..588c434c3 100644
--- a/internal/console/templates/app_analytics.html
+++ b/internal/console/templates/app_analytics.html
@@ -76,6 +76,23 @@ When analytics is on, the edge counts HTML page views and daily visitors. No Jav
{{if .Countries}}{{template "sharelist" .Countries}}{{else}}<p class="small">No country data for this period.</p>{{end}}
{{range geoAttributions .Sum.GeoSources}}<p class="small"><a href="{{.URL}}">{{.Text}}</a></p>{{end}}
</section>
+ {{/* Browsers, devices and bots come from edges that count them; on an
+ older edge's days there are none, and the cards stay away. */}}
+ {{if or .Browsers .Devices}}
+ <section class="an-card" aria-labelledby="an-browsers">
+ <h3 id="an-browsers">Browsers</h3>
+ {{template "sharelist" .Browsers}}
+ <h3 class="an-subhead">Devices</h3>
+ {{template "sharelist" .Devices}}
+ </section>
+ {{end}}
+ {{if .Bots}}
+ <section class="an-card" aria-labelledby="an-bots">
+ <h3 id="an-bots">Bots</h3>
+ {{template "sharelist" .Bots}}
+ <p class="small">Requests from bots and crawlers, left out of every number above. An unnamed crawler is a browser that read pages faster than a person does.</p>
+ </section>
+ {{end}}
</div>{{end}}
{{end}}
<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>
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index 17fec0605..46c804139 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -775,6 +775,7 @@
.an-muted .an-track span { background: var(--muted); opacity: 0.5; }
.an-more { margin: 0.6rem 0 0; font-size: 0.9rem; }
+ .an-card h3.an-subhead { margin-top: 1.4rem; }
.an-pages { margin: 0 0 2rem; }
.an-pages-head { display: flex; justify-content: space-between; align-items: baseline; gap: 1rem; margin: 0 0 0.8rem; }
.an-pages-head h3 { font-size: 1rem; margin: 0; }