use std::collections::BTreeMap;
use std::sync::Arc;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use crate::principal::{AgentId, SubjectRef};
use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, ErrorDetails, Result, SystemClock};
pub const GOVERNANCE_CONFLICT_CODE: &str = "governance.conflict";
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum GovernanceScope {
Org,
Tenant(String),
Agent(AgentId),
}
impl GovernanceScope {
pub fn key(&self) -> String {
match self {
Self::Org => "org".to_string(),
Self::Tenant(tenant) => format!("tenant:{tenant}"),
Self::Agent(agent) => format!("agent:{agent}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GovernanceState {
pub scope: GovernanceScope,
pub frozen: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub issued_by: Option<SubjectRef>,
pub issued_at: DateTime<Utc>,
pub epoch: u64,
}
#[async_trait]
pub trait GovernanceStateStore: Send + Sync {
async fn get(&self, scope: &GovernanceScope) -> Result<Option<GovernanceState>>;
async fn set(
&self,
scope: GovernanceScope,
expected_epoch: u64,
frozen: bool,
reason: Option<String>,
issued_by: Option<SubjectRef>,
) -> Result<GovernanceState>;
async fn list(&self) -> Result<Vec<GovernanceState>>;
}
pub fn governance_conflict_error(
scope: &GovernanceScope,
expected_epoch: u64,
current_epoch: u64,
) -> AdkError {
let mut details = ErrorDetails::default();
details.metadata.insert("current_epoch".to_string(), current_epoch.into());
AdkError::new(
ErrorComponent::Agent,
ErrorCategory::Conflict,
GOVERNANCE_CONFLICT_CODE,
format!(
"governance state of '{}' is at epoch {current_epoch}, not {expected_epoch}; another \
change landed first, so re-read the state and decide again",
scope.key()
),
)
.with_details(details)
}
#[derive(Debug)]
pub struct InMemoryGovernanceStateStore {
states: Mutex<BTreeMap<String, GovernanceState>>,
clock: Arc<dyn Clock>,
}
impl Default for InMemoryGovernanceStateStore {
fn default() -> Self {
Self::new()
}
}
impl InMemoryGovernanceStateStore {
pub fn new() -> Self {
Self { states: Mutex::new(BTreeMap::new()), clock: Arc::new(SystemClock) }
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
}
#[async_trait]
impl GovernanceStateStore for InMemoryGovernanceStateStore {
async fn get(&self, scope: &GovernanceScope) -> Result<Option<GovernanceState>> {
Ok(self.states.lock().await.get(&scope.key()).cloned())
}
async fn set(
&self,
scope: GovernanceScope,
expected_epoch: u64,
frozen: bool,
reason: Option<String>,
issued_by: Option<SubjectRef>,
) -> Result<GovernanceState> {
let key = scope.key();
let mut states = self.states.lock().await;
let current_epoch = states.get(&key).map_or(0, |state| state.epoch);
if current_epoch != expected_epoch {
return Err(governance_conflict_error(&scope, expected_epoch, current_epoch));
}
let state = GovernanceState {
scope,
frozen,
reason,
issued_by,
issued_at: self.clock.now(),
epoch: current_epoch + 1,
};
states.insert(key, state.clone());
Ok(state)
}
async fn list(&self) -> Result<Vec<GovernanceState>> {
Ok(self.states.lock().await.values().cloned().collect())
}
}