Skip to main content

rws_proxy/traffic/
record.rs

1//! Counting traffic: every request (fed from the access-log path, so all
2//! protocols and whether or not lines are written) lands in hourly counts
3//! per host and group, daily unique visitors, and daily top lists.
4//!
5//! Bounded by construction: every site the configuration routes
6//! ([`set_configured_hosts`], up to [`MAX_SLOTS`]) and [`MAX_HOSTS`] other
7//! Host headers (more go to `other`),
8//! hourly buckets for `retention_days`, top lists of [`TOP`] entries a day
9//! (the rest added to `(other)`), [`MAX_PENDING`] undecided browsers per
10//! shard, a classification cache of [`MAX_CACHE`] per shard. Unique
11//! visitors are counted with `hash(secret, day, host, ip, user-agent)` —
12//! the secret is made at start and never stored, nor are the hashes — so
13//! nobody can be followed from one day to the next and no IP or User-Agent
14//! is kept.
15//!
16//! A browser isn't a person until it loads a stylesheet, script or font as
17//! a browser rendering the page does: its requests wait in a pending record
18//! and are counted as a person's then, or as "browser, no assets" (a bot)
19//! after [`UNDECIDED`] without one — or at once after 32 requests without
20//! one.
21
22use std::collections::hash_map::RandomState;
23use std::collections::{BTreeMap, HashMap, VecDeque};
24use std::hash::{BuildHasher, Hash, Hasher};
25use std::net::IpAddr;
26use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
27use std::sync::{Mutex, OnceLock, RwLock};
28use std::time::{Duration, SystemTime, UNIX_EPOCH};
29
30use super::{classify, Class, Group, Kind};
31
32/// Host headers that aren't a configured site counted separately; others
33/// are `other`.
34pub const MAX_HOSTS: usize = 16;
35/// Host slots in all (the index is a `u8`; one is kept for `other`).
36pub const MAX_SLOTS: usize = 255;
37/// Entries a daily top list keeps.
38pub const TOP: usize = 200;
39/// Entries of each top list kept on disk and reported.
40pub const TOP_SAVED: usize = 100;
41/// Browsers awaiting their first asset, per shard.
42pub const MAX_PENDING: usize = 4096;
43/// Classifications cached per shard.
44pub const MAX_CACHE: usize = 16384;
45/// A browser that loads no asset this long after its last request isn't
46/// a person.
47pub const UNDECIDED: Duration = Duration::from_secs(120);
48/// A browser that makes this many requests without loading an asset is
49/// decided at once: automation.
50const MAX_PENDING_REQUESTS: usize = 32;
51const SHARDS: usize = 16;
52
53/// The groups counted, as array indexes: people, AI agents, bots, the
54/// site's apps (18.35) and the owner (18.35).
55const PEOPLE: usize = 0;
56const AI: usize = 1;
57const BOTS: usize = 2;
58const APPS: usize = 3;
59const OWNER: usize = 4;
60/// How many groups are counted.
61pub const GROUPS: usize = 5;
62
63fn slot(group: Group) -> Option<usize> {
64    match group {
65        Group::Person => Some(PEOPLE),
66        Group::Ai => Some(AI),
67        Group::Bot => Some(BOTS),
68        Group::App => Some(APPS),
69        Group::Owner => Some(OWNER),
70        Group::Internal => None,
71    }
72}
73
74/// One request, as counted.
75#[derive(Clone, Debug)]
76#[doc(hidden)]
77pub struct Hit<'a> {
78    pub ip: IpAddr,
79    pub host: &'a str,
80    pub user_agent: Option<&'a str>,
81    pub referer: Option<&'a str>,
82    pub method: &'a str,
83    pub path: &'a str,
84    pub status: i16,
85    /// The response's media type, when known.
86    pub content_type: Option<&'a str>,
87    /// The request's headers: read (for the `Sec-CH-UA-Platform` and
88    /// `Sec-CH-UA-Mobile` client hints) only when a visitor is first seen,
89    /// so other requests don't pay for the lookup.
90    pub headers: &'a [crate::header::Header],
91    pub now: u64,
92}
93
94/// The per-day lists of people's audience and sources, keyed
95/// `host\tvalue`: countries, browsers, OSes and device classes count
96/// visitors; channels and UTM values count visits (page views arriving
97/// from outside the site).
98pub const DIMS: [&str; 8] = ["countries", "browsers", "os", "devices", "channels", "utm_source", "utm_medium", "utm_campaign"];
99const COUNTRIES: usize = 0;
100const CHANNELS: usize = 4;
101const UTM: usize = 5;
102/// A person's page views more than this apart are separate sessions (as
103/// Google Analytics counts them).
104pub const SESSION_GAP: u64 = 30 * 60;
105/// Sessions open at once, per shard; past it the quietest is closed.
106#[cfg(not(test))]
107pub const MAX_OPEN_SESSIONS: usize = 8192;
108#[cfg(test)]
109pub const MAX_OPEN_SESSIONS: usize = 64;
110
111/// The per-day lists the script feeds (`[traffic] script`): seconds and
112/// page views with a report, keyed `host/path`; scroll depth, screen
113/// sizes, events and event properties, keyed `host\tvalue`; goal
114/// conversions (sessions that reached the goal), keyed `host\tgoal`.
115pub const BEHAVIOUR: [&str; 7] = ["engaged_secs", "engaged_views", "scroll", "screens", "events", "event_props", "goals"];
116const ENGAGED_SECS: usize = 0;
117const ENGAGED_VIEWS: usize = 1;
118const SCROLL: usize = 2;
119const SCREENS: usize = 3;
120const EVENTS: usize = 4;
121const EVENT_PROPS: usize = 5;
122const GOALS: usize = 6;
123/// Reports a session may make; the rest are ignored.
124pub const MAX_REPORTS: u32 = 500;
125/// The longest time on one page counted (a tab left open).
126pub const MAX_ENGAGED_SECS: u64 = 6 * 3600;
127
128/// How far back the live view looks.
129pub const LIVE_WINDOW: u64 = 30 * 60;
130/// People's recent page views kept for it, per shard.
131pub const MAX_RECENT: usize = 4096;
132
133/// A person's page view, for the live view.
134#[derive(Clone, Debug)]
135#[doc(hidden)]
136pub struct Recent {
137    pub at: u64,
138    pub visitor: u64,
139    /// `host/path`.
140    pub page: String,
141    pub country: Option<[u8; 2]>,
142}
143
144/// Entries a day's audience/source list keeps (all hosts together).
145pub const DIM_TOP: usize = 400;
146/// Entries of each audience/source list kept on disk.
147pub const DIM_SAVED: usize = 300;
148
149/// A person's country and device, worked out once a day.
150#[derive(Clone, Debug)]
151struct Audience {
152    country: Option<[u8; 2]>,
153    device: super::device::Device,
154}
155
156/// How a visit arrived, for a page view from outside the site.
157#[derive(Clone, Debug, Default)]
158struct Arrival {
159    channel: &'static str,
160    /// `utm_source`, `utm_medium`, `utm_campaign`.
161    utm: [Option<String>; 3],
162}
163
164#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
165#[doc(hidden)]
166pub struct Counts {
167    pub requests: u64,
168    pub pages: u64,
169}
170
171/// A top list: counts by key, at most [`TOP`] keys and `(other)`.
172#[derive(Default, Debug, Clone)]
173#[doc(hidden)]
174pub struct Top(pub HashMap<String, u64>);
175
176impl Top {
177    fn add(&mut self, key: &str, n: u64) {
178        self.add_capped(key, n, TOP);
179    }
180
181    fn add_capped(&mut self, key: &str, n: u64, cap: usize) {
182        if let Some(count) = self.0.get_mut(key) {
183            *count += n;
184        } else if self.0.len() < cap {
185            self.0.insert(key.chars().take(300).collect(), n);
186        } else {
187            *self.0.entry("(other)".to_string()).or_default() += n;
188        }
189    }
190
191    #[doc(hidden)]
192    pub fn merge(&mut self, other: &Top) {
193        for (key, n) in &other.0 {
194            *self.0.entry(key.clone()).or_default() += n;
195        }
196    }
197
198    #[doc(hidden)]
199    pub fn sorted(&self, n: usize) -> Vec<(String, u64)> {
200        let mut out: Vec<(String, u64)> = self.0.iter().map(|(k, v)| (k.clone(), *v)).collect();
201        out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
202        out.truncate(n);
203        out
204    }
205}
206
207/// One day's lists and unique visitors (all hosts; keys carry the host).
208#[derive(Default, Debug, Clone)]
209#[doc(hidden)]
210pub struct Day {
211    pub visitors: [u64; GROUPS],
212    pub people_pages: Top,
213    pub ai_pages: Top,
214    /// `name\toperator\tkind\tverified`, all sites: days saved before
215    /// 18.35 only (now [`Day::site_ai_agents`]).
216    pub ai_agents: Top,
217    /// `kind\tname`, all sites: days saved before 18.35 only.
218    pub bots: Top,
219    /// Referring hosts, all sites: days saved before 18.35 only.
220    pub referrers: Top,
221    /// Unique visitors per site: `host\tgroup` (`0` people, `1` AI, `2` bots).
222    pub site_visitors: Top,
223    /// `host\tname\toperator\tkind\tverified`.
224    pub site_ai_agents: Top,
225    /// `host\tkind\tname`.
226    pub site_bots: Top,
227    /// `host\treferring host`.
228    pub site_referrers: Top,
229    pub not_found: Top,
230    /// The [`DIMS`] lists, in that order.
231    pub dims: [Top; 8],
232    /// People's sessions per host (by the day they started).
233    pub sessions: BTreeMap<String, Sessions>,
234    /// The first and last page of people's sessions (`host/path`).
235    pub entry_pages: Top,
236    pub exit_pages: Top,
237    /// The [`BEHAVIOUR`] lists, in that order.
238    pub behaviour: [Top; 7],
239    /// The [`EXTRA`] lists (18.35), in that order.
240    pub extra: [Top; EXTRA.len()],
241    /// People's visits that ended this day (18.35): the recent-visitors
242    /// feed. Only the last [`MAX_VISITS`] are kept across all days.
243    pub visits: Vec<Visit>,
244}
245
246/// The per-day lists added in 18.35, all keyed by host first:
247/// - `site_apps`: app users, `host\tapp\tplatform`;
248/// - `app_versions`: app users, `host\tapp\tversion`;
249/// - `app_events`: events apps sent to `/_rws/e`, `host\tapp\tevent`;
250/// - `site_tiers`: visitors by how sure rws is they're a person,
251///   `host\ttier` (`verified` ran the script, `page-only` loaded no asset,
252///   `hosting` came from a server network);
253/// - `site_probes`: scanner requests, `host\tpath`;
254/// - `probe_sources`: scanner requests, `host\tcountry\tnetwork` (and the
255///   address with `[traffic] probe_addresses`);
256/// - `site_crawl`: named bots' and AI agents' page fetches and 404s,
257///   `host\tname\tpages|404`;
258/// - `crawl_404`: the paths named bots got a 404 for, `host/path\tname`;
259/// - `site_entries`: the first page of people's visits by channel,
260///   `host/path\tchannel`;
261/// - `downloads`: files downloaded (installers, packages, archives,
262///   `install.sh`), `host/path\tgroup`;
263/// - `owner_pages`: the owner's page views, `host/path`.
264pub const EXTRA: [&str; 11] =
265    ["site_apps", "app_versions", "app_events", "site_tiers", "site_probes", "probe_sources", "site_crawl", "crawl_404", "site_entries", "downloads", "owner_pages"];
266const SITE_APPS: usize = 0;
267const APP_VERSIONS: usize = 1;
268const APP_EVENTS: usize = 2;
269const SITE_TIERS: usize = 3;
270const SITE_PROBES: usize = 4;
271const PROBE_SOURCES: usize = 5;
272const SITE_CRAWL: usize = 6;
273const CRAWL_404: usize = 7;
274const SITE_ENTRIES: usize = 8;
275const DOWNLOADS: usize = 9;
276const OWNER_PAGES: usize = 10;
277
278/// Visits kept for the recent-visitors feed (across all days).
279pub const MAX_VISITS: usize = 300;
280/// Pages a visit lists.
281pub const VISIT_PAGES: usize = 20;
282
283/// One person's visit (a closed session, or an open one in a snapshot),
284/// for the recent-visitors feed: what they read and how they came, with
285/// no address, User-Agent or visitor key.
286#[derive(Clone, Debug, Default, PartialEq, Eq)]
287#[doc(hidden)]
288pub struct Visit {
289    pub start: u64,
290    pub end: u64,
291    pub host: String,
292    /// Paths, in order (at most [`VISIT_PAGES`]).
293    pub pages: Vec<String>,
294    /// Page views in all (more than `pages` when it's long).
295    pub views: u64,
296    pub country: String,
297    pub browser: String,
298    pub os: String,
299    pub device: String,
300    pub channel: String,
301    pub referrer: String,
302    pub campaign: String,
303    /// The visitor ran the script (`[traffic] script`).
304    pub verified: bool,
305    /// This visitor's visit number today (2 = came back).
306    pub number: u32,
307    pub events: Vec<String>,
308}
309
310/// Sessions added up.
311#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
312#[doc(hidden)]
313pub struct Sessions {
314    pub sessions: u64,
315    /// Sessions of one page view.
316    pub bounces: u64,
317    /// Seconds from each session's first page view to its last.
318    pub duration: u64,
319    /// Page views in sessions.
320    pub pages: u64,
321}
322
323impl Sessions {
324    #[doc(hidden)]
325    pub fn add(&mut self, other: &Sessions) {
326        self.sessions += other.sessions;
327        self.bounces += other.bounces;
328        self.duration += other.duration;
329        self.pages += other.pages;
330    }
331}
332
333/// A person's session while it's open.
334struct Session {
335    start: u64,
336    last: u64,
337    pages: u64,
338    /// The page key (`host/path`) last viewed.
339    exit: String,
340    /// Goals reached, by index into the configured goals.
341    goals: u32,
342    /// How the session arrived (for the database's rows).
343    channel: Option<&'static str>,
344    utm: [Option<String>; 3],
345    /// Script reports so far.
346    reports: u32,
347    /// For the visit feed: paths in order (at most [`VISIT_PAGES`]), the
348    /// visitor's audience, the referring site, events, the visit number.
349    paths: Vec<String>,
350    visitor: u64,
351    audience: Option<Audience>,
352    referrer: Option<String>,
353    events: Vec<String>,
354    number: u32,
355    verified: bool,
356}
357
358impl Session {
359    fn visit(&self) -> Visit {
360        let host = self.exit.split('/').next().unwrap_or("").to_string();
361        let audience = self.audience.as_ref();
362        Visit {
363            start: self.start,
364            end: self.last,
365            host,
366            pages: self.paths.clone(),
367            views: self.pages,
368            country: audience.and_then(|a| a.country).map_or_else(String::new, |c| String::from_utf8_lossy(&c).into_owned()),
369            browser: audience.map_or("", |a| a.device.browser).to_string(),
370            os: audience.map_or("", |a| a.device.os).to_string(),
371            device: audience.map_or("", |a| a.device.class).to_string(),
372            channel: self.channel.unwrap_or("").to_string(),
373            referrer: self.referrer.clone().unwrap_or_default(),
374            campaign: self.utm[2].clone().or_else(|| self.utm[0].clone()).unwrap_or_default(),
375            verified: self.verified,
376            number: self.number,
377            events: self.events.clone(),
378        }
379    }
380
381    fn totals(&self) -> Sessions {
382        Sessions { sessions: 1, bounces: (self.pages == 1) as u64, duration: self.last - self.start, pages: self.pages }
383    }
384}
385
386impl Day {
387    #[doc(hidden)]
388    pub fn merge(&mut self, other: &Day) {
389        for g in 0..GROUPS {
390            self.visitors[g] += other.visitors[g];
391        }
392        for (mine, theirs) in self.extra.iter_mut().zip(&other.extra) {
393            mine.merge(theirs);
394        }
395        self.visits.extend(other.visits.iter().cloned());
396        for (mine, theirs) in self.dims.iter_mut().zip(&other.dims) {
397            mine.merge(theirs);
398        }
399        self.people_pages.merge(&other.people_pages);
400        self.ai_pages.merge(&other.ai_pages);
401        self.ai_agents.merge(&other.ai_agents);
402        self.bots.merge(&other.bots);
403        self.referrers.merge(&other.referrers);
404        self.site_visitors.merge(&other.site_visitors);
405        self.site_ai_agents.merge(&other.site_ai_agents);
406        self.site_bots.merge(&other.site_bots);
407        self.site_referrers.merge(&other.site_referrers);
408        self.not_found.merge(&other.not_found);
409        for (mine, theirs) in self.behaviour.iter_mut().zip(&other.behaviour) {
410            mine.merge(theirs);
411        }
412        self.entry_pages.merge(&other.entry_pages);
413        self.exit_pages.merge(&other.exit_pages);
414        for (host, s) in &other.sessions {
415            self.sessions.entry(host.clone()).or_default().add(s);
416        }
417    }
418}
419
420/// A browser's requests while it's undecided.
421struct Pending {
422    last: u64,
423    requests: Vec<Deferred>,
424}
425
426struct Deferred {
427    /// When it was made (seconds).
428    at: u64,
429    hour: u64,
430    host: u8,
431    page: Option<String>,
432    referrer: Option<String>,
433    not_found: Option<String>,
434    arrival: Option<Arrival>,
435}
436
437/// A visitor's classification, and for browsers their audience.
438#[derive(Clone)]
439struct Cached {
440    class: Class,
441    audience: Option<Audience>,
442    /// For an app client: the version its User-Agent names.
443    app_version: Option<String>,
444}
445
446#[derive(Default)]
447struct Shard {
448    /// `(hour, host)` → counts per group.
449    hours: BTreeMap<(u64, u8), [Counts; GROUPS]>,
450    days: BTreeMap<u64, Day>,
451    /// Today's visitors and the group each was counted in.
452    seen: HashMap<u64, Group>,
453    pending: HashMap<u64, Pending>,
454    cache: HashMap<u64, Cached>,
455    /// People's open sessions by visitor.
456    open: HashMap<u64, Session>,
457    /// People's page views of the last [`LIVE_WINDOW`], oldest first.
458    recent: VecDeque<Recent>,
459    today: u64,
460    /// Today's people who ran the script (18.35).
461    verified: std::collections::HashSet<u64>,
462    /// Visits each person started today.
463    visit_numbers: HashMap<u64, u32>,
464    /// Events each app client sent today (`/_rws/e`), to cap them.
465    app_reports: HashMap<u64, u32>,
466}
467
468struct Recorder {
469    shards: Vec<Mutex<Shard>>,
470    hosts: RwLock<Vec<String>>,
471    /// The sites the configuration routes (normalized, sorted).
472    configured: RwLock<Vec<String>>,
473    /// A secret made at start and never saved; with the day it keys the
474    /// visitor hash, so one day's visitors can't be matched to the next's.
475    secret: RandomState,
476    retention_days: u64,
477    exclude: Vec<String>,
478    /// `[traffic] hosting_networks`.
479    hosting: bool,
480    /// Today's owner fingerprints (`hash(secret, day, ip, user-agent)`,
481    /// no host): `(day, set)`.
482    owners: Mutex<(u64, std::collections::HashSet<u64>)>,
483}
484
485static ENABLED: AtomicBool = AtomicBool::new(false);
486/// Bumped when host indexes change meaning (a restore, tests' resets).
487static HOSTS_GENERATION: AtomicU64 = AtomicU64::new(1);
488static CALLS: AtomicU64 = AtomicU64::new(0);
489/// Bumped when a client becomes the owner, so threads forget the group
490/// they had decided for it.
491static OWNER_GENERATION: AtomicU64 = AtomicU64::new(1);
492
493fn recorder() -> &'static Recorder {
494    static RECORDER: OnceLock<Recorder> = OnceLock::new();
495    RECORDER.get_or_init(|| Recorder {
496        shards: (0..SHARDS).map(|_| Mutex::new(Shard::default())).collect(),
497        hosts: RwLock::new(Vec::new()),
498        configured: RwLock::new(Vec::new()),
499        secret: RandomState::new(),
500        retention_days: super::config::retention_days(),
501        exclude: super::config::exclude(),
502        hosting: super::config::hosting_networks(),
503        owners: Mutex::new((0, std::collections::HashSet::new())),
504    })
505}
506
507/// Start counting (the binary does this when the admin API is on).
508pub fn enable() {
509    // The access log (no `log` module on wasm32) reports each request here.
510    #[cfg(not(target_arch = "wasm32"))]
511    crate::log::set_access_observer(super::observe);
512    let _ = recorder();
513    ENABLED.store(true, Ordering::Relaxed);
514}
515
516/// Whether requests are being counted.
517pub fn enabled() -> bool {
518    ENABLED.load(Ordering::Relaxed)
519}
520
521/// Seconds since the epoch, as the counts use.
522pub fn now() -> u64 {
523    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
524}
525
526/// A Host header as counted: lowercase, without the port.
527fn normalize_host(host: &str) -> String {
528    let host = host.trim();
529    // `[::1]:8080` keeps its brackets; `example.com:443` loses the port.
530    let host = match host.strip_prefix('[') {
531        Some(rest) => rest.split(']').next().unwrap_or(rest),
532        None => host.split(':').next().unwrap_or(host),
533    };
534    if host.is_empty() { "(none)".to_string() } else { host.to_ascii_lowercase() }
535}
536
537fn host_index(raw: &str) -> u8 {
538    // The last host this thread saw: most requests repeat it.
539    thread_local! {
540        static LAST: std::cell::RefCell<(u64, String, u8)> = const { std::cell::RefCell::new((0, String::new(), 0)) };
541    }
542    let generation = HOSTS_GENERATION.load(Ordering::Relaxed);
543    if let Ok(Some(i)) = LAST.try_with(|last| {
544        let last = last.borrow();
545        (last.0 == generation && !last.1.is_empty() && last.1 == raw).then_some(last.2)
546    }) {
547        return i;
548    }
549    let i = host_index_slow(raw);
550    let _ = LAST.try_with(|last| *last.borrow_mut() = (generation, raw.to_string(), i));
551    i
552}
553
554fn host_index_slow(host: &str) -> u8 {
555    let host = normalize_host(host);
556    let recorder = recorder();
557    if let Some(i) = recorder.hosts.read().unwrap_or_else(|e| e.into_inner()).iter().position(|h| *h == host) {
558        return i as u8;
559    }
560    let configured = recorder.configured.read().unwrap_or_else(|e| e.into_inner());
561    let mut hosts = recorder.hosts.write().unwrap_or_else(|e| e.into_inner());
562    host_slot(&mut hosts, &configured, host)
563}
564
565/// The slot of `host` (normalized), added when there's room: a configured
566/// site always gets one; another Host header while fewer than
567/// [`MAX_HOSTS`] such are counted (with no configured sites, the first
568/// [`MAX_HOSTS`] hosts seen); the rest share `other`.
569fn host_slot(hosts: &mut Vec<String>, configured: &[String], host: String) -> u8 {
570    if let Some(i) = hosts.iter().position(|h| *h == host) {
571        return i as u8;
572    }
573    let room = host != "other"
574        && hosts.len() < MAX_SLOTS
575        && if configured.is_empty() {
576            hosts.len() < MAX_HOSTS
577        } else {
578            configured.binary_search(&host).is_ok() || hosts.iter().filter(|h| *h != "other" && configured.binary_search(h).is_err()).count() < MAX_HOSTS
579        };
580    if room {
581        hosts.push(host);
582        return (hosts.len() - 1) as u8;
583    }
584    if let Some(i) = hosts.iter().position(|h| h == "other") {
585        return i as u8;
586    }
587    hosts.push("other".to_string());
588    (hosts.len() - 1) as u8
589}
590
591/// The most configured sites counted separately.
592const MAX_CONFIGURED: usize = MAX_SLOTS - MAX_HOSTS - 1;
593
594/// The sites the configuration routes (`[[route]] match.host`): each gets
595/// its own counts, ahead of whatever else arrives in a Host header, and is
596/// listed first on the Traffic page. Set at start and on every reload.
597pub fn set_configured_hosts<I: IntoIterator<Item = String>>(hosts: I) {
598    let mut list: Vec<String> = hosts.into_iter().map(|h| normalize_host(&h)).filter(|h| h != "(none)" && h != "other" && !h.contains('*')).collect();
599    list.sort();
600    list.dedup();
601    list.truncate(MAX_CONFIGURED);
602    let mut configured = recorder().configured.write().unwrap_or_else(|e| e.into_inner());
603    if *configured != list {
604        *configured = list;
605        // Hosts that went to `other` may have a slot now.
606        HOSTS_GENERATION.fetch_add(1, Ordering::Relaxed);
607    }
608}
609
610/// The configured sites ([`set_configured_hosts`]), sorted.
611#[doc(hidden)]
612pub fn configured_hosts() -> Vec<String> {
613    recorder().configured.read().unwrap_or_else(|e| e.into_inner()).clone()
614}
615
616/// The name of host slot `i`.
617fn host_name(i: u8) -> String {
618    recorder().hosts.read().unwrap_or_else(|e| e.into_inner()).get(i as usize).cloned().unwrap_or_else(|| "other".to_string())
619}
620
621#[doc(hidden)]
622pub fn host_names() -> Vec<String> {
623    recorder().hosts.read().unwrap_or_else(|e| e.into_inner()).clone()
624}
625
626/// `hash(secret, day, host, ip, user-agent)` — no lock.
627fn visitor(day: u64, host: u8, ip: IpAddr, user_agent: Option<&str>) -> u64 {
628    let mut hasher = recorder().secret.build_hasher();
629    day.hash(&mut hasher);
630    host.hash(&mut hasher);
631    ip.hash(&mut hasher);
632    user_agent.unwrap_or("").hash(&mut hasher);
633    hasher.finish()
634}
635
636fn is_page(hit: &Hit<'_>) -> bool {
637    if hit.method != "GET" || !matches!(hit.status, 200 | 304) {
638        return false;
639    }
640    match hit.content_type {
641        Some(ct) => ct.trim_start().as_bytes().get(..9).is_some_and(|p| p.eq_ignore_ascii_case(b"text/html")),
642        None => {
643            let last = hit.path.rsplit('/').next().unwrap_or("");
644            last.is_empty() || !last.contains('.') || last.ends_with(".html")
645        }
646    }
647}
648
649fn is_asset(path: &str) -> bool {
650    let path = path.split('?').next().unwrap_or(path).as_bytes();
651    [&b".css"[..], b".js", b".mjs", b".woff2", b".woff"].iter().any(|ext| path.len() >= ext.len() && path[path.len() - ext.len()..].eq_ignore_ascii_case(ext))
652}
653
654fn page_key(host: &str, path: &str) -> String {
655    format!("{}{}", normalize_host(host), path.split('?').next().unwrap_or(path))
656}
657
658fn referrer_host(referer: Option<&str>, host: &str) -> Option<String> {
659    let rest = referer?.split_once("://")?.1;
660    let other = rest.split(['/', '?', '#']).next()?.split(':').next()?.to_ascii_lowercase();
661    (!other.is_empty() && other != normalize_host(host)).then_some(other)
662}
663
664/// The channel a referring site belongs to.
665#[doc(hidden)]
666pub fn channel_of(referrer_host: &str) -> &'static str {
667    let h = referrer_host.strip_prefix("www.").unwrap_or(referrer_host);
668    let is = |d: &str| h == d || h.ends_with(&format!(".{d}"));
669    const AI: &[&str] = &["chatgpt.com", "chat.openai.com", "perplexity.ai", "claude.ai", "gemini.google.com", "copilot.microsoft.com", "chat.deepseek.com", "chat.mistral.ai", "you.com", "phind.com", "kagi.com"];
670    const SEARCH: &[&str] = &["bing.com", "duckduckgo.com", "search.yahoo.com", "yandex.ru", "yandex.com", "baidu.com", "ecosia.org", "search.brave.com", "startpage.com", "qwant.com", "naver.com", "seznam.cz"];
671    const SOCIAL: &[&str] = &[
672        "facebook.com", "m.facebook.com", "l.facebook.com", "lm.facebook.com", "t.co", "twitter.com", "x.com", "linkedin.com", "lnkd.in", "reddit.com", "instagram.com",
673        "youtube.com", "tiktok.com", "pinterest.com", "news.ycombinator.com", "mastodon.social", "bsky.app", "threads.net", "vk.com", "telegram.org", "t.me", "discord.com",
674        "whatsapp.com", "lobste.rs",
675    ];
676    // App stores, before search: play.google.com isn't Google search.
677    const STORE: &[&str] = &[
678        "apps.apple.com", "itunes.apple.com", "play.google.com", "chromewebstore.google.com", "addons.mozilla.org", "microsoftedge.microsoft.com",
679        "apps.microsoft.com", "snapcraft.io", "flathub.org", "f-droid.org", "appgallery.huawei.com",
680    ];
681    if AI.iter().any(|d| is(d)) {
682        "ai"
683    } else if STORE.iter().any(|d| is(d)) || (h == "chrome.google.com") {
684        "store"
685    } else if SEARCH.iter().any(|d| is(d)) || h.starts_with("google.") || h.contains(".google.") {
686        "search"
687    } else if SOCIAL.iter().any(|d| is(d)) {
688        "social"
689    } else {
690        "referral"
691    }
692}
693
694/// `%XX` and `+` decoded, at most 100 characters; `None` when empty.
695fn query_value(raw: &str) -> Option<String> {
696    let bytes = raw.as_bytes();
697    let mut out = Vec::with_capacity(bytes.len().min(300));
698    let mut i = 0;
699    while i < bytes.len() && out.len() < 300 {
700        match bytes[i] {
701            b'+' => out.push(b' '),
702            b'%' if i + 2 < bytes.len() => {
703                match std::str::from_utf8(&bytes[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) {
704                    Some(b) => {
705                        out.push(b);
706                        i += 2;
707                    }
708                    None => out.push(b'%'),
709                }
710            }
711            b => out.push(b),
712        }
713        i += 1;
714    }
715    let value: String = String::from_utf8_lossy(&out).trim().chars().filter(|c| !c.is_control()).take(100).collect();
716    (!value.is_empty()).then_some(value)
717}
718
719/// `utm_source`, `utm_medium` and `utm_campaign` from a request target.
720#[doc(hidden)]
721pub fn utm(target: &str) -> [Option<String>; 3] {
722    let mut out: [Option<String>; 3] = Default::default();
723    let Some(query) = target.split_once('?').map(|(_, q)| q.split('#').next().unwrap_or(q)) else { return out };
724    for pair in query.split('&') {
725        let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
726        let slot = match name {
727            "utm_source" => 0,
728            "utm_medium" => 1,
729            "utm_campaign" => 2,
730            _ => continue,
731        };
732        if out[slot].is_none() {
733            out[slot] = query_value(value);
734        }
735    }
736    out
737}
738
739/// How a page view arrived: `None` for navigation within the site (a
740/// same-site `Referer`), else the channel and any UTM values.
741fn arrival(hit: &Hit<'_>) -> Option<Arrival> {
742    let utm = utm(hit.path);
743    let channel = if utm[0].is_some() || utm[1].is_some() || utm[2].is_some() {
744        "campaign"
745    } else {
746        match hit.referer {
747            None => "direct",
748            Some(_) => channel_of(&referrer_host(hit.referer, hit.host)?),
749        }
750    };
751    Some(Arrival { channel, utm })
752}
753
754/// Requests of visitors already decided, counted by the thread that served
755/// them (merged by readers): most requests are assets and repeats, and they
756/// then cost no shared lock. Pages, 404s and undecided browsers take the
757/// shared path, which also feeds the lists.
758#[derive(Default)]
759struct Local {
760    /// Visitor → (day, counted group slot), as decided by a shard.
761    /// Visitor → (day, owner generation, counted group slot).
762    decided: HashMap<u64, (u64, u64, usize)>,
763    counts: BTreeMap<(u64, u8), [Counts; GROUPS]>,
764}
765
766/// How many decided visitors a thread remembers.
767const LOCAL_DECIDED: usize = 1024;
768
769fn locals() -> &'static Mutex<Vec<std::sync::Weak<Mutex<Local>>>> {
770    static LOCALS: OnceLock<Mutex<Vec<std::sync::Weak<Mutex<Local>>>>> = OnceLock::new();
771    LOCALS.get_or_init(Mutex::default)
772}
773
774thread_local! {
775    static LOCAL: std::sync::Arc<Mutex<Local>> = {
776        let local = std::sync::Arc::new(Mutex::new(Local::default()));
777        let mut all = locals().lock().unwrap_or_else(|e| e.into_inner());
778        all.retain(|w| w.strong_count() > 0);
779        all.push(std::sync::Arc::downgrade(&local));
780        local
781    };
782}
783
784/// Move every thread's buffered counts into shard 0.
785fn drain_locals() {
786    let all: Vec<_> = locals().lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(|w| w.upgrade()).collect();
787    let mut target = recorder().shards[0].lock().unwrap_or_else(|e| e.into_inner());
788    for local in all {
789        let counts = std::mem::take(&mut local.lock().unwrap_or_else(|e| e.into_inner()).counts);
790        for (key, c) in counts {
791            let entry = target.hours.entry(key).or_default();
792            for g in 0..GROUPS {
793                entry[g].requests += c[g].requests;
794                entry[g].pages += c[g].pages;
795            }
796        }
797    }
798}
799
800/// Count one request.
801#[doc(hidden)]
802pub fn record(hit: &Hit<'_>) {
803    if !enabled() {
804        return;
805    }
806    let recorder = recorder();
807    let path = hit.path.split('?').next().unwrap_or(hit.path);
808    // rws's own endpoints (the script's reports, app events, the owner
809    // link) are counted by what they report, not as requests. The script
810    // itself is an asset like any: loading it shows a browser.
811    if recorder.exclude.iter().any(|e| path == e)
812        || (path.starts_with("/_rws/") && matches!(path, super::script::BEACON_PATH | super::script::APP_EVENTS_PATH | super::owner::PATH))
813    {
814        return;
815    }
816    let day = hit.now / 86_400;
817    // A successful admin API call: this client is the owner from now on.
818    // (JSON first: it rules out almost every request without a search.)
819    let json = hit.content_type.is_some_and(|ct| ct.as_bytes().get(..16).is_some_and(|p| p.eq_ignore_ascii_case(b"application/json")));
820    if json && path.contains("/api/") && super::owner::is_admin_call(hit.headers, hit.status) {
821        mark_owner(hit.ip, hit.user_agent, hit.now);
822    }
823    let hour = hit.now / 3_600;
824    let host = host_index(hit.host);
825    let visitor = visitor(day, host, hit.ip, hit.user_agent);
826    let generation = OWNER_GENERATION.load(Ordering::Relaxed);
827    let download = is_download(hit, path);
828    let request_goal = request_goals_configured() && (200..400).contains(&hit.status);
829    // A decided visitor's non-page request: counted by this thread (no
830    // scanner check — the visitor keeps the group it was decided in).
831    if hit.status != 404 && !download && !request_goal && !is_page(hit) {
832        let counted = LOCAL.try_with(|local| {
833            let mut local = local.lock().unwrap_or_else(|e| e.into_inner());
834            match local.decided.get(&visitor) {
835                Some((d, gen, g)) if *d == day && *gen == generation => {
836                    let g = *g;
837                    local.counts.entry((hour, host)).or_default()[g].requests += 1;
838                    true
839                }
840                _ => false,
841            }
842        });
843        if counted == Ok(true) {
844            return;
845        }
846    }
847    let decided = record_shared(hit, day, hour, host, visitor, path, download);
848    if let Some(g) = decided {
849        let _ = LOCAL.try_with(|local| {
850            let mut local = local.lock().unwrap_or_else(|e| e.into_inner());
851            if local.decided.len() >= LOCAL_DECIDED {
852                local.decided.clear();
853            }
854            local.decided.insert(visitor, (day, generation, g));
855        });
856    }
857    if CALLS.fetch_add(1, Ordering::Relaxed) % 1024 == 0 {
858        settle(hit.now);
859    }
860}
861
862/// The shared path; returns the visitor's group slot once it's decided.
863fn record_shared(hit: &Hit<'_>, day: u64, hour: u64, host: u8, visitor: u64, path: &str, download: bool) -> Option<usize> {
864    let recorder = recorder();
865    let mut shard = recorder.shards[(visitor % SHARDS as u64) as usize].lock().unwrap_or_else(|e| e.into_inner());
866    shard.roll(day, recorder.retention_days);
867
868    let cached = match shard.cache.get(&visitor) {
869        Some(cached) => cached.clone(),
870        None => {
871            let class = classify(hit.ip, hit.user_agent, "/");
872            // The owner, then the site's apps, before the network checks:
873            // an app on a phone behind a cloud VPN is still the app.
874            let header = |name: &str| hit.headers.iter().find(|h| h.name.eq_ignore_ascii_case(name)).map(|h| h.value.as_ref());
875            let owner = class.kind != Kind::Local
876                && (super::owner::in_networks(hit.ip) || super::owner::has_cookie(hit.headers) || is_owner(day, hit.ip, hit.user_agent));
877            let app = if owner || class.verified || class.kind == Kind::Local { None } else { super::apps::detect(hit.user_agent, header("origin")) };
878            let app_version = app.as_ref().and_then(|a| a.version.clone());
879            let class = match (owner, app) {
880                (true, _) => owner_class(),
881                (false, Some(app)) => Class { kind: Kind::App, name: app.name, operator: app.platform, verified: false },
882                (false, None) => class,
883            };
884            // A browser from a hosting network is a program (looked up once
885            // per visitor: the class is cached).
886            let class = match (class.kind, recorder.hosting) {
887                (Kind::Browser, true) => match super::hosting::provider(hit.ip) {
888                    Some(provider) => Class { kind: Kind::Hosting, name: provider, operator: "", verified: false },
889                    None => class,
890                },
891                _ => class,
892            };
893            // Country and device only for browsers: they're shown for people.
894            let audience = (class.kind == Kind::Browser).then(|| Audience {
895                country: super::geo::country(hit.ip),
896                device: {
897                    let hint = |name: &str| hit.headers.iter().find(|h| h.name.eq_ignore_ascii_case(name)).map(|h| h.value.as_ref());
898                    super::device::parse(hit.user_agent.unwrap_or(""), hint("sec-ch-ua-platform"), hint("sec-ch-ua-mobile"))
899                },
900            });
901            let cached = Cached { class, audience, app_version };
902            if shard.cache.len() >= MAX_CACHE {
903                shard.cache.clear();
904            }
905            shard.cache.insert(visitor, cached.clone());
906            cached
907        }
908    };
909    let class = cached.class;
910    let scanner = super::classify::scanner_path(hit.path) && matches!(class.kind, Kind::Browser | Kind::Hosting | Kind::Tool | Kind::NoUserAgent);
911    let class = if scanner { Class { kind: Kind::Scanner, name: "", operator: "", verified: false } } else { class };
912    let page = is_page(hit).then(|| page_key(hit.host, path));
913    let not_found = (hit.status == 404).then(|| page_key(hit.host, path));
914    let referrer = referrer_host(hit.referer, hit.host);
915    // Where a person's page view came from (only browsers become people).
916    let arrival = if page.is_some() && class.kind == Kind::Browser { arrival(hit) } else { None };
917
918    let decided = match class.group() {
919        Group::Internal => None,
920        Group::Person => {
921            match shard.seen.get(&visitor).copied() {
922                Some(Group::Person) => {
923                    shard.count_person(visitor, hit.now, host, page, referrer, not_found, arrival);
924                    Some(PEOPLE)
925                }
926                Some(_) => {
927                    shard.count(BOTS, hour, host, &browser_without_assets(), page, not_found, visitor);
928                    Some(BOTS)
929                }
930                None if is_asset(path) => {
931                    shard.seen.insert(visitor, Group::Person);
932                    shard.new_visitor(day, host, PEOPLE);
933                    if let Some(audience) = &cached.audience {
934                        shard.count_audience(day, &normalize_host(hit.host), audience);
935                    }
936                    if let Some(pending) = shard.pending.remove(&visitor) {
937                        for d in pending.requests {
938                            shard.count_person(visitor, d.at, d.host, d.page, d.referrer, d.not_found, d.arrival);
939                        }
940                    }
941                    shard.count_person(visitor, hit.now, host, page, referrer, not_found, arrival);
942                    Some(PEOPLE)
943                }
944                None => {
945                    if shard.pending.len() >= MAX_PENDING && !shard.pending.contains_key(&visitor) {
946                        // Too many undecided at once: count this one as a bot.
947                        shard.seen.insert(visitor, Group::Bot);
948                        shard.new_visitor(day, host, BOTS);
949                        shard.count(BOTS, hour, host, &browser_without_assets(), page, not_found, visitor);
950                        Some(BOTS)
951                    } else {
952                        let pending = shard.pending.entry(visitor).or_insert(Pending { last: hit.now, requests: Vec::new() });
953                        pending.last = hit.now;
954                        pending.requests.push(Deferred { at: hit.now, hour, host, page, referrer, not_found, arrival });
955                        if pending.requests.len() < MAX_PENDING_REQUESTS {
956                            None
957                        } else {
958                            // This many requests and no stylesheet, script or
959                            // font: automation, not someone reading pages.
960                            let pending = shard.pending.remove(&visitor).expect("just added");
961                            shard.seen.insert(visitor, Group::Bot);
962                            shard.new_visitor(day, host, BOTS);
963                            shard.count_page_only(day, host);
964                            for d in pending.requests {
965                                shard.count(BOTS, d.hour, d.host, &browser_without_assets(), d.page, d.not_found, visitor);
966                            }
967                            Some(BOTS)
968                        }
969                    }
970                }
971            }
972        }
973        group => {
974            let g = slot(group).expect("counted group");
975            if shard.seen.insert(visitor, group).is_none() {
976                shard.new_visitor(day, host, g);
977                let site = host_name(host);
978                if g == APPS {
979                    shard.count_app_user(day, &site, class.name, class.operator, cached.app_version.as_deref());
980                } else if class.kind == Kind::Hosting {
981                    shard.day(day).extra[SITE_TIERS].add_capped(&format!("{site}\thosting"), 1, DIM_TOP);
982                }
983            }
984            if scanner {
985                shard.count_probe(day, &host_name(host), path, hit.ip);
986            }
987            shard.count(g, hour, host, &class, page, not_found, visitor);
988            // A scanner request isn't the visitor's usual class: not cached.
989            (!scanner).then_some(g)
990        }
991    };
992    if download {
993        let label = decided.map_or("undecided", group_label);
994        shard.day(day).extra[DOWNLOADS].add_capped(&format!("{}\t{label}", page_key(hit.host, path)), 1, DIM_TOP);
995    }
996    if decided == Some(PEOPLE) && request_goals_configured() {
997        let reached = request_goals(path);
998        if let (true, Some(session)) = (reached != 0, shard.open.get_mut(&visitor)) {
999            session.goals |= reached;
1000        }
1001    }
1002    decided
1003}
1004
1005/// The name of a counted group slot.
1006fn group_label(g: usize) -> &'static str {
1007    ["people", "ai", "bots", "apps", "owner"].get(g).copied().unwrap_or("other")
1008}
1009
1010fn owner_class() -> Class {
1011    Class { kind: Kind::Owner, name: "", operator: "", verified: false }
1012}
1013
1014/// `hash(secret, day, ip, user-agent)`: a client on every site, for the
1015/// owner's fingerprint.
1016fn fingerprint(day: u64, ip: IpAddr, user_agent: Option<&str>) -> u64 {
1017    let mut hasher = recorder().secret.build_hasher();
1018    "owner".hash(&mut hasher);
1019    day.hash(&mut hasher);
1020    ip.hash(&mut hasher);
1021    user_agent.unwrap_or("").hash(&mut hasher);
1022    hasher.finish()
1023}
1024
1025fn is_owner(day: u64, ip: IpAddr, user_agent: Option<&str>) -> bool {
1026    let owners = recorder().owners.lock().unwrap_or_else(|e| e.into_inner());
1027    owners.0 == day && owners.1.contains(&fingerprint(day, ip, user_agent))
1028}
1029
1030/// Make the client at `ip` with `user_agent` the owner for the rest of
1031/// the day, on every site: its visitors on each site are re-decided as the
1032/// owner (an open visit is dropped, not counted).
1033#[doc(hidden)]
1034pub fn mark_owner(ip: IpAddr, user_agent: Option<&str>, now: u64) {
1035    let day = now / 86_400;
1036    let fp = fingerprint(day, ip, user_agent);
1037    {
1038        let mut owners = recorder().owners.lock().unwrap_or_else(|e| e.into_inner());
1039        if owners.0 != day {
1040            *owners = (day, std::collections::HashSet::new());
1041        }
1042        // Bounded: a day's owner clients are few; past 1024 something is off.
1043        if owners.1.len() >= 1024 || !owners.1.insert(fp) {
1044            return;
1045        }
1046    }
1047    let slots = recorder().hosts.read().unwrap_or_else(|e| e.into_inner()).len();
1048    for host in 0..slots.max(1) {
1049        let v = visitor(day, host as u8, ip, user_agent);
1050        let mut shard = recorder().shards[(v % SHARDS as u64) as usize].lock().unwrap_or_else(|e| e.into_inner());
1051        if shard.today != day {
1052            continue;
1053        }
1054        shard.pending.remove(&v);
1055        shard.open.remove(&v);
1056        shard.seen.insert(v, Group::Owner);
1057        if shard.cache.len() >= MAX_CACHE {
1058            shard.cache.clear();
1059        }
1060        shard.cache.insert(v, Cached { class: owner_class(), audience: None, app_version: None });
1061    }
1062    OWNER_GENERATION.fetch_add(1, Ordering::Relaxed);
1063}
1064
1065/// Extensions of files counted as downloads.
1066const DOWNLOAD_EXTENSIONS: &[&str] = &[
1067    ".dmg", ".pkg", ".zip", ".tar.gz", ".tgz", ".tar.xz", ".exe", ".msi", ".msix", ".deb", ".rpm", ".appimage", ".apk", ".aab", ".ipa", ".vsix", ".xpi",
1068    ".crx", ".flatpak", ".snap", ".7z",
1069];
1070
1071/// A downloaded file: an installer, package or archive, or an install
1072/// script (`install.sh`, `install.ps1`), fetched in full.
1073fn is_download(hit: &Hit<'_>, path: &str) -> bool {
1074    if hit.status != 200 || hit.method != "GET" {
1075        return false;
1076    }
1077    let last = path.rsplit('/').next().unwrap_or("").as_bytes();
1078    // Pages, scripts, styles and fonts end in a byte no download ends in.
1079    if !matches!(last.last().map(u8::to_ascii_lowercase), Some(b'g' | b'e' | b'p' | b'z' | b'b' | b'i' | b'x' | b'k' | b'a' | b'm' | b'h' | b'1')) {
1080        return false;
1081    }
1082    let ends = |ext: &str| last.len() >= ext.len() && last[last.len() - ext.len()..].eq_ignore_ascii_case(ext.as_bytes());
1083    DOWNLOAD_EXTENSIONS.iter().any(|ext| ends(ext)) || last.eq_ignore_ascii_case(b"install.sh") || last.eq_ignore_ascii_case(b"install.ps1")
1084}
1085
1086fn browser_without_assets() -> Class {
1087    Class { kind: Kind::Browser, name: "browser, no assets", operator: "", verified: false }
1088}
1089
1090impl Shard {
1091    fn day(&mut self, day: u64) -> &mut Day {
1092        self.days.entry(day).or_default()
1093    }
1094
1095    /// A visitor first seen today, in group `g`, on host slot `host`.
1096    fn new_visitor(&mut self, day: u64, host: u8, g: usize) {
1097        let name = host_name(host);
1098        let day = self.day(day);
1099        day.visitors[g] += 1;
1100        day.site_visitors.add_capped(&format!("{name}\t{g}"), 1, DIM_TOP);
1101    }
1102
1103    /// A new day: forget today's visitors and cache; drop what's past retention.
1104    fn roll(&mut self, day: u64, retention_days: u64) {
1105        if self.today == day {
1106            return;
1107        }
1108        self.today = day;
1109        // Visitors are new each day, so no session continues past midnight.
1110        self.close_sessions(|_| true);
1111        self.seen.clear();
1112        self.cache.clear();
1113        self.verified.clear();
1114        self.visit_numbers.clear();
1115        self.app_reports.clear();
1116        let oldest_day = day.saturating_sub(retention_days.saturating_sub(1));
1117        self.days.retain(|d, _| *d >= oldest_day);
1118        self.hours.retain(|(h, _), _| *h / 24 >= oldest_day);
1119    }
1120
1121    /// A person's page view as a database row.
1122    #[cfg(feature = "model-postgres")]
1123    fn store_view(&self, visitor: u64, at: u64, page: &str, referrer: Option<&str>) {
1124        let (host, path) = page.find('/').map_or((page, "/"), |i| (&page[..i], &page[i..]));
1125        let session = self.open.get(&visitor);
1126        let audience = self.cache.get(&visitor).and_then(|c| c.audience.as_ref());
1127        super::store::enqueue(super::store::Row::PageView(super::store::PageView {
1128            at,
1129            host: host.to_string(),
1130            path: path.to_string(),
1131            visitor,
1132            session_start: session.map_or(at, |s| s.start),
1133            referrer_host: referrer.map(str::to_string),
1134            channel: session.and_then(|s| s.channel),
1135            utm: session.map(|s| s.utm.clone()).unwrap_or_default(),
1136            country: audience.and_then(|a| a.country).map(|c| String::from_utf8_lossy(&c).into_owned()),
1137            browser: audience.map(|a| a.device.browser),
1138            os: audience.map(|a| a.device.os),
1139            device: audience.map(|a| a.device.class),
1140        }));
1141    }
1142
1143    /// A person ran the script today: verified (counted once a day).
1144    fn mark_verified(&mut self, visitor: u64, day: u64, host: &str) {
1145        if self.verified.insert(visitor) {
1146            self.day(day).extra[SITE_TIERS].add_capped(&format!("{host}\tverified"), 1, DIM_TOP);
1147        }
1148    }
1149
1150    /// A new app user: by app and platform, and by version when known.
1151    fn count_app_user(&mut self, day: u64, host: &str, app: &str, platform: &str, version: Option<&str>) {
1152        let day = self.day(day);
1153        day.extra[SITE_APPS].add_capped(&format!("{host}\t{app}\t{platform}"), 1, DIM_TOP);
1154        day.extra[APP_VERSIONS].add_capped(&format!("{host}\t{app}\t{}", version.unwrap_or("(unknown)")), 1, DIM_TOP);
1155    }
1156
1157    /// A scanner's request: the path, and where it came from (country and
1158    /// network; the address too with `[traffic] probe_addresses`).
1159    fn count_probe(&mut self, day: u64, host: &str, path: &str, ip: IpAddr) {
1160        let country = super::geo::country(ip).map_or("(unknown)".to_string(), |c| String::from_utf8_lossy(&c).into_owned());
1161        let network = super::hosting::provider(ip).unwrap_or("-");
1162        let source = if super::config::probe_addresses() { format!("{host}\t{country}\t{network}\t{}", ip.to_canonical()) } else { format!("{host}\t{country}\t{network}") };
1163        let day = self.day(day);
1164        day.extra[SITE_PROBES].add_capped(&format!("{host}\t{}", path.chars().take(200).collect::<String>()), 1, DIM_TOP);
1165        day.extra[PROBE_SOURCES].add_capped(&source, 1, DIM_TOP);
1166    }
1167
1168    /// A browser decided to be no person (it loaded no asset).
1169    fn count_page_only(&mut self, day: u64, host: u8) {
1170        let site = host_name(host);
1171        self.day(day).extra[SITE_TIERS].add_capped(&format!("{site}\tpage-only"), 1, DIM_TOP);
1172    }
1173
1174    /// A new person's country, browser, OS and device class.
1175    fn count_audience(&mut self, day: u64, host: &str, audience: &Audience) {
1176        let day = self.day(day);
1177        let country = audience.country.map(|c| String::from_utf8_lossy(&c).into_owned());
1178        let values = [country.as_deref().unwrap_or("(unknown)"), audience.device.browser, audience.device.os, audience.device.class];
1179        for (i, value) in values.iter().enumerate() {
1180            day.dims[COUNTRIES + i].add_capped(&format!("{host}\t{value}"), 1, DIM_TOP);
1181        }
1182    }
1183
1184    /// Close the open sessions `which` picks, adding them to the day they
1185    /// started.
1186    fn close_sessions(&mut self, which: impl Fn(&Session) -> bool) {
1187        let done: Vec<u64> = self.open.iter().filter(|(_, s)| which(s)).map(|(v, _)| *v).collect();
1188        for visitor in done {
1189            if let Some(session) = self.open.remove(&visitor) {
1190                self.close(session);
1191            }
1192        }
1193    }
1194
1195    fn close(&mut self, mut session: Session) {
1196        session.verified |= self.verified.contains(&session.visitor);
1197        let day = self.day(session.start / 86_400);
1198        add_session(day, &session);
1199        if day.visits.len() >= MAX_VISITS {
1200            day.visits.remove(0);
1201        }
1202        day.visits.push(session.visit());
1203    }
1204
1205    /// A person's page view at `at`: continues their session, or ends it and
1206    /// starts the next. True when it started one.
1207    fn session_page(&mut self, visitor: u64, at: u64, page: &str) -> bool {
1208        if let Some(session) = self.open.get_mut(&visitor) {
1209            if at.saturating_sub(session.last) < SESSION_GAP {
1210                session.last = session.last.max(at);
1211                session.pages += 1;
1212                session.exit = page.to_string();
1213                session.goals |= page_goals(page);
1214                if session.paths.len() < VISIT_PAGES {
1215                    session.paths.push(path_of(page).to_string());
1216                }
1217                return false;
1218            }
1219            let ended = self.open.remove(&visitor).expect("just found");
1220            self.close(ended);
1221        }
1222        if self.open.len() >= MAX_OPEN_SESSIONS {
1223            if let Some(quietest) = self.open.iter().min_by_key(|(_, s)| s.last).map(|(v, _)| *v) {
1224                let ended = self.open.remove(&quietest).expect("just found");
1225                self.close(ended);
1226            }
1227        }
1228        self.day(at / 86_400).entry_pages.add(page, 1);
1229        let audience = self.cache.get(&visitor).and_then(|c| c.audience.clone());
1230        let number = {
1231            let n = self.visit_numbers.entry(visitor).or_insert(0);
1232            *n += 1;
1233            *n
1234        };
1235        self.open.insert(
1236            visitor,
1237            Session {
1238                start: at,
1239                last: at,
1240                pages: 1,
1241                exit: page.to_string(),
1242                goals: 0,
1243                reports: 0,
1244                channel: None,
1245                utm: Default::default(),
1246                paths: vec![path_of(page).to_string()],
1247                visitor,
1248                audience,
1249                referrer: None,
1250                events: Vec::new(),
1251                number,
1252                verified: false,
1253            },
1254        );
1255        if let Some(session) = self.open.get_mut(&visitor) {
1256            session.goals |= page_goals(page);
1257        }
1258        true
1259    }
1260
1261    #[allow(clippy::too_many_arguments)]
1262    fn count_person(&mut self, visitor: u64, at: u64, host: u8, page: Option<String>, referrer: Option<String>, not_found: Option<String>, arrival: Option<Arrival>) {
1263        let hour = at / 3_600;
1264        // Sources count once per session, from its first page view (as
1265        // Google Analytics attributes a session).
1266        let started = page.as_ref().is_some_and(|page| self.session_page(visitor, at, page));
1267        if let Some(page) = &page {
1268            let country = self.cache.get(&visitor).and_then(|c| c.audience.as_ref()).and_then(|a| a.country);
1269            while self.recent.front().is_some_and(|r| r.at + LIVE_WINDOW < at) || self.recent.len() >= MAX_RECENT {
1270                self.recent.pop_front();
1271            }
1272            self.recent.push_back(Recent { at, visitor, page: page.clone(), country });
1273        }
1274        let arrival = arrival.filter(|_| started);
1275        if let (Some(arrival), Some(session)) = (&arrival, self.open.get_mut(&visitor)) {
1276            session.channel = Some(arrival.channel);
1277            session.utm = arrival.utm.clone();
1278            session.referrer = referrer.clone();
1279        }
1280        #[cfg(feature = "model-postgres")]
1281        if let (true, Some(page)) = (super::store::enabled(), &page) {
1282            self.store_view(visitor, at, page, referrer.as_deref());
1283        }
1284        let counts = &mut self.hours.entry((hour, host)).or_default()[PEOPLE];
1285        counts.requests += 1;
1286        counts.pages += page.is_some() as u64;
1287        let day = self.day(hour / 24);
1288        if let (Some(arrival), Some(page)) = (arrival, &page) {
1289            // The page key starts with the host.
1290            let host = page.split('/').next().unwrap_or("");
1291            day.dims[CHANNELS].add_capped(&format!("{host}\t{}", arrival.channel), 1, DIM_TOP);
1292            day.extra[SITE_ENTRIES].add_capped(&format!("{page}\t{}", arrival.channel), 1, DIM_TOP);
1293            for (i, value) in arrival.utm.iter().enumerate() {
1294                if let Some(value) = value {
1295                    day.dims[UTM + i].add_capped(&format!("{host}\t{value}"), 1, DIM_TOP);
1296                }
1297            }
1298        }
1299        if let Some(page) = page {
1300            day.people_pages.add(&page, 1);
1301            if let Some(referrer) = referrer {
1302                let host = page.split('/').next().unwrap_or("");
1303                day.site_referrers.add_capped(&format!("{host}\t{referrer}"), 1, DIM_TOP);
1304            }
1305        }
1306        if let Some(path) = not_found {
1307            day.not_found.add(&path, 1);
1308        }
1309    }
1310
1311    #[allow(clippy::too_many_arguments)]
1312    fn count(&mut self, g: usize, hour: u64, host: u8, class: &Class, page: Option<String>, not_found: Option<String>, _visitor: u64) {
1313        let counts = &mut self.hours.entry((hour, host)).or_default()[g];
1314        counts.requests += 1;
1315        counts.pages += page.is_some() as u64;
1316        let name = host_name(host);
1317        let day = self.day(hour / 24);
1318        if (g == AI || g == BOTS) && !class.name.is_empty() && !matches!(class.kind, Kind::Hosting | Kind::Browser) {
1319            // What named crawlers fetch: pages, and the paths that 404 for them.
1320            if page.is_some() {
1321                day.extra[SITE_CRAWL].add_capped(&format!("{name}\t{}\tpages", class.name), 1, DIM_TOP);
1322            }
1323            if let Some(path) = &not_found {
1324                day.extra[SITE_CRAWL].add_capped(&format!("{name}\t{}\t404", class.name), 1, DIM_TOP);
1325                day.extra[CRAWL_404].add_capped(&format!("{path}\t{}", class.name), 1, DIM_TOP);
1326            }
1327        }
1328        if g == AI {
1329            day.site_ai_agents.add_capped(&format!("{name}\t{}\t{}\t{}\t{}", or_unknown(class.name), class.operator, class.kind.label(), class.verified), 1, DIM_TOP);
1330            if let Some(page) = page {
1331                day.ai_pages.add(&page, 1);
1332            }
1333        } else if g == OWNER {
1334            if let Some(page) = page {
1335                day.extra[OWNER_PAGES].add(&page, 1);
1336            }
1337            // The owner's 404s are still the site's.
1338        } else if g == BOTS {
1339            let kind = if class.kind == Kind::Browser { "browser-no-assets" } else { class.kind.label() };
1340            day.site_bots.add_capped(&format!("{name}\t{kind}\t{}", class.name), 1, DIM_TOP);
1341        }
1342        if let Some(path) = not_found {
1343            day.not_found.add(&path, 1);
1344        }
1345    }
1346}
1347
1348fn or_unknown(name: &str) -> &str {
1349    if name.is_empty() { "(unnamed)" } else { name }
1350}
1351
1352/// Decide browsers that went quiet without loading an asset: bots.
1353#[doc(hidden)]
1354pub fn settle(now: u64) {
1355    for shard in &recorder().shards {
1356        let mut shard = shard.lock().unwrap_or_else(|e| e.into_inner());
1357        shard.close_sessions(|s| now.saturating_sub(s.last) >= SESSION_GAP);
1358        let done: Vec<u64> = shard.pending.iter().filter(|(_, p)| now.saturating_sub(p.last) >= UNDECIDED.as_secs()).map(|(v, _)| *v).collect();
1359        for visitor in done {
1360            let Some(pending) = shard.pending.remove(&visitor) else { continue };
1361            let day = pending.requests.first().map_or(now / 86_400, |d| d.hour / 24);
1362            let host = pending.requests.first().map_or(0, |d| d.host);
1363            if shard.seen.insert(visitor, Group::Bot).is_none() {
1364                shard.new_visitor(day, host, BOTS);
1365                shard.count_page_only(day, host);
1366            }
1367            for d in pending.requests {
1368                shard.count(BOTS, d.hour, d.host, &browser_without_assets(), d.page, d.not_found, visitor);
1369            }
1370        }
1371    }
1372}
1373
1374/// Everything counted, merged across shards: `(hour, host) → counts` and
1375/// `day → lists` (after settling quiet browsers as of `now`).
1376#[doc(hidden)]
1377pub fn snapshot(now: u64) -> (BTreeMap<(u64, u8), [Counts; GROUPS]>, BTreeMap<u64, Day>) {
1378    settle(now);
1379    drain_locals();
1380    let mut hours: BTreeMap<(u64, u8), [Counts; GROUPS]> = BTreeMap::new();
1381    let mut days: BTreeMap<u64, Day> = BTreeMap::new();
1382    for shard in &recorder().shards {
1383        let shard = shard.lock().unwrap_or_else(|e| e.into_inner());
1384        for (key, counts) in &shard.hours {
1385            let entry = hours.entry(*key).or_default();
1386            for g in 0..GROUPS {
1387                entry[g].requests += counts[g].requests;
1388                entry[g].pages += counts[g].pages;
1389            }
1390        }
1391        for (day, lists) in &shard.days {
1392            days.entry(*day).or_default().merge(lists);
1393        }
1394        // Open sessions count as if they ended now (they stay open).
1395        for session in shard.open.values() {
1396            let day = days.entry(session.start / 86_400).or_default();
1397            add_session(day, session);
1398            let mut visit = session.visit();
1399            visit.verified |= shard.verified.contains(&session.visitor);
1400            day.visits.push(visit);
1401        }
1402    }
1403    (hours, days)
1404}
1405
1406/// A closed (or, in a snapshot, open) session's totals, exit page and goals
1407/// into its day.
1408fn add_session(day: &mut Day, session: &Session) {
1409    let host = session.exit.split('/').next().unwrap_or("").to_string();
1410    day.sessions.entry(host.clone()).or_default().add(&session.totals());
1411    day.exit_pages.add(&session.exit, 1);
1412    if session.goals != 0 {
1413        for (i, goal) in goals().iter().enumerate() {
1414            if session.goals & (1 << i) != 0 {
1415                day.behaviour[GOALS].add_capped(&format!("{host}\t{goal}"), 1, DIM_TOP);
1416            }
1417        }
1418    }
1419}
1420
1421/// Whether any goal is a request goal: unknown (`u64::MAX`), 0 or 1.
1422static REQUEST_GOALS: AtomicU64 = AtomicU64::new(u64::MAX);
1423
1424fn goals_lock() -> &'static RwLock<Vec<String>> {
1425    static GOALS_SET: OnceLock<RwLock<Vec<String>>> = OnceLock::new();
1426    GOALS_SET.get_or_init(|| RwLock::new(super::config::goals()))
1427}
1428
1429/// The configured goals (read from the settings once).
1430fn goals() -> std::sync::RwLockReadGuard<'static, Vec<String>> {
1431    goals_lock().read().unwrap_or_else(|e| e.into_inner())
1432}
1433
1434/// Replace the goals (tests).
1435#[cfg(test)]
1436#[doc(hidden)]
1437pub fn set_goals_for_tests(goals: &[&str]) {
1438    *goals_lock().write().unwrap_or_else(|e| e.into_inner()) = goals.iter().map(|g| g.to_string()).collect();
1439    REQUEST_GOALS.store(u64::MAX, Ordering::Relaxed);
1440}
1441
1442/// The path of a page key (`host/path`).
1443fn path_of(page: &str) -> &str {
1444    page.find('/').map_or("/", |i| &page[i..])
1445}
1446
1447/// The goals a page view (`host/path`) reaches.
1448fn page_goals(page: &str) -> u32 {
1449    let path = page.find('/').map_or("/", |i| &page[i..]);
1450    let mut reached = 0;
1451    for (i, goal) in goals().iter().enumerate() {
1452        let hit = match goal.strip_suffix('*') {
1453            _ if goal.starts_with("event:") || goal.starts_with("req:") => false,
1454            Some(prefix) => path.starts_with(prefix),
1455            None => path == goal,
1456        };
1457        if hit {
1458            reached |= 1 << i;
1459        }
1460    }
1461    reached
1462}
1463
1464/// Whether any goal is a request (`req:/api/proxy`): then people's
1465/// requests other than pages are checked against them.
1466fn request_goals_configured() -> bool {
1467    match REQUEST_GOALS.load(Ordering::Relaxed) {
1468        u64::MAX => {
1469            let any = goals().iter().any(|g| g.starts_with("req:"));
1470            REQUEST_GOALS.store(any as u64, Ordering::Relaxed);
1471            any
1472        }
1473        n => n == 1,
1474    }
1475}
1476
1477/// The request goals (`req:/path`, or `req:/prefix*`) a request path reaches.
1478fn request_goals(path: &str) -> u32 {
1479    let mut reached = 0;
1480    for (i, goal) in goals().iter().enumerate() {
1481        let Some(want) = goal.strip_prefix("req:") else { continue };
1482        let hit = match want.strip_suffix('*') {
1483            Some(prefix) => path.starts_with(prefix),
1484            None => path == want,
1485        };
1486        if hit {
1487            reached |= 1 << i;
1488        }
1489    }
1490    reached
1491}
1492
1493/// The goals an event reaches.
1494fn event_goals(name: &str) -> u32 {
1495    let mut reached = 0;
1496    for (i, goal) in goals().iter().enumerate() {
1497        if goal.strip_prefix("event:") == Some(name) {
1498            reached |= 1 << i;
1499        }
1500    }
1501    reached
1502}
1503
1504fn json_string(raw: &str) -> Option<String> {
1505    crate::mcp::json_rpc::extract_str(&format!("{{\"v\":{raw}}}"), "v")
1506}
1507
1508fn width_bucket(width: u64) -> &'static str {
1509    match width {
1510        0 => "(unknown)",
1511        1..=599 => "phone",
1512        600..=1023 => "tablet",
1513        1024..=1439 => "laptop",
1514        _ => "wide",
1515    }
1516}
1517
1518/// A report from the first-party script (`/_rws/t`): `{"t":"leave"|"view"|
1519/// "event", …}`. Counted only for a visitor already counted as a person
1520/// today — a client that never loaded the page's assets can't post reports
1521/// in.
1522#[doc(hidden)]
1523pub fn beacon(ip: IpAddr, raw_host: &str, user_agent: Option<&str>, body: &str, now: u64) {
1524    if !enabled() {
1525        return;
1526    }
1527    let Some(members) = crate::mcp::json_rpc::object_members(body) else { return };
1528    let get = |key: &str| members.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
1529    let number = |key: &str| get(key).and_then(|v| v.trim().parse::<f64>().ok()).filter(|n| n.is_finite() && *n >= 0.0).map(|n| n as u64);
1530    let Some(kind) = get("t").and_then(json_string) else { return };
1531    let Some(path) = get("p").and_then(json_string).filter(|p| p.starts_with('/') && p.len() <= 1000) else { return };
1532    let host = host_index(raw_host);
1533    let day = now / 86_400;
1534    let visitor = visitor(day, host, ip, user_agent);
1535    let host_name = normalize_host(raw_host);
1536
1537    if kind == "view" {
1538        // A single-page app's route change: a page view like any other,
1539        // arriving from the page before (same site, so not a new arrival).
1540        let from = get("r").and_then(json_string).filter(|r| r.starts_with('/')).unwrap_or_else(|| "/".to_string());
1541        let referer = format!("https://{host_name}{from}");
1542        let is_person = {
1543            let mut shard = recorder().shards[(visitor % SHARDS as u64) as usize].lock().unwrap_or_else(|e| e.into_inner());
1544            let person = shard.seen.get(&visitor) == Some(&Group::Person);
1545            if person {
1546                shard.mark_verified(visitor, day, &host_name);
1547            }
1548            person
1549        };
1550        if is_person {
1551            record(&Hit {
1552                ip,
1553                host: raw_host,
1554                user_agent,
1555                referer: Some(&referer),
1556                method: "GET",
1557                path: &path,
1558                status: 200,
1559                content_type: Some("text/html"),
1560                headers: &[],
1561                now,
1562            });
1563        }
1564        return;
1565    }
1566
1567    let mut shard = recorder().shards[(visitor % SHARDS as u64) as usize].lock().unwrap_or_else(|e| e.into_inner());
1568    if shard.seen.get(&visitor) != Some(&Group::Person) {
1569        return;
1570    }
1571    shard.mark_verified(visitor, day, &host_name);
1572    if let Some(session) = shard.open.get_mut(&visitor) {
1573        session.reports += 1;
1574        if session.reports > MAX_REPORTS {
1575            return;
1576        }
1577    }
1578    let page = page_key(raw_host, &path);
1579    match kind.as_str() {
1580        "leave" => {
1581            // A report without a usable time isn't one.
1582            let Some(ms) = number("ms") else { return };
1583            let secs = ms.min(MAX_ENGAGED_SECS * 1000) / 1000;
1584            let depth = number("sd").unwrap_or(0).min(100);
1585            let width = number("w").unwrap_or(0);
1586            let bucket = match depth {
1587                0..=25 => "25",
1588                26..=50 => "50",
1589                51..=75 => "75",
1590                _ => "100",
1591            };
1592            #[cfg(feature = "model-postgres")]
1593            super::store::enqueue(super::store::Row::Report(super::store::Report {
1594                at: now,
1595                host: host_name.clone(),
1596                path: path.clone(),
1597                visitor,
1598                kind: "leave",
1599                secs: Some(secs),
1600                scroll: Some(depth),
1601                width: Some(width),
1602                ..Default::default()
1603            }));
1604            let d = shard.day(day);
1605            d.behaviour[ENGAGED_SECS].add(&page, secs);
1606            d.behaviour[ENGAGED_VIEWS].add(&page, 1);
1607            d.behaviour[SCROLL].add_capped(&format!("{host_name}\t{bucket}"), 1, DIM_TOP);
1608            d.behaviour[SCREENS].add_capped(&format!("{host_name}\t{}", width_bucket(width)), 1, DIM_TOP);
1609        }
1610        "event" => {
1611            let Some(name) = get("n").and_then(json_string).map(|n| n.chars().filter(|c| !c.is_control()).take(64).collect::<String>()).filter(|n| !n.is_empty()) else {
1612                return;
1613            };
1614            let props: Vec<(String, String)> = get("q")
1615                .and_then(crate::mcp::json_rpc::object_members)
1616                .unwrap_or_default()
1617                .into_iter()
1618                .take(4)
1619                .filter_map(|(k, v)| Some((k.chars().take(32).collect::<String>(), json_string(&v)?.chars().take(64).collect::<String>())))
1620                .collect();
1621            let reached = event_goals(&name);
1622            if let Some(session) = shard.open.get_mut(&visitor) {
1623                session.goals |= reached;
1624                if session.events.len() < 10 {
1625                    session.events.push(name.clone());
1626                }
1627            }
1628            #[cfg(feature = "model-postgres")]
1629            super::store::enqueue(super::store::Row::Report(super::store::Report {
1630                at: now,
1631                host: host_name.clone(),
1632                path: path.clone(),
1633                visitor,
1634                kind: "event",
1635                name: Some(name.clone()),
1636                props: (!props.is_empty()).then(|| props.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&")),
1637                ..Default::default()
1638            }));
1639            let d = shard.day(day);
1640            d.behaviour[EVENTS].add_capped(&format!("{host_name}\t{name}"), 1, DIM_TOP);
1641            for (k, v) in props {
1642                d.behaviour[EVENT_PROPS].add_capped(&format!("{host_name}\t{name}\t{k}={v}"), 1, DIM_TOP);
1643            }
1644        }
1645        _ => {}
1646    }
1647}
1648
1649/// Platforms an app may report in an event (`p`); others are `other`.
1650const APP_PLATFORMS: &[&str] = &["ios", "ipados", "macos", "visionos", "watchos", "android", "windows", "linux", "chrome", "edge", "firefox", "safari", "web", "other"];
1651
1652/// Why an app event was refused.
1653#[derive(Debug, PartialEq, Eq)]
1654#[doc(hidden)]
1655pub enum AppEventError {
1656    /// Not JSON, or without `app` and `n`.
1657    Malformed,
1658    /// `app` isn't one of `[traffic] apps`.
1659    UnknownApp,
1660}
1661
1662/// An event from one of the site's apps (`POST /_rws/e`, 18.35):
1663/// `{"app":"HITOP","v":"2.3.1","p":"ios","n":"request_sent"}`. Native apps
1664/// and extensions don't load pages, so unlike the script's reports these
1665/// aren't tied to a person: the client counts as a user of `app` (by
1666/// `p` platform and `v` version) and the event under its name. Only
1667/// configured apps are taken, at most [`MAX_REPORTS`] events per client a
1668/// day; nothing is stored in the app.
1669#[doc(hidden)]
1670pub fn app_event(ip: IpAddr, raw_host: &str, user_agent: Option<&str>, body: &str, now: u64) -> Result<(), AppEventError> {
1671    if !enabled() {
1672        return Ok(());
1673    }
1674    let members = crate::mcp::json_rpc::object_members(body).ok_or(AppEventError::Malformed)?;
1675    let get = |key: &str| members.iter().find(|(k, _)| k == key).and_then(|(_, v)| json_string(v));
1676    let clean = |v: String, n: usize| v.chars().filter(|c| !c.is_control() && *c != '\t').take(n).collect::<String>();
1677    let app = get("app").ok_or(AppEventError::Malformed)?;
1678    let name = get("n").map(|n| clean(n, 64)).filter(|n| !n.is_empty()).ok_or(AppEventError::Malformed)?;
1679    let app = super::apps::configured(&app).ok_or(AppEventError::UnknownApp)?;
1680    let platform = get("p").map(|p| p.to_ascii_lowercase()).map_or("other", |p| APP_PLATFORMS.iter().copied().find(|k| *k == p).unwrap_or("other"));
1681    let version = get("v").map(|v| clean(v, 32)).filter(|v| !v.is_empty());
1682    let day = now / 86_400;
1683    let hour = now / 3_600;
1684    let host = host_index(raw_host);
1685    let visitor = visitor(day, host, ip, user_agent);
1686    let site = host_name(host);
1687    let recorder = recorder();
1688    let mut shard = recorder.shards[(visitor % SHARDS as u64) as usize].lock().unwrap_or_else(|e| e.into_inner());
1689    shard.roll(day, recorder.retention_days);
1690    let reports = shard.app_reports.entry(visitor).or_insert(0);
1691    *reports += 1;
1692    if *reports > MAX_REPORTS {
1693        return Ok(());
1694    }
1695    match shard.seen.get(&visitor).copied() {
1696        // The owner's own app use stays the owner's.
1697        Some(Group::Owner) => return Ok(()),
1698        Some(Group::App) => {}
1699        _ => {
1700            if shard.seen.insert(visitor, Group::App).is_none() {
1701                shard.new_visitor(day, host, APPS);
1702            }
1703            shard.count_app_user(day, &site, app, platform, version.as_deref());
1704            shard.hours.entry((hour, host)).or_default()[APPS].requests += 1;
1705        }
1706    }
1707    shard.day(day).extra[APP_EVENTS].add_capped(&format!("{site}\t{app}\t{name}"), 1, DIM_TOP);
1708    Ok(())
1709}
1710
1711/// People's page views of the last [`LIVE_WINDOW`] before `now`, from every
1712/// shard (unordered). Visitor keys are the day's hashes: comparable within
1713/// the result, meaningless outside it.
1714#[doc(hidden)]
1715pub fn recent(now: u64) -> Vec<Recent> {
1716    settle(now);
1717    let mut out = Vec::new();
1718    for shard in &recorder().shards {
1719        let shard = shard.lock().unwrap_or_else(|e| e.into_inner());
1720        out.extend(shard.recent.iter().filter(|r| r.at + LIVE_WINDOW >= now && r.at <= now).cloned());
1721    }
1722    out
1723}
1724
1725/// Put back what [`snapshot`] gave (loading a saved file): counts are added
1726/// to shard 0.
1727#[doc(hidden)]
1728pub fn restore(hosts: Vec<String>, hours: BTreeMap<(u64, u8), [Counts; GROUPS]>, days: BTreeMap<u64, Day>) {
1729    let recorder = recorder();
1730    let configured = recorder.configured.read().unwrap_or_else(|e| e.into_inner());
1731    let mut known = recorder.hosts.write().unwrap_or_else(|e| e.into_inner());
1732    // Configured sites first, so the hosts saved before them can't take
1733    // their slots.
1734    let mut order: Vec<usize> = (0..hosts.len()).collect();
1735    order.sort_by_key(|i| configured.binary_search(&hosts[*i]).is_err());
1736    let mut map = vec![0u8; hosts.len()];
1737    for i in order {
1738        map[i] = host_slot(&mut known, &configured, hosts[i].clone());
1739    }
1740    drop(known);
1741    drop(configured);
1742    HOSTS_GENERATION.fetch_add(1, Ordering::Relaxed);
1743    let mut shard = recorder.shards[0].lock().unwrap_or_else(|e| e.into_inner());
1744    for ((hour, host), counts) in hours {
1745        let host = map.get(host as usize).copied().unwrap_or(0);
1746        let entry = shard.hours.entry((hour, host)).or_default();
1747        for g in 0..GROUPS {
1748            entry[g].requests += counts[g].requests;
1749            entry[g].pages += counts[g].pages;
1750        }
1751    }
1752    for (day, lists) in days {
1753        shard.days.entry(day).or_default().merge(&lists);
1754    }
1755}
1756
1757#[cfg(test)]
1758#[doc(hidden)]
1759pub fn disable_for_tests() {
1760    ENABLED.store(false, Ordering::Relaxed);
1761}
1762
1763#[cfg(test)]
1764#[doc(hidden)]
1765pub fn reset_for_tests() {
1766    let recorder = recorder();
1767    HOSTS_GENERATION.fetch_add(1, Ordering::Relaxed);
1768    for local in locals().lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(|w| w.upgrade()) {
1769        *local.lock().unwrap_or_else(|e| e.into_inner()) = Local::default();
1770    }
1771    for shard in &recorder.shards {
1772        *shard.lock().unwrap_or_else(|e| e.into_inner()) = Shard::default();
1773    }
1774    recorder.hosts.write().unwrap_or_else(|e| e.into_inner()).clear();
1775    recorder.configured.write().unwrap_or_else(|e| e.into_inner()).clear();
1776}