Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / networklocation / wps_harvest / src / store.rs

store.rs453 lines · 16.2 KiBRaw
1//! Writer for the `WPSDB2` store format read by
2//! `networklocation/src/main/rust/src/wpsdb.rs`.
3//!
4//! The layout is documented there and duplicated here only as far as the constants; the two
5//! must stay in step. `wpsdb.rs`'s own fixture tests build a store with a transcription of
6//! this writer, so a divergence shows up as a failure on the reader side too.
7//!
8//! ```text
9//! 0 magic "WPSDB2\0\0" 8 B
10//! 8 key_kind:u8, universe_bits:u8, payload_kind:u8, l:u8
11//! 12 select_sample_log2:u8, reserved:u8 * 3
12//! 16 n:u64
13//! 24 high_len_bits:u64
14//! 32 high_len:u64
15//! 40 high[high_len]
16//! zeros_len:u64, zeros[zeros_len]
17//! low_len:u64, low[low_len]
18//! payload_len:u64, payload[payload_len]
19//! ```
20//!
21//! Nothing is held in memory proportional to the record count except the `select0` sample
22//! table (a few MB at a billion records): `high`, `low` and `payload` are streamed to scratch
23//! files as the sorted records arrive and concatenated at the end.
24
25use std::fs::File;
26use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
27use std::path::{Path, PathBuf};
28
29use crate::record::{Record, ALT_UNKNOWN, LAT_E8_MIN, LON_E8_MIN};
30
31const MAGIC: &[u8; 8] = b"WPSDB2\x00\x00";
32
33const LAT_BITS: u32 = 35;
34const LON_BITS: u32 = 36;
35const ACC_BITS: u32 = 16;
36const ALT_BITS: u32 = 16;
37
38/// Payload: lat(35) | lon(36) | accuracy(16) | altitude(16), LSB-first — 103 bits.
39/// Altitude is metres biased by 32768 (two's complement in 16 bits), 0 meaning "unknown".
40/// Kind-1 stores (87 bits, no altitude) remain readable; new builds always write kind 2.
41const PAYLOAD_LATLON_E8_ACC16_ALT16: u8 = 2;
42
43/// Cap on the Elias-Fano low width, so a low value always fits the reader's `u64`. Exceeding
44/// it would only ever lengthen `high`, so the cap costs nothing at real record counts.
45pub(crate) const MAX_L: u8 = 64;
46
47/// Default `select0` sampling stride, as a power of two. 4096 bounds the in-block scan of a
48/// `select0` to 4096 bit tests while keeping the table small.
49pub const DEFAULT_SAMPLE_LOG2: u8 = 12;
50
51/// Which keyspace a store indexes. Recorded in the header for diagnostics; the reader keys
52/// its behaviour off `universe_bits`.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum KeyKind {
55 /// 48-bit BSSID.
56 Wifi = 1,
57 /// 84-bit packed cell identity.
58 Cell = 2,
59}
60
61/// Elias-Fano low-part width for `n` keys drawn from a `universe_bits`-wide universe.
62///
63/// The bucket space is `2^(universe_bits - l)` bits of `high`, so a small `l` over a wide
64/// universe is catastrophic rather than merely wasteful: at `n = 0` the unguarded formula
65/// gives `l = 0` and asks for `2^48` bits of padding. An empty or tiny set therefore pins `l`
66/// as wide as it is allowed to go, which makes the bucket space as small as possible.
67pub fn choose_l(universe_bits: u8, n: u64) -> u8 {
68 if n == 0 {
69 return universe_bits.min(MAX_L);
70 }
71 let u = 1u128 << universe_bits;
72 let mut l = 0u8;
73 while l < MAX_L && (u >> (l as u32 + 1)) >= n as u128 {
74 l += 1;
75 }
76 l
77}
78
79// --------------------------------------------------------------------------- bit writer
80struct BitWriter<W: Write> {
81 inner: W,
82 cur: u8,
83 used: u32,
84 bits: u64,
85}
86
87impl<W: Write> BitWriter<W> {
88 fn new(inner: W) -> BitWriter<W> {
89 BitWriter { inner, cur: 0, used: 0, bits: 0 }
90 }
91
92 fn push(&mut self, v: u64, nbits: u32) -> io::Result<()> {
93 for k in 0..nbits {
94 self.push_bit((v >> k) & 1 == 1)?;
95 }
96 Ok(())
97 }
98
99 fn push_bit(&mut self, set: bool) -> io::Result<()> {
100 if set {
101 self.cur |= 1 << self.used;
102 }
103 self.used += 1;
104 self.bits += 1;
105 if self.used == 8 {
106 self.inner.write_all(&[self.cur])?;
107 self.cur = 0;
108 self.used = 0;
109 }
110 Ok(())
111 }
112
113 /// Flush the partial final byte and return `(bits written, bytes written)`.
114 fn finish(mut self) -> io::Result<(u64, u64)> {
115 let mut bytes = self.bits / 8;
116 if self.used > 0 {
117 self.inner.write_all(&[self.cur])?;
118 bytes += 1;
119 }
120 self.inner.flush()?;
121 Ok((self.bits, bytes))
122 }
123}
124
125// --------------------------------------------------------------------------- scratch
126/// A scratch file that deletes itself.
127struct Scratch {
128 path: PathBuf,
129}
130
131impl Scratch {
132 fn create(dir: &Path, name: &str) -> io::Result<(Scratch, File)> {
133 std::fs::create_dir_all(dir)?;
134 let path = dir.join(name);
135 let file = File::create(&path)?;
136 Ok((Scratch { path }, file))
137 }
138}
139
140impl Drop for Scratch {
141 fn drop(&mut self) {
142 let _ = std::fs::remove_file(&self.path);
143 }
144}
145
146fn append_file(out: &mut impl Write, path: &Path) -> io::Result<u64> {
147 let mut f = BufReader::new(File::open(path)?);
148 io::copy(&mut f, out)
149}
150
151// --------------------------------------------------------------------------- writer
152/// Write a `WPSDB2` store.
153///
154/// `records` must be **sorted by key and free of duplicate keys**, and must yield exactly `n`
155/// items. Both are invariants of the Elias-Fano index rather than preferences: an out-of-order
156/// key produces a bitvector that decodes to a different key, and a duplicate produces two
157/// records the reader can only ever reach one of. They are checked, not assumed.
158///
159/// Records are consumed as a stream of results so the caller can read them straight off disk;
160/// nothing proportional to `n` is held in memory. `scratch_dir` holds three intermediate files
161/// whose combined size is roughly that of the finished store; they are removed on both success
162/// and failure.
163pub fn write_store<I>(
164 out_path: &Path,
165 scratch_dir: &Path,
166 kind: KeyKind,
167 universe_bits: u8,
168 n: u64,
169 sample_log2: u8,
170 records: I,
171) -> io::Result<u64>
172where
173 I: IntoIterator<Item = io::Result<Record>>,
174{
175 if universe_bits == 0 || universe_bits > 127 {
176 return Err(invalid(format!("universe_bits {universe_bits} out of range")));
177 }
178 if !(6..=20).contains(&sample_log2) {
179 return Err(invalid(format!("select sample stride 2^{sample_log2} out of range")));
180 }
181 let l = choose_l(universe_bits, n);
182 if (universe_bits as u32).saturating_sub(l as u32) > 64 {
183 return Err(invalid("bucket space wider than 64 bits".to_string()));
184 }
185 let buckets = 1u64 << (universe_bits as u32 - l as u32);
186
187 let (high_s, high_f) = Scratch::create(scratch_dir, "wpsdb.high")?;
188 let (low_s, low_f) = Scratch::create(scratch_dir, "wpsdb.low")?;
189 let (pay_s, pay_f) = Scratch::create(scratch_dir, "wpsdb.payload")?;
190
191 let mut high = BitWriter::new(BufWriter::new(high_f));
192 let mut low = BitWriter::new(BufWriter::new(low_f));
193 let mut payload = BitWriter::new(BufWriter::new(pay_f));
194
195 // `zeros[b]` = number of zero bits in high[0 .. b << sample_log2). Accumulated while the
196 // bitvector streams past, so `high` never has to be resident to build the index.
197 let sample_mask = (1u64 << sample_log2) - 1;
198 let mut zeros: Vec<u64> = vec![0];
199 let mut zero_count = 0u64;
200 let mut high_bits = 0u64;
201
202 let emit_high = |bit: bool,
203 high: &mut BitWriter<BufWriter<File>>,
204 zeros: &mut Vec<u64>,
205 zero_count: &mut u64,
206 high_bits: &mut u64|
207 -> io::Result<()> {
208 high.push_bit(bit)?;
209 if !bit {
210 *zero_count += 1;
211 }
212 *high_bits += 1;
213 if (*high_bits & sample_mask) == 0 {
214 zeros.push(*zero_count);
215 }
216 Ok(())
217 };
218
219 let mut written = 0u64;
220 let mut prev_bucket = 0u64;
221 let mut prev_key: Option<u128> = None;
222
223 for r in records {
224 let r = r?;
225 if written == n {
226 return Err(invalid(format!("more than the declared {n} records")));
227 }
228 if r.key >= (1u128 << universe_bits) {
229 return Err(invalid(format!(
230 "key {:#x} outside the {universe_bits}-bit universe",
231 r.key
232 )));
233 }
234 if let Some(p) = prev_key {
235 if r.key <= p {
236 return Err(invalid(format!(
237 "records must be strictly ascending by key; {:#x} follows {:#x}",
238 r.key, p
239 )));
240 }
241 }
242 if !r.in_range() {
243 return Err(invalid(format!("record {:#x} has out-of-range coordinates", r.key)));
244 }
245 prev_key = Some(r.key);
246
247 let bucket = (r.key >> l) as u64;
248 for _ in prev_bucket..bucket {
249 emit_high(false, &mut high, &mut zeros, &mut zero_count, &mut high_bits)?;
250 }
251 emit_high(true, &mut high, &mut zeros, &mut zero_count, &mut high_bits)?;
252 prev_bucket = bucket;
253
254 let lo = if l == 0 { 0 } else { (r.key & ((1u128 << l) - 1)) as u64 };
255 low.push(lo, l as u32)?;
256
257 payload.push((r.lat_e8 - LAT_E8_MIN) as u64, LAT_BITS)?;
258 payload.push((r.lon_e8 - LON_E8_MIN) as u64, LON_BITS)?;
259 payload.push(u64::from(r.accuracy_m), ACC_BITS)?;
260 // Altitude biased so "unknown" (i16::MIN) lands on 0 and real metres on 1..=65535.
261 payload.push((i64::from(r.altitude_m) - i64::from(ALT_UNKNOWN)) as u64, ALT_BITS)?;
262
263 written += 1;
264 }
265 if written != n {
266 return Err(invalid(format!("declared {n} records but got {written}")));
267 }
268
269 // Pad the bucket space out so `select0(bucket - 1)` resolves for every reachable bucket,
270 // including ones past the last key.
271 for _ in prev_bucket..buckets {
272 emit_high(false, &mut high, &mut zeros, &mut zero_count, &mut high_bits)?;
273 }
274
275 let (high_len_bits, high_len) = high.finish()?;
276 let (_, low_len) = low.finish()?;
277 let (_, payload_len) = payload.finish()?;
278
279 debug_assert_eq!(high_len_bits, n + buckets);
280 if zeros.len() as u64 != (high_len_bits >> sample_log2) + 1 {
281 return Err(invalid("select0 sample table has the wrong length".to_string()));
282 }
283
284 let mut out = BufWriter::new(File::create(out_path)?);
285 out.write_all(MAGIC)?;
286 out.write_all(&[kind as u8, universe_bits, PAYLOAD_LATLON_E8_ACC16_ALT16, l])?;
287 out.write_all(&[sample_log2, 0, 0, 0])?;
288 out.write_all(&n.to_le_bytes())?;
289 out.write_all(&high_len_bits.to_le_bytes())?;
290 out.write_all(&high_len.to_le_bytes())?;
291 let copied = append_file(&mut out, &high_s.path)?;
292 debug_assert_eq!(copied, high_len);
293 out.write_all(&((zeros.len() * 8) as u64).to_le_bytes())?;
294 for z in &zeros {
295 out.write_all(&z.to_le_bytes())?;
296 }
297 out.write_all(&low_len.to_le_bytes())?;
298 let _ = append_file(&mut out, &low_s.path)?;
299 out.write_all(&payload_len.to_le_bytes())?;
300 let _ = append_file(&mut out, &pay_s.path)?;
301 out.flush()?;
302
303 let mut f = out.into_inner().map_err(|e| e.into_error())?;
304 let size = f.seek(SeekFrom::End(0))?;
305 Ok(size)
306}
307
308fn invalid(msg: String) -> io::Error {
309 io::Error::new(io::ErrorKind::InvalidData, msg)
310}
311
312// --------------------------------------------------------------------------- self-test
313/// Sequential LSB-first bit reader over one section of the store.
314struct BitStream<R: Read> {
315 inner: R,
316 acc: u64,
317 have: u32,
318}
319
320impl<R: Read> BitStream<R> {
321 fn new(inner: R) -> BitStream<R> {
322 BitStream { inner, acc: 0, have: 0 }
323 }
324
325 fn take_small(&mut self, n: u32) -> io::Result<u64> {
326 while self.have < n {
327 let mut b = [0u8; 1];
328 self.inner.read_exact(&mut b)?;
329 self.acc |= (b[0] as u64) << self.have;
330 self.have += 8;
331 }
332 let v = if n == 64 { self.acc } else { self.acc & ((1u64 << n) - 1) };
333 self.acc >>= n;
334 self.have -= n;
335 Ok(v)
336 }
337
338 /// Next `n` bits (`n <= 64`). Taken in 32-bit chunks so the accumulator cannot overflow.
339 fn take(&mut self, n: u32) -> io::Result<u64> {
340 let mut out = 0u64;
341 let mut taken = 0u32;
342 while taken < n {
343 let chunk = (n - taken).min(32);
344 out |= self.take_small(chunk)? << taken;
345 taken += chunk;
346 }
347 Ok(out)
348 }
349
350 fn take_bit(&mut self) -> io::Result<bool> {
351 Ok(self.take_small(1)? == 1)
352 }
353}
354
355fn section_reader(path: &Path, offset: u64) -> io::Result<BufReader<File>> {
356 let mut f = File::open(path)?;
357 let _ = f.seek(SeekFrom::Start(offset))?;
358 Ok(BufReader::with_capacity(1 << 16, f))
359}
360
361/// Read a finished store back and check every record resolves to what was written.
362///
363/// The store's own writer is not reused: this walks the Elias-Fano bitvector directly instead
364/// of using `select0`, so a shared misunderstanding between two `index()` implementations
365/// cannot hide here. It is also the only check that the bytes on disk are what the writer
366/// believed it wrote.
367///
368/// `expected` must yield the same records, in the same order, that were written. All four
369/// sections are streamed in parallel — `idx` only ever increases, so `low` and `payload` are
370/// consumed strictly in order — which keeps this O(1) in memory over a store of any size.
371pub fn verify_store<I>(path: &Path, expected: I) -> io::Result<u64>
372where
373 I: IntoIterator<Item = io::Result<Record>>,
374{
375 let mut head = [0u8; 40];
376 File::open(path)?.read_exact(&mut head)?;
377 if &head[0..8] != MAGIC {
378 return Err(invalid("bad magic".to_string()));
379 }
380 let universe_bits = head[9];
381 let l = head[11] as u32;
382 let n =
383 u64::from_le_bytes(head[16..24].try_into().map_err(|_| invalid("short header".into()))?);
384 let high_len_bits =
385 u64::from_le_bytes(head[24..32].try_into().map_err(|_| invalid("short header".into()))?);
386 let high_len =
387 u64::from_le_bytes(head[32..40].try_into().map_err(|_| invalid("short header".into()))?);
388
389 // Section offsets follow from the lengths; the file has no offset table.
390 let mut len_buf = [0u8; 8];
391 let read_u64_at = |off: u64, buf: &mut [u8; 8]| -> io::Result<u64> {
392 let mut f = File::open(path)?;
393 let _ = f.seek(SeekFrom::Start(off))?;
394 f.read_exact(buf)?;
395 Ok(u64::from_le_bytes(*buf))
396 };
397 let zeros_len_off = 40 + high_len;
398 let zeros_len = read_u64_at(zeros_len_off, &mut len_buf)?;
399 let low_len_off = zeros_len_off + 8 + zeros_len;
400 let low_len = read_u64_at(low_len_off, &mut len_buf)?;
401 let payload_len_off = low_len_off + 8 + low_len;
402 let _payload_len = read_u64_at(payload_len_off, &mut len_buf)?;
403
404 let mut high = BitStream::new(section_reader(path, 40)?);
405 let mut low = BitStream::new(section_reader(path, low_len_off + 8)?);
406 let mut payload = BitStream::new(section_reader(path, payload_len_off + 8)?);
407
408 let mut want = expected.into_iter();
409 let mut idx = 0u64;
410 let mut p = 0u64;
411 while p < high_len_bits && idx < n {
412 if high.take_bit()? {
413 let upper = (p - idx) as u128;
414 let lo = if l == 0 { 0 } else { low.take(l)? as u128 };
415 let key = (upper << l) | lo;
416
417 let lat = payload.take(LAT_BITS)? as i64 + LAT_E8_MIN;
418 let lon = payload.take(LON_BITS)? as i64 + LON_E8_MIN;
419 let acc = payload.take(ACC_BITS)? as u16;
420 let alt = payload.take(ALT_BITS)? as i64 + i64::from(ALT_UNKNOWN);
421
422 let w = want
423 .next()
424 .transpose()?
425 .ok_or_else(|| invalid(format!("store holds more than the {idx} expected")))?;
426 if key != w.key || lat != w.lat_e8 || lon != w.lon_e8 || acc != w.accuracy_m {
427 return Err(invalid(format!(
428 "record {idx} mismatch: got ({key:#x}, {lat}, {lon}, {acc}), \
429 want ({:#x}, {}, {}, {})",
430 w.key, w.lat_e8, w.lon_e8, w.accuracy_m
431 )));
432 }
433 if alt != i64::from(w.altitude_m) {
434 return Err(invalid(format!(
435 "record {idx} altitude mismatch: got {alt}, want {}",
436 w.altitude_m
437 )));
438 }
439 if key >= (1u128 << universe_bits) {
440 return Err(invalid(format!("record {idx} key escapes the universe")));
441 }
442 idx += 1;
443 }
444 p += 1;
445 }
446 if idx != n {
447 return Err(invalid(format!("recovered {idx} of {n} records from the bitvector")));
448 }
449 if want.next().transpose()?.is_some() {
450 return Err(invalid(format!("expected more records than the {n} the store holds")));
451 }
452 Ok(n)
453}