Skip to main content

adk_kernel/stores/
watermark_mongodb.rs

1//! The MongoDB [`CronWatermarkStore`] (spec 3.2 §7.4, §13 Q8, feature `mongodb`).
2
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use mongodb::bson::{Document, doc};
6use mongodb::options::ReturnDocument;
7use mongodb::{Collection, Database};
8
9use super::mongodb::{connect, read_i64, retry_upsert, store_error};
10use crate::error::Result;
11use crate::watermark::CronWatermarkStore;
12
13const WATERMARKS: &str = "adk_kernel_cron_watermarks";
14
15/// A [`CronWatermarkStore`] in MongoDB, shared by every replica (spec 3.2 §7.4, §13 Q8,
16/// feature `mongodb`).
17///
18/// | Collection | `_id` | Contents |
19/// |------------|-------|----------|
20/// | `adk_kernel_cron_watermarks` | The source's name | `cursor_us`, the cursor in microseconds since the Unix epoch |
21///
22/// An advance is one `findOneAndUpdate` upsert with `$max`, which keeps the later of the
23/// stored cursor and the one given and returns the document as stored, so replicas writing
24/// in any order never move a cursor back. Every read and write is by `_id`, and every write
25/// is a single-document write, so a standalone `mongod` serves the store as a replica set
26/// does.
27///
28/// # Example
29///
30/// ```rust,no_run
31/// # async fn example() -> adk_kernel::Result<()> {
32/// let store =
33///     adk_kernel::MongoCronWatermarkStore::connect("mongodb://localhost:27017", "adk").await?;
34/// store.migrate().await?;
35/// # Ok(())
36/// # }
37/// ```
38#[derive(Debug, Clone)]
39pub struct MongoCronWatermarkStore {
40    db: Database,
41}
42
43impl MongoCronWatermarkStore {
44    /// A store over `db`, such as the process store's.
45    pub fn from_database(db: Database) -> Self {
46        Self { db }
47    }
48
49    /// Connects to `connection_string` and uses the database `database_name`.
50    ///
51    /// # Errors
52    ///
53    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the connection string
54    /// is invalid.
55    pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
56        Ok(Self::from_database(connect(connection_string, database_name).await?))
57    }
58
59    /// The database the store writes to.
60    pub fn database(&self) -> &Database {
61        &self.db
62    }
63
64    /// Prepares the store's storage. MongoDB creates the collection on first write and the
65    /// `_id` index serves every read, so there is nothing to create; the method exists so
66    /// every backend is set up the same way.
67    ///
68    /// # Errors
69    ///
70    /// Never returns an error.
71    pub async fn migrate(&self) -> Result<()> {
72        Ok(())
73    }
74
75    fn cursors(&self) -> Collection<Document> {
76        self.db.collection(WATERMARKS)
77    }
78}
79
80/// The instant a stored document's cursor names.
81fn instant(document: &Document) -> Result<DateTime<Utc>> {
82    let micros = read_i64(document, "cursor_us")
83        .ok_or_else(|| store_error("read a cron watermark", &"the cursor is not an integer"))?;
84    DateTime::from_timestamp_micros(micros).ok_or_else(|| {
85        store_error("read a cron watermark", &format!("the cursor {micros} is out of range"))
86    })
87}
88
89#[async_trait]
90impl CronWatermarkStore for MongoCronWatermarkStore {
91    async fn read(&self, source: &str) -> Result<Option<DateTime<Utc>>> {
92        let document = self
93            .cursors()
94            .find_one(doc! { "_id": source })
95            .await
96            .map_err(|error| store_error("read a cron watermark", &error))?;
97        document.as_ref().map(instant).transpose()
98    }
99
100    async fn advance(&self, source: &str, cursor: DateTime<Utc>) -> Result<DateTime<Utc>> {
101        let update = doc! { "$max": { "cursor_us": cursor.timestamp_micros() } };
102        let cursors = self.cursors();
103        let stored = retry_upsert("advance a cron watermark", || {
104            cursors
105                .find_one_and_update(doc! { "_id": source }, update.clone())
106                .upsert(true)
107                .return_document(ReturnDocument::After)
108        })
109        .await?;
110        stored.as_ref().map(instant).transpose()?.ok_or_else(|| {
111            store_error("advance a cron watermark", &"the upsert returned no document")
112        })
113    }
114
115    async fn delete(&self, source: &str) -> Result<bool> {
116        let result = self
117            .cursors()
118            .delete_one(doc! { "_id": source })
119            .await
120            .map_err(|error| store_error("delete a cron watermark", &error))?;
121        Ok(result.deleted_count == 1)
122    }
123}