Skip to main content

adk_kernel/stores/
partition_sql.rs

1//! The SQLite and PostgreSQL [`PartitionStore`](crate::PartitionStore)s (spec 3.2 §7.8,
2//! §13 Q8).
3//!
4//! One row per partition in `adk_kernel_partitions`, the record as JSON text beside its id,
5//! so a partition reads back exactly as written and later fields need no schema change.
6//! One row per crossing in `adk_kernel_crossings`: the columns a filter reads (`from_partition`,
7//! `to_partition`, `run_key`, `fingerprint`, `outcome`, and `at` in microseconds since the
8//! Unix epoch) beside the record as JSON text. Crossing rows are only ever inserted. A
9//! durable run's live grants are rows of `adk_kernel_crossing_grants`, deleted when the run
10//! is released.
11//!
12//! Parameters appear in ascending order in every statement, so SQLite, which numbers `$N`
13//! parameters by first appearance, binds them as PostgreSQL does.
14
15use crate::error::{KernelError, Result};
16use crate::partition::{CrossingFilter, CrossingRecord, Partition};
17
18/// The migration registry of the partition store, distinct from every other store's.
19pub(crate) const PARTITION_REGISTRY_TABLE: &str = "_adk_kernel_partition_migrations";
20
21/// The SQLite schema.
22#[cfg(feature = "sqlite")]
23const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[(
24    1,
25    "create the kernel partition and crossing tables",
26    "\
27CREATE TABLE IF NOT EXISTS adk_kernel_partitions (\
28    id TEXT PRIMARY KEY, \
29    record TEXT NOT NULL\
30);\
31CREATE TABLE IF NOT EXISTS adk_kernel_crossings (\
32    id TEXT PRIMARY KEY, \
33    at BIGINT NOT NULL, \
34    run_key TEXT NOT NULL, \
35    from_partition TEXT NOT NULL, \
36    to_partition TEXT NOT NULL, \
37    fingerprint TEXT NOT NULL, \
38    outcome TEXT NOT NULL, \
39    record TEXT NOT NULL\
40);\
41CREATE INDEX IF NOT EXISTS adk_kernel_crossings_run ON adk_kernel_crossings (run_key, fingerprint);\
42CREATE INDEX IF NOT EXISTS adk_kernel_crossings_from ON adk_kernel_crossings (from_partition, at, id);\
43CREATE INDEX IF NOT EXISTS adk_kernel_crossings_to ON adk_kernel_crossings (to_partition, at, id);\
44CREATE INDEX IF NOT EXISTS adk_kernel_crossings_at ON adk_kernel_crossings (at, id);\
45CREATE TABLE IF NOT EXISTS adk_kernel_crossing_grants (\
46    run_key TEXT NOT NULL, \
47    fingerprint TEXT NOT NULL, \
48    PRIMARY KEY (run_key, fingerprint)\
49);",
50)];
51
52/// The PostgreSQL schema; ids take the `C` collation, so they order by the bytes of the
53/// UTF-8 text on every server, as the other backends do.
54#[cfg(feature = "postgres")]
55const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[(
56    1,
57    "create the kernel partition and crossing tables",
58    "\
59CREATE TABLE IF NOT EXISTS adk_kernel_partitions (\
60    id TEXT COLLATE \"C\" PRIMARY KEY, \
61    record TEXT NOT NULL\
62);\
63CREATE TABLE IF NOT EXISTS adk_kernel_crossings (\
64    id TEXT COLLATE \"C\" PRIMARY KEY, \
65    at BIGINT NOT NULL, \
66    run_key TEXT NOT NULL, \
67    from_partition TEXT NOT NULL, \
68    to_partition TEXT NOT NULL, \
69    fingerprint TEXT NOT NULL, \
70    outcome TEXT NOT NULL, \
71    record TEXT NOT NULL\
72);\
73CREATE INDEX IF NOT EXISTS adk_kernel_crossings_run ON adk_kernel_crossings (run_key, fingerprint);\
74CREATE INDEX IF NOT EXISTS adk_kernel_crossings_from ON adk_kernel_crossings (from_partition, at, id);\
75CREATE INDEX IF NOT EXISTS adk_kernel_crossings_to ON adk_kernel_crossings (to_partition, at, id);\
76CREATE INDEX IF NOT EXISTS adk_kernel_crossings_at ON adk_kernel_crossings (at, id);\
77CREATE TABLE IF NOT EXISTS adk_kernel_crossing_grants (\
78    run_key TEXT NOT NULL, \
79    fingerprint TEXT NOT NULL, \
80    PRIMARY KEY (run_key, fingerprint)\
81);",
82)];
83
84pub(crate) const PUT: &str = "\
85INSERT INTO adk_kernel_partitions (id, record) VALUES ($1, $2) \
86ON CONFLICT (id) DO UPDATE SET record = excluded.record";
87
88pub(crate) const GET: &str = "SELECT record FROM adk_kernel_partitions WHERE id = $1";
89
90pub(crate) const LIST: &str = "SELECT record FROM adk_kernel_partitions ORDER BY id";
91
92pub(crate) const DELETE: &str = "DELETE FROM adk_kernel_partitions WHERE id = $1";
93
94pub(crate) const RECORD_CROSSING: &str = "\
95INSERT INTO adk_kernel_crossings \
96    (id, at, run_key, from_partition, to_partition, fingerprint, outcome, record) \
97VALUES ($1, $2, $3, $4, $5, $6, $7, $8)";
98
99pub(crate) const GRANT: &str = "\
100INSERT INTO adk_kernel_crossing_grants (run_key, fingerprint) VALUES ($1, $2) \
101ON CONFLICT (run_key, fingerprint) DO NOTHING";
102
103pub(crate) const GRANTS: &str =
104    "SELECT fingerprint FROM adk_kernel_crossing_grants WHERE run_key = $1 ORDER BY fingerprint";
105
106pub(crate) const RELEASE_RUN: &str = "DELETE FROM adk_kernel_crossing_grants WHERE run_key = $1";
107
108/// A value bound to a `crossings` statement.
109pub(crate) enum Bind {
110    Text(String),
111    Int(i64),
112}
113
114/// The `crossings` statement for `filter` and its parameters, in order.
115pub(crate) fn crossings(filter: &CrossingFilter) -> (String, Vec<Bind>) {
116    let mut conditions = Vec::new();
117    let mut binds = Vec::new();
118    let mut text = |column: &str, value: String, binds: &mut Vec<Bind>| {
119        binds.push(Bind::Text(value));
120        conditions.push(format!("{column} = ${}", binds.len()));
121    };
122    if let Some(from) = &filter.from {
123        text("from_partition", from.as_str().to_string(), &mut binds);
124    }
125    if let Some(to) = &filter.to {
126        text("to_partition", to.as_str().to_string(), &mut binds);
127    }
128    if let Some(run) = &filter.run {
129        text("run_key", run.clone(), &mut binds);
130    }
131    if let Some(fingerprint) = &filter.fingerprint {
132        text("fingerprint", fingerprint.clone(), &mut binds);
133    }
134    if !filter.outcomes.is_empty() {
135        let mut placeholders = Vec::new();
136        for outcome in &filter.outcomes {
137            binds.push(Bind::Text(outcome.as_str().to_string()));
138            placeholders.push(format!("${}", binds.len()));
139        }
140        conditions.push(format!("outcome IN ({})", placeholders.join(", ")));
141    }
142    if let Some(since) = filter.since {
143        binds.push(Bind::Int(since.timestamp_micros()));
144        conditions.push(format!("at >= ${}", binds.len()));
145    }
146    let mut sql = "SELECT record FROM adk_kernel_crossings".to_string();
147    if !conditions.is_empty() {
148        sql.push_str(" WHERE ");
149        sql.push_str(&conditions.join(" AND "));
150    }
151    sql.push_str(" ORDER BY at, id");
152    if let Some(limit) = filter.limit {
153        binds.push(Bind::Int(i64::try_from(limit).unwrap_or(i64::MAX)));
154        sql.push_str(&format!(" LIMIT ${}", binds.len()));
155    }
156    (sql, binds)
157}
158
159/// Reads a stored partition back.
160pub(crate) fn decode_partition(backend: &'static str, record: &str) -> Result<Partition> {
161    serde_json::from_str(record).map_err(|error| KernelError::Store {
162        backend,
163        reason: format!("a stored partition is corrupt: {error}"),
164    })
165}
166
167/// Reads a stored crossing back.
168pub(crate) fn decode_crossing(backend: &'static str, record: &str) -> Result<CrossingRecord> {
169    serde_json::from_str(record).map_err(|error| KernelError::Store {
170        backend,
171        reason: format!("a stored crossing record is corrupt: {error}"),
172    })
173}
174
175/// Maps a database error.
176pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
177    KernelError::Store {
178        backend,
179        reason: format!("could not {action} the partition table: {error}"),
180    }
181}
182
183/// Implements [`PartitionStore`](crate::PartitionStore) for a store with a `pool` field over
184/// the shared statements.
185macro_rules! sql_partition_store {
186    ($store:ty, $backend:literal) => {
187        #[async_trait::async_trait]
188        impl $crate::partition::PartitionStore for $store {
189            async fn put(
190                &self,
191                partition: $crate::partition::Partition,
192            ) -> $crate::error::Result<()> {
193                let record = serde_json::to_string(&partition)?;
194                sqlx::query($crate::stores::partition_sql::PUT)
195                    .bind(partition.id.as_str())
196                    .bind(record)
197                    .execute(&self.pool)
198                    .await
199                    .map_err(|e| $crate::stores::partition_sql::db_error($backend, "write", &e))?;
200                Ok(())
201            }
202
203            async fn get(
204                &self,
205                id: &$crate::partition::PartitionId,
206            ) -> $crate::error::Result<Option<$crate::partition::Partition>> {
207                let row: Option<(String,)> = sqlx::query_as($crate::stores::partition_sql::GET)
208                    .bind(id.as_str())
209                    .fetch_optional(&self.pool)
210                    .await
211                    .map_err(|e| $crate::stores::partition_sql::db_error($backend, "read", &e))?;
212                row.map(|(record,)| {
213                    $crate::stores::partition_sql::decode_partition($backend, &record)
214                })
215                .transpose()
216            }
217
218            async fn list(&self) -> $crate::error::Result<Vec<$crate::partition::Partition>> {
219                let rows: Vec<(String,)> = sqlx::query_as($crate::stores::partition_sql::LIST)
220                    .fetch_all(&self.pool)
221                    .await
222                    .map_err(|e| $crate::stores::partition_sql::db_error($backend, "list", &e))?;
223                rows.iter()
224                    .map(|(record,)| {
225                        $crate::stores::partition_sql::decode_partition($backend, record)
226                    })
227                    .collect()
228            }
229
230            async fn delete(
231                &self,
232                id: &$crate::partition::PartitionId,
233            ) -> $crate::error::Result<bool> {
234                let done = sqlx::query($crate::stores::partition_sql::DELETE)
235                    .bind(id.as_str())
236                    .execute(&self.pool)
237                    .await
238                    .map_err(|e| {
239                        $crate::stores::partition_sql::db_error($backend, "delete from", &e)
240                    })?;
241                Ok(done.rows_affected() > 0)
242            }
243
244            async fn record_crossing(
245                &self,
246                record: $crate::partition::CrossingRecord,
247            ) -> $crate::error::Result<()> {
248                let json = serde_json::to_string(&record)?;
249                sqlx::query($crate::stores::partition_sql::RECORD_CROSSING)
250                    .bind(&record.id)
251                    .bind(record.at.timestamp_micros())
252                    .bind(&record.run)
253                    .bind(record.from.as_str())
254                    .bind(record.to.as_str())
255                    .bind(&record.fingerprint)
256                    .bind(record.outcome.as_str())
257                    .bind(json)
258                    .execute(&self.pool)
259                    .await
260                    .map_err(|e| {
261                        $crate::stores::partition_sql::db_error(
262                            $backend,
263                            "record a crossing in",
264                            &e,
265                        )
266                    })?;
267                Ok(())
268            }
269
270            async fn crossings(
271                &self,
272                filter: &$crate::partition::CrossingFilter,
273            ) -> $crate::error::Result<Vec<$crate::partition::CrossingRecord>> {
274                let (sql, binds) = $crate::stores::partition_sql::crossings(filter);
275                let mut query = sqlx::query_as::<_, (String,)>(sqlx::AssertSqlSafe(sql));
276                for bind in binds {
277                    query = match bind {
278                        $crate::stores::partition_sql::Bind::Text(text) => query.bind(text),
279                        $crate::stores::partition_sql::Bind::Int(int) => query.bind(int),
280                    };
281                }
282                let rows = query.fetch_all(&self.pool).await.map_err(|e| {
283                    $crate::stores::partition_sql::db_error($backend, "list crossings in", &e)
284                })?;
285                rows.iter()
286                    .map(|(record,)| {
287                        $crate::stores::partition_sql::decode_crossing($backend, record)
288                    })
289                    .collect()
290            }
291
292            async fn grant(&self, run: &str, fingerprint: &str) -> $crate::error::Result<()> {
293                sqlx::query($crate::stores::partition_sql::GRANT)
294                    .bind(run)
295                    .bind(fingerprint)
296                    .execute(&self.pool)
297                    .await
298                    .map_err(|e| {
299                        $crate::stores::partition_sql::db_error($backend, "record a grant in", &e)
300                    })?;
301                Ok(())
302            }
303
304            async fn grants(&self, run: &str) -> $crate::error::Result<Vec<String>> {
305                let rows: Vec<(String,)> = sqlx::query_as($crate::stores::partition_sql::GRANTS)
306                    .bind(run)
307                    .fetch_all(&self.pool)
308                    .await
309                    .map_err(|e| {
310                        $crate::stores::partition_sql::db_error($backend, "read the grants in", &e)
311                    })?;
312                Ok(rows.into_iter().map(|(fingerprint,)| fingerprint).collect())
313            }
314
315            async fn release_run(&self, run: &str) -> $crate::error::Result<u64> {
316                let done = sqlx::query($crate::stores::partition_sql::RELEASE_RUN)
317                    .bind(run)
318                    .execute(&self.pool)
319                    .await
320                    .map_err(|e| {
321                        $crate::stores::partition_sql::db_error($backend, "release grants in", &e)
322                    })?;
323                Ok(done.rows_affected())
324            }
325        }
326    };
327}
328
329/// A [`PartitionStore`](crate::PartitionStore) in SQLite (spec 3.2 §7.1, §7.8, feature
330/// `sqlite`).
331///
332/// In the CLI it lives in `harness.db` beside the harness stores, on the same pool: its
333/// tables are `adk_kernel_partitions` and `adk_kernel_crossings`, and
334/// [`migrate`](Self::migrate) records its steps in `_adk_kernel_partition_migrations`,
335/// distinct from every other store's. Call `migrate` once before use.
336///
337/// # Example
338///
339/// ```rust
340/// use adk_kernel::{Partition, PartitionId, PartitionStore, SqlitePartitionStore};
341///
342/// # #[tokio::main(flavor = "current_thread")]
343/// # async fn main() -> adk_kernel::Result<()> {
344/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
345/// let store = SqlitePartitionStore::new(pool);
346/// store.migrate().await?;
347/// store.put(Partition::new("work", "work")).await?;
348/// assert!(store.get(&PartitionId::new("work")).await?.is_some());
349/// # Ok(())
350/// # }
351/// ```
352#[cfg(feature = "sqlite")]
353#[derive(Debug, Clone)]
354pub struct SqlitePartitionStore {
355    pool: sqlx::SqlitePool,
356}
357
358#[cfg(feature = "sqlite")]
359impl SqlitePartitionStore {
360    /// A store over `pool`, such as the pool of `harness.db`.
361    pub fn new(pool: sqlx::SqlitePool) -> Self {
362        Self { pool }
363    }
364
365    /// The pool the store writes to.
366    pub fn pool(&self) -> &sqlx::SqlitePool {
367        &self.pool
368    }
369
370    /// Creates or upgrades the store's tables.
371    ///
372    /// Idempotent: a step already recorded in `_adk_kernel_partition_migrations` is not run
373    /// again.
374    ///
375    /// # Errors
376    ///
377    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
378    /// migrated by a newer release.
379    pub async fn migrate(&self) -> Result<()> {
380        adk_session::migration::sqlite_runner::run_sql_migrations(
381            &self.pool,
382            PARTITION_REGISTRY_TABLE,
383            SQLITE_MIGRATIONS,
384            || async { Ok(false) },
385        )
386        .await
387        .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
388    }
389}
390
391#[cfg(feature = "sqlite")]
392sql_partition_store!(SqlitePartitionStore, "sqlite");
393
394/// A [`PartitionStore`](crate::PartitionStore) in PostgreSQL, shared by every replica (spec
395/// 3.2 §7.1, §7.8, feature `postgres`).
396///
397/// It opens from the URL of `adk-rust serve --store`. Its tables are
398/// `adk_kernel_partitions` and `adk_kernel_crossings`; [`migrate`](Self::migrate) records
399/// its steps in `_adk_kernel_partition_migrations` under an advisory lock, so replicas
400/// starting together migrate one at a time.
401///
402/// # Example
403///
404/// ```rust,no_run
405/// # async fn example() -> adk_kernel::Result<()> {
406/// let store = adk_kernel::PostgresPartitionStore::connect("postgres://localhost/app").await?;
407/// store.migrate().await?;
408/// # Ok(())
409/// # }
410/// ```
411#[cfg(feature = "postgres")]
412#[derive(Debug, Clone)]
413pub struct PostgresPartitionStore {
414    pool: sqlx::PgPool,
415}
416
417#[cfg(feature = "postgres")]
418impl PostgresPartitionStore {
419    /// A store over `pool`, such as the one the session service and the run store use.
420    pub fn new(pool: sqlx::PgPool) -> Self {
421        Self { pool }
422    }
423
424    /// The pool the store writes to.
425    pub fn pool(&self) -> &sqlx::PgPool {
426        &self.pool
427    }
428
429    /// Connects to `database_url` with a pool of its own.
430    ///
431    /// # Errors
432    ///
433    /// Returns [`KernelError::Store`] when the server cannot be reached.
434    pub async fn connect(database_url: &str) -> Result<Self> {
435        let pool =
436            sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
437                backend: "postgres",
438                reason: format!("could not connect: {error}"),
439            })?;
440        Ok(Self::new(pool))
441    }
442
443    /// Creates or upgrades the store's tables, under a session-level advisory lock keyed by
444    /// the registry table, so replicas starting together migrate one at a time.
445    ///
446    /// # Errors
447    ///
448    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
449    /// migrated by a newer release.
450    pub async fn migrate(&self) -> Result<()> {
451        migrate_locked(self.pool.clone()).await
452    }
453}
454
455/// Runs the migrations under the advisory lock. Boxed so the future is checked for `Send`
456/// here, with concrete lifetimes, rather than inside callers' `async_trait` methods.
457#[cfg(feature = "postgres")]
458fn migrate_locked(
459    pool: sqlx::PgPool,
460) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> {
461    use sqlx::Connection as _;
462
463    let store_error = |action: &str, error: &dyn std::fmt::Display| KernelError::Store {
464        backend: "postgres",
465        reason: format!("could not {action}: {error}"),
466    };
467    Box::pin(async move {
468        let key = PARTITION_REGISTRY_TABLE
469            .bytes()
470            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
471                (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
472            })
473            .cast_signed();
474        let mut lock = sqlx::PgConnection::connect_with(&pool.connect_options())
475            .await
476            .map_err(|error| store_error("connect for the migration lock", &error))?;
477        sqlx::query("SELECT pg_advisory_lock($1)")
478            .bind(key)
479            .execute(&mut lock)
480            .await
481            .map_err(|error| store_error("take the migration lock", &error))?;
482        let result = adk_session::migration::pg_runner::run_sql_migrations(
483            &pool,
484            PARTITION_REGISTRY_TABLE,
485            POSTGRES_MIGRATIONS,
486            || async { Ok(false) },
487        )
488        .await
489        .map_err(|error| KernelError::Store { backend: "postgres", reason: error.message });
490        let _ = lock.close().await;
491        result
492    })
493}
494
495#[cfg(feature = "postgres")]
496sql_partition_store!(PostgresPartitionStore, "postgres");
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use crate::partition::CrossingOutcome;
502
503    #[test]
504    fn crossings_numbers_parameters_in_order() {
505        assert_eq!(
506            crossings(&CrossingFilter::default()).0,
507            "SELECT record FROM adk_kernel_crossings ORDER BY at, id"
508        );
509        let filter = CrossingFilter::default()
510            .from("home")
511            .to("work")
512            .run("run-1")
513            .fingerprint("sha256:00")
514            .outcomes([CrossingOutcome::Approved, CrossingOutcome::RunGrant])
515            .since(chrono::DateTime::UNIX_EPOCH)
516            .limit(3);
517        let (sql, binds) = crossings(&filter);
518        assert_eq!(
519            sql,
520            "SELECT record FROM adk_kernel_crossings WHERE from_partition = $1 AND \
521             to_partition = $2 AND run_key = $3 AND fingerprint = $4 AND outcome IN ($5, $6) \
522             AND at >= $7 ORDER BY at, id LIMIT $8"
523        );
524        assert_eq!(binds.len(), 8);
525    }
526}