Skip to main content

adk_kernel/stores/
agenda_sql.rs

1//! The SQLite and PostgreSQL [`AgendaStore`](crate::AgendaStore)s (spec 3.2 §7.5, §13 Q8).
2//!
3//! One row per item in `adk_kernel_agenda`: the columns a filter or the order reads
4//! (`partition_id`, `state`, `created_at` in microseconds since the Unix epoch) beside the
5//! item as JSON text, so an item reads back exactly as written. `transition` is one
6//! `UPDATE … WHERE id = … AND state = …`, so two writers moving one item from the same
7//! state move it once.
8
9use crate::agenda::{AgendaFilter, AgendaItem};
10use crate::error::{KernelError, Result};
11
12/// The migration registry of the agenda store, distinct from every other store's.
13pub(crate) const AGENDA_REGISTRY_TABLE: &str = "_adk_kernel_agenda_migrations";
14
15/// The SQLite schema.
16#[cfg(feature = "sqlite")]
17const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[(
18    1,
19    "create the kernel agenda table",
20    "\
21CREATE TABLE IF NOT EXISTS adk_kernel_agenda (\
22    id TEXT PRIMARY KEY, \
23    partition_id TEXT NOT NULL, \
24    state TEXT NOT NULL, \
25    created_at BIGINT NOT NULL, \
26    item TEXT NOT NULL\
27);\
28CREATE INDEX IF NOT EXISTS adk_kernel_agenda_partition ON adk_kernel_agenda (partition_id, state, created_at, id);\
29CREATE INDEX IF NOT EXISTS adk_kernel_agenda_state ON adk_kernel_agenda (state, created_at, id);",
30)];
31
32/// The PostgreSQL schema; `id` takes the `C` collation, so ties order by the bytes of the
33/// UTF-8 text on every server, as the other backends do.
34#[cfg(feature = "postgres")]
35const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[(
36    1,
37    "create the kernel agenda table",
38    "\
39CREATE TABLE IF NOT EXISTS adk_kernel_agenda (\
40    id TEXT COLLATE \"C\" PRIMARY KEY, \
41    partition_id TEXT NOT NULL, \
42    state TEXT NOT NULL, \
43    created_at BIGINT NOT NULL, \
44    item TEXT NOT NULL\
45);\
46CREATE INDEX IF NOT EXISTS adk_kernel_agenda_partition ON adk_kernel_agenda (partition_id, state, created_at, id);\
47CREATE INDEX IF NOT EXISTS adk_kernel_agenda_state ON adk_kernel_agenda (state, created_at, id);",
48)];
49
50pub(crate) const PUT: &str = "\
51INSERT INTO adk_kernel_agenda (id, partition_id, state, created_at, item) \
52VALUES ($1, $2, $3, $4, $5) \
53ON CONFLICT (id) DO UPDATE SET \
54    partition_id = excluded.partition_id, state = excluded.state, \
55    created_at = excluded.created_at, item = excluded.item";
56
57pub(crate) const GET: &str = "SELECT item FROM adk_kernel_agenda WHERE id = $1";
58
59pub(crate) const TRANSITION: &str = "\
60UPDATE adk_kernel_agenda SET partition_id = $1, state = $2, created_at = $3, item = $4 \
61WHERE id = $5 AND state = $6";
62
63pub(crate) const DELETE: &str = "DELETE FROM adk_kernel_agenda WHERE id = $1";
64
65/// The stored order key of an item: microseconds since the Unix epoch.
66pub(crate) fn created_at(item: &AgendaItem) -> i64 {
67    item.created_at.timestamp_micros()
68}
69
70/// The `list` statement for `filter` and its text and limit parameters, in order.
71pub(crate) fn list(filter: &AgendaFilter) -> (String, Vec<String>, Option<i64>) {
72    let mut conditions = Vec::new();
73    let mut binds = Vec::new();
74    if let Some(partition) = &filter.partition {
75        binds.push(partition.as_str().to_string());
76        conditions.push(format!("partition_id = ${}", binds.len()));
77    }
78    if !filter.states.is_empty() {
79        let mut placeholders = Vec::new();
80        for state in &filter.states {
81            binds.push(state.as_str().to_string());
82            placeholders.push(format!("${}", binds.len()));
83        }
84        conditions.push(format!("state IN ({})", placeholders.join(", ")));
85    }
86    let mut sql = "SELECT item FROM adk_kernel_agenda".to_string();
87    if !conditions.is_empty() {
88        sql.push_str(" WHERE ");
89        sql.push_str(&conditions.join(" AND "));
90    }
91    sql.push_str(" ORDER BY created_at, id");
92    let limit = filter.limit.map(|limit| i64::try_from(limit).unwrap_or(i64::MAX));
93    if limit.is_some() {
94        sql.push_str(&format!(" LIMIT ${}", binds.len() + 1));
95    }
96    (sql, binds, limit)
97}
98
99/// Reads a stored item back.
100pub(crate) fn decode(backend: &'static str, item: &str) -> Result<AgendaItem> {
101    serde_json::from_str(item).map_err(|error| KernelError::Store {
102        backend,
103        reason: format!("an agenda row is corrupt: {error}"),
104    })
105}
106
107/// Maps a database error.
108pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
109    KernelError::Store { backend, reason: format!("could not {action} the agenda table: {error}") }
110}
111
112/// Implements [`AgendaStore`](crate::AgendaStore) for a store with a `pool` field over the
113/// shared statements.
114macro_rules! sql_agenda_store {
115    ($store:ty, $backend:literal) => {
116        #[async_trait::async_trait]
117        impl $crate::agenda::AgendaStore for $store {
118            async fn put(&self, item: $crate::agenda::AgendaItem) -> $crate::error::Result<()> {
119                let json = serde_json::to_string(&item)?;
120                sqlx::query($crate::stores::agenda_sql::PUT)
121                    .bind(&item.id)
122                    .bind(item.partition.as_str())
123                    .bind(item.state.kind().as_str())
124                    .bind($crate::stores::agenda_sql::created_at(&item))
125                    .bind(json)
126                    .execute(&self.pool)
127                    .await
128                    .map_err(|e| $crate::stores::agenda_sql::db_error($backend, "write", &e))?;
129                Ok(())
130            }
131
132            async fn get(
133                &self,
134                id: &str,
135            ) -> $crate::error::Result<Option<$crate::agenda::AgendaItem>> {
136                let row: Option<(String,)> = sqlx::query_as($crate::stores::agenda_sql::GET)
137                    .bind(id)
138                    .fetch_optional(&self.pool)
139                    .await
140                    .map_err(|e| $crate::stores::agenda_sql::db_error($backend, "read", &e))?;
141                row.map(|(item,)| $crate::stores::agenda_sql::decode($backend, &item)).transpose()
142            }
143
144            async fn list(
145                &self,
146                filter: &$crate::agenda::AgendaFilter,
147            ) -> $crate::error::Result<Vec<$crate::agenda::AgendaItem>> {
148                let (sql, binds, limit) = $crate::stores::agenda_sql::list(filter);
149                let mut query = sqlx::query_as::<_, (String,)>(sqlx::AssertSqlSafe(sql));
150                for bind in binds {
151                    query = query.bind(bind);
152                }
153                if let Some(limit) = limit {
154                    query = query.bind(limit);
155                }
156                let rows = query
157                    .fetch_all(&self.pool)
158                    .await
159                    .map_err(|e| $crate::stores::agenda_sql::db_error($backend, "list", &e))?;
160                rows.iter()
161                    .map(|(item,)| $crate::stores::agenda_sql::decode($backend, item))
162                    .collect()
163            }
164
165            async fn transition(
166                &self,
167                item: $crate::agenda::AgendaItem,
168                from: $crate::agenda::AgendaStateKind,
169            ) -> $crate::error::Result<bool> {
170                let json = serde_json::to_string(&item)?;
171                let done = sqlx::query($crate::stores::agenda_sql::TRANSITION)
172                    .bind(item.partition.as_str())
173                    .bind(item.state.kind().as_str())
174                    .bind($crate::stores::agenda_sql::created_at(&item))
175                    .bind(json)
176                    .bind(&item.id)
177                    .bind(from.as_str())
178                    .execute(&self.pool)
179                    .await
180                    .map_err(|e| $crate::stores::agenda_sql::db_error($backend, "update", &e))?;
181                Ok(done.rows_affected() > 0)
182            }
183
184            async fn delete(&self, id: &str) -> $crate::error::Result<bool> {
185                let done = sqlx::query($crate::stores::agenda_sql::DELETE)
186                    .bind(id)
187                    .execute(&self.pool)
188                    .await
189                    .map_err(|e| {
190                        $crate::stores::agenda_sql::db_error($backend, "delete from", &e)
191                    })?;
192                Ok(done.rows_affected() > 0)
193            }
194        }
195    };
196}
197
198/// An [`AgendaStore`](crate::AgendaStore) in SQLite (spec 3.2 §7.1, §7.5, feature `sqlite`).
199///
200/// In the CLI it lives in `harness.db` beside the process store, on the same pool: its
201/// table is `adk_kernel_agenda`, and [`migrate`](Self::migrate) records its steps in
202/// `_adk_kernel_agenda_migrations`. Call `migrate` once before use.
203///
204/// # Example
205///
206/// ```rust
207/// use adk_core::principal::SubjectRef;
208/// use adk_kernel::{AgendaItem, AgendaOrigin, AgendaStore, SqliteAgendaStore};
209///
210/// # #[tokio::main(flavor = "current_thread")]
211/// # async fn main() -> adk_kernel::Result<()> {
212/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
213/// let store = SqliteAgendaStore::new(pool);
214/// store.migrate().await?;
215/// store.put(AgendaItem::new("item-1", SubjectRef::human("alice"), "Tidy", "Weekly", AgendaOrigin::User, chrono::Utc::now())).await?;
216/// assert_eq!(store.get("item-1").await?.unwrap().title, "Tidy");
217/// # Ok(())
218/// # }
219/// ```
220#[cfg(feature = "sqlite")]
221#[derive(Debug, Clone)]
222pub struct SqliteAgendaStore {
223    pool: sqlx::SqlitePool,
224}
225
226#[cfg(feature = "sqlite")]
227impl SqliteAgendaStore {
228    /// A store over `pool`, such as the pool of `harness.db`.
229    pub fn new(pool: sqlx::SqlitePool) -> Self {
230        Self { pool }
231    }
232
233    /// The pool the store writes to.
234    pub fn pool(&self) -> &sqlx::SqlitePool {
235        &self.pool
236    }
237
238    /// Creates or upgrades the store's table; a step already recorded is not run again.
239    ///
240    /// # Errors
241    ///
242    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
243    /// migrated by a newer release.
244    pub async fn migrate(&self) -> Result<()> {
245        adk_session::migration::sqlite_runner::run_sql_migrations(
246            &self.pool,
247            AGENDA_REGISTRY_TABLE,
248            SQLITE_MIGRATIONS,
249            || async { Ok(false) },
250        )
251        .await
252        .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
253    }
254}
255
256#[cfg(feature = "sqlite")]
257sql_agenda_store!(SqliteAgendaStore, "sqlite");
258
259/// An [`AgendaStore`](crate::AgendaStore) in PostgreSQL, shared by every replica (spec 3.2
260/// §7.1, §7.5, feature `postgres`).
261///
262/// It opens from the URL of `adk-rust serve --store`. Its table is `adk_kernel_agenda`;
263/// [`migrate`](Self::migrate) records its steps in `_adk_kernel_agenda_migrations` under an
264/// advisory lock, so replicas starting together migrate one at a time.
265///
266/// # Example
267///
268/// ```rust,no_run
269/// # async fn example() -> adk_kernel::Result<()> {
270/// let store = adk_kernel::PostgresAgendaStore::connect("postgres://localhost/app").await?;
271/// store.migrate().await?;
272/// # Ok(())
273/// # }
274/// ```
275#[cfg(feature = "postgres")]
276#[derive(Debug, Clone)]
277pub struct PostgresAgendaStore {
278    pool: sqlx::PgPool,
279}
280
281#[cfg(feature = "postgres")]
282impl PostgresAgendaStore {
283    /// A store over `pool`, such as the one the run store uses.
284    pub fn new(pool: sqlx::PgPool) -> Self {
285        Self { pool }
286    }
287
288    /// The pool the store writes to.
289    pub fn pool(&self) -> &sqlx::PgPool {
290        &self.pool
291    }
292
293    /// Connects to `database_url` with a pool of its own.
294    ///
295    /// # Errors
296    ///
297    /// Returns [`KernelError::Store`] when the server cannot be reached.
298    pub async fn connect(database_url: &str) -> Result<Self> {
299        let pool =
300            sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
301                backend: "postgres",
302                reason: format!("could not connect: {error}"),
303            })?;
304        Ok(Self::new(pool))
305    }
306
307    /// Creates or upgrades the store's table under a session-level advisory lock keyed by
308    /// the registry table.
309    ///
310    /// # Errors
311    ///
312    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
313    /// migrated by a newer release.
314    pub async fn migrate(&self) -> Result<()> {
315        super::postgres::migrate_locked(
316            self.pool.clone(),
317            AGENDA_REGISTRY_TABLE,
318            POSTGRES_MIGRATIONS,
319        )
320        .await
321    }
322}
323
324#[cfg(feature = "postgres")]
325sql_agenda_store!(PostgresAgendaStore, "postgres");
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330    use crate::agenda::AgendaStateKind;
331
332    #[test]
333    fn list_numbers_parameters_in_order() {
334        assert_eq!(
335            list(&AgendaFilter::default()).0,
336            "SELECT item FROM adk_kernel_agenda ORDER BY created_at, id"
337        );
338        let filter = AgendaFilter::default()
339            .partition("work")
340            .states([AgendaStateKind::Proposed, AgendaStateKind::Scheduled])
341            .limit(5);
342        let (sql, binds, limit) = list(&filter);
343        assert_eq!(
344            sql,
345            "SELECT item FROM adk_kernel_agenda WHERE partition_id = $1 AND state IN ($2, $3) \
346             ORDER BY created_at, id LIMIT $4"
347        );
348        assert_eq!(binds, ["work", "proposed", "scheduled"]);
349        assert_eq!(limit, Some(5));
350    }
351}