pub mod collect;
pub mod model;
pub mod query;
pub mod retention;
pub mod ws;
pub use model::{ensure_table, AnalyticsEvent};
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
pub const COLLECT_PATH: &str = "/__cms__/collect";
pub const BEACON_JS_PATH: &str = "/__cms__/a.js";
pub const WS_PATH: &str = "/__cms__/ws";
pub const SETTINGS_SCOPE: &str = "analytics";
const BEACON_JS: &str = include_str!("a.js");
#[must_use]
pub fn beacon_asset_version() -> &'static str {
static V: OnceLock<String> = OnceLock::new();
V.get_or_init(|| {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in BEACON_JS.as_bytes() {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
format!("{h:x}")
})
}
pub async fn serve_beacon_js() -> impl axum::response::IntoResponse {
(
[
(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("text/javascript; charset=utf-8"),
),
(
axum::http::header::CACHE_CONTROL,
axum::http::HeaderValue::from_static("public, max-age=31536000, immutable"),
),
],
BEACON_JS,
)
}
#[must_use]
pub fn enabled(site_settings: &HashMap<String, serde_json::Value>) -> bool {
site_settings
.get(SETTINGS_SCOPE)
.and_then(|v| v.get("enabled"))
.and_then(serde_json::Value::as_bool)
!= Some(false)
}
#[must_use]
pub fn inject_beacon(html: String) -> String {
let Some(pos) = html.rfind("</body>") else {
return html;
};
let tag = format!(
"<script defer src=\"{}?v={}\"></script>",
BEACON_JS_PATH,
beacon_asset_version()
);
let mut out = String::with_capacity(html.len() + tag.len());
out.push_str(&html[..pos]);
out.push_str(&tag);
out.push_str(&html[pos..]);
out
}
fn presence() -> &'static Mutex<HashMap<String, u64>> {
static P: OnceLock<Mutex<HashMap<String, u64>>> = OnceLock::new();
P.get_or_init(|| Mutex::new(HashMap::new()))
}
pub(crate) fn presence_incr(host: &str) {
if let Ok(mut m) = presence().lock() {
*m.entry(host.to_owned()).or_insert(0) += 1;
}
}
pub(crate) fn presence_decr(host: &str) {
if let Ok(mut m) = presence().lock() {
if let Some(c) = m.get_mut(host) {
*c = c.saturating_sub(1);
if *c == 0 {
m.remove(host);
}
}
}
}
#[must_use]
pub fn presence_count(host: &str) -> u64 {
presence()
.lock()
.ok()
.and_then(|m| m.get(host).copied())
.unwrap_or(0)
}