burrito_secrets/
database.rs

1/*
2 * Copyright (c) 2024.
3 *
4 * Licensed under the MIT license <http://opensource.org/licenses/MIT>.
5 */
6use std::collections::BTreeMap;
7use serde::Serialize;
8use crate::waiters::Waiter;
9
10pub type Entry = bson::Document;
11
12pub trait Metadata: Sized {
13    fn get_meta(&self, key: &str) -> Option<&bson::Bson>;
14
15    fn set_meta(&mut self, metadata: (&str, impl Serialize));
16
17    fn add_meta(&mut self, metadata: (&str, impl Serialize)) {
18        if self.get_meta(metadata.0).is_none() {
19            self.set_meta(metadata);
20        }
21    }
22
23    fn with_meta(mut self, metadata: (&str, impl Serialize)) -> Self {
24        self.set_meta(metadata);
25        self
26    }
27
28    fn and_meta(mut self, metadata: (&str, impl Serialize)) -> Self {
29        self.add_meta(metadata);
30        self
31    }
32
33    fn and_defaults<T: Waiter>(self) -> Self {
34        self.with_meta(("waiter", T::name()))
35            .with_meta(("version", T::version()))
36            .and_meta(("created", bson::DateTime::now()))
37    }
38}
39
40impl Metadata for Entry {
41    fn get_meta(&self, key: &str) -> Option<&bson::Bson> {
42        self.get(key)
43    }
44
45    fn set_meta(&mut self, metadata: (&str, impl Serialize)) {
46        let (key, value) = metadata;
47        let value = bson::to_bson(&value).expect("Failed to serialize metadata");
48        self.insert(key, value);
49    }
50}
51
52impl Metadata for BTreeMap<String, bson::Bson> {
53    fn get_meta(&self, key: &str) -> Option<&bson::Bson> {
54        self.get(key)
55    }
56
57    fn set_meta(&mut self, metadata: (&str, impl Serialize)) {
58        self.insert(metadata.0.to_string(), bson::to_bson(&metadata.1).unwrap());
59    }
60}