rustango_cms/analytics/model.rs
1//! Analytics event model + boot-time table/index creation.
2//!
3//! `cms_analytics_event` is created per tenant at boot via
4//! `CREATE TABLE IF NOT EXISTS` (the same pattern as `cms_form_entry`).
5//! The create-table shortcut does **not** emit index DDL, so the indexes
6//! the dashboard aggregates rely on are created explicitly here.
7
8use chrono::{DateTime, Utc};
9use rustango::core::Model as _;
10use rustango::sql::Auto;
11use rustango::Model;
12use serde::{Deserialize, Serialize};
13
14/// One analytics hit — a `pageview` (HTTP beacon on load) or an
15/// `engagement` record (written when the visitor's WebSocket
16/// disconnects, or via an unload fallback beacon). Append-only. No raw
17/// IP is ever stored — only a coarse `country` resolved from a CDN
18/// header.
19#[derive(Model, Debug, Clone, Serialize, Deserialize)]
20#[rustango(table = "cms_analytics_event", app = "cms")]
21pub struct AnalyticsEvent {
22 #[rustango(primary_key)]
23 pub id: Auto<i64>,
24 /// Persistent client id (localStorage UUID).
25 #[rustango(max_length = 36)]
26 pub visitor_id: String,
27 /// Per-tab session id (sessionStorage UUID).
28 #[rustango(max_length = 36)]
29 pub session_id: String,
30 /// `"pageview"` | `"engagement"`.
31 #[rustango(max_length = 16)]
32 pub event_type: String,
33 /// Path only — no scheme/host/query.
34 #[rustango(max_length = 512)]
35 pub path: String,
36 /// Referrer host only (privacy: no full URL / query string).
37 #[rustango(max_length = 255)]
38 pub referrer_host: String,
39 /// ISO-3166 alpha-2 country from a CDN header; `""` = Unknown.
40 #[rustango(max_length = 2)]
41 pub country: String,
42 /// `"desktop"` | `"mobile"` | `"tablet"`.
43 #[rustango(max_length = 16)]
44 pub device: String,
45 #[rustango(max_length = 32)]
46 pub browser: String,
47 #[rustango(max_length = 32)]
48 pub os: String,
49 pub screen_w: i32,
50 pub screen_h: i32,
51 /// Engagement only: time on page (ms). 0 for pageviews.
52 pub duration_ms: i64,
53 /// Engagement only: max scroll depth 0-100. 0 for pageviews.
54 pub max_scroll_pct: i32,
55 /// Engagement only: client bounce hint (the authoritative bounce
56 /// rate is derived server-side in the dashboard query).
57 pub is_bounce: bool,
58 #[rustango(max_length = 16)]
59 pub locale: String,
60 /// Set explicitly at insert (`Utc::now()`) rather than via SQLite's
61 /// space-formatted `CURRENT_TIMESTAMP`, so the value is stored as an
62 /// RFC3339 timestamp and typed ORM date filters
63 /// (`created_at.gte(from)`) compare correctly across dialects.
64 pub created_at: DateTime<Utc>,
65}
66
67/// Create `cms_analytics_event` (+ its indexes) if absent. Idempotent;
68/// called per tenant at boot.
69///
70/// # Errors
71/// Driver / DDL failures on the CREATE TABLE.
72pub async fn ensure_table(pool: &rustango::sql::Pool) -> Result<(), rustango::sql::ExecError> {
73 let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
74 pool.dialect(),
75 &AnalyticsEvent::SCHEMA,
76 );
77 for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
78 rustango::sql::raw_execute_pool(pool, stmt, Vec::new()).await?;
79 }
80 // Indexes — hand-emitted because the create-table shortcut skips
81 // them. Build the DDL up front so the borrowed `&dyn Dialect` isn't
82 // held across the `.await` (which would make this future non-Send);
83 // then run each (MySQL-safe via `run_ddl_idempotent`, which forgives a
84 // re-run's duplicate-index error). MySQL has no `CREATE INDEX IF NOT
85 // EXISTS`, so there the clause is left out; with it every statement
86 // was a syntax error and the table got no index at all (#715).
87 let index_sql: Vec<String> = {
88 let d = pool.dialect();
89 let if_not_exists = if d.supports_create_index_if_not_exists() {
90 "IF NOT EXISTS "
91 } else {
92 ""
93 };
94 let table = d.quote_ident("cms_analytics_event");
95 let mut v = Vec::new();
96 for (name, col) in [
97 ("idx_cms_analytics_created", "created_at"),
98 ("idx_cms_analytics_visitor", "visitor_id"),
99 ("idx_cms_analytics_session", "session_id"),
100 ("idx_cms_analytics_path", "path"),
101 ] {
102 v.push(format!(
103 "CREATE INDEX {if_not_exists}{} ON {} ({})",
104 d.quote_ident(name),
105 table,
106 d.quote_ident(col),
107 ));
108 }
109 v
110 };
111 for sql in &index_sql {
112 // Best-effort: the table works without them, only slower.
113 if let Err(e) = rustango::sql::run_ddl_idempotent(pool, sql).await {
114 tracing::warn!(target: "rustango_cms::analytics", error = %e, %sql, "analytics index not created");
115 }
116 }
117 Ok(())
118}