Skip to main content

rustango_cms/analytics/
ws.rs

1//! Engagement WebSocket — `GET /__cms__/ws` (an HTTP upgrade, so it
2//! bypasses both the page cache and CSRF).
3//!
4//! The socket's lifetime *is* the engagement signal: on connect we bump
5//! the per-tenant "active now" gauge and start a timer; on disconnect we
6//! decrement the gauge and append one `engagement` row with the measured
7//! duration + max scroll depth. The client pushes `{"scroll":N}` updates
8//! over the socket; a 30s keepalive ping detects dead connections.
9//!
10//! Pool safety: we clone the cheap `Pool` handle and **drop the `Tenant`
11//! extractor before the socket future runs**, so a Postgres-eager
12//! checked-out connection is never held for the (long) socket lifetime —
13//! the engagement INSERT acquires a connection only transiently at close.
14
15use crate::log_err::LogErr as _;
16use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
17use axum::extract::Query;
18use axum::http::HeaderMap;
19use axum::response::{IntoResponse, Response};
20use rustango::extractors::Tenant;
21use rustango::sql::{Auto, Pool};
22use serde::Deserialize;
23
24use super::collect::{classify_ua, geo_country, header_str, host_of, is_bot, sanitize_path};
25use super::model::AnalyticsEvent;
26
27#[derive(Deserialize, Default)]
28pub(crate) struct WsParams {
29    #[serde(default)]
30    vid: String,
31    #[serde(default)]
32    sid: String,
33    #[serde(default)]
34    p: String,
35    #[serde(default)]
36    loc: String,
37    #[serde(default)]
38    referrer: String,
39}
40
41#[derive(Deserialize)]
42struct ScrollMsg {
43    scroll: i32,
44}
45
46/// Immutable per-connection context moved into the socket future.
47struct Engage {
48    pool: Pool,
49    host: String,
50    visitor_id: String,
51    session_id: String,
52    path: String,
53    referrer_host: String,
54    country: String,
55    device: String,
56    browser: String,
57    os: String,
58    locale: String,
59}
60
61/// `GET /__cms__/ws` — upgrade + track one visitor's engagement.
62pub(crate) async fn handle_ws(
63    tenant: Tenant,
64    headers: HeaderMap,
65    Query(q): Query<WsParams>,
66    ws: WebSocketUpgrade,
67) -> Response {
68    let ua = header_str(&headers, axum::http::header::USER_AGENT.as_str());
69    if is_bot(&ua) {
70        return (axum::http::StatusCode::BAD_REQUEST, "").into_response();
71    }
72    // Clone the pool handle (no connection held) + capture the tenant
73    // Host, then drop `tenant` before the socket future.
74    let pool = tenant.pool().clone();
75    drop(tenant);
76
77    let (device, browser, os) = classify_ua(&ua);
78    let ctx = Engage {
79        pool,
80        host: header_str(&headers, "host"),
81        visitor_id: q.vid.chars().take(36).collect(),
82        session_id: q.sid.chars().take(36).collect(),
83        path: sanitize_path(&q.p),
84        referrer_host: host_of(&q.referrer),
85        country: geo_country(&headers),
86        device: device.to_owned(),
87        browser: browser.chars().take(32).collect(),
88        os: os.chars().take(32).collect(),
89        locale: q.loc.chars().take(16).collect(),
90    };
91    ws.on_upgrade(move |socket| run(socket, ctx))
92}
93
94async fn run(mut socket: WebSocket, ctx: Engage) {
95    super::presence_incr(&ctx.host);
96    let start = std::time::Instant::now();
97    let mut max_scroll: i32 = 0;
98
99    // Read until the client closes (on pagehide) or the connection
100    // errors. The socket's lifetime is the engagement duration. Reply to
101    // client pings; browsers close cleanly on unload so no server-side
102    // keepalive timer is needed (avoids a tokio dependency here).
103    while let Some(msg) = socket.recv().await {
104        match msg {
105            Ok(Message::Text(t)) => {
106                if let Ok(m) = serde_json::from_str::<ScrollMsg>(t.as_str()) {
107                    let p = m.scroll.clamp(0, 100);
108                    if p > max_scroll {
109                        max_scroll = p;
110                    }
111                }
112            }
113            Ok(Message::Ping(p)) => {
114                if socket.send(Message::Pong(p)).await.is_err() {
115                    break;
116                }
117            }
118            Ok(Message::Close(_)) => break,
119            Ok(_) => {}
120            Err(_) => break,
121        }
122    }
123
124    super::presence_decr(&ctx.host);
125
126    let dur_ms = i64::try_from(start.elapsed().as_millis()).unwrap_or(i64::MAX);
127    let mut entry = AnalyticsEvent {
128        id: Auto::Unset,
129        visitor_id: ctx.visitor_id,
130        session_id: ctx.session_id,
131        event_type: "engagement".to_owned(),
132        path: ctx.path,
133        referrer_host: ctx.referrer_host,
134        country: ctx.country,
135        device: ctx.device,
136        browser: ctx.browser,
137        os: ctx.os,
138        screen_w: 0,
139        screen_h: 0,
140        duration_ms: dur_ms,
141        max_scroll_pct: max_scroll,
142        is_bounce: false,
143        locale: ctx.locale,
144        created_at: chrono::Utc::now(),
145    };
146    entry.insert_pool(&ctx.pool).await.log_warn("analytics event not recorded");
147}