Skip to main content

adk_kernel/stores/
agenda_firestore.rs

1//! The Firestore [`AgendaStore`] (spec 3.2 §7.1, §7.5, §13 Q8, 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::agenda::{AgendaFilter, AgendaItem, AgendaStateKind, AgendaStore};
14use crate::error::Result;
15
16const AGENDA: &str = "adk_kernel_agenda";
17
18/// One agenda item, as stored.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20struct AgendaDoc {
21    id: String,
22    partition: String,
23    state: String,
24    created_us: i64,
25    item: String,
26}
27
28impl AgendaDoc {
29    fn new(item: &AgendaItem) -> Result<Self> {
30        Ok(Self {
31            id: item.id.clone(),
32            partition: item.partition.as_str().to_string(),
33            state: item.state.kind().as_str().to_string(),
34            created_us: item.created_at.timestamp_micros(),
35            item: serde_json::to_string(item)?,
36        })
37    }
38
39    fn decode(&self) -> Result<AgendaItem> {
40        json("agenda item", &self.item)
41    }
42}
43
44/// An [`AgendaStore`] in Firestore, shared by every replica (spec 3.2 §7.1, §7.5, §13 Q8,
45/// feature `firestore`).
46///
47/// One `adk_kernel_agenda` document per item, named by the hex of its id: `id`,
48/// `partition`, `state` (its kind), `created_us` (microseconds since the Unix epoch) and
49/// `item`, the item as JSON text. `list` queries with equality filters only — the
50/// partition and the states — which Firestore serves from its automatic single-field
51/// indexes, then orders by `created_us` and id and applies the limit in memory, so no
52/// composite index is needed; a listing reads every item its filters match. `transition`
53/// reads and writes the item in one serializable transaction, so of two replicas moving one
54/// item from the same state the second retries, sees the first's write and moves nothing. An
55/// id longer than 700 bytes is refused.
56///
57/// # Example
58///
59/// ```rust,no_run
60/// # async fn example() -> adk_kernel::Result<()> {
61/// let store = adk_kernel::FirestoreAgendaStore::connect("my-project").await?;
62/// store.migrate().await?;
63/// # Ok(())
64/// # }
65/// ```
66#[derive(Clone)]
67pub struct FirestoreAgendaStore {
68    db: FirestoreDb,
69}
70
71impl std::fmt::Debug for FirestoreAgendaStore {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        f.debug_struct("FirestoreAgendaStore").finish_non_exhaustive()
74    }
75}
76
77impl FirestoreAgendaStore {
78    /// A store over `db`, such as the process store's.
79    pub fn from_db(db: FirestoreDb) -> Self {
80        Self { db }
81    }
82
83    /// Connects to `project_id` with Application Default Credentials.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the client cannot be
88    /// created.
89    pub async fn connect(project_id: &str) -> Result<Self> {
90        Ok(Self::from_db(connect(project_id).await?))
91    }
92
93    /// The client the store uses.
94    pub fn db(&self) -> &FirestoreDb {
95        &self.db
96    }
97
98    /// Prepares the store's storage; Firestore needs nothing created, so this does nothing.
99    ///
100    /// # Errors
101    ///
102    /// Never returns an error.
103    pub async fn migrate(&self) -> Result<()> {
104        Ok(())
105    }
106}
107
108#[async_trait]
109impl AgendaStore for FirestoreAgendaStore {
110    async fn put(&self, item: AgendaItem) -> Result<()> {
111        let doc = AgendaDoc::new(&item)?;
112        self.db
113            .fluent()
114            .update()
115            .in_col(AGENDA)
116            .document_id(doc_id("agenda item", &item.id)?)
117            .object(&doc)
118            .execute::<AgendaDoc>()
119            .await
120            .map(|_| ())
121            .map_err(|error| store_error("write the agenda", &error))
122    }
123
124    async fn get(&self, id: &str) -> Result<Option<AgendaItem>> {
125        let Ok(doc_name) = doc_id("agenda item", id) else {
126            return Ok(None);
127        };
128        let doc: Option<AgendaDoc> = self
129            .db
130            .fluent()
131            .select()
132            .by_id_in(AGENDA)
133            .obj()
134            .one(doc_name)
135            .await
136            .map_err(|error| store_error("read the agenda", &error))?;
137        doc.filter(|doc| doc.id == id).as_ref().map(AgendaDoc::decode).transpose()
138    }
139
140    async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>> {
141        if filter.limit == Some(0) {
142            return Ok(Vec::new());
143        }
144        let states: Vec<&str> = filter.states.iter().map(|state| state.as_str()).collect();
145        let mut docs: Vec<AgendaDoc> = self
146            .db
147            .fluent()
148            .select()
149            .from(AGENDA)
150            .filter(|q| {
151                q.for_all([
152                    filter.partition.as_ref().and_then(|p| q.field("partition").eq(p.as_str())),
153                    if states.is_empty() { None } else { q.field("state").is_in(states.clone()) },
154                ])
155            })
156            .obj()
157            .query()
158            .await
159            .map_err(|error| store_error("list the agenda", &error))?;
160        docs.sort_by(|a, b| (a.created_us, &a.id).cmp(&(b.created_us, &b.id)));
161        docs.truncate(filter.limit.unwrap_or(usize::MAX));
162        docs.iter().map(AgendaDoc::decode).collect()
163    }
164
165    async fn transition(&self, item: AgendaItem, from: AgendaStateKind) -> Result<bool> {
166        let doc_name = Arc::new(doc_id("agenda item", &item.id)?);
167        let doc = Arc::new(AgendaDoc::new(&item)?);
168        self.db
169            .run_transaction_with_options(
170                move |db, transaction| -> TxFuture<'_, bool> {
171                    let (doc_name, doc) = (doc_name.clone(), doc.clone());
172                    Box::pin(async move {
173                        let stored: Option<AgendaDoc> = db
174                            .fluent()
175                            .select()
176                            .by_id_in(AGENDA)
177                            .obj()
178                            .one(doc_name.as_str())
179                            .await
180                            .map_err(tx_fail("read the agenda"))?;
181                        if stored.is_none_or(|stored| {
182                            stored.id != doc.id || stored.state != from.as_str()
183                        }) {
184                            return Ok(false);
185                        }
186                        db.fluent()
187                            .update()
188                            .in_col(AGENDA)
189                            .document_id(doc_name.as_str())
190                            .object(doc.as_ref())
191                            .add_to_transaction(transaction)
192                            .map_err(tx_fail("update the agenda"))?;
193                        Ok(true)
194                    })
195                },
196                transaction_options(),
197            )
198            .await
199            .map_err(|error| transaction_error(error, "update the agenda"))
200    }
201
202    async fn delete(&self, id: &str) -> Result<bool> {
203        let Ok(doc_name) = doc_id("agenda item", id) else {
204            return Ok(false);
205        };
206        let id = id.to_string();
207        let matches = move |doc: &AgendaDoc| doc.id == id;
208        delete_where(&self.db, AGENDA, doc_name, matches, "delete from the agenda").await
209    }
210}