Skip to main content

adk_kernel/stores/
agent_sql.rs

1//! The SQLite and PostgreSQL [`AgentStore`](crate::agents::AgentStore)s (spec 3.3 §5.7, §10
2//! K7).
3//!
4//! One row per agent in `adk_kernel_agents`: the columns a write compares (`version`) or a
5//! delete reads (`state`) beside the record as JSON text, so a record reads back exactly as
6//! written. `put_if_version` is one `INSERT … ON CONFLICT DO NOTHING` for a new agent and one
7//! `UPDATE … WHERE id = … AND version = …` otherwise, so two writers changing one agent from
8//! the same version change it once.
9//!
10//! Parameters appear in ascending order in every statement, so SQLite, which numbers `$N`
11//! parameters by first appearance, binds them as PostgreSQL does.
12
13use crate::agents::AgentRecord;
14use crate::error::{KernelError, Result};
15
16/// The migration registry of the agent store, distinct from every other store's.
17pub(crate) const AGENT_REGISTRY_TABLE: &str = "_adk_kernel_agent_migrations";
18
19/// The SQLite schema.
20#[cfg(feature = "sqlite")]
21const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[(
22    1,
23    "create the kernel agent table",
24    "\
25CREATE TABLE IF NOT EXISTS adk_kernel_agents (\
26    id TEXT PRIMARY KEY, \
27    version BIGINT NOT NULL, \
28    state TEXT NOT NULL, \
29    record TEXT NOT NULL\
30);",
31)];
32
33/// The PostgreSQL schema; `id` takes the `C` collation, so `list` orders by the bytes of the
34/// UTF-8 text on every server, as the other backends do.
35#[cfg(feature = "postgres")]
36const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[(
37    1,
38    "create the kernel agent table",
39    "\
40CREATE TABLE IF NOT EXISTS adk_kernel_agents (\
41    id TEXT COLLATE \"C\" PRIMARY KEY, \
42    version BIGINT NOT NULL, \
43    state TEXT NOT NULL, \
44    record TEXT NOT NULL\
45);",
46)];
47
48pub(crate) const INSERT: &str = "\
49INSERT INTO adk_kernel_agents (id, version, state, record) VALUES ($1, $2, $3, $4) \
50ON CONFLICT (id) DO NOTHING";
51
52pub(crate) const UPDATE: &str = "\
53UPDATE adk_kernel_agents SET version = $1, state = $2, record = $3 \
54WHERE id = $4 AND version = $5";
55
56pub(crate) const GET: &str = "SELECT record FROM adk_kernel_agents WHERE id = $1";
57
58pub(crate) const LIST: &str = "SELECT record FROM adk_kernel_agents ORDER BY id";
59
60pub(crate) const DELETE: &str =
61    "DELETE FROM adk_kernel_agents WHERE id = $1 AND state = 'proposed'";
62
63/// The stored form of a version, a signed 64-bit integer.
64pub(crate) fn stored_version(backend: &'static str, version: u64) -> Result<i64> {
65    i64::try_from(version).map_err(|_| KernelError::Store {
66        backend,
67        reason: format!("agent version {version} exceeds a signed 64-bit integer"),
68    })
69}
70
71/// Reads a stored record back.
72pub(crate) fn decode(backend: &'static str, record: &str) -> Result<AgentRecord> {
73    serde_json::from_str(record).map_err(|error| KernelError::Store {
74        backend,
75        reason: format!("a stored agent is corrupt: {error}"),
76    })
77}
78
79/// Maps a database error.
80pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
81    KernelError::Store { backend, reason: format!("could not {action} the agent table: {error}") }
82}
83
84/// Implements [`AgentStore`](crate::agents::AgentStore) for a store with a `pool` field over
85/// the shared statements.
86macro_rules! sql_agent_store {
87    ($store:ty, $backend:literal) => {
88        #[async_trait::async_trait]
89        impl $crate::agents::AgentStore for $store {
90            async fn put_if_version(
91                &self,
92                record: $crate::agents::AgentRecord,
93                expected: u64,
94            ) -> $crate::error::Result<bool> {
95                let json = serde_json::to_string(&record)?;
96                let version = $crate::stores::agent_sql::stored_version($backend, record.version)?;
97                let done = if expected == 0 {
98                    sqlx::query($crate::stores::agent_sql::INSERT)
99                        .bind(&record.id)
100                        .bind(version)
101                        .bind(record.state.as_str())
102                        .bind(json)
103                        .execute(&self.pool)
104                        .await
105                } else {
106                    let expected = $crate::stores::agent_sql::stored_version($backend, expected)?;
107                    sqlx::query($crate::stores::agent_sql::UPDATE)
108                        .bind(version)
109                        .bind(record.state.as_str())
110                        .bind(json)
111                        .bind(&record.id)
112                        .bind(expected)
113                        .execute(&self.pool)
114                        .await
115                }
116                .map_err(|e| $crate::stores::agent_sql::db_error($backend, "write", &e))?;
117                Ok(done.rows_affected() > 0)
118            }
119
120            async fn get(
121                &self,
122                id: &str,
123            ) -> $crate::error::Result<Option<$crate::agents::AgentRecord>> {
124                let row: Option<(String,)> = sqlx::query_as($crate::stores::agent_sql::GET)
125                    .bind(id)
126                    .fetch_optional(&self.pool)
127                    .await
128                    .map_err(|e| $crate::stores::agent_sql::db_error($backend, "read", &e))?;
129                row.map(|(record,)| $crate::stores::agent_sql::decode($backend, &record))
130                    .transpose()
131            }
132
133            async fn list(&self) -> $crate::error::Result<Vec<$crate::agents::AgentRecord>> {
134                let rows: Vec<(String,)> = sqlx::query_as($crate::stores::agent_sql::LIST)
135                    .fetch_all(&self.pool)
136                    .await
137                    .map_err(|e| $crate::stores::agent_sql::db_error($backend, "list", &e))?;
138                rows.iter()
139                    .map(|(record,)| $crate::stores::agent_sql::decode($backend, record))
140                    .collect()
141            }
142
143            async fn delete(&self, id: &str) -> $crate::error::Result<bool> {
144                let done = sqlx::query($crate::stores::agent_sql::DELETE)
145                    .bind(id)
146                    .execute(&self.pool)
147                    .await
148                    .map_err(|e| {
149                        $crate::stores::agent_sql::db_error($backend, "delete from", &e)
150                    })?;
151                Ok(done.rows_affected() > 0)
152            }
153        }
154    };
155}
156
157/// An [`AgentStore`](crate::agents::AgentStore) in SQLite (spec 3.3 §5.7, §10 K7, feature
158/// `sqlite`).
159///
160/// In the CLI it lives in `harness.db` beside the kernel's other stores, on the same pool:
161/// its table is `adk_kernel_agents`, and [`migrate`](Self::migrate) records its steps in
162/// `_adk_kernel_agent_migrations`, distinct from every other store's. Call `migrate` once
163/// before use.
164///
165/// # Example
166///
167/// ```rust
168/// use adk_core::principal::SubjectRef;
169/// use adk_kernel::agents::{AgentDefinition, AgentOrigin, AgentRecord, AgentRecordState, AgentStore};
170/// use adk_kernel::stores::SqliteAgentStore;
171///
172/// # #[tokio::main(flavor = "current_thread")]
173/// # async fn main() -> adk_kernel::Result<()> {
174/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
175/// let store = SqliteAgentStore::new(pool);
176/// store.migrate().await?;
177/// let record = AgentRecord::new("finance", AgentDefinition::new("Finance", "default"),
178///     AgentRecordState::Active, AgentOrigin::ByHand, SubjectRef::human("alice"), chrono::Utc::now());
179/// assert!(store.put_if_version(record, 0).await?);
180/// assert!(store.get("finance").await?.is_some());
181/// # Ok(())
182/// # }
183/// ```
184#[cfg(feature = "sqlite")]
185#[derive(Debug, Clone)]
186pub struct SqliteAgentStore {
187    pool: sqlx::SqlitePool,
188}
189
190#[cfg(feature = "sqlite")]
191impl SqliteAgentStore {
192    /// A store over `pool`, such as the pool of `harness.db`.
193    pub fn new(pool: sqlx::SqlitePool) -> Self {
194        Self { pool }
195    }
196
197    /// The pool the store writes to.
198    pub fn pool(&self) -> &sqlx::SqlitePool {
199        &self.pool
200    }
201
202    /// Creates or upgrades the store's table; a step already recorded in
203    /// `_adk_kernel_agent_migrations` is not run again.
204    ///
205    /// # Errors
206    ///
207    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
208    /// migrated by a newer release.
209    pub async fn migrate(&self) -> Result<()> {
210        adk_session::migration::sqlite_runner::run_sql_migrations(
211            &self.pool,
212            AGENT_REGISTRY_TABLE,
213            SQLITE_MIGRATIONS,
214            || async { Ok(false) },
215        )
216        .await
217        .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
218    }
219}
220
221#[cfg(feature = "sqlite")]
222sql_agent_store!(SqliteAgentStore, "sqlite");
223
224/// An [`AgentStore`](crate::agents::AgentStore) in PostgreSQL, shared by every replica
225/// (spec 3.3 §5.7, §10 K7, feature `postgres`).
226///
227/// It opens from the URL of `adk-rust serve --store`. Its table is `adk_kernel_agents`;
228/// [`migrate`](Self::migrate) records its steps in `_adk_kernel_agent_migrations` under an
229/// advisory lock, so replicas starting together migrate one at a time.
230///
231/// # Example
232///
233/// ```rust,no_run
234/// # async fn example() -> adk_kernel::Result<()> {
235/// let store = adk_kernel::stores::PostgresAgentStore::connect("postgres://localhost/app").await?;
236/// store.migrate().await?;
237/// # Ok(())
238/// # }
239/// ```
240#[cfg(feature = "postgres")]
241#[derive(Debug, Clone)]
242pub struct PostgresAgentStore {
243    pool: sqlx::PgPool,
244}
245
246#[cfg(feature = "postgres")]
247impl PostgresAgentStore {
248    /// A store over `pool`, such as the one the run store uses.
249    pub fn new(pool: sqlx::PgPool) -> Self {
250        Self { pool }
251    }
252
253    /// The pool the store writes to.
254    pub fn pool(&self) -> &sqlx::PgPool {
255        &self.pool
256    }
257
258    /// Connects to `database_url` with a pool of its own.
259    ///
260    /// # Errors
261    ///
262    /// Returns [`KernelError::Store`] when the server cannot be reached.
263    pub async fn connect(database_url: &str) -> Result<Self> {
264        let pool =
265            sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
266                backend: "postgres",
267                reason: format!("could not connect: {error}"),
268            })?;
269        Ok(Self::new(pool))
270    }
271
272    /// Creates or upgrades the store's table under a session-level advisory lock keyed by
273    /// the registry table.
274    ///
275    /// # Errors
276    ///
277    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
278    /// migrated by a newer release.
279    pub async fn migrate(&self) -> Result<()> {
280        super::postgres::migrate_locked(
281            self.pool.clone(),
282            AGENT_REGISTRY_TABLE,
283            POSTGRES_MIGRATIONS,
284        )
285        .await
286    }
287}
288
289#[cfg(feature = "postgres")]
290sql_agent_store!(PostgresAgentStore, "postgres");