Skip to main content

adk_kernel/stores/
agent_firestore.rs

1//! The Firestore [`AgentStore`] (spec 3.3 §5.7, §10 K7, feature `firestore`).
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6use firestore::FirestoreDb;
7use serde::{Deserialize, Serialize};
8
9use super::firestore::{
10    TxFuture, connect, delete_where, doc_id, json, store_error, transaction_error,
11    transaction_options, tx_fail,
12};
13use crate::agents::{AgentRecord, AgentStore};
14use crate::error::Result;
15
16const AGENTS: &str = "adk_kernel_agents";
17
18/// One agent, as stored.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20struct AgentDoc {
21    id: String,
22    version: i64,
23    state: String,
24    record: String,
25}
26
27impl AgentDoc {
28    fn new(record: &AgentRecord) -> Result<Self> {
29        Ok(Self {
30            id: record.id.clone(),
31            version: i64::try_from(record.version).map_err(|_| {
32                store_error("write the agent table", &"the version exceeds a signed 64-bit integer")
33            })?,
34            state: record.state.as_str().to_string(),
35            record: serde_json::to_string(record)?,
36        })
37    }
38
39    fn decode(&self) -> Result<AgentRecord> {
40        json("agent", &self.record)
41    }
42}
43
44/// An [`AgentStore`] in Firestore, shared by every replica (spec 3.3 §5.7, §10 K7, feature
45/// `firestore`).
46///
47/// One `adk_kernel_agents` document per agent, named by the hex of its id: `id`, `version`,
48/// `state` and `record`, the record as JSON text. `put_if_version` reads and writes the
49/// document in one serializable transaction, so of two replicas changing one agent from the
50/// same version the second retries, sees the first's write and changes nothing. `list` reads
51/// every document and orders them by id in memory; an agent table is small.
52///
53/// # Example
54///
55/// ```rust,no_run
56/// # async fn example() -> adk_kernel::Result<()> {
57/// let store = adk_kernel::stores::FirestoreAgentStore::connect("my-project").await?;
58/// store.migrate().await?;
59/// # Ok(())
60/// # }
61/// ```
62#[derive(Clone)]
63pub struct FirestoreAgentStore {
64    db: FirestoreDb,
65}
66
67impl std::fmt::Debug for FirestoreAgentStore {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        f.debug_struct("FirestoreAgentStore").finish_non_exhaustive()
70    }
71}
72
73impl FirestoreAgentStore {
74    /// A store over `db`, such as the process store's.
75    pub fn from_db(db: FirestoreDb) -> Self {
76        Self { db }
77    }
78
79    /// Connects to `project_id` with Application Default Credentials.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the client cannot be
84    /// created.
85    pub async fn connect(project_id: &str) -> Result<Self> {
86        Ok(Self::from_db(connect(project_id).await?))
87    }
88
89    /// The client the store uses.
90    pub fn db(&self) -> &FirestoreDb {
91        &self.db
92    }
93
94    /// Prepares the store's storage; Firestore needs nothing created, so this does nothing.
95    ///
96    /// # Errors
97    ///
98    /// Never returns an error.
99    pub async fn migrate(&self) -> Result<()> {
100        Ok(())
101    }
102}
103
104#[async_trait]
105impl AgentStore for FirestoreAgentStore {
106    async fn put_if_version(&self, record: AgentRecord, expected: u64) -> Result<bool> {
107        let doc_name = Arc::new(doc_id("agent", &record.id)?);
108        let doc = Arc::new(AgentDoc::new(&record)?);
109        self.db
110            .run_transaction_with_options(
111                move |db, transaction| -> TxFuture<'_, bool> {
112                    let (doc_name, doc) = (doc_name.clone(), doc.clone());
113                    Box::pin(async move {
114                        let stored: Option<AgentDoc> = db
115                            .fluent()
116                            .select()
117                            .by_id_in(AGENTS)
118                            .obj()
119                            .one(doc_name.as_str())
120                            .await
121                            .map_err(tx_fail("read the agent table"))?;
122                        let version = stored
123                            .filter(|stored| stored.id == doc.id)
124                            .map_or(0, |stored| stored.version);
125                        if u64::try_from(version).ok() != Some(expected) {
126                            return Ok(false);
127                        }
128                        db.fluent()
129                            .update()
130                            .in_col(AGENTS)
131                            .document_id(doc_name.as_str())
132                            .object(doc.as_ref())
133                            .add_to_transaction(transaction)
134                            .map_err(tx_fail("write the agent table"))?;
135                        Ok(true)
136                    })
137                },
138                transaction_options(),
139            )
140            .await
141            .map_err(|error| transaction_error(error, "write the agent table"))
142    }
143
144    async fn get(&self, id: &str) -> Result<Option<AgentRecord>> {
145        let Ok(doc_name) = doc_id("agent", id) else {
146            return Ok(None);
147        };
148        let doc: Option<AgentDoc> = self
149            .db
150            .fluent()
151            .select()
152            .by_id_in(AGENTS)
153            .obj()
154            .one(doc_name)
155            .await
156            .map_err(|error| store_error("read the agent table", &error))?;
157        doc.filter(|doc| doc.id == id).as_ref().map(AgentDoc::decode).transpose()
158    }
159
160    async fn list(&self) -> Result<Vec<AgentRecord>> {
161        let mut docs: Vec<AgentDoc> = self
162            .db
163            .fluent()
164            .select()
165            .from(AGENTS)
166            .obj()
167            .query()
168            .await
169            .map_err(|error| store_error("list the agent table", &error))?;
170        docs.sort_by(|a, b| a.id.cmp(&b.id));
171        docs.iter().map(AgentDoc::decode).collect()
172    }
173
174    async fn delete(&self, id: &str) -> Result<bool> {
175        let Ok(doc_name) = doc_id("agent", id) else {
176            return Ok(false);
177        };
178        let id = id.to_string();
179        let matches = move |doc: &AgentDoc| doc.id == id && doc.state == "proposed";
180        delete_where(&self.db, AGENTS, doc_name, matches, "delete from the agent table").await
181    }
182}