Skip to main content

no_mistakes_postgres_sql/source/
batch_pool.rs

1use rayon::ThreadPoolBuilder;
2use std::sync::OnceLock;
3
4static RECORDED_RAYON_THREADS: OnceLock<usize> = OnceLock::new();
5
6/// Record the process-wide Rayon pool size chosen by the host binary.
7pub fn record_global_rayon_threads(threads: usize) {
8    let _ = RECORDED_RAYON_THREADS.set(threads);
9}
10
11pub(super) fn install<T: Send>(jobs: usize, work: impl FnOnce() -> T + Send) -> T {
12    let environment = std::env::var("RAYON_NUM_THREADS").ok();
13    let recorded = RECORDED_RAYON_THREADS.get().copied();
14    let threads = worker_limit(jobs, environment.as_deref(), recorded);
15    // Source-only batches must not initialize the global analysis pool:
16    // its first repository invocation still needs to select `jobs`.
17    // Reuse that pool when it is already this size; otherwise build a local
18    // pool no larger than the recorded analysis pool.
19    dispatch(threads, recorded, work)
20}
21
22pub(super) fn worker_limit(
23    jobs: usize,
24    environment: Option<&str>,
25    recorded: Option<usize>,
26) -> usize {
27    let requested = rayon_thread_count(jobs, environment);
28    recorded.map_or(requested, |recorded| requested.min(recorded))
29}
30
31fn rayon_thread_count(jobs: usize, raw_threads: Option<&str>) -> usize {
32    if jobs > 0 {
33        return jobs;
34    }
35    raw_threads
36        .and_then(|raw| raw.parse::<usize>().ok())
37        .filter(|count| *count > 0)
38        .unwrap_or_else(num_cpus::get)
39}
40
41fn dispatch<T: Send>(
42    threads: usize,
43    recorded: Option<usize>,
44    work: impl FnOnce() -> T + Send,
45) -> T {
46    if recorded == Some(threads) {
47        return work();
48    }
49    ThreadPoolBuilder::new()
50        .num_threads(threads)
51        .thread_name(|index| format!("no-mistakes-sql-{index}"))
52        .build()
53        .expect("create PostgreSQL source worker pool")
54        .install(work)
55}
56
57#[cfg(all(test, any(nm_shard_all, nm_shard_1, nm_shard_postgres_source)))]
58#[path = "batch_pool_tests.rs"]
59mod tests;