Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / src / bin / wps_build.rs
wps_build.rs235 lines · 8.0 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 | |
| 11 | use std::fs::File; |
| 12 | use std::io::{BufReader, BufWriter}; |
| 13 | use std::path::{Path, PathBuf}; |
| 14 | use std::process::ExitCode; |
| 15 | |
| 16 | use wps_harvest::keys; |
| 17 | use wps_harvest::quality::{self, Policy, Rejects}; |
| 18 | use wps_harvest::record::{Record, RecordReader, RecordWriter}; |
| 19 | use wps_harvest::sort::ExternalSort; |
| 20 | use wps_harvest::store::{self, KeyKind, DEFAULT_SAMPLE_LOG2}; |
| 21 | |
| 22 | const USAGE: &str = "\ |
| 23 | Usage: 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 | |
| 34 | struct 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 | |
| 44 | fn 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 = || argv.get(i + 1).cloned().ok_or_else(|| format!("{a} needs a value")); |
| 58 | match a { |
| 59 | "--kind" => { |
| 60 | kind = Some(match value()?.as_str() { |
| 61 | "wifi" => KeyKind::Wifi, |
| 62 | "cell" => KeyKind::Cell, |
| 63 | other => return Err(format!("unknown --kind '{other}'")), |
| 64 | }); |
| 65 | i += 2; |
| 66 | } |
| 67 | "--out" => { |
| 68 | out = Some(PathBuf::from(value()?)); |
| 69 | i += 2; |
| 70 | } |
| 71 | "--scratch" => { |
| 72 | scratch = Some(PathBuf::from(value()?)); |
| 73 | i += 2; |
| 74 | } |
| 75 | "--mover-threshold" => { |
| 76 | mover = Some(value()?.parse::<u32>().map_err(|e| e.to_string())?); |
| 77 | i += 2; |
| 78 | } |
| 79 | "--max-accuracy" => { |
| 80 | max_accuracy = Some(value()?.parse::<u16>().map_err(|e| e.to_string())?); |
| 81 | i += 2; |
| 82 | } |
| 83 | "--run-records" => { |
| 84 | run_records = value()?.parse::<usize>().map_err(|e| e.to_string())?; |
| 85 | i += 2; |
| 86 | } |
| 87 | "--no-verify" => { |
| 88 | verify = false; |
| 89 | i += 1; |
| 90 | } |
| 91 | "-h" | "--help" => return Err("help".to_string()), |
| 92 | other if other.starts_with("--") => return Err(format!("unknown option: {other}")), |
| 93 | other => { |
| 94 | shards.push(PathBuf::from(other)); |
| 95 | i += 1; |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | let kind = kind.ok_or("--kind is required")?; |
| 101 | let mut policy = match kind { |
| 102 | KeyKind::Wifi => Policy::wifi(), |
| 103 | KeyKind::Cell => Policy::cell(), |
| 104 | }; |
| 105 | if let Some(m) = mover { |
| 106 | policy.mover_threshold_m = m; |
| 107 | } |
| 108 | policy.max_accuracy_m = max_accuracy; |
| 109 | |
| 110 | if shards.is_empty() { |
| 111 | return Err("at least one input shard is required".to_string()); |
| 112 | } |
| 113 | Ok(Args { |
| 114 | kind, |
| 115 | out: out.ok_or("--out is required")?, |
| 116 | scratch: scratch.ok_or("--scratch is required")?, |
| 117 | policy, |
| 118 | run_records, |
| 119 | verify, |
| 120 | shards, |
| 121 | }) |
| 122 | } |
| 123 | |
| 124 | /// Sort every shard, reduce each key's observations, and write the survivors to `reduced`. |
| 125 | /// Returns the record count and what was rejected. |
| 126 | fn sort_and_reduce( |
| 127 | shards: &[PathBuf], |
| 128 | scratch: &Path, |
| 129 | policy: &Policy, |
| 130 | run_records: usize, |
| 131 | reduced: &Path, |
| 132 | ) -> std::io::Result<(u64, u64, Rejects)> { |
| 133 | let mut sorter = ExternalSort::new(scratch, run_records)?; |
| 134 | for path in shards { |
| 135 | let mut rd = RecordReader::new(BufReader::with_capacity(1 << 20, File::open(path)?)); |
| 136 | while let Some(r) = rd.next().transpose()? { |
| 137 | sorter.push(r)?; |
| 138 | } |
| 139 | println!(" read {} ({} observations so far)", path.display(), sorter.len()); |
| 140 | } |
| 141 | let observations = sorter.len(); |
| 142 | |
| 143 | let mut merge = sorter.finish()?; |
| 144 | let mut writer = RecordWriter::new(BufWriter::with_capacity(1 << 20, File::create(reduced)?)); |
| 145 | let mut rejects = Rejects::default(); |
| 146 | |
| 147 | // Equal keys arrive adjacent, so one group is one beacon and the whole group is visible at |
| 148 | // once - which is what makes the mover test possible at all. |
| 149 | let mut group: Vec<Record> = Vec::new(); |
| 150 | let flush = |group: &mut Vec<Record>, |
| 151 | writer: &mut RecordWriter<BufWriter<File>>, |
| 152 | rejects: &mut Rejects| |
| 153 | -> std::io::Result<()> { |
| 154 | if let Some(r) = quality::reduce(group, policy, rejects) { |
| 155 | writer.push(&r)?; |
| 156 | } |
| 157 | group.clear(); |
| 158 | Ok(()) |
| 159 | }; |
| 160 | |
| 161 | while let Some(r) = merge.next().transpose()? { |
| 162 | if group.first().is_some_and(|g| g.key != r.key) { |
| 163 | flush(&mut group, &mut writer, &mut rejects)?; |
| 164 | } |
| 165 | group.push(r); |
| 166 | } |
| 167 | flush(&mut group, &mut writer, &mut rejects)?; |
| 168 | |
| 169 | let kept = writer.finish()?; |
| 170 | Ok((observations, kept, rejects)) |
| 171 | } |
| 172 | |
| 173 | fn run(args: &Args) -> std::io::Result<()> { |
| 174 | std::fs::create_dir_all(&args.scratch)?; |
| 175 | let reduced = args.scratch.join("reduced.shard"); |
| 176 | |
| 177 | let started = std::time::Instant::now(); |
| 178 | let (observations, kept, rejects) = |
| 179 | sort_and_reduce(&args.shards, &args.scratch, &args.policy, args.run_records, &reduced)?; |
| 180 | |
| 181 | println!( |
| 182 | "{observations} observation(s) -> {kept} beacon(s) in {:.1}s", |
| 183 | started.elapsed().as_secs_f64() |
| 184 | ); |
| 185 | println!( |
| 186 | " rejected {} total: {} randomized MAC, {} mobile, {} out of range, {} too coarse", |
| 187 | rejects.total(), |
| 188 | rejects.randomized_mac, |
| 189 | rejects.mover, |
| 190 | rejects.out_of_range, |
| 191 | rejects.too_coarse |
| 192 | ); |
| 193 | |
| 194 | let universe_bits = match args.kind { |
| 195 | KeyKind::Wifi => keys::WIFI_UNIVERSE_BITS, |
| 196 | KeyKind::Cell => keys::CELL_UNIVERSE_BITS, |
| 197 | }; |
| 198 | |
| 199 | // Reduced records are already sorted and unique, which is what the writer requires. They |
| 200 | // are streamed back off disk rather than held: at planet scale this list is tens of GB. |
| 201 | let size = store::write_store( |
| 202 | &args.out, |
| 203 | &args.scratch, |
| 204 | args.kind, |
| 205 | universe_bits, |
| 206 | kept, |
| 207 | DEFAULT_SAMPLE_LOG2, |
| 208 | stream_shard(&reduced)?, |
| 209 | )?; |
| 210 | println!("Wrote {} ({})", args.out.display(), wps_harvest::human_bytes(size)); |
| 211 | if kept > 0 { |
| 212 | println!(" {:.1} bits per beacon", (size as f64 * 8.0) / kept as f64); |
| 213 | } |
| 214 | |
| 215 | if args.verify { |
| 216 | let t = std::time::Instant::now(); |
| 217 | let n = store::verify_store(&args.out, stream_shard(&reduced)?)?; |
| 218 | println!("Verified {n} record(s) in {:.1}s", t.elapsed().as_secs_f64()); |
| 219 | } else { |
| 220 | eprintln!("WARNING: --no-verify; the store was not read back"); |
| 221 | } |
| 222 | |
| 223 | let _ = std::fs::remove_file(&reduced); |
| 224 | Ok(()) |
| 225 | } |
| 226 | |
| 227 | /// Stream a shard as the `io::Result<Record>` sequence the store writer and verifier take. |
| 228 | fn stream_shard(path: &Path) -> std::io::Result<impl Iterator<Item = std::io::Result<Record>>> { |
| 229 | let rd = RecordReader::new(BufReader::with_capacity(1 << 20, File::open(path)?)); |
| 230 | Ok(rd) |
| 231 | } |
| 232 | |
| 233 | fn main() -> ExitCode { |
| 234 | wps_harvest::run_main(parse_args, USAGE, run) |
| 235 | } |