Skip to main content

adk_session/
subject_sql.rs

1//! SQL-backed [`SubjectRegistry`](adk_core::subject::SubjectRegistry) and
2//! [`ConsentStore`](adk_core::subject::ConsentStore) implementations.
3//!
4//! | Table | Key | Holds |
5//! |-------|-----|-------|
6//! | `adk_subjects` | `subject_key` (`kind:id`) | Pseudonym (unique), state, the link, registration time |
7//! | `adk_consent_records` | `id` | One consent record; indexed by `(subject_key, granted_at_us, id)` |
8//!
9//! A subject key is the subject's kind, a colon, and its id. Kinds contain no colon, so two
10//! subjects never share a key.
11//!
12//! | Change | Statement | Why it has one winner |
13//! |--------|-----------|-----------------------|
14//! | `ensure`, `set_state` | `INSERT ... ON CONFLICT (subject_key) DO NOTHING` / `DO UPDATE` | The primary key admits one insert |
15//! | `link` | `UPDATE ... WHERE subject_key = $k AND linked_to IS NULL AND state = 'active'` | The empty link is compared inside the write |
16//! | `grant` | `INSERT ... ON CONFLICT (id) DO NOTHING` | The primary key admits one insert |
17//! | `revoke` | `UPDATE ... WHERE id = $k AND revoked_at_us IS NULL` | The first revocation is kept |
18//!
19//! | Backend | Feature |
20//! |---------|---------|
21//! | `SqliteSubjectRegistry`, `SqliteConsentStore` | `sqlite` |
22//! | `PostgresSubjectRegistry`, `PostgresConsentStore` | `postgres` |
23
24use std::sync::Arc;
25
26use adk_core::principal::SubjectRef;
27use adk_core::subject::{
28    ConsentEvidence, ConsentPurpose, ConsentRecord, ConsentStore, SubjectRecord, SubjectRegistry,
29    SubjectState, consent_conflict_error, erasing_error, link_consumed_error, new_pseudonym,
30    validate_link,
31};
32use adk_core::{Clock, Result, SystemClock};
33use chrono::{DateTime, Utc};
34
35use crate::durable_sql::{from_json, from_micros, micros, now, storage_error, to_json};
36
37const CODE: &str = "session.subject_store.storage";
38
39const REGISTRY_TABLE: &str = "_adk_subject_migrations";
40
41const MIGRATIONS: &[(i64, &str, &str)] = &[(
42    1,
43    "create subject registry and consent tables",
44    "\
45CREATE TABLE IF NOT EXISTS adk_subjects (\
46    subject_key TEXT PRIMARY KEY, \
47    subject TEXT NOT NULL, \
48    pseudonym TEXT NOT NULL UNIQUE, \
49    state TEXT NOT NULL, \
50    linked_to TEXT, \
51    linked_to_subject TEXT, \
52    linked_at_us BIGINT, \
53    created_at_us BIGINT NOT NULL\
54);\
55CREATE INDEX IF NOT EXISTS adk_subjects_linked_to ON adk_subjects (linked_to);\
56CREATE TABLE IF NOT EXISTS adk_consent_records (\
57    id TEXT PRIMARY KEY, \
58    subject_key TEXT NOT NULL, \
59    subject TEXT NOT NULL, \
60    purpose TEXT NOT NULL, \
61    policy_version TEXT NOT NULL, \
62    granted_at_us BIGINT NOT NULL, \
63    expires_at_us BIGINT, \
64    revoked_at_us BIGINT, \
65    evidence TEXT\
66);\
67CREATE INDEX IF NOT EXISTS adk_consent_records_subject \
68    ON adk_consent_records (subject_key, granted_at_us, id);",
69)];
70
71const GET_SUBJECT: &str = "\
72SELECT subject, pseudonym, state, linked_to_subject, linked_at_us, created_at_us \
73FROM adk_subjects WHERE subject_key = $1";
74
75// Parameters appear in ascending order in every statement, so SQLite, which numbers
76// `$N` parameters by first appearance, binds them as PostgreSQL does.
77const ENSURE: &str = "\
78INSERT INTO adk_subjects (subject_key, subject, pseudonym, state, created_at_us) \
79VALUES ($1, $2, $3, 'active', $4) \
80ON CONFLICT (subject_key) DO NOTHING";
81
82const SET_STATE: &str = "\
83INSERT INTO adk_subjects (subject_key, subject, pseudonym, state, created_at_us) \
84VALUES ($1, $2, $3, $4, $5) \
85ON CONFLICT (subject_key) DO UPDATE SET state = excluded.state";
86
87const LINK: &str = "\
88UPDATE adk_subjects SET linked_to = $1, linked_to_subject = $2, linked_at_us = $3 \
89WHERE subject_key = $4 AND linked_to IS NULL AND state = 'active'";
90
91const REMOVE: &str = "DELETE FROM adk_subjects WHERE subject_key = $1";
92
93const GRANT: &str = "\
94INSERT INTO adk_consent_records \
95    (id, subject_key, subject, purpose, policy_version, granted_at_us, expires_at_us, \
96     revoked_at_us, evidence) \
97VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) \
98ON CONFLICT (id) DO NOTHING";
99
100const GET_CONSENT: &str = "\
101SELECT id, subject, purpose, policy_version, granted_at_us, expires_at_us, revoked_at_us, \
102    evidence \
103FROM adk_consent_records WHERE id = $1";
104
105const REVOKE: &str = "\
106UPDATE adk_consent_records SET revoked_at_us = $1 WHERE id = $2 AND revoked_at_us IS NULL";
107
108const ERASE: &str = "DELETE FROM adk_consent_records WHERE subject_key = $1";
109
110/// The key a subject is stored under: `kind:id`. Kinds contain no colon.
111fn subject_key(subject: &SubjectRef) -> String {
112    subject.to_string()
113}
114
115fn state_name(state: SubjectState) -> Result<String> {
116    match serde_json::to_value(state) {
117        Ok(serde_json::Value::String(name)) => Ok(name),
118        Ok(other) => Err(storage_error(CODE, format!("subject state encodes as {other}"))),
119        Err(e) => Err(storage_error(CODE, format!("subject state does not encode: {e}"))),
120    }
121}
122
123type SubjectRow = (String, String, String, Option<String>, Option<i64>, i64);
124
125fn decode_subject(
126    (subject, pseudonym, state, linked_to, linked_at_us, created_at_us): SubjectRow,
127) -> Result<SubjectRecord> {
128    Ok(SubjectRecord {
129        subject: from_json(CODE, "subject", &subject)?,
130        pseudonym,
131        state: serde_json::from_value(serde_json::Value::String(state))
132            .map_err(|e| storage_error(CODE, format!("column 'state' is corrupt: {e}")))?,
133        linked_to: linked_to.map(|json| from_json(CODE, "linked_to_subject", &json)).transpose()?,
134        linked_at: linked_at_us.map(|us| from_micros(CODE, "linked_at_us", us)).transpose()?,
135        created_at: from_micros(CODE, "created_at_us", created_at_us)?,
136    })
137}
138
139type ConsentRow = (String, String, String, String, i64, Option<i64>, Option<i64>, Option<String>);
140
141fn decode_consent(
142    (id, subject, purpose, policy_version, granted, expires, revoked, evidence): ConsentRow,
143) -> Result<ConsentRecord> {
144    let instant = |column: &str, us: Option<i64>| -> Result<Option<DateTime<Utc>>> {
145        us.map(|us| from_micros(CODE, column, us)).transpose()
146    };
147    Ok(ConsentRecord {
148        id,
149        subject: from_json(CODE, "subject", &subject)?,
150        purpose: ConsentPurpose::from(purpose),
151        policy_version,
152        granted_at: from_micros(CODE, "granted_at_us", granted)?,
153        expires_at: instant("expires_at_us", expires)?,
154        revoked_at: instant("revoked_at_us", revoked)?,
155        evidence: evidence
156            .map(|json| from_json::<ConsentEvidence>(CODE, "evidence", &json))
157            .transpose()?,
158    })
159}
160
161fn failed(e: sqlx::Error) -> adk_core::AdkError {
162    storage_error(CODE, format!("subject store query failed: {e}"))
163}
164
165macro_rules! sql_subject_stores {
166    (
167        $(#[$registry_doc:meta])*
168        $registry:ident,
169        $(#[$consent_doc:meta])*
170        $consent:ident,
171        $pool:ty, $collate:literal, $migrate:expr
172    ) => {
173        $(#[$registry_doc])*
174        #[derive(Debug, Clone)]
175        pub struct $registry {
176            pool: $pool,
177            clock: Arc<dyn Clock>,
178        }
179
180        impl $registry {
181            /// Connects to `database_url` and creates a connection pool.
182            ///
183            /// Call [`migrate`](Self::migrate) before first use.
184            ///
185            /// # Errors
186            ///
187            /// Returns `session.subject_store.storage` when the database cannot be reached.
188            pub async fn new(database_url: &str) -> Result<Self> {
189                let pool = <$pool>::connect(database_url).await.map_err(|e| {
190                    storage_error(CODE, format!("subject store connection failed: {e}"))
191                })?;
192                Ok(Self::from_pool(pool))
193            }
194
195            /// Uses an existing pool, such as the one the session service holds.
196            pub fn from_pool(pool: $pool) -> Self {
197                Self { pool, clock: Arc::new(SystemClock) }
198            }
199
200            /// Sets the clock that stamps registration and link times.
201            #[must_use]
202            pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
203                self.clock = clock;
204                self
205            }
206
207            /// Creates or upgrades the registry and consent tables.
208            ///
209            /// # Errors
210            ///
211            /// Returns an error when a migration statement fails.
212            pub async fn migrate(&self) -> Result<()> {
213                let migrate = $migrate;
214                migrate(&self.pool).await
215            }
216
217            async fn insert_if_absent(&self, subject: &SubjectRef) -> Result<()> {
218                let (_, created_at_us) = now(&*self.clock);
219                sqlx::query(ENSURE)
220                    .bind(subject_key(subject))
221                    .bind(to_json(CODE, subject)?)
222                    .bind(new_pseudonym())
223                    .bind(created_at_us)
224                    .execute(&self.pool)
225                    .await
226                    .map_err(failed)?;
227                Ok(())
228            }
229
230            async fn required(&self, subject: &SubjectRef) -> Result<SubjectRecord> {
231                self.get(subject).await?.ok_or_else(|| {
232                    storage_error(CODE, format!("{} was written but does not read back", subject.kind))
233                })
234            }
235        }
236
237        #[async_trait::async_trait]
238        impl SubjectRegistry for $registry {
239            async fn get(&self, subject: &SubjectRef) -> Result<Option<SubjectRecord>> {
240                let row: Option<SubjectRow> = sqlx::query_as(GET_SUBJECT)
241                .bind(subject_key(subject))
242                .fetch_optional(&self.pool)
243                .await
244                .map_err(failed)?;
245                row.map(decode_subject).transpose()
246            }
247
248            async fn ensure(&self, subject: &SubjectRef) -> Result<SubjectRecord> {
249                self.insert_if_absent(subject).await?;
250                self.required(subject).await
251            }
252
253            async fn by_pseudonym(&self, pseudonym: &str) -> Result<Option<SubjectRef>> {
254                let subject: Option<String> =
255                    sqlx::query_scalar("SELECT subject FROM adk_subjects WHERE pseudonym = $1")
256                        .bind(pseudonym)
257                        .fetch_optional(&self.pool)
258                        .await
259                        .map_err(failed)?;
260                subject.map(|json| from_json(CODE, "subject", &json)).transpose()
261            }
262
263            async fn link(
264                &self,
265                visitor: &SubjectRef,
266                identified: &SubjectRef,
267            ) -> Result<SubjectRecord> {
268                validate_link(visitor, identified)?;
269                for subject in [visitor, identified] {
270                    if self.get(subject).await?.is_some_and(|r| r.state == SubjectState::Erasing) {
271                        return Err(erasing_error(subject));
272                    }
273                }
274                if self.get(visitor).await?.is_some_and(|record| record.linked_to.is_some()) {
275                    return Err(link_consumed_error());
276                }
277                self.insert_if_absent(identified).await?;
278                self.insert_if_absent(visitor).await?;
279                let (_, linked_at_us) = now(&*self.clock);
280                let changed = sqlx::query(LINK)
281                    .bind(subject_key(identified))
282                    .bind(to_json(CODE, identified)?)
283                    .bind(linked_at_us)
284                    .bind(subject_key(visitor))
285                    .execute(&self.pool)
286                    .await
287                    .map_err(failed)?;
288                let record = self.required(visitor).await?;
289                if changed.rows_affected() == 0 {
290                    return Err(if record.state == SubjectState::Erasing {
291                        erasing_error(visitor)
292                    } else {
293                        link_consumed_error()
294                    });
295                }
296                Ok(record)
297            }
298
299            async fn linked(&self, identified: &SubjectRef) -> Result<Vec<SubjectRef>> {
300                let rows: Vec<String> = sqlx::query_scalar(concat!(
301                    "SELECT subject FROM adk_subjects WHERE linked_to = $1 ORDER BY subject_key",
302                    $collate
303                ))
304                .bind(subject_key(identified))
305                .fetch_all(&self.pool)
306                .await
307                .map_err(failed)?;
308                rows.iter().map(|json| from_json(CODE, "subject", json)).collect()
309            }
310
311            async fn set_state(
312                &self,
313                subject: &SubjectRef,
314                state: SubjectState,
315            ) -> Result<SubjectRecord> {
316                let (_, created_at_us) = now(&*self.clock);
317                sqlx::query(SET_STATE)
318                    .bind(subject_key(subject))
319                    .bind(to_json(CODE, subject)?)
320                    .bind(new_pseudonym())
321                    .bind(state_name(state)?)
322                    .bind(created_at_us)
323                    .execute(&self.pool)
324                    .await
325                    .map_err(failed)?;
326                self.required(subject).await
327            }
328
329            async fn remove(&self, subject: &SubjectRef) -> Result<bool> {
330                let removed = sqlx::query(REMOVE)
331                    .bind(subject_key(subject))
332                    .execute(&self.pool)
333                    .await
334                    .map_err(failed)?;
335                Ok(removed.rows_affected() > 0)
336            }
337        }
338
339        $(#[$consent_doc])*
340        #[derive(Debug, Clone)]
341        pub struct $consent {
342            pool: $pool,
343        }
344
345        impl $consent {
346            /// Connects to `database_url` and creates a connection pool.
347            ///
348            /// Call [`migrate`](Self::migrate) before first use.
349            ///
350            /// # Errors
351            ///
352            /// Returns `session.subject_store.storage` when the database cannot be reached.
353            pub async fn new(database_url: &str) -> Result<Self> {
354                let pool = <$pool>::connect(database_url).await.map_err(|e| {
355                    storage_error(CODE, format!("consent store connection failed: {e}"))
356                })?;
357                Ok(Self::from_pool(pool))
358            }
359
360            /// Uses an existing pool, such as the one the session service holds.
361            pub fn from_pool(pool: $pool) -> Self {
362                Self { pool }
363            }
364
365            /// Creates or upgrades the registry and consent tables.
366            ///
367            /// # Errors
368            ///
369            /// Returns an error when a migration statement fails.
370            pub async fn migrate(&self) -> Result<()> {
371                let migrate = $migrate;
372                migrate(&self.pool).await
373            }
374        }
375
376        #[async_trait::async_trait]
377        impl ConsentStore for $consent {
378            async fn grant(&self, record: ConsentRecord) -> Result<()> {
379                let stamp = |at: Option<DateTime<Utc>>| at.map(|at| micros(at).1);
380                let inserted = sqlx::query(GRANT)
381                    .bind(&record.id)
382                    .bind(subject_key(&record.subject))
383                    .bind(to_json(CODE, &record.subject)?)
384                    .bind(record.purpose.as_str())
385                    .bind(&record.policy_version)
386                    .bind(micros(record.granted_at).1)
387                    .bind(stamp(record.expires_at))
388                    .bind(stamp(record.revoked_at))
389                    .bind(record.evidence.as_ref().map(|e| to_json(CODE, e)).transpose()?)
390                    .execute(&self.pool)
391                    .await
392                    .map_err(failed)?;
393                if inserted.rows_affected() == 0 {
394                    return Err(consent_conflict_error(&record.id));
395                }
396                Ok(())
397            }
398
399            async fn get(&self, id: &str) -> Result<Option<ConsentRecord>> {
400                let row: Option<ConsentRow> = sqlx::query_as(GET_CONSENT)
401                .bind(id)
402                .fetch_optional(&self.pool)
403                .await
404                .map_err(failed)?;
405                row.map(decode_consent).transpose()
406            }
407
408            async fn for_subject(&self, subject: &SubjectRef) -> Result<Vec<ConsentRecord>> {
409                let rows: Vec<ConsentRow> = sqlx::query_as(concat!(
410                    "SELECT id, subject, purpose, policy_version, granted_at_us, expires_at_us, \
411                     revoked_at_us, evidence FROM adk_consent_records WHERE subject_key = $1 \
412                     ORDER BY granted_at_us, id",
413                    $collate
414                ))
415                .bind(subject_key(subject))
416                .fetch_all(&self.pool)
417                .await
418                .map_err(failed)?;
419                rows.into_iter().map(decode_consent).collect()
420            }
421
422            async fn revoke(&self, id: &str, at: DateTime<Utc>) -> Result<Option<ConsentRecord>> {
423                sqlx::query(REVOKE)
424                    .bind(micros(at).1)
425                    .bind(id)
426                    .execute(&self.pool)
427                    .await
428                    .map_err(failed)?;
429                self.get(id).await
430            }
431
432            async fn erase(&self, subject: &SubjectRef) -> Result<u64> {
433                let erased = sqlx::query(ERASE)
434                    .bind(subject_key(subject))
435                    .execute(&self.pool)
436                    .await
437                    .map_err(failed)?;
438                Ok(erased.rows_affected())
439            }
440        }
441    };
442}
443
444#[cfg(feature = "sqlite")]
445sql_subject_stores! {
446    /// SQLite-backed [`SubjectRegistry`].
447    ///
448    /// # Example
449    ///
450    /// ```rust,no_run
451    /// use adk_core::principal::SubjectRef;
452    /// use adk_core::subject::SubjectRegistry;
453    /// use adk_session::SqliteSubjectRegistry;
454    ///
455    /// # async fn example() -> adk_core::Result<()> {
456    /// let registry = SqliteSubjectRegistry::new("sqlite://subjects.db?mode=rwc").await?;
457    /// registry.migrate().await?;
458    /// let record = registry.ensure(&SubjectRef::human("alice")).await?;
459    /// assert!(record.pseudonym.starts_with("psn:"));
460    /// # Ok(())
461    /// # }
462    /// ```
463    SqliteSubjectRegistry,
464    /// SQLite-backed [`ConsentStore`].
465    ///
466    /// # Example
467    ///
468    /// ```rust,no_run
469    /// use adk_core::subject::{ConsentPurpose, ConsentRecord, ConsentStore, VisitorId};
470    /// use adk_session::SqliteConsentStore;
471    ///
472    /// # async fn example() -> adk_core::Result<()> {
473    /// let consent = SqliteConsentStore::new("sqlite://subjects.db?mode=rwc").await?;
474    /// consent.migrate().await?;
475    /// let visitor = VisitorId::generate().subject();
476    /// consent.grant(ConsentRecord::new(visitor, ConsentPurpose::Analytics, "2026-10")).await?;
477    /// # Ok(())
478    /// # }
479    /// ```
480    SqliteConsentStore,
481    sqlx::SqlitePool,
482    "",
483    |pool: &sqlx::SqlitePool| {
484        let pool = pool.clone();
485        async move {
486            crate::migration::sqlite_runner::run_sql_migrations(
487                &pool,
488                REGISTRY_TABLE,
489                MIGRATIONS,
490                || async { Ok(false) },
491            )
492            .await
493        }
494    }
495}
496
497#[cfg(feature = "postgres")]
498sql_subject_stores! {
499    /// PostgreSQL-backed [`SubjectRegistry`] shared by every replica.
500    /// [`migrate`](Self::migrate) takes an advisory lock, so concurrent processes can call it
501    /// at startup.
502    ///
503    /// # Example
504    ///
505    /// ```rust,no_run
506    /// use adk_core::principal::SubjectRef;
507    /// use adk_core::subject::SubjectRegistry;
508    /// use adk_session::PostgresSubjectRegistry;
509    ///
510    /// # async fn example() -> adk_core::Result<()> {
511    /// let registry = PostgresSubjectRegistry::new("postgres://localhost/app").await?;
512    /// registry.migrate().await?;
513    /// let record = registry.ensure(&SubjectRef::human("alice")).await?;
514    /// # let _ = record;
515    /// # Ok(())
516    /// # }
517    /// ```
518    PostgresSubjectRegistry,
519    /// PostgreSQL-backed [`ConsentStore`] shared by every replica.
520    ///
521    /// # Example
522    ///
523    /// ```rust,no_run
524    /// use adk_core::subject::{ConsentPurpose, ConsentRecord, ConsentStore, VisitorId};
525    /// use adk_session::PostgresConsentStore;
526    ///
527    /// # async fn example() -> adk_core::Result<()> {
528    /// let consent = PostgresConsentStore::new("postgres://localhost/app").await?;
529    /// consent.migrate().await?;
530    /// let visitor = VisitorId::generate().subject();
531    /// consent.grant(ConsentRecord::new(visitor, ConsentPurpose::Analytics, "2026-10")).await?;
532    /// # Ok(())
533    /// # }
534    /// ```
535    PostgresConsentStore,
536    sqlx::PgPool,
537    // Byte order, as Rust compares strings.
538    " COLLATE \"C\"",
539    |pool: &sqlx::PgPool| {
540        let pool = pool.clone();
541        async move {
542            crate::migration::run_pg_migrations_locked(&pool, REGISTRY_TABLE, MIGRATIONS).await
543        }
544    }
545}