massa_event_cache/
controller.rs

1// std
2use std::collections::{BTreeSet, VecDeque};
3use std::sync::Arc;
4// third-party
5use parking_lot::{Condvar, Mutex, RwLock};
6// internal
7use crate::event_cache::EventCache;
8use massa_models::execution::EventFilter;
9use massa_models::output_event::SCOutputEvent;
10
11/// structure used to communicate with controller
12#[derive(Debug, Default)]
13pub(crate) struct EventCacheWriterInputData {
14    /// set stop to true to stop the thread
15    pub stop: bool,
16    pub(crate) events: VecDeque<SCOutputEvent>,
17}
18
19impl EventCacheWriterInputData {
20    pub fn new() -> Self {
21        Self {
22            stop: Default::default(),
23            events: Default::default(),
24        }
25    }
26}
27
28/// interface that communicates with the worker thread
29#[cfg_attr(feature = "test-exports", mockall_wrap::wrap, mockall::automock)]
30pub trait EventCacheController: Send + Sync {
31    fn save_events(&self, events: VecDeque<SCOutputEvent>);
32
33    /// Events matching `filter`, from the queue of events not written yet and from the cache.
34    ///
35    /// Fails if the cache query would scan more than its configured number of index keys.
36    fn get_filtered_sc_output_events(
37        &self,
38        filter: &EventFilter,
39    ) -> Result<Vec<SCOutputEvent>, String>;
40}
41
42#[derive(Clone)]
43/// implementation of the event cache controller
44pub struct EventCacheControllerImpl {
45    /// input data to process in the VM loop
46    /// with a wake-up condition variable that needs to be triggered when the data changes
47    pub(crate) input_data: Arc<(Condvar, Mutex<EventCacheWriterInputData>)>,
48    /// Event cache
49    pub(crate) cache: Arc<RwLock<EventCache>>,
50}
51
52impl EventCacheController for EventCacheControllerImpl {
53    fn save_events(&self, events: VecDeque<SCOutputEvent>) {
54        // lock input data
55        let mut input_data = self.input_data.1.lock();
56        input_data.events.extend(events);
57        massa_metrics::set_event_cache_vec_len(input_data.events.len());
58        // Wake up the condvar in EventCacheWriterThread waiting for events
59        self.input_data.0.notify_all();
60    }
61
62    fn get_filtered_sc_output_events(
63        &self,
64        filter: &EventFilter,
65    ) -> Result<Vec<SCOutputEvent>, String> {
66        let mut res_0 = {
67            // Read from new events first
68            let lock_0 = self.input_data.1.lock();
69            #[allow(clippy::unnecessary_filter_map)]
70            let it = lock_0.events.iter().filter_map(|event| {
71                if let Some(start) = filter.start {
72                    if event.context.slot < start {
73                        return None;
74                    }
75                }
76                if let Some(end) = filter.end {
77                    if event.context.slot >= end {
78                        return None;
79                    }
80                }
81                if let Some(is_final) = filter.is_final {
82                    if event.context.is_final != is_final {
83                        return None;
84                    }
85                }
86                if let Some(is_error) = filter.is_error {
87                    if event.context.is_error != is_error {
88                        return None;
89                    }
90                }
91                match (
92                    filter.original_caller_address,
93                    event.context.call_stack.front(),
94                ) {
95                    (Some(addr1), Some(addr2)) if addr1 != *addr2 => return None,
96                    (Some(_), None) => return None,
97                    _ => (),
98                }
99                match (filter.emitter_address, event.context.call_stack.back()) {
100                    (Some(addr1), Some(addr2)) if addr1 != *addr2 => return None,
101                    (Some(_), None) => return None,
102                    _ => (),
103                }
104                match (
105                    filter.original_operation_id,
106                    event.context.origin_operation_id,
107                ) {
108                    (Some(addr1), Some(addr2)) if addr1 != addr2 => return None,
109                    (Some(_), None) => return None,
110                    _ => (),
111                }
112                Some(event)
113            });
114
115            let res_0: BTreeSet<SCOutputEvent> = it.cloned().collect();
116            // Drop the lock on the queue as soon as possible to avoid deadlocks
117            drop(lock_0);
118            res_0
119        };
120
121        let res_1 = {
122            // Read from db (on disk) events
123            let lock = self.cache.read();
124            let res_1 = lock.get_filtered_sc_output_events(filter);
125            // Drop the lock on the event cache db asap
126            drop(lock);
127            res_1?.1
128        };
129
130        // Merge results
131        let res_1: BTreeSet<SCOutputEvent> = BTreeSet::from_iter(res_1);
132        res_0.extend(res_1);
133        Ok(Vec::from_iter(res_0))
134    }
135}