Skip to main content

rustango_cms/analytics/
mod.rs

1//! Default first-party web analytics (#analytics).
2//!
3//! Every rustango-cms site gets privacy-conscious engagement analytics
4//! that keeps working when the HTML is served from a CDN and deeply
5//! cached. Collection is driven entirely by a client beacon to endpoints
6//! that are never cached:
7//!
8//! - **Pageview** — `POST /__cms__/collect` (CSRF-exempt, `no-store`),
9//!   one row per page load. See [`collect`].
10//! - **Engagement + "active now"** — a WebSocket at `/__cms__/ws`; the
11//!   server times connect→disconnect and writes one engagement row on
12//!   close, and keeps an in-memory per-tenant "active now" gauge. See
13//!   [`ws`]. If the socket can't open, the beacon falls back to an
14//!   unload `POST /__cms__/collect`.
15//!
16//! The beacon `<script>` is auto-injected into every rendered public
17//! page (see `render.rs`), so consumers need no template change. The
18//! one required consumer line is `CsrfConfig::exempt_prefix(COLLECT_PATH)`
19//! (a sendBeacon POST can't carry an `X-CSRF-Token`, and a CDN-cached
20//! page may never have received a CSRF cookie).
21//!
22//! Data model + boot table creation: [`model`]. Aggregates for the
23//! admin dashboard (`/cms-admin/analytics`): [`query`]. Retention:
24//! [`retention`].
25
26pub mod collect;
27pub mod model;
28pub mod query;
29pub mod retention;
30pub mod ws;
31
32pub use model::{ensure_table, AnalyticsEvent};
33
34use std::collections::HashMap;
35use std::sync::{Mutex, OnceLock};
36
37/// Public collector endpoint (POST via `sendBeacon`). Referenced by the
38/// consumer's `CsrfConfig::exempt_prefix` and by the beacon JS.
39pub const COLLECT_PATH: &str = "/__cms__/collect";
40/// Beacon script endpoint (GET, immutable-cached).
41pub const BEACON_JS_PATH: &str = "/__cms__/a.js";
42/// Engagement WebSocket endpoint (GET upgrade).
43pub const WS_PATH: &str = "/__cms__/ws";
44/// `SiteSetting` scope holding the analytics config `{ enabled, retention_days }`.
45pub const SETTINGS_SCOPE: &str = "analytics";
46
47const BEACON_JS: &str = include_str!("a.js");
48
49/// FNV-1a fingerprint of the beacon JS, for the `?v=` cache-buster.
50#[must_use]
51pub fn beacon_asset_version() -> &'static str {
52    static V: OnceLock<String> = OnceLock::new();
53    V.get_or_init(|| {
54        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
55        for b in BEACON_JS.as_bytes() {
56            h ^= u64::from(*b);
57            h = h.wrapping_mul(0x0000_0100_0000_01b3);
58        }
59        format!("{h:x}")
60    })
61}
62
63/// `GET /__cms__/a.js` — the beacon script, immutable-cached (version
64/// busted via the `?v=` the injected tag carries).
65pub async fn serve_beacon_js() -> impl axum::response::IntoResponse {
66    (
67        [
68            (
69                axum::http::header::CONTENT_TYPE,
70                axum::http::HeaderValue::from_static("text/javascript; charset=utf-8"),
71            ),
72            (
73                axum::http::header::CACHE_CONTROL,
74                axum::http::HeaderValue::from_static("public, max-age=31536000, immutable"),
75            ),
76        ],
77        BEACON_JS,
78    )
79}
80
81/// Whether analytics is enabled for this render, from the prefetched
82/// `SiteSetting` scope→value map. Default **on** (inject unless the
83/// `"analytics"` row explicitly sets `enabled: false`).
84#[must_use]
85pub fn enabled(site_settings: &HashMap<String, serde_json::Value>) -> bool {
86    site_settings
87        .get(SETTINGS_SCOPE)
88        .and_then(|v| v.get("enabled"))
89        .and_then(serde_json::Value::as_bool)
90        != Some(false)
91}
92
93/// Insert the beacon `<script>` immediately before the last `</body>`.
94/// No-op when the tag is absent (fragments / non-HTML) — never appends
95/// blindly. Runs during render, before the page cache stores the
96/// response, so cached HTML carries the tag.
97#[must_use]
98pub fn inject_beacon(html: String) -> String {
99    let Some(pos) = html.rfind("</body>") else {
100        return html;
101    };
102    let tag = format!(
103        "<script defer src=\"{}?v={}\"></script>",
104        BEACON_JS_PATH,
105        beacon_asset_version()
106    );
107    let mut out = String::with_capacity(html.len() + tag.len());
108    out.push_str(&html[..pos]);
109    out.push_str(&tag);
110    out.push_str(&html[pos..]);
111    out
112}
113
114// ---- "active now" presence (in-memory, per-tenant by Host) ----------
115
116/// Process-global live-connection counts, keyed by tenant `Host`. This
117/// is a gauge, not persisted — it resets on restart, which is fine for
118/// "who's online right now".
119fn presence() -> &'static Mutex<HashMap<String, u64>> {
120    static P: OnceLock<Mutex<HashMap<String, u64>>> = OnceLock::new();
121    P.get_or_init(|| Mutex::new(HashMap::new()))
122}
123
124pub(crate) fn presence_incr(host: &str) {
125    if let Ok(mut m) = presence().lock() {
126        *m.entry(host.to_owned()).or_insert(0) += 1;
127    }
128}
129
130pub(crate) fn presence_decr(host: &str) {
131    if let Ok(mut m) = presence().lock() {
132        if let Some(c) = m.get_mut(host) {
133            *c = c.saturating_sub(1);
134            if *c == 0 {
135                m.remove(host);
136            }
137        }
138    }
139}
140
141/// Current "active now" count for a tenant `Host`.
142#[must_use]
143pub fn presence_count(host: &str) -> u64 {
144    presence()
145        .lock()
146        .ok()
147        .and_then(|m| m.get(host).copied())
148        .unwrap_or(0)
149}