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

Modern-Apps.git / scripts / networklocation / wps_harvest / src / bin / wps_build.rs

wps_build.rs259 lines · 8.6 KiBRaw
1//! `wps_build --kind wifi|cell --out STORE --scratch DIR SHARD...`
2//!
3//! Merge every record shard into one `WPSDB2` store: sort by key, reduce each beacon's
4//! observations to at most one record, then write and verify.
5//!
6//! Two passes over the sorted data, because the Elias-Fano index needs the record count
7//! before it can choose its parameters. The first pass writes the reduced records to a scratch
8//! shard and counts them; the second streams that shard into the writer. Nothing proportional
9//! to the record count is ever held in memory.
10
11use std::fs::File;
12use std::io::{BufReader, BufWriter};
13use std::path::{Path, PathBuf};
14use std::process::ExitCode;
15
16use wps_harvest::keys;
17use wps_harvest::quality::{self, Policy, Rejects};
18use wps_harvest::record::{Record, RecordReader, RecordWriter};
19use wps_harvest::sort::ExternalSort;
20use wps_harvest::store::{self, KeyKind, DEFAULT_SAMPLE_LOG2};
21
22const USAGE: &str = "\
23Usage: wps_build --kind wifi|cell --out STORE --scratch DIR [options] SHARD...
24
25 --kind which store to build
26 --out .wpsdb path to write
27 --scratch directory for sort runs and intermediates (needs ~2x the store size)
28 --mover-threshold metres; a beacon seen further apart than this is dropped as mobile
29 (default 1000 for wifi, 20000 for cell)
30 --max-accuracy metres; drop observations less precise than this (default: keep all)
31 --run-records records held in memory per sort run (default 4000000, ~160 MiB)
32 --no-verify skip the read-back check (not recommended)";
33
34struct Args {
35 kind: KeyKind,
36 out: PathBuf,
37 scratch: PathBuf,
38 policy: Policy,
39 run_records: usize,
40 verify: bool,
41 shards: Vec<PathBuf>,
42}
43
44fn parse_args(argv: &[String]) -> Result<Args, String> {
45 let mut kind = None;
46 let mut out = None;
47 let mut scratch = None;
48 let mut mover = None;
49 let mut max_accuracy = None;
50 let mut run_records = 4_000_000usize;
51 let mut verify = true;
52 let mut shards = Vec::new();
53
54 let mut i = 0;
55 while i < argv.len() {
56 let a = argv[i].as_str();
57 let value = || {
58 argv.get(i + 1).cloned().ok_or_else(|| format!("{a} needs a value"))
59 };
60 match a {
61 "--kind" => {
62 kind = Some(match value()?.as_str() {
63 "wifi" => KeyKind::Wifi,
64 "cell" => KeyKind::Cell,
65 other => return Err(format!("unknown --kind '{other}'")),
66 });
67 i += 2;
68 }
69 "--out" => {
70 out = Some(PathBuf::from(value()?));
71 i += 2;
72 }
73 "--scratch" => {
74 scratch = Some(PathBuf::from(value()?));
75 i += 2;
76 }
77 "--mover-threshold" => {
78 mover = Some(value()?.parse::<u32>().map_err(|e| e.to_string())?);
79 i += 2;
80 }
81 "--max-accuracy" => {
82 max_accuracy = Some(value()?.parse::<u16>().map_err(|e| e.to_string())?);
83 i += 2;
84 }
85 "--run-records" => {
86 run_records = value()?.parse::<usize>().map_err(|e| e.to_string())?;
87 i += 2;
88 }
89 "--no-verify" => {
90 verify = false;
91 i += 1;
92 }
93 "-h" | "--help" => return Err("help".to_string()),
94 other if other.starts_with("--") => return Err(format!("unknown option: {other}")),
95 other => {
96 shards.push(PathBuf::from(other));
97 i += 1;
98 }
99 }
100 }
101
102 let kind = kind.ok_or("--kind is required")?;
103 let mut policy = match kind {
104 KeyKind::Wifi => Policy::wifi(),
105 KeyKind::Cell => Policy::cell(),
106 };
107 if let Some(m) = mover {
108 policy.mover_threshold_m = m;
109 }
110 policy.max_accuracy_m = max_accuracy;
111
112 if shards.is_empty() {
113 return Err("at least one input shard is required".to_string());
114 }
115 Ok(Args {
116 kind,
117 out: out.ok_or("--out is required")?,
118 scratch: scratch.ok_or("--scratch is required")?,
119 policy,
120 run_records,
121 verify,
122 shards,
123 })
124}
125
126/// Sort every shard, reduce each key's observations, and write the survivors to `reduced`.
127/// Returns the record count and what was rejected.
128fn sort_and_reduce(
129 shards: &[PathBuf],
130 scratch: &Path,
131 policy: &Policy,
132 run_records: usize,
133 reduced: &Path,
134) -> std::io::Result<(u64, u64, Rejects)> {
135 let mut sorter = ExternalSort::new(scratch, run_records)?;
136 for path in shards {
137 let mut rd = RecordReader::new(BufReader::with_capacity(1 << 20, File::open(path)?));
138 while let Some(r) = rd.next()? {
139 sorter.push(r)?;
140 }
141 println!(" read {} ({} observations so far)", path.display(), sorter.len());
142 }
143 let observations = sorter.len();
144
145 let mut merge = sorter.finish()?;
146 let mut writer = RecordWriter::new(BufWriter::with_capacity(1 << 20, File::create(reduced)?));
147 let mut rejects = Rejects::default();
148
149 // Equal keys arrive adjacent, so one group is one beacon and the whole group is visible at
150 // once - which is what makes the mover test possible at all.
151 let mut group: Vec<Record> = Vec::new();
152 let flush = |group: &mut Vec<Record>,
153 writer: &mut RecordWriter<BufWriter<File>>,
154 rejects: &mut Rejects|
155 -> std::io::Result<()> {
156 if let Some(r) = quality::reduce(group, policy, rejects) {
157 writer.push(&r)?;
158 }
159 group.clear();
160 Ok(())
161 };
162
163 while let Some(r) = merge.next()? {
164 if group.first().is_some_and(|g| g.key != r.key) {
165 flush(&mut group, &mut writer, &mut rejects)?;
166 }
167 group.push(r);
168 }
169 flush(&mut group, &mut writer, &mut rejects)?;
170
171 let kept = writer.finish()?;
172 Ok((observations, kept, rejects))
173}
174
175fn run(args: &Args) -> std::io::Result<()> {
176 std::fs::create_dir_all(&args.scratch)?;
177 let reduced = args.scratch.join("reduced.shard");
178
179 let started = std::time::Instant::now();
180 let (observations, kept, rejects) = sort_and_reduce(
181 &args.shards,
182 &args.scratch,
183 &args.policy,
184 args.run_records,
185 &reduced,
186 )?;
187
188 println!(
189 "{observations} observation(s) -> {kept} beacon(s) in {:.1}s",
190 started.elapsed().as_secs_f64()
191 );
192 println!(
193 " rejected {} total: {} randomized MAC, {} mobile, {} out of range, {} too coarse",
194 rejects.total(),
195 rejects.randomized_mac,
196 rejects.mover,
197 rejects.out_of_range,
198 rejects.too_coarse
199 );
200
201 let universe_bits = match args.kind {
202 KeyKind::Wifi => keys::WIFI_UNIVERSE_BITS,
203 KeyKind::Cell => keys::CELL_UNIVERSE_BITS,
204 };
205
206 // Reduced records are already sorted and unique, which is what the writer requires. They
207 // are streamed back off disk rather than held: at planet scale this list is tens of GB.
208 let size = store::write_store(
209 &args.out,
210 &args.scratch,
211 args.kind,
212 universe_bits,
213 kept,
214 DEFAULT_SAMPLE_LOG2,
215 stream_shard(&reduced)?,
216 )?;
217 println!("Wrote {} ({})", args.out.display(), wps_harvest::human_bytes(size));
218 if kept > 0 {
219 println!(" {:.1} bits per beacon", (size as f64 * 8.0) / kept as f64);
220 }
221
222 if args.verify {
223 let t = std::time::Instant::now();
224 let n = store::verify_store(&args.out, stream_shard(&reduced)?)?;
225 println!("Verified {n} record(s) in {:.1}s", t.elapsed().as_secs_f64());
226 } else {
227 eprintln!("WARNING: --no-verify; the store was not read back");
228 }
229
230 let _ = std::fs::remove_file(&reduced);
231 Ok(())
232}
233
234/// Stream a shard as the `io::Result<Record>` sequence the store writer and verifier take.
235fn stream_shard(path: &Path) -> std::io::Result<impl Iterator<Item = std::io::Result<Record>>> {
236 let mut rd = RecordReader::new(BufReader::with_capacity(1 << 20, File::open(path)?));
237 Ok(std::iter::from_fn(move || rd.next().transpose()))
238}
239
240fn main() -> ExitCode {
241 let argv: Vec<String> = std::env::args().skip(1).collect();
242 let args = match parse_args(&argv) {
243 Ok(a) => a,
244 Err(e) => {
245 if e != "help" {
246 eprintln!("error: {e}");
247 }
248 eprintln!("{USAGE}");
249 return if e == "help" { ExitCode::SUCCESS } else { ExitCode::FAILURE };
250 }
251 };
252 match run(&args) {
253 Ok(()) => ExitCode::SUCCESS,
254 Err(e) => {
255 eprintln!("error: {e}");
256 ExitCode::FAILURE
257 }
258 }
259}