1use async_trait::async_trait;
4use firestore::{FirestoreDb, FirestoreQueryDirection};
5use serde::{Deserialize, Serialize};
6
7use super::firestore::{connect, delete_where, digest_id, doc_id, json, store_error};
8use crate::error::Result;
9use crate::partition::{CrossingFilter, CrossingRecord, Partition, PartitionId, PartitionStore};
10
11const PARTITIONS: &str = "adk_kernel_partitions";
12const CROSSINGS: &str = "adk_kernel_crossings";
13const GRANTS: &str = "adk_kernel_crossing_grants";
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17struct PartitionDoc {
18 id: String,
19 record: String,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24struct CrossingDoc {
25 id: String,
26 at_us: i64,
27 run: String,
28 from: String,
29 to: String,
30 fingerprint: String,
31 outcome: String,
32 record: String,
33}
34
35#[derive(Debug, Clone, Serialize, Deserialize)]
37struct GrantDoc {
38 run: String,
39 fingerprint: String,
40}
41
42#[derive(Clone)]
71pub struct FirestorePartitionStore {
72 db: FirestoreDb,
73}
74
75impl std::fmt::Debug for FirestorePartitionStore {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 f.debug_struct("FirestorePartitionStore").finish_non_exhaustive()
78 }
79}
80
81impl FirestorePartitionStore {
82 pub fn from_db(db: FirestoreDb) -> Self {
84 Self { db }
85 }
86
87 pub async fn connect(project_id: &str) -> Result<Self> {
94 Ok(Self::from_db(connect(project_id).await?))
95 }
96
97 pub fn db(&self) -> &FirestoreDb {
99 &self.db
100 }
101
102 pub async fn migrate(&self) -> Result<()> {
108 Ok(())
109 }
110
111 async fn grant_docs(&self, run: &str) -> Result<Vec<GrantDoc>> {
113 self.db
114 .fluent()
115 .select()
116 .from(GRANTS)
117 .filter(|q| q.for_all([q.field("run").eq(run)]))
118 .obj()
119 .query()
120 .await
121 .map_err(|error| store_error("read the crossing grants", &error))
122 }
123}
124
125fn grant_id(run: &str, fingerprint: &str) -> String {
127 digest_id(&[run, fingerprint])
128}
129
130#[async_trait]
131impl PartitionStore for FirestorePartitionStore {
132 async fn put(&self, partition: Partition) -> Result<()> {
133 let doc = PartitionDoc {
134 id: partition.id.as_str().to_string(),
135 record: serde_json::to_string(&partition)?,
136 };
137 self.db
138 .fluent()
139 .update()
140 .in_col(PARTITIONS)
141 .document_id(doc_id("partition", &doc.id)?)
142 .object(&doc)
143 .execute::<PartitionDoc>()
144 .await
145 .map(|_| ())
146 .map_err(|error| store_error("write the partition table", &error))
147 }
148
149 async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
150 let Ok(doc_name) = doc_id("partition", id.as_str()) else {
151 return Ok(None);
152 };
153 let doc: Option<PartitionDoc> = self
154 .db
155 .fluent()
156 .select()
157 .by_id_in(PARTITIONS)
158 .obj()
159 .one(doc_name)
160 .await
161 .map_err(|error| store_error("read the partition table", &error))?;
162 doc.filter(|doc| doc.id == id.as_str())
163 .map(|doc| json("partition", &doc.record))
164 .transpose()
165 }
166
167 async fn list(&self) -> Result<Vec<Partition>> {
168 let mut docs: Vec<PartitionDoc> = self
169 .db
170 .fluent()
171 .select()
172 .from(PARTITIONS)
173 .obj()
174 .query()
175 .await
176 .map_err(|error| store_error("list the partition table", &error))?;
177 docs.sort_by(|a, b| a.id.cmp(&b.id));
178 docs.iter().map(|doc| json("partition", &doc.record)).collect()
179 }
180
181 async fn delete(&self, id: &PartitionId) -> Result<bool> {
182 let Ok(doc_name) = doc_id("partition", id.as_str()) else {
183 return Ok(false);
184 };
185 let id = id.as_str().to_string();
186 let matches = move |doc: &PartitionDoc| doc.id == id;
187 delete_where(&self.db, PARTITIONS, doc_name, matches, "delete from the partition table")
188 .await
189 }
190
191 async fn record_crossing(&self, record: CrossingRecord) -> Result<()> {
192 let doc = CrossingDoc {
193 id: record.id.clone(),
194 at_us: record.at.timestamp_micros(),
195 run: record.run.clone(),
196 from: record.from.as_str().to_string(),
197 to: record.to.as_str().to_string(),
198 fingerprint: record.fingerprint.clone(),
199 outcome: record.outcome.as_str().to_string(),
200 record: serde_json::to_string(&record)?,
201 };
202 self.db
203 .fluent()
204 .insert()
205 .into(CROSSINGS)
206 .document_id(doc_id("crossing", &record.id)?)
207 .object(&doc)
208 .execute::<CrossingDoc>()
209 .await
210 .map(|_| ())
211 .map_err(|error| store_error("record a crossing", &error))
212 }
213
214 async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
215 if filter.limit == Some(0) {
216 return Ok(Vec::new());
217 }
218 let by_equality = filter.from.is_some()
219 || filter.to.is_some()
220 || filter.run.is_some()
221 || filter.fingerprint.is_some();
222 let since = filter.since.map(|since| since.timestamp_micros());
223 let mut select = self.db.fluent().select().from(CROSSINGS).filter(|q| {
224 q.for_all([
225 filter.from.as_ref().and_then(|from| q.field("from").eq(from.as_str())),
226 filter.to.as_ref().and_then(|to| q.field("to").eq(to.as_str())),
227 filter.run.as_ref().and_then(|run| q.field("run").eq(run.as_str())),
228 filter
229 .fingerprint
230 .as_ref()
231 .and_then(|fingerprint| q.field("fingerprint").eq(fingerprint.as_str())),
232 since
233 .filter(|_| !by_equality)
234 .and_then(|since| q.field("at_us").greater_than_or_equal(since)),
235 ])
236 });
237 if !by_equality && since.is_some() {
238 select = select.order_by([("at_us", FirestoreQueryDirection::Ascending)]);
239 }
240 let mut docs: Vec<CrossingDoc> = select
241 .obj()
242 .query()
243 .await
244 .map_err(|error| store_error("read the crossings", &error))?;
245 docs.sort_by(|a, b| (a.at_us, &a.id).cmp(&(b.at_us, &b.id)));
246 let mut out = Vec::new();
247 for doc in &docs {
248 let record: CrossingRecord = json("crossing record", &doc.record)?;
249 if filter.matches(&record) {
250 out.push(record);
251 if filter.limit.is_some_and(|limit| out.len() >= limit) {
252 break;
253 }
254 }
255 }
256 Ok(out)
257 }
258
259 async fn grant(&self, run: &str, fingerprint: &str) -> Result<()> {
260 let doc = GrantDoc { run: run.to_string(), fingerprint: fingerprint.to_string() };
261 self.db
262 .fluent()
263 .update()
264 .in_col(GRANTS)
265 .document_id(grant_id(run, fingerprint))
266 .object(&doc)
267 .execute::<GrantDoc>()
268 .await
269 .map(|_| ())
270 .map_err(|error| store_error("record a crossing grant", &error))
271 }
272
273 async fn grants(&self, run: &str) -> Result<Vec<String>> {
274 let mut grants: Vec<String> =
275 self.grant_docs(run).await?.into_iter().map(|doc| doc.fingerprint).collect();
276 grants.sort();
277 Ok(grants)
278 }
279
280 async fn release_run(&self, run: &str) -> Result<u64> {
281 let mut released = 0;
282 for doc in self.grant_docs(run).await? {
283 let (run, fingerprint) = (doc.run.clone(), doc.fingerprint.clone());
284 let matches =
285 move |stored: &GrantDoc| stored.run == run && stored.fingerprint == fingerprint;
286 let doc_name = grant_id(&doc.run, &doc.fingerprint);
287 if delete_where(&self.db, GRANTS, doc_name, matches, "release the crossing grants")
288 .await?
289 {
290 released += 1;
291 }
292 }
293 Ok(released)
294 }
295}