1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::rpc::eth::filter::ActorEventBlock;
use crate::rpc::eth::filter::ParsedFilter;
use crate::rpc::eth::{filter::Filter, FilterID};
use crate::rpc::Arc;
use crate::shim::address::Address;
use crate::shim::clock::ChainEpoch;
use ahash::AHashMap as HashMap;
use anyhow::{Context, Result};
use cid::Cid;
use parking_lot::RwLock;
use std::any::Any;

#[allow(dead_code)]
#[derive(Debug, PartialEq)]
pub struct EventFilter {
    id: FilterID,
    min_height: ChainEpoch, // minimum epoch to apply filter
    max_height: ChainEpoch, // maximum epoch to apply filter
    tipset_cid: Cid,
    addresses: Vec<Address>, // list of actor addresses that are extpected to emit the event
    keys_with_codec: HashMap<String, Vec<ActorEventBlock>>, // map of key names to a list of alternate values that may match
    max_results: usize,                                     // maximum number of results to collect
}

impl Filter for EventFilter {
    fn id(&self) -> &FilterID {
        &self.id
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// The `EventFilterManager` structure maintains a set of filters, allowing new filters to be
/// installed or existing ones to be removed. It ensures that each filter is uniquely identifiable
/// by its ID and that a maximum number of results can be configured for each filter.
pub struct EventFilterManager {
    filters: RwLock<HashMap<FilterID, Arc<EventFilter>>>,
    max_filter_results: usize,
    // TODO(elmattic): https://github.com/ChainSafe/forest/issues/4740
    //pub event_index: Option<Arc<EventIndex>>,
}

impl EventFilterManager {
    pub fn new(max_filter_results: usize) -> Arc<Self> {
        Arc::new(Self {
            filters: RwLock::new(HashMap::new()),
            max_filter_results,
        })
    }

    pub fn install(&self, pf: ParsedFilter) -> Result<Arc<EventFilter>> {
        let id = FilterID::new().context("Failed to generate new FilterID")?;

        let filter = Arc::new(EventFilter {
            id: id.clone(),
            min_height: pf.min_height,
            max_height: pf.max_height,
            tipset_cid: pf.tipset_cid,
            addresses: pf.addresses,
            keys_with_codec: pf.keys,
            max_results: self.max_filter_results,
        });

        self.filters.write().insert(id, filter.clone());

        Ok(filter)
    }

    pub fn remove(&self, id: &FilterID) -> Option<Arc<EventFilter>> {
        let mut filters = self.filters.write();
        filters.remove(id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rpc::eth::filter::ParsedFilter;
    use crate::shim::address::Address;
    use crate::shim::clock::ChainEpoch;
    use cid::Cid;

    #[test]
    fn test_event_filter() {
        let max_filter_results = 10;
        let event_manager = EventFilterManager::new(max_filter_results);

        let parsed_filter = ParsedFilter {
            min_height: ChainEpoch::from(0),
            max_height: ChainEpoch::from(100),
            tipset_cid: Cid::default(),
            addresses: vec![Address::new_id(123)],
            keys: HashMap::new(),
        };
        // Test case 1: Install the EventFilter
        let filter = event_manager
            .install(parsed_filter)
            .expect("Failed to install EventFilter");

        // Verify that the filter has been added to the event manager
        let filter_id = filter.id().clone();
        {
            let filters = event_manager.filters.read();
            assert!(filters.contains_key(&filter_id));
        }

        // Test case 2: Remove the EventFilter
        let removed = event_manager.remove(&filter_id);
        assert_eq!(
            removed,
            Some(filter),
            "Filter should be successfully removed"
        );

        // Verify that the filter is no longer in the event manager
        {
            let filters = event_manager.filters.read();
            assert!(!filters.contains_key(&filter_id));
        }
    }
}