Skip to main content

fedimint_client/
oplog.rs

1use std::collections::HashSet;
2use std::fmt::Debug;
3use std::ops::Range;
4use std::sync::Arc;
5use std::time::{Duration, SystemTime};
6
7use fedimint_client_module::oplog::{
8    IOperationLog, JsonStringed, OperationLogEntry, OperationOutcome, UpdateStreamOrOutcome,
9};
10use fedimint_core::core::OperationId;
11use fedimint_core::db::{Database, DatabaseTransaction, IDatabaseTransactionOpsCoreTyped as _};
12use fedimint_core::task::{MaybeSend, MaybeSync};
13use fedimint_core::time::now;
14use fedimint_core::util::BoxStream;
15use fedimint_core::{apply, async_trait_maybe_send};
16use fedimint_logging::LOG_CLIENT;
17use futures::StreamExt as _;
18use serde::Serialize;
19use serde::de::DeserializeOwned;
20use tokio::sync::RwLock;
21use tracing::{error, instrument, warn};
22
23use crate::db::{ChronologicalOperationLogKey, OperationLogKey};
24
25#[cfg(test)]
26mod tests;
27
28#[derive(Debug, Clone)]
29pub struct OperationLog {
30    db: Database,
31    oldest_entry: Arc<RwLock<Option<ChronologicalOperationLogKey>>>,
32}
33
34impl OperationLog {
35    pub fn new(db: Database) -> Self {
36        Self {
37            db,
38            oldest_entry: Arc::new(RwLock::new(None)),
39        }
40    }
41
42    /// Will return the oldest operation log key in the database and cache the
43    /// result. If no entry exists yet the DB will be queried on each call till
44    /// an entry is present.
45    async fn get_oldest_operation_log_key(&self) -> Option<ChronologicalOperationLogKey> {
46        if let Some(oldest_entry) = *self.oldest_entry.read().await {
47            return Some(oldest_entry);
48        }
49
50        let mut dbtx = self.db.begin_transaction_nc().await;
51        let oldest_entry = dbtx
52            .find_by_prefix(&crate::db::ChronologicalOperationLogKeyPrefix)
53            .await
54            .map(|(key, ())| key)
55            .next()
56            .await;
57
58        if let Some(oldest_entry) = oldest_entry {
59            *self.oldest_entry.write().await = Some(oldest_entry);
60        }
61
62        oldest_entry
63    }
64
65    pub async fn add_operation_log_entry_dbtx(
66        &self,
67        dbtx: &mut DatabaseTransaction<'_>,
68        operation_id: OperationId,
69        operation_type: &str,
70        operation_meta: impl serde::Serialize,
71    ) {
72        self.add_operation_log_entry_dbtx_with_creation_time(
73            dbtx,
74            operation_id,
75            operation_type,
76            operation_meta,
77            now(),
78        )
79        .await;
80    }
81
82    pub async fn add_operation_log_entry_dbtx_with_creation_time(
83        &self,
84        dbtx: &mut DatabaseTransaction<'_>,
85        operation_id: OperationId,
86        operation_type: &str,
87        operation_meta: impl serde::Serialize,
88        creation_time: SystemTime,
89    ) {
90        dbtx.insert_new_entry(
91            &OperationLogKey { operation_id },
92            &OperationLogEntry::new(
93                operation_type.to_string(),
94                JsonStringed(
95                    serde_json::to_value(operation_meta)
96                        .expect("Can only fail if meta is not serializable"),
97                ),
98                None,
99            ),
100        )
101        .await;
102        let chronological_operation_log_key = ChronologicalOperationLogKey {
103            creation_time,
104            operation_id,
105        };
106        dbtx.insert_new_entry(&chronological_operation_log_key, &())
107            .await;
108
109        let mut oldest_entry = self.oldest_entry.write().await;
110        if let Some(oldest_entry_key) = &mut *oldest_entry
111            && chronological_operation_log_key_is_older(
112                &chronological_operation_log_key,
113                oldest_entry_key,
114            )
115        {
116            *oldest_entry_key = chronological_operation_log_key;
117        }
118    }
119
120    #[deprecated(since = "0.6.0", note = "Use `paginate_operations_rev` instead")]
121    pub async fn list_operations(
122        &self,
123        limit: usize,
124        last_seen: Option<ChronologicalOperationLogKey>,
125    ) -> Vec<(ChronologicalOperationLogKey, OperationLogEntry)> {
126        self.paginate_operations_rev(limit, last_seen).await
127    }
128
129    /// Returns the last `limit` operations. To fetch the next page, pass the
130    /// last operation's [`ChronologicalOperationLogKey`] as `start_after`.
131    pub async fn paginate_operations_rev(
132        &self,
133        limit: usize,
134        last_seen: Option<ChronologicalOperationLogKey>,
135    ) -> Vec<(ChronologicalOperationLogKey, OperationLogEntry)> {
136        const EPOCH_DURATION: Duration = Duration::from_secs(60 * 60 * 24 * 7);
137
138        let start_after_key = last_seen.unwrap_or_else(|| ChronologicalOperationLogKey {
139            // We don't expect any operations from the future to exist, since SystemTime isn't
140            // monotone and CI can be overloaded at times we add a small buffer to avoid flakiness
141            // in tests.
142            creation_time: now() + Duration::from_secs(30),
143            operation_id: OperationId([0; 32]),
144        });
145
146        let Some(oldest_entry_key) = self.get_oldest_operation_log_key().await else {
147            return vec![];
148        };
149
150        let mut dbtx = self.db.begin_transaction_nc().await;
151        let mut operation_log_keys = Vec::with_capacity(32);
152
153        // Find all the operation log keys in the requested window. Since we decided to
154        // not introduce a find_by_range_rev function we have to jump through some
155        // hoops, see also the comments in rev_epoch_ranges.
156        // TODO: Implement using find_by_range_rev if ever introduced
157        'outer: for key_range_rev in
158            rev_epoch_ranges(start_after_key, oldest_entry_key, EPOCH_DURATION)
159        {
160            let epoch_operation_log_keys_rev = dbtx
161                .find_by_range(key_range_rev)
162                .await
163                .map(|(key, ())| key)
164                .collect::<Vec<_>>()
165                .await;
166
167            for operation_log_key in epoch_operation_log_keys_rev.into_iter().rev() {
168                operation_log_keys.push(operation_log_key);
169                if operation_log_keys.len() >= limit {
170                    break 'outer;
171                }
172            }
173        }
174
175        debug_assert!(
176            operation_log_keys.iter().collect::<HashSet<_>>().len() == operation_log_keys.len(),
177            "Operation log keys returned are not unique"
178        );
179
180        let mut operation_log_entries = Vec::with_capacity(operation_log_keys.len());
181        for operation_log_key in operation_log_keys {
182            let operation_log_entry = dbtx
183                .get_value(&OperationLogKey {
184                    operation_id: operation_log_key.operation_id,
185                })
186                .await
187                .expect("Inconsistent DB");
188            operation_log_entries.push((operation_log_key, operation_log_entry));
189        }
190
191        operation_log_entries
192    }
193
194    pub async fn get_operation(&self, operation_id: OperationId) -> Option<OperationLogEntry> {
195        Self::get_operation_dbtx(
196            &mut self.db.begin_transaction_nc().await.into_nc(),
197            operation_id,
198        )
199        .await
200    }
201
202    pub async fn get_operation_dbtx(
203        dbtx: &mut DatabaseTransaction<'_>,
204        operation_id: OperationId,
205    ) -> Option<OperationLogEntry> {
206        dbtx.get_value(&OperationLogKey { operation_id }).await
207    }
208
209    /// Sets the outcome of an operation
210    #[instrument(target = LOG_CLIENT, skip(db), level = "debug")]
211    pub async fn set_operation_outcome(
212        db: &Database,
213        operation_id: OperationId,
214        outcome: &(impl Serialize + Debug),
215    ) -> anyhow::Result<()> {
216        let outcome_json =
217            JsonStringed(serde_json::to_value(outcome).expect("Outcome is not serializable"));
218
219        let mut dbtx = db.begin_transaction().await;
220        let mut operation = Self::get_operation_dbtx(&mut dbtx.to_ref_nc(), operation_id)
221            .await
222            .expect("Operation exists");
223        operation.set_outcome(OperationOutcome {
224            time: fedimint_core::time::now(),
225            outcome: outcome_json,
226        });
227        dbtx.insert_entry(&OperationLogKey { operation_id }, &operation)
228            .await;
229        dbtx.commit_tx_result().await?;
230
231        Ok(())
232    }
233
234    /// Returns an a [`UpdateStreamOrOutcome`] enum that can be converted into
235    /// an update stream for easier handling using
236    /// [`UpdateStreamOrOutcome::into_stream`] but can also be matched over to
237    /// shortcut the handling of final outcomes.
238    pub fn outcome_or_updates<U, S>(
239        db: &Database,
240        operation_id: OperationId,
241        operation_log_entry: OperationLogEntry,
242        stream_gen: impl FnOnce() -> S,
243    ) -> UpdateStreamOrOutcome<U>
244    where
245        U: Clone + Serialize + DeserializeOwned + Debug + MaybeSend + MaybeSync + 'static,
246        S: futures::Stream<Item = U> + MaybeSend + 'static,
247    {
248        match operation_log_entry.outcome::<U>() {
249            Some(outcome) => UpdateStreamOrOutcome::Outcome(outcome),
250            None => UpdateStreamOrOutcome::UpdateStream(caching_operation_update_stream(
251                db.clone(),
252                operation_id,
253                stream_gen(),
254            )),
255        }
256    }
257
258    /// Tries to set the outcome of an operation, but only logs an error if it
259    /// fails and does not return it. Since the outcome can always be recomputed
260    /// from an update stream, failing to save it isn't a problem in cases where
261    /// we do this merely for caching.
262    pub async fn optimistically_set_operation_outcome(
263        db: &Database,
264        operation_id: OperationId,
265        outcome: &(impl Serialize + Debug),
266    ) {
267        if let Err(e) = Self::set_operation_outcome(db, operation_id, outcome).await {
268            warn!(
269                target: LOG_CLIENT,
270                "Error setting operation outcome: {e}"
271            );
272        }
273    }
274}
275
276#[apply(async_trait_maybe_send!)]
277impl IOperationLog for OperationLog {
278    async fn get_operation(&self, operation_id: OperationId) -> Option<OperationLogEntry> {
279        OperationLog::get_operation(self, operation_id).await
280    }
281
282    async fn get_operation_dbtx(
283        &self,
284        dbtx: &mut DatabaseTransaction<'_>,
285        operation_id: OperationId,
286    ) -> Option<OperationLogEntry> {
287        OperationLog::get_operation_dbtx(dbtx, operation_id).await
288    }
289
290    async fn add_operation_log_entry_dbtx(
291        &self,
292        dbtx: &mut DatabaseTransaction<'_>,
293        operation_id: OperationId,
294        operation_type: &str,
295        operation_meta: serde_json::Value,
296    ) {
297        OperationLog::add_operation_log_entry_dbtx(
298            self,
299            dbtx,
300            operation_id,
301            operation_type,
302            operation_meta,
303        )
304        .await
305    }
306
307    fn outcome_or_updates(
308        &self,
309        db: &Database,
310        operation_id: OperationId,
311        operation: OperationLogEntry,
312        stream_gen: Box<dyn FnOnce() -> BoxStream<'static, serde_json::Value>>,
313    ) -> UpdateStreamOrOutcome<serde_json::Value> {
314        match OperationLog::outcome_or_updates(db, operation_id, operation, stream_gen) {
315            UpdateStreamOrOutcome::UpdateStream(pin) => UpdateStreamOrOutcome::UpdateStream(pin),
316            UpdateStreamOrOutcome::Outcome(o) => {
317                UpdateStreamOrOutcome::Outcome(serde_json::from_value(o).expect("Can't fail"))
318            }
319        }
320    }
321}
322
323fn chronological_operation_log_key_is_older(
324    lhs: &ChronologicalOperationLogKey,
325    rhs: &ChronologicalOperationLogKey,
326) -> bool {
327    (lhs.creation_time, lhs.operation_id) < (rhs.creation_time, rhs.operation_id)
328}
329
330/// Returns an iterator over the ranges of operation log keys, starting from the
331/// most recent range and going backwards in time till slightly later than
332/// `last_entry`.
333///
334/// Simplifying keys to integers and assuming a `start_after` of 100, a
335/// `last_entry` of 55 and an `epoch_duration` of 10 the ranges would be:
336/// ```text
337/// [90..100, 80..90, 70..80, 60..70, 50..60]
338/// ```
339fn rev_epoch_ranges(
340    start_after: ChronologicalOperationLogKey,
341    last_entry: ChronologicalOperationLogKey,
342    epoch_duration: Duration,
343) -> impl Iterator<Item = Range<ChronologicalOperationLogKey>> {
344    // We want to fetch all operations that were created before `start_after`, going
345    // backwards in time. This means "start" generally means a later time than
346    // "end". Only when creating a rust Range we have to swap the terminology (see
347    // comment there).
348    (0..)
349        .map(move |epoch| start_after.creation_time - epoch * epoch_duration)
350        // We want to get all operation log keys in the range [last_key, start_after). So as
351        // long as the start time is greater than the last key's creation time, we have to
352        // keep going.
353        .take_while(move |&start_time| start_time >= last_entry.creation_time)
354        .map(move |start_time| {
355            let end_time = start_time - epoch_duration;
356
357            // In the edge case that there were two events logged at exactly the same time
358            // we need to specify the correct operation_id for the first key. Otherwise, we
359            // could miss entries.
360            let start_key = if start_time == start_after.creation_time {
361                start_after
362            } else {
363                ChronologicalOperationLogKey {
364                    creation_time: start_time,
365                    operation_id: OperationId([0; 32]),
366                }
367            };
368
369            // We could also special-case the last key here, but it's not necessary, making
370            // it last_key if end_time < last_key.creation_time. We know there are no
371            // entries beyond last_key though, so the range query will be equivalent either
372            // way.
373            let end_key = ChronologicalOperationLogKey {
374                creation_time: end_time,
375                operation_id: OperationId([0; 32]),
376            };
377
378            // We want to go backwards using a forward range query. This means we have to
379            // swap the start and end keys and then reverse the vector returned by the
380            // query.
381            Range {
382                start: end_key,
383                end: start_key,
384            }
385        })
386}
387
388/// Wraps an operation update stream such that the last update before it closes
389/// is tried to be written to the operation log entry as its outcome.
390pub fn caching_operation_update_stream<'a, U, S>(
391    db: Database,
392    operation_id: OperationId,
393    stream: S,
394) -> BoxStream<'a, U>
395where
396    U: Clone + Serialize + Debug + MaybeSend + MaybeSync + 'static,
397    S: futures::Stream<Item = U> + MaybeSend + 'a,
398{
399    let mut stream = Box::pin(stream);
400    Box::pin(async_stream::stream! {
401        let mut last_update = None;
402        while let Some(update) = stream.next().await {
403            yield update.clone();
404            last_update = Some(update);
405        }
406
407        let Some(last_update) = last_update else {
408            error!(
409                target: LOG_CLIENT,
410                "Stream ended without any updates, this should not happen!"
411            );
412            return;
413        };
414
415        OperationLog::optimistically_set_operation_outcome(&db, operation_id, &last_update).await;
416    })
417}