1use std::{
31 ffi::CStr,
32 fmt,
33 fs::{self, File, OpenOptions, TryLockError},
34 io::{self, Write as _},
35 os::unix::fs::MetadataExt as _,
36 path::{Path, PathBuf},
37 thread,
38 time::{Duration, SystemTime, UNIX_EPOCH},
39};
40
41use minicbor::{Decode, Encode};
42
43pub const LOCK_FILE_NAME: &str = "kizz.lock";
45
46#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
49pub struct LockDetails {
50 #[n(0)]
52 pub pid: u32,
53 #[n(1)]
55 pub user: String,
56 #[n(2)]
58 pub host: String,
59 #[n(3)]
61 pub working_directory: String,
62 #[n(4)]
64 pub command_line: Vec<String>,
65 #[n(5)]
67 pub start_time_nanos: u64,
68}
69
70impl LockDetails {
71 #[must_use]
73 pub fn current() -> Self {
74 let start_time_nanos = SystemTime::now()
75 .duration_since(UNIX_EPOCH)
76 .map_or(0, |elapsed| {
77 u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX)
78 });
79 Self {
80 pid: std::process::id(),
81 user: user_name(),
82 host: host_name(),
83 working_directory: std::env::current_dir().map_or_else(
84 |_| String::from("(unknown)"),
85 |dir| dir.to_string_lossy().into_owned(),
86 ),
87 command_line: std::env::args_os()
88 .map(|arg| arg.to_string_lossy().into_owned())
89 .collect(),
90 start_time_nanos,
91 }
92 }
93
94 #[must_use]
98 pub fn read(path: &Path) -> Option<Self> {
99 let bytes = fs::read(path).ok()?;
100 minicbor::decode(&bytes).ok()
101 }
102}
103
104impl fmt::Display for LockDetails {
105 fn fmt(
106 &self,
107 f: &mut fmt::Formatter<'_>,
108 ) -> fmt::Result {
109 write!(
110 f,
111 "process {} of user {} on host {}, started {}, in {}: {}",
112 self.pid,
113 self.user,
114 self.host,
115 format_utc(self.start_time_nanos),
116 self.working_directory,
117 self.command_line.join(" ")
118 )
119 }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct LockOptions {
125 pub poll_interval: Duration,
127}
128
129impl Default for LockOptions {
130 fn default() -> Self {
131 Self {
132 poll_interval: Duration::from_millis(20),
133 }
134 }
135}
136
137#[derive(Debug, thiserror::Error)]
139pub enum LockError {
140 #[error("cannot create the cache directory `{}`", path.display())]
142 CreateDir {
143 path: PathBuf,
145 #[source]
147 source: io::Error,
148 },
149 #[error("cannot lock `{}`", path.display())]
151 Lock {
152 path: PathBuf,
154 #[source]
156 source: io::Error,
157 },
158 #[error("cannot write the lock holder's details to `{}`", path.display())]
160 WriteDetails {
161 path: PathBuf,
163 #[source]
165 source: io::Error,
166 },
167 #[error("cannot delete the lock file `{}`", path.display())]
169 Remove {
170 path: PathBuf,
172 #[source]
174 source: io::Error,
175 },
176}
177
178#[derive(Debug)]
180pub struct CacheLock {
181 path: PathBuf,
183 file: Option<File>,
185 note: Option<kizz_threads::overflow::Note>,
188}
189
190impl CacheLock {
191 pub fn acquire(
203 cache_dir: &Path,
204 details: &LockDetails,
205 on_wait: impl FnMut(&LockDetails),
206 ) -> Result<Self, LockError> {
207 Self::acquire_with(cache_dir, details, LockOptions::default(), on_wait)
208 }
209
210 pub fn acquire_with(
216 cache_dir: &Path,
217 details: &LockDetails,
218 options: LockOptions,
219 mut on_wait: impl FnMut(&LockDetails),
220 ) -> Result<Self, LockError> {
221 acquire_inner(cache_dir, details, options, &mut on_wait, &mut |_| {})
222 }
223
224 #[must_use]
226 pub fn path(&self) -> &Path {
227 &self.path
228 }
229
230 pub fn release(mut self) -> Result<(), LockError> {
237 self.release_inner()
238 }
239
240 fn release_inner(&mut self) -> Result<(), LockError> {
244 let Some(file) = self.file.take() else {
245 return Ok(());
246 };
247 drop(self.note.take());
250 let removed = match fs::remove_file(&self.path) {
251 Err(error) if error.kind() != io::ErrorKind::NotFound => {
252 Err(LockError::Remove {
253 path: self.path.clone(),
254 source: error,
255 })
256 },
257 _ => Ok(()),
258 };
259 drop(file);
260 removed
261 }
262}
263
264impl Drop for CacheLock {
265 fn drop(&mut self) {
266 let _ignored: Result<(), LockError> = self.release_inner();
268 }
269}
270
271fn acquire_inner(
276 cache_dir: &Path,
277 details: &LockDetails,
278 options: LockOptions,
279 on_wait: &mut dyn FnMut(&LockDetails),
280 after_lock: &mut dyn FnMut(&Path),
281) -> Result<CacheLock, LockError> {
282 fs::create_dir_all(cache_dir).map_err(|source| {
283 LockError::CreateDir {
284 path: cache_dir.to_path_buf(),
285 source,
286 }
287 })?;
288 let path = cache_dir.join(LOCK_FILE_NAME);
289 let lock_error = |source: io::Error| {
290 LockError::Lock {
291 path: path.clone(),
292 source,
293 }
294 };
295 let mut reported: Option<LockDetails> = None;
296 loop {
297 let file = OpenOptions::new()
298 .read(true)
299 .write(true)
300 .create(true)
301 .truncate(false)
302 .open(&path)
303 .map_err(lock_error)?;
304 match file.try_lock() {
305 Ok(()) => {
306 after_lock(&path);
307 if !is_at_path(&file, &path).map_err(lock_error)? {
308 continue;
311 }
312 write_details(&file, details).map_err(|source| {
313 LockError::WriteDetails {
314 path: path.clone(),
315 source,
316 }
317 })?;
318 return Ok(CacheLock {
319 note: Some(kizz_threads::overflow::note_lock(&path)),
320 path,
321 file: Some(file),
322 });
323 },
324 Err(TryLockError::WouldBlock) => {
325 drop(file);
326 if let Some(holder) = LockDetails::read(&path)
327 && reported.as_ref() != Some(&holder)
328 {
329 on_wait(&holder);
330 reported = Some(holder);
331 }
332 thread::sleep(options.poll_interval);
333 },
334 Err(TryLockError::Error(source)) => return Err(lock_error(source)),
335 }
336 }
337}
338
339fn is_at_path(
341 file: &File,
342 path: &Path,
343) -> io::Result<bool> {
344 let held = file.metadata()?;
345 match fs::metadata(path) {
346 Ok(current) => Ok(current.dev() == held.dev() && current.ino() == held.ino()),
347 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
348 Err(error) => Err(error),
349 }
350}
351
352fn write_details(
354 mut file: &File,
355 details: &LockDetails,
356) -> io::Result<()> {
357 let bytes = minicbor::to_vec(details).map_err(io::Error::other)?;
358 file.set_len(0)?;
359 file.write_all(&bytes)?;
360 file.flush()
361}
362
363fn user_name() -> String {
365 let uid = unsafe { libc::geteuid() };
367 let mut entry = std::mem::MaybeUninit::<libc::passwd>::uninit();
368 let mut buffer: Vec<libc::c_char> = vec![0; 16_384];
369 let mut result: *mut libc::passwd = std::ptr::null_mut();
370 let status = unsafe {
373 libc::getpwuid_r(
374 uid,
375 entry.as_mut_ptr(),
376 buffer.as_mut_ptr(),
377 buffer.len(),
378 &raw mut result,
379 )
380 };
381 if status != 0 || result.is_null() {
382 return uid.to_string();
383 }
384 let name = unsafe { entry.assume_init_ref() }.pw_name;
386 if name.is_null() {
387 return uid.to_string();
388 }
389 unsafe { CStr::from_ptr(name) }
391 .to_string_lossy()
392 .into_owned()
393}
394
395pub(crate) fn host_name() -> String {
398 let mut buffer = [0_u8; 256];
399 let status = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
401 if status != 0 {
402 return String::from("(unknown)");
403 }
404 CStr::from_bytes_until_nul(&buffer).map_or_else(
405 |_| String::from_utf8_lossy(&buffer).into_owned(),
406 |name| name.to_string_lossy().into_owned(),
407 )
408}
409
410fn format_utc(nanos: u64) -> String {
414 civil_utc(nanos).unwrap_or_else(|| format!("{nanos} nanoseconds after the epoch"))
415}
416
417fn civil_utc(nanos: u64) -> Option<String> {
421 let seconds = nanos.checked_div(1_000_000_000)?;
422 let days = seconds.checked_div(86_400)?;
423 let second_of_day = seconds.checked_rem(86_400)?;
424 let shifted = days.checked_add(719_468)?;
427 let era = shifted.checked_div(146_097)?;
428 let day_of_era = shifted.checked_rem(146_097)?;
429 let year_of_era = day_of_era
430 .checked_sub(day_of_era.checked_div(1_460)?)?
431 .checked_add(day_of_era.checked_div(36_524)?)?
432 .checked_sub(day_of_era.checked_div(146_096)?)?
433 .checked_div(365)?;
434 let day_of_year = day_of_era.checked_sub(
435 year_of_era
436 .checked_mul(365)?
437 .checked_add(year_of_era.checked_div(4)?)?
438 .checked_sub(year_of_era.checked_div(100)?)?,
439 )?;
440 let shifted_month = day_of_year
441 .checked_mul(5)?
442 .checked_add(2)?
443 .checked_div(153)?;
444 let day = day_of_year
445 .checked_sub(
446 shifted_month
447 .checked_mul(153)?
448 .checked_add(2)?
449 .checked_div(5)?,
450 )?
451 .checked_add(1)?;
452 let month = if shifted_month < 10 {
453 shifted_month.checked_add(3)?
454 } else {
455 shifted_month.checked_sub(9)?
456 };
457 let year = year_of_era
458 .checked_add(era.checked_mul(400)?)?
459 .checked_add(u64::from(month <= 2))?;
460 Some(format!(
461 "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
462 second_of_day.checked_div(3_600)?,
463 second_of_day.checked_rem(3_600)?.checked_div(60)?,
464 second_of_day.checked_rem(60)?
465 ))
466}
467
468#[cfg(test)]
470#[allow(
471 clippy::disallowed_macros,
472 clippy::disallowed_methods,
473 reason = "test code: a thread of a scope waits for the lock, and the tests assert"
474)]
475mod tests {
476 use std::cell::Cell;
477
478 use super::*;
479
480 fn details(pid: u32) -> LockDetails {
482 LockDetails {
483 pid,
484 user: String::from("builder"),
485 host: String::from("build-host"),
486 working_directory: String::from("/work"),
487 command_line: vec![String::from("kizz"), String::from("build")],
488 start_time_nanos: 1_761_282_720_000_000_000,
489 }
490 }
491
492 #[test]
493 fn holder_details_are_written_and_the_file_is_deleted_on_release() {
494 let dir = tempfile::tempdir().unwrap();
495 let cache = dir.path().join("cache");
496 let lock = CacheLock::acquire(&cache, &details(7), |_| {
497 panic!("nobody else holds the lock")
498 })
499 .unwrap();
500 assert_eq!(lock.path(), cache.join(LOCK_FILE_NAME));
501 assert_eq!(LockDetails::read(lock.path()), Some(details(7)));
502 lock.release().unwrap();
503 assert!(!cache.join(LOCK_FILE_NAME).exists());
504 }
505
506 #[test]
507 fn dropping_the_lock_deletes_the_file() {
508 let dir = tempfile::tempdir().unwrap();
509 let lock = CacheLock::acquire(dir.path(), &details(7), |_| {}).unwrap();
510 let path = lock.path().to_path_buf();
511 assert!(path.exists());
512 drop(lock);
513 assert!(!path.exists());
514 }
515
516 #[test]
517 fn a_stale_file_is_taken_over() {
518 let dir = tempfile::tempdir().unwrap();
519 let path = dir.path().join(LOCK_FILE_NAME);
520 fs::write(&path, minicbor::to_vec(details(1)).unwrap()).unwrap();
521 let stale_inode = fs::metadata(&path).unwrap().ino();
522 let lock = CacheLock::acquire(dir.path(), &details(2), |_| {
523 panic!("a stale file is not a holder")
524 })
525 .unwrap();
526 assert_eq!(fs::metadata(&path).unwrap().ino(), stale_inode);
527 assert_eq!(LockDetails::read(&path), Some(details(2)));
528 drop(lock);
529 }
530
531 #[test]
532 fn the_holder_retries_when_the_locked_file_is_no_longer_at_the_path() {
533 let dir = tempfile::tempdir().unwrap();
534 let path = dir.path().join(LOCK_FILE_NAME);
535 let locked = Cell::new(0_u32);
536 let replaced_inode = Cell::new(None);
537 let lock = acquire_inner(
538 dir.path(),
539 &details(3),
540 LockOptions::default(),
541 &mut |_| panic!("nobody else holds the lock"),
542 &mut |lock_path| {
543 locked.set(locked.get().saturating_add(1));
544 if locked.get() == 1 {
545 fs::remove_file(lock_path).unwrap();
548 fs::write(lock_path, b"").unwrap();
549 replaced_inode.set(Some(fs::metadata(lock_path).unwrap().ino()));
550 }
551 },
552 )
553 .unwrap();
554 assert_eq!(
555 locked.get(),
556 2,
557 "the first lock was dropped and taken again"
558 );
559 let held = lock.file.as_ref().unwrap().metadata().unwrap().ino();
560 assert_eq!(Some(held), replaced_inode.get());
561 assert_eq!(fs::metadata(&path).unwrap().ino(), held);
562 assert_eq!(LockDetails::read(&path), Some(details(3)));
563 drop(lock);
564 }
565
566 #[test]
567 fn a_waiting_lock_in_the_same_process_reports_the_holder() {
568 let dir = tempfile::tempdir().unwrap();
569 let holder = CacheLock::acquire(dir.path(), &details(10), |_| {}).unwrap();
570 let reports = std::sync::Mutex::new(Vec::new());
571 thread::scope(|scope| {
572 let waiter = scope.spawn(|| {
573 CacheLock::acquire(dir.path(), &details(11), |seen| {
574 reports.lock().unwrap().push(seen.clone());
575 })
576 });
577 while reports.lock().unwrap().is_empty() {
578 thread::sleep(Duration::from_millis(5));
579 }
580 assert!(!waiter.is_finished());
581 drop(holder);
582 let lock = waiter.join().unwrap().unwrap();
583 assert_eq!(LockDetails::read(lock.path()), Some(details(11)));
584 });
585 assert_eq!(reports.into_inner().unwrap(), vec![details(10)]);
586 }
587
588 #[test]
589 fn incomplete_details_are_not_read() {
590 let dir = tempfile::tempdir().unwrap();
591 let path = dir.path().join(LOCK_FILE_NAME);
592 assert_eq!(LockDetails::read(&path), None);
593 fs::write(&path, b"").unwrap();
594 assert_eq!(LockDetails::read(&path), None);
595 let bytes = minicbor::to_vec(details(4)).unwrap();
596 fs::write(&path, &bytes[..bytes.len() / 2]).unwrap();
597 assert_eq!(LockDetails::read(&path), None);
598 }
599
600 #[test]
601 fn details_display_every_field() {
602 let text = details(42).to_string();
603 assert_eq!(
604 text,
605 "process 42 of user builder on host build-host, started 2025-10-24T05:12:00Z, in \
606 /work: kizz build"
607 );
608 }
609
610 #[test]
611 fn utc_formatting_handles_leap_years_and_the_epoch() {
612 assert_eq!(format_utc(0), "1970-01-01T00:00:00Z");
613 assert_eq!(format_utc(951_782_400_000_000_000), "2000-02-29T00:00:00Z");
614 assert_eq!(
615 format_utc(1_798_761_599_000_000_000),
616 "2026-12-31T23:59:59Z"
617 );
618 }
619
620 #[test]
621 fn current_details_describe_this_process() {
622 let current = LockDetails::current();
623 assert_eq!(current.pid, std::process::id());
624 assert_ne!(current.user, "");
625 assert_ne!(current.host, "");
626 assert_ne!(current.command_line, Vec::<String>::new());
627 assert!(current.start_time_nanos > 0);
628 }
629}