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

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

record.rs303 lines · 10.5 KiBRaw
1//! Observation records and the fixed-width scratch format the pipeline passes them in.
2//!
3//! `wps_seed` and `wps_crawl` both emit unsorted [`Record`] shards; `wps_build` sorts, merges
4//! and filters them into a store. The scratch format is fixed-width so an external sort can
5//! seek and a merge can stream, and little-endian so a shard is byte-identical on any host
6//! the pipeline runs on.
7
8use std::io::{self, Read, Write};
9
10/// Bytes on disk per record: key(16) + lat(8) + lon(8) + accuracy(2) + source(1)
11/// + altitude(2) + pad(2) + flags(1).
12///
13/// The altitude slot and flag byte reuse what was the zero pad, so a shard written before
14/// altitude existed still reads cleanly: its flags byte is 0, meaning "altitude unknown".
15pub const RECORD_BYTES: usize = 40;
16
17/// `lat * 1e8`, the range the store's 35-bit latitude field covers.
18pub const LAT_E8_MIN: i64 = -90_00_000_000;
19/// `lat * 1e8`, upper bound.
20pub const LAT_E8_MAX: i64 = 90_00_000_000;
21/// `lon * 1e8`, the range the store's 36-bit longitude field covers.
22pub const LON_E8_MIN: i64 = -180_00_000_000;
23/// `lon * 1e8`, upper bound.
24pub const LON_E8_MAX: i64 = 180_00_000_000;
25
26/// Stored accuracy meaning "the source did not report one".
27pub const ACC_UNKNOWN: u16 = 0xFFFF;
28
29/// Stored altitude meaning "the source did not report one" (or the shard predates altitude,
30/// which reads as flags = 0). Metres are otherwise well inside `i16` (Dead Sea to Everest).
31pub const ALT_UNKNOWN: i16 = i16::MIN;
32
33/// Flags byte bit: the altitude slot holds a real measurement.
34const FLAG_ALTITUDE_PRESENT: u8 = 1;
35
36/// Where an observation came from. Kept per record so the merge can prefer a source and so a
37/// disagreement between sources is attributable rather than anonymous.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
39pub enum Source {
40 /// beacondb bulk dump.
41 Beacondb = 1,
42 /// OpenCelliD bulk dump.
43 OpenCellId = 2,
44 /// Apple gs-loc crawl.
45 Gsloc = 3,
46}
47
48impl Source {
49 fn from_wire(v: u8) -> Option<Source> {
50 match v {
51 1 => Some(Source::Beacondb),
52 2 => Some(Source::OpenCellId),
53 3 => Some(Source::Gsloc),
54 _ => None,
55 }
56 }
57}
58
59/// One observation of one beacon.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub struct Record {
62 /// Packed store key (see [`crate::keys`]).
63 pub key: u128,
64 /// Latitude in degrees x 1e8.
65 pub lat_e8: i64,
66 /// Longitude in degrees x 1e8.
67 pub lon_e8: i64,
68 /// Horizontal accuracy in metres, or [`ACC_UNKNOWN`].
69 pub accuracy_m: u16,
70 /// Altitude in metres (Apple's `location.5`), or [`ALT_UNKNOWN`]. Cells and the bulk
71 /// CSV dumps have no altitude; WiFi from gs-loc does.
72 pub altitude_m: i16,
73 /// Which dataset or crawl produced it.
74 pub source: Source,
75}
76
77impl Record {
78 /// Whether the coordinates are inside the range the store's fields can represent.
79 ///
80 /// Out-of-range values are not clamped: a clamped coordinate is a confident-looking claim
81 /// about the wrong place, whereas a dropped record is just a miss.
82 pub fn in_range(&self) -> bool {
83 (LAT_E8_MIN..=LAT_E8_MAX).contains(&self.lat_e8)
84 && (LON_E8_MIN..=LON_E8_MAX).contains(&self.lon_e8)
85 }
86
87 /// Serialize into `out`, which must be [`RECORD_BYTES`] long.
88 pub fn write_into(&self, out: &mut [u8; RECORD_BYTES]) {
89 out[0..16].copy_from_slice(&self.key.to_le_bytes());
90 out[16..24].copy_from_slice(&self.lat_e8.to_le_bytes());
91 out[24..32].copy_from_slice(&self.lon_e8.to_le_bytes());
92 out[32..34].copy_from_slice(&self.accuracy_m.to_le_bytes());
93 out[34] = self.source as u8;
94 let has_alt = self.altitude_m != ALT_UNKNOWN;
95 out[35..37].copy_from_slice(&self.altitude_m.to_le_bytes());
96 out[37..39].fill(0);
97 out[39] = if has_alt { FLAG_ALTITUDE_PRESENT } else { 0 };
98 }
99
100 /// Deserialize from exactly [`RECORD_BYTES`], or `None` if the source byte is unknown.
101 pub fn read_from(buf: &[u8; RECORD_BYTES]) -> Option<Record> {
102 let mut k = [0u8; 16];
103 k.copy_from_slice(&buf[0..16]);
104 let mut a = [0u8; 8];
105 a.copy_from_slice(&buf[16..24]);
106 let mut b = [0u8; 8];
107 b.copy_from_slice(&buf[24..32]);
108 let altitude_m = if buf[39] & FLAG_ALTITUDE_PRESENT != 0 {
109 i16::from_le_bytes([buf[35], buf[36]])
110 } else {
111 ALT_UNKNOWN
112 };
113 Some(Record {
114 key: u128::from_le_bytes(k),
115 lat_e8: i64::from_le_bytes(a),
116 lon_e8: i64::from_le_bytes(b),
117 accuracy_m: u16::from_le_bytes([buf[32], buf[33]]),
118 altitude_m,
119 source: Source::from_wire(buf[34])?,
120 })
121 }
122}
123
124/// Buffered writer for a record shard.
125pub struct RecordWriter<W: Write> {
126 inner: W,
127 scratch: [u8; RECORD_BYTES],
128 count: u64,
129}
130
131impl<W: Write> RecordWriter<W> {
132 /// Wrap `inner`. Callers are expected to pass something buffered.
133 pub fn new(inner: W) -> RecordWriter<W> {
134 RecordWriter { inner, scratch: [0u8; RECORD_BYTES], count: 0 }
135 }
136
137 /// Append one record.
138 pub fn push(&mut self, r: &Record) -> io::Result<()> {
139 r.write_into(&mut self.scratch);
140 self.inner.write_all(&self.scratch)?;
141 self.count += 1;
142 Ok(())
143 }
144
145 /// Flush buffered records to disk without consuming the writer.
146 ///
147 /// A crawl runs for weeks and is expected to be killed. Buffered records that were never
148 /// flushed are simply lost, and the frontier will not re-offer the BSSIDs that produced
149 /// them, so the work is gone for good — flushing at each checkpoint bounds that loss.
150 pub fn flush(&mut self) -> io::Result<()> {
151 self.inner.flush()
152 }
153
154 /// Records written so far.
155 pub fn count(&self) -> u64 {
156 self.count
157 }
158
159 /// Flush and return the number of records written.
160 pub fn finish(mut self) -> io::Result<u64> {
161 self.inner.flush()?;
162 Ok(self.count)
163 }
164}
165
166/// Streaming reader over a record shard.
167pub struct RecordReader<R: Read> {
168 inner: R,
169 scratch: [u8; RECORD_BYTES],
170}
171
172impl<R: Read> RecordReader<R> {
173 /// Wrap `inner`. Callers are expected to pass something buffered.
174 pub fn new(inner: R) -> RecordReader<R> {
175 RecordReader { inner, scratch: [0u8; RECORD_BYTES] }
176 }
177
178 /// Next record, or `Ok(None)` at a clean end of file.
179 ///
180 /// A partial trailing record is an error rather than an end: shards are produced by long
181 /// runs that can be killed, and silently ignoring a torn tail would quietly drop data.
182 pub fn next(&mut self) -> io::Result<Option<Record>> {
183 let mut filled = 0usize;
184 while filled < RECORD_BYTES {
185 match self.inner.read(&mut self.scratch[filled..])? {
186 0 => break,
187 n => filled += n,
188 }
189 }
190 if filled == 0 {
191 return Ok(None);
192 }
193 if filled != RECORD_BYTES {
194 return Err(io::Error::new(
195 io::ErrorKind::UnexpectedEof,
196 format!("shard ends with a partial record ({filled} of {RECORD_BYTES} bytes)"),
197 ));
198 }
199 Record::read_from(&self.scratch)
200 .map(Some)
201 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "unknown record source"))
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 fn sample() -> Record {
210 Record {
211 key: (0x4D904u128 << 64) | 0x3003039ABCDEF123,
212 lat_e8: 37_77_493_000,
213 lon_e8: -122_41_942_000,
214 accuracy_m: 35,
215 altitude_m: 12,
216 source: Source::Gsloc,
217 }
218 }
219
220 #[test]
221 fn record_round_trips_through_the_scratch_format() {
222 let r = sample();
223 let mut buf = [0u8; RECORD_BYTES];
224 r.write_into(&mut buf);
225 assert_eq!(Record::read_from(&buf), Some(r));
226 }
227
228 #[test]
229 fn extremes_and_the_unknown_accuracy_sentinel_round_trip() {
230 for r in [
231 Record { lat_e8: LAT_E8_MIN, lon_e8: LON_E8_MIN, accuracy_m: 0, ..sample() },
232 Record { lat_e8: LAT_E8_MAX, lon_e8: LON_E8_MAX, accuracy_m: 65534, ..sample() },
233 Record { accuracy_m: ACC_UNKNOWN, ..sample() },
234 Record { key: u128::MAX >> 44, ..sample() },
235 ] {
236 let mut buf = [0u8; RECORD_BYTES];
237 r.write_into(&mut buf);
238 assert_eq!(Record::read_from(&buf), Some(r));
239 }
240 }
241
242 #[test]
243 fn altitude_round_trips_and_absence_is_distinct_from_zero() {
244 for alt in [ALT_UNKNOWN, -430, 0, 55, 8848] {
245 let r = Record { altitude_m: alt, ..sample() };
246 let mut buf = [0u8; RECORD_BYTES];
247 r.write_into(&mut buf);
248 assert_eq!(Record::read_from(&buf).unwrap().altitude_m, alt, "altitude {alt}");
249 }
250 }
251
252 #[test]
253 fn a_pre_altitude_shard_reads_as_altitude_unknown() {
254 // Old layout: everything past `source` was zero pad.
255 let r = Record { altitude_m: 250, ..sample() };
256 let mut buf = [0u8; RECORD_BYTES];
257 r.write_into(&mut buf);
258 buf[35..40].fill(0);
259 assert_eq!(Record::read_from(&buf).unwrap().altitude_m, ALT_UNKNOWN);
260 }
261
262 #[test]
263 fn out_of_range_coordinates_are_detected() {
264 assert!(sample().in_range());
265 assert!(!Record { lat_e8: LAT_E8_MAX + 1, ..sample() }.in_range());
266 assert!(!Record { lon_e8: LON_E8_MIN - 1, ..sample() }.in_range());
267 }
268
269 #[test]
270 fn a_shard_round_trips_through_reader_and_writer() {
271 let records: Vec<Record> = (0..500)
272 .map(|i| Record { key: i as u128 * 7919, accuracy_m: i as u16, ..sample() })
273 .collect();
274 let mut bytes: Vec<u8> = Vec::new();
275 let mut w = RecordWriter::new(&mut bytes);
276 for r in &records {
277 w.push(r).unwrap();
278 }
279 assert_eq!(w.finish().unwrap(), 500);
280
281 let mut rd = RecordReader::new(bytes.as_slice());
282 let mut got = Vec::new();
283 while let Some(r) = rd.next().unwrap() {
284 got.push(r);
285 }
286 assert_eq!(got, records);
287 }
288
289 #[test]
290 fn a_torn_trailing_record_is_an_error_not_an_end() {
291 let mut bytes: Vec<u8> = Vec::new();
292 let mut w = RecordWriter::new(&mut bytes);
293 w.push(&sample()).unwrap();
294 w.finish().unwrap();
295 bytes.truncate(RECORD_BYTES + 9);
296 bytes.extend_from_slice(&[0u8; 9]);
297 bytes.truncate(RECORD_BYTES + 9);
298
299 let mut rd = RecordReader::new(bytes.as_slice());
300 assert_eq!(rd.next().unwrap(), Some(sample()));
301 assert!(rd.next().is_err(), "a partial tail must not read as end of shard");
302 }
303}