Skip to main content

adk_kernel/stores/
agenda_mongodb.rs

1//! The MongoDB [`AgendaStore`] (spec 3.2 §7.1, §7.5, §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::agenda::{AgendaFilter, AgendaItem, AgendaStateKind, AgendaStore};
11use crate::error::Result;
12
13const AGENDA: &str = "adk_kernel_agenda";
14
15/// An [`AgendaStore`] in MongoDB, shared by every replica (spec 3.2 §7.1, §7.5, §13 Q8,
16/// feature `mongodb`).
17///
18/// One `adk_kernel_agenda` document per item, `_id` its id: `partition`, `state` (its kind)
19/// and `created_us` (microseconds since the Unix epoch), the fields `list` filters and sorts
20/// on, beside `item`, the item as JSON text, so it reads back exactly as written. `list`
21/// sorts by `created_us`, then `_id` under MongoDB's binary string comparison, so ties order
22/// by the ids' UTF-8 bytes. `transition` is one update filtered on `_id` and `state`, so two
23/// replicas moving one item from the same state move it once. Every write is a
24/// single-document write, so a standalone `mongod` serves it as a replica set does.
25///
26/// # Example
27///
28/// ```rust,no_run
29/// # async fn example() -> adk_kernel::Result<()> {
30/// let store = adk_kernel::MongoAgendaStore::connect("mongodb://localhost:27017", "adk").await?;
31/// store.migrate().await?;
32/// # Ok(())
33/// # }
34/// ```
35#[derive(Debug, Clone)]
36pub struct MongoAgendaStore {
37    db: Database,
38}
39
40impl MongoAgendaStore {
41    /// A store over `db`, such as the process store's.
42    pub fn from_database(db: Database) -> Self {
43        Self { db }
44    }
45
46    /// Connects to `connection_string` and uses the database `database_name`.
47    ///
48    /// # Errors
49    ///
50    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the connection string
51    /// is invalid.
52    pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
53        Ok(Self::from_database(connect(connection_string, database_name).await?))
54    }
55
56    /// The database the store writes to.
57    pub fn database(&self) -> &Database {
58        &self.db
59    }
60
61    /// Creates the indexes `list` reads; an index that exists is kept.
62    ///
63    /// # Errors
64    ///
65    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server cannot be
66    /// reached or refuses an index.
67    pub async fn migrate(&self) -> Result<()> {
68        create_indexes(
69            &self.items(),
70            &[
71                (
72                    "adk_kernel_agenda_partition",
73                    doc! { "partition": 1, "state": 1, "created_us": 1, "_id": 1 },
74                ),
75                ("adk_kernel_agenda_state", doc! { "state": 1, "created_us": 1, "_id": 1 }),
76                ("adk_kernel_agenda_created", doc! { "created_us": 1, "_id": 1 }),
77            ],
78        )
79        .await
80    }
81
82    fn items(&self) -> Collection<Document> {
83        self.db.collection(AGENDA)
84    }
85}
86
87/// The fields of `item` other than `_id`.
88fn fields(item: &AgendaItem) -> Result<Document> {
89    Ok(doc! {
90        "partition": item.partition.as_str(),
91        "state": item.state.kind().as_str(),
92        "created_us": item.created_at.timestamp_micros(),
93        "item": serde_json::to_string(item)?,
94    })
95}
96
97fn decode(document: &Document) -> Result<AgendaItem> {
98    json("agenda item", text(document, "item")?)
99}
100
101#[async_trait]
102impl AgendaStore for MongoAgendaStore {
103    async fn put(&self, item: AgendaItem) -> Result<()> {
104        let mut document = doc! { "_id": &item.id };
105        document.extend(fields(&item)?);
106        let items = self.items();
107        retry_upsert("write the agenda", || {
108            items.replace_one(doc! { "_id": &item.id }, document.clone()).upsert(true)
109        })
110        .await?;
111        Ok(())
112    }
113
114    async fn get(&self, id: &str) -> Result<Option<AgendaItem>> {
115        let document = self
116            .items()
117            .find_one(doc! { "_id": id })
118            .await
119            .map_err(|error| store_error("read the agenda", &error))?;
120        document.as_ref().map(decode).transpose()
121    }
122
123    async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>> {
124        if filter.limit == Some(0) {
125            return Ok(Vec::new());
126        }
127        let mut query = Document::new();
128        if let Some(partition) = &filter.partition {
129            query.insert("partition", partition.as_str());
130        }
131        if !filter.states.is_empty() {
132            let states: Vec<&str> = filter.states.iter().map(|state| state.as_str()).collect();
133            query.insert("state", doc! { "$in": states });
134        }
135        let cursor = self
136            .items()
137            .find(query)
138            .with_options(sorted(doc! { "created_us": 1, "_id": 1 }, filter.limit))
139            .await
140            .map_err(|error| store_error("list the agenda", &error))?;
141        collect(cursor, "list the agenda").await?.iter().map(decode).collect()
142    }
143
144    async fn transition(&self, item: AgendaItem, from: AgendaStateKind) -> Result<bool> {
145        let result = self
146            .items()
147            .update_one(
148                doc! { "_id": &item.id, "state": from.as_str() },
149                doc! { "$set": fields(&item)? },
150            )
151            .await
152            .map_err(|error| store_error("update the agenda", &error))?;
153        Ok(result.matched_count == 1)
154    }
155
156    async fn delete(&self, id: &str) -> Result<bool> {
157        let result = self
158            .items()
159            .delete_one(doc! { "_id": id })
160            .await
161            .map_err(|error| store_error("delete from the agenda", &error))?;
162        Ok(result.deleted_count == 1)
163    }
164}