Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / src / record.rs
record.rs311 lines · 10.7 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 | |
| 8 | use 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". |
| 15 | pub const RECORD_BYTES: usize = 40; |
| 16 | |
| 17 | /// `lat * 1e8`, the range the store's 35-bit latitude field covers. |
| 18 | pub const LAT_E8_MIN: i64 = -9_000_000_000; |
| 19 | /// `lat * 1e8`, upper bound. |
| 20 | pub const LAT_E8_MAX: i64 = 9_000_000_000; |
| 21 | /// `lon * 1e8`, the range the store's 36-bit longitude field covers. |
| 22 | pub const LON_E8_MIN: i64 = -18_000_000_000; |
| 23 | /// `lon * 1e8`, upper bound. |
| 24 | pub const LON_E8_MAX: i64 = 18_000_000_000; |
| 25 | |
| 26 | /// Stored accuracy meaning "the source did not report one". |
| 27 | pub 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). |
| 31 | pub const ALT_UNKNOWN: i16 = i16::MIN; |
| 32 | |
| 33 | /// Flags byte bit: the altitude slot holds a real measurement. |
| 34 | const 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)] |
| 39 | pub 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 | |
| 48 | impl 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)] |
| 61 | pub 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 | |
| 77 | impl 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. |
| 125 | pub struct RecordWriter<W: Write> { |
| 126 | inner: W, |
| 127 | scratch: [u8; RECORD_BYTES], |
| 128 | count: u64, |
| 129 | } |
| 130 | |
| 131 | impl<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. |
| 167 | pub struct RecordReader<R: Read> { |
| 168 | inner: R, |
| 169 | scratch: [u8; RECORD_BYTES], |
| 170 | } |
| 171 | |
| 172 | impl<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 | fn next_record(&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 | impl<R: Read> Iterator for RecordReader<R> { |
| 206 | type Item = io::Result<Record>; |
| 207 | |
| 208 | fn next(&mut self) -> Option<Self::Item> { |
| 209 | self.next_record().transpose() |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[cfg(test)] |
| 214 | mod tests { |
| 215 | use super::*; |
| 216 | |
| 217 | fn sample() -> Record { |
| 218 | Record { |
| 219 | key: (0x4D904u128 << 64) | 0x3003039ABCDEF123, |
| 220 | lat_e8: 3_777_493_000, |
| 221 | lon_e8: -12_241_942_000, |
| 222 | accuracy_m: 35, |
| 223 | altitude_m: 12, |
| 224 | source: Source::Gsloc, |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | #[test] |
| 229 | fn record_round_trips_through_the_scratch_format() { |
| 230 | let r = sample(); |
| 231 | let mut buf = [0u8; RECORD_BYTES]; |
| 232 | r.write_into(&mut buf); |
| 233 | assert_eq!(Record::read_from(&buf), Some(r)); |
| 234 | } |
| 235 | |
| 236 | #[test] |
| 237 | fn extremes_and_the_unknown_accuracy_sentinel_round_trip() { |
| 238 | for r in [ |
| 239 | Record { lat_e8: LAT_E8_MIN, lon_e8: LON_E8_MIN, accuracy_m: 0, ..sample() }, |
| 240 | Record { lat_e8: LAT_E8_MAX, lon_e8: LON_E8_MAX, accuracy_m: 65534, ..sample() }, |
| 241 | Record { accuracy_m: ACC_UNKNOWN, ..sample() }, |
| 242 | Record { key: u128::MAX >> 44, ..sample() }, |
| 243 | ] { |
| 244 | let mut buf = [0u8; RECORD_BYTES]; |
| 245 | r.write_into(&mut buf); |
| 246 | assert_eq!(Record::read_from(&buf), Some(r)); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | #[test] |
| 251 | fn altitude_round_trips_and_absence_is_distinct_from_zero() { |
| 252 | for alt in [ALT_UNKNOWN, -430, 0, 55, 8848] { |
| 253 | let r = Record { altitude_m: alt, ..sample() }; |
| 254 | let mut buf = [0u8; RECORD_BYTES]; |
| 255 | r.write_into(&mut buf); |
| 256 | assert_eq!(Record::read_from(&buf).unwrap().altitude_m, alt, "altitude {alt}"); |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | #[test] |
| 261 | fn a_pre_altitude_shard_reads_as_altitude_unknown() { |
| 262 | // Old layout: everything past `source` was zero pad. |
| 263 | let r = Record { altitude_m: 250, ..sample() }; |
| 264 | let mut buf = [0u8; RECORD_BYTES]; |
| 265 | r.write_into(&mut buf); |
| 266 | buf[35..40].fill(0); |
| 267 | assert_eq!(Record::read_from(&buf).unwrap().altitude_m, ALT_UNKNOWN); |
| 268 | } |
| 269 | |
| 270 | #[test] |
| 271 | fn out_of_range_coordinates_are_detected() { |
| 272 | assert!(sample().in_range()); |
| 273 | assert!(!Record { lat_e8: LAT_E8_MAX + 1, ..sample() }.in_range()); |
| 274 | assert!(!Record { lon_e8: LON_E8_MIN - 1, ..sample() }.in_range()); |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn a_shard_round_trips_through_reader_and_writer() { |
| 279 | let records: Vec<Record> = (0..500) |
| 280 | .map(|i| Record { key: i as u128 * 7919, accuracy_m: i as u16, ..sample() }) |
| 281 | .collect(); |
| 282 | let mut bytes: Vec<u8> = Vec::new(); |
| 283 | let mut w = RecordWriter::new(&mut bytes); |
| 284 | for r in &records { |
| 285 | w.push(r).unwrap(); |
| 286 | } |
| 287 | assert_eq!(w.finish().unwrap(), 500); |
| 288 | |
| 289 | let rd = RecordReader::new(bytes.as_slice()); |
| 290 | let mut got = Vec::new(); |
| 291 | for r in rd { |
| 292 | got.push(r.unwrap()); |
| 293 | } |
| 294 | assert_eq!(got, records); |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn a_torn_trailing_record_is_an_error_not_an_end() { |
| 299 | let mut bytes: Vec<u8> = Vec::new(); |
| 300 | let mut w = RecordWriter::new(&mut bytes); |
| 301 | w.push(&sample()).unwrap(); |
| 302 | w.finish().unwrap(); |
| 303 | bytes.truncate(RECORD_BYTES + 9); |
| 304 | bytes.extend_from_slice(&[0u8; 9]); |
| 305 | bytes.truncate(RECORD_BYTES + 9); |
| 306 | |
| 307 | let mut rd = RecordReader::new(bytes.as_slice()); |
| 308 | assert_eq!(rd.next().unwrap().unwrap(), sample()); |
| 309 | assert!(matches!(rd.next(), Some(Err(_))), "a partial tail must not read as end of shard"); |
| 310 | } |
| 311 | } |