1#![allow(clippy::needless_lifetimes)]
2
3use 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
36pub 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
48const TRIMABLE_EVENTLOG_MIN_ID_AGE: u64 = 10_000;
50const TRIMABLE_EVENTLOG_MIN_TS_AGE: u64 = 14 * 24 * 60 * 60 * 1_000_000;
52const TRIMABLE_EVENTLOG_MAX_TRIMMED_EVENTS: usize = 100_000;
54
55#[derive(Clone, Copy)]
80pub enum EventPersistence {
81 Transient,
83 Trimable,
85 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
96static UNORDEREDED_EVENT_LOG_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
99
100#[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 .unwrap_or(u64::MAX),
118 counter: UNORDEREDED_EVENT_LOG_ID_COUNTER.fetch_add(1, Ordering::Relaxed),
119 }
120 }
121}
122
123#[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 pub kind: EventKind,
242
243 pub module: Option<EventLogModule>,
251
252 pub ts_usecs: u64,
254
255 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 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#[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 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 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 async fn get_next_event_log_id(&mut self) -> EventLogId;
545
546 async fn get_next_event_log_trimable_id(&mut self) -> EventLogTrimableId;
548
549 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
666async 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 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
698const UNORDERED_SCAN_MARGIN: Duration = Duration::from_secs(60);
709
710const UNORDERED_FULL_SCAN_INTERVAL: Duration = Duration::from_secs(60);
714
715pub 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 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 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 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 let _ = log_event_added_transient.send(entry);
815 }
816 });
817 }
818 }
819
820 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 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#[apply(async_trait_maybe_send!)]
860pub trait EventLogNonTrimableTracker {
861 async fn store(
863 &mut self,
864 dbtx: &mut DatabaseTransaction<NonCommittable>,
865 pos: EventLogId,
866 ) -> Result<(), EventLogTrackerError>;
867
868 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#[apply(async_trait_maybe_send!)]
878pub trait EventLogTrimableTracker {
879 async fn store(
881 &mut self,
882 dbtx: &mut DatabaseTransaction<NonCommittable>,
883 pos: EventLogTrimableId,
884 ) -> Result<(), EventLogTrackerError>;
885
886 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#[derive(Debug, Error)]
901#[error(transparent)]
902pub struct EventLogTrackerError(Box<dyn std::error::Error + Send + Sync>);
903
904impl EventLogTrackerError {
905 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#[derive(Debug, Error)]
917#[non_exhaustive]
918pub enum EventHandlerError<E> {
919 #[error("The event handler failed")]
921 Handler(#[source] E),
922
923 #[error("The event log tracker failed")]
925 Tracker(#[source] Box<dyn std::error::Error + Send + Sync>),
926}
927
928pub 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
978pub 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
1024pub 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
1043pub 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#[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 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 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;