File size: 10,930 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
use std::{
    fs::File,
    hash::BuildHasherDefault,
    io::{BufReader, Seek},
    ops::Deref,
    path::{Path, PathBuf},
    sync::{Arc, OnceLock},
};

use anyhow::{Context, Result, bail};
use byteorder::{BE, ReadBytesExt};
use either::Either;
use memmap2::{Mmap, MmapOptions};
use quick_cache::sync::GuardResult;
use rustc_hash::FxHasher;

use crate::{
    QueryKey,
    static_sorted_file::{BlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData},
};

#[derive(Clone, Default)]
pub struct AqmfWeighter;

impl quick_cache::Weighter<u32, Arc<qfilter::Filter>> for AqmfWeighter {
    fn weight(&self, _key: &u32, filter: &Arc<qfilter::Filter>) -> u64 {
        filter.capacity() + 1
    }
}

pub type AqmfCache =
    quick_cache::sync::Cache<u32, Arc<qfilter::Filter>, AqmfWeighter, BuildHasherDefault<FxHasher>>;

pub struct MetaEntry {
    /// The metadata for the static sorted file.
    sst_data: StaticSortedFileMetaData,
    /// The key family of the SST file.
    family: u32,
    /// The minimum hash value of the keys in the SST file.
    min_hash: u64,
    /// The maximum hash value of the keys in the SST file.
    max_hash: u64,
    /// The size of the SST file in bytes.
    size: u64,
    /// The offset of the start of the AQMF data in the meta file relative to the end of the
    /// header.
    start_of_aqmf_data_offset: u32,
    /// The offset of the end of the AQMF data in the the meta file relative to the end of the
    /// header.
    end_of_aqmf_data_offset: u32,
    /// The AQMF filter of this file. This is only used if the range is very large. Smaller ranges
    /// use the AQMF cache instead.
    aqmf: OnceLock<qfilter::Filter>,
    /// The static sorted file that is lazily loaded
    sst: OnceLock<StaticSortedFile>,
}

impl MetaEntry {
    pub fn sequence_number(&self) -> u32 {
        self.sst_data.sequence_number
    }

    pub fn size(&self) -> u64 {
        self.size
    }

    pub fn aqmf_size(&self) -> u32 {
        self.end_of_aqmf_data_offset - self.start_of_aqmf_data_offset
    }

    pub fn raw_aqmf<'l>(&self, aqmf_data: &'l [u8]) -> &'l [u8] {
        aqmf_data
            .get(self.start_of_aqmf_data_offset as usize..self.end_of_aqmf_data_offset as usize)
            .expect("AQMF data out of bounds")
    }

    pub fn deserialize_aqmf(&self, meta: &MetaFile) -> Result<qfilter::Filter> {
        let aqmf = self.raw_aqmf(meta.aqmf_data());
        pot::from_slice(aqmf).with_context(|| {
            format!(
                "Failed to deserialize AQMF from {:08}.meta for {:08}.sst",
                meta.sequence_number,
                self.sequence_number()
            )
        })
    }

    pub fn aqmf(
        &self,
        meta: &MetaFile,
        aqmf_cache: &AqmfCache,
    ) -> Result<impl Deref<Target = qfilter::Filter>> {
        let use_aqmf_cache = self.max_hash - self.min_hash < 1 << 60;
        Ok(if use_aqmf_cache {
            let aqmf = match aqmf_cache.get_value_or_guard(&self.sequence_number(), None) {
                GuardResult::Value(aqmf) => aqmf,
                GuardResult::Guard(guard) => {
                    let aqmf = self.deserialize_aqmf(meta)?;
                    let aqmf: Arc<qfilter::Filter> = Arc::new(aqmf);
                    let _ = guard.insert(aqmf.clone());
                    aqmf
                }
                GuardResult::Timeout => unreachable!(),
            };
            Either::Left(aqmf)
        } else {
            let aqmf = self.aqmf.get_or_try_init(|| {
                let aqmf = self.deserialize_aqmf(meta)?;
                anyhow::Ok(aqmf)
            })?;
            Either::Right(aqmf)
        })
    }

    pub fn sst(&self, meta: &MetaFile) -> Result<&StaticSortedFile> {
        self.sst.get_or_try_init(|| {
            StaticSortedFile::open(&meta.db_path, self.sst_data.clone()).with_context(|| {
                format!(
                    "Unable to open static sorted file referenced from {:08}.meta",
                    meta.sequence_number()
                )
            })
        })
    }

    /// Returns the key family and hash range of this file.
    pub fn range(&self) -> StaticSortedFileRange {
        StaticSortedFileRange {
            family: self.family,
            min_hash: self.min_hash,
            max_hash: self.max_hash,
        }
    }

    pub fn min_hash(&self) -> u64 {
        self.min_hash
    }

    pub fn max_hash(&self) -> u64 {
        self.max_hash
    }

    pub fn key_compression_dictionary_length(&self) -> u16 {
        self.sst_data.key_compression_dictionary_length
    }

    pub fn value_compression_dictionary_length(&self) -> u16 {
        self.sst_data.value_compression_dictionary_length
    }

    pub fn block_count(&self) -> u16 {
        self.sst_data.block_count
    }
}

/// The result of a lookup operation.
pub enum MetaLookupResult {
    /// The key was not found because it is from a different key family.
    FamilyMiss,
    /// The key was not found because it is out of the range of this SST file. But it was the
    /// correct key family.
    RangeMiss,
    /// The key was not found because it was not in the AQMF filter. But it was in the range.
    QuickFilterMiss,
    /// The key was looked up in the SST file. It was in the AQMF filter.
    SstLookup(SstLookupResult),
}

/// The key family and hash range of an SST file.
#[derive(Clone, Copy)]
pub struct StaticSortedFileRange {
    pub family: u32,
    pub min_hash: u64,
    pub max_hash: u64,
}

pub struct MetaFile {
    /// The database path
    db_path: PathBuf,
    /// The sequence number of this file.
    sequence_number: u32,
    /// The key family of the SST files in this meta file.
    family: u32,
    /// The entries of the file.
    entries: Vec<MetaEntry>,
    /// The entries that have been marked as obsolete.
    obsolete_entries: Vec<u32>,
    /// The obsolete SST files.
    obsolete_sst_files: Vec<u32>,
    /// The memory mapped file.
    mmap: Mmap,
}

impl MetaFile {
    /// Opens a meta file at the given path. This memory maps the file, but does not read it yet.
    /// It's lazy read on demand.
    pub fn open(db_path: &Path, sequence_number: u32) -> Result<Self> {
        let filename = format!("{sequence_number:08}.meta");
        let path = db_path.join(&filename);
        Self::open_internal(db_path.to_path_buf(), sequence_number, &path)
            .with_context(|| format!("Unable to open meta file {filename}"))
    }

    fn open_internal(db_path: PathBuf, sequence_number: u32, path: &Path) -> Result<Self> {
        let mut file = BufReader::new(File::open(path)?);
        let magic = file.read_u32::<BE>()?;
        if magic != 0xFE4ADA4A {
            bail!("Invalid magic number");
        }
        let family = file.read_u32::<BE>()?;
        let obsolete_count = file.read_u32::<BE>()?;
        let mut obsolete_sst_files = Vec::with_capacity(obsolete_count as usize);
        for _ in 0..obsolete_count {
            let obsolete_sst = file.read_u32::<BE>()?;
            obsolete_sst_files.push(obsolete_sst);
        }
        let count = file.read_u32::<BE>()?;
        let mut entries = Vec::with_capacity(count as usize);
        let mut start_of_aqmf_data_offset = 0;
        for _ in 0..count {
            let entry = MetaEntry {
                sst_data: StaticSortedFileMetaData {
                    sequence_number: file.read_u32::<BE>()?,
                    key_compression_dictionary_length: file.read_u16::<BE>()?,
                    value_compression_dictionary_length: file.read_u16::<BE>()?,
                    block_count: file.read_u16::<BE>()?,
                },
                family,
                min_hash: file.read_u64::<BE>()?,
                max_hash: file.read_u64::<BE>()?,
                size: file.read_u64::<BE>()?,
                start_of_aqmf_data_offset,
                end_of_aqmf_data_offset: file.read_u32::<BE>()?,
                aqmf: OnceLock::new(),
                sst: OnceLock::new(),
            };
            start_of_aqmf_data_offset = entry.end_of_aqmf_data_offset;
            entries.push(entry);
        }
        let offset = file.stream_position()?;
        let file = file.into_inner();
        let mut options = MmapOptions::new();
        options.offset(offset);
        let mmap = unsafe { options.map(&file)? };
        #[cfg(unix)]
        mmap.advise(memmap2::Advice::Random)?;
        let file = Self {
            db_path,
            sequence_number,
            family,
            entries,
            obsolete_entries: Vec::new(),
            obsolete_sst_files,
            mmap,
        };
        Ok(file)
    }

    pub fn sequence_number(&self) -> u32 {
        self.sequence_number
    }

    pub fn family(&self) -> u32 {
        self.family
    }

    pub fn entries(&self) -> &[MetaEntry] {
        &self.entries
    }

    pub fn entry(&self, index: u32) -> &MetaEntry {
        let index = index as usize;
        &self.entries[index]
    }

    pub fn aqmf_data(&self) -> &[u8] {
        &self.mmap
    }

    pub fn retain_entries(&mut self, mut predicate: impl FnMut(u32) -> bool) -> bool {
        let old_len = self.entries.len();
        self.entries.retain(|entry| {
            if predicate(entry.sst_data.sequence_number) {
                true
            } else {
                self.obsolete_entries.push(entry.sst_data.sequence_number);
                false
            }
        });
        old_len != self.entries.len()
    }

    pub fn obsolete_entries(&self) -> &[u32] {
        &self.obsolete_entries
    }

    pub fn has_active_entries(&self) -> bool {
        !self.entries.is_empty()
    }

    pub fn obsolete_sst_files(&self) -> &[u32] {
        &self.obsolete_sst_files
    }

    pub fn lookup<K: QueryKey>(
        &self,
        key_family: u32,
        key_hash: u64,
        key: &K,
        aqmf_cache: &AqmfCache,
        key_block_cache: &BlockCache,
        value_block_cache: &BlockCache,
    ) -> Result<MetaLookupResult> {
        if key_family != self.family {
            return Ok(MetaLookupResult::FamilyMiss);
        }
        let mut miss_result = MetaLookupResult::RangeMiss;
        for entry in self.entries.iter().rev() {
            if key_hash < entry.min_hash || key_hash > entry.max_hash {
                continue;
            }
            {
                let aqmf = entry.aqmf(self, aqmf_cache)?;
                if !aqmf.contains_fingerprint(key_hash) {
                    miss_result = MetaLookupResult::QuickFilterMiss;
                    continue;
                }
            }
            let result =
                entry
                    .sst(self)?
                    .lookup(key_hash, key, key_block_cache, value_block_cache)?;
            if !matches!(result, SstLookupResult::NotFound) {
                return Ok(MetaLookupResult::SstLookup(result));
            }
        }
        Ok(miss_result)
    }
}