1use crate::error::{KernelError, Result};
16use crate::partition::{CrossingFilter, CrossingRecord, Partition};
17
18pub(crate) const PARTITION_REGISTRY_TABLE: &str = "_adk_kernel_partition_migrations";
20
21#[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#[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
108pub(crate) enum Bind {
110 Text(String),
111 Int(i64),
112}
113
114pub(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
159pub(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
167pub(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
175pub(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
183macro_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#[cfg(feature = "sqlite")]
353#[derive(Debug, Clone)]
354pub struct SqlitePartitionStore {
355 pool: sqlx::SqlitePool,
356}
357
358#[cfg(feature = "sqlite")]
359impl SqlitePartitionStore {
360 pub fn new(pool: sqlx::SqlitePool) -> Self {
362 Self { pool }
363 }
364
365 pub fn pool(&self) -> &sqlx::SqlitePool {
367 &self.pool
368 }
369
370 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#[cfg(feature = "postgres")]
412#[derive(Debug, Clone)]
413pub struct PostgresPartitionStore {
414 pool: sqlx::PgPool,
415}
416
417#[cfg(feature = "postgres")]
418impl PostgresPartitionStore {
419 pub fn new(pool: sqlx::PgPool) -> Self {
421 Self { pool }
422 }
423
424 pub fn pool(&self) -> &sqlx::PgPool {
426 &self.pool
427 }
428
429 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 pub async fn migrate(&self) -> Result<()> {
451 migrate_locked(self.pool.clone()).await
452 }
453}
454
455#[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}