use std::sync::Arc;
use adk_core::audit_log::{AuditRecordDraft, AuditRecorder};
use adk_core::{Clock, Result, SystemClock};
use adk_kernel::charter::KpiSource;
use adk_server::awp::BeaconStore;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::Value;
use uuid::Uuid;
use super::{check_site, total};
pub struct EdgeMeter {
inner: Arc<dyn AuditRecorder>,
counts: Arc<dyn BeaconStore>,
clock: Arc<dyn Clock>,
}
impl std::fmt::Debug for EdgeMeter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EdgeMeter").finish_non_exhaustive()
}
}
impl EdgeMeter {
pub fn new(inner: Arc<dyn AuditRecorder>, counts: Arc<dyn BeaconStore>) -> Self {
Self { inner, counts, clock: Arc::new(SystemClock) }
}
#[must_use]
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
fn metrics(draft: &AuditRecordDraft) -> Vec<String> {
let field = |name: &str| draft.ext.get(name).and_then(Value::as_str).unwrap_or_default();
let held = match draft.action.as_str() {
"awp.capability.called" => false,
"awp.capability.held" => true,
"awp.request.verified" => {
let surface = field("awp.surface");
if surface.is_empty() {
return Vec::new();
}
return vec!["agent_discovery".to_string(), format!("agent_discovery:{surface}")];
}
_ => return Vec::new(),
};
let (capability, binding, tier) =
(field("awp.capability"), field("awp.binding"), field("awp.tier"));
let mut metrics = vec!["calls".to_string(), format!("calls:{capability}")];
if held {
metrics.push("held".to_string());
}
if !tier.is_empty() && tier != "public" {
metrics.push("agent_calls".to_string());
metrics.push(format!("agent_calls:{binding}"));
metrics.push(format!("agent_calls:{capability}"));
}
metrics
}
}
#[async_trait]
impl AuditRecorder for EdgeMeter {
fn digest(&self, value: &Value) -> String {
self.inner.digest(value)
}
async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
let metrics = Self::metrics(&draft);
self.inner.record(draft).await?;
let day = self.clock.now().date_naive();
for metric in metrics {
if let Err(error) = self.counts.add(day, &metric, 1).await {
tracing::warn!(metric = %metric, error = %error, "an edge call count was not recorded");
}
}
Ok(())
}
async fn seal(&self) -> Result<()> {
self.inner.seal().await
}
}
#[derive(Clone)]
pub struct AgentSearchKpi {
site: Uuid,
counts: Arc<dyn BeaconStore>,
}
impl std::fmt::Debug for AgentSearchKpi {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AgentSearchKpi").field("site", &self.site).finish_non_exhaustive()
}
}
impl AgentSearchKpi {
pub fn new(site: Uuid, counts: Arc<dyn BeaconStore>) -> Self {
Self { site, counts }
}
}
#[async_trait]
impl KpiSource for AgentSearchKpi {
fn name(&self) -> &str {
"agents"
}
async fn read(
&self,
site: Uuid,
metric: &str,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> adk_kernel::Result<Option<f64>> {
check_site("agents", self.site, site)?;
total("agents", &self.counts, metric, from, to).await
}
}