Skip to main content

adk_kernel/stores/
firestore.rs

1//! The Firestore [`ProcessStore`] (spec 3.2 §7.1, §13 Q8, feature `firestore`), and the
2//! helpers the kernel's other Firestore stores share.
3
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use chrono::NaiveDate;
8use firestore::errors::{BackoffError, FirestoreError};
9use firestore::{FirestoreDb, FirestoreTransactionOptions, FirestoreWritePrecondition};
10use futures::future::BoxFuture;
11use serde::{Deserialize, Serialize};
12
13use super::{
14    ProcessFilter, ProcessStore, SpendScope, UsageTotals, counters, day_number, stored_amount,
15    stored_micro_usd, stored_total,
16};
17use crate::bus::SpendDelta;
18use crate::error::{KernelError, Result};
19use crate::partition::PartitionId;
20use crate::process::ProcessMeta;
21use crate::sched::QueueClass;
22use crate::wake::WakeSet;
23
24const PROCESSES: &str = "adk_kernel_processes";
25const PROCESS_SPEND: &str = "adk_kernel_spend";
26const PARTITION_SPEND: &str = "adk_kernel_partition_spend";
27
28/// The backend name in [`KernelError::Store`].
29pub(super) const BACKEND: &str = "firestore";
30
31/// The longest identifier a document is named after: its hex must fit Firestore's 1,500-byte
32/// document IDs.
33const MAX_ID_BYTES: usize = 700;
34
35/// How long one operation may spend retrying transactions Firestore aborted for contention.
36const TRANSACTION_DEADLINE: chrono::TimeDelta = chrono::TimeDelta::seconds(120);
37
38pub(super) type TxResult<T> = std::result::Result<T, BackoffError<KernelError>>;
39pub(super) type TxFuture<'b, T> = BoxFuture<'b, TxResult<T>>;
40
41pub(super) fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
42    KernelError::Store { backend: BACKEND, reason: format!("could not {action}: {error}") }
43}
44
45/// A client of `project_id` with Application Default Credentials; the `firestore` crate
46/// reaches the emulator when `FIRESTORE_EMULATOR_HOST` is set.
47pub(super) async fn connect(project_id: &str) -> Result<FirestoreDb> {
48    FirestoreDb::new(project_id).await.map_err(|error| store_error("connect to Firestore", &error))
49}
50
51/// The document ID of `id`: the hex of its UTF-8 bytes, which holds no `/` and orders as
52/// the bytes do, so a query ordered by document name follows byte order as on every backend.
53pub(super) fn doc_id(what: &str, id: &str) -> Result<String> {
54    if id.len() > MAX_ID_BYTES {
55        return Err(KernelError::Store {
56            backend: BACKEND,
57            reason: format!(
58                "a Firestore {what} id is at most {MAX_ID_BYTES} bytes, and this one has {}",
59                id.len()
60            ),
61        });
62    }
63    Ok(id.bytes().map(|byte| format!("{byte:02x}")).collect())
64}
65
66/// The document ID of a key of several parts: the SHA-256 of their JSON array, in hex. The
67/// document stores the parts, and every read compares them.
68pub(super) fn digest_id(parts: &[&str]) -> String {
69    use sha2::Digest as _;
70
71    let encoded = serde_json::to_vec(parts).unwrap_or_default();
72    sha2::Sha256::digest(&encoded).iter().map(|byte| format!("{byte:02x}")).collect()
73}
74
75pub(super) fn transaction_options() -> FirestoreTransactionOptions {
76    FirestoreTransactionOptions::new().with_max_elapsed_time(TRANSACTION_DEADLINE)
77}
78
79/// Maps a failure inside a transaction: retried when Firestore says it may succeed, such as
80/// a contention abort.
81pub(super) fn tx_fail(
82    action: &'static str,
83) -> impl Fn(FirestoreError) -> BackoffError<KernelError> {
84    move |error| {
85        let retryable = matches!(&error, FirestoreError::DatabaseError(db) if db.retry_possible);
86        let error = store_error(action, &error);
87        if retryable { BackoffError::transient(error) } else { BackoffError::permanent(error) }
88    }
89}
90
91/// The [`KernelError`] a transaction body failed with, or the transaction's own failure.
92pub(super) fn transaction_error(error: FirestoreError, action: &str) -> KernelError {
93    match error {
94        FirestoreError::ErrorInTransaction(inner) => match inner.source.downcast::<KernelError>() {
95            Ok(error) => *error,
96            Err(source) => store_error(action, &source),
97        },
98        other => store_error(action, &other),
99    }
100}
101
102/// Deletes the document `doc_name` of `collection` when `matches` accepts what it holds,
103/// reading and deleting in one transaction, so of two concurrent deletes one answers `true`.
104pub(super) async fn delete_where<T>(
105    db: &FirestoreDb,
106    collection: &'static str,
107    doc_name: String,
108    matches: impl Fn(&T) -> bool + Send + Sync + 'static,
109    action: &'static str,
110) -> Result<bool>
111where
112    T: for<'de> Deserialize<'de> + Send + Sync + 'static,
113{
114    let (doc_name, matches) = (Arc::new(doc_name), Arc::new(matches));
115    db.run_transaction_with_options(
116        move |db, transaction| -> TxFuture<'_, bool> {
117            let (doc_name, matches) = (doc_name.clone(), matches.clone());
118            Box::pin(async move {
119                let stored: Option<T> = db
120                    .fluent()
121                    .select()
122                    .by_id_in(collection)
123                    .obj()
124                    .one(doc_name.as_str())
125                    .await
126                    .map_err(tx_fail(action))?;
127                if !stored.as_ref().is_some_and(|stored| matches(stored)) {
128                    return Ok(false);
129                }
130                db.fluent()
131                    .delete()
132                    .from(collection)
133                    .document_id(doc_name.as_str())
134                    .add_to_transaction(transaction)
135                    .map_err(tx_fail(action))?;
136                Ok(true)
137            })
138        },
139        transaction_options(),
140    )
141    .await
142    .map_err(|error| transaction_error(error, action))
143}
144
145/// JSON text a store wrote, read back.
146pub(super) fn json<T: serde::de::DeserializeOwned>(what: &str, text: &str) -> Result<T> {
147    serde_json::from_str(text).map_err(|error| KernelError::Store {
148        backend: BACKEND,
149        reason: format!("a stored {what} is corrupt: {error}"),
150    })
151}
152
153/// One process, as stored.
154#[derive(Debug, Clone, Serialize, Deserialize)]
155struct ProcessDoc {
156    pid: String,
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    parent: Option<String>,
159    partition: String,
160    queue: String,
161    kind: String,
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    wake: Option<String>,
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    suspended_by: Option<String>,
166    #[serde(default)]
167    suspend_requested: bool,
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    agenda_item: Option<String>,
170    labels: String,
171}
172
173impl ProcessDoc {
174    fn new(meta: &ProcessMeta) -> Result<Self> {
175        Ok(Self {
176            pid: meta.pid.clone(),
177            parent: meta.parent.clone(),
178            partition: meta.partition.as_str().to_string(),
179            queue: meta.queue.as_str().to_string(),
180            kind: serde_json::to_string(&meta.kind)?,
181            wake: meta.wake.as_ref().map(serde_json::to_string).transpose()?,
182            suspended_by: meta.suspended_by.as_ref().map(serde_json::to_string).transpose()?,
183            suspend_requested: meta.suspend_requested,
184            agenda_item: meta.agenda_item.clone(),
185            labels: serde_json::to_string(&meta.labels)?,
186        })
187    }
188
189    fn decode(self) -> Result<ProcessMeta> {
190        Ok(ProcessMeta {
191            kind: json("process kind", &self.kind)?,
192            wake: self.wake.map(|wake| json("wake set", &wake)).transpose()?,
193            suspended_by: self
194                .suspended_by
195                .map(|suspension| json("suspension", &suspension))
196                .transpose()?,
197            labels: json("label set", &self.labels)?,
198            partition: PartitionId::new(self.partition),
199            queue: QueueClass::from_name(&self.queue),
200            suspend_requested: self.suspend_requested,
201            agenda_item: self.agenda_item,
202            parent: self.parent,
203            pid: self.pid,
204        })
205    }
206}
207
208/// The fields one update of a process sets; `None` deletes the field.
209#[derive(Debug, Default, Serialize, Deserialize)]
210#[serde(default)]
211struct ProcessFields {
212    #[serde(skip_serializing_if = "Option::is_none")]
213    wake: Option<String>,
214    #[serde(skip_serializing_if = "Option::is_none")]
215    queue: Option<String>,
216    #[serde(skip_serializing_if = "Option::is_none")]
217    suspend_requested: Option<bool>,
218}
219
220/// One day's spend of a process, or of a partition when `pid` is absent.
221#[derive(Debug, Clone, Default, Serialize, Deserialize)]
222struct SpendDoc {
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pid: Option<String>,
225    partition: String,
226    day: i64,
227    #[serde(default, skip_serializing)]
228    micro_usd: i64,
229    /// Model calls, total tokens and units by name, written only by increments.
230    #[serde(default, skip_serializing)]
231    counters: std::collections::BTreeMap<String, i64>,
232}
233
234/// A [`ProcessStore`] in Firestore, shared by every replica (spec 3.2 §7.1, §13 Q8, feature
235/// `firestore`).
236///
237/// | Collection (document ID) | Contents |
238/// |--------------------------|----------|
239/// | `adk_kernel_processes` (hex of the pid) | `pid`, `partition`, `queue`, `suspend_requested` and, when set, `parent` and `agenda_item`; `kind`, `labels` and, when set, `wake` and `suspended_by` as JSON text |
240/// | `adk_kernel_spend` (SHA-256 of pid, partition and day) | One process's spend in one partition on one UTC day: `pid`, `partition`, `day` (days from the common era), `micro_usd`, and `counters`: model calls, total tokens and units by name |
241/// | `adk_kernel_partition_spend` (SHA-256 of partition and day) | One partition's spend on one UTC day: `partition`, `day`, `micro_usd`, `counters` |
242///
243/// `list` queries with equality filters only and Firestore orders their results by
244/// document name, the hex of the pid, which orders as the pid's UTF-8 bytes do; Firestore
245/// serves such queries from its automatic single-field indexes, so no composite index is
246/// needed. A pid longer than 700 bytes is refused. `set_wake`, `set_queue` and
247/// `set_suspend_requested` write one field under a field mask with an exists precondition,
248/// so writers changing different fields of one row never lose each other's update.
249/// `add_spend` adds to the process's and the partition's day totals with Firestore's
250/// server-side increment in one commit, so concurrent additions all count; `spend` reads
251/// the scope's day totals with one equality query and sums the days in range. Deleting a
252/// process keeps its spend.
253///
254/// # Example
255///
256/// ```rust,no_run
257/// # async fn example() -> adk_kernel::Result<()> {
258/// let store = adk_kernel::FirestoreProcessStore::connect("my-project").await?;
259/// store.migrate().await?;
260/// # Ok(())
261/// # }
262/// ```
263#[derive(Clone)]
264pub struct FirestoreProcessStore {
265    db: FirestoreDb,
266}
267
268impl std::fmt::Debug for FirestoreProcessStore {
269    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270        f.debug_struct("FirestoreProcessStore").finish_non_exhaustive()
271    }
272}
273
274impl FirestoreProcessStore {
275    /// A store over `db`, such as the client `adk_session::FirestoreRunStore::from_db` uses,
276    /// so the kernel's collections sit beside the run, schedule and governance stores.
277    pub fn from_db(db: FirestoreDb) -> Self {
278        Self { db }
279    }
280
281    /// Connects to `project_id` with Application Default Credentials.
282    ///
283    /// # Errors
284    ///
285    /// Returns [`KernelError::Store`] when the client cannot be created.
286    pub async fn connect(project_id: &str) -> Result<Self> {
287        Ok(Self::from_db(connect(project_id).await?))
288    }
289
290    /// The client the store uses.
291    pub fn db(&self) -> &FirestoreDb {
292        &self.db
293    }
294
295    /// Prepares the store's storage. Firestore creates collections on first write and
296    /// serves every query from its automatic single-field indexes, so there is nothing to
297    /// create; the method exists so every backend is set up the same way.
298    ///
299    /// # Errors
300    ///
301    /// Never returns an error.
302    pub async fn migrate(&self) -> Result<()> {
303        Ok(())
304    }
305
306    /// Writes `fields` under the mask `mask` to the process `pid`, failing when there is
307    /// none.
308    async fn update(&self, pid: &str, mask: &str, fields: ProcessFields) -> Result<()> {
309        let result = self
310            .db
311            .fluent()
312            .update()
313            .fields([mask])
314            .in_col(PROCESSES)
315            .precondition(FirestoreWritePrecondition::Exists(true))
316            .document_id(doc_id("process", pid)?)
317            .object(&fields)
318            .execute::<ProcessFields>()
319            .await;
320        match result {
321            Ok(_) => Ok(()),
322            Err(FirestoreError::DataNotFoundError(_)) => {
323                Err(KernelError::NotFound { pid: pid.into() })
324            }
325            Err(error) => Err(store_error("update the process table", &error)),
326        }
327    }
328
329    /// The day totals of `field` = `key` in `collection`.
330    async fn day_totals(&self, collection: &str, field: &str, key: &str) -> Result<Vec<SpendDoc>> {
331        self.db
332            .fluent()
333            .select()
334            .from(collection)
335            .filter(|q| q.for_all([q.field(field).eq(key)]))
336            .obj::<SpendDoc>()
337            .query()
338            .await
339            .map_err(|error| store_error("read the spend totals", &error))
340    }
341}
342
343#[async_trait]
344impl ProcessStore for FirestoreProcessStore {
345    async fn put(&self, meta: ProcessMeta) -> Result<()> {
346        let doc = ProcessDoc::new(&meta)?;
347        self.db
348            .fluent()
349            .update()
350            .in_col(PROCESSES)
351            .document_id(doc_id("process", &meta.pid)?)
352            .object(&doc)
353            .execute::<ProcessDoc>()
354            .await
355            .map(|_| ())
356            .map_err(|error| store_error("write the process table", &error))
357    }
358
359    async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>> {
360        let Ok(id) = doc_id("process", pid) else {
361            return Ok(None);
362        };
363        let doc: Option<ProcessDoc> = self
364            .db
365            .fluent()
366            .select()
367            .by_id_in(PROCESSES)
368            .obj()
369            .one(id)
370            .await
371            .map_err(|error| store_error("read the process table", &error))?;
372        doc.filter(|doc| doc.pid == pid).map(ProcessDoc::decode).transpose()
373    }
374
375    async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>> {
376        if filter.limit == Some(0) {
377            return Ok(Vec::new());
378        }
379        let mut select = self.db.fluent().select().from(PROCESSES).filter(|q| {
380            q.for_all([
381                filter.partition.as_ref().and_then(|p| q.field("partition").eq(p.as_str())),
382                filter.queue.as_ref().and_then(|queue| q.field("queue").eq(queue.as_str())),
383                filter.parent.as_ref().and_then(|parent| q.field("parent").eq(parent.as_str())),
384                filter
385                    .suspend_requested
386                    .and_then(|requested| q.field("suspend_requested").eq(requested)),
387            ])
388        });
389        // Firestore takes a limit up to `i32::MAX`; a larger one limits nothing.
390        if let Some(limit) = filter.limit.and_then(|limit| i32::try_from(limit).ok()) {
391            select = select.limit(limit.unsigned_abs());
392        }
393        let docs: Vec<ProcessDoc> =
394            select.obj().query().await.map_err(|error| store_error("list processes", &error))?;
395        docs.into_iter().map(ProcessDoc::decode).collect()
396    }
397
398    async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()> {
399        let wake = wake.as_ref().map(serde_json::to_string).transpose()?;
400        self.update(pid, "wake", ProcessFields { wake, ..ProcessFields::default() }).await
401    }
402
403    async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()> {
404        let queue = Some(queue.as_str().to_string());
405        self.update(pid, "queue", ProcessFields { queue, ..ProcessFields::default() }).await
406    }
407
408    async fn delete(&self, pid: &str) -> Result<bool> {
409        let Ok(id) = doc_id("process", pid) else {
410            return Ok(false);
411        };
412        let pid = pid.to_string();
413        let matches = move |doc: &ProcessDoc| doc.pid == pid;
414        delete_where(&self.db, PROCESSES, id, matches, "delete from the process table").await
415    }
416
417    async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()> {
418        let fields =
419            ProcessFields { suspend_requested: Some(requested), ..ProcessFields::default() };
420        self.update(pid, "suspend_requested", fields).await
421    }
422
423    async fn add_spend(
424        &self,
425        pid: &str,
426        partition: &PartitionId,
427        day: NaiveDate,
428        delta: SpendDelta,
429    ) -> Result<()> {
430        let mut increments = vec![("micro_usd".to_string(), stored_micro_usd(BACKEND, &delta)?)];
431        for (name, amount) in counters(&delta) {
432            increments.push((format!("counters.{name}"), stored_amount(BACKEND, name, amount)?));
433        }
434        let increments = Arc::new(increments);
435        let day = day_number(day);
436        let day_text = day.to_string();
437        let process = SpendDoc {
438            pid: Some(pid.to_string()),
439            partition: partition.as_str().to_string(),
440            day,
441            ..SpendDoc::default()
442        };
443        let shared = SpendDoc { pid: None, ..process.clone() };
444        let writes = Arc::new([
445            (
446                PROCESS_SPEND,
447                digest_id(&[pid, partition.as_str(), &day_text]),
448                vec!["pid", "partition", "day"],
449                process,
450            ),
451            (
452                PARTITION_SPEND,
453                digest_id(&[partition.as_str(), &day_text]),
454                vec!["partition", "day"],
455                shared,
456            ),
457        ]);
458        self.db
459            .run_transaction_with_options(
460                move |db, transaction| -> TxFuture<'_, ()> {
461                    let writes = writes.clone();
462                    let increments = increments.clone();
463                    Box::pin(async move {
464                        for (collection, id, mask, doc) in writes.iter() {
465                            db.fluent()
466                                .update()
467                                .fields(mask)
468                                .in_col(collection)
469                                .document_id(id)
470                                .object(doc)
471                                .transforms(|t| {
472                                    t.fields(
473                                        increments.iter().map(|(field, amount)| {
474                                            t.field(field).increment(*amount)
475                                        }),
476                                    )
477                                })
478                                .add_to_transaction(transaction)
479                                .map_err(tx_fail("add to the spend totals"))?;
480                        }
481                        Ok(())
482                    })
483                },
484                transaction_options(),
485            )
486            .await
487            .map_err(|error| transaction_error(error, "add to the spend totals"))
488    }
489
490    async fn spend(
491        &self,
492        scope: &SpendScope,
493        from: NaiveDate,
494        to_inclusive: NaiveDate,
495    ) -> Result<u64> {
496        let docs = match scope {
497            SpendScope::Process(pid) => self.day_totals(PROCESS_SPEND, "pid", pid).await?,
498            SpendScope::Partition(partition) => {
499                self.day_totals(PARTITION_SPEND, "partition", partition.as_str()).await?
500            }
501        };
502        let days = day_number(from)..=day_number(to_inclusive);
503        let total = docs
504            .iter()
505            .filter(|doc| days.contains(&doc.day))
506            .fold(0_i64, |total, doc| total.saturating_add(doc.micro_usd));
507        stored_total(BACKEND, total)
508    }
509
510    async fn usage(
511        &self,
512        scope: &SpendScope,
513        from: NaiveDate,
514        to_inclusive: NaiveDate,
515    ) -> Result<UsageTotals> {
516        let docs = match scope {
517            SpendScope::Process(pid) => self.day_totals(PROCESS_SPEND, "pid", pid).await?,
518            SpendScope::Partition(partition) => {
519                self.day_totals(PARTITION_SPEND, "partition", partition.as_str()).await?
520            }
521        };
522        let days = day_number(from)..=day_number(to_inclusive);
523        let mut totals = UsageTotals::default();
524        for doc in docs.iter().filter(|doc| days.contains(&doc.day)) {
525            totals.micro_usd =
526                totals.micro_usd.saturating_add(stored_total(BACKEND, doc.micro_usd)?);
527            for (name, amount) in &doc.counters {
528                totals.add_counter(name, stored_total(BACKEND, *amount)?);
529            }
530        }
531        Ok(totals)
532    }
533}