Skip to main content

adk_kernel/stores/
partition_mongodb.rs

1//! The MongoDB [`PartitionStore`] (spec 3.2 §7.8, §13 Q8, feature `mongodb`).
2
3use async_trait::async_trait;
4use mongodb::bson::{Document, doc};
5use mongodb::{Collection, Database};
6
7use super::mongodb::{
8    collect, connect, create_indexes, json, retry_upsert, sorted, store_error, text,
9};
10use crate::error::Result;
11use crate::partition::{CrossingFilter, CrossingRecord, Partition, PartitionId, PartitionStore};
12
13const PARTITIONS: &str = "adk_kernel_partitions";
14const CROSSINGS: &str = "adk_kernel_crossings";
15const GRANTS: &str = "adk_kernel_crossing_grants";
16
17/// A [`PartitionStore`] in MongoDB, shared by every replica (spec 3.2 §7.1, §7.8, §13 Q8,
18/// feature `mongodb`).
19///
20/// | Collection | `_id` | Contents |
21/// |------------|-------|----------|
22/// | `adk_kernel_partitions` | The partition id | `record`, the partition as JSON text |
23/// | `adk_kernel_crossings` | The crossing id | `at_us` (microseconds since the Unix epoch), `run`, `from`, `to`, `fingerprint` and `outcome`, the fields `crossings` filters on, and `record`, the crossing as JSON text |
24/// | `adk_kernel_crossing_grants` | `{run, fingerprint}` | `run` and `fingerprint`: one live grant |
25///
26/// Sorts use MongoDB's binary string comparison, so partitions order by their ids' UTF-8
27/// bytes and crossings by time, then id, as on every backend. A crossing is inserted once
28/// and never changed. A grant is an upsert, so granting twice keeps one grant;
29/// `release_run` deletes a run's grants in one `deleteMany` and answers how many it
30/// deleted. Every write is a single-document write or one `deleteMany`, so a standalone
31/// `mongod` serves the store as a replica set does.
32///
33/// # Example
34///
35/// ```rust,no_run
36/// # async fn example() -> adk_kernel::Result<()> {
37/// let store =
38///     adk_kernel::MongoPartitionStore::connect("mongodb://localhost:27017", "adk").await?;
39/// store.migrate().await?;
40/// # Ok(())
41/// # }
42/// ```
43#[derive(Debug, Clone)]
44pub struct MongoPartitionStore {
45    db: Database,
46}
47
48impl MongoPartitionStore {
49    /// A store over `db`, such as the process store's.
50    pub fn from_database(db: Database) -> Self {
51        Self { db }
52    }
53
54    /// Connects to `connection_string` and uses the database `database_name`.
55    ///
56    /// # Errors
57    ///
58    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the connection string
59    /// is invalid.
60    pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
61        Ok(Self::from_database(connect(connection_string, database_name).await?))
62    }
63
64    /// The database the store writes to.
65    pub fn database(&self) -> &Database {
66        &self.db
67    }
68
69    /// Creates the indexes `crossings` and `grants` read; an index that exists is kept.
70    ///
71    /// # Errors
72    ///
73    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server cannot be
74    /// reached or refuses an index.
75    pub async fn migrate(&self) -> Result<()> {
76        create_indexes(
77            &self.crossing_rows(),
78            &[
79                ("adk_kernel_crossings_at", doc! { "at_us": 1, "_id": 1 }),
80                ("adk_kernel_crossings_run", doc! { "run": 1, "at_us": 1, "_id": 1 }),
81                ("adk_kernel_crossings_from", doc! { "from": 1, "at_us": 1, "_id": 1 }),
82                ("adk_kernel_crossings_to", doc! { "to": 1, "at_us": 1, "_id": 1 }),
83            ],
84        )
85        .await?;
86        create_indexes(
87            &self.grant_rows(),
88            &[("adk_kernel_crossing_grants_run", doc! { "run": 1, "fingerprint": 1 })],
89        )
90        .await
91    }
92
93    fn partition_rows(&self) -> Collection<Document> {
94        self.db.collection(PARTITIONS)
95    }
96
97    fn crossing_rows(&self) -> Collection<Document> {
98        self.db.collection(CROSSINGS)
99    }
100
101    fn grant_rows(&self) -> Collection<Document> {
102        self.db.collection(GRANTS)
103    }
104}
105
106fn decode_partition(document: &Document) -> Result<Partition> {
107    json("partition", text(document, "record")?)
108}
109
110#[async_trait]
111impl PartitionStore for MongoPartitionStore {
112    async fn put(&self, partition: Partition) -> Result<()> {
113        let id = partition.id.as_str().to_string();
114        let document = doc! { "_id": &id, "record": serde_json::to_string(&partition)? };
115        let rows = self.partition_rows();
116        retry_upsert("write the partition table", || {
117            rows.replace_one(doc! { "_id": &id }, document.clone()).upsert(true)
118        })
119        .await?;
120        Ok(())
121    }
122
123    async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
124        let document = self
125            .partition_rows()
126            .find_one(doc! { "_id": id.as_str() })
127            .await
128            .map_err(|error| store_error("read the partition table", &error))?;
129        document.as_ref().map(decode_partition).transpose()
130    }
131
132    async fn list(&self) -> Result<Vec<Partition>> {
133        let cursor = self
134            .partition_rows()
135            .find(Document::new())
136            .with_options(sorted(doc! { "_id": 1 }, None))
137            .await
138            .map_err(|error| store_error("list the partition table", &error))?;
139        collect(cursor, "list the partition table").await?.iter().map(decode_partition).collect()
140    }
141
142    async fn delete(&self, id: &PartitionId) -> Result<bool> {
143        let result = self
144            .partition_rows()
145            .delete_one(doc! { "_id": id.as_str() })
146            .await
147            .map_err(|error| store_error("delete from the partition table", &error))?;
148        Ok(result.deleted_count == 1)
149    }
150
151    async fn record_crossing(&self, record: CrossingRecord) -> Result<()> {
152        self.crossing_rows()
153            .insert_one(doc! {
154                "_id": &record.id,
155                "at_us": record.at.timestamp_micros(),
156                "run": &record.run,
157                "from": record.from.as_str(),
158                "to": record.to.as_str(),
159                "fingerprint": &record.fingerprint,
160                "outcome": record.outcome.as_str(),
161                "record": serde_json::to_string(&record)?,
162            })
163            .await
164            .map_err(|error| store_error("record a crossing", &error))?;
165        Ok(())
166    }
167
168    async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
169        if filter.limit == Some(0) {
170            return Ok(Vec::new());
171        }
172        let mut query = Document::new();
173        if let Some(from) = &filter.from {
174            query.insert("from", from.as_str());
175        }
176        if let Some(to) = &filter.to {
177            query.insert("to", to.as_str());
178        }
179        if let Some(run) = &filter.run {
180            query.insert("run", run);
181        }
182        if let Some(fingerprint) = &filter.fingerprint {
183            query.insert("fingerprint", fingerprint);
184        }
185        if !filter.outcomes.is_empty() {
186            let outcomes: Vec<&str> =
187                filter.outcomes.iter().map(|outcome| outcome.as_str()).collect();
188            query.insert("outcome", doc! { "$in": outcomes });
189        }
190        if let Some(since) = filter.since {
191            query.insert("at_us", doc! { "$gte": since.timestamp_micros() });
192        }
193        let cursor = self
194            .crossing_rows()
195            .find(query)
196            .with_options(sorted(doc! { "at_us": 1, "_id": 1 }, filter.limit))
197            .await
198            .map_err(|error| store_error("read the crossings", &error))?;
199        collect(cursor, "read the crossings")
200            .await?
201            .iter()
202            .map(|document| json("crossing record", text(document, "record")?))
203            .collect()
204    }
205
206    async fn grant(&self, run: &str, fingerprint: &str) -> Result<()> {
207        let id = doc! { "run": run, "fingerprint": fingerprint };
208        let update = doc! { "$setOnInsert": { "run": run, "fingerprint": fingerprint } };
209        let rows = self.grant_rows();
210        retry_upsert("record a crossing grant", || {
211            rows.update_one(doc! { "_id": id.clone() }, update.clone()).upsert(true)
212        })
213        .await?;
214        Ok(())
215    }
216
217    async fn grants(&self, run: &str) -> Result<Vec<String>> {
218        let cursor = self
219            .grant_rows()
220            .find(doc! { "run": run })
221            .with_options(sorted(doc! { "fingerprint": 1 }, None))
222            .await
223            .map_err(|error| store_error("read the crossing grants", &error))?;
224        collect(cursor, "read the crossing grants")
225            .await?
226            .iter()
227            .map(|document| text(document, "fingerprint").map(str::to_string))
228            .collect()
229    }
230
231    async fn release_run(&self, run: &str) -> Result<u64> {
232        let result = self
233            .grant_rows()
234            .delete_many(doc! { "run": run })
235            .await
236            .map_err(|error| store_error("release the crossing grants", &error))?;
237        Ok(result.deleted_count)
238    }
239}