1use std::sync::Arc;
4
5use async_trait::async_trait;
6use firestore::{FirestoreDb, FirestoreQueryDirection};
7use serde::{Deserialize, Serialize};
8
9use super::day_number;
10use super::firestore::{
11 BACKEND, TxFuture, connect, doc_id, json, store_error, transaction_error, transaction_options,
12 tx_fail,
13};
14use crate::error::{KernelError, Result};
15use crate::partition::PartitionId;
16use crate::proc::{
17 LedgerEntry, LedgerQuery, LedgerStore, Observation, ObservationQuery, PassState,
18 order_observations,
19};
20
21const LEDGER: &str = "adk_kernel_ledger";
22const COUNTERS: &str = "adk_kernel_ledger_counters";
23const OBSERVATIONS: &str = "adk_kernel_observations";
24const PASS_STATES: &str = "adk_kernel_proc_state";
25
26const SEQUENCE: &str = "ledger";
28
29const CHUNK: u32 = 512;
31
32#[derive(Debug, Clone, Default, Serialize, Deserialize)]
34struct CounterDoc {
35 seq: i64,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
40struct RowDoc {
41 seq: i64,
42 ts_ms: i64,
43 partition: String,
44 agent: String,
45 kind: String,
46 row: String,
47}
48
49impl RowDoc {
50 fn decode(&self) -> Result<LedgerEntry> {
51 let mut entry: LedgerEntry = json("ledger row", &self.row)?;
52 entry.seq = u64::try_from(self.seq).map_err(|_| KernelError::Store {
53 backend: BACKEND,
54 reason: format!("a ledger row has the negative sequence number {}", self.seq),
55 })?;
56 Ok(entry)
57 }
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
62struct ObservationDoc {
63 id: String,
64 partition: String,
65 as_of: i64,
66 body: String,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize)]
71struct PassStateDoc {
72 partition: String,
73 body: String,
74}
75
76fn row_id(seq: i64) -> String {
79 format!("{seq:020}")
80}
81
82#[derive(Clone)]
110pub struct FirestoreLedgerStore {
111 db: FirestoreDb,
112}
113
114impl std::fmt::Debug for FirestoreLedgerStore {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 f.debug_struct("FirestoreLedgerStore").finish_non_exhaustive()
117 }
118}
119
120impl FirestoreLedgerStore {
121 pub fn from_db(db: FirestoreDb) -> Self {
123 Self { db }
124 }
125
126 pub async fn connect(project_id: &str) -> Result<Self> {
132 Ok(Self::from_db(connect(project_id).await?))
133 }
134
135 pub fn db(&self) -> &FirestoreDb {
137 &self.db
138 }
139
140 pub async fn migrate(&self) -> Result<()> {
146 Ok(())
147 }
148
149 async fn page(&self, cursor: i64) -> Result<Vec<RowDoc>> {
151 self.db
152 .fluent()
153 .select()
154 .from(LEDGER)
155 .filter(|q| q.for_all([q.field("seq").greater_than(cursor)]))
156 .order_by([("seq", FirestoreQueryDirection::Ascending)])
157 .limit(CHUNK)
158 .obj()
159 .query()
160 .await
161 .map_err(|error| store_error("read the ledger", &error))
162 }
163
164 async fn window(&self, query: &LedgerQuery) -> Result<Vec<RowDoc>> {
166 let from = query.from.map(|from| from.timestamp_millis());
167 let to = query.to.map(|to| to.timestamp_millis());
168 self.db
169 .fluent()
170 .select()
171 .from(LEDGER)
172 .filter(|q| {
173 q.for_all([
174 from.and_then(|from| q.field("ts_ms").greater_than_or_equal(from)),
175 to.and_then(|to| q.field("ts_ms").less_than(to)),
176 ])
177 })
178 .order_by([("ts_ms", FirestoreQueryDirection::Ascending)])
179 .obj()
180 .query()
181 .await
182 .map_err(|error| store_error("read the ledger", &error))
183 }
184}
185
186#[async_trait]
187impl LedgerStore for FirestoreLedgerStore {
188 async fn append(&self, mut entry: LedgerEntry) -> Result<LedgerEntry> {
189 entry.seq = 0;
190 let row = Arc::new(RowDoc {
191 seq: 0,
192 ts_ms: entry.ts.timestamp_millis(),
193 partition: entry.partition.as_str().to_string(),
194 agent: entry.agent.clone(),
195 kind: entry.kind.clone(),
196 row: serde_json::to_string(&entry)?,
197 });
198 let seq = self
199 .db
200 .run_transaction_with_options(
201 move |db, transaction| -> TxFuture<'_, i64> {
202 let row = row.clone();
203 Box::pin(async move {
204 let counter: Option<CounterDoc> = db
205 .fluent()
206 .select()
207 .by_id_in(COUNTERS)
208 .obj()
209 .one(SEQUENCE)
210 .await
211 .map_err(tx_fail("take a ledger sequence number"))?;
212 let seq = counter.unwrap_or_default().seq + 1;
213 db.fluent()
214 .update()
215 .in_col(COUNTERS)
216 .document_id(SEQUENCE)
217 .object(&CounterDoc { seq })
218 .add_to_transaction(transaction)
219 .map_err(tx_fail("take a ledger sequence number"))?;
220 db.fluent()
221 .update()
222 .in_col(LEDGER)
223 .document_id(row_id(seq))
224 .object(&RowDoc { seq, ..(*row).clone() })
225 .add_to_transaction(transaction)
226 .map_err(tx_fail("append to the ledger"))?;
227 Ok(seq)
228 })
229 },
230 transaction_options(),
231 )
232 .await
233 .map_err(|error| transaction_error(error, "append to the ledger"))?;
234 entry.seq = u64::try_from(seq).map_err(|_| KernelError::Store {
235 backend: BACKEND,
236 reason: format!("the ledger counter holds a negative sequence number {seq}"),
237 })?;
238 Ok(entry)
239 }
240
241 async fn list(&self, query: &LedgerQuery) -> Result<Vec<LedgerEntry>> {
242 let limit = query.limit.unwrap_or(usize::MAX);
243 let mut found = Vec::new();
244 if limit == 0 {
245 return Ok(found);
246 }
247 let mut rest = query.clone();
250 rest.from = None;
251 rest.to = None;
252 if query.from.is_some() || query.to.is_some() {
253 let mut rows = self.window(query).await?;
254 rows.sort_by_key(|row| row.seq);
255 for row in &rows {
256 let entry = row.decode()?;
257 if rest.matches(&entry) {
258 found.push(entry);
259 if found.len() == limit {
260 break;
261 }
262 }
263 }
264 return Ok(found);
265 }
266 let mut cursor = query.after.map_or(0, |after| i64::try_from(after).unwrap_or(i64::MAX));
267 loop {
268 let rows = self.page(cursor).await?;
269 for row in &rows {
270 cursor = row.seq;
271 let entry = row.decode()?;
272 if rest.matches(&entry) {
273 found.push(entry);
274 if found.len() == limit {
275 return Ok(found);
276 }
277 }
278 }
279 if rows.len() < CHUNK as usize {
280 return Ok(found);
281 }
282 }
283 }
284
285 async fn put_observation(&self, observation: Observation) -> Result<()> {
286 let doc = ObservationDoc {
287 id: observation.id.clone(),
288 partition: observation.partition.as_str().to_string(),
289 as_of: day_number(observation.as_of),
290 body: serde_json::to_string(&observation)?,
291 };
292 self.db
293 .fluent()
294 .update()
295 .in_col(OBSERVATIONS)
296 .document_id(doc_id("observation", &observation.id)?)
297 .object(&doc)
298 .execute::<ObservationDoc>()
299 .await
300 .map(|_| ())
301 .map_err(|error| store_error("write an observation", &error))
302 }
303
304 async fn observations(&self, query: &ObservationQuery) -> Result<Vec<Observation>> {
305 let docs: Vec<ObservationDoc> = self
306 .db
307 .fluent()
308 .select()
309 .from(OBSERVATIONS)
310 .filter(|q| {
311 q.for_all([query
312 .partition
313 .as_ref()
314 .and_then(|partition| q.field("partition").eq(partition.as_str()))])
315 })
316 .obj()
317 .query()
318 .await
319 .map_err(|error| store_error("read the observations", &error))?;
320 let mut observations = docs
321 .iter()
322 .map(|doc| json::<Observation>("observation", &doc.body))
323 .collect::<Result<Vec<_>>>()?;
324 observations.retain(|observation| query.matches(observation));
325 order_observations(&mut observations);
326 observations.truncate(query.limit.unwrap_or(usize::MAX));
327 Ok(observations)
328 }
329
330 async fn pass_state(&self, partition: &PartitionId) -> Result<Option<PassState>> {
331 let Ok(doc_name) = doc_id("partition", partition.as_str()) else {
332 return Ok(None);
333 };
334 let doc: Option<PassStateDoc> = self
335 .db
336 .fluent()
337 .select()
338 .by_id_in(PASS_STATES)
339 .obj()
340 .one(doc_name)
341 .await
342 .map_err(|error| store_error("read the pass state", &error))?;
343 doc.filter(|doc| doc.partition == partition.as_str())
344 .map(|doc| json("pass state", &doc.body))
345 .transpose()
346 }
347
348 async fn pass_states(&self) -> Result<Vec<PassState>> {
349 let docs: Vec<PassStateDoc> = self
350 .db
351 .fluent()
352 .select()
353 .from(PASS_STATES)
354 .obj()
355 .query()
356 .await
357 .map_err(|error| store_error("read the pass states", &error))?;
358 let mut states = docs
359 .iter()
360 .map(|doc| json::<PassState>("pass state", &doc.body))
361 .collect::<Result<Vec<_>>>()?;
362 states.sort_by(|a, b| a.partition.cmp(&b.partition));
363 Ok(states)
364 }
365
366 async fn put_pass_state(&self, state: PassState) -> Result<()> {
367 let doc = PassStateDoc {
368 partition: state.partition.as_str().to_string(),
369 body: serde_json::to_string(&state)?,
370 };
371 self.db
372 .fluent()
373 .update()
374 .in_col(PASS_STATES)
375 .document_id(doc_id("partition", state.partition.as_str())?)
376 .object(&doc)
377 .execute::<PassStateDoc>()
378 .await
379 .map(|_| ())
380 .map_err(|error| store_error("write the pass state", &error))
381 }
382}