Skip to main content

adk_graph/checkpointers/
firestore.rs

1//! Firestore [`Checkpointer`].
2
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use firestore::errors::{BackoffError, FirestoreError};
9use firestore::{
10    FirestoreDb, FirestoreQueryDirection, FirestoreTransaction, FirestoreTransactionOptions,
11};
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14
15use super::{decode, encode, storage_error};
16use crate::checkpoint::{Checkpointer, RetentionPolicy, conflict, duplicate_id, ensure_newer};
17use crate::error::{GraphError, Result};
18use crate::state::Checkpoint;
19
20const BACKEND: &str = "firestore";
21const THREADS: &str = "adk_graph_threads";
22const CHECKPOINTS: &str = "checkpoints";
23const IDS: &str = "adk_graph_checkpoint_ids";
24
25/// How long one save may spend retrying conflicting transactions.
26const TRANSACTION_DEADLINE: chrono::TimeDelta = chrono::TimeDelta::seconds(120);
27
28type TxResult<T> = std::result::Result<T, BackoffError<GraphError>>;
29type TxFuture<'b, T> = Pin<Box<dyn Future<Output = TxResult<T>> + Send + 'b>>;
30
31/// A thread: its ID and highest version.
32#[derive(Debug, Clone, Serialize, Deserialize)]
33struct ThreadDoc {
34    thread_id: String,
35    head: i64,
36}
37
38/// One checkpoint, under its thread.
39#[derive(Debug, Clone, Serialize, Deserialize)]
40struct CheckpointDoc {
41    checkpoint_id: String,
42    thread_id: String,
43    version: i64,
44    data: String,
45}
46
47/// Where a checkpoint ID is stored.
48#[derive(Debug, Clone, Serialize, Deserialize)]
49struct IdDoc {
50    checkpoint_id: String,
51    thread_id: String,
52    version: i64,
53}
54
55/// Document IDs cannot hold `/` and are length-limited, so identifiers are addressed
56/// by their SHA-256; each document also stores the identifier and every read checks it.
57fn digest(text: &str) -> String {
58    Sha256::digest(text.as_bytes()).iter().map(|byte| format!("{byte:02x}")).collect()
59}
60
61/// Zero-padded, so document ID order is version order.
62fn version_id(version: i64) -> String {
63    format!("{version:020}")
64}
65
66fn version_param(version: u64) -> Result<i64> {
67    i64::try_from(version)
68        .map_err(|_| storage_error(BACKEND, format!("version {version} exceeds a 64-bit integer")))
69}
70
71fn retry_or_fail(error: FirestoreError) -> BackoffError<GraphError> {
72    let retryable = matches!(&error, FirestoreError::DatabaseError(db) if db.retry_possible);
73    if retryable {
74        BackoffError::transient(storage_error(BACKEND, error))
75    } else {
76        BackoffError::permanent(storage_error(BACKEND, error))
77    }
78}
79
80/// Firestore-backed [`Checkpointer`].
81///
82/// | Document | Contents |
83/// |----------|----------|
84/// | `adk_graph_threads/{sha256(thread)}` | The thread ID and its highest version, `head` |
85/// | `adk_graph_threads/{sha256(thread)}/checkpoints/{version, zero-padded}` | The checkpoint as JSON in `data` |
86/// | `adk_graph_checkpoint_ids/{sha256(id)}` | The thread and version holding a checkpoint ID |
87///
88/// A save is one read-write transaction: it reads the thread document and the ID
89/// document, then writes the checkpoint, the ID, and the new head. Firestore
90/// transactions are serializable, so of two concurrent saves of one thread the second
91/// is aborted, retried, and sees the first's head. Every query orders or filters on
92/// the single `version` field, which Firestore serves from its automatic indexes.
93///
94/// # Example
95///
96/// ```rust,no_run
97/// use adk_graph::FirestoreCheckpointer;
98///
99/// # async fn example() -> adk_graph::Result<()> {
100/// let checkpointer = FirestoreCheckpointer::new("my-gcp-project").await?;
101/// checkpointer.migrate().await?;
102/// # Ok(())
103/// # }
104/// ```
105#[derive(Clone)]
106pub struct FirestoreCheckpointer {
107    db: FirestoreDb,
108}
109
110impl std::fmt::Debug for FirestoreCheckpointer {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.debug_struct("FirestoreCheckpointer").finish_non_exhaustive()
113    }
114}
115
116impl FirestoreCheckpointer {
117    /// Connects to `project_id` with Application Default Credentials. Honors
118    /// `FIRESTORE_EMULATOR_HOST`.
119    ///
120    /// # Errors
121    ///
122    /// Returns `GraphError::CheckpointError` when the client cannot be created.
123    pub async fn new(project_id: &str) -> Result<Self> {
124        let db = FirestoreDb::new(project_id)
125            .await
126            .map_err(|e| storage_error(BACKEND, format!("connection failed: {e}")))?;
127        Ok(Self::from_db(db))
128    }
129
130    /// Uses an existing client, such as one shared with session storage.
131    pub fn from_db(db: FirestoreDb) -> Self {
132        Self { db }
133    }
134
135    /// Connects to the Firestore emulator at `FIRESTORE_EMULATOR_HOST` without
136    /// Application Default Credentials, for local development and tests.
137    ///
138    /// # Example
139    ///
140    /// ```rust,no_run
141    /// use adk_graph::FirestoreCheckpointer;
142    ///
143    /// # async fn example() -> adk_graph::Result<()> {
144    /// // FIRESTORE_EMULATOR_HOST=127.0.0.1:8080
145    /// let checkpointer = FirestoreCheckpointer::connect_emulator("demo-project").await?;
146    /// # let _ = checkpointer;
147    /// # Ok(())
148    /// # }
149    /// ```
150    ///
151    /// # Errors
152    ///
153    /// Returns `GraphError::CheckpointError` when `FIRESTORE_EMULATOR_HOST` is unset or
154    /// the client cannot be created. Without the variable the client would reach
155    /// production Firestore with a token it rejects, so the call fails instead.
156    pub async fn connect_emulator(project_id: &str) -> Result<Self> {
157        if std::env::var_os("FIRESTORE_EMULATOR_HOST").is_none() {
158            return Err(storage_error(
159                BACKEND,
160                "FIRESTORE_EMULATOR_HOST is not set; set it to the emulator's host:port",
161            ));
162        }
163        let db = FirestoreDb::with_options_token_source(
164            firestore::FirestoreDbOptions::new(project_id.to_string()),
165            Vec::new(),
166            gcloud_sdk::TokenSourceType::ExternalSource(Box::new(EmulatorOwnerToken)),
167        )
168        .await
169        .map_err(|e| storage_error(BACKEND, format!("emulator connection failed: {e}")))?;
170        Ok(Self::from_db(db))
171    }
172
173    /// Firestore creates collections on first write and serves every query from
174    /// automatic single-field indexes, so there is nothing to create; the method
175    /// exists so every backend is set up the same way.
176    ///
177    /// # Errors
178    ///
179    /// Never returns an error.
180    pub async fn migrate(&self) -> Result<()> {
181        Ok(())
182    }
183
184    fn thread_parent(&self, thread_id: &str) -> Result<String> {
185        self.db
186            .parent_path(THREADS, digest(thread_id))
187            .map(|path| path.to_string())
188            .map_err(|e| storage_error(BACKEND, e))
189    }
190
191    async fn checkpoints(
192        &self,
193        thread_id: &str,
194        direction: FirestoreQueryDirection,
195        before: Option<i64>,
196        limit: Option<u32>,
197    ) -> Result<Vec<Checkpoint>> {
198        let parent = self.thread_parent(thread_id)?;
199        let mut select = self
200            .db
201            .fluent()
202            .select()
203            .from(CHECKPOINTS)
204            .parent(&parent)
205            .order_by([("version", direction)]);
206        if let Some(before) = before {
207            select = select.filter(|q| q.for_all([q.field("version").less_than(before)]));
208        }
209        if let Some(limit) = limit {
210            select = select.limit(limit);
211        }
212        let documents: Vec<CheckpointDoc> =
213            select.obj::<CheckpointDoc>().query().await.map_err(|e| storage_error(BACKEND, e))?;
214        documents
215            .into_iter()
216            .filter(|document| document.thread_id == thread_id)
217            .map(|document| decode(BACKEND, &document.data))
218            .collect()
219    }
220
221    async fn remove(&self, thread_id: &str, checkpoints: &[Checkpoint]) -> Result<usize> {
222        let parent = self.thread_parent(thread_id)?;
223        for checkpoint in checkpoints {
224            let version = version_param(checkpoint.version)?;
225            self.db
226                .fluent()
227                .delete()
228                .from(CHECKPOINTS)
229                .parent(&parent)
230                .document_id(version_id(version))
231                .execute()
232                .await
233                .map_err(|e| storage_error(BACKEND, e))?;
234            self.db
235                .fluent()
236                .delete()
237                .from(IDS)
238                .document_id(digest(&checkpoint.checkpoint_id))
239                .execute()
240                .await
241                .map_err(|e| storage_error(BACKEND, e))?;
242        }
243        Ok(checkpoints.len())
244    }
245}
246
247/// The Firestore emulator accepts the `owner` token as an administrator.
248struct EmulatorOwnerToken;
249
250#[async_trait]
251impl gcloud_sdk::Source for EmulatorOwnerToken {
252    async fn token(&self) -> gcloud_sdk::error::Result<gcloud_sdk::Token> {
253        Ok(gcloud_sdk::Token::new(
254            "Bearer".to_string(),
255            "owner".into(),
256            chrono::Utc::now() + chrono::Duration::hours(1),
257        ))
258    }
259}
260
261/// What a save transaction concluded.
262enum Outcome {
263    Stored,
264    Behind(u64),
265    DuplicateId,
266}
267
268async fn save_in_transaction(
269    db: &FirestoreDb,
270    transaction: &mut FirestoreTransaction<'_>,
271    checkpoint: &Checkpoint,
272    version: i64,
273    data: &str,
274) -> TxResult<Outcome> {
275    let thread_key = digest(&checkpoint.thread_id);
276    let thread: Option<ThreadDoc> = db
277        .fluent()
278        .select()
279        .by_id_in(THREADS)
280        .obj::<ThreadDoc>()
281        .one(&thread_key)
282        .await
283        .map_err(retry_or_fail)?;
284    if let Some(thread) = &thread {
285        if thread.thread_id != checkpoint.thread_id {
286            return Err(BackoffError::permanent(storage_error(
287                BACKEND,
288                format!("thread digest collision for '{}'", checkpoint.thread_id),
289            )));
290        }
291        if thread.head >= version {
292            return Ok(Outcome::Behind(thread.head as u64));
293        }
294    }
295    let id_key = digest(&checkpoint.checkpoint_id);
296    let existing: Option<IdDoc> = db
297        .fluent()
298        .select()
299        .by_id_in(IDS)
300        .obj::<IdDoc>()
301        .one(&id_key)
302        .await
303        .map_err(retry_or_fail)?;
304    if existing.is_some() {
305        return Ok(Outcome::DuplicateId);
306    }
307    let parent = db.parent_path(THREADS, &thread_key).map_err(retry_or_fail)?;
308    db.fluent()
309        .update()
310        .in_col(CHECKPOINTS)
311        .document_id(version_id(version))
312        .parent(&parent)
313        .object(&CheckpointDoc {
314            checkpoint_id: checkpoint.checkpoint_id.clone(),
315            thread_id: checkpoint.thread_id.clone(),
316            version,
317            data: data.to_string(),
318        })
319        .add_to_transaction(transaction)
320        .map_err(retry_or_fail)?;
321    db.fluent()
322        .update()
323        .in_col(IDS)
324        .document_id(&id_key)
325        .object(&IdDoc {
326            checkpoint_id: checkpoint.checkpoint_id.clone(),
327            thread_id: checkpoint.thread_id.clone(),
328            version,
329        })
330        .add_to_transaction(transaction)
331        .map_err(retry_or_fail)?;
332    db.fluent()
333        .update()
334        .in_col(THREADS)
335        .document_id(&thread_key)
336        .object(&ThreadDoc { thread_id: checkpoint.thread_id.clone(), head: version })
337        .add_to_transaction(transaction)
338        .map_err(retry_or_fail)?;
339    Ok(Outcome::Stored)
340}
341
342#[async_trait]
343impl Checkpointer for FirestoreCheckpointer {
344    async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
345        ensure_newer(checkpoint, None)?;
346        let version = version_param(checkpoint.version)?;
347        let request = Arc::new((checkpoint.clone(), encode(checkpoint)?));
348        let outcome = self
349            .db
350            .run_transaction_with_options(
351                move |db, transaction| -> TxFuture<'_, Outcome> {
352                    let request = Arc::clone(&request);
353                    Box::pin(async move {
354                        let (checkpoint, data) = &*request;
355                        save_in_transaction(&db, transaction, checkpoint, version, data).await
356                    })
357                },
358                FirestoreTransactionOptions::new().with_max_elapsed_time(TRANSACTION_DEADLINE),
359            )
360            .await
361            .map_err(|error| match error {
362                FirestoreError::ErrorInTransaction(inner) => {
363                    match inner.source.downcast::<GraphError>() {
364                        Ok(graph_error) => *graph_error,
365                        Err(source) => storage_error(BACKEND, source),
366                    }
367                }
368                other => storage_error(BACKEND, other),
369            })?;
370        match outcome {
371            Outcome::Stored => Ok(checkpoint.checkpoint_id.clone()),
372            Outcome::Behind(head) => Err(conflict(checkpoint, head)),
373            Outcome::DuplicateId => Err(duplicate_id(&checkpoint.checkpoint_id)),
374        }
375    }
376
377    async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
378        Ok(self
379            .checkpoints(thread_id, FirestoreQueryDirection::Descending, None, Some(1))
380            .await?
381            .pop())
382    }
383
384    async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
385        let location: Option<IdDoc> = self
386            .db
387            .fluent()
388            .select()
389            .by_id_in(IDS)
390            .obj::<IdDoc>()
391            .one(digest(checkpoint_id))
392            .await
393            .map_err(|e| storage_error(BACKEND, e))?;
394        let Some(location) = location.filter(|location| location.checkpoint_id == checkpoint_id)
395        else {
396            return Ok(None);
397        };
398        let parent = self.thread_parent(&location.thread_id)?;
399        let document: Option<CheckpointDoc> = self
400            .db
401            .fluent()
402            .select()
403            .by_id_in(CHECKPOINTS)
404            .parent(&parent)
405            .obj::<CheckpointDoc>()
406            .one(version_id(location.version))
407            .await
408            .map_err(|e| storage_error(BACKEND, e))?;
409        document
410            .filter(|document| document.checkpoint_id == checkpoint_id)
411            .map(|document| decode(BACKEND, &document.data))
412            .transpose()
413    }
414
415    async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
416        self.checkpoints(thread_id, FirestoreQueryDirection::Ascending, None, None).await
417    }
418
419    async fn list_page(
420        &self,
421        thread_id: &str,
422        before: Option<u64>,
423        limit: usize,
424    ) -> Result<Vec<Checkpoint>> {
425        if limit == 0 {
426            return Ok(Vec::new());
427        }
428        let before = before.map(version_param).transpose()?;
429        let limit = u32::try_from(limit).unwrap_or(u32::MAX);
430        self.checkpoints(thread_id, FirestoreQueryDirection::Descending, before, Some(limit)).await
431    }
432
433    async fn delete(&self, thread_id: &str) -> Result<()> {
434        let checkpoints = self.list(thread_id).await?;
435        self.remove(thread_id, &checkpoints).await?;
436        self.db
437            .fluent()
438            .delete()
439            .from(THREADS)
440            .document_id(digest(thread_id))
441            .execute()
442            .await
443            .map_err(|e| storage_error(BACKEND, e))
444    }
445
446    async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
447        let checkpoints = self.list(thread_id).await?;
448        let expired = policy.expired(&checkpoints);
449        let doomed: Vec<Checkpoint> = checkpoints
450            .into_iter()
451            .filter(|checkpoint| expired.contains(&checkpoint.checkpoint_id))
452            .collect();
453        self.remove(thread_id, &doomed).await
454    }
455}