Skip to main content

adk_drivers/analytics/
mod.rs

1//! Analytics and search-console drivers (spec 3.5 §7.12, §7.13): read-only metrics, each a
2//! [`KpiSource`] for the KPI tracker.
3//!
4//! | Tool | Effect class | Side | Default cap |
5//! |---|---|---|---|
6//! | `analytics_metric` | `read` | back office | Read |
7//! | `search_console_performance` | `read` | back office | Read |
8//!
9//! | Adapter | Contract | Feature |
10//! |---|---|---|
11//! | [`InMemoryAnalytics`], [`InMemorySearchConsole`] | [`AnalyticsDriver`], [`SearchConsoleDriver`] | — |
12//! | `PlausibleAnalytics`: the Plausible Stats API v2, cookieless and self-hostable | [`AnalyticsDriver`] | `plausible` |
13//! | `SearchAnalyticsApi`: a Search Analytics `query` endpoint, as Google Search Console serves it | [`SearchConsoleDriver`] | `search-console` |
14
15use std::collections::BTreeMap;
16use std::sync::{Arc, Mutex, PoisonError};
17
18use adk_core::Tool;
19use adk_kernel::drivers::EffectClass;
20use async_trait::async_trait;
21use chrono::{DateTime, NaiveDate, Utc};
22use serde::{Deserialize, Serialize};
23use serde_json::{Value, json};
24use uuid::Uuid;
25
26use crate::class::{AutonomyCap, Side, ToolSpec};
27use crate::email::time_arg;
28use crate::error::{DriverError, Result};
29use crate::metrics::{KpiSource, unknown_metric};
30use crate::outbound::str_arg;
31use crate::tools::{DriverTool, spec};
32
33#[cfg(feature = "plausible")]
34mod plausible;
35#[cfg(feature = "search-console")]
36mod search_console;
37
38#[cfg(feature = "plausible")]
39pub use plausible::PlausibleAnalytics;
40#[cfg(feature = "search-console")]
41pub use search_console::SearchAnalyticsApi;
42
43/// One metric over a window (spec 3.5 §7.12).
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46#[non_exhaustive]
47pub struct MetricQuery {
48    /// The metric, such as `visitors`.
49    pub metric: String,
50    /// The start, inclusive.
51    pub from: DateTime<Utc>,
52    /// The end, exclusive.
53    pub to: DateTime<Utc>,
54    /// Filters by dimension, such as `event:page` = `/pricing`.
55    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
56    pub filters: BTreeMap<String, String>,
57}
58
59impl MetricQuery {
60    /// `metric` over `[from, to)`, unfiltered.
61    pub fn new(metric: impl Into<String>, from: DateTime<Utc>, to: DateTime<Utc>) -> Self {
62        Self { metric: metric.into(), from, to, filters: BTreeMap::new() }
63    }
64
65    /// Adds a filter.
66    #[must_use]
67    pub fn filter(mut self, dimension: impl Into<String>, value: impl Into<String>) -> Self {
68        self.filters.insert(dimension.into(), value.into());
69        self
70    }
71
72    /// Refuses an empty or reversed window.
73    pub(crate) fn check(&self) -> Result<()> {
74        if self.to <= self.from {
75            return Err(DriverError::invalid("a metric window ends after it starts"));
76        }
77        Ok(())
78    }
79}
80
81/// The days `[from, to)` covers, as the first and last calendar day in UTC.
82pub(crate) fn day_range(from: DateTime<Utc>, to: DateTime<Utc>) -> (NaiveDate, NaiveDate) {
83    let last = to - chrono::Duration::seconds(1);
84    (from.date_naive(), last.date_naive().max(from.date_naive()))
85}
86
87/// A site analytics service (spec 3.5 §7.12, §7.13): reads metrics, never writes.
88#[async_trait]
89pub trait AnalyticsDriver: Send + Sync {
90    /// The adapter's name.
91    fn name(&self) -> &str;
92
93    /// The metrics it answers.
94    fn metrics(&self) -> Vec<String>;
95
96    /// The value of `query`, or `None` when the service has no data for the window.
97    ///
98    /// # Errors
99    ///
100    /// Returns [`DriverError::Invalid`] for a metric it does not answer or a reversed
101    /// window, and the service's errors.
102    async fn metric(&self, query: &MetricQuery) -> Result<Option<f64>>;
103}
104
105/// Search performance over a window (spec 3.5 §7.12): SEO from a search console.
106#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase")]
108#[non_exhaustive]
109pub struct SearchPerformance {
110    /// Clicks from search results.
111    pub clicks: f64,
112    /// Times a result was shown.
113    pub impressions: f64,
114    /// Clicks per impression.
115    pub ctr: f64,
116    /// The average position, 1 at the top.
117    pub position: f64,
118}
119
120/// What a search-performance read is narrowed to.
121#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase")]
123#[non_exhaustive]
124pub struct SearchFilter {
125    /// One search query.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub query: Option<String>,
128    /// One page.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub page: Option<String>,
131}
132
133/// A search console (spec 3.5 §7.12, §7.13): reads search performance, never writes.
134#[async_trait]
135pub trait SearchConsoleDriver: Send + Sync {
136    /// The adapter's name.
137    fn name(&self) -> &str;
138
139    /// Performance over the days of `[from, to)`, or `None` when there is no data.
140    ///
141    /// # Errors
142    ///
143    /// Returns [`DriverError::Invalid`] for a reversed window, and the service's errors.
144    async fn performance(
145        &self,
146        from: DateTime<Utc>,
147        to: DateTime<Utc>,
148        filter: &SearchFilter,
149    ) -> Result<Option<SearchPerformance>>;
150}
151
152/// The metrics of an [`AnalyticsDriver`] as a [`KpiSource`] named `analytics`, its metrics
153/// prefixed `analytics.`.
154///
155/// # Example
156///
157/// ```rust
158/// use std::sync::Arc;
159/// use adk_drivers::KpiSource;
160/// use adk_drivers::analytics::{AnalyticsMetrics, InMemoryAnalytics};
161///
162/// # futures::executor::block_on(async {
163/// let now = chrono::Utc::now();
164/// let analytics = InMemoryAnalytics::new().with("visitors", now, 40.0);
165/// let source = AnalyticsMetrics::new(Arc::new(analytics));
166/// let value = source.read(uuid::Uuid::nil(), "analytics.visitors", now - chrono::Duration::days(1), now + chrono::Duration::days(1)).await.unwrap();
167/// assert_eq!(value, Some(40.0));
168/// # });
169/// ```
170pub struct AnalyticsMetrics {
171    driver: Arc<dyn AnalyticsDriver>,
172}
173
174impl AnalyticsMetrics {
175    /// The source over `driver`.
176    pub fn new(driver: Arc<dyn AnalyticsDriver>) -> Self {
177        Self { driver }
178    }
179}
180
181impl AnalyticsMetrics {
182    /// The metrics it measures, as KPIs name them.
183    pub fn metrics(&self) -> Vec<String> {
184        self.driver.metrics().into_iter().map(|metric| format!("analytics.{metric}")).collect()
185    }
186
187    /// The value of `metric` over `[from, to)`; `None` when there is no data for the
188    /// window.
189    ///
190    /// # Errors
191    ///
192    /// Returns [`DriverError::Invalid`] for a metric it does
193    /// not measure, and the service's errors.
194    pub async fn measure(
195        &self,
196        metric: &str,
197        from: DateTime<Utc>,
198        to: DateTime<Utc>,
199    ) -> Result<Option<f64>> {
200        let Some(name) = metric.strip_prefix("analytics.") else {
201            return Err(unknown_metric("analytics", self.metrics(), metric));
202        };
203        self.driver.metric(&MetricQuery::new(name, from, to)).await
204    }
205}
206
207#[async_trait]
208impl KpiSource for AnalyticsMetrics {
209    fn name(&self) -> &str {
210        "analytics"
211    }
212
213    async fn read(
214        &self,
215        _site: Uuid,
216        metric: &str,
217        from: DateTime<Utc>,
218        to: DateTime<Utc>,
219    ) -> adk_kernel::Result<Option<f64>> {
220        Ok(self.measure(metric, from, to).await?)
221    }
222}
223
224/// The metrics of a [`SearchConsoleDriver`] as a [`KpiSource`] named `search`:
225/// `search.clicks`, `search.impressions`, `search.ctr` and `search.position`.
226pub struct SearchMetrics {
227    driver: Arc<dyn SearchConsoleDriver>,
228}
229
230impl SearchMetrics {
231    /// The source over `driver`.
232    pub fn new(driver: Arc<dyn SearchConsoleDriver>) -> Self {
233        Self { driver }
234    }
235}
236
237impl SearchMetrics {
238    /// The metrics it measures, as KPIs name them.
239    pub fn metrics(&self) -> Vec<String> {
240        ["search.clicks", "search.impressions", "search.ctr", "search.position"]
241            .map(String::from)
242            .to_vec()
243    }
244
245    /// The value of `metric` over `[from, to)`; `None` when there is no data for the
246    /// window.
247    ///
248    /// # Errors
249    ///
250    /// Returns [`DriverError::Invalid`] for a metric it does
251    /// not measure, and the service's errors.
252    pub async fn measure(
253        &self,
254        metric: &str,
255        from: DateTime<Utc>,
256        to: DateTime<Utc>,
257    ) -> Result<Option<f64>> {
258        if !self.metrics().iter().any(|known| known == metric) {
259            return Err(unknown_metric("search", self.metrics(), metric));
260        }
261        let Some(performance) = self.driver.performance(from, to, &SearchFilter::default()).await?
262        else {
263            return Ok(None);
264        };
265        Ok(Some(match metric {
266            "search.clicks" => performance.clicks,
267            "search.impressions" => performance.impressions,
268            "search.ctr" => performance.ctr,
269            _ => performance.position,
270        }))
271    }
272}
273
274#[async_trait]
275impl KpiSource for SearchMetrics {
276    fn name(&self) -> &str {
277        "search"
278    }
279
280    async fn read(
281        &self,
282        _site: Uuid,
283        metric: &str,
284        from: DateTime<Utc>,
285        to: DateTime<Utc>,
286    ) -> adk_kernel::Result<Option<f64>> {
287        Ok(self.measure(metric, from, to).await?)
288    }
289}
290
291/// Analytics in process memory: daily values per metric, summed over a window, for tests
292/// and as the hermetic reference of the [`AnalyticsDriver`] conformance suite.
293#[derive(Debug, Default)]
294pub struct InMemoryAnalytics {
295    days: Mutex<BTreeMap<(String, NaiveDate), f64>>,
296}
297
298impl InMemoryAnalytics {
299    /// No data.
300    pub fn new() -> Self {
301        Self::default()
302    }
303
304    /// Records `value` of `metric` on the day of `at`.
305    #[must_use]
306    pub fn with(self, metric: &str, at: DateTime<Utc>, value: f64) -> Self {
307        self.record(metric, at, value);
308        self
309    }
310
311    /// Adds `value` to `metric` on the day of `at`.
312    pub fn record(&self, metric: &str, at: DateTime<Utc>, value: f64) {
313        *self
314            .days
315            .lock()
316            .unwrap_or_else(PoisonError::into_inner)
317            .entry((metric.to_string(), at.date_naive()))
318            .or_default() += value;
319    }
320}
321
322#[async_trait]
323impl AnalyticsDriver for InMemoryAnalytics {
324    fn name(&self) -> &str {
325        "in-memory"
326    }
327
328    fn metrics(&self) -> Vec<String> {
329        let days = self.days.lock().unwrap_or_else(PoisonError::into_inner);
330        let mut metrics: Vec<String> = days.keys().map(|(metric, _)| metric.clone()).collect();
331        metrics.dedup();
332        metrics
333    }
334
335    async fn metric(&self, query: &MetricQuery) -> Result<Option<f64>> {
336        query.check()?;
337        if !query.filters.is_empty() {
338            return Err(DriverError::unsupported("in-memory analytics", "filters"));
339        }
340        let (first, last) = day_range(query.from, query.to);
341        let days = self.days.lock().unwrap_or_else(PoisonError::into_inner);
342        if !days.keys().any(|(metric, _)| *metric == query.metric) {
343            return Err(DriverError::invalid(format!(
344                "in-memory analytics has no metric `{}`",
345                query.metric
346            )));
347        }
348        let values: Vec<f64> = days
349            .iter()
350            .filter(|((metric, day), _)| *metric == query.metric && *day >= first && *day <= last)
351            .map(|(_, value)| *value)
352            .collect();
353        Ok((!values.is_empty()).then(|| values.iter().sum()))
354    }
355}
356
357/// A search console in process memory: daily clicks, impressions and position, for tests
358/// and as the hermetic reference of the [`SearchConsoleDriver`] conformance suite.
359#[derive(Debug, Default)]
360pub struct InMemorySearchConsole {
361    days: Mutex<BTreeMap<NaiveDate, (f64, f64, f64)>>,
362}
363
364impl InMemorySearchConsole {
365    /// No data.
366    pub fn new() -> Self {
367        Self::default()
368    }
369
370    /// Records a day of `clicks`, `impressions` and average `position`.
371    #[must_use]
372    pub fn with_day(self, day: NaiveDate, clicks: f64, impressions: f64, position: f64) -> Self {
373        self.days
374            .lock()
375            .unwrap_or_else(PoisonError::into_inner)
376            .insert(day, (clicks, impressions, position));
377        self
378    }
379}
380
381/// Days of `(clicks, impressions, position)` combined: sums, the ratio, and the
382/// impression-weighted position.
383pub(crate) fn combine(
384    days: impl IntoIterator<Item = (f64, f64, f64)>,
385) -> Option<SearchPerformance> {
386    let (mut clicks, mut impressions, mut weighted, mut any) = (0.0, 0.0, 0.0, false);
387    for (day_clicks, day_impressions, position) in days {
388        any = true;
389        clicks += day_clicks;
390        impressions += day_impressions;
391        weighted += position * day_impressions;
392    }
393    any.then(|| SearchPerformance {
394        clicks,
395        impressions,
396        ctr: if impressions > 0.0 { clicks / impressions } else { 0.0 },
397        position: if impressions > 0.0 { weighted / impressions } else { 0.0 },
398    })
399}
400
401#[async_trait]
402impl SearchConsoleDriver for InMemorySearchConsole {
403    fn name(&self) -> &str {
404        "in-memory"
405    }
406
407    async fn performance(
408        &self,
409        from: DateTime<Utc>,
410        to: DateTime<Utc>,
411        filter: &SearchFilter,
412    ) -> Result<Option<SearchPerformance>> {
413        if to <= from {
414            return Err(DriverError::invalid("a metric window ends after it starts"));
415        }
416        if filter.query.is_some() || filter.page.is_some() {
417            return Err(DriverError::unsupported("in-memory search console", "filters"));
418        }
419        let (first, last) = day_range(from, to);
420        let days = self.days.lock().unwrap_or_else(PoisonError::into_inner);
421        Ok(combine(days.range(first..=last).map(|(_, day)| *day)))
422    }
423}
424
425fn analytics_schema() -> Value {
426    json!({
427        "type": "object",
428        "properties": {
429            "metric": {"type": "string", "description": "Such as visitors, pageviews or bounce_rate"},
430            "from": {"type": "string", "format": "date-time"},
431            "to": {"type": "string", "format": "date-time"},
432            "filters": {"type": "object", "additionalProperties": {"type": "string"}, "description": "Dimension to value, such as {\"event:page\": \"/pricing\"}"}
433        },
434        "required": ["metric", "from", "to"]
435    })
436}
437
438fn search_schema() -> Value {
439    json!({
440        "type": "object",
441        "properties": {
442            "from": {"type": "string", "format": "date-time"},
443            "to": {"type": "string", "format": "date-time"},
444            "query": {"type": "string"},
445            "page": {"type": "string"}
446        },
447        "required": ["from", "to"]
448    })
449}
450
451/// The analytics class's tools (spec 3.5 §7.13).
452pub const ANALYTICS_TOOLS: &[ToolSpec] = &[ToolSpec {
453    name: "analytics_metric",
454    description: "Read one site metric over a window, such as visitors or pageviews.",
455    class: EffectClass::Read,
456    also: None,
457    side: Side::BackOffice,
458    cap: AutonomyCap::Read,
459    budget_arg: None,
460    schema: analytics_schema,
461}];
462
463/// The search-console class's tools (spec 3.5 §7.13).
464pub const SEARCH_CONSOLE_TOOLS: &[ToolSpec] = &[ToolSpec {
465    name: "search_console_performance",
466    description: "Read search clicks, impressions, click-through rate and average position over a window.",
467    class: EffectClass::Read,
468    also: None,
469    side: Side::BackOffice,
470    cap: AutonomyCap::Read,
471    budget_arg: None,
472    schema: search_schema,
473}];
474
475/// The analytics tools over `driver`.
476pub fn analytics_tools(driver: Arc<dyn AnalyticsDriver>) -> Vec<Arc<dyn Tool>> {
477    let name = format!("analytics/{}", driver.name());
478    vec![DriverTool::shared(spec(ANALYTICS_TOOLS, "analytics_metric"), &name, move |args| {
479        let driver = Arc::clone(&driver);
480        Box::pin(async move {
481            let mut query = MetricQuery::new(
482                str_arg(&args, "metric")?,
483                time_arg(&args, "from")?,
484                time_arg(&args, "to")?,
485            );
486            if let Some(filters) = args.get("filters").and_then(Value::as_object) {
487                for (dimension, value) in filters {
488                    let value = value
489                        .as_str()
490                        .ok_or_else(|| DriverError::invalid("a filter value is a string"))?;
491                    query = query.filter(dimension.as_str(), value);
492                }
493            }
494            let value = driver.metric(&query).await?;
495            Ok(
496                json!({ "metric": query.metric, "from": query.from, "to": query.to, "value": value }),
497            )
498        })
499    })]
500}
501
502/// The search-console tools over `driver`.
503pub fn search_console_tools(driver: Arc<dyn SearchConsoleDriver>) -> Vec<Arc<dyn Tool>> {
504    let name = format!("search_console/{}", driver.name());
505    vec![DriverTool::shared(
506        spec(SEARCH_CONSOLE_TOOLS, "search_console_performance"),
507        &name,
508        move |args| {
509            let driver = Arc::clone(&driver);
510            Box::pin(async move {
511                let filter = SearchFilter {
512                    query: args.get("query").and_then(Value::as_str).map(str::to_string),
513                    page: args.get("page").and_then(Value::as_str).map(str::to_string),
514                };
515                let performance = driver
516                    .performance(time_arg(&args, "from")?, time_arg(&args, "to")?, &filter)
517                    .await?;
518                Ok(json!({ "performance": performance }))
519            })
520        },
521    )]
522}