Skip to main content

geocoder_core/index/
store.rs

1use std::io::Read;
2use std::path::Path;
3
4use flate2::read::ZlibDecoder;
5use fst::Map;
6use memmap2::Mmap;
7use roaring::RoaringBitmap;
8
9use super::format::{HEADER_SIZE, MAGIC, Meta, SECTION_HEADER_SIZE, SectionKind, VERSION};
10use crate::doc::Document;
11use crate::error::GeocoderError;
12use crate::types::{DocId, TokenId};
13
14/// A read-only index, memory mapped. Only the FSTs are copied in memory;
15/// postings, bitmaps and documents are read in place on demand.
16///
17/// Reading never trusts the file: every offset is bounds checked and the
18/// FSTs' checksums verified, so a damaged or tampered index fails to open
19/// or yields empty lookups, never a panic. Whether the content is genuine
20/// is a matter of signatures (see `signed`), not of this type.
21pub struct Index {
22    mmap: Mmap,
23    ranges: Vec<(usize, usize)>,
24    pub meta: Meta,
25    token_fst: Map<Vec<u8>>,
26    ngram_fst: Map<Vec<u8>>,
27    geohash_fst: Map<Vec<u8>>,
28    filter_fst: Map<Vec<u8>>,
29}
30
31impl Index {
32    pub fn open(path: &Path) -> Result<Self, GeocoderError> {
33        let file = std::fs::File::open(path)?;
34        // SAFETY: the index file is written once and never modified in place.
35        let mmap = unsafe { Mmap::map(&file)? };
36        let data: &[u8] = &mmap;
37        if data.len() < HEADER_SIZE || &data[..8] != MAGIC {
38            return Err(GeocoderError::InvalidIndex("bad magic bytes"));
39        }
40        if u32::from_le_bytes(data[8..12].try_into().unwrap()) != VERSION {
41            return Err(GeocoderError::InvalidIndex(
42                "unsupported format version, rebuild the index",
43            ));
44        }
45        let count = u32::from_le_bytes(data[12..16].try_into().unwrap()) as usize;
46        let mut ranges = vec![(0usize, 0usize); SectionKind::ALL.len()];
47        let mut found = vec![false; SectionKind::ALL.len()];
48        for i in 0..count {
49            let at = HEADER_SIZE + i * SECTION_HEADER_SIZE;
50            let header = data
51                .get(at..at + SECTION_HEADER_SIZE)
52                .ok_or(GeocoderError::InvalidIndex("truncated"))?;
53            let Ok(kind) = SectionKind::try_from(header[0]) else {
54                continue;
55            };
56            let offset = u64::from_le_bytes(header[1..9].try_into().unwrap());
57            let length = u64::from_le_bytes(header[9..17].try_into().unwrap());
58            let end = offset
59                .checked_add(length)
60                .filter(|&end| end <= data.len() as u64)
61                .ok_or(GeocoderError::InvalidIndex("truncated"))?;
62            ranges[kind as usize] = (offset as usize, end as usize);
63            found[kind as usize] = true;
64        }
65        if found.iter().any(|f| !f) {
66            return Err(GeocoderError::InvalidIndex("missing section"));
67        }
68        let section = |kind: SectionKind| {
69            let (start, end) = ranges[kind as usize];
70            &data[start..end]
71        };
72        let meta: Meta = serde_json::from_slice(section(SectionKind::Meta))?;
73        // fst walks its nodes without bounds checks of its own (it panics on
74        // a malformed node): its checksum is verified first.
75        let fst = |kind: SectionKind| -> Result<Map<Vec<u8>>, GeocoderError> {
76            let map = Map::new(section(kind).to_vec())?;
77            map.as_fst().verify()?;
78            Ok(map)
79        };
80        let token_fst = fst(SectionKind::TokenFst)?;
81        let ngram_fst = fst(SectionKind::NgramFst)?;
82        let geohash_fst = fst(SectionKind::GeohashFst)?;
83        let filter_fst = fst(SectionKind::FilterFst)?;
84        Ok(Self {
85            mmap,
86            ranges,
87            meta,
88            token_fst,
89            ngram_fst,
90            geohash_fst,
91            filter_fst,
92        })
93    }
94
95    fn section(&self, kind: SectionKind) -> &[u8] {
96        let (start, end) = self.ranges[kind as usize];
97        &self.mmap[start..end]
98    }
99
100    /// Entry `i` of an offset table: `(start, end)`, with `start <= end`.
101    fn offset(&self, kind: SectionKind, i: usize) -> Option<(usize, usize)> {
102        let table = self.section(kind);
103        let at = i.checked_mul(8)?;
104        let start = u64::from_le_bytes(table.get(at..at.checked_add(8)?)?.try_into().ok()?);
105        let end = u64::from_le_bytes(table.get(at + 8..at.checked_add(16)?)?.try_into().ok()?);
106        (start <= end).then_some((usize::try_from(start).ok()?, usize::try_from(end).ok()?))
107    }
108
109    /// `section[start * width..end * width]`, empty when out of bounds.
110    fn slice(&self, kind: SectionKind, range: Option<(usize, usize)>, width: usize) -> &[u8] {
111        range
112            .and_then(|(start, end)| {
113                let (start, end) = (start.checked_mul(width)?, end.checked_mul(width)?);
114                self.section(kind).get(start..end)
115            })
116            .unwrap_or_default()
117    }
118
119    pub fn token_id(&self, token: &str) -> Option<TokenId> {
120        self.token_fst.get(token).map(|v| v as TokenId)
121    }
122
123    pub fn token_fst(&self) -> &Map<Vec<u8>> {
124        &self.token_fst
125    }
126
127    /// Number of documents holding the token (Redis `ZCARD`).
128    pub fn frequency(&self, token: TokenId) -> usize {
129        self.offset(SectionKind::PostingOffsets, token as usize)
130            .map(|(s, e)| e - s)
131            .unwrap_or(0)
132    }
133
134    /// Postings sorted by document.
135    pub fn postings(&self, token: TokenId) -> Postings<'_> {
136        let range = self.offset(SectionKind::PostingOffsets, token as usize);
137        Postings {
138            bytes: self.slice(SectionKind::PostingsByDoc, range, 8),
139        }
140    }
141
142    /// The first `limit` documents of a token, like `ZREVRANGE key 0 limit-1`.
143    pub fn top(&self, token: TokenId, limit: usize) -> impl Iterator<Item = DocId> + '_ {
144        let range = self.offset(SectionKind::PostingOffsets, token as usize);
145        self.slice(SectionKind::PostingsByScore, range, 4)
146            .as_chunks::<4>()
147            .0
148            .iter()
149            .take(limit)
150            .map(|c| u32::from_le_bytes(*c))
151    }
152
153    /// Tokens seen in at least one document along with `token`.
154    pub fn pairs(&self, token: TokenId) -> RoaringBitmap {
155        let range = self.offset(SectionKind::PairOffsets, token as usize);
156        bitmap(self.slice(SectionKind::PairBlobs, range, 1))
157    }
158
159    /// Tokens starting with `prefix` (and longer than it).
160    pub fn edge_ngram(&self, prefix: &str) -> RoaringBitmap {
161        self.keyed(
162            &self.ngram_fst,
163            prefix,
164            SectionKind::NgramOffsets,
165            SectionKind::NgramBlobs,
166        )
167    }
168
169    pub fn geohash(&self, cell: &str) -> RoaringBitmap {
170        self.keyed(
171            &self.geohash_fst,
172            cell,
173            SectionKind::GeohashOffsets,
174            SectionKind::GeohashBlobs,
175        )
176    }
177
178    /// Documents whose filter `key` has `value`.
179    pub fn filter(&self, key: &str, value: &str) -> RoaringBitmap {
180        let k = format!("{key}|{value}");
181        self.keyed(
182            &self.filter_fst,
183            &k,
184            SectionKind::FilterOffsets,
185            SectionKind::FilterBlobs,
186        )
187    }
188
189    fn keyed(
190        &self,
191        fst: &Map<Vec<u8>>,
192        key: &str,
193        offsets: SectionKind,
194        blobs: SectionKind,
195    ) -> RoaringBitmap {
196        let range = fst.get(key).and_then(|i| self.offset(offsets, i as usize));
197        bitmap(self.slice(blobs, range, 1))
198    }
199
200    pub fn document(&self, doc: DocId) -> Option<Document> {
201        let range = self.offset(SectionKind::DocOffsets, doc as usize)?;
202        let blob = self.slice(SectionKind::DocBlobs, Some(range), 1);
203        // Bounded: a zlib bomb would otherwise fill the memory.
204        let mut json = Vec::new();
205        ZlibDecoder::new(blob)
206            .take(MAX_DOCUMENT_BYTES + 1)
207            .read_to_end(&mut json)
208            .ok()?;
209        if json.len() as u64 > MAX_DOCUMENT_BYTES {
210            return None;
211        }
212        serde_json::from_slice(&json).ok()
213    }
214}
215
216/// Largest decompressed document. The biggest BAN street (thousands of
217/// housenumbers) is a few hundred KB.
218const MAX_DOCUMENT_BYTES: u64 = 16 << 20;
219
220/// A serialized bitmap, validated (empty when invalid).
221fn bitmap(bytes: &[u8]) -> RoaringBitmap {
222    RoaringBitmap::deserialize_from(bytes).unwrap_or_default()
223}
224
225/// `(doc, boost)` entries of one token, sorted by doc.
226#[derive(Clone, Copy)]
227pub struct Postings<'a> {
228    bytes: &'a [u8],
229}
230
231impl<'a> Postings<'a> {
232    pub fn len(&self) -> usize {
233        self.bytes.len() / 8
234    }
235
236    pub fn is_empty(&self) -> bool {
237        self.bytes.is_empty()
238    }
239
240    pub fn get(&self, i: usize) -> (DocId, f32) {
241        let at = i * 8;
242        let doc = u32::from_le_bytes(self.bytes[at..at + 4].try_into().unwrap());
243        let boost = f32::from_le_bytes(self.bytes[at + 4..at + 8].try_into().unwrap());
244        (doc, boost)
245    }
246
247    pub fn iter(&self) -> impl Iterator<Item = (DocId, f32)> + 'a {
248        let bytes = self.bytes;
249        bytes.as_chunks::<8>().0.iter().map(|c| {
250            (
251                u32::from_le_bytes([c[0], c[1], c[2], c[3]]),
252                f32::from_le_bytes([c[4], c[5], c[6], c[7]]),
253            )
254        })
255    }
256
257    /// Boost of `doc`, if it holds the token.
258    pub fn find(&self, doc: DocId) -> Option<f32> {
259        let (mut lo, mut hi) = (0, self.len());
260        while lo < hi {
261            let mid = (lo + hi) / 2;
262            let (d, boost) = self.get(mid);
263            match d.cmp(&doc) {
264                std::cmp::Ordering::Equal => return Some(boost),
265                std::cmp::Ordering::Less => lo = mid + 1,
266                std::cmp::Ordering::Greater => hi = mid,
267            }
268        }
269        None
270    }
271}