1use std::fmt;
2use std::fs::{self, File, OpenOptions};
3use std::io::{self, Write};
4use std::path::{Path, PathBuf};
5use std::sync::{
6 atomic::{AtomicBool, AtomicU64, Ordering},
7 mpsc, Arc,
8};
9use std::thread::{self, JoinHandle};
10use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
11
12use serde::{Deserialize, Serialize};
13
14use crate::{slog_debug, slog_error, slog_info, slog_warn};
15
16pub const HEARTBEAT_INTERVAL_MS: u64 = 5_000;
17pub const STALE_HEARTBEAT_MS: u64 = 15_000;
18pub const LIVE_OWNER_WARN_MS: u64 = 600_000;
19pub const POLL_INTERVAL_MS: u64 = 100;
20
21const MAX_TRANSIENT_CREATE_RETRIES: u32 = 50;
29
30fn is_transient_create_contention(error: &io::Error) -> bool {
36 if error.kind() == io::ErrorKind::PermissionDenied {
37 return true;
38 }
39 #[cfg(windows)]
40 {
41 if let Some(code) = error.raw_os_error() {
45 if code == 32 || code == 5 {
46 return true;
47 }
48 }
49 }
50 false
51}
52
53#[derive(Clone, Copy, Debug)]
54struct LockConfig {
55 heartbeat_interval_ms: u64,
56 stale_heartbeat_ms: u64,
57 live_owner_warn_ms: u64,
58 poll_interval_ms: u64,
59}
60
61impl LockConfig {
62 fn cross_host_stale_heartbeat_ms(self) -> u64 {
63 self.stale_heartbeat_ms.saturating_mul(5)
64 }
65}
66
67impl Default for LockConfig {
68 fn default() -> Self {
69 Self {
70 heartbeat_interval_ms: HEARTBEAT_INTERVAL_MS,
71 stale_heartbeat_ms: STALE_HEARTBEAT_MS,
72 live_owner_warn_ms: LIVE_OWNER_WARN_MS,
73 poll_interval_ms: POLL_INTERVAL_MS,
74 }
75 }
76}
77
78#[derive(Clone, Debug, PartialEq, Eq)]
79struct ProcessIdentity {
80 start_time: u64,
81 boot_id: Option<String>,
82}
83
84#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
85struct LockMetadata {
86 pid: u32,
87 hostname: String,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
91 process_start_time: Option<u64>,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
96 boot_id: Option<String>,
97 created_at_ms: u64,
98 heartbeat_at_ms: u64,
99 #[serde(default)]
102 writer_epoch: String,
103}
104
105pub fn acquire(path: &Path) -> Result<LockGuard, AcquireError> {
110 acquire_with_config(path, None, LockConfig::default())
111}
112
113pub fn try_acquire(path: &Path, timeout: Duration) -> Result<LockGuard, AcquireError> {
115 acquire_with_config(path, Some(timeout), LockConfig::default())
116}
117
118pub fn try_acquire_once(path: &Path) -> Result<LockGuard, AcquireError> {
124 try_acquire(path, Duration::ZERO)
125}
126
127pub struct LockGuard {
128 path: PathBuf,
129 metadata: LockMetadata,
130 shutdown: Arc<AtomicBool>,
131 heartbeat_failed: Arc<AtomicBool>,
132 heartbeat_done: mpsc::Receiver<()>,
133 heartbeat: Option<JoinHandle<()>>,
134}
135
136impl LockGuard {
137 pub fn path(&self) -> &Path {
138 &self.path
139 }
140
141 pub fn writer_epoch(&self) -> &str {
142 &self.metadata.writer_epoch
143 }
144
145 pub fn verify_writer_epoch(&self) -> io::Result<bool> {
149 if self.heartbeat_failed.load(Ordering::Acquire) {
150 return Ok(false);
151 }
152 match read_lock_metadata(&self.path) {
153 Ok(metadata) => Ok(lock_identity_matches(&metadata, &self.metadata)),
154 Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => Ok(false),
155 Err(ReadLockError::Io(error)) => Err(error),
156 Err(ReadLockError::Malformed(_)) => Ok(false),
157 }
158 }
159}
160
161impl Drop for LockGuard {
162 fn drop(&mut self) {
163 self.shutdown.store(true, Ordering::Release);
187 if let Some(handle) = self.heartbeat.take() {
188 handle.thread().unpark();
189 let _ = handle.join();
190 }
191 while self.heartbeat_done.try_recv().is_ok() {}
195
196 match remove_lock_if_owned(&self.path, &self.metadata) {
197 Ok(true) => slog_debug!("released filesystem lock at {}", self.path.display()),
198 Ok(false) => {}
199 Err(error) => slog_warn!(
200 "failed to release filesystem lock at {}: {}",
201 self.path.display(),
202 error
203 ),
204 }
205 }
206}
207
208#[derive(Debug)]
209pub enum AcquireError {
210 Io(io::Error),
211 Timeout,
212}
213
214impl fmt::Display for AcquireError {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 match self {
217 AcquireError::Io(error) => write!(f, "filesystem lock I/O error: {error}"),
218 AcquireError::Timeout => write!(f, "timed out acquiring filesystem lock"),
219 }
220 }
221}
222
223impl std::error::Error for AcquireError {}
224
225impl From<io::Error> for AcquireError {
226 fn from(error: io::Error) -> Self {
227 AcquireError::Io(error)
228 }
229}
230
231fn acquire_with_config(
232 path: &Path,
233 timeout: Option<Duration>,
234 config: LockConfig,
235) -> Result<LockGuard, AcquireError> {
236 let deadline = timeout.map(|timeout| Instant::now() + timeout);
237 let hostname = current_hostname();
238 let mut warned_live_owner = false;
239 let mut warned_stale_live_owner = false;
240 let mut transient_create_failures: u32 = 0;
241 let mut attempted_once = false;
242 let mut immediate_retry_budget = 0_u8;
245
246 loop {
247 if attempted_once {
248 if immediate_retry_budget > 0 {
249 immediate_retry_budget -= 1;
250 } else if let Some(deadline) = deadline {
251 if Instant::now() >= deadline {
252 return Err(AcquireError::Timeout);
253 }
254 }
255 }
256 attempted_once = true;
257
258 match create_new_lock(path, &hostname, config) {
259 Ok(guard) => return Ok(guard),
260 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
262 Err(error) if is_transient_create_contention(&error) => {
268 transient_create_failures += 1;
269 if transient_create_failures > MAX_TRANSIENT_CREATE_RETRIES {
270 return Err(error.into());
271 }
272 sleep_until_retry(deadline, config.poll_interval_ms)?;
273 continue;
274 }
275 Err(error) => return Err(error.into()),
276 }
277 transient_create_failures = 0;
278
279 let metadata = match read_lock_metadata(path) {
280 Ok(metadata) => metadata,
281 Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
282 immediate_retry_budget = 1;
283 continue;
284 }
285 Err(ReadLockError::Io(error)) => return Err(error.into()),
286 Err(ReadLockError::Malformed(error)) => {
287 sleep_until_retry(deadline, config.poll_interval_ms)?;
291 match read_lock_metadata(path) {
292 Ok(_) => continue,
293 Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
294 continue;
295 }
296 Err(ReadLockError::Io(error)) => return Err(error.into()),
297 Err(ReadLockError::Malformed(_)) => {}
298 }
299 slog_warn!(
300 "removing malformed filesystem lock at {}: {}",
301 path.display(),
302 error
303 );
304 remove_lock_file(path)?;
305 immediate_retry_budget = 1;
306 continue;
307 }
308 };
309
310 let now = now_ms();
311 let since_heartbeat = now.saturating_sub(metadata.heartbeat_at_ms);
312
313 if metadata.hostname != hostname {
314 let cross_host_stale_ms = config.cross_host_stale_heartbeat_ms();
315 if since_heartbeat > cross_host_stale_ms {
316 slog_warn!(
317 "reclaiming cross-host filesystem lock at {} from host {} after stale heartbeat ({}ms > {}ms)",
318 path.display(),
319 metadata.hostname,
320 since_heartbeat,
321 cross_host_stale_ms
322 );
323 if reclaim_lock_file(path, &metadata)? {
326 immediate_retry_budget = 1;
327 }
328 continue;
329 }
330 sleep_until_retry(deadline, config.poll_interval_ms)?;
331 continue;
332 }
333
334 if !lock_owner_is_alive(&metadata) {
335 slog_warn!(
336 "removing filesystem lock at {} from dead or recycled PID {}",
337 path.display(),
338 metadata.pid
339 );
340 if reclaim_lock_file(path, &metadata)? {
344 immediate_retry_budget = 1;
345 }
346 continue;
347 }
348
349 if since_heartbeat > config.stale_heartbeat_ms && !warned_stale_live_owner {
350 slog_warn!(
359 "filesystem lock at {} held by live PID {} has stale heartbeat ({}ms); NOT breaking",
360 path.display(),
361 metadata.pid,
362 since_heartbeat
363 );
364 warned_stale_live_owner = true;
365 }
366
367 let held_for = now.saturating_sub(metadata.created_at_ms);
368 if held_for > config.live_owner_warn_ms && !warned_live_owner {
369 slog_warn!(
370 "filesystem lock at {} held >10min by live heartbeating PID {}; NOT breaking",
371 path.display(),
372 metadata.pid
373 );
374 warned_live_owner = true;
375 }
376
377 sleep_until_retry(deadline, config.poll_interval_ms)?;
378 }
379}
380
381fn create_new_lock(path: &Path, hostname: &str, config: LockConfig) -> io::Result<LockGuard> {
382 let now = now_ms();
383 let pid = std::process::id();
384 let process_identity = process_identity(pid);
385 let metadata = LockMetadata {
386 pid,
387 hostname: hostname.to_string(),
388 process_start_time: process_identity
389 .as_ref()
390 .map(|identity| identity.start_time),
391 boot_id: process_identity.and_then(|identity| identity.boot_id),
392 created_at_ms: now,
393 heartbeat_at_ms: now,
394 writer_epoch: format!("{pid}-{}", now_nanos()),
395 };
396
397 create_lock_file_atomically(path, &metadata)?;
398
399 let shutdown = Arc::new(AtomicBool::new(false));
400 let heartbeat_failed = Arc::new(AtomicBool::new(false));
401 let (done_tx, done_rx) = mpsc::channel();
402 let heartbeat_path = path.to_path_buf();
403 let heartbeat_metadata = metadata.clone();
404 let heartbeat_shutdown = Arc::clone(&shutdown);
405 let heartbeat_failed_for_thread = Arc::clone(&heartbeat_failed);
406 let heartbeat = thread::Builder::new()
407 .name("aft-fs-lock-heartbeat".to_string())
408 .spawn(move || {
409 let heartbeat_shutdown_for_run = Arc::clone(&heartbeat_shutdown);
410 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
411 run_heartbeat(
412 heartbeat_path,
413 heartbeat_metadata,
414 heartbeat_shutdown_for_run,
415 config,
416 );
417 }));
418 if result.is_err() || !heartbeat_shutdown.load(Ordering::Acquire) {
419 heartbeat_failed_for_thread.store(true, Ordering::Release);
420 }
421 let _ = done_tx.send(());
422 })?;
423
424 slog_debug!("acquired filesystem lock at {}", path.display());
425
426 Ok(LockGuard {
427 path: path.to_path_buf(),
428 metadata,
429 shutdown,
430 heartbeat_failed,
431 heartbeat_done: done_rx,
432 heartbeat: Some(heartbeat),
433 })
434}
435
436fn run_heartbeat(
437 path: PathBuf,
438 owner: LockMetadata,
439 shutdown: Arc<AtomicBool>,
440 config: LockConfig,
441) {
442 let stale_intervals = config
447 .stale_heartbeat_ms
448 .checked_div(config.heartbeat_interval_ms.max(1))
449 .unwrap_or(3)
450 .max(1);
451 let mut consecutive_transient_failures: u64 = 0;
452
453 loop {
454 thread::park_timeout(Duration::from_millis(config.heartbeat_interval_ms));
455 if shutdown.load(Ordering::Acquire) {
456 return;
457 }
458
459 match heartbeat_once(&path, &owner) {
460 Ok(()) => {
461 if consecutive_transient_failures > 0 {
462 slog_info!(
463 "filesystem lock at {} heartbeat recovered after {} transient failure(s)",
464 path.display(),
465 consecutive_transient_failures
466 );
467 consecutive_transient_failures = 0;
468 }
469 }
470 Err(error) if heartbeat_error_is_terminal(&error) => {
471 slog_error!(
476 "{}; stopping heartbeat",
477 terminal_heartbeat_message(&path, &error)
478 );
479 return;
480 }
481 Err(error) => {
482 consecutive_transient_failures += 1;
492 log_transient_heartbeat_failure(
493 &path,
494 &transient_heartbeat_reason(&error),
495 consecutive_transient_failures,
496 stale_intervals,
497 );
498 }
499 }
500 }
501}
502
503fn heartbeat_error_is_terminal(error: &HeartbeatError) -> bool {
509 matches!(error, HeartbeatError::LockGone | HeartbeatError::NotOwner)
510}
511
512fn terminal_heartbeat_message(path: &Path, error: &HeartbeatError) -> String {
513 match error {
514 HeartbeatError::LockGone => {
515 format!("filesystem lock at {} disappeared", path.display())
516 }
517 HeartbeatError::NotOwner => format!(
518 "filesystem lock at {} is no longer owned by this guard",
519 path.display()
520 ),
521 HeartbeatError::Io(error) => {
523 format!("filesystem lock at {} I/O error: {error}", path.display())
524 }
525 HeartbeatError::Malformed(error) => {
526 format!(
527 "filesystem lock at {} became malformed: {error}",
528 path.display()
529 )
530 }
531 }
532}
533
534fn transient_heartbeat_reason(error: &HeartbeatError) -> String {
535 match error {
536 HeartbeatError::Io(error) => format!("I/O error: {error}"),
537 HeartbeatError::Malformed(error) => format!("became malformed: {error}"),
538 HeartbeatError::LockGone => "lock disappeared".to_string(),
539 HeartbeatError::NotOwner => "lock no longer owned".to_string(),
540 }
541}
542
543fn log_transient_heartbeat_failure(
548 path: &Path,
549 reason: &str,
550 consecutive_failures: u64,
551 stale_intervals: u64,
552) {
553 if consecutive_failures < stale_intervals {
554 slog_warn!(
555 "transient failure to heartbeat filesystem lock at {}: {}; retrying (attempt {})",
556 path.display(),
557 reason,
558 consecutive_failures
559 );
560 } else if consecutive_failures == stale_intervals {
561 slog_error!(
562 "filesystem lock at {} has failed {} consecutive heartbeats: {}; \
563 the lock may now be reclaimed by another owner — continuing to retry",
564 path.display(),
565 consecutive_failures,
566 reason
567 );
568 }
569}
570
571fn heartbeat_once(path: &Path, owner: &LockMetadata) -> Result<(), HeartbeatError> {
572 let mut metadata = match read_lock_metadata(path) {
573 Ok(metadata) => metadata,
574 Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
575 return Err(HeartbeatError::LockGone);
576 }
577 Err(ReadLockError::Io(error)) => return Err(HeartbeatError::Io(error)),
578 Err(ReadLockError::Malformed(error)) => return Err(HeartbeatError::Malformed(error)),
579 };
580
581 if !lock_identity_matches(&metadata, owner) {
582 return Err(HeartbeatError::NotOwner);
583 }
584
585 metadata.heartbeat_at_ms = now_ms();
586 atomic_write_lock_metadata(path, &metadata).map_err(HeartbeatError::Io)
587}
588
589#[derive(Debug)]
590enum HeartbeatError {
591 Io(io::Error),
592 LockGone,
593 Malformed(serde_json::Error),
594 NotOwner,
595}
596
597#[derive(Debug)]
598enum ReadLockError {
599 Io(io::Error),
600 Malformed(serde_json::Error),
601}
602
603fn read_lock_metadata(path: &Path) -> Result<LockMetadata, ReadLockError> {
604 let bytes = fs::read(path).map_err(ReadLockError::Io)?;
605 serde_json::from_slice(&bytes).map_err(ReadLockError::Malformed)
606}
607
608#[cfg(unix)]
609fn open_new_lock_file(path: &Path) -> io::Result<File> {
610 use std::os::unix::fs::OpenOptionsExt;
611
612 OpenOptions::new()
613 .write(true)
614 .create_new(true)
615 .mode(0o600)
616 .open(path)
617}
618
619#[cfg(not(unix))]
620fn open_new_lock_file(path: &Path) -> io::Result<File> {
621 OpenOptions::new().write(true).create_new(true).open(path)
622}
623
624fn write_lock_metadata_to_file(file: &mut File, metadata: &LockMetadata) -> io::Result<()> {
625 serde_json::to_writer(&mut *file, metadata).map_err(io::Error::other)?;
626 file.write_all(b"\n")?;
627 file.sync_all()
628}
629
630fn create_lock_file_atomically(path: &Path, metadata: &LockMetadata) -> io::Result<()> {
631 let tmp_path = temp_path_for_lock(path);
632 let result = (|| {
633 let mut file = open_new_lock_file(&tmp_path)?;
634 write_lock_metadata_to_file(&mut file, metadata)?;
635 drop(file);
636
637 fs::hard_link(&tmp_path, path)?;
638 sync_parent(path);
639 Ok(())
640 })();
641
642 let _ = fs::remove_file(&tmp_path);
643 result
644}
645
646fn atomic_write_lock_metadata(path: &Path, metadata: &LockMetadata) -> io::Result<()> {
647 let tmp_path = temp_path_for_lock(path);
648 let write_result = (|| {
649 let mut file = open_new_lock_file(&tmp_path)?;
650 write_lock_metadata_to_file(&mut file, metadata)?;
651 drop(file);
652
653 rename_over(&tmp_path, path)?;
654 sync_parent(path);
655 Ok(())
656 })();
657
658 if write_result.is_err() {
659 let _ = fs::remove_file(&tmp_path);
660 }
661
662 write_result
663}
664
665#[cfg(any(windows, test))]
666fn rename_over_with(
667 from: &Path,
668 to: &Path,
669 replace: impl FnOnce(&Path, &Path) -> io::Result<()>,
670) -> io::Result<()> {
671 replace(from, to)
672}
673
674#[cfg(windows)]
675pub(crate) fn rename_over(from: &Path, to: &Path) -> io::Result<()> {
676 rename_over_with(from, to, |from, to| fs::rename(from, to))
686}
687
688#[cfg(not(windows))]
689pub(crate) fn rename_over(from: &Path, to: &Path) -> io::Result<()> {
690 fs::rename(from, to)
691}
692
693static TEMP_LOCK_COUNTER: AtomicU64 = AtomicU64::new(0);
706
707fn temp_path_for_lock(path: &Path) -> PathBuf {
708 let file_name = path
709 .file_name()
710 .and_then(|name| name.to_str())
711 .unwrap_or("lock");
712 let seq = TEMP_LOCK_COUNTER.fetch_add(1, Ordering::Relaxed);
713 path.with_file_name(format!(
714 ".{file_name}.tmp.{}.{}.{}",
715 std::process::id(),
716 now_nanos(),
717 seq
718 ))
719}
720
721fn lock_identity_matches(left: &LockMetadata, right: &LockMetadata) -> bool {
722 left.pid == right.pid
723 && left.hostname == right.hostname
724 && left.process_start_time == right.process_start_time
725 && left.boot_id == right.boot_id
726 && left.created_at_ms == right.created_at_ms
727 && left.writer_epoch == right.writer_epoch
728}
729
730fn remove_lock_if_owned(path: &Path, owner: &LockMetadata) -> io::Result<bool> {
731 let metadata = match read_lock_metadata(path) {
732 Ok(metadata) => metadata,
733 Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
734 return Ok(false);
735 }
736 Err(ReadLockError::Io(error)) => return Err(error),
737 Err(ReadLockError::Malformed(_)) => return Ok(false),
738 };
739
740 if lock_identity_matches(&metadata, owner) {
741 remove_lock_file(path)?;
742 Ok(true)
743 } else {
744 Ok(false)
745 }
746}
747
748fn remove_lock_file(path: &Path) -> io::Result<()> {
749 match fs::remove_file(path) {
750 Ok(()) => Ok(()),
751 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
752 Err(error) => Err(error),
753 }
754}
755
756fn reclaim_lock_file(path: &Path, judged: &LockMetadata) -> io::Result<bool> {
766 let Some(_token) = acquire_reclaim_token(path)? else {
767 return Ok(false);
768 };
769 match read_lock_metadata(path) {
770 Ok(current) => {
771 if lock_identity_matches(¤t, judged) {
772 remove_lock_file(path)?;
773 Ok(true)
774 } else {
775 Ok(false)
777 }
778 }
779 Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => Ok(false),
781 Err(ReadLockError::Malformed(_)) => Ok(false),
783 Err(ReadLockError::Io(error)) => Err(error),
784 }
785}
786
787struct ReclaimTokenGuard {
788 path: PathBuf,
789}
790
791impl Drop for ReclaimTokenGuard {
792 fn drop(&mut self) {
793 let _ = fs::remove_file(&self.path);
794 sync_parent(&self.path);
795 }
796}
797
798fn acquire_reclaim_token(lock_path: &Path) -> io::Result<Option<ReclaimTokenGuard>> {
799 let token_path = reclaim_token_path(lock_path);
800 let pid = std::process::id();
801 let process_identity = process_identity(pid);
802 let metadata = LockMetadata {
803 pid,
804 hostname: current_hostname(),
805 process_start_time: process_identity
806 .as_ref()
807 .map(|identity| identity.start_time),
808 boot_id: process_identity.and_then(|identity| identity.boot_id),
809 created_at_ms: now_ms(),
810 heartbeat_at_ms: now_ms(),
811 writer_epoch: format!("reclaim-{pid}-{}", now_nanos()),
812 };
813 let mut file = match open_new_lock_file(&token_path) {
814 Ok(file) => file,
815 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return Ok(None),
816 Err(error) => return Err(error),
817 };
818 if let Err(error) = write_lock_metadata_to_file(&mut file, &metadata) {
819 let _ = fs::remove_file(&token_path);
820 return Err(error);
821 }
822 sync_parent(&token_path);
823 Ok(Some(ReclaimTokenGuard { path: token_path }))
824}
825
826fn reclaim_token_path(lock_path: &Path) -> PathBuf {
827 let file_name = lock_path
828 .file_name()
829 .and_then(|name| name.to_str())
830 .unwrap_or("lock");
831 lock_path.with_file_name(format!(".{file_name}.reclaim"))
832}
833
834fn sleep_until_retry(deadline: Option<Instant>, poll_interval_ms: u64) -> Result<(), AcquireError> {
835 let poll = Duration::from_millis(poll_interval_ms);
836 let sleep_for = match deadline {
837 Some(deadline) => {
838 let now = Instant::now();
839 if now >= deadline {
840 return Err(AcquireError::Timeout);
841 }
842 poll.min(deadline.saturating_duration_since(now))
843 }
844 None => poll,
845 };
846 thread::sleep(sleep_for);
847 Ok(())
848}
849
850pub(crate) fn sync_parent(path: &Path) {
851 if let Some(parent) = path.parent() {
852 if let Ok(dir) = File::open(parent) {
853 let _ = dir.sync_all();
854 }
855 }
856}
857
858fn now_ms() -> u64 {
859 SystemTime::now()
860 .duration_since(UNIX_EPOCH)
861 .unwrap_or(Duration::ZERO)
862 .as_millis() as u64
863}
864
865fn now_nanos() -> u128 {
866 SystemTime::now()
867 .duration_since(UNIX_EPOCH)
868 .unwrap_or(Duration::ZERO)
869 .as_nanos()
870}
871
872#[cfg(unix)]
873fn current_hostname() -> String {
874 let mut buffer = [0u8; 256];
875 let result = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
876 if result == 0 {
877 let len = buffer
878 .iter()
879 .position(|byte| *byte == 0)
880 .unwrap_or(buffer.len());
881 if len > 0 {
882 return String::from_utf8_lossy(&buffer[..len]).into_owned();
883 }
884 }
885
886 std::env::var("HOSTNAME").unwrap_or_else(|_| "unknown-host".to_string())
887}
888
889#[cfg(windows)]
890fn current_hostname() -> String {
891 std::env::var("COMPUTERNAME")
892 .or_else(|_| std::env::var("HOSTNAME"))
893 .unwrap_or_else(|_| "unknown-host".to_string())
894}
895
896#[cfg(not(any(unix, windows)))]
897fn current_hostname() -> String {
898 std::env::var("HOSTNAME").unwrap_or_else(|_| "unknown-host".to_string())
899}
900
901fn lock_owner_is_alive(metadata: &LockMetadata) -> bool {
908 if !process_alive(metadata.pid) {
909 return false;
910 }
911
912 let Some(recorded_start_time) = metadata.process_start_time else {
913 return true;
914 };
915 let Some(current_identity) = process_identity(metadata.pid) else {
916 return true;
917 };
918
919 if current_identity.start_time != recorded_start_time {
920 return false;
921 }
922
923 match &metadata.boot_id {
924 Some(recorded_boot_id) => current_identity
925 .boot_id
926 .as_deref()
927 .map_or(true, |current_boot_id| current_boot_id == recorded_boot_id),
928 None => true,
929 }
930}
931
932#[cfg(target_os = "linux")]
933fn process_identity(pid: u32) -> Option<ProcessIdentity> {
934 let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
937 let start_time = stat
938 .rsplit_once(") ")?
939 .1
940 .split_ascii_whitespace()
941 .nth(19)?
942 .parse()
943 .ok()?;
944 let boot_id = fs::read_to_string("/proc/sys/kernel/random/boot_id")
945 .ok()?
946 .trim()
947 .to_owned();
948 if boot_id.is_empty() {
949 return None;
950 }
951
952 Some(ProcessIdentity {
953 start_time,
954 boot_id: Some(boot_id),
955 })
956}
957
958#[cfg(target_os = "macos")]
959fn process_identity(pid: u32) -> Option<ProcessIdentity> {
960 if pid == 0 || pid > i32::MAX as u32 {
961 return None;
962 }
963
964 const PROC_PIDTBSDINFO: libc::c_int = 3;
967 let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::zeroed();
968 let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
969 let written = unsafe {
970 proc_pidinfo(
971 pid as libc::c_int,
972 PROC_PIDTBSDINFO,
973 0,
974 info.as_mut_ptr().cast(),
975 size,
976 )
977 };
978 if written != size {
979 return None;
980 }
981 let info = unsafe { info.assume_init() };
982 let start_time = info
983 .pbi_start_tvsec
984 .checked_mul(1_000_000)?
985 .checked_add(info.pbi_start_tvusec)?;
986
987 Some(ProcessIdentity {
988 start_time,
989 boot_id: None,
990 })
991}
992
993#[cfg(windows)]
994fn process_identity(_pid: u32) -> Option<ProcessIdentity> {
995 None
999}
1000
1001#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
1002fn process_identity(_pid: u32) -> Option<ProcessIdentity> {
1003 None
1004}
1005
1006#[cfg(target_os = "macos")]
1007unsafe extern "C" {
1008 fn proc_pidinfo(
1009 pid: libc::c_int,
1010 flavor: libc::c_int,
1011 arg: u64,
1012 buffer: *mut libc::c_void,
1013 buffersize: libc::c_int,
1014 ) -> libc::c_int;
1015}
1016
1017#[cfg(unix)]
1018pub(crate) fn process_alive(pid: u32) -> bool {
1019 if pid == 0 || pid > i32::MAX as u32 {
1020 return false;
1021 }
1022
1023 let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
1024 if result == 0 {
1025 return true;
1026 }
1027
1028 io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
1029}
1030
1031#[cfg(windows)]
1032pub(crate) fn process_alive(pid: u32) -> bool {
1033 if pid == 0 {
1034 return false;
1035 }
1036 let filter = format!("PID eq {pid}");
1037 let Ok(output) = std::process::Command::new("tasklist")
1038 .args(["/FI", &filter, "/FO", "CSV", "/NH"])
1039 .output()
1040 else {
1041 return true;
1042 };
1043
1044 if !output.status.success() {
1045 return true;
1046 }
1047
1048 let stdout = String::from_utf8_lossy(&output.stdout);
1049
1050 if stdout.contains("No tasks are running") {
1061 return false;
1062 }
1063 stdout.contains(&format!("\"{pid}\""))
1064}
1065
1066#[cfg(not(any(unix, windows)))]
1067pub(crate) fn process_alive(_pid: u32) -> bool {
1068 true
1069}
1070
1071#[cfg(test)]
1072mod tests {
1073 use super::*;
1074 use std::sync::atomic::{AtomicUsize, Ordering};
1075 use std::sync::{mpsc, Arc, Barrier};
1076
1077 fn test_config() -> LockConfig {
1078 LockConfig {
1079 heartbeat_interval_ms: 25,
1080 stale_heartbeat_ms: 2_000,
1081 live_owner_warn_ms: LIVE_OWNER_WARN_MS,
1082 poll_interval_ms: 10,
1083 }
1084 }
1085
1086 fn test_lock_path() -> (tempfile::TempDir, PathBuf) {
1087 let dir = tempfile::tempdir().expect("create temp dir");
1088 let path = dir.path().join("test.lock");
1089 (dir, path)
1090 }
1091
1092 fn write_synthetic_lock(path: &Path, metadata: &LockMetadata) {
1093 let mut file = open_new_lock_file(path).expect("create synthetic lock");
1094 write_lock_metadata_to_file(&mut file, metadata).expect("write synthetic lock");
1095 }
1096
1097 #[derive(Serialize)]
1098 struct LegacyLockMetadata<'a> {
1099 pid: u32,
1100 hostname: &'a str,
1101 created_at_ms: u64,
1102 heartbeat_at_ms: u64,
1103 writer_epoch: &'a str,
1104 }
1105
1106 fn write_legacy_lock(path: &Path, metadata: &LockMetadata) -> String {
1107 let legacy = LegacyLockMetadata {
1108 pid: metadata.pid,
1109 hostname: &metadata.hostname,
1110 created_at_ms: metadata.created_at_ms,
1111 heartbeat_at_ms: metadata.heartbeat_at_ms,
1112 writer_epoch: &metadata.writer_epoch,
1113 };
1114 let contents = format!(
1115 "{}\n",
1116 serde_json::to_string(&legacy).expect("serialize legacy lock")
1117 );
1118 fs::write(path, &contents).expect("write legacy synthetic lock");
1119 contents
1120 }
1121
1122 fn synthetic_metadata(pid: u32, hostname: String, created_at_ms: u64) -> LockMetadata {
1123 LockMetadata {
1124 pid,
1125 hostname,
1126 process_start_time: None,
1129 boot_id: None,
1130 created_at_ms,
1131 heartbeat_at_ms: created_at_ms,
1132 writer_epoch: format!("synthetic-{pid}-{created_at_ms}"),
1133 }
1134 }
1135
1136 fn current_process_metadata() -> LockMetadata {
1137 let now = now_ms();
1138 let pid = std::process::id();
1139 let process_identity = process_identity(pid);
1140 let mut metadata = synthetic_metadata(pid, current_hostname(), now);
1141 metadata.process_start_time = process_identity
1142 .as_ref()
1143 .map(|identity| identity.start_time);
1144 metadata.boot_id = process_identity.and_then(|identity| identity.boot_id);
1145 metadata
1146 }
1147
1148 fn different_start_time(start_time: u64) -> u64 {
1149 start_time.checked_add(1).unwrap_or(start_time - 1)
1150 }
1151
1152 #[test]
1153 fn lock_operation_trace_lines_are_debug_not_info() {
1154 let source = include_str!("fs_lock.rs");
1155 assert!(source.contains("slog_debug!(\"acquired filesystem lock at {}\", path.display())"));
1156 assert!(
1157 source.contains("slog_debug!(\"released filesystem lock at {}\", self.path.display())")
1158 );
1159 assert!(!source.contains("slog_info!(\"acquired filesystem lock at {}\", path.display())"));
1160 assert!(
1161 !source.contains("slog_info!(\"released filesystem lock at {}\", self.path.display())")
1162 );
1163 }
1164
1165 #[test]
1166 fn acquire_creates_lockfile_and_unlocks_on_drop() {
1167 let (_dir, path) = test_lock_path();
1168
1169 let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
1170 let metadata = read_lock_metadata(&path).expect("read lock metadata");
1171 assert_eq!(metadata.pid, std::process::id());
1172 assert_eq!(metadata.hostname, current_hostname());
1173 assert_eq!(metadata.created_at_ms, guard.metadata.created_at_ms);
1174 assert_eq!(metadata.writer_epoch, guard.metadata.writer_epoch);
1175 #[cfg(unix)]
1176 {
1177 use std::os::unix::fs::PermissionsExt;
1178 assert_eq!(
1179 fs::metadata(&path).unwrap().permissions().mode() & 0o777,
1180 0o600
1181 );
1182 }
1183
1184 drop(guard);
1185 assert!(!path.exists());
1186 }
1187
1188 #[test]
1189 fn permission_denied_is_treated_as_transient_create_contention() {
1190 let err = io::Error::from(io::ErrorKind::PermissionDenied);
1193 assert!(is_transient_create_contention(&err));
1194 }
1195
1196 #[test]
1197 fn unrelated_io_errors_are_not_treated_as_contention() {
1198 let err = io::Error::from(io::ErrorKind::NotFound);
1201 assert!(!is_transient_create_contention(&err));
1202 }
1203
1204 #[cfg(windows)]
1205 #[test]
1206 fn windows_sharing_violation_is_treated_as_transient_create_contention() {
1207 let err = io::Error::from_raw_os_error(32);
1210 assert!(is_transient_create_contention(&err));
1211 }
1212
1213 #[test]
1214 fn reclaim_refuses_to_delete_a_different_owners_lock() {
1215 let (_dir, path) = test_lock_path();
1216
1217 let owner_b = synthetic_metadata(4242, "host-b".to_string(), now_ms());
1219 create_lock_file_atomically(&path, &owner_b).expect("write owner B lock");
1220
1221 let judged_a = synthetic_metadata(1111, "host-a".to_string(), now_ms() - 1_000_000);
1224 let removed = reclaim_lock_file(&path, &judged_a).expect("reclaim");
1225 assert!(!removed, "must not remove a different owner's lock");
1226 assert!(path.exists(), "owner B's lock must survive");
1227 let still = read_lock_metadata(&path).expect("still readable");
1228 assert_eq!(still.pid, 4242, "owner B's lock intact");
1229 }
1230
1231 #[test]
1232 fn reclaim_deletes_when_identity_still_matches() {
1233 let (_dir, path) = test_lock_path();
1234 let owner = synthetic_metadata(1111, "host-a".to_string(), 5_000);
1235 create_lock_file_atomically(&path, &owner).expect("write lock");
1236
1237 let removed = reclaim_lock_file(&path, &owner).expect("reclaim");
1239 assert!(removed, "matching-identity stale lock should be removed");
1240 assert!(!path.exists());
1241
1242 assert!(!reclaim_lock_file(&path, &owner).expect("reclaim missing"));
1244 }
1245
1246 #[test]
1247 fn try_acquire_once_never_waits_behind_live_owner() {
1248 let (_dir, path) = test_lock_path();
1249 let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
1250 let contender_path = path.clone();
1251 let (started_tx, started_rx) = mpsc::sync_channel(1);
1252 let (result_tx, result_rx) = mpsc::sync_channel(1);
1253 let contender = std::thread::spawn(move || {
1254 let _ = started_tx.send(());
1255 let _ = result_tx.send(try_acquire_once(&contender_path));
1256 });
1257
1258 started_rx
1259 .recv_timeout(Duration::from_secs(5))
1260 .expect("contender should start");
1261 let result = match result_rx.recv_timeout(Duration::from_secs(2)) {
1262 Ok(result) => result,
1263 Err(mpsc::RecvTimeoutError::Disconnected) => {
1264 contender.join().expect("contender should not panic");
1265 panic!("contender exited without reporting a result");
1266 }
1267 Err(mpsc::RecvTimeoutError::Timeout) => {
1268 drop(guard);
1269 match result_rx.recv_timeout(Duration::from_secs(1)) {
1270 Ok(_) | Err(mpsc::RecvTimeoutError::Disconnected) => {
1271 let _ = contender.join();
1272 }
1273 Err(mpsc::RecvTimeoutError::Timeout) => {}
1274 }
1275 panic!("try-acquire blocked behind the live owner");
1276 }
1277 };
1278
1279 contender.join().expect("contender should exit");
1280 assert!(matches!(result, Err(AcquireError::Timeout)));
1281 }
1282
1283 #[test]
1284 fn acquire_serializes_concurrent_callers() {
1285 let (_dir, path) = test_lock_path();
1286 let path = Arc::new(path);
1287 let barrier = Arc::new(Barrier::new(3));
1288 let inside = Arc::new(AtomicUsize::new(0));
1289 let entered = Arc::new(AtomicUsize::new(0));
1290 let max_inside = Arc::new(AtomicUsize::new(0));
1291
1292 let mut handles = Vec::new();
1293 for _ in 0..2 {
1294 let path = Arc::clone(&path);
1295 let barrier = Arc::clone(&barrier);
1296 let inside = Arc::clone(&inside);
1297 let entered = Arc::clone(&entered);
1298 let max_inside = Arc::clone(&max_inside);
1299 handles.push(thread::spawn(move || {
1300 barrier.wait();
1301 let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
1302 .expect("thread acquire lock");
1303 let previous = inside.fetch_add(1, Ordering::SeqCst);
1304 assert_eq!(previous, 0, "two lock holders overlapped");
1305 entered.fetch_add(1, Ordering::SeqCst);
1306 max_inside.fetch_max(previous + 1, Ordering::SeqCst);
1307 thread::sleep(Duration::from_millis(75));
1308 inside.fetch_sub(1, Ordering::SeqCst);
1309 drop(guard);
1310 }));
1311 }
1312
1313 barrier.wait();
1314 for handle in handles {
1315 handle.join().expect("join worker");
1316 }
1317
1318 assert_eq!(entered.load(Ordering::SeqCst), 2);
1319 assert_eq!(max_inside.load(Ordering::SeqCst), 1);
1320 assert!(!path.exists());
1321 }
1322
1323 #[test]
1324 fn failed_atomic_replacement_preserves_existing_destination() {
1325 let dir = tempfile::tempdir().expect("create temp dir");
1326 let source = dir.path().join("source.tmp");
1327 let destination = dir.path().join("artifact.bin");
1328 fs::write(&source, b"new artifact").expect("write source");
1329 fs::write(&destination, b"valid old artifact").expect("write destination");
1330
1331 let error = rename_over_with(&source, &destination, |_from, _to| {
1332 Err(io::Error::new(
1333 io::ErrorKind::PermissionDenied,
1334 "injected replacement failure",
1335 ))
1336 })
1337 .expect_err("replacement must fail");
1338
1339 assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
1340 assert_eq!(
1341 fs::read(&destination).expect("read preserved destination"),
1342 b"valid old artifact"
1343 );
1344 assert_eq!(
1345 fs::read(&source).expect("read retained source"),
1346 b"new artifact"
1347 );
1348 }
1349
1350 #[test]
1351 fn heartbeat_updates_lockfile_timestamp() {
1352 let (_dir, path) = test_lock_path();
1353 let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
1354 let initial_metadata = read_lock_metadata(&path).expect("read initial metadata");
1355 let initial = initial_metadata.heartbeat_at_ms;
1356
1357 let deadline = std::time::Instant::now() + Duration::from_millis(2_000);
1367 let mut updated = initial;
1368 while std::time::Instant::now() < deadline {
1369 thread::sleep(Duration::from_millis(50));
1370 match read_lock_metadata(&path) {
1371 Ok(meta) => {
1372 updated = meta.heartbeat_at_ms;
1373 if updated > initial {
1374 break;
1375 }
1376 }
1377 Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
1378 continue;
1381 }
1382 Err(other) => panic!("read updated metadata: {other:?}"),
1383 }
1384 }
1385 assert!(
1386 updated > initial,
1387 "heartbeat timestamp did not advance within 2s"
1388 );
1389 let updated_metadata = read_lock_metadata(&path).expect("read final metadata");
1390 assert_eq!(
1391 updated_metadata.process_start_time, guard.metadata.process_start_time,
1392 "heartbeat rewrite must preserve the owner's process start time"
1393 );
1394 assert_eq!(
1395 updated_metadata.boot_id, guard.metadata.boot_id,
1396 "heartbeat rewrite must preserve the owner's boot identity"
1397 );
1398 drop(guard);
1399 }
1400
1401 #[test]
1402 fn dead_pid_lock_is_reclaimed() {
1403 let (_dir, path) = test_lock_path();
1404 let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
1405 write_synthetic_lock(&path, &metadata);
1406
1407 let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
1408 .expect("reclaim dead pid lock");
1409 let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
1410 assert_eq!(metadata.pid, std::process::id());
1411 drop(guard);
1412 }
1413
1414 #[test]
1415 fn zero_timeout_dead_pid_reclaim_acquires_after_removing_stale_file() {
1416 let (_dir, path) = test_lock_path();
1417 let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
1418 write_synthetic_lock(&path, &metadata);
1419
1420 let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
1421 .expect("zero-timeout acquire should claim the reaped stale lock");
1422 let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
1423 assert_eq!(metadata.pid, std::process::id());
1424 drop(guard);
1425 }
1426
1427 #[test]
1428 fn stale_heartbeat_from_live_pid_blocks() {
1429 let (_dir, path) = test_lock_path();
1430 let mut metadata = current_process_metadata();
1431 #[cfg(any(target_os = "linux", target_os = "macos"))]
1432 {
1433 let identity = process_identity(std::process::id())
1434 .expect("current process should have a start-time identity");
1435 assert_eq!(metadata.process_start_time, Some(identity.start_time));
1436 assert_eq!(metadata.boot_id, identity.boot_id);
1437 }
1438 metadata.created_at_ms = now_ms().saturating_sub(60_000);
1439 metadata.heartbeat_at_ms = now_ms().saturating_sub(60_000);
1440 write_synthetic_lock(&path, &metadata);
1441
1442 let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
1443 assert!(matches!(result, Err(AcquireError::Timeout)));
1444 assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
1445
1446 remove_lock_file(&path).expect("cleanup synthetic lock");
1447 }
1448
1449 #[cfg(any(target_os = "linux", target_os = "macos"))]
1450 #[test]
1451 fn live_pid_with_wrong_start_time_is_reclaimed() {
1452 let (_dir, path) = test_lock_path();
1453 let mut metadata = current_process_metadata();
1454 let current_identity = process_identity(std::process::id())
1455 .expect("current process should have a start-time identity");
1456 metadata.process_start_time = Some(different_start_time(current_identity.start_time));
1457 metadata.boot_id = current_identity.boot_id;
1458 write_synthetic_lock(&path, &metadata);
1459
1460 let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
1461 .expect("zero-timeout acquire should reclaim a reused PID");
1462 assert_eq!(guard.metadata.pid, std::process::id());
1463 assert_eq!(
1464 guard.metadata.process_start_time,
1465 Some(current_identity.start_time)
1466 );
1467 drop(guard);
1468 }
1469
1470 #[cfg(target_os = "linux")]
1471 #[test]
1472 fn live_pid_with_wrong_boot_id_is_reclaimed() {
1473 let (_dir, path) = test_lock_path();
1474 let mut metadata = current_process_metadata();
1475 let current_identity = process_identity(std::process::id())
1476 .expect("current process should have a start-time identity");
1477 metadata.boot_id = Some(format!("wrong-{}", current_identity.boot_id.unwrap()));
1478 write_synthetic_lock(&path, &metadata);
1479
1480 let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
1481 .expect("zero-timeout acquire should reclaim a rebooted PID identity");
1482 assert_eq!(guard.metadata.pid, std::process::id());
1483 drop(guard);
1484 }
1485
1486 #[test]
1487 fn legacy_live_pid_lock_keeps_pid_only_liveness() {
1488 let (_dir, path) = test_lock_path();
1489 let stale_at = now_ms().saturating_sub(60_000);
1490 let mut metadata = synthetic_metadata(std::process::id(), current_hostname(), stale_at);
1491 metadata.heartbeat_at_ms = stale_at;
1492 let original = write_legacy_lock(&path, &metadata);
1493 assert!(!original.contains("process_start_time"));
1494 assert!(!original.contains("boot_id"));
1495
1496 let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
1497 assert!(matches!(result, Err(AcquireError::Timeout)));
1498 assert_eq!(
1499 fs::read_to_string(&path).expect("read legacy lock"),
1500 original
1501 );
1502
1503 remove_lock_file(&path).expect("cleanup legacy lock");
1504 }
1505
1506 #[test]
1507 fn legacy_dead_pid_lock_is_reclaimed() {
1508 let (_dir, path) = test_lock_path();
1509 let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
1510 let original = write_legacy_lock(&path, &metadata);
1511 assert!(!original.contains("process_start_time"));
1512 assert!(!original.contains("boot_id"));
1513
1514 let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
1515 .expect("zero-timeout acquire should reclaim a legacy dead PID lock");
1516 assert_eq!(guard.metadata.pid, std::process::id());
1517 drop(guard);
1518 }
1519
1520 #[test]
1521 fn healthy_live_owner_blocks() {
1522 let (_dir, path) = test_lock_path();
1523 let metadata = current_process_metadata();
1524 write_synthetic_lock(&path, &metadata);
1525
1526 let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
1527 assert!(matches!(result, Err(AcquireError::Timeout)));
1528
1529 remove_lock_file(&path).expect("cleanup synthetic lock");
1530 }
1531
1532 #[test]
1533 fn malformed_lockfile_is_reclaimed() {
1534 let (_dir, path) = test_lock_path();
1535 fs::write(&path, b"not valid json").expect("write malformed lock");
1536
1537 let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
1538 .expect("reclaim malformed lock");
1539 let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
1540 assert_eq!(metadata.pid, std::process::id());
1541 drop(guard);
1542 }
1543
1544 #[test]
1545 fn cross_host_lock_is_not_stolen_before_extended_stale_threshold() {
1546 let (_dir, path) = test_lock_path();
1547 let now = now_ms();
1548 let mut metadata = current_process_metadata();
1549 metadata.hostname = format!("{}-other", current_hostname());
1550 metadata.process_start_time = metadata.process_start_time.map(different_start_time);
1551 metadata.created_at_ms = now;
1552 metadata.heartbeat_at_ms = now;
1553 metadata.writer_epoch = format!("cross-host-{now}");
1554 #[cfg(any(target_os = "linux", target_os = "macos"))]
1555 assert_ne!(
1556 metadata.process_start_time,
1557 process_identity(std::process::id()).map(|identity| identity.start_time)
1558 );
1559 write_synthetic_lock(&path, &metadata);
1560
1561 let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
1562 assert!(matches!(result, Err(AcquireError::Timeout)));
1563 assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
1564
1565 remove_lock_file(&path).expect("cleanup synthetic lock");
1566 }
1567
1568 #[test]
1569 fn stale_cross_host_lock_is_reclaimed_after_extended_threshold() {
1570 let (_dir, path) = test_lock_path();
1571 let stale_at =
1572 now_ms().saturating_sub(test_config().cross_host_stale_heartbeat_ms() + 1_000);
1573 let mut metadata = current_process_metadata();
1574 metadata.hostname = format!("{}-other", current_hostname());
1575 metadata.process_start_time = metadata.process_start_time.map(different_start_time);
1576 metadata.created_at_ms = stale_at;
1577 metadata.heartbeat_at_ms = stale_at;
1578 metadata.writer_epoch = format!("cross-host-{stale_at}");
1579 write_synthetic_lock(&path, &metadata);
1580
1581 let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
1582 .expect("reclaim stale cross-host lock");
1583 let reclaimed = read_lock_metadata(&path).expect("read reclaimed lock");
1584 assert_eq!(reclaimed.hostname, current_hostname());
1585 assert_ne!(reclaimed.created_at_ms, metadata.created_at_ms);
1586 drop(guard);
1587 }
1588
1589 #[test]
1590 fn live_owner_over_10min_warns_but_blocks() {
1591 let (_dir, path) = test_lock_path();
1592 let mut metadata = current_process_metadata();
1593 metadata.created_at_ms = now_ms().saturating_sub(11 * 60 * 1_000);
1594 metadata.heartbeat_at_ms = now_ms();
1595 write_synthetic_lock(&path, &metadata);
1596
1597 let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
1598 assert!(matches!(result, Err(AcquireError::Timeout)));
1599 assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
1600
1601 remove_lock_file(&path).expect("cleanup synthetic lock");
1602 }
1603
1604 #[test]
1605 fn drop_stops_heartbeat_thread() {
1606 let (_dir, path) = test_lock_path();
1607 let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
1608 drop(guard);
1609
1610 thread::sleep(Duration::from_millis(
1611 test_config().heartbeat_interval_ms * 3,
1612 ));
1613 assert!(
1614 !path.exists(),
1615 "heartbeat recreated or kept updating lockfile"
1616 );
1617 }
1618
1619 #[test]
1620 fn heartbeat_error_classification_terminal_vs_transient() {
1621 assert!(heartbeat_error_is_terminal(&HeartbeatError::LockGone));
1623 assert!(heartbeat_error_is_terminal(&HeartbeatError::NotOwner));
1624 assert!(!heartbeat_error_is_terminal(&HeartbeatError::Io(
1627 io::Error::other("disk blip")
1628 )));
1629 let malformed: serde_json::Error =
1630 serde_json::from_str::<LockMetadata>("not json").unwrap_err();
1631 assert!(!heartbeat_error_is_terminal(&HeartbeatError::Malformed(
1632 malformed
1633 )));
1634 }
1635
1636 #[test]
1637 fn heartbeat_survives_transient_malformed_and_recovers() {
1638 let (_dir, path) = test_lock_path();
1646 let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
1647 let owner = guard.metadata.clone();
1648
1649 fs::write(&path, b"{ not valid json").expect("corrupt lockfile");
1654
1655 thread::sleep(Duration::from_millis(
1658 test_config().heartbeat_interval_ms * 4,
1659 ));
1660
1661 let sentinel = now_ms().saturating_sub(1_000_000);
1672 let mut restored = owner.clone();
1673 restored.heartbeat_at_ms = sentinel;
1674 atomic_write_lock_metadata(&path, &restored).expect("atomically restore lock metadata");
1675
1676 let deadline = std::time::Instant::now() + Duration::from_millis(3_000);
1679 let mut recovered = false;
1680 while std::time::Instant::now() < deadline {
1681 thread::sleep(Duration::from_millis(25));
1682 match read_lock_metadata(&path) {
1683 Ok(meta)
1684 if meta.created_at_ms == owner.created_at_ms
1685 && meta.heartbeat_at_ms > sentinel =>
1686 {
1687 recovered = true;
1688 break;
1689 }
1690 _ => continue,
1691 }
1692 }
1693 assert!(
1694 recovered,
1695 "heartbeat did not recover after a transient malformed read — thread likely died"
1696 );
1697 drop(guard);
1698 }
1699}