Skip to main content

adk_website/
observability.rs

1//! Observability (spec 3.5 §7.24): spans, metrics and the site view.
2//!
3//! | Span | Emitted by |
4//! |---|---|
5//! | `website.onboarding.{stage}` | [`crate::onboarding::Stage::span`], [`crate::onboarding::OnboardingProgress`] |
6//! | `site.probe` | [`crate::incident::GuardianProbe::run`] |
7//! | `website.job.{job}` | the jobs' runs: `website.job.protect` (incident path), `website.job.weekly-review` (review composer) |
8//! | `site.release` | `adk-site`'s pipeline: every release, with its sequence, source and items |
9//! | `kernel.signal` | [`crate::edge::adapters::KernelSignals`]: every signal the edge files, with its kind, id and emitter |
10//! | `awp.request`, `awp.capability.call` | the agent edge |
11//!
12//! Metrics are `tracing` events whose fields follow the OpenTelemetry metrics layer's
13//! prefixes (`histogram.`, `counter.`, `monotonic_counter.`), so `adk-telemetry`'s export
14//! turns them into instruments: every KPI source's readings, time to detect and restore,
15//! held decisions and their latency, autonomy changes, and spend by category. The site view
16//! ([`SiteView`]) is what every surface shows: status, release, KPIs, jobs and their levels,
17//! signals and the wallet.
18
19use std::sync::Arc;
20
21use adk_core::{AdkError, Result};
22use adk_harness::website::SiteRuntime;
23use adk_kernel::PartitionId;
24use adk_kernel::charter::{
25    AutonomyStore, KpiReview, KpiSource, KpiTracker, SignalFilter, SignalStore,
26};
27use awp_types::AutonomyLevel;
28use chrono::{DateTime, Datelike, Utc};
29use serde::{Deserialize, Serialize};
30
31use crate::incident::{Incident, StatusRecord, StatusSink};
32use crate::wallet::WalletKpi;
33
34/// The site's spans (spec 3.5 §7.24).
35pub mod spans {
36    /// Prefix of the onboarding stages' spans.
37    pub const ONBOARDING: &str = "website.onboarding";
38    /// A release: `adk-site`'s pipeline span.
39    pub const SITE_RELEASE: &str = adk_site::pipeline::RELEASE_SPAN;
40    /// A probe.
41    pub const SITE_PROBE: &str = "site.probe";
42    /// A request at the edge.
43    pub const AWP_REQUEST: &str = "awp.request";
44    /// A capability call at the edge.
45    pub const AWP_CAPABILITY_CALL: &str = "awp.capability.call";
46    /// A signal filed in the back office.
47    pub const KERNEL_SIGNAL: &str = "kernel.signal";
48    /// Prefix of the jobs' spans.
49    pub const JOB: &str = "website.job";
50}
51
52/// Records one KPI reading from `source` (spec 3.5 §7.24 "metrics for every KPI source").
53pub fn record_kpi(source: &str, kpi: &str, value: f64) {
54    tracing::info!(
55        website.kpi.source = source,
56        website.kpi = kpi,
57        histogram.website.kpi.value = value,
58        "website.kpi"
59    );
60}
61
62/// Records an incident's time to detect and, once rolled back, to restore, in milliseconds
63/// (spec 3.5 §7.24).
64pub fn record_incident(
65    incident: &Incident,
66    drift_since: DateTime<Utc>,
67    restored_at: Option<DateTime<Utc>>,
68) {
69    let detect = (incident.opened_at - drift_since).num_milliseconds().max(0);
70    tracing::info!(website.incident = %incident.id, histogram.website.incident.time_to_detect_ms = detect, "website.incident.detected");
71    if let Some(restored) = restored_at {
72        let restore = (restored - incident.opened_at).num_milliseconds().max(0);
73        tracing::info!(website.incident = %incident.id, histogram.website.incident.time_to_restore_ms = restore, "website.incident.restored");
74    }
75}
76
77/// Records a held decision and, once answered, its latency (spec 3.5 §7.24).
78pub fn record_held_decision(tool: &str, latency: Option<chrono::Duration>) {
79    tracing::info!(
80        website.tool = tool,
81        monotonic_counter.website.decisions.held = 1u64,
82        "website.decision.held"
83    );
84    if let Some(latency) = latency {
85        tracing::info!(
86            website.tool = tool,
87            histogram.website.decisions.latency_ms = latency.num_milliseconds().max(0),
88            "website.decision.answered"
89        );
90    }
91}
92
93/// Records an autonomy change (spec 3.5 §7.24).
94pub fn record_autonomy_change(job: &str, from: Option<AutonomyLevel>, to: AutonomyLevel) {
95    tracing::info!(website.job = job, from = ?from, to = ?to, monotonic_counter.website.autonomy.changes = 1u64, "website.autonomy.changed");
96}
97
98/// Records spend in a category, in major units (spec 3.5 §7.24).
99pub fn record_spend(category: &str, amount: f64) {
100    tracing::info!(
101        website.spend.category = category,
102        counter.website.spend = amount,
103        "website.spend"
104    );
105}
106
107/// What every surface shows of a site (spec 3.5 §7.24).
108#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
109#[serde(rename_all = "camelCase")]
110pub struct SiteView {
111    /// The status.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub status: Option<StatusRecord>,
114    /// The release served.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub release: Option<u64>,
117    /// This week's KPIs.
118    pub kpis: Vec<KpiReview>,
119    /// Each job and its level.
120    pub jobs: Vec<(String, AutonomyLevel)>,
121    /// Signals waiting in the back office.
122    pub open_signals: usize,
123    /// The month's spend, in major units.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub spend_this_month: Option<f64>,
126}
127
128/// What [`SiteView::read`] reads.
129pub struct SiteViewSources {
130    /// The site runtime.
131    pub runtime: Arc<SiteRuntime>,
132    /// The status.
133    pub status: Arc<dyn StatusSink>,
134    /// The KPI tracker.
135    pub tracker: KpiTracker,
136    /// The jobs' levels.
137    pub autonomy: Arc<dyn AutonomyStore>,
138    /// The signals and the back office's partition.
139    pub signals: (Arc<dyn SignalStore>, PartitionId),
140    /// The wallet, when the site has one.
141    pub wallet: Option<Arc<WalletKpi>>,
142}
143
144impl SiteView {
145    /// Reads the view at `now`.
146    ///
147    /// # Errors
148    ///
149    /// Returns a store's error.
150    pub async fn read(sources: &SiteViewSources, now: DateTime<Utc>) -> Result<Self> {
151        let store = |e: adk_kernel::KernelError| AdkError::config(e.to_string());
152        let site = sources.runtime.site().id;
153        let today = now.date_naive();
154        let monday =
155            today - chrono::Duration::days(i64::from(today.weekday().num_days_from_monday()));
156        let jobs = sources
157            .autonomy
158            .list(site)
159            .await
160            .map_err(store)?
161            .into_iter()
162            .map(|job| (job.job, job.level))
163            .collect();
164        let (signals, partition) = &sources.signals;
165        let open_signals = signals
166            .list(&SignalFilter::default().partition(partition.clone()))
167            .await
168            .map_err(store)?
169            .iter()
170            .filter(|record| record.open)
171            .count();
172        let spend_this_month = match &sources.wallet {
173            Some(wallet) => {
174                let start = today
175                    .with_day(1)
176                    .and_then(|day| day.and_hms_opt(0, 0, 0))
177                    .map_or(now, |start| start.and_utc());
178                wallet.read(site, "spend", start, now).await.map_err(store)?
179            }
180            None => None,
181        };
182        Ok(Self {
183            status: sources.status.get(site).await?,
184            release: sources.runtime.pipeline().previous().await.map(|p| p.manifest.seq),
185            kpis: sources.tracker.review(monday).await.map_err(store)?,
186            jobs,
187            open_signals,
188            spend_this_month,
189        })
190    }
191}