Skip to main content

adk_session/
governance_state.rs

1//! SQL-backed [`GovernanceStateStore`](adk_core::GovernanceStateStore) implementations.
2//!
3//! One row per scope in `adk_governance_state`, keyed by [`GovernanceScope::key`](adk_core::GovernanceScope::key).
4//!
5//! | Change | Statement | Why it has one winner |
6//! |--------|-----------|-----------------------|
7//! | From epoch 0 | `INSERT ... ON CONFLICT (scope_key) DO NOTHING` | The primary key admits one insert |
8//! | From epoch `n` | `UPDATE ... SET epoch = epoch + 1 WHERE scope_key = $k AND epoch = $n` | The epoch is compared inside the write |
9//!
10//! A write that changes no row reads the current epoch for the `governance.conflict`
11//! error's `current_epoch` metadata.
12//!
13//! | Backend | Feature | Serialization |
14//! |---------|---------|---------------|
15//! | [`SqliteGovernanceStateStore`](crate::SqliteGovernanceStateStore) | `sqlite` | SQLite's single writer |
16//! | `PostgresGovernanceStateStore` | `postgres` | The row lock the update takes; a waiting update re-checks the epoch against the committed row |
17
18use std::sync::Arc;
19
20use adk_core::governance_state::governance_conflict_error;
21use adk_core::principal::SubjectRef;
22use adk_core::{
23    Clock, GovernanceScope, GovernanceState, GovernanceStateStore, Result, SystemClock,
24};
25
26use crate::durable_sql::{from_json, from_micros, now, storage_error, to_json, to_u64};
27
28const CODE: &str = "session.governance_store.storage";
29
30const REGISTRY_TABLE: &str = "_adk_governance_migrations";
31
32const MIGRATIONS: &[(i64, &str, &str)] = &[(
33    1,
34    "create governance state table",
35    "\
36CREATE TABLE IF NOT EXISTS adk_governance_state (\
37    scope_key TEXT PRIMARY KEY, \
38    scope TEXT NOT NULL, \
39    frozen BOOLEAN NOT NULL, \
40    reason TEXT, \
41    issued_by TEXT, \
42    issued_at_us BIGINT NOT NULL, \
43    epoch BIGINT NOT NULL\
44);",
45)];
46
47// Parameters appear in ascending order in every statement, so SQLite, which numbers
48// `$N` parameters by first appearance, binds them as PostgreSQL does.
49const CREATE: &str = "\
50INSERT INTO adk_governance_state \
51    (scope_key, scope, frozen, reason, issued_by, issued_at_us, epoch) \
52VALUES ($1, $2, $3, $4, $5, $6, 1) \
53ON CONFLICT (scope_key) DO NOTHING";
54
55const SWAP: &str = "\
56UPDATE adk_governance_state \
57SET frozen = $1, reason = $2, issued_by = $3, issued_at_us = $4, epoch = epoch + 1 \
58WHERE scope_key = $5 AND epoch = $6";
59
60const EPOCH: &str = "SELECT epoch FROM adk_governance_state WHERE scope_key = $1";
61
62const GET: &str = "\
63SELECT scope, frozen, reason, issued_by, issued_at_us, epoch \
64FROM adk_governance_state WHERE scope_key = $1";
65
66type StateRow = (String, bool, Option<String>, Option<String>, i64, i64);
67
68fn decode(
69    (scope, frozen, reason, issued_by, issued_at_us, epoch): StateRow,
70) -> Result<GovernanceState> {
71    Ok(GovernanceState {
72        scope: from_json(CODE, "scope", &scope)?,
73        frozen,
74        reason,
75        issued_by: issued_by.map(|json| from_json(CODE, "issued_by", &json)).transpose()?,
76        issued_at: from_micros(CODE, "issued_at_us", issued_at_us)?,
77        epoch: to_u64(CODE, "epoch", epoch)?,
78    })
79}
80
81macro_rules! sql_governance_state_store {
82    (
83        $(#[$doc:meta])*
84        $name:ident, $pool:ty, $list:literal, $migrate:expr
85    ) => {
86        $(#[$doc])*
87        #[derive(Debug, Clone)]
88        pub struct $name {
89            pool: $pool,
90            clock: Arc<dyn Clock>,
91        }
92
93        impl $name {
94            /// Connects to `database_url` and creates a connection pool.
95            ///
96            /// Call [`migrate`](Self::migrate) before first use.
97            ///
98            /// # Errors
99            ///
100            /// Returns `session.governance_store.storage` when the database cannot be
101            /// reached.
102            pub async fn new(database_url: &str) -> Result<Self> {
103                let pool = <$pool>::connect(database_url).await.map_err(|e| {
104                    storage_error(CODE, format!("governance store connection failed: {e}"))
105                })?;
106                Ok(Self::from_pool(pool))
107            }
108
109            /// Uses an existing pool, such as the one the session service holds.
110            pub fn from_pool(pool: $pool) -> Self {
111                Self { pool, clock: Arc::new(SystemClock) }
112            }
113
114            /// Sets the clock that stamps `issued_at`.
115            pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
116                self.clock = clock;
117                self
118            }
119
120            /// Creates or upgrades the governance state table.
121            ///
122            /// # Errors
123            ///
124            /// Returns an error when a migration statement fails.
125            pub async fn migrate(&self) -> Result<()> {
126                let migrate = $migrate;
127                migrate(&self.pool).await
128            }
129        }
130
131        #[async_trait::async_trait]
132        impl GovernanceStateStore for $name {
133            async fn get(&self, scope: &GovernanceScope) -> Result<Option<GovernanceState>> {
134                let row: Option<StateRow> = sqlx::query_as(GET)
135                    .bind(scope.key())
136                    .fetch_optional(&self.pool)
137                    .await
138                    .map_err(|e| storage_error(CODE, format!("governance read failed: {e}")))?;
139                row.map(decode).transpose()
140            }
141
142            async fn set(
143                &self,
144                scope: GovernanceScope,
145                expected_epoch: u64,
146                frozen: bool,
147                reason: Option<String>,
148                issued_by: Option<SubjectRef>,
149            ) -> Result<GovernanceState> {
150                let key = scope.key();
151                let (issued_at, issued_at_us) = now(&*self.clock);
152                let issued_by_json =
153                    issued_by.as_ref().map(|subject| to_json(CODE, subject)).transpose()?;
154                let failed =
155                    |e: sqlx::Error| storage_error(CODE, format!("governance write failed: {e}"));
156                let changed = if expected_epoch == 0 {
157                    sqlx::query(CREATE)
158                        .bind(&key)
159                        .bind(to_json(CODE, &scope)?)
160                        .bind(frozen)
161                        .bind(reason.as_deref())
162                        .bind(issued_by_json.as_deref())
163                        .bind(issued_at_us)
164                        .execute(&self.pool)
165                        .await
166                        .map_err(failed)?
167                } else {
168                    let Ok(expected) = i64::try_from(expected_epoch) else {
169                        let current = self.get(&scope).await?.map_or(0, |state| state.epoch);
170                        return Err(governance_conflict_error(&scope, expected_epoch, current));
171                    };
172                    sqlx::query(SWAP)
173                        .bind(frozen)
174                        .bind(reason.as_deref())
175                        .bind(issued_by_json.as_deref())
176                        .bind(issued_at_us)
177                        .bind(&key)
178                        .bind(expected)
179                        .execute(&self.pool)
180                        .await
181                        .map_err(failed)?
182                };
183                if changed.rows_affected() == 0 {
184                    let current: Option<i64> = sqlx::query_scalar(EPOCH)
185                        .bind(&key)
186                        .fetch_optional(&self.pool)
187                        .await
188                        .map_err(failed)?;
189                    let current = current.map_or(Ok(0), |epoch| to_u64(CODE, "epoch", epoch))?;
190                    return Err(governance_conflict_error(&scope, expected_epoch, current));
191                }
192                Ok(GovernanceState {
193                    scope,
194                    frozen,
195                    reason,
196                    issued_by,
197                    issued_at,
198                    epoch: expected_epoch + 1,
199                })
200            }
201
202            async fn list(&self) -> Result<Vec<GovernanceState>> {
203                let rows: Vec<StateRow> = sqlx::query_as($list)
204                    .fetch_all(&self.pool)
205                    .await
206                    .map_err(|e| storage_error(CODE, format!("governance read failed: {e}")))?;
207                rows.into_iter().map(decode).collect()
208            }
209        }
210    };
211}
212
213#[cfg(feature = "sqlite")]
214sql_governance_state_store! {
215    /// SQLite-backed [`GovernanceStateStore`].
216    ///
217    /// # Example
218    ///
219    /// ```rust,no_run
220    /// use adk_core::{GovernanceScope, GovernanceStateStore};
221    /// use adk_session::SqliteGovernanceStateStore;
222    ///
223    /// # async fn example() -> adk_core::Result<()> {
224    /// let store = SqliteGovernanceStateStore::new("sqlite://runtime.db?mode=rwc").await?;
225    /// store.migrate().await?;
226    /// let current = store.get(&GovernanceScope::Org).await?.map_or(0, |state| state.epoch);
227    /// store.set(GovernanceScope::Org, current, true, Some("incident 42".into()), None).await?;
228    /// # Ok(())
229    /// # }
230    /// ```
231    SqliteGovernanceStateStore, sqlx::SqlitePool,
232    "SELECT scope, frozen, reason, issued_by, issued_at_us, epoch \
233     FROM adk_governance_state ORDER BY scope_key",
234    |pool: &sqlx::SqlitePool| {
235        let pool = pool.clone();
236        async move {
237            crate::migration::sqlite_runner::run_sql_migrations(
238                &pool,
239                REGISTRY_TABLE,
240                MIGRATIONS,
241                || async { Ok(false) },
242            )
243            .await
244        }
245    }
246}
247
248#[cfg(feature = "postgres")]
249sql_governance_state_store! {
250    /// PostgreSQL-backed [`GovernanceStateStore`] for a kill switch shared by every
251    /// replica. [`migrate`](Self::migrate) takes an advisory lock, so concurrent
252    /// processes can call it at startup.
253    ///
254    /// # Example
255    ///
256    /// ```rust,no_run
257    /// use adk_core::{GovernanceScope, GovernanceStateStore};
258    /// use adk_session::PostgresGovernanceStateStore;
259    ///
260    /// # async fn example() -> adk_core::Result<()> {
261    /// let store = PostgresGovernanceStateStore::new("postgres://localhost/app").await?;
262    /// store.migrate().await?;
263    /// let frozen = store.get(&GovernanceScope::Org).await?.is_some_and(|state| state.frozen);
264    /// # let _ = frozen;
265    /// # Ok(())
266    /// # }
267    /// ```
268    PostgresGovernanceStateStore, sqlx::PgPool,
269    // Byte order, as `GovernanceScope::key` strings compare in Rust.
270    "SELECT scope, frozen, reason, issued_by, issued_at_us, epoch \
271     FROM adk_governance_state ORDER BY scope_key COLLATE \"C\"",
272    |pool: &sqlx::PgPool| {
273        let pool = pool.clone();
274        async move {
275            crate::migration::run_pg_migrations_locked(&pool, REGISTRY_TABLE, MIGRATIONS).await
276        }
277    }
278}