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

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

seed.rs386 lines · 15.1 KiBRaw
1//! Ingest of the open bulk datasets that seed the stores.
2//!
3//! **Cells only, in practice.** OpenCelliD publishes a full CSV dump. There is no equivalent
4//! for WiFi: beaconDB's dumps are announced but unpublished, Mozilla Location Services was
5//! never able to release its WiFi data for legal and privacy reasons, and WiGLE's terms forbid
6//! bulk redistribution. The WiFi store is built by `wps_crawl` instead, which needs only a
7//! handful of real BSSIDs to start from.
8//!
9//! The parser is nonetheless source-agnostic and handles WiFi dumps too, so a dump becoming
10//! available later needs no code change. Column names differ between sources and have changed
11//! over time, so it is driven by the header row rather than by fixed positions — a renamed
12//! column fails loudly instead of silently reading longitude out of the accuracy field.
13//!
14//! Coordinates are parsed as **exact decimals**, not through `f64`. The store keeps degrees
15//! x 1e8 and the whole point of that choice is that it is bit-exact against the source, which
16//! a parse-then-multiply round trip would quietly give up.
17//!
18//! Compressed dumps are read from stdin (`gunzip -c dump.csv.gz | wps_seed -`) rather than
19//! decompressed in process; that keeps a decompressor out of the dependency list for a step
20//! that runs once per dataset.
21
22use std::io::{self, BufRead};
23
24use crate::keys::{self, CellId, RadioType};
25use crate::quality::clamp_accuracy;
26use crate::record::{ALT_UNKNOWN, Record, Source, ACC_UNKNOWN};
27
28/// Column aliases accepted for each field, lowercased.
29const MAC_NAMES: &[&str] = &["bssid", "mac", "macaddress", "mac_address"];
30const LAT_NAMES: &[&str] = &["lat", "latitude"];
31const LON_NAMES: &[&str] = &["lon", "long", "lng", "longitude"];
32const ACC_NAMES: &[&str] = &["accuracy", "range", "radius", "horizontal_accuracy"];
33const RADIO_NAMES: &[&str] = &["radio", "radiotype", "radio_type"];
34const MCC_NAMES: &[&str] = &["mcc", "mobilecountrycode"];
35const MNC_NAMES: &[&str] = &["net", "mnc", "mobilenetworkcode"];
36const AREA_NAMES: &[&str] = &["area", "lac", "tac", "lacid", "locationareacode"];
37const CELL_NAMES: &[&str] = &["cell", "cid", "cellid", "cell_id"];
38
39/// What a dump holds.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Kind {
42 /// WiFi access points, keyed by BSSID.
43 Wifi,
44 /// Cell towers.
45 Cell,
46}
47
48/// Column positions resolved from a header row.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Schema {
51 kind: Kind,
52 mac: usize,
53 lat: usize,
54 lon: usize,
55 accuracy: Option<usize>,
56 radio: Option<usize>,
57 mcc: usize,
58 mnc: usize,
59 area: usize,
60 cell: usize,
61}
62
63fn find(header: &[String], names: &[&str]) -> Option<usize> {
64 header.iter().position(|h| names.contains(&h.as_str()))
65}
66
67impl Schema {
68 /// Resolve `header` for a dump of `kind`.
69 pub fn from_header(kind: Kind, header_line: &str) -> Result<Schema, String> {
70 let header: Vec<String> =
71 split_csv(header_line).into_iter().map(|s| s.trim().to_ascii_lowercase()).collect();
72
73 let lat = find(&header, LAT_NAMES).ok_or("no latitude column")?;
74 let lon = find(&header, LON_NAMES).ok_or("no longitude column")?;
75 let accuracy = find(&header, ACC_NAMES);
76 let radio = find(&header, RADIO_NAMES);
77
78 let (mac, mcc, mnc, area, cell) = match kind {
79 Kind::Wifi => (find(&header, MAC_NAMES).ok_or("no bssid column")?, 0, 0, 0, 0),
80 Kind::Cell => (
81 0,
82 find(&header, MCC_NAMES).ok_or("no mcc column")?,
83 find(&header, MNC_NAMES).ok_or("no mnc/net column")?,
84 find(&header, AREA_NAMES).ok_or("no area/lac/tac column")?,
85 find(&header, CELL_NAMES).ok_or("no cell id column")?,
86 ),
87 };
88 if kind == Kind::Cell && radio.is_none() {
89 // Without it every tower would be filed under one radio type and LTE/GSM cells
90 // would alias, which is exactly the bug the new key layout exists to fix.
91 return Err("no radio column; a cell dump without one cannot be keyed".to_string());
92 }
93 Ok(Schema { kind, mac, lat, lon, accuracy, radio, mcc, mnc, area, cell })
94 }
95
96 /// Parse one data row. `Ok(None)` means "skip this row", which is normal: dumps carry
97 /// entries this store cannot represent.
98 pub fn parse_row(&self, line: &str, source: Source) -> Result<Option<Record>, String> {
99 let f = split_csv(line);
100 let get = |i: usize| -> Result<&str, String> {
101 f.get(i).map(|s| s.trim()).ok_or_else(|| format!("row has only {} fields", f.len()))
102 };
103
104 let lat_e8 = match parse_degrees(get(self.lat)?) {
105 Some(v) => v,
106 None => return Ok(None),
107 };
108 let lon_e8 = match parse_degrees(get(self.lon)?) {
109 Some(v) => v,
110 None => return Ok(None),
111 };
112 let accuracy_m = match self.accuracy {
113 // Dumps report an integer radius in metres; a blank or unparseable one is
114 // "unknown", not zero, because zero would claim perfect precision.
115 Some(i) => get(i)?.parse::<f64>().ok().map_or(ACC_UNKNOWN, |v| clamp_accuracy(v as i32)),
116 None => ACC_UNKNOWN,
117 };
118
119 let key = match self.kind {
120 Kind::Wifi => {
121 let Some(mac) = keys::parse_mac(&get(self.mac)?.to_ascii_lowercase()) else {
122 return Ok(None);
123 };
124 keys::wifi_key(mac)
125 }
126 Kind::Cell => {
127 let radio = match self.radio.and_then(|i| get(i).ok()).and_then(RadioType::parse) {
128 Some(r) => r,
129 None => return Ok(None),
130 };
131 let id = CellId {
132 mcc: match get(self.mcc)?.parse() {
133 Ok(v) => v,
134 Err(_) => return Ok(None),
135 },
136 mnc: match get(self.mnc)?.parse() {
137 Ok(v) => v,
138 Err(_) => return Ok(None),
139 },
140 radio,
141 cell_id: match get(self.cell)?.parse() {
142 Ok(v) => v,
143 Err(_) => return Ok(None),
144 },
145 area: match get(self.area)?.parse() {
146 Ok(v) => v,
147 Err(_) => return Ok(None),
148 },
149 };
150 if !keys::cell_fits(&id) {
151 return Ok(None);
152 }
153 keys::cell_key(&id)
154 }
155 };
156
157 let record = Record { key, lat_e8, lon_e8, accuracy_m, altitude_m: ALT_UNKNOWN, source };
158 Ok(record.in_range().then_some(record))
159 }
160}
161
162/// Split one CSV line, honouring double-quoted fields.
163///
164/// Not a general CSV implementation: these dumps have no embedded newlines, and a field is
165/// either bare or wholly quoted.
166fn split_csv(line: &str) -> Vec<String> {
167 let mut out = Vec::new();
168 let mut cur = String::new();
169 let mut quoted = false;
170 let mut chars = line.trim_end_matches(['\r', '\n']).chars().peekable();
171 while let Some(c) = chars.next() {
172 match c {
173 '"' if quoted && chars.peek() == Some(&'"') => {
174 cur.push('"');
175 let _ = chars.next();
176 }
177 '"' => quoted = !quoted,
178 ',' if !quoted => out.push(std::mem::take(&mut cur)),
179 _ => cur.push(c),
180 }
181 }
182 out.push(cur);
183 out
184}
185
186/// Parse decimal degrees to degrees x 1e8, exactly.
187///
188/// Going through `f64` would round: `-122.41942` is not representable, so multiplying by 1e8
189/// and truncating can land a unit either side. Digits are shifted instead, which is both exact
190/// and immune to locale.
191pub fn parse_degrees(s: &str) -> Option<i64> {
192 let s = s.trim();
193 if s.is_empty() {
194 return None;
195 }
196 let (neg, rest) = match s.as_bytes().first()? {
197 b'-' => (true, s.get(1..)?),
198 b'+' => (false, s.get(1..)?),
199 _ => (false, s),
200 };
201 if rest.is_empty() {
202 return None;
203 }
204 let (int_part, frac_part) = match rest.split_once('.') {
205 Some((i, f)) => (i, f),
206 None => (rest, ""),
207 };
208 // An empty integer part (".5") is fine; anything non-numeric is not.
209 if !int_part.bytes().all(|b| b.is_ascii_digit()) || !frac_part.bytes().all(|b| b.is_ascii_digit())
210 {
211 return None;
212 }
213 let whole: i64 = if int_part.is_empty() { 0 } else { int_part.parse().ok()? };
214
215 let mut frac: i64 = 0;
216 for i in 0..8 {
217 let digit = frac_part.as_bytes().get(i).map_or(0, |b| (b - b'0') as i64);
218 frac = frac * 10 + digit;
219 }
220 let v = whole.checked_mul(100_000_000)?.checked_add(frac)?;
221 Some(if neg { -v } else { v })
222}
223
224/// Read a whole dump, calling `sink` for every record that survives parsing.
225///
226/// Returns `(rows read, records emitted)`. Malformed rows are counted, not fatal: a bulk dump
227/// of hundreds of millions of lines will have some, and aborting the ingest over one is worse
228/// than skipping it. A malformed *header* is fatal, because that means every row is being
229/// misread.
230pub fn read_dump<R: BufRead>(
231 input: R,
232 kind: Kind,
233 source: Source,
234 mut sink: impl FnMut(Record) -> io::Result<()>,
235) -> io::Result<(u64, u64, u64)> {
236 let mut lines = input.lines();
237 let header = lines
238 .next()
239 .transpose()?
240 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty dump"))?;
241 let schema = Schema::from_header(kind, &header)
242 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{e}: {header:?}")))?;
243
244 let (mut rows, mut emitted, mut skipped) = (0u64, 0u64, 0u64);
245 for line in lines {
246 let line = line?;
247 if line.trim().is_empty() {
248 continue;
249 }
250 rows += 1;
251 match schema.parse_row(&line, source) {
252 Ok(Some(r)) => {
253 sink(r)?;
254 emitted += 1;
255 }
256 Ok(None) | Err(_) => skipped += 1,
257 }
258 }
259 Ok((rows, emitted, skipped))
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 #[test]
267 fn degrees_parse_exactly_without_going_through_f64() {
268 assert_eq!(parse_degrees("0"), Some(0));
269 assert_eq!(parse_degrees("1"), Some(100_000_000));
270 assert_eq!(parse_degrees("-1"), Some(-100_000_000));
271 assert_eq!(parse_degrees("37.774930"), Some(3_777_493_000));
272 assert_eq!(parse_degrees("-122.41942"), Some(-12_241_942_000));
273 assert_eq!(parse_degrees("+51.5"), Some(5_150_000_000));
274 assert_eq!(parse_degrees(".5"), Some(50_000_000));
275 assert_eq!(parse_degrees("-0.00000001"), Some(-1));
276 // More precision than the field holds is truncated, not rounded up into a lie.
277 assert_eq!(parse_degrees("1.123456789"), Some(112_345_678));
278 // 90 and 180 exactly, the range endpoints.
279 assert_eq!(parse_degrees("90"), Some(9_000_000_000));
280 assert_eq!(parse_degrees("-180"), Some(-18_000_000_000));
281 }
282
283 #[test]
284 fn malformed_degrees_are_rejected() {
285 for bad in ["", " ", "-", "+", "abc", "1.2.3", "1e5", "--1", "1,5", "nan"] {
286 assert_eq!(parse_degrees(bad), None, "{bad:?} must not parse");
287 }
288 }
289
290 #[test]
291 fn csv_splitting_handles_quotes() {
292 assert_eq!(split_csv("a,b,c"), vec!["a", "b", "c"]);
293 assert_eq!(split_csv("a,,c"), vec!["a", "", "c"]);
294 assert_eq!(split_csv(r#"a,"b,c",d"#), vec!["a", "b,c", "d"]);
295 assert_eq!(split_csv(r#""a""b",c"#), vec![r#"a"b"#, "c"]);
296 assert_eq!(split_csv("a,b\r\n"), vec!["a", "b"]);
297 }
298
299 #[test]
300 fn opencellid_header_resolves() {
301 let header = "radio,mcc,net,area,cell,unit,lon,lat,range,samples,changeable,created,updated,averageSignal";
302 let s = Schema::from_header(Kind::Cell, header).unwrap();
303 let row = "LTE,310,260,4242,123456789,0,-122.41942,37.774930,650,12,1,0,0,-90";
304 let r = s.parse_row(row, Source::OpenCellId).unwrap().unwrap();
305 assert_eq!(r.lat_e8, 3_777_493_000);
306 assert_eq!(r.lon_e8, -12_241_942_000);
307 assert_eq!(r.accuracy_m, 650);
308 assert_eq!(
309 r.key,
310 keys::cell_key(&CellId {
311 mcc: 310,
312 mnc: 260,
313 radio: RadioType::Lte,
314 cell_id: 123456789,
315 area: 4242,
316 })
317 );
318 }
319
320 #[test]
321 fn a_wifi_header_resolves_under_either_spelling() {
322 for header in ["bssid,lat,lon,accuracy", "mac,latitude,longitude,radius"] {
323 let s = Schema::from_header(Kind::Wifi, header).unwrap();
324 let r = s
325 .parse_row("00:11:22:33:44:55,37.774930,-122.41942,20", Source::Beacondb)
326 .unwrap()
327 .unwrap();
328 assert_eq!(r.key, 0x001122334455);
329 assert_eq!(r.accuracy_m, 20);
330 }
331 }
332
333 #[test]
334 fn a_missing_column_is_a_hard_error_not_a_wrong_guess() {
335 assert!(Schema::from_header(Kind::Wifi, "lat,lon").is_err());
336 assert!(Schema::from_header(Kind::Cell, "mcc,net,area,cell,lat,lon").is_err());
337 assert!(Schema::from_header(Kind::Cell, "radio,mcc,net,cell,lat,lon").is_err());
338 }
339
340 #[test]
341 fn rows_the_store_cannot_represent_are_skipped_not_truncated() {
342 let s = Schema::from_header(Kind::Cell, "radio,mcc,net,area,cell,lon,lat,range").unwrap();
343 // 5G NCI wider than 36 bits.
344 let too_wide = format!("NR,310,260,1,{},1.0,1.0,100", 1u64 << 37);
345 assert_eq!(s.parse_row(&too_wide, Source::OpenCellId).unwrap(), None);
346 // CDMA has no identity of this shape.
347 assert_eq!(s.parse_row("CDMA,310,260,1,5,1.0,1.0,100", Source::OpenCellId).unwrap(), None);
348 // Out of range coordinates.
349 assert_eq!(s.parse_row("LTE,310,260,1,5,1.0,91.0,100", Source::OpenCellId).unwrap(), None);
350 // A zero cell id is a placeholder, not a cell.
351 assert_eq!(s.parse_row("LTE,310,260,1,0,1.0,1.0,100", Source::OpenCellId).unwrap(), None);
352 }
353
354 #[test]
355 fn a_blank_accuracy_is_unknown_rather_than_zero() {
356 let s = Schema::from_header(Kind::Wifi, "bssid,lat,lon,accuracy").unwrap();
357 let r = s.parse_row("00:11:22:33:44:55,1.0,1.0,", Source::Beacondb).unwrap().unwrap();
358 assert_eq!(r.accuracy_m, ACC_UNKNOWN);
359 }
360
361 #[test]
362 fn a_dump_reads_end_to_end_and_counts_what_it_skipped() {
363 let dump = "bssid,lat,lon,accuracy\n\
364 00:11:22:33:44:55,37.774930,-122.41942,20\n\
365 garbage\n\
366 \n\
367 00:11:22:33:44:56,51.5,-0.1276,15\n\
368 zz:11:22:33:44:57,1.0,1.0,5\n";
369 let mut got = Vec::new();
370 let (rows, emitted, skipped) =
371 read_dump(dump.as_bytes(), Kind::Wifi, Source::Beacondb, |r| {
372 got.push(r);
373 Ok(())
374 })
375 .unwrap();
376 assert_eq!((rows, emitted, skipped), (4, 2, 2));
377 assert_eq!(got.len(), 2);
378 }
379
380 #[test]
381 fn a_bad_header_is_fatal() {
382 let dump = "wat,who\n1,2\n";
383 let err = read_dump(dump.as_bytes(), Kind::Wifi, Source::Beacondb, |_| Ok(()));
384 assert!(err.is_err(), "a misread header would misread every row");
385 }
386}