adk_core/governance_state.rs
1//! Durable freeze state for the kill switch, shared by every replica.
2//!
3//! A [`GovernanceStateStore`] records whether an organisation, a tenant, or one agent is
4//! frozen, who froze it, and why. Every change is a compare-and-swap on the scope's
5//! `epoch`, so two operators who act at once cannot silently overwrite each other: the
6//! second sees `governance.conflict`, re-reads, and decides again. Replicas read the
7//! store to learn of a freeze issued anywhere; the store is the durable truth and any
8//! notification channel only shortens the time until a replica reads it.
9//!
10//! | Scope | Key ([`GovernanceScope::key`]) |
11//! |-------|-------------------------------|
12//! | [`Org`](GovernanceScope::Org) | `org` |
13//! | [`Tenant`](GovernanceScope::Tenant) | `tenant:{tenant}` |
14//! | [`Agent`](GovernanceScope::Agent) | `agent:{agent id}` |
15//!
16//! # Backend primitives
17//!
18//! | Backend | Compare-and-swap on the epoch |
19//! |---------|-------------------------------|
20//! | SQL | `INSERT ... ON CONFLICT DO NOTHING` for epoch 0, `UPDATE ... WHERE key = $1 AND epoch = $2` otherwise |
21//! | Redis | Lua compare of the epoch field |
22//! | MongoDB | `insert_one` for epoch 0, `updateOne` filtered on `epoch` otherwise |
23//! | Neo4j, Firestore | A transaction that reads the scope record and checks its epoch |
24
25use std::collections::BTreeMap;
26use std::sync::Arc;
27
28use async_trait::async_trait;
29use chrono::{DateTime, Utc};
30use serde::{Deserialize, Serialize};
31use tokio::sync::Mutex;
32
33use crate::principal::{AgentId, SubjectRef};
34use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, ErrorDetails, Result, SystemClock};
35
36/// Error code returned when a governance change carries an epoch that moved.
37pub const GOVERNANCE_CONFLICT_CODE: &str = "governance.conflict";
38
39/// What a governance state applies to.
40///
41/// # Example
42///
43/// ```rust
44/// use adk_core::governance_state::GovernanceScope;
45///
46/// assert_eq!(GovernanceScope::Tenant("acme".into()).key(), "tenant:acme");
47/// assert_eq!(serde_json::to_value(GovernanceScope::Org).unwrap(), "org");
48/// ```
49#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51#[non_exhaustive]
52pub enum GovernanceScope {
53 /// The whole organisation.
54 Org,
55 /// One tenant.
56 Tenant(String),
57 /// One agent.
58 Agent(AgentId),
59}
60
61impl GovernanceScope {
62 /// Returns the canonical storage key: `org`, `tenant:{tenant}`, or `agent:{id}`.
63 pub fn key(&self) -> String {
64 match self {
65 Self::Org => "org".to_string(),
66 Self::Tenant(tenant) => format!("tenant:{tenant}"),
67 Self::Agent(agent) => format!("agent:{agent}"),
68 }
69 }
70}
71
72/// The freeze state of one scope.
73///
74/// # Example
75///
76/// ```rust
77/// use adk_core::governance_state::{GovernanceScope, GovernanceState};
78///
79/// let state = GovernanceState {
80/// scope: GovernanceScope::Org,
81/// frozen: true,
82/// reason: Some("incident 42".into()),
83/// issued_by: None,
84/// issued_at: chrono::Utc::now(),
85/// epoch: 1,
86/// };
87/// assert_eq!(serde_json::to_value(&state).unwrap()["frozen"], true);
88/// ```
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "camelCase")]
91pub struct GovernanceState {
92 /// The scope the state applies to.
93 pub scope: GovernanceScope,
94 /// Whether new runs and further actions in the scope are refused.
95 pub frozen: bool,
96 /// Why the state was set.
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub reason: Option<String>,
99 /// Who set the state.
100 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub issued_by: Option<SubjectRef>,
102 /// When the state was set.
103 pub issued_at: DateTime<Utc>,
104 /// Increases by one on every change; 0 means the scope has no state.
105 pub epoch: u64,
106}
107
108/// Stores freeze state per scope with compare-and-swap updates.
109///
110/// Every backend passes
111/// `adk_core::governance_state_store_conformance_tests!` (feature `conformance`).
112#[async_trait]
113pub trait GovernanceStateStore: Send + Sync {
114 /// Returns the state of `scope`, or `None` when it was never set.
115 async fn get(&self, scope: &GovernanceScope) -> Result<Option<GovernanceState>>;
116
117 /// Sets the state of `scope` when its current epoch equals `expected_epoch` (0 when
118 /// the scope has no state) and returns the new state at epoch `expected_epoch + 1`.
119 ///
120 /// # Errors
121 ///
122 /// Returns [`GOVERNANCE_CONFLICT_CODE`] when the epoch moved; the error's
123 /// `current_epoch` metadata holds the epoch to re-read from.
124 async fn set(
125 &self,
126 scope: GovernanceScope,
127 expected_epoch: u64,
128 frozen: bool,
129 reason: Option<String>,
130 issued_by: Option<SubjectRef>,
131 ) -> Result<GovernanceState>;
132
133 /// Returns every scope's state, ordered by [`GovernanceScope::key`].
134 async fn list(&self) -> Result<Vec<GovernanceState>>;
135}
136
137/// Builds the error a governance store returns when the epoch moved.
138///
139/// # Example
140///
141/// ```rust
142/// use adk_core::governance_state::{governance_conflict_error, GovernanceScope, GOVERNANCE_CONFLICT_CODE};
143///
144/// let error = governance_conflict_error(&GovernanceScope::Org, 1, 2);
145/// assert_eq!(error.code, GOVERNANCE_CONFLICT_CODE);
146/// assert_eq!(error.details.metadata["current_epoch"], 2);
147/// ```
148pub fn governance_conflict_error(
149 scope: &GovernanceScope,
150 expected_epoch: u64,
151 current_epoch: u64,
152) -> AdkError {
153 let mut details = ErrorDetails::default();
154 details.metadata.insert("current_epoch".to_string(), current_epoch.into());
155 AdkError::new(
156 ErrorComponent::Agent,
157 ErrorCategory::Conflict,
158 GOVERNANCE_CONFLICT_CODE,
159 format!(
160 "governance state of '{}' is at epoch {current_epoch}, not {expected_epoch}; another \
161 change landed first, so re-read the state and decide again",
162 scope.key()
163 ),
164 )
165 .with_details(details)
166}
167
168/// Process-local [`GovernanceStateStore`].
169///
170/// State does not survive a restart and is not shared between processes; use a
171/// durable backend for a cross-replica kill switch.
172///
173/// # Example
174///
175/// ```rust
176/// use adk_core::governance_state::{GovernanceScope, GovernanceStateStore, InMemoryGovernanceStateStore};
177/// use adk_core::principal::SubjectRef;
178///
179/// # futures::executor::block_on(async {
180/// let store = InMemoryGovernanceStateStore::new();
181/// let frozen = store
182/// .set(GovernanceScope::Org, 0, true, Some("incident".into()), Some(SubjectRef::human("oncall")))
183/// .await?;
184/// assert_eq!(frozen.epoch, 1);
185/// assert!(store.set(GovernanceScope::Org, 0, false, None, None).await.is_err());
186/// # Ok::<(), adk_core::AdkError>(())
187/// # }).unwrap();
188/// ```
189#[derive(Debug)]
190pub struct InMemoryGovernanceStateStore {
191 states: Mutex<BTreeMap<String, GovernanceState>>,
192 clock: Arc<dyn Clock>,
193}
194
195impl Default for InMemoryGovernanceStateStore {
196 fn default() -> Self {
197 Self::new()
198 }
199}
200
201impl InMemoryGovernanceStateStore {
202 /// Creates an empty store that reads the system clock.
203 pub fn new() -> Self {
204 Self { states: Mutex::new(BTreeMap::new()), clock: Arc::new(SystemClock) }
205 }
206
207 /// Sets the clock that stamps `issued_at`.
208 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
209 self.clock = clock;
210 self
211 }
212}
213
214#[async_trait]
215impl GovernanceStateStore for InMemoryGovernanceStateStore {
216 async fn get(&self, scope: &GovernanceScope) -> Result<Option<GovernanceState>> {
217 Ok(self.states.lock().await.get(&scope.key()).cloned())
218 }
219
220 async fn set(
221 &self,
222 scope: GovernanceScope,
223 expected_epoch: u64,
224 frozen: bool,
225 reason: Option<String>,
226 issued_by: Option<SubjectRef>,
227 ) -> Result<GovernanceState> {
228 let key = scope.key();
229 let mut states = self.states.lock().await;
230 let current_epoch = states.get(&key).map_or(0, |state| state.epoch);
231 if current_epoch != expected_epoch {
232 return Err(governance_conflict_error(&scope, expected_epoch, current_epoch));
233 }
234 let state = GovernanceState {
235 scope,
236 frozen,
237 reason,
238 issued_by,
239 issued_at: self.clock.now(),
240 epoch: current_epoch + 1,
241 };
242 states.insert(key, state.clone());
243 Ok(state)
244 }
245
246 async fn list(&self) -> Result<Vec<GovernanceState>> {
247 Ok(self.states.lock().await.values().cloned().collect())
248 }
249}