Skip to main content

adk_kernel/stores/
driver_mongodb.rs

1//! The MongoDB [`DriverStore`] (spec 3.2 §7.7, §13 Q8; features `drivers`, `mongodb`).
2
3use adk_core::ApprovalScope;
4use async_trait::async_trait;
5use mongodb::bson::{Document, doc};
6use mongodb::{Collection, Database};
7
8use super::mongodb::{
9    collect, connect, create_indexes, json, retry_upsert, sorted, store_error, text,
10};
11use crate::drivers::{DriverPark, DriverRecord, DriverStore};
12use crate::error::Result;
13
14const DRIVERS: &str = "adk_kernel_drivers";
15const PARKS: &str = "adk_kernel_driver_parks";
16
17/// A [`DriverStore`] in MongoDB, shared by every replica (spec 3.2 §7.7, §13 Q8; features
18/// `drivers`, `mongodb`).
19///
20/// | Collection | `_id` | Contents |
21/// |------------|-------|----------|
22/// | `adk_kernel_drivers` | The driver id | `record`, the record as JSON text |
23/// | `adk_kernel_driver_parks` | `{app, user, session, call}`: the park's scope and call id | `driver`, the fields `app`, `user`, `session` and `call_id` that `list_parks` sorts on, and `park`, the park as JSON text |
24///
25/// Sorts use MongoDB's binary string comparison, so drivers order by their ids' UTF-8
26/// bytes and parks by scope, then call id, as on every backend. Every write is a
27/// single-document write, so a standalone `mongod` serves it as a replica set does.
28///
29/// # Example
30///
31/// ```rust,no_run
32/// # async fn example() -> adk_kernel::Result<()> {
33/// let store =
34///     adk_kernel::stores::MongoDriverStore::connect("mongodb://localhost:27017", "adk").await?;
35/// store.migrate().await?;
36/// # Ok(())
37/// # }
38/// ```
39#[derive(Debug, Clone)]
40pub struct MongoDriverStore {
41    db: Database,
42}
43
44impl MongoDriverStore {
45    /// A store over `db`, such as the process store's.
46    pub fn from_database(db: Database) -> Self {
47        Self { db }
48    }
49
50    /// Connects to `connection_string` and uses the database `database_name`.
51    ///
52    /// # Errors
53    ///
54    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the connection string
55    /// is invalid.
56    pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
57        Ok(Self::from_database(connect(connection_string, database_name).await?))
58    }
59
60    /// The database the store writes to.
61    pub fn database(&self) -> &Database {
62        &self.db
63    }
64
65    /// Creates the indexes `list_parks` reads; an index that exists is kept.
66    ///
67    /// # Errors
68    ///
69    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server cannot be
70    /// reached or refuses an index.
71    pub async fn migrate(&self) -> Result<()> {
72        create_indexes(
73            &self.parks(),
74            &[
75                ("adk_kernel_driver_parks_driver", doc! { "driver": 1 }),
76                (
77                    "adk_kernel_driver_parks_order",
78                    doc! { "app": 1, "user": 1, "session": 1, "call_id": 1 },
79                ),
80            ],
81        )
82        .await
83    }
84
85    fn records(&self) -> Collection<Document> {
86        self.db.collection(DRIVERS)
87    }
88
89    fn parks(&self) -> Collection<Document> {
90        self.db.collection(PARKS)
91    }
92}
93
94/// The `_id` of the park of `call_id` in `scope`.
95fn park_id(scope: &ApprovalScope, call_id: &str) -> Document {
96    doc! {
97        "app": &scope.app_name,
98        "user": &scope.user_id,
99        "session": &scope.session_id,
100        "call": call_id,
101    }
102}
103
104#[async_trait]
105impl DriverStore for MongoDriverStore {
106    async fn put(&self, record: DriverRecord) -> Result<()> {
107        let id = record.id().to_string();
108        let document = doc! { "_id": &id, "record": serde_json::to_string(&record)? };
109        let records = self.records();
110        retry_upsert("write the driver table", || {
111            records.replace_one(doc! { "_id": &id }, document.clone()).upsert(true)
112        })
113        .await?;
114        Ok(())
115    }
116
117    async fn get(&self, id: &str) -> Result<Option<DriverRecord>> {
118        let document = self
119            .records()
120            .find_one(doc! { "_id": id })
121            .await
122            .map_err(|error| store_error("read the driver table", &error))?;
123        document.map(|document| json("driver", text(&document, "record")?)).transpose()
124    }
125
126    async fn list(&self) -> Result<Vec<DriverRecord>> {
127        let cursor = self
128            .records()
129            .find(Document::new())
130            .with_options(sorted(doc! { "_id": 1 }, None))
131            .await
132            .map_err(|error| store_error("list the driver table", &error))?;
133        collect(cursor, "list the driver table")
134            .await?
135            .iter()
136            .map(|document| json("driver", text(document, "record")?))
137            .collect()
138    }
139
140    async fn delete(&self, id: &str) -> Result<bool> {
141        let result = self
142            .records()
143            .delete_one(doc! { "_id": id })
144            .await
145            .map_err(|error| store_error("delete from the driver table", &error))?;
146        Ok(result.deleted_count == 1)
147    }
148
149    async fn put_park(&self, park: DriverPark) -> Result<()> {
150        let id = park_id(&park.scope, &park.call_id);
151        let document = doc! {
152            "_id": id.clone(),
153            "driver": &park.driver,
154            "app": &park.scope.app_name,
155            "user": &park.scope.user_id,
156            "session": &park.scope.session_id,
157            "call_id": &park.call_id,
158            "park": serde_json::to_string(&park)?,
159        };
160        let parks = self.parks();
161        retry_upsert("write the driver table", || {
162            parks.replace_one(doc! { "_id": id.clone() }, document.clone()).upsert(true)
163        })
164        .await?;
165        Ok(())
166    }
167
168    async fn get_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<Option<DriverPark>> {
169        let document = self
170            .parks()
171            .find_one(doc! { "_id": park_id(scope, call_id) })
172            .await
173            .map_err(|error| store_error("read the driver table", &error))?;
174        document.map(|document| json("parked driver call", text(&document, "park")?)).transpose()
175    }
176
177    async fn list_parks(&self, driver: Option<&str>) -> Result<Vec<DriverPark>> {
178        let filter = driver.map_or_else(Document::new, |driver| doc! { "driver": driver });
179        let cursor = self
180            .parks()
181            .find(filter)
182            .with_options(sorted(doc! { "app": 1, "user": 1, "session": 1, "call_id": 1 }, None))
183            .await
184            .map_err(|error| store_error("list the driver table", &error))?;
185        collect(cursor, "list the driver table")
186            .await?
187            .iter()
188            .map(|document| json("parked driver call", text(document, "park")?))
189            .collect()
190    }
191
192    async fn delete_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<bool> {
193        let result = self
194            .parks()
195            .delete_one(doc! { "_id": park_id(scope, call_id) })
196            .await
197            .map_err(|error| store_error("delete from the driver table", &error))?;
198        Ok(result.deleted_count == 1)
199    }
200}