1use std::sync::Arc;
5
6use async_trait::async_trait;
7use chrono::NaiveDate;
8use firestore::errors::{BackoffError, FirestoreError};
9use firestore::{FirestoreDb, FirestoreTransactionOptions, FirestoreWritePrecondition};
10use futures::future::BoxFuture;
11use serde::{Deserialize, Serialize};
12
13use super::{
14 ProcessFilter, ProcessStore, SpendScope, UsageTotals, counters, day_number, stored_amount,
15 stored_micro_usd, stored_total,
16};
17use crate::bus::SpendDelta;
18use crate::error::{KernelError, Result};
19use crate::partition::PartitionId;
20use crate::process::ProcessMeta;
21use crate::sched::QueueClass;
22use crate::wake::WakeSet;
23
24const PROCESSES: &str = "adk_kernel_processes";
25const PROCESS_SPEND: &str = "adk_kernel_spend";
26const PARTITION_SPEND: &str = "adk_kernel_partition_spend";
27
28pub(super) const BACKEND: &str = "firestore";
30
31const MAX_ID_BYTES: usize = 700;
34
35const TRANSACTION_DEADLINE: chrono::TimeDelta = chrono::TimeDelta::seconds(120);
37
38pub(super) type TxResult<T> = std::result::Result<T, BackoffError<KernelError>>;
39pub(super) type TxFuture<'b, T> = BoxFuture<'b, TxResult<T>>;
40
41pub(super) fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
42 KernelError::Store { backend: BACKEND, reason: format!("could not {action}: {error}") }
43}
44
45pub(super) async fn connect(project_id: &str) -> Result<FirestoreDb> {
48 FirestoreDb::new(project_id).await.map_err(|error| store_error("connect to Firestore", &error))
49}
50
51pub(super) fn doc_id(what: &str, id: &str) -> Result<String> {
54 if id.len() > MAX_ID_BYTES {
55 return Err(KernelError::Store {
56 backend: BACKEND,
57 reason: format!(
58 "a Firestore {what} id is at most {MAX_ID_BYTES} bytes, and this one has {}",
59 id.len()
60 ),
61 });
62 }
63 Ok(id.bytes().map(|byte| format!("{byte:02x}")).collect())
64}
65
66pub(super) fn digest_id(parts: &[&str]) -> String {
69 use sha2::Digest as _;
70
71 let encoded = serde_json::to_vec(parts).unwrap_or_default();
72 sha2::Sha256::digest(&encoded).iter().map(|byte| format!("{byte:02x}")).collect()
73}
74
75pub(super) fn transaction_options() -> FirestoreTransactionOptions {
76 FirestoreTransactionOptions::new().with_max_elapsed_time(TRANSACTION_DEADLINE)
77}
78
79pub(super) fn tx_fail(
82 action: &'static str,
83) -> impl Fn(FirestoreError) -> BackoffError<KernelError> {
84 move |error| {
85 let retryable = matches!(&error, FirestoreError::DatabaseError(db) if db.retry_possible);
86 let error = store_error(action, &error);
87 if retryable { BackoffError::transient(error) } else { BackoffError::permanent(error) }
88 }
89}
90
91pub(super) fn transaction_error(error: FirestoreError, action: &str) -> KernelError {
93 match error {
94 FirestoreError::ErrorInTransaction(inner) => match inner.source.downcast::<KernelError>() {
95 Ok(error) => *error,
96 Err(source) => store_error(action, &source),
97 },
98 other => store_error(action, &other),
99 }
100}
101
102pub(super) async fn delete_where<T>(
105 db: &FirestoreDb,
106 collection: &'static str,
107 doc_name: String,
108 matches: impl Fn(&T) -> bool + Send + Sync + 'static,
109 action: &'static str,
110) -> Result<bool>
111where
112 T: for<'de> Deserialize<'de> + Send + Sync + 'static,
113{
114 let (doc_name, matches) = (Arc::new(doc_name), Arc::new(matches));
115 db.run_transaction_with_options(
116 move |db, transaction| -> TxFuture<'_, bool> {
117 let (doc_name, matches) = (doc_name.clone(), matches.clone());
118 Box::pin(async move {
119 let stored: Option<T> = db
120 .fluent()
121 .select()
122 .by_id_in(collection)
123 .obj()
124 .one(doc_name.as_str())
125 .await
126 .map_err(tx_fail(action))?;
127 if !stored.as_ref().is_some_and(|stored| matches(stored)) {
128 return Ok(false);
129 }
130 db.fluent()
131 .delete()
132 .from(collection)
133 .document_id(doc_name.as_str())
134 .add_to_transaction(transaction)
135 .map_err(tx_fail(action))?;
136 Ok(true)
137 })
138 },
139 transaction_options(),
140 )
141 .await
142 .map_err(|error| transaction_error(error, action))
143}
144
145pub(super) fn json<T: serde::de::DeserializeOwned>(what: &str, text: &str) -> Result<T> {
147 serde_json::from_str(text).map_err(|error| KernelError::Store {
148 backend: BACKEND,
149 reason: format!("a stored {what} is corrupt: {error}"),
150 })
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
155struct ProcessDoc {
156 pid: String,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
158 parent: Option<String>,
159 partition: String,
160 queue: String,
161 kind: String,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
163 wake: Option<String>,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 suspended_by: Option<String>,
166 #[serde(default)]
167 suspend_requested: bool,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 agenda_item: Option<String>,
170 labels: String,
171}
172
173impl ProcessDoc {
174 fn new(meta: &ProcessMeta) -> Result<Self> {
175 Ok(Self {
176 pid: meta.pid.clone(),
177 parent: meta.parent.clone(),
178 partition: meta.partition.as_str().to_string(),
179 queue: meta.queue.as_str().to_string(),
180 kind: serde_json::to_string(&meta.kind)?,
181 wake: meta.wake.as_ref().map(serde_json::to_string).transpose()?,
182 suspended_by: meta.suspended_by.as_ref().map(serde_json::to_string).transpose()?,
183 suspend_requested: meta.suspend_requested,
184 agenda_item: meta.agenda_item.clone(),
185 labels: serde_json::to_string(&meta.labels)?,
186 })
187 }
188
189 fn decode(self) -> Result<ProcessMeta> {
190 Ok(ProcessMeta {
191 kind: json("process kind", &self.kind)?,
192 wake: self.wake.map(|wake| json("wake set", &wake)).transpose()?,
193 suspended_by: self
194 .suspended_by
195 .map(|suspension| json("suspension", &suspension))
196 .transpose()?,
197 labels: json("label set", &self.labels)?,
198 partition: PartitionId::new(self.partition),
199 queue: QueueClass::from_name(&self.queue),
200 suspend_requested: self.suspend_requested,
201 agenda_item: self.agenda_item,
202 parent: self.parent,
203 pid: self.pid,
204 })
205 }
206}
207
208#[derive(Debug, Default, Serialize, Deserialize)]
210#[serde(default)]
211struct ProcessFields {
212 #[serde(skip_serializing_if = "Option::is_none")]
213 wake: Option<String>,
214 #[serde(skip_serializing_if = "Option::is_none")]
215 queue: Option<String>,
216 #[serde(skip_serializing_if = "Option::is_none")]
217 suspend_requested: Option<bool>,
218}
219
220#[derive(Debug, Clone, Default, Serialize, Deserialize)]
222struct SpendDoc {
223 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pid: Option<String>,
225 partition: String,
226 day: i64,
227 #[serde(default, skip_serializing)]
228 micro_usd: i64,
229 #[serde(default, skip_serializing)]
231 counters: std::collections::BTreeMap<String, i64>,
232}
233
234#[derive(Clone)]
264pub struct FirestoreProcessStore {
265 db: FirestoreDb,
266}
267
268impl std::fmt::Debug for FirestoreProcessStore {
269 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270 f.debug_struct("FirestoreProcessStore").finish_non_exhaustive()
271 }
272}
273
274impl FirestoreProcessStore {
275 pub fn from_db(db: FirestoreDb) -> Self {
278 Self { db }
279 }
280
281 pub async fn connect(project_id: &str) -> Result<Self> {
287 Ok(Self::from_db(connect(project_id).await?))
288 }
289
290 pub fn db(&self) -> &FirestoreDb {
292 &self.db
293 }
294
295 pub async fn migrate(&self) -> Result<()> {
303 Ok(())
304 }
305
306 async fn update(&self, pid: &str, mask: &str, fields: ProcessFields) -> Result<()> {
309 let result = self
310 .db
311 .fluent()
312 .update()
313 .fields([mask])
314 .in_col(PROCESSES)
315 .precondition(FirestoreWritePrecondition::Exists(true))
316 .document_id(doc_id("process", pid)?)
317 .object(&fields)
318 .execute::<ProcessFields>()
319 .await;
320 match result {
321 Ok(_) => Ok(()),
322 Err(FirestoreError::DataNotFoundError(_)) => {
323 Err(KernelError::NotFound { pid: pid.into() })
324 }
325 Err(error) => Err(store_error("update the process table", &error)),
326 }
327 }
328
329 async fn day_totals(&self, collection: &str, field: &str, key: &str) -> Result<Vec<SpendDoc>> {
331 self.db
332 .fluent()
333 .select()
334 .from(collection)
335 .filter(|q| q.for_all([q.field(field).eq(key)]))
336 .obj::<SpendDoc>()
337 .query()
338 .await
339 .map_err(|error| store_error("read the spend totals", &error))
340 }
341}
342
343#[async_trait]
344impl ProcessStore for FirestoreProcessStore {
345 async fn put(&self, meta: ProcessMeta) -> Result<()> {
346 let doc = ProcessDoc::new(&meta)?;
347 self.db
348 .fluent()
349 .update()
350 .in_col(PROCESSES)
351 .document_id(doc_id("process", &meta.pid)?)
352 .object(&doc)
353 .execute::<ProcessDoc>()
354 .await
355 .map(|_| ())
356 .map_err(|error| store_error("write the process table", &error))
357 }
358
359 async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>> {
360 let Ok(id) = doc_id("process", pid) else {
361 return Ok(None);
362 };
363 let doc: Option<ProcessDoc> = self
364 .db
365 .fluent()
366 .select()
367 .by_id_in(PROCESSES)
368 .obj()
369 .one(id)
370 .await
371 .map_err(|error| store_error("read the process table", &error))?;
372 doc.filter(|doc| doc.pid == pid).map(ProcessDoc::decode).transpose()
373 }
374
375 async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>> {
376 if filter.limit == Some(0) {
377 return Ok(Vec::new());
378 }
379 let mut select = self.db.fluent().select().from(PROCESSES).filter(|q| {
380 q.for_all([
381 filter.partition.as_ref().and_then(|p| q.field("partition").eq(p.as_str())),
382 filter.queue.as_ref().and_then(|queue| q.field("queue").eq(queue.as_str())),
383 filter.parent.as_ref().and_then(|parent| q.field("parent").eq(parent.as_str())),
384 filter
385 .suspend_requested
386 .and_then(|requested| q.field("suspend_requested").eq(requested)),
387 ])
388 });
389 if let Some(limit) = filter.limit.and_then(|limit| i32::try_from(limit).ok()) {
391 select = select.limit(limit.unsigned_abs());
392 }
393 let docs: Vec<ProcessDoc> =
394 select.obj().query().await.map_err(|error| store_error("list processes", &error))?;
395 docs.into_iter().map(ProcessDoc::decode).collect()
396 }
397
398 async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()> {
399 let wake = wake.as_ref().map(serde_json::to_string).transpose()?;
400 self.update(pid, "wake", ProcessFields { wake, ..ProcessFields::default() }).await
401 }
402
403 async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()> {
404 let queue = Some(queue.as_str().to_string());
405 self.update(pid, "queue", ProcessFields { queue, ..ProcessFields::default() }).await
406 }
407
408 async fn delete(&self, pid: &str) -> Result<bool> {
409 let Ok(id) = doc_id("process", pid) else {
410 return Ok(false);
411 };
412 let pid = pid.to_string();
413 let matches = move |doc: &ProcessDoc| doc.pid == pid;
414 delete_where(&self.db, PROCESSES, id, matches, "delete from the process table").await
415 }
416
417 async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()> {
418 let fields =
419 ProcessFields { suspend_requested: Some(requested), ..ProcessFields::default() };
420 self.update(pid, "suspend_requested", fields).await
421 }
422
423 async fn add_spend(
424 &self,
425 pid: &str,
426 partition: &PartitionId,
427 day: NaiveDate,
428 delta: SpendDelta,
429 ) -> Result<()> {
430 let mut increments = vec![("micro_usd".to_string(), stored_micro_usd(BACKEND, &delta)?)];
431 for (name, amount) in counters(&delta) {
432 increments.push((format!("counters.{name}"), stored_amount(BACKEND, name, amount)?));
433 }
434 let increments = Arc::new(increments);
435 let day = day_number(day);
436 let day_text = day.to_string();
437 let process = SpendDoc {
438 pid: Some(pid.to_string()),
439 partition: partition.as_str().to_string(),
440 day,
441 ..SpendDoc::default()
442 };
443 let shared = SpendDoc { pid: None, ..process.clone() };
444 let writes = Arc::new([
445 (
446 PROCESS_SPEND,
447 digest_id(&[pid, partition.as_str(), &day_text]),
448 vec!["pid", "partition", "day"],
449 process,
450 ),
451 (
452 PARTITION_SPEND,
453 digest_id(&[partition.as_str(), &day_text]),
454 vec!["partition", "day"],
455 shared,
456 ),
457 ]);
458 self.db
459 .run_transaction_with_options(
460 move |db, transaction| -> TxFuture<'_, ()> {
461 let writes = writes.clone();
462 let increments = increments.clone();
463 Box::pin(async move {
464 for (collection, id, mask, doc) in writes.iter() {
465 db.fluent()
466 .update()
467 .fields(mask)
468 .in_col(collection)
469 .document_id(id)
470 .object(doc)
471 .transforms(|t| {
472 t.fields(
473 increments.iter().map(|(field, amount)| {
474 t.field(field).increment(*amount)
475 }),
476 )
477 })
478 .add_to_transaction(transaction)
479 .map_err(tx_fail("add to the spend totals"))?;
480 }
481 Ok(())
482 })
483 },
484 transaction_options(),
485 )
486 .await
487 .map_err(|error| transaction_error(error, "add to the spend totals"))
488 }
489
490 async fn spend(
491 &self,
492 scope: &SpendScope,
493 from: NaiveDate,
494 to_inclusive: NaiveDate,
495 ) -> Result<u64> {
496 let docs = match scope {
497 SpendScope::Process(pid) => self.day_totals(PROCESS_SPEND, "pid", pid).await?,
498 SpendScope::Partition(partition) => {
499 self.day_totals(PARTITION_SPEND, "partition", partition.as_str()).await?
500 }
501 };
502 let days = day_number(from)..=day_number(to_inclusive);
503 let total = docs
504 .iter()
505 .filter(|doc| days.contains(&doc.day))
506 .fold(0_i64, |total, doc| total.saturating_add(doc.micro_usd));
507 stored_total(BACKEND, total)
508 }
509
510 async fn usage(
511 &self,
512 scope: &SpendScope,
513 from: NaiveDate,
514 to_inclusive: NaiveDate,
515 ) -> Result<UsageTotals> {
516 let docs = match scope {
517 SpendScope::Process(pid) => self.day_totals(PROCESS_SPEND, "pid", pid).await?,
518 SpendScope::Partition(partition) => {
519 self.day_totals(PARTITION_SPEND, "partition", partition.as_str()).await?
520 }
521 };
522 let days = day_number(from)..=day_number(to_inclusive);
523 let mut totals = UsageTotals::default();
524 for doc in docs.iter().filter(|doc| days.contains(&doc.day)) {
525 totals.micro_usd =
526 totals.micro_usd.saturating_add(stored_total(BACKEND, doc.micro_usd)?);
527 for (name, amount) in &doc.counters {
528 totals.add_counter(name, stored_total(BACKEND, *amount)?);
529 }
530 }
531 Ok(totals)
532 }
533}