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