rch 2.1.3

Remote Compilation Helper - PreToolUse hook CLI
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Update lock to prevent concurrent updates.
//!
//! Uses a PID-based lock file approach that's safe and portable.

use super::types::UpdateError;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

static LOCK_TOKEN_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Lock to prevent concurrent updates.
pub struct UpdateLock {
    path: PathBuf,
    body: String,
}

impl UpdateLock {
    /// Acquire the update lock.
    ///
    /// Uses a PID-based lock file. If a lock file exists, checks if the
    /// process is still running before failing.
    ///
    /// The create step uses `O_CREAT|O_EXCL` (via `OpenOptions::create_new`)
    /// so two concurrent acquirers can't both succeed. A previous revision
    /// used `File::create`, which truncates an existing file — two
    /// processes racing past a stale-lock sweep could each overwrite the
    /// other's PID and both believe they held the lock.
    pub fn acquire() -> Result<Self, UpdateError> {
        let path = get_lock_path()?;

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                UpdateError::InstallFailed(format!("Failed to create lock dir: {}", e))
            })?;
        }

        // One-shot stale sweep: if an existing lock points at a dead PID,
        // reclaim it by comparing the contents we just read and removing
        // only if they still match.
        let mut attempted_sweep = false;
        loop {
            match exclusive_create(&path) {
                Ok(mut file) => {
                    let body = new_lock_body();
                    file.write_all(body.as_bytes()).map_err(|e| {
                        // Clean up our half-written file so a later sweep
                        // doesn't see a malformed PID and choke.
                        let _ = fs::remove_file(&path);
                        UpdateError::InstallFailed(format!("Failed to write lock file: {}", e))
                    })?;
                    file.sync_all().map_err(|e| {
                        let _ = fs::remove_file(&path);
                        UpdateError::InstallFailed(format!("Failed to sync lock file: {}", e))
                    })?;
                    return Ok(Self { path, body });
                }
                Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
                    let Some(existing_pid) = read_pid(&path) else {
                        // A missing or malformed PID is ambiguous: it can be a
                        // lock owner that created the file and has not written
                        // the PID yet. Do not sweep it as stale.
                        return Err(UpdateError::LockHeld);
                    };
                    if is_process_running(existing_pid) {
                        return Err(UpdateError::LockHeld);
                    }
                    if attempted_sweep {
                        // We already tried to sweep once; if the lock is
                        // still blocking us, another process just grabbed
                        // it — treat as held.
                        return Err(UpdateError::LockHeld);
                    }
                    attempted_sweep = true;
                    if !try_sweep_stale(&path, existing_pid) {
                        // Someone else reclaimed or removed it; loop and
                        // let the exclusive create race decide.
                        continue;
                    }
                    // Sweep succeeded; loop to retry create.
                }
                Err(e) => {
                    return Err(UpdateError::InstallFailed(format!(
                        "Failed to create lock file: {}",
                        e
                    )));
                }
            }
        }
    }

    /// Check if an update is currently in progress.
    #[allow(dead_code)]
    pub fn is_locked() -> bool {
        if let Ok(path) = get_lock_path()
            && path.exists()
            && let Some(pid) = read_pid(&path)
        {
            return is_process_running(pid);
        }
        false
    }
}

impl Drop for UpdateLock {
    fn drop(&mut self) {
        // Only remove the exact lock file this guard created. A newer
        // process may have reacquired the lock after the file was manually
        // removed or swept; unconditional removal would clear that fresh lock.
        if read_lock_body(&self.path).as_deref() == Some(self.body.as_str()) {
            let _ = fs::remove_file(&self.path);
        }
    }
}

/// Get the path to the lock file.
fn get_lock_path() -> Result<PathBuf, UpdateError> {
    let data_dir = dirs::data_dir().ok_or_else(|| {
        UpdateError::InstallFailed("Could not determine data directory".to_string())
    })?;

    Ok(data_dir.join("rch/update.lock"))
}

/// Open a file with `O_CREAT|O_EXCL` semantics — succeeds only if the file
/// does not already exist. This is the primitive that makes the acquire
/// loop race-safe.
fn exclusive_create(path: &Path) -> std::io::Result<File> {
    OpenOptions::new().write(true).create_new(true).open(path)
}

/// Produce a lock-file body that remains backward-compatible with old
/// PID-only files by keeping the PID as the first whitespace-delimited token.
fn new_lock_body() -> String {
    let timestamp_ns = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or(0);
    let counter = LOCK_TOKEN_COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("{} {timestamp_ns:x} {counter:x}", std::process::id())
}

/// Read the complete lock body.
fn read_lock_body(path: &Path) -> Option<String> {
    let mut file = File::open(path).ok()?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).ok()?;
    Some(contents)
}

/// Read the PID recorded in the lock file, if any.
fn read_pid(path: &Path) -> Option<u32> {
    let contents = read_lock_body(path)?;
    contents.split_whitespace().next()?.parse().ok()
}

/// Remove the lock file ONLY if the dead PID it contains still matches what we
/// previously observed. This avoids swiping a lock that a fresh process just
/// grabbed between our read and our remove.
fn try_sweep_stale(path: &Path, observed_pid: u32) -> bool {
    let current = read_pid(path);
    if current != Some(observed_pid) {
        return false;
    }
    match fs::remove_file(path) {
        Ok(()) => true,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
        Err(_) => false,
    }
}

/// Check if a process is still running.
fn is_process_running(pid: u32) -> bool {
    #[cfg(target_os = "linux")]
    {
        // On Linux, check /proc filesystem
        let proc_path = format!("/proc/{}", pid);
        std::path::Path::new(&proc_path).exists()
    }

    #[cfg(target_os = "macos")]
    {
        // On macOS, use ps command to check if process exists
        // This is less efficient but avoids unsafe code and works reliably
        std::process::Command::new("ps")
            .args(["-p", &pid.to_string()])
            .output()
            .map(|output| output.status.success())
            .unwrap_or(false)
    }

    #[cfg(windows)]
    {
        // On Windows, assume not running - conservative approach
        // that allows stale locks to be cleaned up
        false
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
    {
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, OnceLock};

    fn test_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    #[test]
    fn test_lock_acquire_and_release() {
        let _guard = test_lock().lock().unwrap();
        // First lock should succeed
        let lock1 = UpdateLock::acquire();
        assert!(lock1.is_ok());

        // While first lock is held, second should fail (same process, but tests PID check)
        // Note: In same process, it will see same PID and think it's still locked
        // This is expected behavior - it prevents recursive updates

        // Drop first lock
        drop(lock1);

        // Now acquiring should succeed
        let lock3 = UpdateLock::acquire();
        assert!(lock3.is_ok());
    }

    #[test]
    fn test_is_locked_false_when_no_lock() {
        let _guard = test_lock().lock().unwrap();
        // Clear any existing lock first
        if let Ok(path) = get_lock_path() {
            let _ = std::fs::remove_file(path);
        }

        // Without lock, should not be locked
        assert!(!UpdateLock::is_locked());
    }

    #[test]
    fn test_current_process_is_running() {
        let pid = std::process::id();
        assert!(is_process_running(pid));
    }

    #[test]
    fn test_nonexistent_process_not_running() {
        // Use a very high PID that's unlikely to exist
        assert!(!is_process_running(999999999));
    }

    #[test]
    fn test_lock_file_contains_pid() {
        let _guard = test_lock().lock().unwrap();
        // Clear any existing lock first
        if let Ok(path) = get_lock_path() {
            let _ = std::fs::remove_file(&path);
        }

        let lock = UpdateLock::acquire().unwrap();
        let path = get_lock_path().unwrap();

        // Read the lock file and verify it contains our PID
        let our_pid = std::process::id();

        assert_eq!(read_pid(&path), Some(our_pid));

        drop(lock);
    }

    #[test]
    fn test_lock_removed_on_drop() {
        let _guard = test_lock().lock().unwrap();
        // Clear any existing lock first
        if let Ok(path) = get_lock_path() {
            let _ = std::fs::remove_file(&path);
        }

        let path = get_lock_path().unwrap();

        {
            let _lock = UpdateLock::acquire().unwrap();
            assert!(path.exists());
        }
        // After drop, lock file should be removed
        assert!(!path.exists());
    }

    #[test]
    fn test_stale_lock_from_dead_process() {
        let _guard = test_lock().lock().unwrap();
        // Clear any existing lock first
        let path = get_lock_path().unwrap();
        let _ = std::fs::remove_file(&path);

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }

        // Create a lock file with a non-existent PID
        std::fs::write(&path, "999999999").unwrap();

        // Should be able to acquire lock since the PID doesn't exist
        let lock = UpdateLock::acquire();
        assert!(lock.is_ok());

        // Clean up
        drop(lock);
    }

    #[test]
    fn test_malformed_lock_is_not_swept() {
        let _guard = test_lock().lock().unwrap();
        let path = get_lock_path().unwrap();
        let _ = std::fs::remove_file(&path);

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }

        std::fs::write(&path, "").unwrap();

        let result = UpdateLock::acquire();
        assert!(
            matches!(result, Err(UpdateError::LockHeld)),
            "expected LockHeld for malformed lock"
        );
        assert!(path.exists(), "malformed lock must not be swept");

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_is_locked_with_active_lock() {
        let _guard = test_lock().lock().unwrap();
        // Clear any existing lock first
        if let Ok(path) = get_lock_path() {
            let _ = std::fs::remove_file(&path);
        }

        // Without lock, should not be locked
        assert!(!UpdateLock::is_locked());

        // Acquire lock
        let _lock = UpdateLock::acquire().unwrap();

        // Now should report as locked
        assert!(UpdateLock::is_locked());
    }

    #[test]
    fn test_drop_preserves_replaced_lock_body() {
        let _guard = test_lock().lock().unwrap();
        let path = get_lock_path().unwrap();
        let _ = std::fs::remove_file(&path);

        let old_lock = UpdateLock::acquire().expect("old lock acquire");
        let replacement_body = new_lock_body();
        std::fs::write(&path, &replacement_body).expect("replace lock body");

        drop(old_lock);

        let body_after_old_drop =
            std::fs::read_to_string(&path).expect("replacement lock should remain");
        assert_eq!(body_after_old_drop, replacement_body);

        let replacement_lock = UpdateLock {
            path: path.clone(),
            body: replacement_body,
        };
        drop(replacement_lock);
        assert!(!path.exists(), "replacement owner should remove its lock");
    }

    #[test]
    fn test_read_pid_accepts_tokenized_lock_body() {
        let _guard = test_lock().lock().unwrap();
        let path = get_lock_path().unwrap();
        let _ = std::fs::remove_file(&path);

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }

        std::fs::write(&path, "12345 abc def").unwrap();

        assert_eq!(read_pid(&path), Some(12345));

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_is_process_running_with_zero_pid() {
        // PID 0 is a special kernel process, behavior varies by OS
        // On most systems, this should return false or true based on kernel
        // This test just ensures it doesn't panic
        let _ = is_process_running(0);
    }

    #[test]
    fn test_is_process_running_with_pid_one() {
        // PID 1 (init/systemd) should always be running on Linux
        #[cfg(unix)]
        {
            assert!(is_process_running(1));
        }
    }

    #[test]
    fn test_second_acquire_without_drop_is_rejected() {
        // Regression: the previous implementation used `File::create`,
        // which truncates-and-opens rather than create-exclusively. A
        // subsequent `acquire()` while a lock was still held (identified
        // by matching PID and `is_process_running(pid) = true`) would
        // still fail at the read step, but any code path that reached
        // the `File::create` call would silently overwrite the existing
        // lock. The current implementation uses `O_CREAT|O_EXCL` so the
        // second acquire is rejected unambiguously.
        let _guard = test_lock().lock().unwrap();
        let path = get_lock_path().unwrap();
        let _ = std::fs::remove_file(&path);

        let first = UpdateLock::acquire().expect("first acquire");
        // Our own PID is running, so a second attempt must see
        // `LockHeld` rather than sweeping and overwriting.
        let result = UpdateLock::acquire();
        assert!(
            matches!(result, Err(UpdateError::LockHeld)),
            "expected LockHeld for second acquire"
        );
        drop(first);

        // After drop, a fresh acquire should succeed again.
        let third = UpdateLock::acquire().expect("re-acquire after drop");
        drop(third);
    }

    #[test]
    fn test_acquire_is_atomic_across_threads() -> Result<(), String> {
        // Regression: only one of N concurrent acquirers may succeed.
        // With `File::create`, two threads could both race past a stale
        // sweep and both overwrite the lock file with their own PID.
        use std::sync::{Arc, Barrier};
        let _guard = test_lock().lock().unwrap();
        let path = get_lock_path().unwrap();
        let _ = std::fs::remove_file(&path);

        let thread_count = 8usize;
        let barrier = Arc::new(Barrier::new(thread_count));
        let mut handles = Vec::with_capacity(thread_count);
        for _ in 0..thread_count {
            let b = barrier.clone();
            handles.push(std::thread::spawn(move || {
                b.wait();
                UpdateLock::acquire()
            }));
        }

        let mut successes = Vec::new();
        let mut lock_held = 0usize;
        for h in handles {
            match h.join().expect("join") {
                Ok(lock) => successes.push(lock),
                Err(UpdateError::LockHeld) => lock_held += 1,
                Err(other) => return Err(format!("unexpected error: {other:?}")),
            }
        }
        assert_eq!(
            successes.len(),
            1,
            "exactly one thread must acquire the lock"
        );
        assert_eq!(
            successes.len() + lock_held,
            thread_count,
            "all acquires must resolve to either success or LockHeld"
        );
        Ok(())
    }
}