Skip to main content

adk_server/awp/
beacon.rs

1//! `POST /awp/v2/beacon`: cookieless measurement (spec 3.5 §7.12; AWP 2.0 §20).
2//!
3//! A page sends `{"kind": "pageview", "path": "/pricing"}` or `{"kind": "event", "name":
4//! "signup"}`. The edge counts it per day and answers `204`:
5//!
6//! | Rule | Behaviour |
7//! |---|---|
8//! | No cookies | The beacon sets none and reads none |
9//! | No stored addresses | Counts carry no address; the edge's rate limiter keys on the address in memory only |
10//! | No identifiers without a receipt | A visitor is counted once a day only under a live `persistent_profile` receipt the beacon names, by its pseudonymous `subjectRef` |
11//! | Global Privacy Control | A request with `Sec-GPC: 1` counts nothing |
12//!
13//! Query strings and fragments are cut from paths, so a URL never carries personal data into a
14//! count. [`BeaconCounts`] reads the counts for the KPI tracker.
15//!
16//! | Metric | Counts |
17//! |---|---|
18//! | `pageviews` | Page views |
19//! | `pageviews:{path}` | Page views of one path |
20//! | `events:{name}` | One event |
21//! | `visitors` | Distinct consenting visitors, summed per day |
22
23use std::collections::{BTreeMap, BTreeSet};
24use std::sync::{Arc, Mutex};
25
26use adk_awp::v2::store::{ConsentReceiptStore, StoreError, StoreResult};
27use adk_core::subject::{StoreErasure, SubjectDataStore, SubjectScope, unsupported_error};
28use async_trait::async_trait;
29use awp_types::{ConsentScope, ErrorBody, ErrorCode};
30use axum::Router;
31use axum::body::Bytes;
32use axum::extract::State;
33use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
34use axum::response::{IntoResponse, Response};
35use axum::routing::post;
36use chrono::{DateTime, NaiveDate, Utc};
37use serde::Deserialize;
38use uuid::Uuid;
39
40/// The beacon's path.
41pub const BEACON_PATH: &str = "/awp/v2/beacon";
42/// The largest beacon body.
43pub const MAX_BEACON_BODY: usize = 2 * 1024;
44
45/// Daily counts behind the beacon (spec 3.5 §7.12).
46#[async_trait]
47pub trait BeaconStore: Send + Sync {
48    /// Adds `count` to `metric` on `day`.
49    async fn add(&self, day: NaiveDate, metric: &str, count: u64) -> StoreResult<()>;
50
51    /// Records `visitor`, a pseudonymous subject reference, as seen on `day`.
52    async fn add_visitor(&self, day: NaiveDate, visitor: &str) -> StoreResult<()>;
53
54    /// The total of `metric` over the days in `[from, to)`; `visitors` sums distinct
55    /// visitors per day.
56    async fn total(&self, metric: &str, from: NaiveDate, to: NaiveDate) -> StoreResult<u64>;
57
58    /// Replaces `visitor` in every day's visitor set with a random token, so the day's count
59    /// stays and no set names the visitor; returns how many days named it.
60    async fn forget_visitor(&self, visitor: &str) -> StoreResult<u64>;
61}
62
63/// The token that takes an erased visitor's place in a day's visitor set.
64pub(crate) fn forgotten() -> String {
65    format!("erased:{}", Uuid::new_v4().simple())
66}
67
68/// The beacon's visitor sets as a [`SubjectDataStore`]: erasure replaces the subject in every
69/// day's set (counts stay); export is unsupported, since the sets record only presence.
70pub struct BeaconSubjectData {
71    store: Arc<dyn BeaconStore>,
72}
73
74impl BeaconSubjectData {
75    /// The visitor sets in `store`.
76    pub fn new(store: Arc<dyn BeaconStore>) -> Self {
77        Self { store }
78    }
79}
80
81#[async_trait]
82impl SubjectDataStore for BeaconSubjectData {
83    fn name(&self) -> &str {
84        "awp.beacon"
85    }
86
87    async fn export(&self, _scope: &SubjectScope) -> adk_core::Result<serde_json::Value> {
88        Err(unsupported_error("awp.beacon", "export"))
89    }
90
91    async fn erase(&self, scope: &SubjectScope) -> adk_core::Result<StoreErasure> {
92        let mut forgotten = 0;
93        for subject in scope.subjects() {
94            forgotten += self
95                .store
96                .forget_visitor(&subject.id)
97                .await
98                .map_err(|error| adk_core::AdkError::session(error.to_string()))?;
99        }
100        Ok(StoreErasure::deleted(forgotten))
101    }
102}
103
104/// An in-memory [`BeaconStore`].
105#[derive(Debug, Clone, Default)]
106pub struct InMemoryBeaconStore {
107    counts: Arc<Mutex<BTreeMap<(NaiveDate, String), u64>>>,
108    visitors: Arc<Mutex<BTreeMap<NaiveDate, BTreeSet<String>>>>,
109}
110
111impl InMemoryBeaconStore {
112    /// An empty store.
113    pub fn new() -> Self {
114        Self::default()
115    }
116}
117
118#[async_trait]
119impl BeaconStore for InMemoryBeaconStore {
120    async fn add(&self, day: NaiveDate, metric: &str, count: u64) -> StoreResult<()> {
121        *self
122            .counts
123            .lock()
124            .unwrap_or_else(std::sync::PoisonError::into_inner)
125            .entry((day, metric.to_owned()))
126            .or_default() += count;
127        Ok(())
128    }
129
130    async fn add_visitor(&self, day: NaiveDate, visitor: &str) -> StoreResult<()> {
131        self.visitors
132            .lock()
133            .unwrap_or_else(std::sync::PoisonError::into_inner)
134            .entry(day)
135            .or_default()
136            .insert(visitor.to_owned());
137        Ok(())
138    }
139
140    async fn forget_visitor(&self, visitor: &str) -> StoreResult<u64> {
141        let mut visitors = self.visitors.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
142        let mut forgot = 0;
143        for seen in visitors.values_mut() {
144            if seen.remove(visitor) {
145                seen.insert(forgotten());
146                forgot += 1;
147            }
148        }
149        Ok(forgot)
150    }
151
152    async fn total(&self, metric: &str, from: NaiveDate, to: NaiveDate) -> StoreResult<u64> {
153        if metric == "visitors" {
154            let visitors = self.visitors.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
155            return Ok(visitors.range(from..to).map(|(_, seen)| seen.len() as u64).sum());
156        }
157        let counts = self.counts.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
158        Ok(counts
159            .iter()
160            .filter(|((day, name), _)| *day >= from && *day < to && name == metric)
161            .map(|(_, count)| *count)
162            .sum())
163    }
164}
165
166/// Reads the beacon's counts for the KPI tracker (spec 3.5 §7.11, §7.12): the shape of the
167/// kernel's `KpiSource::read`, so a `beacon` source wraps it directly.
168///
169/// # Example
170///
171/// ```rust
172/// use std::sync::Arc;
173///
174/// use adk_server::awp::beacon::{BeaconCounts, BeaconStore, InMemoryBeaconStore};
175/// use chrono::{TimeZone, Utc};
176///
177/// # #[tokio::main(flavor = "current_thread")]
178/// # async fn main() {
179/// let store = Arc::new(InMemoryBeaconStore::new());
180/// let day = Utc.with_ymd_and_hms(2026, 10, 25, 0, 0, 0).unwrap();
181/// store.add(day.date_naive(), "pageviews", 3).await.unwrap();
182/// let counts = BeaconCounts::new(store);
183/// let views = counts.read("pageviews", day, day + chrono::Duration::days(1)).await.unwrap();
184/// assert_eq!(views, Some(3.0));
185/// # }
186/// ```
187#[derive(Clone)]
188pub struct BeaconCounts {
189    store: Arc<dyn BeaconStore>,
190}
191
192impl std::fmt::Debug for BeaconCounts {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        f.debug_struct("BeaconCounts").finish_non_exhaustive()
195    }
196}
197
198impl BeaconCounts {
199    /// The counts in `store`.
200    pub fn new(store: Arc<dyn BeaconStore>) -> Self {
201        Self { store }
202    }
203
204    /// The total of `metric` over the days `[from, to)` cover; `None` for a window with no
205    /// whole day.
206    ///
207    /// # Errors
208    ///
209    /// [`StoreError`] when the store cannot be read.
210    pub async fn read(
211        &self,
212        metric: &str,
213        from: DateTime<Utc>,
214        to: DateTime<Utc>,
215    ) -> Result<Option<f64>, StoreError> {
216        let (from, to) = (from.date_naive(), to.date_naive());
217        if to <= from {
218            return Ok(None);
219        }
220        Ok(Some(self.store.total(metric, from, to).await? as f64))
221    }
222}
223
224#[derive(Clone)]
225pub(crate) struct BeaconState {
226    pub(crate) store: Arc<dyn BeaconStore>,
227    pub(crate) consent: Arc<dyn ConsentReceiptStore>,
228}
229
230impl BeaconState {
231    pub(crate) fn router(&self) -> Router {
232        // The limit applies while the body is read, so an oversized beacon is never buffered.
233        Router::new()
234            .route(BEACON_PATH, post(beacon))
235            .layer(axum::extract::DefaultBodyLimit::max(MAX_BEACON_BODY))
236            .with_state(self.clone())
237    }
238}
239
240#[derive(Deserialize)]
241struct Hit {
242    kind: String,
243    #[serde(default)]
244    path: Option<String>,
245    #[serde(default)]
246    name: Option<String>,
247    #[serde(default)]
248    receipt: Option<Uuid>,
249}
250
251fn no_content() -> Response {
252    let mut response = StatusCode::NO_CONTENT.into_response();
253    response.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
254    response
255}
256
257fn invalid(message: &str) -> Response {
258    super::envelope(ErrorBody::new(ErrorCode::InvalidRequest, message), None)
259}
260
261/// A path without its query string or fragment, at most 256 characters.
262fn clean_path(path: &str) -> Option<String> {
263    let path = path.split(['?', '#']).next().unwrap_or_default();
264    (path.starts_with('/') && path.len() <= 256 && !path.chars().any(char::is_control))
265        .then(|| path.to_owned())
266}
267
268fn clean_name(name: &str) -> Option<String> {
269    (!name.is_empty()
270        && name.len() <= 64
271        && name
272            .bytes()
273            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b)))
274    .then(|| name.to_owned())
275}
276
277async fn beacon(State(state): State<BeaconState>, headers: HeaderMap, body: Bytes) -> Response {
278    // Global Privacy Control: count nothing.
279    if headers.get("sec-gpc").and_then(|value| value.to_str().ok()).map(str::trim) == Some("1") {
280        return no_content();
281    }
282    if body.len() > MAX_BEACON_BODY {
283        return invalid("the beacon is too large");
284    }
285    // `navigator.sendBeacon` posts text/plain, so the body is read as JSON whatever its type.
286    let Ok(hit) = serde_json::from_slice::<Hit>(&body) else {
287        return invalid("the beacon must be JSON");
288    };
289    let day = Utc::now().date_naive();
290    let mut metrics = Vec::new();
291    match hit.kind.as_str() {
292        "pageview" => {
293            let Some(path) = hit.path.as_deref().and_then(clean_path) else {
294                return invalid("a page view names its path");
295            };
296            metrics.push("pageviews".to_owned());
297            metrics.push(format!("pageviews:{path}"));
298        }
299        "event" => {
300            let Some(name) = hit.name.as_deref().and_then(clean_name) else {
301                return invalid(
302                    "an event names itself in lowercase letters, digits, '.', '_' or '-'",
303                );
304            };
305            metrics.push(format!("events:{name}"));
306        }
307        _ => return invalid("a beacon is a pageview or an event"),
308    }
309    for metric in &metrics {
310        if let Err(error) = state.store.add(day, metric, 1).await {
311            tracing::warn!(error = %error, "awp beacon count not recorded");
312        }
313    }
314    // A visitor is identified only under a live persistent_profile receipt (A-I8).
315    if let Some(id) = hit.receipt
316        && let Ok(Some(record)) = state.consent.get(id).await
317        && record.receipt.scope == ConsentScope::PersistentProfile
318        && record.is_live(
319            &awp_types::ConsentRequirement {
320                scope: ConsentScope::PersistentProfile,
321                policy_version: record.receipt.policy_version.clone(),
322            },
323            Utc::now(),
324        )
325        && let Err(error) = state.store.add_visitor(day, &record.receipt.subject_ref).await
326    {
327        tracing::warn!(error = %error, "awp beacon visitor not recorded");
328    }
329    no_content()
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn paths_lose_their_queries_and_names_are_tokens() {
338        assert_eq!(clean_path("/pricing?email=a@b.example#top").as_deref(), Some("/pricing"));
339        assert_eq!(clean_path("pricing"), None);
340        assert_eq!(clean_name("signup.completed").as_deref(), Some("signup.completed"));
341        assert_eq!(clean_name("Sign Up"), None);
342    }
343}