Skip to main content

adk_kernel/stores/
watermark_firestore.rs

1//! The Firestore [`CronWatermarkStore`] (spec 3.2 §7.4, §13 Q8, feature `firestore`).
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6use chrono::{DateTime, Utc};
7use firestore::FirestoreDb;
8use serde::{Deserialize, Serialize};
9
10use super::firestore::{
11    TxFuture, connect, delete_where, doc_id, store_error, transaction_error, transaction_options,
12    tx_fail,
13};
14use crate::error::Result;
15use crate::watermark::CronWatermarkStore;
16
17const WATERMARKS: &str = "adk_kernel_cron_watermarks";
18
19/// One source's cursor, as stored.
20#[derive(Debug, Clone, Serialize, Deserialize)]
21struct WatermarkDoc {
22    source: String,
23    cursor_us: i64,
24}
25
26/// A [`CronWatermarkStore`] in Firestore, shared by every replica (spec 3.2 §7.4, §13 Q8,
27/// feature `firestore`).
28///
29/// | Collection (document ID) | Contents |
30/// |--------------------------|----------|
31/// | `adk_kernel_cron_watermarks` (hex of the source's name) | `source` and `cursor_us`, the cursor in microseconds since the Unix epoch |
32///
33/// An advance reads the cursor and writes the later one in one serializable transaction,
34/// so of two replicas advancing one source at once the second retries, sees the first's
35/// write and never moves the cursor back. A source name longer than 700 bytes is refused.
36///
37/// # Example
38///
39/// ```rust,no_run
40/// # async fn example() -> adk_kernel::Result<()> {
41/// let store = adk_kernel::FirestoreCronWatermarkStore::connect("my-project").await?;
42/// store.migrate().await?;
43/// # Ok(())
44/// # }
45/// ```
46#[derive(Clone)]
47pub struct FirestoreCronWatermarkStore {
48    db: FirestoreDb,
49}
50
51impl std::fmt::Debug for FirestoreCronWatermarkStore {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        f.debug_struct("FirestoreCronWatermarkStore").finish_non_exhaustive()
54    }
55}
56
57impl FirestoreCronWatermarkStore {
58    /// A store over `db`, such as the process store's.
59    pub fn from_db(db: FirestoreDb) -> Self {
60        Self { db }
61    }
62
63    /// Connects to `project_id` with Application Default Credentials.
64    ///
65    /// # Errors
66    ///
67    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the client cannot be
68    /// created.
69    pub async fn connect(project_id: &str) -> Result<Self> {
70        Ok(Self::from_db(connect(project_id).await?))
71    }
72
73    /// The client the store uses.
74    pub fn db(&self) -> &FirestoreDb {
75        &self.db
76    }
77
78    /// Prepares the store's storage; Firestore needs nothing created, so this does nothing.
79    ///
80    /// # Errors
81    ///
82    /// Never returns an error.
83    pub async fn migrate(&self) -> Result<()> {
84        Ok(())
85    }
86}
87
88/// The instant `micros` microseconds after the Unix epoch.
89fn instant(micros: i64) -> Result<DateTime<Utc>> {
90    DateTime::from_timestamp_micros(micros).ok_or_else(|| {
91        store_error("read a cron watermark", &format!("the cursor {micros} is out of range"))
92    })
93}
94
95#[async_trait]
96impl CronWatermarkStore for FirestoreCronWatermarkStore {
97    async fn read(&self, source: &str) -> Result<Option<DateTime<Utc>>> {
98        let Ok(doc_name) = doc_id("cron source", source) else {
99            return Ok(None);
100        };
101        let doc: Option<WatermarkDoc> = self
102            .db
103            .fluent()
104            .select()
105            .by_id_in(WATERMARKS)
106            .obj()
107            .one(doc_name)
108            .await
109            .map_err(|error| store_error("read a cron watermark", &error))?;
110        doc.filter(|doc| doc.source == source).map(|doc| instant(doc.cursor_us)).transpose()
111    }
112
113    async fn advance(&self, source: &str, cursor: DateTime<Utc>) -> Result<DateTime<Utc>> {
114        let doc_name = Arc::new(doc_id("cron source", source)?);
115        let doc = Arc::new(WatermarkDoc {
116            source: source.to_string(),
117            cursor_us: cursor.timestamp_micros(),
118        });
119        let stored = self
120            .db
121            .run_transaction_with_options(
122                move |db, transaction| -> TxFuture<'_, i64> {
123                    let (doc_name, doc) = (doc_name.clone(), doc.clone());
124                    Box::pin(async move {
125                        let stored: Option<WatermarkDoc> = db
126                            .fluent()
127                            .select()
128                            .by_id_in(WATERMARKS)
129                            .obj()
130                            .one(doc_name.as_str())
131                            .await
132                            .map_err(tx_fail("read a cron watermark"))?;
133                        // A document holding another name reads as no cursor, as in `read`.
134                        if let Some(stored) = stored.filter(|stored| {
135                            stored.source == doc.source && stored.cursor_us >= doc.cursor_us
136                        }) {
137                            return Ok(stored.cursor_us);
138                        }
139                        db.fluent()
140                            .update()
141                            .in_col(WATERMARKS)
142                            .document_id(doc_name.as_str())
143                            .object(doc.as_ref())
144                            .add_to_transaction(transaction)
145                            .map_err(tx_fail("advance a cron watermark"))?;
146                        Ok(doc.cursor_us)
147                    })
148                },
149                transaction_options(),
150            )
151            .await
152            .map_err(|error| transaction_error(error, "advance a cron watermark"))?;
153        instant(stored)
154    }
155
156    async fn delete(&self, source: &str) -> Result<bool> {
157        let Ok(doc_name) = doc_id("cron source", source) else {
158            return Ok(false);
159        };
160        let source = source.to_string();
161        let matches = move |doc: &WatermarkDoc| doc.source == source;
162        delete_where(&self.db, WATERMARKS, doc_name, matches, "delete a cron watermark").await
163    }
164}