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