Skip to main content

fedimint_eventlog/
lib.rs

1#![allow(clippy::needless_lifetimes)]
2
3//! Client Event Log
4//!
5//! The goal here is to maintain a single, ordered, append only
6//! log of all important client-side events: low or high level,
7//! and move as much of coordination between different parts of
8//! the system in a natural and decomposed way.
9//!
10//! Any event log "follower" can just keep going through
11//! all events and react to ones it is interested in (and understands),
12//! potentially emitting events of its own, and atomically updating persisted
13//! event log position ("cursor") of events that were already processed.
14
15use std::borrow::Cow;
16use std::str::FromStr;
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::time::Duration;
19use std::{fmt, ops};
20
21use fedimint_core::core::{ModuleInstanceId, ModuleKind};
22use fedimint_core::db::{
23    Database, DatabaseTransaction, IDatabaseTransactionOpsCoreTyped, NonCommittable,
24};
25use fedimint_core::encoding::{Decodable, Encodable};
26use fedimint_core::runtime::{Instant, timeout};
27use fedimint_core::{Amount, apply, async_trait_maybe_send, impl_db_lookup, impl_db_record};
28use fedimint_logging::LOG_CLIENT_EVENT_LOG;
29use futures::{Future, StreamExt};
30use itertools::Itertools;
31use serde::{Deserialize, Serialize};
32use thiserror::Error;
33use tokio::sync::{broadcast, watch};
34use tracing::{debug, trace};
35
36/// DB prefixes hardcoded for use of the event log
37/// `fedimint-eventlog` was extracted from `fedimint-client` to help
38/// include/re-use in other part of the code. But fundamentally its role
39/// is to implement event log in the client.
40/// There is currently no way to inject the prefixes to use for db records,
41/// so we use these constants to keep them in sync. Any other app that will
42/// want to store its own even log, will need to use the exact same prefixes,
43/// which in practice should not be a problem.
44pub const DB_KEY_PREFIX_UNORDERED_EVENT_LOG: u8 = 0x3a;
45pub const DB_KEY_PREFIX_EVENT_LOG: u8 = 0x39;
46pub const DB_KEY_PREFIX_EVENT_LOG_TRIMABLE: u8 = 0x41;
47
48/// Minimum age in ID count for trimable events to be deleted
49const TRIMABLE_EVENTLOG_MIN_ID_AGE: u64 = 10_000;
50/// Minimum age in microseconds for trimable events to be deleted (14 days)
51const TRIMABLE_EVENTLOG_MIN_TS_AGE: u64 = 14 * 24 * 60 * 60 * 1_000_000;
52/// Maximum number of entries to trim in one operation
53const TRIMABLE_EVENTLOG_MAX_TRIMMED_EVENTS: usize = 100_000;
54
55/// Type of persistence the [`Event`] uses.
56///
57/// As a compromise between richness of events and amount of data to store
58/// Fedimint maintains two event logs in parallel:
59///
60/// * untrimable
61/// * trimable
62///
63/// Untrimable log will append only a subset of events that are infrequent,
64/// but important enough to be forever useful, e.g. for processing or debugging
65/// of historical events.
66///
67/// Trimable log will append all persistent events, but will over time remove
68/// the oldest ones. It will always retain enough events, that no log follower
69/// actively processing it should ever miss any event, but restarting processing
70/// from the start (index 0) can't be used for processing historical data.
71///
72/// Notably the positions in both logs are not interchangeable, so they use
73/// different types.
74///
75/// On top of it, some events are transient and are not persisted at all,
76/// and emitted only at runtime.
77///
78/// Consult [`Event::PERSISTENCE`] to know which event uses which persistence.
79#[derive(Clone, Copy)]
80pub enum EventPersistence {
81    /// Not written anywhere, just broadcasted as notification at runtime
82    Transient,
83    /// Persised only to log that gets trimmed
84    Trimable,
85    /// Persisted in both trimmed and untrimmed logs, so potentially
86    /// stored forever.
87    Persistent,
88}
89
90pub trait Event: serde::Serialize + serde::de::DeserializeOwned {
91    const MODULE: Option<ModuleKind>;
92    const KIND: EventKind;
93    const PERSISTENCE: EventPersistence;
94}
95
96/// An counter that resets on every restart, that guarantees that
97/// [`UnordedEventLogId`]s don't conflict with each other.
98static UNORDEREDED_EVENT_LOG_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
99
100/// A self-allocated ID that is mostly ordered
101///
102/// The goal here is to avoid concurrent database transaction
103/// conflicts due the ID allocation. Instead they are picked based on
104/// a time and a counter, so they are mostly but not strictly ordered and
105/// monotonic, and even more importantly: not contiguous.
106#[derive(Debug, Encodable, Decodable)]
107pub struct UnordedEventLogId {
108    ts_usecs: u64,
109    counter: u64,
110}
111
112impl UnordedEventLogId {
113    fn new() -> Self {
114        Self {
115            ts_usecs: u64::try_from(fedimint_core::time::duration_since_epoch().as_micros())
116                // This will never happen
117                .unwrap_or(u64::MAX),
118            counter: UNORDEREDED_EVENT_LOG_ID_COUNTER.fetch_add(1, Ordering::Relaxed),
119        }
120    }
121}
122
123/// Ordered, contiguous ID space, which is easy for event log followers to
124/// track.
125#[derive(
126    Copy,
127    Clone,
128    Debug,
129    Encodable,
130    Decodable,
131    Default,
132    PartialEq,
133    Eq,
134    PartialOrd,
135    Ord,
136    Serialize,
137    Deserialize,
138)]
139pub struct EventLogId(u64);
140
141impl EventLogId {
142    pub const LOG_START: EventLogId = EventLogId(0);
143
144    pub fn next(self) -> EventLogId {
145        Self(self.0 + 1)
146    }
147
148    pub fn saturating_add(self, rhs: u64) -> EventLogId {
149        Self(self.0.saturating_add(rhs))
150    }
151
152    pub fn saturating_sub(self, rhs: u64) -> EventLogId {
153        Self(self.0.saturating_sub(rhs))
154    }
155
156    pub fn checked_sub(self, rhs: u64) -> Option<EventLogId> {
157        self.0.checked_sub(rhs).map(EventLogId)
158    }
159}
160
161impl From<EventLogId> for u64 {
162    fn from(value: EventLogId) -> Self {
163        value.0
164    }
165}
166
167impl FromStr for EventLogId {
168    type Err = <u64 as FromStr>::Err;
169
170    fn from_str(s: &str) -> Result<Self, Self::Err> {
171        u64::from_str(s).map(Self)
172    }
173}
174
175impl fmt::Display for EventLogId {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        write!(f, "{}", self.0)
178    }
179}
180
181#[derive(Debug, Clone, Encodable, Decodable, PartialEq, Eq, Serialize, Deserialize)]
182pub struct EventKind(Cow<'static, str>);
183
184impl EventKind {
185    pub const fn from_static(value: &'static str) -> Self {
186        Self(Cow::Borrowed(value))
187    }
188}
189
190impl<'s> From<&'s str> for EventKind {
191    fn from(value: &'s str) -> Self {
192        Self(Cow::Owned(value.to_owned()))
193    }
194}
195
196impl From<String> for EventKind {
197    fn from(value: String) -> Self {
198        Self(Cow::Owned(value))
199    }
200}
201
202impl fmt::Display for EventKind {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        f.write_str(&self.0)
205    }
206}
207
208#[derive(Debug, Encodable, Decodable, Clone, Serialize, Deserialize)]
209pub struct EventLogModule {
210    pub kind: ModuleKind,
211    pub id: ModuleInstanceId,
212}
213
214#[derive(Debug, Encodable, Decodable, Clone)]
215pub struct UnorderedEventLogEntry {
216    pub flags: u8,
217    pub inner: EventLogEntry,
218}
219
220impl UnorderedEventLogEntry {
221    pub const FLAG_PERSIST: u8 = 1;
222    pub const FLAG_TRIMABLE: u8 = 2;
223
224    fn persist(&self) -> bool {
225        self.flags & Self::FLAG_PERSIST != 0
226    }
227
228    fn trimable(&self) -> bool {
229        self.flags & Self::FLAG_TRIMABLE != 0
230    }
231}
232
233#[derive(Debug, Encodable, Decodable, Clone)]
234pub struct EventLogEntry {
235    /// Type/kind of the event
236    ///
237    /// Any part of the client is free to self-allocate identifier, denoting a
238    /// certain kind of an event. Notably one event kind have multiple
239    /// instances. E.g. "successful wallet deposit" can be an event kind,
240    /// and it can happen multiple times with different payloads.
241    pub kind: EventKind,
242
243    /// To prevent accidental conflicts between `kind`s, a module kind the
244    /// given event kind belong is used as well.
245    ///
246    /// Note: the meaning of this field is mostly about which part of the code
247    /// defines this event kind. Oftentime a core (non-module)-defined event
248    /// will refer in some way to a module. It should use a separate `module_id`
249    /// field in the `payload`, instead of this field.
250    pub module: Option<EventLogModule>,
251
252    /// Timestamp in microseconds after unix epoch
253    pub ts_usecs: u64,
254
255    /// Event-kind specific payload, typically encoded as a json string for
256    /// flexibility.
257    pub payload: Vec<u8>,
258}
259
260impl EventLogEntry {
261    pub fn module_kind(&self) -> Option<&ModuleKind> {
262        self.module.as_ref().map(|m| &m.kind)
263    }
264
265    pub fn module_id(&self) -> Option<ModuleInstanceId> {
266        self.module.as_ref().map(|m| m.id)
267    }
268
269    /// Get the event payload as typed value
270    pub fn to_event<E>(&self) -> Option<E>
271    where
272        E: Event,
273    {
274        serde_json::from_slice(&self.payload).ok()
275    }
276}
277
278/// An `EventLogEntry` that was already persisted (so has an id)
279#[derive(Debug, Clone)]
280pub struct PersistedLogEntry {
281    id: EventLogId,
282    inner: EventLogEntry,
283}
284
285impl Serialize for PersistedLogEntry {
286    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
287    where
288        S: serde::Serializer,
289    {
290        use serde::ser::SerializeStruct;
291
292        let mut state = serializer.serialize_struct("PersistedLogEntry", 5)?;
293        state.serialize_field("id", &self.id)?;
294        state.serialize_field("kind", &self.inner.kind)?;
295        state.serialize_field("module", &self.inner.module)?;
296        state.serialize_field("ts_usecs", &self.inner.ts_usecs)?;
297
298        // Try to deserialize payload as JSON, fall back to hex encoding
299        let payload_value: serde_json::Value = serde_json::from_slice(&self.inner.payload)
300            .unwrap_or_else(|_| serde_json::Value::String(hex::encode(&self.inner.payload)));
301        state.serialize_field("payload", &payload_value)?;
302
303        state.end()
304    }
305}
306
307impl<'de> Deserialize<'de> for PersistedLogEntry {
308    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
309    where
310        D: serde::Deserializer<'de>,
311    {
312        use serde::de::{self, MapAccess, Visitor};
313
314        #[derive(Deserialize)]
315        #[serde(field_identifier, rename_all = "snake_case")]
316        enum Field {
317            Id,
318            Kind,
319            Module,
320            TsUsecs,
321            Payload,
322        }
323
324        struct PersistedLogEntryVisitor;
325
326        impl<'de> Visitor<'de> for PersistedLogEntryVisitor {
327            type Value = PersistedLogEntry;
328
329            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
330                formatter.write_str("struct PersistedLogEntry")
331            }
332
333            fn visit_map<V>(self, mut map: V) -> Result<PersistedLogEntry, V::Error>
334            where
335                V: MapAccess<'de>,
336            {
337                let mut id = None;
338                let mut kind = None;
339                let mut module = None;
340                let mut ts_usecs = None;
341                let mut payload = None;
342
343                while let Some(key) = map.next_key()? {
344                    match key {
345                        Field::Id => {
346                            if id.is_some() {
347                                return Err(de::Error::duplicate_field("id"));
348                            }
349                            id = Some(map.next_value()?);
350                        }
351                        Field::Kind => {
352                            if kind.is_some() {
353                                return Err(de::Error::duplicate_field("kind"));
354                            }
355                            kind = Some(map.next_value()?);
356                        }
357                        Field::Module => {
358                            if module.is_some() {
359                                return Err(de::Error::duplicate_field("module"));
360                            }
361                            module = Some(map.next_value()?);
362                        }
363                        Field::TsUsecs => {
364                            if ts_usecs.is_some() {
365                                return Err(de::Error::duplicate_field("ts_usecs"));
366                            }
367                            ts_usecs = Some(map.next_value()?);
368                        }
369                        Field::Payload => {
370                            if payload.is_some() {
371                                return Err(de::Error::duplicate_field("payload"));
372                            }
373                            let value: serde_json::Value = map.next_value()?;
374                            payload = Some(serde_json::to_vec(&value).map_err(de::Error::custom)?);
375                        }
376                    }
377                }
378
379                let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
380                let kind = kind.ok_or_else(|| de::Error::missing_field("kind"))?;
381                let module = module.ok_or_else(|| de::Error::missing_field("module"))?;
382                let ts_usecs = ts_usecs.ok_or_else(|| de::Error::missing_field("ts_usecs"))?;
383                let payload = payload.ok_or_else(|| de::Error::missing_field("payload"))?;
384
385                Ok(PersistedLogEntry {
386                    id,
387                    inner: EventLogEntry {
388                        kind,
389                        module,
390                        ts_usecs,
391                        payload,
392                    },
393                })
394            }
395        }
396
397        const FIELDS: &[&str] = &["id", "kind", "module", "ts_usecs", "payload"];
398        deserializer.deserialize_struct("PersistedLogEntry", FIELDS, PersistedLogEntryVisitor)
399    }
400}
401
402impl PersistedLogEntry {
403    pub fn id(&self) -> EventLogId {
404        self.id
405    }
406
407    pub fn as_raw(&self) -> &EventLogEntry {
408        &self.inner
409    }
410}
411
412impl ops::Deref for PersistedLogEntry {
413    type Target = EventLogEntry;
414
415    fn deref(&self) -> &Self::Target {
416        &self.inner
417    }
418}
419
420impl_db_record!(
421    key = UnordedEventLogId,
422    value = UnorderedEventLogEntry,
423    db_prefix = DB_KEY_PREFIX_UNORDERED_EVENT_LOG,
424);
425
426#[derive(Clone, Debug, Encodable, Decodable)]
427pub struct UnorderedEventLogIdPrefixAll;
428
429impl_db_lookup!(
430    key = UnordedEventLogId,
431    query_prefix = UnorderedEventLogIdPrefixAll
432);
433
434#[derive(Clone, Debug, Encodable, Decodable)]
435pub struct EventLogIdPrefixAll;
436
437#[derive(Clone, Debug, Encodable, Decodable)]
438pub struct EventLogIdPrefix(EventLogId);
439
440impl_db_record!(
441    key = EventLogId,
442    value = EventLogEntry,
443    db_prefix = DB_KEY_PREFIX_EVENT_LOG,
444);
445
446impl_db_lookup!(key = EventLogId, query_prefix = EventLogIdPrefixAll);
447
448impl_db_lookup!(key = EventLogId, query_prefix = EventLogIdPrefix);
449
450#[derive(
451    Copy,
452    Clone,
453    Debug,
454    Encodable,
455    Decodable,
456    Default,
457    PartialEq,
458    Eq,
459    PartialOrd,
460    Ord,
461    Serialize,
462    Deserialize,
463)]
464pub struct EventLogTrimableId(EventLogId);
465
466impl EventLogTrimableId {
467    fn next(&self) -> Self {
468        Self(self.0.next())
469    }
470
471    pub fn saturating_add(self, rhs: u64) -> Self {
472        Self(self.0.saturating_add(rhs))
473    }
474}
475
476impl From<u64> for EventLogTrimableId {
477    fn from(value: u64) -> Self {
478        Self(EventLogId(value))
479    }
480}
481
482#[derive(Clone, Debug, Encodable, Decodable)]
483pub struct EventLogTrimableIdPrefixAll;
484
485#[derive(Clone, Debug, Encodable, Decodable)]
486pub struct EventLogTrimableIdPrefix(EventLogId);
487
488impl_db_record!(
489    key = EventLogTrimableId,
490    value = EventLogEntry,
491    db_prefix = DB_KEY_PREFIX_EVENT_LOG_TRIMABLE,
492);
493
494impl_db_lookup!(
495    key = EventLogTrimableId,
496    query_prefix = EventLogTrimableIdPrefixAll
497);
498
499impl_db_lookup!(
500    key = EventLogTrimableId,
501    query_prefix = EventLogTrimableIdPrefix
502);
503
504#[apply(async_trait_maybe_send!)]
505pub trait DBTransactionEventLogExt {
506    #[allow(clippy::too_many_arguments)]
507    async fn log_event_raw(
508        &mut self,
509        log_ordering_wakeup_tx: watch::Sender<()>,
510        kind: EventKind,
511        module_kind: Option<ModuleKind>,
512        module_id: Option<ModuleInstanceId>,
513        payload: Vec<u8>,
514        persist: EventPersistence,
515    );
516
517    /// Log an event log event
518    ///
519    /// The event will start "unordered", but after it is committed an ordering
520    /// task will be notified to "order" it into a final ordered log.
521    async fn log_event<E>(
522        &mut self,
523        log_ordering_wakeup_tx: watch::Sender<()>,
524        module_id: Option<ModuleInstanceId>,
525        event: E,
526    ) where
527        E: Event + Send,
528    {
529        self.log_event_raw(
530            log_ordering_wakeup_tx,
531            E::KIND,
532            E::MODULE,
533            module_id,
534            serde_json::to_vec(&event).expect("Serialization can't fail"),
535            <E as Event>::PERSISTENCE,
536        )
537        .await;
538    }
539
540    /// Next [`EventLogId`] to use for new ordered events.
541    ///
542    /// Used by ordering task, though might be
543    /// useful to get the current count of events.
544    async fn get_next_event_log_id(&mut self) -> EventLogId;
545
546    /// Next [`EventLogTrimableId`] to use for new ordered trimable events
547    async fn get_next_event_log_trimable_id(&mut self) -> EventLogTrimableId;
548
549    /// Read a part of the event log.
550    async fn get_event_log(
551        &mut self,
552        pos: Option<EventLogId>,
553        limit: u64,
554    ) -> Vec<PersistedLogEntry>;
555
556    async fn get_event_log_trimable(
557        &mut self,
558        pos: Option<EventLogTrimableId>,
559        limit: u64,
560    ) -> Vec<PersistedLogEntry>;
561}
562
563#[apply(async_trait_maybe_send!)]
564impl<'tx, Cap> DBTransactionEventLogExt for DatabaseTransaction<'tx, Cap>
565where
566    Cap: Send,
567{
568    async fn log_event_raw(
569        &mut self,
570        log_ordering_wakeup_tx: watch::Sender<()>,
571        kind: EventKind,
572        module_kind: Option<ModuleKind>,
573        module_id: Option<ModuleInstanceId>,
574        payload: Vec<u8>,
575        persist: EventPersistence,
576    ) {
577        assert_eq!(
578            module_kind.is_some(),
579            module_id.is_some(),
580            "Events of modules must have module_id set"
581        );
582
583        let unordered_id = UnordedEventLogId::new();
584        trace!(target: LOG_CLIENT_EVENT_LOG, ?unordered_id, "New unordered event log event");
585
586        if self
587            .insert_entry(
588                &unordered_id,
589                &UnorderedEventLogEntry {
590                    flags: match persist {
591                        EventPersistence::Transient => 0,
592                        EventPersistence::Trimable => {
593                            UnorderedEventLogEntry::FLAG_PERSIST
594                                | UnorderedEventLogEntry::FLAG_TRIMABLE
595                        }
596                        EventPersistence::Persistent => UnorderedEventLogEntry::FLAG_PERSIST,
597                    },
598                    inner: EventLogEntry {
599                        kind,
600                        module: module_kind.map(|kind| EventLogModule {
601                            kind,
602                            id: module_id.expect("module_id exists for module events"),
603                        }),
604                        ts_usecs: unordered_id.ts_usecs,
605                        payload,
606                    },
607                },
608            )
609            .await
610            .is_some()
611        {
612            panic!("Trying to overwrite event in the client event log");
613        }
614        self.on_commit(move || {
615            log_ordering_wakeup_tx.send_replace(());
616        });
617    }
618
619    async fn get_next_event_log_id(&mut self) -> EventLogId {
620        self.find_by_prefix_sorted_descending(&EventLogIdPrefixAll)
621            .await
622            .next()
623            .await
624            .map(|(k, _v)| k.next())
625            .unwrap_or_default()
626    }
627
628    async fn get_next_event_log_trimable_id(&mut self) -> EventLogTrimableId {
629        EventLogTrimableId(
630            self.find_by_prefix_sorted_descending(&EventLogTrimableIdPrefixAll)
631                .await
632                .next()
633                .await
634                .map(|(k, _v)| k.0.next())
635                .unwrap_or_default(),
636        )
637    }
638
639    async fn get_event_log(
640        &mut self,
641        pos: Option<EventLogId>,
642        limit: u64,
643    ) -> Vec<PersistedLogEntry> {
644        let pos = pos.unwrap_or_default();
645        self.find_by_range(pos..pos.saturating_add(limit))
646            .await
647            .map(|(k, v)| PersistedLogEntry { id: k, inner: v })
648            .collect()
649            .await
650    }
651
652    async fn get_event_log_trimable(
653        &mut self,
654        pos: Option<EventLogTrimableId>,
655        limit: u64,
656    ) -> Vec<PersistedLogEntry> {
657        let pos = pos.unwrap_or_default();
658        self.find_by_range(pos..pos.saturating_add(limit))
659            .await
660            .map(|(k, v)| PersistedLogEntry { id: k.0, inner: v })
661            .collect()
662            .await
663    }
664}
665
666/// Trims old entries from the trimable event log
667async fn trim_trimable_log(db: &Database, current_time_usecs: u64) {
668    let mut dbtx = db.begin_transaction().await;
669
670    let current_trimable_id = dbtx.get_next_event_log_trimable_id().await;
671    let min_id_threshold = current_trimable_id
672        .0
673        .saturating_sub(TRIMABLE_EVENTLOG_MIN_ID_AGE);
674    let min_ts_threshold = current_time_usecs.saturating_sub(TRIMABLE_EVENTLOG_MIN_TS_AGE);
675
676    let entries_to_delete: Vec<_> = dbtx
677        .find_by_prefix(&EventLogTrimableIdPrefixAll)
678        .await
679        .take_while(|(id, entry)| {
680            let id_old_enough = id.0 <= min_id_threshold;
681            let ts_old_enough = entry.ts_usecs <= min_ts_threshold;
682
683            // Continue while both conditions are met
684            async move { id_old_enough && ts_old_enough }
685        })
686        .take(TRIMABLE_EVENTLOG_MAX_TRIMMED_EVENTS)
687        .map(|(id, _entry)| id)
688        .collect()
689        .await;
690
691    for id in &entries_to_delete {
692        dbtx.remove_entry(id).await;
693    }
694
695    dbtx.commit_tx().await;
696}
697
698/// How far before the newest unordered event already ordered the ordering task
699/// starts its next scan.
700///
701/// Every unordered event is deleted once ordered, and a key-value store keeps
702/// the deletion as a tombstone until compaction, so a scan of the whole
703/// unordered prefix walks every event ordered since then and its cost grows
704/// with the client's event volume. Unordered ids are wall-clock based and
705/// transactions commit in any order, so an event can only become visible after
706/// newer ones were ordered by as long as its transaction stayed open; the
707/// margin covers that, the periodic full scan below covers the rest.
708const UNORDERED_SCAN_MARGIN: Duration = Duration::from_secs(60);
709
710/// How often the ordering task scans the whole unordered prefix, so an event
711/// committed later than [`UNORDERED_SCAN_MARGIN`] after newer ones, or written
712/// across a backwards clock step, is still ordered within this bound.
713const UNORDERED_FULL_SCAN_INTERVAL: Duration = Duration::from_secs(60);
714
715/// The code that handles new unordered events and rewriters them fully ordered
716/// into the final event log.
717pub async fn run_event_log_ordering_task(
718    db: Database,
719    mut log_ordering_task_wakeup: watch::Receiver<()>,
720    log_event_added: watch::Sender<()>,
721    log_event_added_transient: broadcast::Sender<EventLogEntry>,
722) {
723    debug!(target: LOG_CLIENT_EVENT_LOG, "Event log ordering task started");
724
725    let current_time_usecs =
726        u64::try_from(fedimint_core::time::duration_since_epoch().as_micros()).unwrap_or(u64::MAX);
727    trim_trimable_log(&db, current_time_usecs).await;
728
729    let mut next_entry_id = db
730        .begin_transaction_nc()
731        .await
732        .get_next_event_log_id()
733        .await;
734    let mut next_entry_id_trimable = db
735        .begin_transaction_nc()
736        .await
737        .get_next_event_log_trimable_id()
738        .await;
739
740    let mut scan_from_usecs = 0;
741    let mut next_full_scan = Instant::now();
742
743    loop {
744        let mut dbtx = db.begin_transaction().await;
745
746        let unordered_events = if Instant::now() >= next_full_scan {
747            next_full_scan = Instant::now() + UNORDERED_FULL_SCAN_INTERVAL;
748
749            dbtx.find_by_prefix(&UnorderedEventLogIdPrefixAll)
750                .await
751                .collect::<Vec<_>>()
752                .await
753        } else {
754            let start = UnordedEventLogId {
755                ts_usecs: scan_from_usecs,
756                counter: 0,
757            };
758
759            let end = UnordedEventLogId {
760                ts_usecs: u64::MAX,
761                counter: u64::MAX,
762            };
763
764            dbtx.find_by_range(start..end)
765                .await
766                .collect::<Vec<_>>()
767                .await
768        };
769
770        if let Some(newest_usecs) = unordered_events.iter().map(|entry| entry.0.ts_usecs).max() {
771            let margin_usecs = u64::try_from(UNORDERED_SCAN_MARGIN.as_micros()).unwrap_or(u64::MAX);
772
773            scan_from_usecs = scan_from_usecs.max(newest_usecs.saturating_sub(margin_usecs));
774        }
775        trace!(target: LOG_CLIENT_EVENT_LOG, num=unordered_events.len(), "Fetched unordered events");
776
777        for (unordered_id, entry) in &unordered_events {
778            assert!(
779                dbtx.remove_entry(unordered_id).await.is_some(),
780                "Must never fail to remove entry"
781            );
782            if entry.persist() {
783                // Non-trimable events get persisted in both the default event log
784                // and trimable event log
785                if !entry.trimable() {
786                    assert!(
787                        dbtx.insert_entry(&next_entry_id, &entry.inner)
788                            .await
789                            .is_none(),
790                        "Must never overwrite existing event"
791                    );
792                    trace!(target: LOG_CLIENT_EVENT_LOG, ?unordered_id, id=?next_entry_id, "Ordered event log event");
793                    next_entry_id = next_entry_id.next();
794                }
795
796                // Trimable events get persisted only in trimable log
797                assert!(
798                    dbtx.insert_entry(&next_entry_id_trimable, &entry.inner)
799                        .await
800                        .is_none(),
801                    "Must never overwrite existing event"
802                );
803                trace!(target: LOG_CLIENT_EVENT_LOG, ?unordered_id, id=?next_entry_id, "Ordered event log event");
804                next_entry_id_trimable = next_entry_id_trimable.next();
805            } else {
806                // Transient events don't get persisted at all
807                trace!(target: LOG_CLIENT_EVENT_LOG, ?unordered_id, id=?next_entry_id, "Transient event log event");
808                dbtx.on_commit({
809                    let log_event_added_transient = log_event_added_transient.clone();
810                    let entry = entry.inner.clone();
811
812                    move || {
813                        // we ignore the no-subscribers
814                        let _ = log_event_added_transient.send(entry);
815                    }
816                });
817            }
818        }
819
820        // This thread is the only thread deleting already existing element of unordered
821        // log and inserting new elements into ordered log, so it should never
822        // fail to commit.
823        dbtx.commit_tx().await;
824        if !unordered_events.is_empty() {
825            log_event_added.send_replace(());
826        }
827
828        trace!(target: LOG_CLIENT_EVENT_LOG, "Event log ordering task waits for more events");
829
830        // Waking up for the periodic full scan even without new events keeps the
831        // bound on a late commit that a seeking scan skipped. The deadline is
832        // absolute so that notifications in between cannot postpone it.
833        if let Ok(Err(_)) = timeout(
834            next_full_scan.saturating_duration_since(Instant::now()),
835            log_ordering_task_wakeup.changed(),
836        )
837        .await
838        {
839            break;
840        }
841    }
842
843    debug!(target: LOG_CLIENT_EVENT_LOG, "Event log ordering task finished");
844}
845
846/// Persistent tracker of a position in the event log
847///
848/// During processing of event log the downstream consumer needs to
849/// keep track of which event were processed already. It needs to do it
850/// atomically and persist it so event in the presence of crashes no
851/// event is ever missed or processed twice.
852///
853/// This trait allows abstracting away where and how is such position stored,
854/// e.g. which key exactly is used, in what prefixed namespace etc.
855///
856/// ## Trimmable vs Non-Trimable log
857///
858/// See [`EventPersistence`]
859#[apply(async_trait_maybe_send!)]
860pub trait EventLogNonTrimableTracker {
861    // Store position in the event log
862    async fn store(
863        &mut self,
864        dbtx: &mut DatabaseTransaction<NonCommittable>,
865        pos: EventLogId,
866    ) -> Result<(), EventLogTrackerError>;
867
868    /// Load the last previous stored position (or None if never stored)
869    async fn load(
870        &mut self,
871        dbtx: &mut DatabaseTransaction<NonCommittable>,
872    ) -> Result<Option<EventLogId>, EventLogTrackerError>;
873}
874pub type DynEventLogTracker = Box<dyn EventLogNonTrimableTracker>;
875
876/// Like [`EventLogNonTrimableTracker`] but for trimable event log
877#[apply(async_trait_maybe_send!)]
878pub trait EventLogTrimableTracker {
879    // Store position in the event log
880    async fn store(
881        &mut self,
882        dbtx: &mut DatabaseTransaction<NonCommittable>,
883        pos: EventLogTrimableId,
884    ) -> Result<(), EventLogTrackerError>;
885
886    /// Load the last previous stored position (or None if never stored)
887    async fn load(
888        &mut self,
889        dbtx: &mut DatabaseTransaction<NonCommittable>,
890    ) -> Result<Option<EventLogTrimableId>, EventLogTrackerError>;
891}
892pub type DynEventLogTrimableTracker = Box<dyn EventLogTrimableTracker>;
893
894/// A failure of an event log tracker to load or store its position in the
895/// log.
896///
897/// Trackers are implemented by applications, so the causes are their own.
898/// This type carries them unchanged: its `Display` and its `source()` are the
899/// cause's.
900#[derive(Debug, Error)]
901#[error(transparent)]
902pub struct EventLogTrackerError(Box<dyn std::error::Error + Send + Sync>);
903
904impl EventLogTrackerError {
905    /// Wraps a failure of an event log tracker, which may be any error value
906    /// or a plain message.
907    pub fn new<E>(source: E) -> Self
908    where
909        E: Into<Box<dyn std::error::Error + Send + Sync>>,
910    {
911        Self(source.into())
912    }
913}
914
915/// A failure while handling entries from the event log.
916#[derive(Debug, Error)]
917#[non_exhaustive]
918pub enum EventHandlerError<E> {
919    /// The handler rejected an event.
920    #[error("The event handler failed")]
921    Handler(#[source] E),
922
923    /// The tracker could not load or store the position in the log.
924    #[error("The event log tracker failed")]
925    Tracker(#[source] Box<dyn std::error::Error + Send + Sync>),
926}
927
928/// Feeds every entry of the event log, past and future, to `call_fn`.
929///
930/// `tracker` remembers how far the log has been read so a restart resumes where
931/// it left off; the loop stops when `call_fn` fails or the client shuts down.
932pub async fn handle_events<F, R, E>(
933    db: Database,
934    mut tracker: DynEventLogTracker,
935    mut log_event_added: watch::Receiver<()>,
936    call_fn: F,
937) -> Result<(), EventHandlerError<E>>
938where
939    F: Fn(&mut DatabaseTransaction<NonCommittable>, EventLogEntry) -> R,
940    R: Future<Output = Result<(), E>>,
941    E: std::error::Error + 'static,
942{
943    let mut next_key: EventLogId = tracker
944        .load(&mut db.begin_transaction_nc().await)
945        .await
946        .map_err(|err| EventHandlerError::Tracker(err.into()))?
947        .unwrap_or_default();
948
949    trace!(target: LOG_CLIENT_EVENT_LOG, ?next_key, "Handling events");
950
951    loop {
952        let mut dbtx = db.begin_transaction().await;
953
954        match dbtx.get_value(&next_key).await {
955            Some(event) => {
956                (call_fn)(&mut dbtx.to_ref_nc(), event)
957                    .await
958                    .map_err(EventHandlerError::Handler)?;
959
960                next_key = next_key.next();
961
962                tracker
963                    .store(&mut dbtx.to_ref_nc(), next_key)
964                    .await
965                    .map_err(|err| EventHandlerError::Tracker(err.into()))?;
966
967                dbtx.commit_tx().await;
968            }
969            _ => {
970                if log_event_added.changed().await.is_err() {
971                    break Ok(());
972                }
973            }
974        }
975    }
976}
977
978/// Like [`handle_events`], for the trimable part of the log: entries are handed
979/// to `call_fn` and the tracker's position drives when they can be trimmed.
980pub async fn handle_trimable_events<F, R, E>(
981    db: Database,
982    mut tracker: DynEventLogTrimableTracker,
983    mut log_event_added: watch::Receiver<()>,
984    call_fn: F,
985) -> Result<(), EventHandlerError<E>>
986where
987    F: Fn(&mut DatabaseTransaction<NonCommittable>, EventLogEntry) -> R,
988    R: Future<Output = Result<(), E>>,
989    E: std::error::Error + 'static,
990{
991    let mut next_key: EventLogTrimableId = tracker
992        .load(&mut db.begin_transaction_nc().await)
993        .await
994        .map_err(|err| EventHandlerError::Tracker(err.into()))?
995        .unwrap_or_default();
996    trace!(target: LOG_CLIENT_EVENT_LOG, ?next_key, "Handling trimable events");
997
998    loop {
999        let mut dbtx = db.begin_transaction().await;
1000
1001        match dbtx.get_value(&next_key).await {
1002            Some(event) => {
1003                (call_fn)(&mut dbtx.to_ref_nc(), event)
1004                    .await
1005                    .map_err(EventHandlerError::Handler)?;
1006
1007                next_key = next_key.next();
1008                tracker
1009                    .store(&mut dbtx.to_ref_nc(), next_key)
1010                    .await
1011                    .map_err(|err| EventHandlerError::Tracker(err.into()))?;
1012
1013                dbtx.commit_tx().await;
1014            }
1015            _ => {
1016                if log_event_added.changed().await.is_err() {
1017                    break Ok(());
1018                }
1019            }
1020        }
1021    }
1022}
1023
1024/// Filters the `PersistedLogEntries` by the `EventKind` and
1025/// `ModuleKind`.
1026pub fn filter_events_by_kind<'a, I>(
1027    all_events: I,
1028    module_kind: ModuleKind,
1029    event_kind: EventKind,
1030) -> impl Iterator<Item = &'a PersistedLogEntry> + 'a
1031where
1032    I: IntoIterator<Item = &'a PersistedLogEntry> + 'a,
1033{
1034    all_events.into_iter().filter(move |e| {
1035        if let Some(module) = &e.inner.module {
1036            e.inner.kind == event_kind && module.kind == module_kind
1037        } else {
1038            false
1039        }
1040    })
1041}
1042
1043/// Joins two sets of events on a predicate.
1044///
1045/// This function computes a "nested loop join" by first computing the cross
1046/// product of the start event vector and the success/failure event vectors. The
1047/// resulting cartesian product is then filtered according to the join predicate
1048/// supplied in the parameters.
1049///
1050/// This function is intended for small data sets. If the data set relations
1051/// grow, this function should implement a different join algorithm or be moved
1052/// out of the gateway.
1053pub fn join_events<'a, L, R, Res>(
1054    events_l: &'a [&PersistedLogEntry],
1055    events_r: &'a [&PersistedLogEntry],
1056    max_time_distance: Option<Duration>,
1057    predicate: impl Fn(L, R, Duration) -> Option<Res> + 'a,
1058) -> impl Iterator<Item = Res> + 'a
1059where
1060    L: Event,
1061    R: Event,
1062{
1063    events_l
1064        .iter()
1065        .cartesian_product(events_r)
1066        .filter_map(move |(l, r)| {
1067            if L::MODULE.as_ref() == l.as_raw().module_kind()
1068                && L::KIND == l.as_raw().kind
1069                && R::MODULE.as_ref() == r.as_raw().module_kind()
1070                && R::KIND == r.as_raw().kind
1071                && let Some(latency_usecs) = r.inner.ts_usecs.checked_sub(l.inner.ts_usecs)
1072                && max_time_distance.is_none_or(|max| u128::from(latency_usecs) <= max.as_millis())
1073                && let Some(l) = l.as_raw().to_event()
1074                && let Some(r) = r.as_raw().to_event()
1075            {
1076                predicate(l, r, Duration::from_millis(latency_usecs))
1077            } else {
1078                None
1079            }
1080        })
1081}
1082
1083/// Helper struct for storing computed data about outgoing and incoming
1084/// payments.
1085#[derive(Debug, Default)]
1086pub struct StructuredPaymentEvents {
1087    pub latencies_usecs: Vec<u64>,
1088    pub fees: Vec<Amount>,
1089    pub latencies_failure: Vec<u64>,
1090}
1091
1092impl StructuredPaymentEvents {
1093    pub fn new(
1094        success_stats: &[(u64, Amount)],
1095        failure_stats: Vec<u64>,
1096    ) -> StructuredPaymentEvents {
1097        let mut events = StructuredPaymentEvents {
1098            latencies_usecs: success_stats.iter().map(|(l, _)| *l).collect(),
1099            fees: success_stats.iter().map(|(_, f)| *f).collect(),
1100            latencies_failure: failure_stats,
1101        };
1102        events.sort();
1103        events
1104    }
1105
1106    /// Combines this `StructuredPaymentEvents` with the `other`
1107    /// `StructuredPaymentEvents` by appending all of the internal vectors.
1108    pub fn combine(&mut self, other: &mut StructuredPaymentEvents) {
1109        self.latencies_usecs.append(&mut other.latencies_usecs);
1110        self.fees.append(&mut other.fees);
1111        self.latencies_failure.append(&mut other.latencies_failure);
1112        self.sort();
1113    }
1114
1115    /// Sorts this `StructuredPaymentEvents` by sorting all of the internal
1116    /// vectors.
1117    fn sort(&mut self) {
1118        self.latencies_usecs.sort_unstable();
1119        self.fees.sort_unstable();
1120        self.latencies_failure.sort_unstable();
1121    }
1122}
1123
1124#[cfg(test)]
1125mod tests;