1use 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
40pub const BEACON_PATH: &str = "/awp/v2/beacon";
42pub const MAX_BEACON_BODY: usize = 2 * 1024;
44
45#[async_trait]
47pub trait BeaconStore: Send + Sync {
48 async fn add(&self, day: NaiveDate, metric: &str, count: u64) -> StoreResult<()>;
50
51 async fn add_visitor(&self, day: NaiveDate, visitor: &str) -> StoreResult<()>;
53
54 async fn total(&self, metric: &str, from: NaiveDate, to: NaiveDate) -> StoreResult<u64>;
57
58 async fn forget_visitor(&self, visitor: &str) -> StoreResult<u64>;
61}
62
63pub(crate) fn forgotten() -> String {
65 format!("erased:{}", Uuid::new_v4().simple())
66}
67
68pub struct BeaconSubjectData {
71 store: Arc<dyn BeaconStore>,
72}
73
74impl BeaconSubjectData {
75 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#[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 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#[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 pub fn new(store: Arc<dyn BeaconStore>) -> Self {
201 Self { store }
202 }
203
204 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 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
261fn 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 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 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 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}