solana_accounts_db/accounts_index/
secondary.rs

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