use std::sync::Arc;
use adk_core::audit_log::AuditActor;
use adk_core::principal::SubjectRef;
use adk_core::{
AdkError, DurableRunStore, ErrorCategory, ErrorComponent, GovernanceControl, RequestContext,
RunFilter, RunState,
};
use async_trait::async_trait;
use axum::{
Extension, Json,
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use super::error_details;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RunningRuns {
Park,
Cancel,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FreezeReport {
pub parked_runs: usize,
pub cancelled_runs: usize,
}
#[async_trait]
pub trait FreezeDelegate: Send + Sync {
async fn freeze(&self, reason: &str, by: AuditActor) -> adk_core::Result<FreezeReport>;
async fn unfreeze(&self, by: AuditActor) -> adk_core::Result<()>;
fn running_runs(&self) -> RunningRuns {
RunningRuns::Park
}
}
#[derive(Clone)]
pub struct GovernanceController {
control: GovernanceControl,
run_stores: Vec<Arc<dyn DurableRunStore>>,
delegate: Option<Arc<dyn FreezeDelegate>>,
expose_error_details: bool,
admin_scope: String,
}
impl std::fmt::Debug for GovernanceController {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GovernanceController")
.field("control", &self.control)
.field("run_stores", &self.run_stores.len())
.field("delegate", &self.delegate.is_some())
.field("expose_error_details", &self.expose_error_details)
.field("admin_scope", &self.admin_scope)
.finish()
}
}
impl GovernanceController {
pub fn new(control: GovernanceControl) -> Self {
Self {
control,
run_stores: Vec::new(),
delegate: None,
expose_error_details: false,
admin_scope: crate::ADMIN_SCOPE.to_string(),
}
}
#[must_use]
pub fn with_error_details(mut self, expose: bool) -> Self {
self.expose_error_details = expose;
self
}
pub fn with_admin_scope(mut self, scope: impl Into<String>) -> Self {
self.admin_scope = scope.into();
self
}
pub fn with_run_store(mut self, store: Arc<dyn DurableRunStore>) -> Self {
if !self.run_stores.iter().any(|existing| Arc::ptr_eq(existing, &store)) {
self.run_stores.push(store);
}
self
}
pub fn with_freeze_delegate(mut self, delegate: Arc<dyn FreezeDelegate>) -> Self {
self.delegate = Some(delegate);
self
}
pub fn running_runs(&self) -> RunningRuns {
self.delegate.as_ref().map_or(RunningRuns::Cancel, |delegate| delegate.running_runs())
}
fn status(&self) -> GovernanceStatus {
GovernanceStatus {
frozen: self.control.is_frozen(),
reason: self.control.reason(),
mirrored: self.control.is_mirrored(),
stale: self.control.is_stale(),
running_runs: self.running_runs(),
parked_runs: None,
cancelled_runs: None,
error: None,
}
}
async fn cancel_running(&self) -> usize {
let mut cancelled = 0;
for store in &self.run_stores {
let running = store.list(RunFilter::default().states([RunState::Running])).await;
match running {
Ok(runs) => {
for run in runs {
match store.request_cancel(&run.run_id).await {
Ok(()) => cancelled += 1,
Err(error) => {
tracing::error!(run.id = %run.run_id, error = %error, "could not request cancellation of a running run")
}
}
}
}
Err(error) => {
tracing::error!(error = %error, "could not list running runs to cancel")
}
}
}
cancelled
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FreezeRequest {
#[serde(default)]
pub reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GovernanceStatus {
pub frozen: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
pub mirrored: bool,
pub stale: bool,
pub running_runs: RunningRuns,
#[serde(skip_serializing_if = "Option::is_none")]
pub parked_runs: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancelled_runs: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
fn admin_actor(caller: &RequestContext) -> AuditActor {
AuditActor {
on_behalf_of: Some(SubjectRef::human(caller.user_id.clone())),
..AuditActor::default()
}
}
fn administrator(
controller: &GovernanceController,
caller: Option<RequestContext>,
action: &str,
) -> Result<RequestContext, Response> {
let scope = &controller.admin_scope;
let refusal = |category, code, message: String| {
let error = AdkError::new(ErrorComponent::Server, category, code, message);
let status = StatusCode::from_u16(error.http_status_code())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
(status, Json(error.to_problem_json())).into_response()
};
let Some(caller) = caller else {
tracing::warn!(governance.action = action, "governance change refused: no caller");
return Err(refusal(
ErrorCategory::Unauthorized,
"governance.unauthenticated",
format!(
"{action} needs an authenticated administrator; configure a \
RequestContextExtractor that grants the `{scope}` scope"
),
));
};
if !caller.scopes.iter().any(|granted| granted == scope) {
tracing::warn!(
caller.user_id = %caller.user_id,
governance.action = action,
"governance change refused: the caller is not an administrator"
);
return Err(refusal(
ErrorCategory::Forbidden,
"governance.forbidden",
format!("{} may not {action}: it needs the `{scope}` scope", caller.user_id),
));
}
Ok(caller)
}
pub async fn freeze(
State(controller): State<GovernanceController>,
Extension(caller): Extension<Option<RequestContext>>,
Json(request): Json<FreezeRequest>,
) -> Response {
let caller = match administrator(&controller, caller, "freeze") {
Ok(caller) => caller,
Err(refusal) => return refusal,
};
let reason = request.reason.unwrap_or_else(|| "frozen by an administrator".to_string());
tracing::warn!(
caller.user_id = %caller.user_id,
governance.reason = %reason,
"governance freeze requested"
);
let actor = admin_actor(&caller);
let mut status = controller.status();
let written = match &controller.delegate {
Some(delegate) => match delegate.freeze(&reason, actor).await {
Ok(report) => {
status.parked_runs = Some(report.parked_runs);
status.cancelled_runs = Some(report.cancelled_runs);
tracing::warn!(
runs.parked = report.parked_runs,
runs.cancel_requested = report.cancelled_runs,
"governance freeze applied by the delegate"
);
Ok(())
}
Err(error) => Err(error),
},
None => {
let written = controller.control.freeze_recorded(reason, actor).await;
let cancelled = controller.cancel_running().await;
tracing::warn!(runs.cancel_requested = cancelled, "governance freeze applied");
status.parked_runs = Some(0);
status.cancelled_runs = Some(cancelled);
written
}
};
let current = controller.status();
status.frozen = current.frozen;
status.reason = current.reason;
status.stale = current.stale;
match written {
Ok(()) => Json(status).into_response(),
Err(error) => {
status.error = Some(error_details::display(&error, controller.expose_error_details));
(StatusCode::SERVICE_UNAVAILABLE, Json(status)).into_response()
}
}
}
pub async fn unfreeze(
State(controller): State<GovernanceController>,
Extension(caller): Extension<Option<RequestContext>>,
) -> Response {
let caller = match administrator(&controller, caller, "unfreeze") {
Ok(caller) => caller,
Err(refusal) => return refusal,
};
tracing::warn!(caller.user_id = %caller.user_id, "governance unfreeze requested");
let actor = admin_actor(&caller);
let lifted = match &controller.delegate {
Some(delegate) => delegate.unfreeze(actor).await,
None => controller.control.unfreeze_recorded(actor).await,
};
match lifted {
Ok(()) => Json(controller.status()).into_response(),
Err(error) => {
let mut status = controller.status();
status.error = Some(error_details::display(&error, controller.expose_error_details));
(StatusCode::SERVICE_UNAVAILABLE, Json(status)).into_response()
}
}
}
pub async fn status(State(controller): State<GovernanceController>) -> Json<GovernanceStatus> {
Json(controller.status())
}