1use async_trait::async_trait;
5use chrono::NaiveDate;
6use mongodb::bson::{Bson, Document, doc};
7use mongodb::error::{ErrorKind, WriteFailure};
8use mongodb::options::{ClientOptions, FindOptions, IndexOptions};
9use mongodb::{Client, Collection, Cursor, Database, IndexModel};
10
11use super::{
12 ProcessFilter, ProcessStore, SpendScope, UsageTotals, counters, day_number, stored_amount,
13 stored_micro_usd, stored_total,
14};
15use crate::bus::SpendDelta;
16use crate::error::{KernelError, Result};
17use crate::partition::PartitionId;
18use crate::process::ProcessMeta;
19use crate::sched::QueueClass;
20use crate::wake::WakeSet;
21
22const PROCESSES: &str = "adk_kernel_processes";
23const SPEND: &str = "adk_kernel_spend";
24
25pub(super) const BACKEND: &str = "mongodb";
27
28const DUPLICATE_KEY: i32 = 11000;
30
31const UPSERT_ATTEMPTS: u32 = 5;
33
34pub(super) fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
35 KernelError::Store { backend: BACKEND, reason: format!("could not {action}: {error}") }
36}
37
38pub(super) async fn connect(connection_string: &str, database_name: &str) -> Result<Database> {
40 let options = ClientOptions::parse(connection_string)
41 .await
42 .map_err(|error| store_error("parse the MongoDB connection string", &error))?;
43 let client = Client::with_options(options)
44 .map_err(|error| store_error("build the MongoDB client", &error))?;
45 Ok(client.database(database_name))
46}
47
48pub(super) async fn create_indexes(
50 collection: &Collection<Document>,
51 indexes: &[(&str, Document)],
52) -> Result<()> {
53 for (name, keys) in indexes {
54 let model = IndexModel::builder()
55 .keys(keys.clone())
56 .options(IndexOptions::builder().name((*name).to_string()).build())
57 .build();
58 collection
59 .create_index(model)
60 .await
61 .map_err(|error| store_error(&format!("create the index {name}"), &error))?;
62 }
63 Ok(())
64}
65
66pub(super) async fn collect(mut cursor: Cursor<Document>, action: &str) -> Result<Vec<Document>> {
68 let mut documents = Vec::new();
69 while cursor.advance().await.map_err(|error| store_error(action, &error))? {
70 documents.push(cursor.deserialize_current().map_err(|error| store_error(action, &error))?);
71 }
72 Ok(documents)
73}
74
75pub(super) fn text<'a>(document: &'a Document, field: &str) -> Result<&'a str> {
77 document.get_str(field).map_err(|_| KernelError::Store {
78 backend: BACKEND,
79 reason: format!("a stored document has no text field `{field}`"),
80 })
81}
82
83pub(super) fn optional_text(document: &Document, field: &str) -> Option<String> {
85 document.get_str(field).ok().map(str::to_string)
86}
87
88pub(super) fn read_i64(document: &Document, field: &str) -> Option<i64> {
90 match document.get(field)? {
91 Bson::Int32(value) => Some(i64::from(*value)),
92 Bson::Int64(value) => Some(*value),
93 Bson::Double(value) => Some(*value as i64),
94 _ => None,
95 }
96}
97
98pub(super) fn json<T: serde::de::DeserializeOwned>(what: &str, text: &str) -> Result<T> {
100 serde_json::from_str(text).map_err(|error| KernelError::Store {
101 backend: BACKEND,
102 reason: format!("a stored {what} is corrupt: {error}"),
103 })
104}
105
106pub(super) fn find_limit(limit: Option<usize>) -> Option<i64> {
109 limit.map(|limit| i64::try_from(limit).unwrap_or(i64::MAX))
110}
111
112pub(super) fn sorted(sort: Document, limit: Option<usize>) -> FindOptions {
114 FindOptions::builder().sort(sort).limit(find_limit(limit)).build()
115}
116
117pub(super) fn is_duplicate_key(error: &mongodb::error::Error) -> bool {
118 match error.kind.as_ref() {
119 ErrorKind::Write(WriteFailure::WriteError(write)) => write.code == DUPLICATE_KEY,
120 ErrorKind::Command(command) => command.code == DUPLICATE_KEY,
121 _ => false,
122 }
123}
124
125pub(super) async fn retry_upsert<T, F, Fut>(action: &str, mut upsert: F) -> Result<T>
128where
129 F: FnMut() -> Fut,
130 Fut: std::future::IntoFuture<Output = mongodb::error::Result<T>>,
131{
132 let mut attempt = 1;
133 loop {
134 match upsert().await {
135 Err(error) if is_duplicate_key(&error) && attempt < UPSERT_ATTEMPTS => attempt += 1,
136 result => return result.map_err(|error| store_error(action, &error)),
137 }
138 }
139}
140
141#[derive(Debug, Clone)]
169pub struct MongoProcessStore {
170 db: Database,
171}
172
173impl MongoProcessStore {
174 pub fn from_database(db: Database) -> Self {
177 Self { db }
178 }
179
180 pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
186 Ok(Self::from_database(connect(connection_string, database_name).await?))
187 }
188
189 pub fn database(&self) -> &Database {
191 &self.db
192 }
193
194 pub async fn migrate(&self) -> Result<()> {
200 create_indexes(
201 &self.processes(),
202 &[
203 ("adk_kernel_processes_partition", doc! { "partition": 1, "_id": 1 }),
204 ("adk_kernel_processes_queue", doc! { "queue": 1, "_id": 1 }),
205 ("adk_kernel_processes_parent", doc! { "parent": 1, "_id": 1 }),
206 ("adk_kernel_processes_suspend", doc! { "suspend_requested": 1, "_id": 1 }),
207 ],
208 )
209 .await?;
210 create_indexes(
211 &self.spend_totals(),
212 &[
213 ("adk_kernel_spend_pid", doc! { "pid": 1, "day": 1 }),
214 ("adk_kernel_spend_partition", doc! { "partition": 1, "day": 1 }),
215 ],
216 )
217 .await
218 }
219
220 fn processes(&self) -> Collection<Document> {
221 self.db.collection(PROCESSES)
222 }
223
224 fn spend_totals(&self) -> Collection<Document> {
225 self.db.collection(SPEND)
226 }
227
228 async fn update(&self, pid: &str, update: Document) -> Result<()> {
230 let result = self
231 .processes()
232 .update_one(doc! { "_id": pid }, update)
233 .await
234 .map_err(|error| store_error("update the process table", &error))?;
235 if result.matched_count == 0 {
236 return Err(KernelError::NotFound { pid: pid.into() });
237 }
238 Ok(())
239 }
240}
241
242fn encode(meta: &ProcessMeta) -> Result<Document> {
244 let mut document = doc! {
245 "_id": &meta.pid,
246 "partition": meta.partition.as_str(),
247 "queue": meta.queue.as_str(),
248 "kind": serde_json::to_string(&meta.kind)?,
249 "labels": serde_json::to_string(&meta.labels)?,
250 "suspend_requested": meta.suspend_requested,
251 };
252 if let Some(parent) = &meta.parent {
253 document.insert("parent", parent);
254 }
255 if let Some(wake) = &meta.wake {
256 document.insert("wake", serde_json::to_string(wake)?);
257 }
258 if let Some(suspension) = &meta.suspended_by {
259 document.insert("suspended_by", serde_json::to_string(suspension)?);
260 }
261 if let Some(item) = &meta.agenda_item {
262 document.insert("agenda_item", item);
263 }
264 Ok(document)
265}
266
267fn decode(document: &Document) -> Result<ProcessMeta> {
269 let pid = text(document, "_id")?.to_string();
270 let structured = |field: &str| optional_text(document, field);
271 Ok(ProcessMeta {
272 parent: optional_text(document, "parent"),
273 partition: PartitionId::new(text(document, "partition")?),
274 queue: QueueClass::from_name(text(document, "queue")?),
275 kind: json("process kind", text(document, "kind")?)?,
276 wake: structured("wake").map(|wake| json("wake set", &wake)).transpose()?,
277 suspended_by: structured("suspended_by")
278 .map(|suspension| json("suspension", &suspension))
279 .transpose()?,
280 suspend_requested: document.get_bool("suspend_requested").unwrap_or(false),
281 agenda_item: optional_text(document, "agenda_item"),
282 labels: json("label set", text(document, "labels")?)?,
283 pid,
284 })
285}
286
287#[async_trait]
288impl ProcessStore for MongoProcessStore {
289 async fn put(&self, meta: ProcessMeta) -> Result<()> {
290 let document = encode(&meta)?;
291 let processes = self.processes();
292 retry_upsert("write the process table", || {
293 processes.replace_one(doc! { "_id": &meta.pid }, document.clone()).upsert(true)
294 })
295 .await?;
296 Ok(())
297 }
298
299 async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>> {
300 let document = self
301 .processes()
302 .find_one(doc! { "_id": pid })
303 .await
304 .map_err(|error| store_error("read the process table", &error))?;
305 document.as_ref().map(decode).transpose()
306 }
307
308 async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>> {
309 if filter.limit == Some(0) {
310 return Ok(Vec::new());
311 }
312 let mut query = Document::new();
313 if let Some(partition) = &filter.partition {
314 query.insert("partition", partition.as_str());
315 }
316 if let Some(queue) = &filter.queue {
317 query.insert("queue", queue.as_str());
318 }
319 if let Some(parent) = &filter.parent {
320 query.insert("parent", parent);
321 }
322 if let Some(requested) = filter.suspend_requested {
323 query.insert("suspend_requested", requested);
324 }
325 let cursor = self
326 .processes()
327 .find(query)
328 .with_options(sorted(doc! { "_id": 1 }, filter.limit))
329 .await
330 .map_err(|error| store_error("list processes", &error))?;
331 collect(cursor, "list processes").await?.iter().map(decode).collect()
332 }
333
334 async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()> {
335 let update = match &wake {
336 Some(wake) => doc! { "$set": { "wake": serde_json::to_string(wake)? } },
337 None => doc! { "$unset": { "wake": "" } },
338 };
339 self.update(pid, update).await
340 }
341
342 async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()> {
343 self.update(pid, doc! { "$set": { "queue": queue.as_str() } }).await
344 }
345
346 async fn delete(&self, pid: &str) -> Result<bool> {
347 let result = self
348 .processes()
349 .delete_one(doc! { "_id": pid })
350 .await
351 .map_err(|error| store_error("delete from the process table", &error))?;
352 Ok(result.deleted_count == 1)
353 }
354
355 async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()> {
356 self.update(pid, doc! { "$set": { "suspend_requested": requested } }).await
357 }
358
359 async fn add_spend(
360 &self,
361 pid: &str,
362 partition: &PartitionId,
363 day: NaiveDate,
364 delta: SpendDelta,
365 ) -> Result<()> {
366 let mut increments = doc! { "micro_usd": stored_micro_usd(BACKEND, &delta)? };
367 for (name, amount) in counters(&delta) {
368 increments.insert(format!("counters.{name}"), stored_amount(BACKEND, name, amount)?);
369 }
370 let day = day_number(day);
371 let key = doc! { "pid": pid, "partition": partition.as_str(), "day": day };
372 let update = doc! {
373 "$inc": increments,
374 "$setOnInsert": { "pid": pid, "partition": partition.as_str(), "day": day },
375 };
376 let totals = self.spend_totals();
377 retry_upsert("add to the spend totals", || {
378 totals.update_one(doc! { "_id": key.clone() }, update.clone()).upsert(true)
379 })
380 .await?;
381 Ok(())
382 }
383
384 async fn spend(
385 &self,
386 scope: &SpendScope,
387 from: NaiveDate,
388 to_inclusive: NaiveDate,
389 ) -> Result<u64> {
390 let mut filter = match scope {
391 SpendScope::Process(pid) => doc! { "pid": pid },
392 SpendScope::Partition(partition) => doc! { "partition": partition.as_str() },
393 };
394 filter.insert("day", doc! { "$gte": day_number(from), "$lte": day_number(to_inclusive) });
395 let pipeline = [
396 doc! { "$match": filter },
397 doc! { "$group": { "_id": Bson::Null, "total": { "$sum": "$micro_usd" } } },
398 ];
399 let cursor = self
400 .spend_totals()
401 .aggregate(pipeline)
402 .await
403 .map_err(|error| store_error("sum the spend totals", &error))?;
404 let rows = collect(cursor, "sum the spend totals").await?;
405 let sum = rows.first().and_then(|row| read_i64(row, "total")).unwrap_or(0);
406 stored_total(BACKEND, sum)
407 }
408
409 async fn usage(
410 &self,
411 scope: &SpendScope,
412 from: NaiveDate,
413 to_inclusive: NaiveDate,
414 ) -> Result<UsageTotals> {
415 let mut filter = match scope {
416 SpendScope::Process(pid) => doc! { "pid": pid },
417 SpendScope::Partition(partition) => doc! { "partition": partition.as_str() },
418 };
419 filter.insert("day", doc! { "$gte": day_number(from), "$lte": day_number(to_inclusive) });
420 let cursor = self
421 .spend_totals()
422 .find(filter)
423 .await
424 .map_err(|error| store_error("read the usage totals", &error))?;
425 let mut totals = UsageTotals::default();
426 for row in collect(cursor, "read the usage totals").await? {
427 let micro_usd = stored_total(BACKEND, read_i64(&row, "micro_usd").unwrap_or(0))?;
428 totals.micro_usd = totals.micro_usd.saturating_add(micro_usd);
429 let Ok(counters) = row.get_document("counters") else { continue };
430 for name in counters.keys() {
431 let amount = stored_total(BACKEND, read_i64(counters, name).unwrap_or(0))?;
432 totals.add_counter(name, amount);
433 }
434 }
435 Ok(totals)
436 }
437}