Skip to main content

adk_kernel/stores/
driver_firestore.rs

1//! The Firestore [`DriverStore`] (spec 3.2 §7.7, §13 Q8; features `drivers`, `firestore`).
2
3use adk_core::ApprovalScope;
4use async_trait::async_trait;
5use firestore::FirestoreDb;
6use serde::{Deserialize, Serialize};
7
8use super::firestore::{connect, delete_where, digest_id, doc_id, json, store_error};
9use crate::drivers::store::park_key;
10use crate::drivers::{DriverPark, DriverRecord, DriverStore};
11use crate::error::Result;
12
13const DRIVERS: &str = "adk_kernel_drivers";
14const PARKS: &str = "adk_kernel_driver_parks";
15
16/// One driver's record, as stored.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18struct DriverDoc {
19    id: String,
20    record: String,
21}
22
23/// One parked call, as stored, with the scope and call id it is keyed by.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25struct ParkDoc {
26    app: String,
27    user: String,
28    session: String,
29    call_id: String,
30    driver: String,
31    park: String,
32}
33
34impl ParkDoc {
35    fn is_for(&self, scope: &ApprovalScope, call_id: &str) -> bool {
36        self.app == scope.app_name
37            && self.user == scope.user_id
38            && self.session == scope.session_id
39            && self.call_id == call_id
40    }
41}
42
43/// The document ID of the park of `call_id` in `scope`.
44fn park_doc_id(scope: &ApprovalScope, call_id: &str) -> String {
45    digest_id(&[&scope.app_name, &scope.user_id, &scope.session_id, call_id])
46}
47
48/// A [`DriverStore`] in Firestore, shared by every replica (spec 3.2 §7.7, §13 Q8; features
49/// `drivers`, `firestore`).
50///
51/// | Collection (document ID) | Contents |
52/// |--------------------------|----------|
53/// | `adk_kernel_drivers` (hex of the driver id) | `id` and `record`, the record as JSON text |
54/// | `adk_kernel_driver_parks` (SHA-256 of the scope and call id) | `app`, `user`, `session`, `call_id`, `driver`, and `park`, the park as JSON text |
55///
56/// A park's document stores the scope and call id it is addressed by, and every read
57/// compares them, so two keys that share a digest never read each other's park. `list`
58/// and `list_parks` read every record or every park of one driver with an equality query
59/// and order them in memory, so no composite index is needed. `delete` and `delete_park`
60/// read and delete in one transaction, so of two concurrent deletes one answers `true`.
61///
62/// # Example
63///
64/// ```rust,no_run
65/// # async fn example() -> adk_kernel::Result<()> {
66/// let store = adk_kernel::stores::FirestoreDriverStore::connect("my-project").await?;
67/// store.migrate().await?;
68/// # Ok(())
69/// # }
70/// ```
71#[derive(Clone)]
72pub struct FirestoreDriverStore {
73    db: FirestoreDb,
74}
75
76impl std::fmt::Debug for FirestoreDriverStore {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        f.debug_struct("FirestoreDriverStore").finish_non_exhaustive()
79    }
80}
81
82impl FirestoreDriverStore {
83    /// A store over `db`, such as the process store's.
84    pub fn from_db(db: FirestoreDb) -> Self {
85        Self { db }
86    }
87
88    /// Connects to `project_id` with Application Default Credentials.
89    ///
90    /// # Errors
91    ///
92    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the client cannot be
93    /// created.
94    pub async fn connect(project_id: &str) -> Result<Self> {
95        Ok(Self::from_db(connect(project_id).await?))
96    }
97
98    /// The client the store uses.
99    pub fn db(&self) -> &FirestoreDb {
100        &self.db
101    }
102
103    /// Prepares the store's storage; Firestore needs nothing created, so this does nothing.
104    ///
105    /// # Errors
106    ///
107    /// Never returns an error.
108    pub async fn migrate(&self) -> Result<()> {
109        Ok(())
110    }
111}
112
113#[async_trait]
114impl DriverStore for FirestoreDriverStore {
115    async fn put(&self, record: DriverRecord) -> Result<()> {
116        let doc =
117            DriverDoc { id: record.id().to_string(), record: serde_json::to_string(&record)? };
118        self.db
119            .fluent()
120            .update()
121            .in_col(DRIVERS)
122            .document_id(doc_id("driver", &doc.id)?)
123            .object(&doc)
124            .execute::<DriverDoc>()
125            .await
126            .map(|_| ())
127            .map_err(|error| store_error("write the driver table", &error))
128    }
129
130    async fn get(&self, id: &str) -> Result<Option<DriverRecord>> {
131        let Ok(doc_name) = doc_id("driver", id) else {
132            return Ok(None);
133        };
134        let doc: Option<DriverDoc> = self
135            .db
136            .fluent()
137            .select()
138            .by_id_in(DRIVERS)
139            .obj()
140            .one(doc_name)
141            .await
142            .map_err(|error| store_error("read the driver table", &error))?;
143        doc.filter(|doc| doc.id == id).map(|doc| json("driver", &doc.record)).transpose()
144    }
145
146    async fn list(&self) -> Result<Vec<DriverRecord>> {
147        let mut docs: Vec<DriverDoc> = self
148            .db
149            .fluent()
150            .select()
151            .from(DRIVERS)
152            .obj()
153            .query()
154            .await
155            .map_err(|error| store_error("list the driver table", &error))?;
156        docs.sort_by(|a, b| a.id.cmp(&b.id));
157        docs.iter().map(|doc| json("driver", &doc.record)).collect()
158    }
159
160    async fn delete(&self, id: &str) -> Result<bool> {
161        let Ok(doc_name) = doc_id("driver", id) else {
162            return Ok(false);
163        };
164        let id = id.to_string();
165        let matches = move |doc: &DriverDoc| doc.id == id;
166        delete_where(&self.db, DRIVERS, doc_name, matches, "delete from the driver table").await
167    }
168
169    async fn put_park(&self, park: DriverPark) -> Result<()> {
170        let doc = ParkDoc {
171            app: park.scope.app_name.clone(),
172            user: park.scope.user_id.clone(),
173            session: park.scope.session_id.clone(),
174            call_id: park.call_id.clone(),
175            driver: park.driver.clone(),
176            park: serde_json::to_string(&park)?,
177        };
178        self.db
179            .fluent()
180            .update()
181            .in_col(PARKS)
182            .document_id(park_doc_id(&park.scope, &park.call_id))
183            .object(&doc)
184            .execute::<ParkDoc>()
185            .await
186            .map(|_| ())
187            .map_err(|error| store_error("write the driver table", &error))
188    }
189
190    async fn get_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<Option<DriverPark>> {
191        let doc: Option<ParkDoc> = self
192            .db
193            .fluent()
194            .select()
195            .by_id_in(PARKS)
196            .obj()
197            .one(park_doc_id(scope, call_id))
198            .await
199            .map_err(|error| store_error("read the driver table", &error))?;
200        doc.filter(|doc| doc.is_for(scope, call_id))
201            .map(|doc| json("parked driver call", &doc.park))
202            .transpose()
203    }
204
205    async fn list_parks(&self, driver: Option<&str>) -> Result<Vec<DriverPark>> {
206        let docs: Vec<ParkDoc> = self
207            .db
208            .fluent()
209            .select()
210            .from(PARKS)
211            .filter(|q| q.for_all([driver.and_then(|driver| q.field("driver").eq(driver))]))
212            .obj()
213            .query()
214            .await
215            .map_err(|error| store_error("list the driver table", &error))?;
216        let mut parks = docs
217            .iter()
218            .map(|doc| json::<DriverPark>("parked driver call", &doc.park))
219            .collect::<Result<Vec<_>>>()?;
220        parks.sort_by_key(|park| park_key(&park.scope, &park.call_id));
221        Ok(parks)
222    }
223
224    async fn delete_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<bool> {
225        let (scope, call) = (scope.clone(), call_id.to_string());
226        let doc_name = park_doc_id(&scope, call_id);
227        let matches = move |doc: &ParkDoc| doc.is_for(&scope, &call);
228        delete_where(&self.db, PARKS, doc_name, matches, "delete from the driver table").await
229    }
230}