solana_runtime/
secondary_index.rs

1use {
2    dashmap::{mapref::entry::Entry::Occupied, DashMap},
3    log::*,
4    solana_sdk::{pubkey::Pubkey, timing::AtomicInterval},
5    std::{
6        collections::HashSet,
7        fmt::Debug,
8        sync::{
9            atomic::{AtomicU64, Ordering},
10            RwLock,
11        },
12    },
13};
14
15// The only cases where an inner key should map to a different outer key is
16// if the key had different account data for the indexed key across different
17// slots. As this is rare, it should be ok to use a Vec here over a HashSet, even
18// though we are running some key existence checks.
19pub type SecondaryReverseIndexEntry = RwLock<Vec<Pubkey>>;
20
21pub trait SecondaryIndexEntry: Debug {
22    fn insert_if_not_exists(&self, key: &Pubkey, inner_keys_count: &AtomicU64);
23    // Removes a value from the set. Returns whether the value was present in the set.
24    fn remove_inner_key(&self, key: &Pubkey) -> bool;
25    fn is_empty(&self) -> bool;
26    fn keys(&self) -> Vec<Pubkey>;
27    fn len(&self) -> usize;
28}
29
30#[derive(Debug, Default)]
31pub struct SecondaryIndexStats {
32    last_report: AtomicInterval,
33    num_inner_keys: AtomicU64,
34}
35
36#[derive(Debug, Default)]
37pub struct DashMapSecondaryIndexEntry {
38    account_keys: DashMap<Pubkey, ()>,
39}
40
41impl SecondaryIndexEntry for DashMapSecondaryIndexEntry {
42    fn insert_if_not_exists(&self, key: &Pubkey, inner_keys_count: &AtomicU64) {
43        if self.account_keys.get(key).is_none() {
44            self.account_keys.entry(*key).or_insert_with(|| {
45                inner_keys_count.fetch_add(1, Ordering::Relaxed);
46            });
47        }
48    }
49
50    fn remove_inner_key(&self, key: &Pubkey) -> bool {
51        self.account_keys.remove(key).is_some()
52    }
53
54    fn is_empty(&self) -> bool {
55        self.account_keys.is_empty()
56    }
57
58    fn keys(&self) -> Vec<Pubkey> {
59        self.account_keys
60            .iter()
61            .map(|entry_ref| *entry_ref.key())
62            .collect()
63    }
64
65    fn len(&self) -> usize {
66        self.account_keys.len()
67    }
68}
69
70#[derive(Debug, Default)]
71pub struct RwLockSecondaryIndexEntry {
72    account_keys: RwLock<HashSet<Pubkey>>,
73}
74
75impl SecondaryIndexEntry for RwLockSecondaryIndexEntry {
76    fn insert_if_not_exists(&self, key: &Pubkey, inner_keys_count: &AtomicU64) {
77        let exists = self.account_keys.read().unwrap().contains(key);
78        if !exists {
79            let mut w_account_keys = self.account_keys.write().unwrap();
80            w_account_keys.insert(*key);
81            inner_keys_count.fetch_add(1, Ordering::Relaxed);
82        };
83    }
84
85    fn remove_inner_key(&self, key: &Pubkey) -> bool {
86        self.account_keys.write().unwrap().remove(key)
87    }
88
89    fn is_empty(&self) -> bool {
90        self.account_keys.read().unwrap().is_empty()
91    }
92
93    fn keys(&self) -> Vec<Pubkey> {
94        self.account_keys.read().unwrap().iter().cloned().collect()
95    }
96
97    fn len(&self) -> usize {
98        self.account_keys.read().unwrap().len()
99    }
100}
101
102#[derive(Debug, Default)]
103pub struct SecondaryIndex<SecondaryIndexEntryType: SecondaryIndexEntry + Default + Sync + Send> {
104    metrics_name: &'static str,
105    // Map from index keys to index values
106    pub index: DashMap<Pubkey, SecondaryIndexEntryType>,
107    pub reverse_index: DashMap<Pubkey, SecondaryReverseIndexEntry>,
108    stats: SecondaryIndexStats,
109}
110
111impl<SecondaryIndexEntryType: SecondaryIndexEntry + Default + Sync + Send>
112    SecondaryIndex<SecondaryIndexEntryType>
113{
114    pub fn new(metrics_name: &'static str) -> Self {
115        Self {
116            metrics_name,
117            ..Self::default()
118        }
119    }
120
121    pub fn insert(&self, key: &Pubkey, inner_key: &Pubkey) {
122        {
123            let pubkeys_map = self
124                .index
125                .get(key)
126                .unwrap_or_else(|| self.index.entry(*key).or_default().downgrade());
127
128            pubkeys_map.insert_if_not_exists(inner_key, &self.stats.num_inner_keys);
129        }
130
131        {
132            let outer_keys = self.reverse_index.get(inner_key).unwrap_or_else(|| {
133                self.reverse_index
134                    .entry(*inner_key)
135                    .or_insert(RwLock::new(Vec::with_capacity(1)))
136                    .downgrade()
137            });
138
139            let should_insert = !outer_keys.read().unwrap().contains(key);
140            if should_insert {
141                let mut w_outer_keys = outer_keys.write().unwrap();
142                if !w_outer_keys.contains(key) {
143                    w_outer_keys.push(*key);
144                }
145            }
146        }
147
148        if self.stats.last_report.should_update(1000) {
149            datapoint_info!(
150                self.metrics_name,
151                ("num_secondary_keys", self.index.len() as i64, i64),
152                (
153                    "num_inner_keys",
154                    self.stats.num_inner_keys.load(Ordering::Relaxed) as i64,
155                    i64
156                ),
157                (
158                    "num_reverse_index_keys",
159                    self.reverse_index.len() as i64,
160                    i64
161                ),
162            );
163        }
164    }
165
166    // Only safe to call from `remove_by_inner_key()` due to asserts
167    fn remove_index_entries(&self, outer_key: &Pubkey, removed_inner_key: &Pubkey) {
168        let is_outer_key_empty = {
169            let inner_key_map = self
170                .index
171                .get_mut(outer_key)
172                .expect("If we're removing a key, then it must have an entry in the map");
173            // If we deleted a pubkey from the reverse_index, then the corresponding entry
174            // better exist in this index as well or the two indexes are out of sync!
175            assert!(inner_key_map.value().remove_inner_key(removed_inner_key));
176            inner_key_map.is_empty()
177        };
178
179        // Delete the `key` if the set of inner keys is empty
180        if is_outer_key_empty {
181            // Other threads may have interleaved writes to this `key`,
182            // so double-check again for its emptiness
183            if let Occupied(key_entry) = self.index.entry(*outer_key) {
184                if key_entry.get().is_empty() {
185                    key_entry.remove();
186                }
187            }
188        }
189    }
190
191    pub fn remove_by_inner_key(&self, inner_key: &Pubkey) {
192        // Save off which keys in `self.index` had slots removed so we can remove them
193        // after we purge the reverse index
194        let mut removed_outer_keys: HashSet<Pubkey> = HashSet::new();
195
196        // Check if the entry for `inner_key` in the reverse index is empty
197        // and can be removed
198        if let Some((_, outer_keys_set)) = self.reverse_index.remove(inner_key) {
199            for removed_outer_key in outer_keys_set.into_inner().unwrap().into_iter() {
200                removed_outer_keys.insert(removed_outer_key);
201            }
202        }
203
204        // Remove this value from those keys
205        for outer_key in &removed_outer_keys {
206            self.remove_index_entries(outer_key, inner_key);
207        }
208
209        // Safe to `fetch_sub()` here because a dead key cannot be removed more than once,
210        // and the `num_inner_keys` must have been incremented by exactly removed_outer_keys.len()
211        // in previous unique insertions of `inner_key` into `self.index` for each key
212        // in `removed_outer_keys`
213        self.stats
214            .num_inner_keys
215            .fetch_sub(removed_outer_keys.len() as u64, Ordering::Relaxed);
216    }
217
218    pub fn get(&self, key: &Pubkey) -> Vec<Pubkey> {
219        if let Some(inner_keys_map) = self.index.get(key) {
220            inner_keys_map.keys()
221        } else {
222            vec![]
223        }
224    }
225
226    /// log top 20 (owner, # accounts) in descending order of # accounts
227    pub fn log_contents(&self) {
228        let mut entries = self
229            .index
230            .iter()
231            .map(|entry| (entry.value().len(), *entry.key()))
232            .collect::<Vec<_>>();
233        entries.sort_unstable();
234        entries
235            .iter()
236            .rev()
237            .take(20)
238            .for_each(|(v, k)| info!("owner: {}, accounts: {}", k, v));
239    }
240}