1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//! Global concurrency limiter for lean-ctx processes.
//!
//! Prevents runaway CPU usage by limiting the number of concurrent lean-ctx
//! processes to `MAX_CONCURRENT`. Each process acquires a numbered lock slot
//! under `~/.lean-ctx/locks/`. If all slots are taken, the caller gets `None`.
use std::fs::File;
use std::path::PathBuf;
const MAX_CONCURRENT: usize = 4;
pub struct ProcessGuard {
_file: File,
path: PathBuf,
}
impl Drop for ProcessGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
fn lock_dir() -> Option<PathBuf> {
let dir = crate::core::data_dir::lean_ctx_data_dir()
.ok()?
.join("locks");
let _ = std::fs::create_dir_all(&dir);
Some(dir)
}
/// Try to acquire one of N concurrent process slots.
/// Returns `None` if all slots are occupied (= too many lean-ctx already running).
pub fn acquire() -> Option<ProcessGuard> {
let dir = lock_dir()?;
for slot in 0..MAX_CONCURRENT {
let path = dir.join(format!("slot-{slot}.lock"));
let Ok(file) = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(&path)
else {
continue;
};
if try_flock(&file) {
use std::io::Write;
let mut f = file;
let _ = f.write_all(format!("{}", std::process::id()).as_bytes());
return Some(ProcessGuard { _file: f, path });
}
}
None
}
/// Checks how many slots are currently held (best-effort).
pub fn active_count() -> usize {
let Some(dir) = lock_dir() else { return 0 };
let mut count = 0;
for slot in 0..MAX_CONCURRENT {
let path = dir.join(format!("slot-{slot}.lock"));
if let Ok(f) = std::fs::OpenOptions::new().read(true).open(&path) {
if !try_flock(&f) {
count += 1;
}
}
}
count
}
#[cfg(unix)]
fn try_flock(file: &File) -> bool {
use std::os::unix::io::AsRawFd;
let fd = file.as_raw_fd();
let rc = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
rc == 0
}
#[cfg(not(unix))]
fn try_flock(_file: &File) -> bool {
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn acquire_and_release() {
let guard = acquire();
assert!(guard.is_some(), "should acquire first slot");
drop(guard);
}
#[cfg(unix)]
#[test]
fn active_count_reflects_held_slots() {
let g1 = acquire();
assert!(g1.is_some());
let count = active_count();
assert!(count >= 1, "at least one slot held, got {count}");
drop(g1);
}
}