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