1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46#[non_exhaustive]
47pub struct MetricQuery {
48 pub metric: String,
50 pub from: DateTime<Utc>,
52 pub to: DateTime<Utc>,
54 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
56 pub filters: BTreeMap<String, String>,
57}
58
59impl MetricQuery {
60 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 #[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 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
81pub(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#[async_trait]
89pub trait AnalyticsDriver: Send + Sync {
90 fn name(&self) -> &str;
92
93 fn metrics(&self) -> Vec<String>;
95
96 async fn metric(&self, query: &MetricQuery) -> Result<Option<f64>>;
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase")]
108#[non_exhaustive]
109pub struct SearchPerformance {
110 pub clicks: f64,
112 pub impressions: f64,
114 pub ctr: f64,
116 pub position: f64,
118}
119
120#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase")]
123#[non_exhaustive]
124pub struct SearchFilter {
125 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub query: Option<String>,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub page: Option<String>,
131}
132
133#[async_trait]
135pub trait SearchConsoleDriver: Send + Sync {
136 fn name(&self) -> &str;
138
139 async fn performance(
145 &self,
146 from: DateTime<Utc>,
147 to: DateTime<Utc>,
148 filter: &SearchFilter,
149 ) -> Result<Option<SearchPerformance>>;
150}
151
152pub struct AnalyticsMetrics {
171 driver: Arc<dyn AnalyticsDriver>,
172}
173
174impl AnalyticsMetrics {
175 pub fn new(driver: Arc<dyn AnalyticsDriver>) -> Self {
177 Self { driver }
178 }
179}
180
181impl AnalyticsMetrics {
182 pub fn metrics(&self) -> Vec<String> {
184 self.driver.metrics().into_iter().map(|metric| format!("analytics.{metric}")).collect()
185 }
186
187 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
224pub struct SearchMetrics {
227 driver: Arc<dyn SearchConsoleDriver>,
228}
229
230impl SearchMetrics {
231 pub fn new(driver: Arc<dyn SearchConsoleDriver>) -> Self {
233 Self { driver }
234 }
235}
236
237impl SearchMetrics {
238 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 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#[derive(Debug, Default)]
294pub struct InMemoryAnalytics {
295 days: Mutex<BTreeMap<(String, NaiveDate), f64>>,
296}
297
298impl InMemoryAnalytics {
299 pub fn new() -> Self {
301 Self::default()
302 }
303
304 #[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 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#[derive(Debug, Default)]
360pub struct InMemorySearchConsole {
361 days: Mutex<BTreeMap<NaiveDate, (f64, f64, f64)>>,
362}
363
364impl InMemorySearchConsole {
365 pub fn new() -> Self {
367 Self::default()
368 }
369
370 #[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
381pub(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
451pub 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
463pub 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
475pub 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
502pub 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}