Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / src / progress.rs
progress.rs334 lines · 11.0 KiBRaw
| 1 | //! Crawl progress accounting and the status line. |
| 2 | //! |
| 3 | //! Split out from the crawler so the rate arithmetic and formatting can be tested without |
| 4 | //! making a single request. |
| 5 | //! |
| 6 | //! Two things this gets right that a naive counter does not: |
| 7 | //! |
| 8 | //! * **Rate is reported over a recent window as well as for the whole run.** A crawl that has |
| 9 | //! been backing off for ten minutes still has a healthy-looking lifetime average, which is |
| 10 | //! exactly when you want to know it has stalled. |
| 11 | //! * **Status is emitted on a timer, not every N queries.** Tying output to query count means |
| 12 | //! a crawl that has stopped making progress also stops telling you anything. |
| 13 | |
| 14 | use std::time::{Duration, Instant}; |
| 15 | |
| 16 | /// Why a request failed, counted separately because they mean different things: a 400 is the |
| 17 | /// protocol being wrong, a transport error is the network, and a malformed body is the service |
| 18 | /// answering with something unexpected. |
| 19 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 20 | pub enum FailKind { |
| 21 | /// HTTP 400 — almost always a malformed request, i.e. the protocol has drifted. |
| 22 | BadRequest, |
| 23 | /// Any other HTTP status. |
| 24 | Status, |
| 25 | /// Connection refused, timed out, DNS, TLS. |
| 26 | Transport, |
| 27 | /// A 200 whose body could not be read as a response. |
| 28 | Malformed, |
| 29 | } |
| 30 | |
| 31 | /// Running totals for one crawl. |
| 32 | pub struct Progress { |
| 33 | started: Instant, |
| 34 | last_print: Instant, |
| 35 | interval: Duration, |
| 36 | window_started: Instant, |
| 37 | window_queries: u64, |
| 38 | |
| 39 | /// Successful requests. |
| 40 | pub queries: u64, |
| 41 | /// Requests made, including failures. |
| 42 | pub attempts: u64, |
| 43 | /// BSSIDs seen for the first time. |
| 44 | pub discovered: u64, |
| 45 | /// Observations written to the shard. |
| 46 | pub observations: u64, |
| 47 | /// Failed requests. |
| 48 | pub failures: u64, |
| 49 | /// HTTP 400s specifically. |
| 50 | pub bad_requests: u64, |
| 51 | /// Other HTTP statuses. |
| 52 | pub bad_status: u64, |
| 53 | /// Transport errors. |
| 54 | pub transport_errors: u64, |
| 55 | /// Unreadable response bodies. |
| 56 | pub malformed: u64, |
| 57 | } |
| 58 | |
| 59 | impl Progress { |
| 60 | /// Start accounting, printing a status line no more often than every `interval`. |
| 61 | pub fn new(interval: Duration) -> Progress { |
| 62 | let now = Instant::now(); |
| 63 | Progress { |
| 64 | started: now, |
| 65 | last_print: now, |
| 66 | interval, |
| 67 | window_started: now, |
| 68 | window_queries: 0, |
| 69 | queries: 0, |
| 70 | attempts: 0, |
| 71 | discovered: 0, |
| 72 | observations: 0, |
| 73 | failures: 0, |
| 74 | bad_requests: 0, |
| 75 | bad_status: 0, |
| 76 | transport_errors: 0, |
| 77 | malformed: 0, |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Record a successful request. |
| 82 | pub fn success(&mut self, observations: u64, discovered: u64) { |
| 83 | self.attempts += 1; |
| 84 | self.queries += 1; |
| 85 | self.window_queries += 1; |
| 86 | self.observations += observations; |
| 87 | self.discovered += discovered; |
| 88 | } |
| 89 | |
| 90 | /// Record a failed request. |
| 91 | pub fn failure(&mut self, kind: FailKind) { |
| 92 | self.attempts += 1; |
| 93 | self.failures += 1; |
| 94 | match kind { |
| 95 | FailKind::BadRequest => self.bad_requests += 1, |
| 96 | FailKind::Status => self.bad_status += 1, |
| 97 | FailKind::Transport => self.transport_errors += 1, |
| 98 | FailKind::Malformed => self.malformed += 1, |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// Whether enough time has passed to print again. Resets the timer when it says yes. |
| 103 | pub fn should_print(&mut self) -> bool { |
| 104 | if self.last_print.elapsed() >= self.interval { |
| 105 | self.last_print = Instant::now(); |
| 106 | true |
| 107 | } else { |
| 108 | false |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// Requests per second over the whole run. |
| 113 | pub fn overall_rate(&self) -> f64 { |
| 114 | rate(self.queries, self.started.elapsed()) |
| 115 | } |
| 116 | |
| 117 | /// Requests per second since the last window reset. |
| 118 | pub fn window_rate(&self) -> f64 { |
| 119 | rate(self.window_queries, self.window_started.elapsed()) |
| 120 | } |
| 121 | |
| 122 | /// Begin a new rate window. Called after printing, so each line's window rate covers the |
| 123 | /// period since the previous line. |
| 124 | pub fn reset_window(&mut self) { |
| 125 | self.window_started = Instant::now(); |
| 126 | self.window_queries = 0; |
| 127 | } |
| 128 | |
| 129 | /// How long the crawl has been running. |
| 130 | pub fn elapsed(&self) -> Duration { |
| 131 | self.started.elapsed() |
| 132 | } |
| 133 | |
| 134 | /// New BSSIDs per successful query. Falling towards zero means the crawl is re-treading |
| 135 | /// ground it has already covered. |
| 136 | pub fn discovery_per_query(&self) -> f64 { |
| 137 | if self.queries == 0 { |
| 138 | 0.0 |
| 139 | } else { |
| 140 | self.discovered as f64 / self.queries as f64 |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// The periodic status line. |
| 145 | pub fn line(&self, pending: u64, fp_rate: f64) -> String { |
| 146 | let mut s = format!( |
| 147 | "[{}] {} q ({:.2}/s, now {:.2}/s) | new {} ({:.0}/q) | pending {} | obs {} | fail {}", |
| 148 | hms(self.elapsed()), |
| 149 | count(self.queries), |
| 150 | self.overall_rate(), |
| 151 | self.window_rate(), |
| 152 | count(self.discovered), |
| 153 | self.discovery_per_query(), |
| 154 | count(pending), |
| 155 | count(self.observations), |
| 156 | count(self.failures), |
| 157 | ); |
| 158 | if self.failures > 0 { |
| 159 | s.push_str(&format!( |
| 160 | " ({}x400 {}xhttp {}xnet {}xbad)", |
| 161 | self.bad_requests, self.bad_status, self.transport_errors, self.malformed |
| 162 | )); |
| 163 | } |
| 164 | s.push_str(&format!(" | seen fp {:.2}%", fp_rate * 100.0)); |
| 165 | s |
| 166 | } |
| 167 | |
| 168 | /// The closing summary. |
| 169 | pub fn summary(&self, pending: u64) -> String { |
| 170 | format!( |
| 171 | "Stopped after {} in {}: {} quer(ies) of {} attempt(s) at {:.2}/s, \ |
| 172 | {} new BSSID(s), {} observation(s) written, {} still pending", |
| 173 | count(self.attempts), |
| 174 | hms(self.elapsed()), |
| 175 | count(self.queries), |
| 176 | count(self.attempts), |
| 177 | self.overall_rate(), |
| 178 | count(self.discovered), |
| 179 | count(self.observations), |
| 180 | count(pending), |
| 181 | ) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | fn rate(n: u64, over: Duration) -> f64 { |
| 186 | let secs = over.as_secs_f64(); |
| 187 | if secs <= 0.0 { |
| 188 | 0.0 |
| 189 | } else { |
| 190 | n as f64 / secs |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | /// `HH:MM:SS`, growing past 24 hours rather than wrapping — a crawl runs for weeks. |
| 195 | pub fn hms(d: Duration) -> String { |
| 196 | let t = d.as_secs(); |
| 197 | format!("{:02}:{:02}:{:02}", t / 3600, (t % 3600) / 60, t % 60) |
| 198 | } |
| 199 | |
| 200 | /// Short human count: `1.9M`, `312k`, `847`. |
| 201 | pub fn count(n: u64) -> String { |
| 202 | match n { |
| 203 | 0..=9_999 => n.to_string(), |
| 204 | 10_000..=999_999 => format!("{:.0}k", n as f64 / 1e3), |
| 205 | 1_000_000..=999_999_999 => format!("{:.2}M", n as f64 / 1e6), |
| 206 | _ => format!("{:.2}B", n as f64 / 1e9), |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | #[cfg(test)] |
| 211 | mod tests { |
| 212 | use super::*; |
| 213 | |
| 214 | #[test] |
| 215 | fn durations_format_and_do_not_wrap_at_a_day() { |
| 216 | assert_eq!(hms(Duration::from_secs(0)), "00:00:00"); |
| 217 | assert_eq!(hms(Duration::from_secs(59)), "00:00:59"); |
| 218 | assert_eq!(hms(Duration::from_secs(3661)), "01:01:01"); |
| 219 | // A week-long crawl must read as 170 hours, not as day 7 hour 2. |
| 220 | assert_eq!(hms(Duration::from_secs(612_000)), "170:00:00"); |
| 221 | } |
| 222 | |
| 223 | #[test] |
| 224 | fn counts_stay_readable_at_every_scale() { |
| 225 | assert_eq!(count(0), "0"); |
| 226 | assert_eq!(count(847), "847"); |
| 227 | assert_eq!(count(9_999), "9999"); |
| 228 | assert_eq!(count(312_400), "312k"); |
| 229 | assert_eq!(count(1_894_039), "1.89M"); |
| 230 | assert_eq!(count(287_460_836), "287.46M"); |
| 231 | assert_eq!(count(2_000_000_000), "2.00B"); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn failures_are_counted_by_kind() { |
| 236 | let mut p = Progress::new(Duration::from_secs(30)); |
| 237 | p.failure(FailKind::BadRequest); |
| 238 | p.failure(FailKind::BadRequest); |
| 239 | p.failure(FailKind::Transport); |
| 240 | p.failure(FailKind::Malformed); |
| 241 | p.failure(FailKind::Status); |
| 242 | assert_eq!(p.failures, 5); |
| 243 | assert_eq!(p.bad_requests, 2); |
| 244 | assert_eq!(p.transport_errors, 1); |
| 245 | assert_eq!(p.malformed, 1); |
| 246 | assert_eq!(p.bad_status, 1); |
| 247 | assert_eq!(p.attempts, 5, "failures are attempts too"); |
| 248 | assert_eq!(p.queries, 0, "but not successes"); |
| 249 | } |
| 250 | |
| 251 | #[test] |
| 252 | fn success_accumulates_observations_and_discoveries() { |
| 253 | let mut p = Progress::new(Duration::from_secs(30)); |
| 254 | p.success(108, 108); |
| 255 | p.success(104, 2); |
| 256 | assert_eq!(p.queries, 2); |
| 257 | assert_eq!(p.observations, 212); |
| 258 | assert_eq!(p.discovered, 110); |
| 259 | assert_eq!(p.discovery_per_query(), 55.0); |
| 260 | } |
| 261 | |
| 262 | #[test] |
| 263 | fn discovery_per_query_is_zero_before_any_query() { |
| 264 | assert_eq!(Progress::new(Duration::from_secs(1)).discovery_per_query(), 0.0); |
| 265 | } |
| 266 | |
| 267 | #[test] |
| 268 | fn rates_are_zero_rather_than_infinite_at_the_start() { |
| 269 | let p = Progress::new(Duration::from_secs(30)); |
| 270 | assert_eq!(p.overall_rate(), 0.0); |
| 271 | assert_eq!(p.window_rate(), 0.0); |
| 272 | assert_eq!(rate(5, Duration::ZERO), 0.0, "must not divide by zero"); |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn the_window_rate_tracks_recent_work_not_the_whole_run() { |
| 277 | let mut p = Progress::new(Duration::from_secs(30)); |
| 278 | for _ in 0..10 { |
| 279 | p.success(1, 1); |
| 280 | } |
| 281 | std::thread::sleep(Duration::from_millis(60)); |
| 282 | // Both see the same 10 queries so far. |
| 283 | assert!(p.window_rate() > 0.0); |
| 284 | |
| 285 | p.reset_window(); |
| 286 | std::thread::sleep(Duration::from_millis(60)); |
| 287 | // Nothing since the reset: the window has gone quiet even though the lifetime |
| 288 | // average is still healthy. This is the stall signal the lifetime rate hides. |
| 289 | assert_eq!(p.window_rate(), 0.0); |
| 290 | assert!(p.overall_rate() > 0.0); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn printing_is_rate_limited_by_time() { |
| 295 | let mut p = Progress::new(Duration::from_millis(80)); |
| 296 | assert!(!p.should_print(), "must not fire immediately"); |
| 297 | std::thread::sleep(Duration::from_millis(100)); |
| 298 | assert!(p.should_print()); |
| 299 | assert!(!p.should_print(), "the timer resets when it fires"); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn the_status_line_reports_what_matters() { |
| 304 | let mut p = Progress::new(Duration::from_secs(30)); |
| 305 | p.success(108, 108); |
| 306 | let line = p.line(1_894_039, 0.0123); |
| 307 | assert!(line.contains("1 q"), "{line}"); |
| 308 | assert!(line.contains("new 108"), "{line}"); |
| 309 | assert!(line.contains("pending 1.89M"), "{line}"); |
| 310 | assert!(line.contains("obs 108"), "{line}"); |
| 311 | assert!(line.contains("fail 0"), "{line}"); |
| 312 | assert!(line.contains("1.23%"), "{line}"); |
| 313 | assert!(!line.contains("x400"), "the breakdown is noise when nothing failed: {line}"); |
| 314 | } |
| 315 | |
| 316 | #[test] |
| 317 | fn the_status_line_breaks_down_failures_once_there_are_any() { |
| 318 | let mut p = Progress::new(Duration::from_secs(30)); |
| 319 | p.failure(FailKind::BadRequest); |
| 320 | let line = p.line(0, 0.0); |
| 321 | assert!(line.contains("fail 1"), "{line}"); |
| 322 | assert!(line.contains("1x400"), "{line}"); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn the_summary_distinguishes_attempts_from_successes() { |
| 327 | let mut p = Progress::new(Duration::from_secs(30)); |
| 328 | p.success(10, 10); |
| 329 | p.failure(FailKind::Transport); |
| 330 | let s = p.summary(42); |
| 331 | assert!(s.contains("1 quer(ies) of 2 attempt(s)"), "{s}"); |
| 332 | assert!(s.contains("42 still pending"), "{s}"); |
| 333 | } |
| 334 | } |