Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / src / frontier.rs
frontier.rs391 lines · 13.3 KiBRaw
| 1 | //! Resumable crawl state: which BSSIDs have been seen, and which are still to be queried. |
| 2 | //! |
| 3 | //! A planet crawl runs for weeks and will be interrupted — by a reboot, a network outage, or |
| 4 | //! somebody pressing Ctrl-C. Losing the frontier would mean restarting from the seed, so both |
| 5 | //! halves of the state are on disk and both are safe to reload mid-run. |
| 6 | //! |
| 7 | //! ## Why the seen-set is approximate |
| 8 | //! |
| 9 | //! An exact set of a billion 48-bit keys is tens of gigabytes of hash table. A Bloom filter of |
| 10 | //! the same cardinality is about 1.2 GB at a 1% false-positive rate, and the cost of a false |
| 11 | //! positive here is that one BSSID never gets queried directly. That is nearly free: the |
| 12 | //! crawl reaches almost every AP as a *neighbour* in somebody else's response, so a skipped |
| 13 | //! query loses a small amount of expansion, not the beacon. Trading a rare missed query for |
| 14 | //! twenty times less memory is the right way round. |
| 15 | //! |
| 16 | //! Records themselves are never deduplicated here — that is `wps_build`'s job, working over |
| 17 | //! the sorted whole, where it can be exact. |
| 18 | |
| 19 | use std::fs::{File, OpenOptions}; |
| 20 | use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write}; |
| 21 | use std::path::{Path, PathBuf}; |
| 22 | |
| 23 | /// Bits per expected element, giving roughly a 1% false-positive rate at two hashes. |
| 24 | const BITS_PER_ELEMENT: u64 = 10; |
| 25 | |
| 26 | const SEEN_MAGIC: &[u8; 8] = b"WPSSEEN1"; |
| 27 | const QUEUE_MAGIC: &[u8; 8] = b"WPSQUE01"; |
| 28 | |
| 29 | fn mix(mut z: u64) -> u64 { |
| 30 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9); |
| 31 | z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB); |
| 32 | z ^ (z >> 31) |
| 33 | } |
| 34 | |
| 35 | /// Approximate membership over the BSSIDs the crawl has already encountered. |
| 36 | pub struct SeenSet { |
| 37 | bits: Vec<u64>, |
| 38 | nbits: u64, |
| 39 | inserted: u64, |
| 40 | path: PathBuf, |
| 41 | } |
| 42 | |
| 43 | impl SeenSet { |
| 44 | /// Size for `expected` elements, or reload from `path` if it already holds a filter of the |
| 45 | /// same size. A size change starts a fresh filter rather than misreading the old one. |
| 46 | pub fn open(path: &Path, expected: u64) -> io::Result<SeenSet> { |
| 47 | let nbits = (expected.max(1) * BITS_PER_ELEMENT).next_power_of_two(); |
| 48 | let words = (nbits / 64) as usize; |
| 49 | |
| 50 | if path.exists() { |
| 51 | let mut f = BufReader::new(File::open(path)?); |
| 52 | let mut head = [0u8; 24]; |
| 53 | if f.read_exact(&mut head).is_ok() && &head[0..8] == SEEN_MAGIC { |
| 54 | let stored_bits = u64::from_le_bytes( |
| 55 | head[8..16].try_into().map_err(|_| bad("short seen header"))?, |
| 56 | ); |
| 57 | let inserted = u64::from_le_bytes( |
| 58 | head[16..24].try_into().map_err(|_| bad("short seen header"))?, |
| 59 | ); |
| 60 | if stored_bits == nbits { |
| 61 | let mut bits = vec![0u64; words]; |
| 62 | let mut buf = [0u8; 8]; |
| 63 | for w in bits.iter_mut() { |
| 64 | f.read_exact(&mut buf)?; |
| 65 | *w = u64::from_le_bytes(buf); |
| 66 | } |
| 67 | return Ok(SeenSet { bits, nbits, inserted, path: path.to_path_buf() }); |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | Ok(SeenSet { |
| 72 | bits: vec![0u64; words], |
| 73 | nbits, |
| 74 | inserted: 0, |
| 75 | path: path.to_path_buf(), |
| 76 | }) |
| 77 | } |
| 78 | |
| 79 | fn positions(&self, key: u64) -> (u64, u64) { |
| 80 | let h1 = mix(key); |
| 81 | let h2 = mix(key ^ 0x9E3779B97F4A7C15) | 1; |
| 82 | (h1 % self.nbits, h2 % self.nbits) |
| 83 | } |
| 84 | |
| 85 | /// Whether `key` has probably been seen. False positives are possible, false negatives are |
| 86 | /// not, which is the direction that keeps the crawl from looping. |
| 87 | pub fn contains(&self, key: u64) -> bool { |
| 88 | let (a, b) = self.positions(key); |
| 89 | self.get(a) && self.get(b) |
| 90 | } |
| 91 | |
| 92 | /// Record `key`. Returns whether it was new. |
| 93 | pub fn insert(&mut self, key: u64) -> bool { |
| 94 | let (a, b) = self.positions(key); |
| 95 | let had = self.get(a) && self.get(b); |
| 96 | self.set(a); |
| 97 | self.set(b); |
| 98 | if !had { |
| 99 | self.inserted += 1; |
| 100 | } |
| 101 | !had |
| 102 | } |
| 103 | |
| 104 | fn get(&self, bit: u64) -> bool { |
| 105 | self.bits.get((bit >> 6) as usize).is_some_and(|w| (w >> (bit & 63)) & 1 == 1) |
| 106 | } |
| 107 | |
| 108 | fn set(&mut self, bit: u64) { |
| 109 | if let Some(w) = self.bits.get_mut((bit >> 6) as usize) { |
| 110 | *w |= 1 << (bit & 63); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | /// How many distinct keys have been inserted, as the filter counts them. |
| 115 | pub fn len(&self) -> u64 { |
| 116 | self.inserted |
| 117 | } |
| 118 | |
| 119 | /// Whether nothing has been inserted. |
| 120 | pub fn is_empty(&self) -> bool { |
| 121 | self.inserted == 0 |
| 122 | } |
| 123 | |
| 124 | /// Estimated false-positive rate at the current load, for the crawl's status line. |
| 125 | pub fn false_positive_rate(&self) -> f64 { |
| 126 | let k = 2.0; |
| 127 | let exp = -(k * self.inserted as f64) / self.nbits as f64; |
| 128 | (1.0 - exp.exp()).powf(k) |
| 129 | } |
| 130 | |
| 131 | /// Write the filter out. Writes to a sibling temp file and renames, so an interrupted |
| 132 | /// checkpoint leaves the previous one intact rather than a half-written filter that would |
| 133 | /// load as garbage. |
| 134 | pub fn checkpoint(&self) -> io::Result<()> { |
| 135 | let tmp = self.path.with_extension("tmp"); |
| 136 | { |
| 137 | let mut f = BufWriter::new(File::create(&tmp)?); |
| 138 | f.write_all(SEEN_MAGIC)?; |
| 139 | f.write_all(&self.nbits.to_le_bytes())?; |
| 140 | f.write_all(&self.inserted.to_le_bytes())?; |
| 141 | for w in &self.bits { |
| 142 | f.write_all(&w.to_le_bytes())?; |
| 143 | } |
| 144 | f.flush()?; |
| 145 | } |
| 146 | std::fs::rename(&tmp, &self.path) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /// The queue of BSSIDs still to be queried: an append-only file plus a read cursor. |
| 151 | /// |
| 152 | /// Append-only because the crawl's whole shape is "every answer adds more questions", and a |
| 153 | /// file that only grows at one end and is consumed at the other never needs rewriting. The |
| 154 | /// cursor is a separate small file so checkpointing it is atomic on its own. |
| 155 | pub struct Frontier { |
| 156 | file: File, |
| 157 | path: PathBuf, |
| 158 | cursor_path: PathBuf, |
| 159 | /// Index of the next entry to hand out. |
| 160 | cursor: u64, |
| 161 | /// Number of entries appended. |
| 162 | len: u64, |
| 163 | } |
| 164 | |
| 165 | impl Frontier { |
| 166 | /// Open or create the queue at `path`, restoring the cursor from `path.cursor`. |
| 167 | pub fn open(path: &Path) -> io::Result<Frontier> { |
| 168 | let cursor_path = path.with_extension("cursor"); |
| 169 | let mut file = |
| 170 | OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path)?; |
| 171 | let size = file.seek(SeekFrom::End(0))?; |
| 172 | |
| 173 | if size == 0 { |
| 174 | file.write_all(QUEUE_MAGIC)?; |
| 175 | } else { |
| 176 | let _ = file.seek(SeekFrom::Start(0))?; |
| 177 | let mut magic = [0u8; 8]; |
| 178 | file.read_exact(&mut magic)?; |
| 179 | if &magic != QUEUE_MAGIC { |
| 180 | return Err(bad("frontier file is not a crawl queue")); |
| 181 | } |
| 182 | } |
| 183 | let len = size.saturating_sub(8) / 8; |
| 184 | |
| 185 | let cursor = std::fs::read(&cursor_path) |
| 186 | .ok() |
| 187 | .and_then(|b| b.get(0..8).map(|s| s.to_vec())) |
| 188 | .and_then(|b| b.try_into().ok()) |
| 189 | .map_or(0, u64::from_le_bytes) |
| 190 | .min(len); |
| 191 | |
| 192 | Ok(Frontier { file, path: path.to_path_buf(), cursor_path, cursor, len }) |
| 193 | } |
| 194 | |
| 195 | /// Append one BSSID. |
| 196 | pub fn push(&mut self, mac: u64) -> io::Result<()> { |
| 197 | let _ = self.file.seek(SeekFrom::End(0))?; |
| 198 | self.file.write_all(&mac.to_le_bytes())?; |
| 199 | self.len += 1; |
| 200 | Ok(()) |
| 201 | } |
| 202 | |
| 203 | /// Take up to `n` BSSIDs, advancing the cursor. |
| 204 | pub fn take(&mut self, n: usize) -> io::Result<Vec<u64>> { |
| 205 | let available = (self.len - self.cursor).min(n as u64) as usize; |
| 206 | if available == 0 { |
| 207 | return Ok(Vec::new()); |
| 208 | } |
| 209 | let _ = self.file.seek(SeekFrom::Start(8 + self.cursor * 8))?; |
| 210 | let mut buf = vec![0u8; available * 8]; |
| 211 | self.file.read_exact(&mut buf)?; |
| 212 | self.cursor += available as u64; |
| 213 | |
| 214 | let mut out = Vec::with_capacity(available); |
| 215 | for chunk in buf.chunks_exact(8) { |
| 216 | let mut a = [0u8; 8]; |
| 217 | a.copy_from_slice(chunk); |
| 218 | out.push(u64::from_le_bytes(a)); |
| 219 | } |
| 220 | Ok(out) |
| 221 | } |
| 222 | |
| 223 | /// Entries not yet handed out. |
| 224 | pub fn pending(&self) -> u64 { |
| 225 | self.len - self.cursor |
| 226 | } |
| 227 | |
| 228 | /// Entries appended over the queue's whole life. |
| 229 | pub fn total(&self) -> u64 { |
| 230 | self.len |
| 231 | } |
| 232 | |
| 233 | /// Flush the queue and persist the cursor. |
| 234 | /// |
| 235 | /// The queue is flushed *before* the cursor is written, so a crash between the two |
| 236 | /// re-queries some BSSIDs rather than skipping them. Re-querying is harmless; skipping |
| 237 | /// loses a branch of the crawl permanently. |
| 238 | pub fn checkpoint(&mut self) -> io::Result<()> { |
| 239 | self.file.sync_data()?; |
| 240 | let tmp = self.cursor_path.with_extension("cursor.tmp"); |
| 241 | std::fs::write(&tmp, self.cursor.to_le_bytes())?; |
| 242 | std::fs::rename(&tmp, &self.cursor_path) |
| 243 | } |
| 244 | |
| 245 | /// Path of the queue file, for status output. |
| 246 | pub fn path(&self) -> &Path { |
| 247 | &self.path |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | fn bad(msg: &str) -> io::Error { |
| 252 | io::Error::new(io::ErrorKind::InvalidData, msg.to_string()) |
| 253 | } |
| 254 | |
| 255 | #[cfg(test)] |
| 256 | mod tests { |
| 257 | use super::*; |
| 258 | |
| 259 | struct TempDir(PathBuf); |
| 260 | impl TempDir { |
| 261 | fn new(tag: &str) -> TempDir { |
| 262 | let p = std::env::temp_dir().join(format!("wpsfront-{tag}-{}", std::process::id())); |
| 263 | let _ = std::fs::remove_dir_all(&p); |
| 264 | std::fs::create_dir_all(&p).unwrap(); |
| 265 | TempDir(p) |
| 266 | } |
| 267 | } |
| 268 | impl Drop for TempDir { |
| 269 | fn drop(&mut self) { |
| 270 | let _ = std::fs::remove_dir_all(&self.0); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | #[test] |
| 275 | fn seen_set_never_reports_a_false_negative() { |
| 276 | let d = TempDir::new("seen"); |
| 277 | let mut s = SeenSet::open(&d.0.join("seen.bin"), 10_000).unwrap(); |
| 278 | let keys: Vec<u64> = (0..5000).map(|i| mix(i) & 0xFFFF_FFFF_FFFF).collect(); |
| 279 | for &k in &keys { |
| 280 | let _ = s.insert(k); |
| 281 | } |
| 282 | for &k in &keys { |
| 283 | assert!(s.contains(k), "{k:#x} was inserted but reads as absent"); |
| 284 | } |
| 285 | assert!(s.len() > 4900, "insert count should track distinct keys"); |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn seen_set_false_positive_rate_stays_near_the_design_point() { |
| 290 | let d = TempDir::new("fp"); |
| 291 | let mut s = SeenSet::open(&d.0.join("seen.bin"), 20_000).unwrap(); |
| 292 | for i in 0..20_000u64 { |
| 293 | let _ = s.insert(mix(i)); |
| 294 | } |
| 295 | let mut fp = 0; |
| 296 | for i in 0..20_000u64 { |
| 297 | if s.contains(mix(i ^ 0xDEAD_BEEF_0000_0000)) { |
| 298 | fp += 1; |
| 299 | } |
| 300 | } |
| 301 | let rate = fp as f64 / 20_000.0; |
| 302 | assert!(rate < 0.05, "false-positive rate {rate} is too high to be useful"); |
| 303 | } |
| 304 | |
| 305 | #[test] |
| 306 | fn seen_set_survives_a_checkpoint_and_reload() { |
| 307 | let d = TempDir::new("reload"); |
| 308 | let path = d.0.join("seen.bin"); |
| 309 | let keys: Vec<u64> = (0..1000).map(mix).collect(); |
| 310 | { |
| 311 | let mut s = SeenSet::open(&path, 10_000).unwrap(); |
| 312 | for &k in &keys { |
| 313 | let _ = s.insert(k); |
| 314 | } |
| 315 | s.checkpoint().unwrap(); |
| 316 | } |
| 317 | let s = SeenSet::open(&path, 10_000).unwrap(); |
| 318 | assert_eq!(s.len(), 1000); |
| 319 | for &k in &keys { |
| 320 | assert!(s.contains(k)); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | #[test] |
| 325 | fn resizing_starts_a_fresh_filter_rather_than_misreading_the_old_one() { |
| 326 | let d = TempDir::new("resize"); |
| 327 | let path = d.0.join("seen.bin"); |
| 328 | { |
| 329 | let mut s = SeenSet::open(&path, 10_000).unwrap(); |
| 330 | let _ = s.insert(42); |
| 331 | s.checkpoint().unwrap(); |
| 332 | } |
| 333 | let s = SeenSet::open(&path, 10_000_000).unwrap(); |
| 334 | assert_eq!(s.len(), 0); |
| 335 | assert!(s.is_empty()); |
| 336 | } |
| 337 | |
| 338 | #[test] |
| 339 | fn frontier_hands_out_entries_in_order_and_resumes() { |
| 340 | let d = TempDir::new("queue"); |
| 341 | let path = d.0.join("frontier.bin"); |
| 342 | { |
| 343 | let mut f = Frontier::open(&path).unwrap(); |
| 344 | for i in 0..100u64 { |
| 345 | f.push(i).unwrap(); |
| 346 | } |
| 347 | assert_eq!(f.take(10).unwrap(), (0..10).collect::<Vec<_>>()); |
| 348 | assert_eq!(f.pending(), 90); |
| 349 | f.checkpoint().unwrap(); |
| 350 | } |
| 351 | let mut f = Frontier::open(&path).unwrap(); |
| 352 | assert_eq!(f.total(), 100); |
| 353 | assert_eq!(f.pending(), 90); |
| 354 | assert_eq!(f.take(5).unwrap(), (10..15).collect::<Vec<_>>()); |
| 355 | } |
| 356 | |
| 357 | #[test] |
| 358 | fn an_uncheckpointed_cursor_repeats_work_rather_than_losing_it() { |
| 359 | let d = TempDir::new("nocheck"); |
| 360 | let path = d.0.join("frontier.bin"); |
| 361 | { |
| 362 | let mut f = Frontier::open(&path).unwrap(); |
| 363 | for i in 0..20u64 { |
| 364 | f.push(i).unwrap(); |
| 365 | } |
| 366 | f.checkpoint().unwrap(); |
| 367 | // Consume without checkpointing, then "crash". |
| 368 | assert_eq!(f.take(8).unwrap().len(), 8); |
| 369 | } |
| 370 | let mut f = Frontier::open(&path).unwrap(); |
| 371 | assert_eq!(f.take(1).unwrap(), vec![0], "must re-query, not skip past"); |
| 372 | } |
| 373 | |
| 374 | #[test] |
| 375 | fn taking_from_an_exhausted_frontier_yields_nothing() { |
| 376 | let d = TempDir::new("drained"); |
| 377 | let mut f = Frontier::open(&d.0.join("frontier.bin")).unwrap(); |
| 378 | f.push(1).unwrap(); |
| 379 | assert_eq!(f.take(10).unwrap(), vec![1]); |
| 380 | assert_eq!(f.take(10).unwrap(), Vec::<u64>::new()); |
| 381 | assert_eq!(f.pending(), 0); |
| 382 | } |
| 383 | |
| 384 | #[test] |
| 385 | fn a_foreign_file_is_refused() { |
| 386 | let d = TempDir::new("foreign"); |
| 387 | let path = d.0.join("frontier.bin"); |
| 388 | std::fs::write(&path, b"not a queue at all").unwrap(); |
| 389 | assert!(Frontier::open(&path).is_err()); |
| 390 | } |
| 391 | } |