Skip to main content

adk_kernel/stores/
mongodb.rs

1//! The MongoDB [`ProcessStore`] (spec 3.2 §7.1, §13 Q8, feature `mongodb`), and the helpers
2//! the kernel's other MongoDB stores share.
3
4use async_trait::async_trait;
5use chrono::NaiveDate;
6use mongodb::bson::{Bson, Document, doc};
7use mongodb::error::{ErrorKind, WriteFailure};
8use mongodb::options::{ClientOptions, FindOptions, IndexOptions};
9use mongodb::{Client, Collection, Cursor, Database, IndexModel};
10
11use super::{
12    ProcessFilter, ProcessStore, SpendScope, UsageTotals, counters, day_number, stored_amount,
13    stored_micro_usd, stored_total,
14};
15use crate::bus::SpendDelta;
16use crate::error::{KernelError, Result};
17use crate::partition::PartitionId;
18use crate::process::ProcessMeta;
19use crate::sched::QueueClass;
20use crate::wake::WakeSet;
21
22const PROCESSES: &str = "adk_kernel_processes";
23const SPEND: &str = "adk_kernel_spend";
24
25/// The backend name in [`KernelError::Store`].
26pub(super) const BACKEND: &str = "mongodb";
27
28/// MongoDB's duplicate key error code.
29const DUPLICATE_KEY: i32 = 11000;
30
31/// Attempts at an upsert that collided with a concurrent one before the error is returned.
32const UPSERT_ATTEMPTS: u32 = 5;
33
34pub(super) fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
35    KernelError::Store { backend: BACKEND, reason: format!("could not {action}: {error}") }
36}
37
38/// The database `database_name` on the deployment `connection_string` names.
39pub(super) async fn connect(connection_string: &str, database_name: &str) -> Result<Database> {
40    let options = ClientOptions::parse(connection_string)
41        .await
42        .map_err(|error| store_error("parse the MongoDB connection string", &error))?;
43    let client = Client::with_options(options)
44        .map_err(|error| store_error("build the MongoDB client", &error))?;
45    Ok(client.database(database_name))
46}
47
48/// Creates each named index of `collection`; an index that exists is left as it is.
49pub(super) async fn create_indexes(
50    collection: &Collection<Document>,
51    indexes: &[(&str, Document)],
52) -> Result<()> {
53    for (name, keys) in indexes {
54        let model = IndexModel::builder()
55            .keys(keys.clone())
56            .options(IndexOptions::builder().name((*name).to_string()).build())
57            .build();
58        collection
59            .create_index(model)
60            .await
61            .map_err(|error| store_error(&format!("create the index {name}"), &error))?;
62    }
63    Ok(())
64}
65
66/// Every document `cursor` yields.
67pub(super) async fn collect(mut cursor: Cursor<Document>, action: &str) -> Result<Vec<Document>> {
68    let mut documents = Vec::new();
69    while cursor.advance().await.map_err(|error| store_error(action, &error))? {
70        documents.push(cursor.deserialize_current().map_err(|error| store_error(action, &error))?);
71    }
72    Ok(documents)
73}
74
75/// A text field every stored document of the kind has.
76pub(super) fn text<'a>(document: &'a Document, field: &str) -> Result<&'a str> {
77    document.get_str(field).map_err(|_| KernelError::Store {
78        backend: BACKEND,
79        reason: format!("a stored document has no text field `{field}`"),
80    })
81}
82
83/// A text field a stored document may lack.
84pub(super) fn optional_text(document: &Document, field: &str) -> Option<String> {
85    document.get_str(field).ok().map(str::to_string)
86}
87
88/// An integer field the server may return as `Int32`, `Int64` or `Double`.
89pub(super) fn read_i64(document: &Document, field: &str) -> Option<i64> {
90    match document.get(field)? {
91        Bson::Int32(value) => Some(i64::from(*value)),
92        Bson::Int64(value) => Some(*value),
93        Bson::Double(value) => Some(*value as i64),
94        _ => None,
95    }
96}
97
98/// JSON text a store wrote, read back.
99pub(super) fn json<T: serde::de::DeserializeOwned>(what: &str, text: &str) -> Result<T> {
100    serde_json::from_str(text).map_err(|error| KernelError::Store {
101        backend: BACKEND,
102        reason: format!("a stored {what} is corrupt: {error}"),
103    })
104}
105
106/// A `limit` as `find` takes it. `None` for no limit; callers answer a limit of 0 themselves,
107/// because MongoDB reads a limit of 0 as no limit.
108pub(super) fn find_limit(limit: Option<usize>) -> Option<i64> {
109    limit.map(|limit| i64::try_from(limit).unwrap_or(i64::MAX))
110}
111
112/// `find` options sorting by `sort` and returning at most `limit` documents.
113pub(super) fn sorted(sort: Document, limit: Option<usize>) -> FindOptions {
114    FindOptions::builder().sort(sort).limit(find_limit(limit)).build()
115}
116
117pub(super) fn is_duplicate_key(error: &mongodb::error::Error) -> bool {
118    match error.kind.as_ref() {
119        ErrorKind::Write(WriteFailure::WriteError(write)) => write.code == DUPLICATE_KEY,
120        ErrorKind::Command(command) => command.code == DUPLICATE_KEY,
121        _ => false,
122    }
123}
124
125/// Runs `upsert` again while it collides with a concurrent upsert of the same `_id`, which
126/// MongoDB reports as a duplicate key error on servers that do not retry it themselves.
127pub(super) async fn retry_upsert<T, F, Fut>(action: &str, mut upsert: F) -> Result<T>
128where
129    F: FnMut() -> Fut,
130    Fut: std::future::IntoFuture<Output = mongodb::error::Result<T>>,
131{
132    let mut attempt = 1;
133    loop {
134        match upsert().await {
135            Err(error) if is_duplicate_key(&error) && attempt < UPSERT_ATTEMPTS => attempt += 1,
136            result => return result.map_err(|error| store_error(action, &error)),
137        }
138    }
139}
140
141/// A [`ProcessStore`] in MongoDB, shared by every replica (spec 3.2 §7.1, §13 Q8, feature
142/// `mongodb`).
143///
144/// It works on a standalone `mongod`, a replica set or a sharded cluster: every change is a
145/// single-document write, so it needs no multi-document transaction.
146///
147/// | Collection | `_id` | Contents |
148/// |------------|-------|----------|
149/// | `adk_kernel_processes` | The pid | `partition`, `queue`, `suspend_requested` and, when set, `parent` and `agenda_item`, the fields `list` filters on; `kind`, `labels` and, when set, `wake` and `suspended_by` as JSON text |
150/// | `adk_kernel_spend` | `{pid, partition, day}` | `micro_usd`, with `pid`, `partition` and `day` (days from the common era) as the fields `spend` sums over, and `counters`: model calls, total tokens and units by name |
151///
152/// `list` sorts by `_id` under MongoDB's binary string comparison, so pids order by their
153/// UTF-8 bytes, as on every backend. `set_wake`, `set_queue` and `set_suspend_requested` each
154/// change one field, so writers changing different fields of one row never lose each other's
155/// update. `add_spend` is one `$inc` upsert, so concurrent additions all count; deleting a
156/// process keeps its spend, so a partition's totals for past days do not change when the run
157/// store prunes a finished run.
158///
159/// # Example
160///
161/// ```rust,no_run
162/// # async fn example() -> adk_kernel::Result<()> {
163/// let store = adk_kernel::MongoProcessStore::connect("mongodb://localhost:27017", "adk").await?;
164/// store.migrate().await?;
165/// # Ok(())
166/// # }
167/// ```
168#[derive(Debug, Clone)]
169pub struct MongoProcessStore {
170    db: Database,
171}
172
173impl MongoProcessStore {
174    /// A store over `db`, such as the database `adk_session::MongoRunStore::from_database`
175    /// uses, so the kernel's tables sit beside the run, schedule and governance stores.
176    pub fn from_database(db: Database) -> Self {
177        Self { db }
178    }
179
180    /// Connects to `connection_string` and uses the database `database_name`.
181    ///
182    /// # Errors
183    ///
184    /// Returns [`KernelError::Store`] when the connection string is invalid.
185    pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
186        Ok(Self::from_database(connect(connection_string, database_name).await?))
187    }
188
189    /// The database the store writes to.
190    pub fn database(&self) -> &Database {
191        &self.db
192    }
193
194    /// Creates the indexes `list` and `spend` read; an index that exists is kept.
195    ///
196    /// # Errors
197    ///
198    /// Returns [`KernelError::Store`] when the server cannot be reached or refuses an index.
199    pub async fn migrate(&self) -> Result<()> {
200        create_indexes(
201            &self.processes(),
202            &[
203                ("adk_kernel_processes_partition", doc! { "partition": 1, "_id": 1 }),
204                ("adk_kernel_processes_queue", doc! { "queue": 1, "_id": 1 }),
205                ("adk_kernel_processes_parent", doc! { "parent": 1, "_id": 1 }),
206                ("adk_kernel_processes_suspend", doc! { "suspend_requested": 1, "_id": 1 }),
207            ],
208        )
209        .await?;
210        create_indexes(
211            &self.spend_totals(),
212            &[
213                ("adk_kernel_spend_pid", doc! { "pid": 1, "day": 1 }),
214                ("adk_kernel_spend_partition", doc! { "partition": 1, "day": 1 }),
215            ],
216        )
217        .await
218    }
219
220    fn processes(&self) -> Collection<Document> {
221        self.db.collection(PROCESSES)
222    }
223
224    fn spend_totals(&self) -> Collection<Document> {
225        self.db.collection(SPEND)
226    }
227
228    /// Sets the fields `update` names on the row of `pid`, failing when there is none.
229    async fn update(&self, pid: &str, update: Document) -> Result<()> {
230        let result = self
231            .processes()
232            .update_one(doc! { "_id": pid }, update)
233            .await
234            .map_err(|error| store_error("update the process table", &error))?;
235        if result.matched_count == 0 {
236            return Err(KernelError::NotFound { pid: pid.into() });
237        }
238        Ok(())
239    }
240}
241
242/// The stored document of `meta`.
243fn encode(meta: &ProcessMeta) -> Result<Document> {
244    let mut document = doc! {
245        "_id": &meta.pid,
246        "partition": meta.partition.as_str(),
247        "queue": meta.queue.as_str(),
248        "kind": serde_json::to_string(&meta.kind)?,
249        "labels": serde_json::to_string(&meta.labels)?,
250        "suspend_requested": meta.suspend_requested,
251    };
252    if let Some(parent) = &meta.parent {
253        document.insert("parent", parent);
254    }
255    if let Some(wake) = &meta.wake {
256        document.insert("wake", serde_json::to_string(wake)?);
257    }
258    if let Some(suspension) = &meta.suspended_by {
259        document.insert("suspended_by", serde_json::to_string(suspension)?);
260    }
261    if let Some(item) = &meta.agenda_item {
262        document.insert("agenda_item", item);
263    }
264    Ok(document)
265}
266
267/// Reads a stored document back into the [`ProcessMeta`] that was put.
268fn decode(document: &Document) -> Result<ProcessMeta> {
269    let pid = text(document, "_id")?.to_string();
270    let structured = |field: &str| optional_text(document, field);
271    Ok(ProcessMeta {
272        parent: optional_text(document, "parent"),
273        partition: PartitionId::new(text(document, "partition")?),
274        queue: QueueClass::from_name(text(document, "queue")?),
275        kind: json("process kind", text(document, "kind")?)?,
276        wake: structured("wake").map(|wake| json("wake set", &wake)).transpose()?,
277        suspended_by: structured("suspended_by")
278            .map(|suspension| json("suspension", &suspension))
279            .transpose()?,
280        suspend_requested: document.get_bool("suspend_requested").unwrap_or(false),
281        agenda_item: optional_text(document, "agenda_item"),
282        labels: json("label set", text(document, "labels")?)?,
283        pid,
284    })
285}
286
287#[async_trait]
288impl ProcessStore for MongoProcessStore {
289    async fn put(&self, meta: ProcessMeta) -> Result<()> {
290        let document = encode(&meta)?;
291        let processes = self.processes();
292        retry_upsert("write the process table", || {
293            processes.replace_one(doc! { "_id": &meta.pid }, document.clone()).upsert(true)
294        })
295        .await?;
296        Ok(())
297    }
298
299    async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>> {
300        let document = self
301            .processes()
302            .find_one(doc! { "_id": pid })
303            .await
304            .map_err(|error| store_error("read the process table", &error))?;
305        document.as_ref().map(decode).transpose()
306    }
307
308    async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>> {
309        if filter.limit == Some(0) {
310            return Ok(Vec::new());
311        }
312        let mut query = Document::new();
313        if let Some(partition) = &filter.partition {
314            query.insert("partition", partition.as_str());
315        }
316        if let Some(queue) = &filter.queue {
317            query.insert("queue", queue.as_str());
318        }
319        if let Some(parent) = &filter.parent {
320            query.insert("parent", parent);
321        }
322        if let Some(requested) = filter.suspend_requested {
323            query.insert("suspend_requested", requested);
324        }
325        let cursor = self
326            .processes()
327            .find(query)
328            .with_options(sorted(doc! { "_id": 1 }, filter.limit))
329            .await
330            .map_err(|error| store_error("list processes", &error))?;
331        collect(cursor, "list processes").await?.iter().map(decode).collect()
332    }
333
334    async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()> {
335        let update = match &wake {
336            Some(wake) => doc! { "$set": { "wake": serde_json::to_string(wake)? } },
337            None => doc! { "$unset": { "wake": "" } },
338        };
339        self.update(pid, update).await
340    }
341
342    async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()> {
343        self.update(pid, doc! { "$set": { "queue": queue.as_str() } }).await
344    }
345
346    async fn delete(&self, pid: &str) -> Result<bool> {
347        let result = self
348            .processes()
349            .delete_one(doc! { "_id": pid })
350            .await
351            .map_err(|error| store_error("delete from the process table", &error))?;
352        Ok(result.deleted_count == 1)
353    }
354
355    async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()> {
356        self.update(pid, doc! { "$set": { "suspend_requested": requested } }).await
357    }
358
359    async fn add_spend(
360        &self,
361        pid: &str,
362        partition: &PartitionId,
363        day: NaiveDate,
364        delta: SpendDelta,
365    ) -> Result<()> {
366        let mut increments = doc! { "micro_usd": stored_micro_usd(BACKEND, &delta)? };
367        for (name, amount) in counters(&delta) {
368            increments.insert(format!("counters.{name}"), stored_amount(BACKEND, name, amount)?);
369        }
370        let day = day_number(day);
371        let key = doc! { "pid": pid, "partition": partition.as_str(), "day": day };
372        let update = doc! {
373            "$inc": increments,
374            "$setOnInsert": { "pid": pid, "partition": partition.as_str(), "day": day },
375        };
376        let totals = self.spend_totals();
377        retry_upsert("add to the spend totals", || {
378            totals.update_one(doc! { "_id": key.clone() }, update.clone()).upsert(true)
379        })
380        .await?;
381        Ok(())
382    }
383
384    async fn spend(
385        &self,
386        scope: &SpendScope,
387        from: NaiveDate,
388        to_inclusive: NaiveDate,
389    ) -> Result<u64> {
390        let mut filter = match scope {
391            SpendScope::Process(pid) => doc! { "pid": pid },
392            SpendScope::Partition(partition) => doc! { "partition": partition.as_str() },
393        };
394        filter.insert("day", doc! { "$gte": day_number(from), "$lte": day_number(to_inclusive) });
395        let pipeline = [
396            doc! { "$match": filter },
397            doc! { "$group": { "_id": Bson::Null, "total": { "$sum": "$micro_usd" } } },
398        ];
399        let cursor = self
400            .spend_totals()
401            .aggregate(pipeline)
402            .await
403            .map_err(|error| store_error("sum the spend totals", &error))?;
404        let rows = collect(cursor, "sum the spend totals").await?;
405        let sum = rows.first().and_then(|row| read_i64(row, "total")).unwrap_or(0);
406        stored_total(BACKEND, sum)
407    }
408
409    async fn usage(
410        &self,
411        scope: &SpendScope,
412        from: NaiveDate,
413        to_inclusive: NaiveDate,
414    ) -> Result<UsageTotals> {
415        let mut filter = match scope {
416            SpendScope::Process(pid) => doc! { "pid": pid },
417            SpendScope::Partition(partition) => doc! { "partition": partition.as_str() },
418        };
419        filter.insert("day", doc! { "$gte": day_number(from), "$lte": day_number(to_inclusive) });
420        let cursor = self
421            .spend_totals()
422            .find(filter)
423            .await
424            .map_err(|error| store_error("read the usage totals", &error))?;
425        let mut totals = UsageTotals::default();
426        for row in collect(cursor, "read the usage totals").await? {
427            let micro_usd = stored_total(BACKEND, read_i64(&row, "micro_usd").unwrap_or(0))?;
428            totals.micro_usd = totals.micro_usd.saturating_add(micro_usd);
429            let Ok(counters) = row.get_document("counters") else { continue };
430            for name in counters.keys() {
431                let amount = stored_total(BACKEND, read_i64(counters, name).unwrap_or(0))?;
432                totals.add_counter(name, amount);
433            }
434        }
435        Ok(totals)
436    }
437}