1use async_trait::async_trait;
4use mongodb::bson::{Document, doc};
5use mongodb::{Collection, Database};
6
7use super::mongodb::{
8 collect, connect, create_indexes, json, retry_upsert, sorted, store_error, text,
9};
10use crate::error::Result;
11use crate::partition::{CrossingFilter, CrossingRecord, Partition, PartitionId, PartitionStore};
12
13const PARTITIONS: &str = "adk_kernel_partitions";
14const CROSSINGS: &str = "adk_kernel_crossings";
15const GRANTS: &str = "adk_kernel_crossing_grants";
16
17#[derive(Debug, Clone)]
44pub struct MongoPartitionStore {
45 db: Database,
46}
47
48impl MongoPartitionStore {
49 pub fn from_database(db: Database) -> Self {
51 Self { db }
52 }
53
54 pub async fn connect(connection_string: &str, database_name: &str) -> Result<Self> {
61 Ok(Self::from_database(connect(connection_string, database_name).await?))
62 }
63
64 pub fn database(&self) -> &Database {
66 &self.db
67 }
68
69 pub async fn migrate(&self) -> Result<()> {
76 create_indexes(
77 &self.crossing_rows(),
78 &[
79 ("adk_kernel_crossings_at", doc! { "at_us": 1, "_id": 1 }),
80 ("adk_kernel_crossings_run", doc! { "run": 1, "at_us": 1, "_id": 1 }),
81 ("adk_kernel_crossings_from", doc! { "from": 1, "at_us": 1, "_id": 1 }),
82 ("adk_kernel_crossings_to", doc! { "to": 1, "at_us": 1, "_id": 1 }),
83 ],
84 )
85 .await?;
86 create_indexes(
87 &self.grant_rows(),
88 &[("adk_kernel_crossing_grants_run", doc! { "run": 1, "fingerprint": 1 })],
89 )
90 .await
91 }
92
93 fn partition_rows(&self) -> Collection<Document> {
94 self.db.collection(PARTITIONS)
95 }
96
97 fn crossing_rows(&self) -> Collection<Document> {
98 self.db.collection(CROSSINGS)
99 }
100
101 fn grant_rows(&self) -> Collection<Document> {
102 self.db.collection(GRANTS)
103 }
104}
105
106fn decode_partition(document: &Document) -> Result<Partition> {
107 json("partition", text(document, "record")?)
108}
109
110#[async_trait]
111impl PartitionStore for MongoPartitionStore {
112 async fn put(&self, partition: Partition) -> Result<()> {
113 let id = partition.id.as_str().to_string();
114 let document = doc! { "_id": &id, "record": serde_json::to_string(&partition)? };
115 let rows = self.partition_rows();
116 retry_upsert("write the partition table", || {
117 rows.replace_one(doc! { "_id": &id }, document.clone()).upsert(true)
118 })
119 .await?;
120 Ok(())
121 }
122
123 async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
124 let document = self
125 .partition_rows()
126 .find_one(doc! { "_id": id.as_str() })
127 .await
128 .map_err(|error| store_error("read the partition table", &error))?;
129 document.as_ref().map(decode_partition).transpose()
130 }
131
132 async fn list(&self) -> Result<Vec<Partition>> {
133 let cursor = self
134 .partition_rows()
135 .find(Document::new())
136 .with_options(sorted(doc! { "_id": 1 }, None))
137 .await
138 .map_err(|error| store_error("list the partition table", &error))?;
139 collect(cursor, "list the partition table").await?.iter().map(decode_partition).collect()
140 }
141
142 async fn delete(&self, id: &PartitionId) -> Result<bool> {
143 let result = self
144 .partition_rows()
145 .delete_one(doc! { "_id": id.as_str() })
146 .await
147 .map_err(|error| store_error("delete from the partition table", &error))?;
148 Ok(result.deleted_count == 1)
149 }
150
151 async fn record_crossing(&self, record: CrossingRecord) -> Result<()> {
152 self.crossing_rows()
153 .insert_one(doc! {
154 "_id": &record.id,
155 "at_us": record.at.timestamp_micros(),
156 "run": &record.run,
157 "from": record.from.as_str(),
158 "to": record.to.as_str(),
159 "fingerprint": &record.fingerprint,
160 "outcome": record.outcome.as_str(),
161 "record": serde_json::to_string(&record)?,
162 })
163 .await
164 .map_err(|error| store_error("record a crossing", &error))?;
165 Ok(())
166 }
167
168 async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
169 if filter.limit == Some(0) {
170 return Ok(Vec::new());
171 }
172 let mut query = Document::new();
173 if let Some(from) = &filter.from {
174 query.insert("from", from.as_str());
175 }
176 if let Some(to) = &filter.to {
177 query.insert("to", to.as_str());
178 }
179 if let Some(run) = &filter.run {
180 query.insert("run", run);
181 }
182 if let Some(fingerprint) = &filter.fingerprint {
183 query.insert("fingerprint", fingerprint);
184 }
185 if !filter.outcomes.is_empty() {
186 let outcomes: Vec<&str> =
187 filter.outcomes.iter().map(|outcome| outcome.as_str()).collect();
188 query.insert("outcome", doc! { "$in": outcomes });
189 }
190 if let Some(since) = filter.since {
191 query.insert("at_us", doc! { "$gte": since.timestamp_micros() });
192 }
193 let cursor = self
194 .crossing_rows()
195 .find(query)
196 .with_options(sorted(doc! { "at_us": 1, "_id": 1 }, filter.limit))
197 .await
198 .map_err(|error| store_error("read the crossings", &error))?;
199 collect(cursor, "read the crossings")
200 .await?
201 .iter()
202 .map(|document| json("crossing record", text(document, "record")?))
203 .collect()
204 }
205
206 async fn grant(&self, run: &str, fingerprint: &str) -> Result<()> {
207 let id = doc! { "run": run, "fingerprint": fingerprint };
208 let update = doc! { "$setOnInsert": { "run": run, "fingerprint": fingerprint } };
209 let rows = self.grant_rows();
210 retry_upsert("record a crossing grant", || {
211 rows.update_one(doc! { "_id": id.clone() }, update.clone()).upsert(true)
212 })
213 .await?;
214 Ok(())
215 }
216
217 async fn grants(&self, run: &str) -> Result<Vec<String>> {
218 let cursor = self
219 .grant_rows()
220 .find(doc! { "run": run })
221 .with_options(sorted(doc! { "fingerprint": 1 }, None))
222 .await
223 .map_err(|error| store_error("read the crossing grants", &error))?;
224 collect(cursor, "read the crossing grants")
225 .await?
226 .iter()
227 .map(|document| text(document, "fingerprint").map(str::to_string))
228 .collect()
229 }
230
231 async fn release_run(&self, run: &str) -> Result<u64> {
232 let result = self
233 .grant_rows()
234 .delete_many(doc! { "run": run })
235 .await
236 .map_err(|error| store_error("release the crossing grants", &error))?;
237 Ok(result.deleted_count)
238 }
239}