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

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

seed.rs389 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::{Record, Source, ACC_UNKNOWN, ALT_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) => {
116 get(i)?.parse::<f64>().ok().map_or(ACC_UNKNOWN, |v| clamp_accuracy(v as i32))
117 }
118 None => ACC_UNKNOWN,
119 };
120
121 let key = match self.kind {
122 Kind::Wifi => {
123 let Some(mac) = keys::parse_mac(&get(self.mac)?.to_ascii_lowercase()) else {
124 return Ok(None);
125 };
126 keys::wifi_key(mac)
127 }
128 Kind::Cell => {
129 let radio = match self.radio.and_then(|i| get(i).ok()).and_then(RadioType::parse) {
130 Some(r) => r,
131 None => return Ok(None),
132 };
133 let id = CellId {
134 mcc: match get(self.mcc)?.parse() {
135 Ok(v) => v,
136 Err(_) => return Ok(None),
137 },
138 mnc: match get(self.mnc)?.parse() {
139 Ok(v) => v,
140 Err(_) => return Ok(None),
141 },
142 radio,
143 cell_id: match get(self.cell)?.parse() {
144 Ok(v) => v,
145 Err(_) => return Ok(None),
146 },
147 area: match get(self.area)?.parse() {
148 Ok(v) => v,
149 Err(_) => return Ok(None),
150 },
151 };
152 if !keys::cell_fits(&id) {
153 return Ok(None);
154 }
155 keys::cell_key(&id)
156 }
157 };
158
159 let record = Record { key, lat_e8, lon_e8, accuracy_m, altitude_m: ALT_UNKNOWN, source };
160 Ok(record.in_range().then_some(record))
161 }
162}
163
164/// Split one CSV line, honouring double-quoted fields.
165///
166/// Not a general CSV implementation: these dumps have no embedded newlines, and a field is
167/// either bare or wholly quoted.
168fn split_csv(line: &str) -> Vec<String> {
169 let mut out = Vec::new();
170 let mut cur = String::new();
171 let mut quoted = false;
172 let mut chars = line.trim_end_matches(['\r', '\n']).chars().peekable();
173 while let Some(c) = chars.next() {
174 match c {
175 '"' if quoted && chars.peek() == Some(&'"') => {
176 cur.push('"');
177 let _ = chars.next();
178 }
179 '"' => quoted = !quoted,
180 ',' if !quoted => out.push(std::mem::take(&mut cur)),
181 _ => cur.push(c),
182 }
183 }
184 out.push(cur);
185 out
186}
187
188/// Parse decimal degrees to degrees x 1e8, exactly.
189///
190/// Going through `f64` would round: `-122.41942` is not representable, so multiplying by 1e8
191/// and truncating can land a unit either side. Digits are shifted instead, which is both exact
192/// and immune to locale.
193pub fn parse_degrees(s: &str) -> Option<i64> {
194 let s = s.trim();
195 if s.is_empty() {
196 return None;
197 }
198 let (neg, rest) = match s.as_bytes().first()? {
199 b'-' => (true, s.get(1..)?),
200 b'+' => (false, s.get(1..)?),
201 _ => (false, s),
202 };
203 if rest.is_empty() {
204 return None;
205 }
206 let (int_part, frac_part) = match rest.split_once('.') {
207 Some((i, f)) => (i, f),
208 None => (rest, ""),
209 };
210 // An empty integer part (".5") is fine; anything non-numeric is not.
211 if !int_part.bytes().all(|b| b.is_ascii_digit())
212 || !frac_part.bytes().all(|b| b.is_ascii_digit())
213 {
214 return None;
215 }
216 let whole: i64 = if int_part.is_empty() { 0 } else { int_part.parse().ok()? };
217
218 let mut frac: i64 = 0;
219 for i in 0..8 {
220 let digit = frac_part.as_bytes().get(i).map_or(0, |b| (b - b'0') as i64);
221 frac = frac * 10 + digit;
222 }
223 let v = whole.checked_mul(100_000_000)?.checked_add(frac)?;
224 Some(if neg { -v } else { v })
225}
226
227/// Read a whole dump, calling `sink` for every record that survives parsing.
228///
229/// Returns `(rows read, records emitted)`. Malformed rows are counted, not fatal: a bulk dump
230/// of hundreds of millions of lines will have some, and aborting the ingest over one is worse
231/// than skipping it. A malformed *header* is fatal, because that means every row is being
232/// misread.
233pub fn read_dump<R: BufRead>(
234 input: R,
235 kind: Kind,
236 source: Source,
237 mut sink: impl FnMut(Record) -> io::Result<()>,
238) -> io::Result<(u64, u64, u64)> {
239 let mut lines = input.lines();
240 let header = lines
241 .next()
242 .transpose()?
243 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty dump"))?;
244 let schema = Schema::from_header(kind, &header)
245 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{e}: {header:?}")))?;
246
247 let (mut rows, mut emitted, mut skipped) = (0u64, 0u64, 0u64);
248 for line in lines {
249 let line = line?;
250 if line.trim().is_empty() {
251 continue;
252 }
253 rows += 1;
254 match schema.parse_row(&line, source) {
255 Ok(Some(r)) => {
256 sink(r)?;
257 emitted += 1;
258 }
259 Ok(None) | Err(_) => skipped += 1,
260 }
261 }
262 Ok((rows, emitted, skipped))
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268
269 #[test]
270 fn degrees_parse_exactly_without_going_through_f64() {
271 assert_eq!(parse_degrees("0"), Some(0));
272 assert_eq!(parse_degrees("1"), Some(100_000_000));
273 assert_eq!(parse_degrees("-1"), Some(-100_000_000));
274 assert_eq!(parse_degrees("37.774930"), Some(3_777_493_000));
275 assert_eq!(parse_degrees("-122.41942"), Some(-12_241_942_000));
276 assert_eq!(parse_degrees("+51.5"), Some(5_150_000_000));
277 assert_eq!(parse_degrees(".5"), Some(50_000_000));
278 assert_eq!(parse_degrees("-0.00000001"), Some(-1));
279 // More precision than the field holds is truncated, not rounded up into a lie.
280 assert_eq!(parse_degrees("1.123456789"), Some(112_345_678));
281 // 90 and 180 exactly, the range endpoints.
282 assert_eq!(parse_degrees("90"), Some(9_000_000_000));
283 assert_eq!(parse_degrees("-180"), Some(-18_000_000_000));
284 }
285
286 #[test]
287 fn malformed_degrees_are_rejected() {
288 for bad in ["", " ", "-", "+", "abc", "1.2.3", "1e5", "--1", "1,5", "nan"] {
289 assert_eq!(parse_degrees(bad), None, "{bad:?} must not parse");
290 }
291 }
292
293 #[test]
294 fn csv_splitting_handles_quotes() {
295 assert_eq!(split_csv("a,b,c"), vec!["a", "b", "c"]);
296 assert_eq!(split_csv("a,,c"), vec!["a", "", "c"]);
297 assert_eq!(split_csv(r#"a,"b,c",d"#), vec!["a", "b,c", "d"]);
298 assert_eq!(split_csv(r#""a""b",c"#), vec![r#"a"b"#, "c"]);
299 assert_eq!(split_csv("a,b\r\n"), vec!["a", "b"]);
300 }
301
302 #[test]
303 fn opencellid_header_resolves() {
304 let header = "radio,mcc,net,area,cell,unit,lon,lat,range,samples,changeable,created,updated,averageSignal";
305 let s = Schema::from_header(Kind::Cell, header).unwrap();
306 let row = "LTE,310,260,4242,123456789,0,-122.41942,37.774930,650,12,1,0,0,-90";
307 let r = s.parse_row(row, Source::OpenCellId).unwrap().unwrap();
308 assert_eq!(r.lat_e8, 3_777_493_000);
309 assert_eq!(r.lon_e8, -12_241_942_000);
310 assert_eq!(r.accuracy_m, 650);
311 assert_eq!(
312 r.key,
313 keys::cell_key(&CellId {
314 mcc: 310,
315 mnc: 260,
316 radio: RadioType::Lte,
317 cell_id: 123456789,
318 area: 4242,
319 })
320 );
321 }
322
323 #[test]
324 fn a_wifi_header_resolves_under_either_spelling() {
325 for header in ["bssid,lat,lon,accuracy", "mac,latitude,longitude,radius"] {
326 let s = Schema::from_header(Kind::Wifi, header).unwrap();
327 let r = s
328 .parse_row("00:11:22:33:44:55,37.774930,-122.41942,20", Source::Beacondb)
329 .unwrap()
330 .unwrap();
331 assert_eq!(r.key, 0x001122334455);
332 assert_eq!(r.accuracy_m, 20);
333 }
334 }
335
336 #[test]
337 fn a_missing_column_is_a_hard_error_not_a_wrong_guess() {
338 assert!(Schema::from_header(Kind::Wifi, "lat,lon").is_err());
339 assert!(Schema::from_header(Kind::Cell, "mcc,net,area,cell,lat,lon").is_err());
340 assert!(Schema::from_header(Kind::Cell, "radio,mcc,net,cell,lat,lon").is_err());
341 }
342
343 #[test]
344 fn rows_the_store_cannot_represent_are_skipped_not_truncated() {
345 let s = Schema::from_header(Kind::Cell, "radio,mcc,net,area,cell,lon,lat,range").unwrap();
346 // 5G NCI wider than 36 bits.
347 let too_wide = format!("NR,310,260,1,{},1.0,1.0,100", 1u64 << 37);
348 assert_eq!(s.parse_row(&too_wide, Source::OpenCellId).unwrap(), None);
349 // CDMA has no identity of this shape.
350 assert_eq!(s.parse_row("CDMA,310,260,1,5,1.0,1.0,100", Source::OpenCellId).unwrap(), None);
351 // Out of range coordinates.
352 assert_eq!(s.parse_row("LTE,310,260,1,5,1.0,91.0,100", Source::OpenCellId).unwrap(), None);
353 // A zero cell id is a placeholder, not a cell.
354 assert_eq!(s.parse_row("LTE,310,260,1,0,1.0,1.0,100", Source::OpenCellId).unwrap(), None);
355 }
356
357 #[test]
358 fn a_blank_accuracy_is_unknown_rather_than_zero() {
359 let s = Schema::from_header(Kind::Wifi, "bssid,lat,lon,accuracy").unwrap();
360 let r = s.parse_row("00:11:22:33:44:55,1.0,1.0,", Source::Beacondb).unwrap().unwrap();
361 assert_eq!(r.accuracy_m, ACC_UNKNOWN);
362 }
363
364 #[test]
365 fn a_dump_reads_end_to_end_and_counts_what_it_skipped() {
366 let dump = "bssid,lat,lon,accuracy\n\
367 00:11:22:33:44:55,37.774930,-122.41942,20\n\
368 garbage\n\
369 \n\
370 00:11:22:33:44:56,51.5,-0.1276,15\n\
371 zz:11:22:33:44:57,1.0,1.0,5\n";
372 let mut got = Vec::new();
373 let (rows, emitted, skipped) =
374 read_dump(dump.as_bytes(), Kind::Wifi, Source::Beacondb, |r| {
375 got.push(r);
376 Ok(())
377 })
378 .unwrap();
379 assert_eq!((rows, emitted, skipped), (4, 2, 2));
380 assert_eq!(got.len(), 2);
381 }
382
383 #[test]
384 fn a_bad_header_is_fatal() {
385 let dump = "wat,who\n1,2\n";
386 let err = read_dump(dump.as_bytes(), Kind::Wifi, Source::Beacondb, |_| Ok(()));
387 assert!(err.is_err(), "a misread header would misread every row");
388 }
389}