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

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

lib.rs112 lines · 3.6 KiBRaw
1//! Build the offline WiFi and cell beacon stores that `:networklocation` reads.
2//!
3//! Three stages, one binary each:
4//!
5//! | Binary | Does |
6//! | --- | --- |
7//! | `wps_seed` | Open bulk dumps (beacondb, OpenCelliD) -> record shards |
8//! | `wps_crawl` | Apple gs-loc snowball -> record shards, resumably |
9//! | `wps_build` | Shards -> a sorted, filtered, deduplicated `WPSDB2` store |
10//!
11//! The stages are separate processes because they have nothing in common operationally: a
12//! seed ingest is minutes, a planet crawl is weeks, and a build is hours of IO. Passing record
13//! shards between them means a crawl can be interrupted, resumed, extended, or merged with a
14//! newer dump without any stage knowing about the others.
15//!
16//! ## Where the accuracy comes from
17//!
18//! The store this writes keeps each beacon's coordinates as integer degrees x 1e8 — bit-exact
19//! against what the source reported — and its own horizontal accuracy, plus its altitude in
20//! metres when the source reports one (Apple's WiFi `location.5`; cell responses have no
21//! altitude field). The format it replaces quantized to a 20 m grid and carried no accuracy
22//! at all, so the device substituted one constant for every beacon and the solver's
23//! uncertainty weighting, which is fully implemented, had nothing to work with.
24
25#![deny(missing_docs)]
26
27pub mod frontier;
28pub mod gsloc;
29pub mod keys;
30pub mod probe;
31pub mod progress;
32pub mod proto;
33pub mod quality;
34pub mod record;
35pub mod seed;
36pub mod sort;
37pub mod store;
38pub mod store_extra;
39pub mod v1;
40
41use std::io::{self, BufRead, BufReader};
42use std::path::Path;
43use std::process::ExitCode;
44
45/// Shared `main` for the harvest binaries: parse, report usage on a parse
46/// error (exit success only for an explicit `help` request), then run and map
47/// the result onto the process exit code.
48pub fn run_main<A>(
49 parse_args: impl Fn(&[String]) -> Result<A, String>,
50 usage: &str,
51 run: impl Fn(&A) -> io::Result<()>,
52) -> ExitCode {
53 let argv: Vec<String> = std::env::args().skip(1).collect();
54 let args = match parse_args(&argv) {
55 Ok(a) => a,
56 Err(e) => {
57 if e != "help" {
58 eprintln!("error: {e}");
59 }
60 eprintln!("{usage}");
61 return if e == "help" { ExitCode::SUCCESS } else { ExitCode::FAILURE };
62 }
63 };
64 match run(&args) {
65 Ok(()) => ExitCode::SUCCESS,
66 Err(e) => {
67 eprintln!("error: {e}");
68 ExitCode::FAILURE
69 }
70 }
71}
72
73/// Open a path for buffered reading, or stdin when it is `-`.
74///
75/// Bulk dumps ship gzipped and are piped in (`gunzip -c dump.csv.gz | wps_seed -`) rather than
76/// decompressed in process, which keeps a decompressor out of the dependency list.
77pub fn open_input(path: &str) -> io::Result<Box<dyn BufRead>> {
78 if path == "-" {
79 Ok(Box::new(BufReader::new(io::stdin())))
80 } else {
81 Ok(Box::new(BufReader::with_capacity(1 << 20, std::fs::File::open(Path::new(path))?)))
82 }
83}
84
85/// Format a byte count for a status line.
86pub fn human_bytes(n: u64) -> String {
87 const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
88 let mut v = n as f64;
89 let mut u = 0;
90 while v >= 1024.0 && u + 1 < UNITS.len() {
91 v /= 1024.0;
92 u += 1;
93 }
94 if u == 0 {
95 format!("{n} B")
96 } else {
97 format!("{v:.2} {}", UNITS[u])
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104
105 #[test]
106 fn byte_counts_are_readable() {
107 assert_eq!(human_bytes(0), "0 B");
108 assert_eq!(human_bytes(1023), "1023 B");
109 assert_eq!(human_bytes(1024), "1.00 KiB");
110 assert_eq!(human_bytes(13_400_000_000), "12.48 GiB");
111 }
112}