adk_kernel/stores/
watermark_mongodb.rs1use 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#[derive(Debug, Clone)]
39pub struct MongoCronWatermarkStore {
40 db: Database,
41}
42
43impl MongoCronWatermarkStore {
44 pub fn from_database(db: Database) -> Self {
46 Self { db }
47 }
48
49 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 pub fn database(&self) -> &Database {
61 &self.db
62 }
63
64 pub async fn migrate(&self) -> Result<()> {
72 Ok(())
73 }
74
75 fn cursors(&self) -> Collection<Document> {
76 self.db.collection(WATERMARKS)
77 }
78}
79
80fn 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}