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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / par.rs

par.rs105 lines · 3.7 KiBRaw
1//! The thread budget.
2//!
3//! Spelled the same way `osm_ingest::par` and `tile_build::par` spell it, so one
4//! `MAPS_THREADS` export governs a whole build and the fan-out in `build_all.sh`
5//! does not oversubscribe the box. `available_parallelism()` reports the whole
6//! machine to every process, so six concurrent tools each claiming 32 threads on a
7//! 32-core box finish slower than running in sequence.
8//!
9//! Unlike the other two crates this one has **no rayon**, and deliberately: this
10//! crate's documented property is zero external dependencies, and its parallel work
11//! is a handful of whole GTFS feeds per batch rather than millions of tiny items.
12//! One `std::thread::scope` per batch is all that shape needs; work stealing would
13//! buy nothing.
14
15use std::sync::atomic::{AtomicUsize, Ordering};
16
17/// 0 means "not set"; any other value is an explicit cap from `--threads`.
18static OVERRIDE: AtomicUsize = AtomicUsize::new(0);
19
20/// Cap the pool for the rest of the process. Called from `main` after parsing.
21pub fn set_threads(n: usize) {
22 OVERRIDE.store(n.max(1), Ordering::Relaxed);
23}
24
25/// Drop the override again, restoring the `MAPS_THREADS`-or-the-box default.
26///
27/// Not `#[cfg(test)]`: the binaries in this crate are separate compilation units, so
28/// a test in `transit_stops` cannot see the library's test-only items.
29pub fn clear_threads() {
30 OVERRIDE.store(0, Ordering::Relaxed);
31}
32
33/// Threads to use. `--threads` beats `MAPS_THREADS` beats the box.
34pub fn threads() -> usize {
35 resolve(
36 OVERRIDE.load(Ordering::Relaxed),
37 std::env::var("MAPS_THREADS").ok().as_deref(),
38 )
39}
40
41/// The precedence rule, split out so it can be tested without mutating the
42/// process-wide override or the environment.
43fn resolve(override_n: usize, env: Option<&str>) -> usize {
44 if override_n > 0 {
45 return override_n;
46 }
47 if let Some(n) = env_threads(env) {
48 return n;
49 }
50 std::thread::available_parallelism()
51 .map(|n| n.get())
52 .unwrap_or(4)
53}
54
55/// A malformed or non-positive `MAPS_THREADS` is ignored rather than fatal: it is
56/// usually exported once for a whole script run, and killing an eight-hour build
57/// over a typo in an environment variable serves nobody.
58fn env_threads(raw: Option<&str>) -> Option<usize> {
59 static WARNED: std::sync::Once = std::sync::Once::new();
60 let trimmed = raw?.trim();
61 match trimmed.parse::<usize>() {
62 Ok(n) if n > 0 => Some(n),
63 _ => {
64 WARNED.call_once(|| {
65 eprintln!("WARN: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)");
66 });
67 None
68 }
69 }
70}
71
72/// Parse a `--threads N` value.
73pub fn parse_threads(value: &str) -> std::result::Result<usize, String> {
74 value
75 .parse::<usize>()
76 .ok()
77 .filter(|n| *n > 0)
78 .ok_or_else(|| format!("--threads wants a positive count, not {value}"))
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn parse_threads_rejects_zero_and_junk() {
87 assert_eq!(parse_threads("8"), Ok(8));
88 assert!(parse_threads("0").is_err());
89 assert!(parse_threads("-1").is_err());
90 assert!(parse_threads("many").is_err());
91 assert!(parse_threads("").is_err());
92 }
93
94 #[test]
95 fn the_flag_beats_the_env_beats_the_box() {
96 let box_threads = resolve(0, None);
97 assert_eq!(resolve(6, Some("2")), 6, "--threads wins");
98 assert_eq!(resolve(0, Some("2")), 2, "MAPS_THREADS wins over the box");
99 assert_eq!(resolve(6, None), 6);
100 for junk in ["0", "many", "", "-4"] {
101 assert_eq!(resolve(0, Some(junk)), box_threads, "MAPS_THREADS={junk}");
102 }
103 assert_eq!(resolve(0, Some(" 3 ")), 3, "surrounding space is tolerated");
104 }
105}