Skip to main content

adk_kernel/stores/
bundle.rs

1//! [`KernelStores`]: every stateful store a kernel keeps, opened together on one backend
2//! (spec 3.2 §7.1, §13 Q8; spec 3.5 §7.22).
3
4use std::collections::BTreeSet;
5use std::fmt;
6use std::sync::Arc;
7
8use adk_core::{
9    ActionLedger, ApprovalStore, DurableRunStore, GovernanceStateStore, InMemoryActionLedger,
10    InMemoryApprovalStore, InMemoryGovernanceStateStore, InMemoryRunStore, InMemoryScheduleStore,
11    InMemorySpendLedger, ScheduleStore, SpendLedger,
12};
13use serde::{Deserialize, Serialize};
14
15use super::{
16    InMemoryAgendaStore, InMemoryAgentStore, InMemoryCronWatermarkStore, InMemoryPartitionStore,
17    InMemoryProcessStore, ProcessStore,
18};
19use crate::agenda::AgendaStore;
20use crate::agents::AgentStore;
21use crate::control::{ControlStore, InMemoryControlStore};
22use crate::error::{KernelError, Result};
23use crate::pairing::{DeviceStore, InMemoryDeviceStore};
24use crate::partition::PartitionStore;
25use crate::watermark::CronWatermarkStore;
26
27/// Every stateful store a kernel keeps, opened together on one backend (spec 3.2 §7.1, §13
28/// Q8): the bundle [`KernelBuilder::stores`](crate::KernelBuilder::stores) and
29/// `TenantKernelBuilder::stores` (feature `managed`) take, so a host opens one value instead
30/// of assembling each store, and a kernel never keeps a store in memory by accident.
31///
32/// | Field | Store | Backends |
33/// |---|---|---|
34/// | `runs`, `schedules`, `approvals`, `actions`, `spend`, `governance` | `adk-session`'s run, schedule, approval, action-ledger, spend-ledger and kill-switch stores | every backend |
35/// | `processes`, `agenda`, `partitions`, `watermarks`, `agents` | the process side table, the agenda, the partition table, cron watermarks, added agents | every backend |
36/// | `drivers` (feature `drivers`), `ledger` (feature `proc`) | mounted drivers, the activity ledger | every backend |
37/// | `devices`, `control`, `channel_bindings` (feature `channels`) | paired devices, settings and "While you were away" cursors, paired chat accounts | in-memory, SQLite, PostgreSQL, Redis |
38/// | `charter` (feature `charter`) | charters, KPIs, autonomy, signals ([`CharterStores`](crate::charter::CharterStores)) | in-memory, SQLite, PostgreSQL, Redis |
39///
40/// A store with no backend on the bundle's backend is kept in memory and named by
41/// [`in_memory_stores`](Self::in_memory_stores), as every store of
42/// [`in_memory`](Self::in_memory) is; [`KernelBuilder::require_durable`](crate::KernelBuilder::require_durable)
43/// refuses a kernel that would use one. The record describes the bundle as it was opened: a
44/// field replaced afterwards keeps its entry.
45///
46/// [`open`](Self::open) takes the store URLs the rest of ADK-Rust takes:
47///
48/// | URL | Backend | Feature |
49/// |---|---|---|
50/// | `memory:` | [`in_memory`](Self::in_memory) | — |
51/// | `sqlite://<path>?mode=rwc` | SQLite, one pool | `sqlite` (default) |
52/// | `postgres://…`, `postgresql://…` | PostgreSQL, one pool | `postgres` |
53/// | `redis://…`, `rediss://…` | Redis, one client | `redis` |
54/// | `mongodb://…/<database>`, `mongodb+srv://…` (database `adk` when the path is empty) | MongoDB | `mongodb` |
55/// | `neo4j://<user>:<password>@<host>`, `neo4j+s://…`, `bolt://…`, `bolt+s://…` | Neo4j | `neo4j` |
56/// | `firestore://<project>` | Firestore, with Application Default Credentials | `firestore` |
57///
58/// # Example
59///
60/// ```rust
61/// use adk_kernel::stores::KernelStores;
62///
63/// # #[tokio::main(flavor = "current_thread")]
64/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
65/// let memory = KernelStores::in_memory();
66/// assert!(memory.is_in_memory("processes"));
67/// assert!(!memory.is_durable());
68///
69/// let dir = tempfile::tempdir()?;
70/// let url = format!("sqlite://{}?mode=rwc", dir.path().join("kernel.db").display());
71/// let sqlite = KernelStores::open(&url).await?;
72/// assert!(sqlite.is_durable());
73/// assert_eq!(sqlite.label(), url);
74/// # Ok(())
75/// # }
76/// ```
77#[derive(Clone)]
78#[non_exhaustive]
79pub struct KernelStores {
80    /// The durable runs every process lives in.
81    pub runs: Arc<dyn DurableRunStore>,
82    /// The process side table: wake sets, admission deferrals, suspensions and daily spend
83    /// totals, which the wake router finds sleepers through.
84    pub processes: Arc<dyn ProcessStore>,
85    /// The schedules the kernel's scheduler fires.
86    pub schedules: Arc<dyn ScheduleStore>,
87    /// Held calls and approval requests, for the approval service the host builds over it.
88    pub approvals: Arc<dyn ApprovalStore>,
89    /// Exactly-once records of non-idempotent calls (K-I4).
90    pub actions: Arc<dyn ActionLedger>,
91    /// Committed and reserved spend.
92    pub spend: Arc<dyn SpendLedger>,
93    /// The kill switch's shared state, which `KernelConfig::mirrored_governance` mirrors.
94    pub governance: Arc<dyn GovernanceStateStore>,
95    /// The agenda (spec 3.2 §7.5).
96    pub agenda: Arc<dyn AgendaStore>,
97    /// The partition table and the crossing ledger (spec 3.2 §7.8).
98    pub partitions: Arc<dyn PartitionStore>,
99    /// Where each cron wake source left off (spec 3.2 §7.4).
100    pub watermarks: Arc<dyn CronWatermarkStore>,
101    /// The agents a person added (spec 3.3 §5.7).
102    pub agents: Arc<dyn AgentStore>,
103    /// Paired devices and their waiting codes, hashed (spec 3.3 §10 K2).
104    pub devices: Arc<dyn DeviceStore>,
105    /// Settings changed while the kernel runs and each device's place in "While you were
106    /// away" (spec 3.3 §10 K3, K4).
107    pub control: Arc<dyn ControlStore>,
108    /// Mounted drivers and their parked calls (spec 3.2 §7.7).
109    #[cfg(feature = "drivers")]
110    pub drivers: Arc<dyn crate::drivers::DriverStore>,
111    /// The content-free activity ledger (spec 3.2 §7.10).
112    #[cfg(feature = "proc")]
113    pub ledger: Arc<dyn crate::proc::LedgerStore>,
114    /// Chat accounts paired to the owner and staff (spec 3.3 §10 K1).
115    #[cfg(feature = "channels")]
116    pub channel_bindings: Arc<dyn crate::channels::ChannelBindingStore>,
117    /// Charters, KPIs, autonomy and signals (spec 3.5 §7.10, §7.11).
118    #[cfg(feature = "charter")]
119    pub charter: crate::charter::CharterStores,
120    label: String,
121    in_memory: BTreeSet<&'static str>,
122}
123
124impl fmt::Debug for KernelStores {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        f.debug_struct("KernelStores")
127            .field("label", &self.label)
128            .field("in_memory", &self.in_memory)
129            .finish_non_exhaustive()
130    }
131}
132
133/// The stores a bundle on MongoDB, Firestore or Neo4j keeps in memory: those backends have
134/// none of them yet.
135#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
136const SQL_AND_REDIS_ONLY: &[&str] = &[
137    "devices",
138    "control",
139    #[cfg(feature = "channels")]
140    "channel_bindings",
141    #[cfg(feature = "charter")]
142    "charter.charters",
143    #[cfg(feature = "charter")]
144    "charter.kpis",
145    #[cfg(feature = "charter")]
146    "charter.autonomy",
147    #[cfg(feature = "charter")]
148    "charter.signals",
149];
150
151impl KernelStores {
152    /// The name of every store of a bundle, as [`in_memory_stores`](Self::in_memory_stores)
153    /// names them.
154    pub const STORES: &'static [&'static str] = &[
155        "runs",
156        "processes",
157        "schedules",
158        "approvals",
159        "actions",
160        "spend",
161        "governance",
162        "agenda",
163        "partitions",
164        "watermarks",
165        "agents",
166        "devices",
167        "control",
168        #[cfg(feature = "drivers")]
169        "drivers",
170        #[cfg(feature = "proc")]
171        "ledger",
172        #[cfg(feature = "channels")]
173        "channel_bindings",
174        #[cfg(feature = "charter")]
175        "charter.charters",
176        #[cfg(feature = "charter")]
177        "charter.kpis",
178        #[cfg(feature = "charter")]
179        "charter.autonomy",
180        #[cfg(feature = "charter")]
181        "charter.signals",
182    ];
183
184    /// Every store in memory: nothing outlives the process, and
185    /// [`KernelBuilder::require_durable`](crate::KernelBuilder::require_durable) refuses it.
186    /// Its label is `memory`.
187    pub fn in_memory() -> Self {
188        Self {
189            runs: Arc::new(InMemoryRunStore::new()),
190            processes: Arc::new(InMemoryProcessStore::new()),
191            schedules: Arc::new(InMemoryScheduleStore::new()),
192            approvals: Arc::new(InMemoryApprovalStore::new()),
193            actions: Arc::new(InMemoryActionLedger::new()),
194            spend: Arc::new(InMemorySpendLedger::new(adk_core::SpendLimits::default())),
195            governance: Arc::new(InMemoryGovernanceStateStore::new()),
196            agenda: Arc::new(InMemoryAgendaStore::new()),
197            partitions: Arc::new(InMemoryPartitionStore::new()),
198            watermarks: Arc::new(InMemoryCronWatermarkStore::new()),
199            agents: Arc::new(InMemoryAgentStore::new()),
200            devices: Arc::new(InMemoryDeviceStore::new()),
201            control: Arc::new(InMemoryControlStore::new()),
202            #[cfg(feature = "drivers")]
203            drivers: Arc::new(super::InMemoryDriverStore::new()),
204            #[cfg(feature = "proc")]
205            ledger: Arc::new(super::InMemoryLedgerStore::new()),
206            #[cfg(feature = "channels")]
207            channel_bindings: Arc::new(crate::channels::InMemoryChannelBindingStore::new()),
208            #[cfg(feature = "charter")]
209            charter: crate::charter::CharterStores::in_memory(),
210            label: "memory".into(),
211            in_memory: Self::STORES.iter().copied().collect(),
212        }
213    }
214
215    /// Opens and migrates every store at `url` (see the type's URL table); the label is the
216    /// URL with its password redacted.
217    ///
218    /// # Errors
219    ///
220    /// Returns [`KernelError::Config`] for a URL with no scheme, an unknown one, or one whose
221    /// feature this build does not include, naming the feature; and
222    /// [`KernelError::Store`] when the backend cannot be reached or migrated.
223    pub async fn open(url: &str) -> Result<Self> {
224        let url = url.trim();
225        let label = redact(url);
226        let scheme = url
227            .split_once(':')
228            .map(|(scheme, _)| scheme.to_ascii_lowercase())
229            .filter(|scheme| !scheme.is_empty())
230            .ok_or_else(|| unknown_scheme(&label))?;
231        let stores: Self = match scheme.as_str() {
232            "memory" => Self::in_memory(),
233            #[cfg(feature = "sqlite")]
234            "sqlite" => {
235                let pool = sqlx::sqlite::SqlitePoolOptions::new()
236                    .max_connections(8)
237                    .connect(url)
238                    .await
239                    .map_err(|error| store_error("sqlite", &label, error))?;
240                Self::from_sqlite_pool(pool).await?
241            }
242            #[cfg(feature = "postgres")]
243            "postgres" | "postgresql" => {
244                let pool = sqlx::PgPool::connect(url)
245                    .await
246                    .map_err(|error| store_error("postgres", &label, error))?;
247                Self::from_postgres_pool(pool).await?
248            }
249            #[cfg(feature = "redis")]
250            "redis" | "rediss" => {
251                let processes = super::RedisProcessStore::connect(url).await?;
252                Self::from_redis_client(processes.client().clone()).await?
253            }
254            #[cfg(feature = "mongodb")]
255            "mongodb" | "mongodb+srv" => {
256                let (_, path) = authority_and_path(url);
257                let database = if path.is_empty() { "adk" } else { path };
258                Self::from_mongo_database(super::mongodb::connect(url, database).await?).await?
259            }
260            #[cfg(feature = "neo4j")]
261            "neo4j" | "neo4j+s" | "neo4j+ssc" | "bolt" | "bolt+s" | "bolt+ssc" => {
262                let (authority, path) = authority_and_path(url);
263                let (userinfo, host) =
264                    authority.rsplit_once('@').ok_or_else(|| KernelError::Config {
265                        reason: format!(
266                            "a Neo4j store URL needs credentials: \
267                             {scheme}://<user>:<password>@{authority}"
268                        ),
269                    })?;
270                let (user, password) = userinfo.split_once(':').unwrap_or((userinfo, ""));
271                let uri = if path.is_empty() {
272                    format!("{scheme}://{host}")
273                } else {
274                    format!("{scheme}://{host}/{path}")
275                };
276                Self::from_neo4j_graph(super::neo4j::connect(&uri, user, password).await?).await?
277            }
278            #[cfg(feature = "firestore")]
279            "firestore" => {
280                let (project, _) = authority_and_path(url);
281                if project.is_empty() {
282                    return Err(KernelError::Config {
283                        reason: "a Firestore store URL names the project: firestore://<project-id>"
284                            .into(),
285                    });
286                }
287                Self::from_firestore_db(super::firestore::connect(project).await?).await?
288            }
289            other => {
290                let feature = match other {
291                    "sqlite" => "sqlite",
292                    "postgres" | "postgresql" => "postgres",
293                    "redis" | "rediss" => "redis",
294                    "mongodb" | "mongodb+srv" => "mongodb",
295                    "neo4j" | "neo4j+s" | "neo4j+ssc" | "bolt" | "bolt+s" | "bolt+ssc" => "neo4j",
296                    "firestore" => "firestore",
297                    _ => return Err(unknown_scheme(&label)),
298                };
299                return Err(KernelError::Config {
300                    reason: format!(
301                        "the kernel's stores at {label} need adk-kernel's `{feature}` feature, \
302                         which this build does not include"
303                    ),
304                });
305            }
306        };
307        Ok(stores.with_label(label))
308    }
309
310    /// Every store on `pool`, each with its own migration table, such as the pool of
311    /// `harness.db` (spec 3.2 §7.1, §13 Q8). The label is `sqlite`.
312    ///
313    /// # Errors
314    ///
315    /// Returns the error of a migration that fails.
316    #[cfg(feature = "sqlite")]
317    pub async fn from_sqlite_pool(pool: sqlx::SqlitePool) -> Result<Self> {
318        use adk_session::{
319            SqliteActionLedger, SqliteApprovalStore, SqliteGovernanceStateStore, SqliteRunStore,
320            SqliteScheduleStore, SqliteSpendLedger,
321        };
322        let runs = SqliteRunStore::from_pool(pool.clone());
323        runs.migrate().await?;
324        let schedules = SqliteScheduleStore::from_pool(pool.clone());
325        schedules.migrate().await?;
326        let approvals = SqliteApprovalStore::from_pool(pool.clone());
327        approvals.migrate().await?;
328        let actions = SqliteActionLedger::from_pool(pool.clone());
329        actions.migrate().await?;
330        let spend = SqliteSpendLedger::from_pool(pool.clone());
331        spend.migrate().await?;
332        let governance = SqliteGovernanceStateStore::from_pool(pool.clone());
333        governance.migrate().await?;
334        let processes = super::SqliteProcessStore::new(pool.clone());
335        processes.migrate().await?;
336        let agenda = super::SqliteAgendaStore::new(pool.clone());
337        agenda.migrate().await?;
338        let partitions = super::SqlitePartitionStore::new(pool.clone());
339        partitions.migrate().await?;
340        let watermarks = super::SqliteCronWatermarkStore::new(pool.clone());
341        watermarks.migrate().await?;
342        let agents = super::SqliteAgentStore::new(pool.clone());
343        agents.migrate().await?;
344        let devices = crate::pairing::SqliteDeviceStore::new(pool.clone());
345        devices.migrate().await?;
346        let control = crate::control::SqliteControlStore::new(pool.clone());
347        control.migrate().await?;
348        #[cfg(feature = "drivers")]
349        let drivers = super::SqliteDriverStore::new(pool.clone());
350        #[cfg(feature = "drivers")]
351        drivers.migrate().await?;
352        #[cfg(feature = "proc")]
353        let ledger = super::SqliteLedgerStore::new(pool.clone());
354        #[cfg(feature = "proc")]
355        ledger.migrate().await?;
356        #[cfg(feature = "channels")]
357        let channel_bindings = crate::channels::SqliteChannelBindingStore::new(pool.clone());
358        #[cfg(feature = "channels")]
359        channel_bindings.migrate().await?;
360        #[cfg(feature = "charter")]
361        let charter = crate::charter::CharterStores::sqlite(pool).await?;
362        Ok(Self {
363            runs: Arc::new(runs),
364            processes: Arc::new(processes),
365            schedules: Arc::new(schedules),
366            approvals: Arc::new(approvals),
367            actions: Arc::new(actions),
368            spend: Arc::new(spend),
369            governance: Arc::new(governance),
370            agenda: Arc::new(agenda),
371            partitions: Arc::new(partitions),
372            watermarks: Arc::new(watermarks),
373            agents: Arc::new(agents),
374            devices: Arc::new(devices),
375            control: Arc::new(control),
376            #[cfg(feature = "drivers")]
377            drivers: Arc::new(drivers),
378            #[cfg(feature = "proc")]
379            ledger: Arc::new(ledger),
380            #[cfg(feature = "channels")]
381            channel_bindings: Arc::new(channel_bindings),
382            #[cfg(feature = "charter")]
383            charter,
384            label: "sqlite".into(),
385            in_memory: BTreeSet::new(),
386        })
387    }
388
389    /// Every store on `pool`, each with its own migration table: the database every replica
390    /// shares (spec 3.2 §13 Q8). The label is `postgres`.
391    ///
392    /// # Errors
393    ///
394    /// Returns the error of a migration that fails.
395    #[cfg(feature = "postgres")]
396    pub async fn from_postgres_pool(pool: sqlx::PgPool) -> Result<Self> {
397        use adk_session::{
398            PostgresActionLedger, PostgresApprovalStore, PostgresGovernanceStateStore,
399            PostgresRunStore, PostgresScheduleStore, PostgresSpendLedger,
400        };
401        let runs = PostgresRunStore::from_pool(pool.clone());
402        runs.migrate().await?;
403        let schedules = PostgresScheduleStore::from_pool(pool.clone());
404        schedules.migrate().await?;
405        let approvals = PostgresApprovalStore::from_pool(pool.clone());
406        approvals.migrate().await?;
407        let actions = PostgresActionLedger::from_pool(pool.clone());
408        actions.migrate().await?;
409        let spend = PostgresSpendLedger::from_pool(pool.clone());
410        spend.migrate().await?;
411        let governance = PostgresGovernanceStateStore::from_pool(pool.clone());
412        governance.migrate().await?;
413        let processes = super::PostgresProcessStore::new(pool.clone());
414        processes.migrate().await?;
415        let agenda = super::PostgresAgendaStore::new(pool.clone());
416        agenda.migrate().await?;
417        let partitions = super::PostgresPartitionStore::new(pool.clone());
418        partitions.migrate().await?;
419        let watermarks = super::PostgresCronWatermarkStore::new(pool.clone());
420        watermarks.migrate().await?;
421        let agents = super::PostgresAgentStore::new(pool.clone());
422        agents.migrate().await?;
423        let devices = crate::pairing::PostgresDeviceStore::new(pool.clone());
424        devices.migrate().await?;
425        let control = crate::control::PostgresControlStore::new(pool.clone());
426        control.migrate().await?;
427        #[cfg(feature = "drivers")]
428        let drivers = super::PostgresDriverStore::new(pool.clone());
429        #[cfg(feature = "drivers")]
430        drivers.migrate().await?;
431        #[cfg(feature = "proc")]
432        let ledger = super::PostgresLedgerStore::new(pool.clone());
433        #[cfg(feature = "proc")]
434        ledger.migrate().await?;
435        #[cfg(feature = "channels")]
436        let channel_bindings = crate::channels::PostgresChannelBindingStore::new(pool.clone());
437        #[cfg(feature = "channels")]
438        channel_bindings.migrate().await?;
439        #[cfg(feature = "charter")]
440        let charter = crate::charter::CharterStores::postgres(pool).await?;
441        Ok(Self {
442            runs: Arc::new(runs),
443            processes: Arc::new(processes),
444            schedules: Arc::new(schedules),
445            approvals: Arc::new(approvals),
446            actions: Arc::new(actions),
447            spend: Arc::new(spend),
448            governance: Arc::new(governance),
449            agenda: Arc::new(agenda),
450            partitions: Arc::new(partitions),
451            watermarks: Arc::new(watermarks),
452            agents: Arc::new(agents),
453            devices: Arc::new(devices),
454            control: Arc::new(control),
455            #[cfg(feature = "drivers")]
456            drivers: Arc::new(drivers),
457            #[cfg(feature = "proc")]
458            ledger: Arc::new(ledger),
459            #[cfg(feature = "channels")]
460            channel_bindings: Arc::new(channel_bindings),
461            #[cfg(feature = "charter")]
462            charter,
463            label: "postgres".into(),
464            in_memory: BTreeSet::new(),
465        })
466    }
467
468    /// Every store on `client`, an initialised Redis client every replica shares (spec 3.2
469    /// §13 Q8). The label is `redis`.
470    ///
471    /// # Errors
472    ///
473    /// Returns the error of a migration that fails.
474    #[cfg(feature = "redis")]
475    pub async fn from_redis_client(client: fred::prelude::Client) -> Result<Self> {
476        use adk_session::{
477            RedisActionLedger, RedisApprovalStore, RedisGovernanceStateStore, RedisRunStore,
478            RedisScheduleStore, RedisSpendLedger,
479        };
480        let runs = RedisRunStore::from_client(client.clone());
481        runs.migrate().await?;
482        let schedules = RedisScheduleStore::from_client(client.clone());
483        schedules.migrate().await?;
484        let approvals = RedisApprovalStore::from_client(client.clone());
485        approvals.migrate().await?;
486        let actions = RedisActionLedger::from_client(client.clone());
487        actions.migrate().await?;
488        let spend = RedisSpendLedger::from_client(client.clone());
489        spend.migrate().await?;
490        let governance = RedisGovernanceStateStore::from_client(client.clone());
491        governance.migrate().await?;
492        let processes = super::RedisProcessStore::from_client(client.clone());
493        processes.migrate().await?;
494        let agenda = super::RedisAgendaStore::from_client(client.clone());
495        agenda.migrate().await?;
496        let partitions = super::RedisPartitionStore::from_client(client.clone());
497        partitions.migrate().await?;
498        let watermarks = super::RedisCronWatermarkStore::from_client(client.clone());
499        watermarks.migrate().await?;
500        let agents = super::RedisAgentStore::from_client(client.clone());
501        agents.migrate().await?;
502        let devices = crate::pairing::RedisDeviceStore::from_client(client.clone());
503        devices.migrate().await?;
504        let control = crate::control::RedisControlStore::from_client(client.clone());
505        control.migrate().await?;
506        #[cfg(feature = "drivers")]
507        let drivers = super::RedisDriverStore::from_client(client.clone());
508        #[cfg(feature = "drivers")]
509        drivers.migrate().await?;
510        #[cfg(feature = "proc")]
511        let ledger = super::RedisLedgerStore::from_client(client.clone());
512        #[cfg(feature = "proc")]
513        ledger.migrate().await?;
514        #[cfg(feature = "channels")]
515        let channel_bindings =
516            crate::channels::RedisChannelBindingStore::from_client(client.clone());
517        #[cfg(feature = "channels")]
518        channel_bindings.migrate().await?;
519        #[cfg(feature = "charter")]
520        let charter = crate::charter::CharterStores::redis(client).await?;
521        Ok(Self {
522            runs: Arc::new(runs),
523            processes: Arc::new(processes),
524            schedules: Arc::new(schedules),
525            approvals: Arc::new(approvals),
526            actions: Arc::new(actions),
527            spend: Arc::new(spend),
528            governance: Arc::new(governance),
529            agenda: Arc::new(agenda),
530            partitions: Arc::new(partitions),
531            watermarks: Arc::new(watermarks),
532            agents: Arc::new(agents),
533            devices: Arc::new(devices),
534            control: Arc::new(control),
535            #[cfg(feature = "drivers")]
536            drivers: Arc::new(drivers),
537            #[cfg(feature = "proc")]
538            ledger: Arc::new(ledger),
539            #[cfg(feature = "channels")]
540            channel_bindings: Arc::new(channel_bindings),
541            #[cfg(feature = "charter")]
542            charter,
543            label: "redis".into(),
544            in_memory: BTreeSet::new(),
545        })
546    }
547
548    /// Every store on `db` (spec 3.2 §13 Q8). Devices, control settings, chat pairings and
549    /// the charter stores have no MongoDB backend: they are kept in memory and named by
550    /// [`in_memory_stores`](Self::in_memory_stores). The label is `mongodb`.
551    ///
552    /// # Errors
553    ///
554    /// Returns the error of a migration that fails.
555    #[cfg(feature = "mongodb")]
556    pub async fn from_mongo_database(db: mongodb::Database) -> Result<Self> {
557        use adk_session::{
558            MongoActionLedger, MongoApprovalStore, MongoGovernanceStateStore, MongoRunStore,
559            MongoScheduleStore, MongoSpendLedger,
560        };
561        let runs = MongoRunStore::from_database(db.clone());
562        runs.migrate().await?;
563        let schedules = MongoScheduleStore::from_database(db.clone());
564        schedules.migrate().await?;
565        let approvals = MongoApprovalStore::from_database(db.clone());
566        approvals.migrate().await?;
567        let actions = MongoActionLedger::from_database(db.clone());
568        actions.migrate().await?;
569        let spend = MongoSpendLedger::from_database(db.clone());
570        spend.migrate().await?;
571        let governance = MongoGovernanceStateStore::from_database(db.clone());
572        governance.migrate().await?;
573        let processes = super::MongoProcessStore::from_database(db.clone());
574        processes.migrate().await?;
575        let agenda = super::MongoAgendaStore::from_database(db.clone());
576        agenda.migrate().await?;
577        let partitions = super::MongoPartitionStore::from_database(db.clone());
578        partitions.migrate().await?;
579        let watermarks = super::MongoCronWatermarkStore::from_database(db.clone());
580        watermarks.migrate().await?;
581        let agents = super::MongoAgentStore::from_database(db.clone());
582        agents.migrate().await?;
583        #[cfg(feature = "drivers")]
584        let drivers = super::MongoDriverStore::from_database(db.clone());
585        #[cfg(feature = "drivers")]
586        drivers.migrate().await?;
587        #[cfg(feature = "proc")]
588        let ledger = super::MongoLedgerStore::from_database(db);
589        #[cfg(feature = "proc")]
590        ledger.migrate().await?;
591        let memory = Self::in_memory();
592        Ok(Self {
593            runs: Arc::new(runs),
594            processes: Arc::new(processes),
595            schedules: Arc::new(schedules),
596            approvals: Arc::new(approvals),
597            actions: Arc::new(actions),
598            spend: Arc::new(spend),
599            governance: Arc::new(governance),
600            agenda: Arc::new(agenda),
601            partitions: Arc::new(partitions),
602            watermarks: Arc::new(watermarks),
603            agents: Arc::new(agents),
604            #[cfg(feature = "drivers")]
605            drivers: Arc::new(drivers),
606            #[cfg(feature = "proc")]
607            ledger: Arc::new(ledger),
608            label: "mongodb".into(),
609            in_memory: partial("MongoDB"),
610            ..memory
611        })
612    }
613
614    /// Every store on `db` (spec 3.2 §13 Q8). Devices, control settings, chat pairings and
615    /// the charter stores have no Firestore backend: they are kept in memory and named by
616    /// [`in_memory_stores`](Self::in_memory_stores). The label is `firestore`.
617    ///
618    /// # Errors
619    ///
620    /// Returns the error of a migration that fails.
621    #[cfg(feature = "firestore")]
622    pub async fn from_firestore_db(db: firestore::FirestoreDb) -> Result<Self> {
623        use adk_session::{
624            FirestoreActionLedger, FirestoreApprovalStore, FirestoreGovernanceStateStore,
625            FirestoreRunStore, FirestoreScheduleStore, FirestoreSpendLedger,
626        };
627        let runs = FirestoreRunStore::from_db(db.clone());
628        runs.migrate().await?;
629        let schedules = FirestoreScheduleStore::from_db(db.clone());
630        schedules.migrate().await?;
631        let approvals = FirestoreApprovalStore::from_db(db.clone());
632        approvals.migrate().await?;
633        let actions = FirestoreActionLedger::from_db(db.clone());
634        actions.migrate().await?;
635        let spend = FirestoreSpendLedger::from_db(db.clone());
636        spend.migrate().await?;
637        let governance = FirestoreGovernanceStateStore::from_db(db.clone());
638        governance.migrate().await?;
639        let processes = super::FirestoreProcessStore::from_db(db.clone());
640        processes.migrate().await?;
641        let agenda = super::FirestoreAgendaStore::from_db(db.clone());
642        agenda.migrate().await?;
643        let partitions = super::FirestorePartitionStore::from_db(db.clone());
644        partitions.migrate().await?;
645        let watermarks = super::FirestoreCronWatermarkStore::from_db(db.clone());
646        watermarks.migrate().await?;
647        let agents = super::FirestoreAgentStore::from_db(db.clone());
648        agents.migrate().await?;
649        #[cfg(feature = "drivers")]
650        let drivers = super::FirestoreDriverStore::from_db(db.clone());
651        #[cfg(feature = "drivers")]
652        drivers.migrate().await?;
653        #[cfg(feature = "proc")]
654        let ledger = super::FirestoreLedgerStore::from_db(db);
655        #[cfg(feature = "proc")]
656        ledger.migrate().await?;
657        let memory = Self::in_memory();
658        Ok(Self {
659            runs: Arc::new(runs),
660            processes: Arc::new(processes),
661            schedules: Arc::new(schedules),
662            approvals: Arc::new(approvals),
663            actions: Arc::new(actions),
664            spend: Arc::new(spend),
665            governance: Arc::new(governance),
666            agenda: Arc::new(agenda),
667            partitions: Arc::new(partitions),
668            watermarks: Arc::new(watermarks),
669            agents: Arc::new(agents),
670            #[cfg(feature = "drivers")]
671            drivers: Arc::new(drivers),
672            #[cfg(feature = "proc")]
673            ledger: Arc::new(ledger),
674            label: "firestore".into(),
675            in_memory: partial("Firestore"),
676            ..memory
677        })
678    }
679
680    /// Every store on `graph` (spec 3.2 §13 Q8). Devices, control settings, chat pairings
681    /// and the charter stores have no Neo4j backend: they are kept in memory and named by
682    /// [`in_memory_stores`](Self::in_memory_stores). The label is `neo4j`.
683    ///
684    /// # Errors
685    ///
686    /// Returns the error of a migration that fails.
687    #[cfg(feature = "neo4j")]
688    pub async fn from_neo4j_graph(graph: neo4rs::Graph) -> Result<Self> {
689        use adk_session::{
690            Neo4jActionLedger, Neo4jApprovalStore, Neo4jGovernanceStateStore, Neo4jRunStore,
691            Neo4jScheduleStore, Neo4jSpendLedger,
692        };
693        let runs = Neo4jRunStore::from_graph(graph.clone());
694        runs.migrate().await?;
695        let schedules = Neo4jScheduleStore::from_graph(graph.clone());
696        schedules.migrate().await?;
697        let approvals = Neo4jApprovalStore::from_graph(graph.clone());
698        approvals.migrate().await?;
699        let actions = Neo4jActionLedger::from_graph(graph.clone());
700        actions.migrate().await?;
701        let spend = Neo4jSpendLedger::from_graph(graph.clone());
702        spend.migrate().await?;
703        let governance = Neo4jGovernanceStateStore::from_graph(graph.clone());
704        governance.migrate().await?;
705        let processes = super::Neo4jProcessStore::from_graph(graph.clone());
706        processes.migrate().await?;
707        let agenda = super::Neo4jAgendaStore::from_graph(graph.clone());
708        agenda.migrate().await?;
709        let partitions = super::Neo4jPartitionStore::from_graph(graph.clone());
710        partitions.migrate().await?;
711        let watermarks = super::Neo4jCronWatermarkStore::from_graph(graph.clone());
712        watermarks.migrate().await?;
713        let agents = super::Neo4jAgentStore::from_graph(graph.clone());
714        agents.migrate().await?;
715        #[cfg(feature = "drivers")]
716        let drivers = super::Neo4jDriverStore::from_graph(graph.clone());
717        #[cfg(feature = "drivers")]
718        drivers.migrate().await?;
719        #[cfg(feature = "proc")]
720        let ledger = super::Neo4jLedgerStore::from_graph(graph);
721        #[cfg(feature = "proc")]
722        ledger.migrate().await?;
723        let memory = Self::in_memory();
724        Ok(Self {
725            runs: Arc::new(runs),
726            processes: Arc::new(processes),
727            schedules: Arc::new(schedules),
728            approvals: Arc::new(approvals),
729            actions: Arc::new(actions),
730            spend: Arc::new(spend),
731            governance: Arc::new(governance),
732            agenda: Arc::new(agenda),
733            partitions: Arc::new(partitions),
734            watermarks: Arc::new(watermarks),
735            agents: Arc::new(agents),
736            #[cfg(feature = "drivers")]
737            drivers: Arc::new(drivers),
738            #[cfg(feature = "proc")]
739            ledger: Arc::new(ledger),
740            label: "neo4j".into(),
741            in_memory: partial("Neo4j"),
742            ..memory
743        })
744    }
745
746    /// Names the bundle `label` in logs, errors and the kernel's inventory, such as
747    /// `harness.db` or a store URL with its password redacted.
748    #[must_use]
749    pub fn with_label(mut self, label: impl Into<String>) -> Self {
750        self.label = label.into();
751        self
752    }
753
754    /// The bundle's name: `memory`, the backend, or the label it was given.
755    pub fn label(&self) -> &str {
756        &self.label
757    }
758
759    /// The stores kept in memory, by name ([`STORES`](Self::STORES)): every store of
760    /// [`in_memory`](Self::in_memory), and the stores the bundle's backend has none of.
761    pub fn in_memory_stores(&self) -> Vec<&'static str> {
762        self.in_memory.iter().copied().collect()
763    }
764
765    /// Whether the store `name` ([`STORES`](Self::STORES)) is kept in memory.
766    pub fn is_in_memory(&self, name: &str) -> bool {
767        self.in_memory.contains(name)
768    }
769
770    /// Whether every store outlives the process.
771    pub fn is_durable(&self) -> bool {
772        self.in_memory.is_empty()
773    }
774}
775
776/// Where one of a kernel's stateful stores came from (spec 3.2 §7.1).
777///
778/// # Example
779///
780/// ```rust
781/// use adk_kernel::stores::StoreOrigin;
782///
783/// assert_eq!(serde_json::to_value(StoreOrigin::Defaulted).unwrap(), "defaulted");
784/// ```
785#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
786#[serde(rename_all = "camelCase")]
787#[non_exhaustive]
788pub enum StoreOrigin {
789    /// Set on the builder or in the configuration.
790    Set,
791    /// Taken from the builder's [`KernelStores`].
792    Bundle,
793    /// Neither: the builder kept it in memory.
794    Defaulted,
795}
796
797/// One of a kernel's stateful stores: where it came from and whether it is known to be held
798/// in memory ([`Kernel::store_uses`](crate::Kernel::store_uses)).
799///
800/// `store` is the builder's name for it: `run_store`, `process_store`, `schedule_store`,
801/// `spend_ledger`, `agenda_store`, `partitions`, `watermark_store`, `agent_store`,
802/// `governance` or `control_store`. A store set on the builder is taken as durable, except
803/// a kill switch that is not mirrored.
804///
805/// # Example
806///
807/// ```rust
808/// use std::sync::Arc;
809/// use adk_core::InMemoryRunStore;
810/// use adk_kernel::Kernel;
811/// use adk_kernel::stores::StoreOrigin;
812///
813/// let kernel = Kernel::builder().run_store(Arc::new(InMemoryRunStore::new())).build().unwrap();
814/// let process = kernel.store_uses().iter().find(|used| used.store == "process_store").unwrap();
815/// assert_eq!((process.origin, process.in_memory), (StoreOrigin::Defaulted, true));
816/// ```
817#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
818#[serde(rename_all = "camelCase")]
819#[non_exhaustive]
820pub struct StoreUse {
821    /// The builder's name for the store.
822    pub store: String,
823    /// Where it came from.
824    pub origin: StoreOrigin,
825    /// Whether it is known to be held in memory, so its state ends with the process.
826    pub in_memory: bool,
827    /// The label of the bundle it came from.
828    #[serde(default, skip_serializing_if = "Option::is_none")]
829    pub bundle: Option<String>,
830}
831
832impl StoreUse {
833    pub(crate) fn new(store: &str, origin: StoreOrigin, in_memory: bool) -> Self {
834        Self { store: store.to_string(), origin, in_memory, bundle: None }
835    }
836}
837
838/// The in-memory record of a bundle on a backend without the stores of
839/// [`SQL_AND_REDIS_ONLY`], logging each.
840#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
841fn partial(backend: &str) -> BTreeSet<&'static str> {
842    for store in SQL_AND_REDIS_ONLY {
843        tracing::warn!(
844            kernel.store = *store,
845            backend,
846            "the store has no backend here and is kept in memory; open the kernel's stores on \
847             SQLite, PostgreSQL or Redis to keep it"
848        );
849    }
850    SQL_AND_REDIS_ONLY.iter().copied().collect()
851}
852
853/// The authority and path of `scheme://authority/path?query`.
854#[cfg(any(feature = "mongodb", feature = "neo4j", feature = "firestore"))]
855fn authority_and_path(url: &str) -> (&str, &str) {
856    let rest = url.split_once("://").map_or("", |(_, rest)| rest);
857    let rest = rest.split(['?', '#']).next().unwrap_or("");
858    rest.split_once('/').unwrap_or((rest, ""))
859}
860
861/// `url` with the password of its user info replaced by `***`.
862fn redact(url: &str) -> String {
863    let Some((scheme, rest)) = url.split_once("://") else { return url.to_string() };
864    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
865    let (authority, tail) = rest.split_at(authority_end);
866    match authority.rsplit_once('@') {
867        Some((userinfo, host)) => match userinfo.split_once(':') {
868            Some((user, _)) => format!("{scheme}://{user}:***@{host}{tail}"),
869            None => url.to_string(),
870        },
871        None => url.to_string(),
872    }
873}
874
875fn unknown_scheme(label: &str) -> KernelError {
876    KernelError::Config {
877        reason: format!(
878            "'{label}' is not a kernel store URL; use memory:, sqlite://, postgres://, redis://, \
879             mongodb://, neo4j:// or firestore://"
880        ),
881    }
882}
883
884#[cfg(any(feature = "sqlite", feature = "postgres"))]
885fn store_error(backend: &'static str, label: &str, error: sqlx::Error) -> KernelError {
886    KernelError::Store { backend, reason: format!("could not connect to {label}: {error}") }
887}
888
889#[cfg(test)]
890mod tests {
891    use super::*;
892
893    #[test]
894    fn a_url_label_hides_the_password() {
895        assert_eq!(
896            redact("postgres://kernel:s3cret@db:5432/adk"),
897            "postgres://kernel:***@db:5432/adk"
898        );
899        assert_eq!(redact("redis://localhost:6379"), "redis://localhost:6379");
900        assert_eq!(redact("sqlite://data/kernel.db?mode=rwc"), "sqlite://data/kernel.db?mode=rwc");
901        assert_eq!(redact("neo4j://neo4j:pa:ss@host:7687"), "neo4j://neo4j:***@host:7687");
902    }
903
904    #[test]
905    fn the_memory_bundle_names_every_store() {
906        let stores = KernelStores::in_memory();
907        assert_eq!(stores.in_memory_stores(), {
908            let mut all = KernelStores::STORES.to_vec();
909            all.sort_unstable();
910            all
911        });
912        assert_eq!(stores.label(), "memory");
913        assert!(!stores.is_durable());
914    }
915
916    #[tokio::test]
917    async fn an_unknown_or_missing_scheme_is_refused_naming_the_choices() {
918        for url in ["kernel.db", "ftp://host/kernel", ":memory:"] {
919            let error = KernelStores::open(url).await.unwrap_err();
920            assert!(error.to_string().contains("sqlite://"), "{url}: {error}");
921        }
922    }
923
924    #[cfg(not(feature = "firestore"))]
925    #[tokio::test]
926    async fn a_backend_this_build_lacks_names_its_feature() {
927        let error = KernelStores::open("firestore://project").await.unwrap_err();
928        assert!(error.to_string().contains("`firestore` feature"), "{error}");
929    }
930
931    #[cfg(feature = "sqlite")]
932    #[tokio::test]
933    async fn the_sqlite_bundle_keeps_every_store_durable() {
934        let dir = tempfile::tempdir().unwrap();
935        let url = format!("sqlite://{}?mode=rwc", dir.path().join("kernel.db").display());
936        let stores = KernelStores::open(&url).await.unwrap();
937        assert!(stores.is_durable(), "{:?}", stores.in_memory_stores());
938        let stores = KernelStores::open("memory:").await.unwrap();
939        assert!(!stores.is_durable());
940    }
941}