use std::sync::Arc;
use async_trait::async_trait;
use axum::Json;
use axum::Router;
use axum::extract::{Query, State};
use axum::routing::get;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::paths;
use super::routes::{Caller, ControlBackend};
use crate::error::{KernelError, Result};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RecordLine {
pub seq: u64,
pub at: DateTime<Utc>,
pub action: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kernel_action: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub decision: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outcome: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub how: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub surface: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_source: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy_ref: Option<String>,
}
impl RecordLine {
pub fn new(seq: u64, at: DateTime<Utc>, action: impl Into<String>) -> Self {
Self {
seq,
at,
action: action.into(),
kernel_action: None,
subject: None,
agent: None,
tool: None,
decision: None,
outcome: None,
how: None,
channel: None,
surface: None,
target: None,
title: None,
tool_source: None,
policy_ref: None,
}
}
#[must_use]
pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
self.subject = Some(subject.into());
self
}
#[must_use]
pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
self.agent = Some(agent.into());
self
}
#[must_use]
pub fn with_tool(mut self, tool: impl Into<String>) -> Self {
self.tool = Some(tool.into());
self
}
#[must_use]
pub fn with_decision(mut self, decision: impl Into<String>) -> Self {
self.decision = Some(decision.into());
self
}
#[must_use]
pub fn with_outcome(mut self, outcome: impl Into<String>) -> Self {
self.outcome = Some(outcome.into());
self
}
#[must_use]
pub fn with_how(mut self, how: impl Into<String>, channel: Option<&str>) -> Self {
self.how = Some(how.into());
self.channel = channel.map(str::to_string);
self
}
#[must_use]
pub fn with_channel(mut self, channel: impl Into<String>) -> Self {
self.channel = Some(channel.into());
self
}
#[must_use]
pub fn with_surface(mut self, surface: impl Into<String>) -> Self {
self.surface = Some(surface.into());
self
}
#[must_use]
pub fn with_kernel_action(mut self, action: impl Into<String>) -> Self {
self.kernel_action = Some(action.into());
self
}
#[must_use]
pub fn with_target(mut self, target: impl Into<String>) -> Self {
self.target = Some(target.into());
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn with_call(mut self, tool_source: impl Into<String>, policy_ref: Option<&str>) -> Self {
self.tool_source = Some(tool_source.into());
self.policy_ref = policy_ref.map(str::to_string);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RecordCheck {
pub valid: bool,
pub entries: u64,
pub checked_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub problem: Option<String>,
#[serde(default, skip_serializing_if = "Value::is_null")]
pub report: Value,
}
impl RecordCheck {
pub fn new(valid: bool, entries: u64, checked_at: DateTime<Utc>) -> Self {
Self { valid, entries, checked_at, problem: None, report: Value::Null }
}
#[must_use]
pub fn with_problem(mut self, problem: impl Into<String>) -> Self {
self.problem = Some(problem.into());
self
}
#[must_use]
pub fn with_report(mut self, report: Value) -> Self {
self.report = report;
self
}
}
#[async_trait]
pub trait RecordBook: Send + Sync {
async fn recent(&self, limit: usize) -> Result<Vec<RecordLine>>;
async fn check(&self) -> Result<RecordCheck>;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordQuery {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordResponse {
pub lines: Vec<RecordLine>,
}
type Backend = State<Arc<dyn ControlBackend>>;
pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
Router::new().route(paths::RECORD, get(recent)).route(paths::RECORD_CHECK, get(check))
}
fn book_of(backend: &dyn ControlBackend) -> Result<Arc<dyn RecordBook>> {
backend.kernel().and_then(|kernel| kernel.config().control.record.clone()).ok_or_else(|| {
KernelError::Config {
reason: "this kernel shows no record: set ControlPlaneConfig::with_record, as \
`adk-rust up` does over its signed audit log"
.into(),
}
})
}
async fn recent(
State(backend): Backend,
caller: Caller,
Query(query): Query<RecordQuery>,
) -> Result<Json<RecordResponse>> {
caller.require_operator("read the record")?;
let limit = query.limit.unwrap_or(20).clamp(1, 500);
Ok(Json(RecordResponse { lines: book_of(backend.as_ref())?.recent(limit).await? }))
}
async fn check(State(backend): Backend, caller: Caller) -> Result<Json<RecordCheck>> {
caller.require_operator("check the record")?;
Ok(Json(book_of(backend.as_ref())?.check().await?))
}