Skip to main content

adk_kernel/stores/
ledger_mongodb.rs

1//! The MongoDB [`LedgerStore`] (spec 3.2 §7.10, §13 Q8, features `proc` and `mongodb`).
2
3use async_trait::async_trait;
4use mongodb::bson::{Document, doc};
5use mongodb::options::ReturnDocument;
6use mongodb::{Collection, Database};
7
8use super::day_number;
9use super::mongodb::{
10    collect, connect, create_indexes, json, read_i64, retry_upsert, sorted, store_error, text,
11};
12use crate::error::{KernelError, Result};
13use crate::partition::PartitionId;
14use crate::proc::{
15    LedgerEntry, LedgerQuery, LedgerStore, Observation, ObservationQuery, PassState,
16};
17
18const LEDGER: &str = "adk_kernel_ledger";
19const COUNTERS: &str = "adk_kernel_ledger_counters";
20const OBSERVATIONS: &str = "adk_kernel_observations";
21const PASS_STATES: &str = "adk_kernel_proc_state";
22
23/// The `_id` of the ledger's sequence counter in `adk_kernel_ledger_counters`.
24const SEQUENCE: &str = "ledger";
25
26/// A [`LedgerStore`] in MongoDB, shared by every replica (spec 3.2 §7.1, §7.10, §13 Q8,
27/// features `proc` and `mongodb`).
28///
29/// | Collection | `_id` | Contents |
30/// |------------|-------|----------|
31/// | `adk_kernel_ledger` | The sequence number | `ts_ms` (the instant in UTC milliseconds), `partition`, `agent` and `kind`, the fields `list` filters on, and `row`, the row as JSON text |
32/// | `adk_kernel_ledger_counters` | `ledger` | `seq`, the last sequence number taken |
33/// | `adk_kernel_observations` | The observation id | `partition`, `as_of` (days from the common era) and `body`, the observation as JSON text |
34/// | `adk_kernel_proc_state` | The partition | `body`, the pass state as JSON text |
35///
36/// An append takes the next number with one `$inc` on the counter, then inserts the row
37/// under it, so every row has its own increasing number. The two writes are separate, so a
38/// reader paging with `after` while appends land can pass a row whose number was taken
39/// before the last row it read but which was inserted after it, as with PostgreSQL's
40/// sequence. Neither write needs a multi-document transaction, so a standalone `mongod`
41/// serves the store as a replica set does.
42///
43/// # Example
44///
45/// ```rust,no_run
46/// # async fn example() -> adk_kernel::Result<()> {
47/// let store =
48///     adk_kernel::proc::MongoLedgerStore::connect("mongodb://localhost:27017", "adk").await?;
49/// store.migrate().await?;
50/// # Ok(())
51/// # }
52/// ```
53#[derive(Debug, Clone)]
54pub struct MongoLedgerStore {
55    db: Database,
56}
57
58impl MongoLedgerStore {
59    /// A store over `db`, such as the process store's.
60    pub fn from_database(db: Database) -> Self {
61        Self { db }
62    }
63
64    /// Connects to `connection_string` and uses the database `database_name`.
65    ///
66    /// # Errors
67    ///
68    /// Returns [`KernelError::Store`] when the connection string is invalid.
69    pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
70        Ok(Self::from_database(connect(connection_string, database_name).await?))
71    }
72
73    /// The database the store writes to.
74    pub fn database(&self) -> &Database {
75        &self.db
76    }
77
78    /// Creates the indexes `list` and `observations` read; an index that exists is kept.
79    ///
80    /// # Errors
81    ///
82    /// Returns [`KernelError::Store`] when the server cannot be reached or refuses an index.
83    pub async fn migrate(&self) -> Result<()> {
84        create_indexes(
85            &self.rows(),
86            &[
87                ("adk_kernel_ledger_ts", doc! { "ts_ms": 1 }),
88                ("adk_kernel_ledger_partition", doc! { "partition": 1, "_id": 1 }),
89                ("adk_kernel_ledger_kind", doc! { "kind": 1, "_id": 1 }),
90            ],
91        )
92        .await?;
93        create_indexes(
94            &self.observation_rows(),
95            &[("adk_kernel_observations_as_of", doc! { "partition": 1, "as_of": -1, "_id": 1 })],
96        )
97        .await
98    }
99
100    fn rows(&self) -> Collection<Document> {
101        self.db.collection(LEDGER)
102    }
103
104    fn observation_rows(&self) -> Collection<Document> {
105        self.db.collection(OBSERVATIONS)
106    }
107
108    fn pass_state_rows(&self) -> Collection<Document> {
109        self.db.collection(PASS_STATES)
110    }
111
112    /// Takes the next sequence number.
113    async fn next_seq(&self) -> Result<i64> {
114        let counters: Collection<Document> = self.db.collection(COUNTERS);
115        let counter = retry_upsert("take a ledger sequence number", || {
116            counters
117                .find_one_and_update(doc! { "_id": SEQUENCE }, doc! { "$inc": { "seq": 1_i64 } })
118                .upsert(true)
119                .return_document(ReturnDocument::After)
120        })
121        .await?;
122        counter.as_ref().and_then(|counter| read_i64(counter, "seq")).ok_or_else(|| {
123            store_error("take a ledger sequence number", &"the counter has no `seq` field")
124        })
125    }
126}
127
128fn decode_row(document: &Document) -> Result<LedgerEntry> {
129    let seq = read_i64(document, "_id")
130        .and_then(|seq| u64::try_from(seq).ok())
131        .ok_or_else(|| store_error("read the ledger", &"a row has no sequence number"))?;
132    let mut entry: LedgerEntry = json("ledger row", text(document, "row")?)?;
133    entry.seq = seq;
134    Ok(entry)
135}
136
137#[async_trait]
138impl LedgerStore for MongoLedgerStore {
139    async fn append(&self, mut entry: LedgerEntry) -> Result<LedgerEntry> {
140        entry.seq = 0;
141        let row = serde_json::to_string(&entry)?;
142        let seq = self.next_seq().await?;
143        self.rows()
144            .insert_one(doc! {
145                "_id": seq,
146                "ts_ms": entry.ts.timestamp_millis(),
147                "partition": entry.partition.as_str(),
148                "agent": &entry.agent,
149                "kind": &entry.kind,
150                "row": row,
151            })
152            .await
153            .map_err(|error| store_error("append to the ledger", &error))?;
154        entry.seq = u64::try_from(seq).map_err(|_| KernelError::Store {
155            backend: super::mongodb::BACKEND,
156            reason: format!("the ledger counter holds a negative sequence number {seq}"),
157        })?;
158        Ok(entry)
159    }
160
161    async fn list(&self, query: &LedgerQuery) -> Result<Vec<LedgerEntry>> {
162        if query.limit == Some(0) {
163            return Ok(Vec::new());
164        }
165        let mut filter = Document::new();
166        if let Some(partition) = &query.partition {
167            filter.insert("partition", partition.as_str());
168        }
169        if !query.kinds.is_empty() {
170            filter.insert("kind", doc! { "$in": query.kinds.clone() });
171        }
172        if let Some(agent) = &query.agent {
173            filter.insert("agent", agent);
174        }
175        let mut window = Document::new();
176        if let Some(from) = query.from {
177            window.insert("$gte", from.timestamp_millis());
178        }
179        if let Some(to) = query.to {
180            window.insert("$lt", to.timestamp_millis());
181        }
182        if !window.is_empty() {
183            filter.insert("ts_ms", window);
184        }
185        if let Some(after) = query.after {
186            filter.insert("_id", doc! { "$gt": i64::try_from(after).unwrap_or(i64::MAX) });
187        }
188        let cursor = self
189            .rows()
190            .find(filter)
191            .with_options(sorted(doc! { "_id": 1 }, query.limit))
192            .await
193            .map_err(|error| store_error("read the ledger", &error))?;
194        collect(cursor, "read the ledger").await?.iter().map(decode_row).collect()
195    }
196
197    async fn put_observation(&self, observation: Observation) -> Result<()> {
198        let document = doc! {
199            "_id": &observation.id,
200            "partition": observation.partition.as_str(),
201            "as_of": day_number(observation.as_of),
202            "body": serde_json::to_string(&observation)?,
203        };
204        let rows = self.observation_rows();
205        retry_upsert("write an observation", || {
206            rows.replace_one(doc! { "_id": &observation.id }, document.clone()).upsert(true)
207        })
208        .await?;
209        Ok(())
210    }
211
212    async fn observations(&self, query: &ObservationQuery) -> Result<Vec<Observation>> {
213        if query.limit == Some(0) {
214            return Ok(Vec::new());
215        }
216        let mut filter = Document::new();
217        if let Some(partition) = &query.partition {
218            filter.insert("partition", partition.as_str());
219        }
220        if let Some(since) = query.since {
221            filter.insert("as_of", doc! { "$gte": day_number(since) });
222        }
223        let cursor = self
224            .observation_rows()
225            .find(filter)
226            .with_options(sorted(doc! { "as_of": -1, "_id": 1 }, query.limit))
227            .await
228            .map_err(|error| store_error("read the observations", &error))?;
229        collect(cursor, "read the observations")
230            .await?
231            .iter()
232            .map(|document| json("observation", text(document, "body")?))
233            .collect()
234    }
235
236    async fn pass_state(&self, partition: &PartitionId) -> Result<Option<PassState>> {
237        let document = self
238            .pass_state_rows()
239            .find_one(doc! { "_id": partition.as_str() })
240            .await
241            .map_err(|error| store_error("read the pass state", &error))?;
242        document.map(|document| json("pass state", text(&document, "body")?)).transpose()
243    }
244
245    async fn pass_states(&self) -> Result<Vec<PassState>> {
246        let cursor = self
247            .pass_state_rows()
248            .find(Document::new())
249            .with_options(sorted(doc! { "_id": 1 }, None))
250            .await
251            .map_err(|error| store_error("read the pass states", &error))?;
252        collect(cursor, "read the pass states")
253            .await?
254            .iter()
255            .map(|document| json("pass state", text(document, "body")?))
256            .collect()
257    }
258
259    async fn put_pass_state(&self, state: PassState) -> Result<()> {
260        let partition = state.partition.as_str().to_string();
261        let document = doc! { "_id": &partition, "body": serde_json::to_string(&state)? };
262        let rows = self.pass_state_rows();
263        retry_upsert("write the pass state", || {
264            rows.replace_one(doc! { "_id": &partition }, document.clone()).upsert(true)
265        })
266        .await?;
267        Ok(())
268    }
269}