Skip to main content

snip_sync/
server_lock.rs

1//! Kernel-backed singleton lock for the `snip-sync` server.
2//!
3//! Authority for mutual exclusion is the operating system kernel; the
4//! persistent lock file is diagnostic metadata only. The Unix path uses
5//! `flock`; Windows uses `LockFileEx`. Unsupported platforms return an
6//! explicit error rather than silently weakening exclusion.
7//!
8//! The server acquires this lock nonblocking at startup. While the lock
9//! is held, current owner metadata is published in the persistent lock file
10//! (and, atomically, in an `*.owner` record beside it) while the listeners
11//! run. Dropping the guard releases the kernel lock; the persistent lock
12//! file remains on disk. Current servers do not create a separate PID file.
13//!
14//! The owner record is published to a sidecar file through a temporary file
15//! and a rename, because the in-place record inside the lock file is
16//! truncated and rewritten: a concurrent reader could otherwise observe it
17//! empty and lose the ability to identify (and stop) the running server.
18//!
19//! A new server can start after a crashed owner exits because the kernel
20//! releases the lock when the previous owner closes its file descriptor
21//! at process teardown. The leftover metadata is harmless.
22
23use serde::{Deserialize, Serialize};
24use std::fs::{File, OpenOptions};
25use std::io::{Seek, Write};
26#[cfg(unix)]
27use std::os::unix::fs::PermissionsExt;
28use std::path::{Path, PathBuf};
29
30/// Diagnostic identity record written into the server lock file after
31/// the kernel lock is acquired. The kernel owns mutual exclusion; this
32/// record is for diagnostics only.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct ServerLockIdentity {
35    /// Schema version for forward compatibility.
36    pub schema_version: u32,
37    /// Process ID of the owner.
38    pub pid: u32,
39    /// Start-time token of the owner, when the platform exposes one.
40    #[serde(default)]
41    pub start_token: Option<String>,
42    /// Random nonce generated at acquisition time.
43    pub nonce: String,
44    /// Unix timestamp in milliseconds when the kernel lock was acquired.
45    pub acquired_at_unix_ms: u64,
46}
47
48const SERVER_LOCK_NAME: &str = "snip-sync.server.lock";
49const SERVER_LOCK_SCHEMA_VERSION: u32 = 1;
50/// Name of the legacy PID file, kept as a bounded upgrade fallback for
51/// identifying the owner of a busy lock.
52const LEGACY_PID_FILE_NAME: &str = "snip-sync.pid";
53
54/// Errors from [`ServerLock::try_acquire`].
55#[derive(Debug)]
56pub enum ServerLockError {
57    /// Another server holds the kernel lock.
58    Busy {
59        /// Best-effort parsed metadata of the current owner, when readable.
60        owner: Option<ServerLockIdentity>,
61    },
62    /// Underlying I/O failure.
63    Io(std::io::Error),
64    /// The current platform has no kernel-backed lock implementation.
65    UnsupportedPlatform,
66}
67
68impl std::fmt::Display for ServerLockError {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        match self {
71            Self::Busy { owner } => match owner {
72                Some(id) => write!(
73                    f,
74                    "snip-sync server already running (pid={}, nonce={})",
75                    id.pid, id.nonce
76                ),
77                None => write!(f, "snip-sync server already running"),
78            },
79            Self::Io(e) => write!(f, "server lock io error: {e}"),
80            Self::UnsupportedPlatform => write!(
81                f,
82                "server lock is not supported on this platform; refusing to weaken exclusion"
83            ),
84        }
85    }
86}
87
88impl std::error::Error for ServerLockError {}
89
90impl From<std::io::Error> for ServerLockError {
91    fn from(e: std::io::Error) -> Self {
92        Self::Io(e)
93    }
94}
95
96/// RAII guard for the kernel-backed server singleton lock.
97#[derive(Debug)]
98pub struct ServerLock {
99    file: Option<File>,
100    path: PathBuf,
101    identity: ServerLockIdentity,
102}
103
104impl ServerLock {
105    /// Path of the persistent lock file.
106    pub fn path(&self) -> &Path {
107        &self.path
108    }
109
110    /// Identity record published after acquisition.
111    pub fn identity(&self) -> &ServerLockIdentity {
112        &self.identity
113    }
114
115    /// Nonce generated at acquisition time.
116    pub fn nonce(&self) -> &str {
117        &self.identity.nonce
118    }
119}
120
121impl Drop for ServerLock {
122    fn drop(&mut self) {
123        #[cfg(unix)]
124        release_unix_lock(self.file.as_ref());
125        #[cfg(windows)]
126        release_windows_lock(self.file.as_ref());
127        self.file = None;
128    }
129}
130
131#[cfg(unix)]
132fn release_unix_lock(file: Option<&File>) {
133    if let Some(file) = file {
134        use std::os::fd::AsRawFd;
135        unsafe {
136            libc::flock(file.as_raw_fd(), libc::LOCK_UN);
137        }
138    }
139}
140
141#[cfg(windows)]
142fn release_windows_lock(file: Option<&File>) {
143    if let Some(file) = file {
144        use std::os::windows::io::AsRawHandle;
145        use windows_sys::Win32::Storage::FileSystem::UnlockFileEx;
146        let handle = file.as_raw_handle();
147        let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED =
148            unsafe { std::mem::zeroed() };
149        overlapped.Anonymous.Anonymous.Offset = LOCKED_BYTE_OFFSET;
150        overlapped.Anonymous.Anonymous.OffsetHigh = 0;
151        unsafe {
152            UnlockFileEx(handle, 0, LOCKED_BYTE_COUNT, 0, &mut overlapped);
153        }
154    }
155}
156
157#[cfg(windows)]
158const LOCKED_BYTE_COUNT: u32 = 1;
159// Lock a single byte at offset `u32::MAX`. This range is far beyond any
160// real file content, so Windows does not deny read or write access to
161// the actual lock-file bytes. Only another attempt to lock the same
162// range returns ERROR_LOCK_VIOLATION.
163#[cfg(windows)]
164const LOCKED_BYTE_OFFSET: u32 = u32::MAX;
165
166/// Path of the persistent server lock file.
167pub fn server_lock_path(state_dir: &Path) -> PathBuf {
168    state_dir.join(SERVER_LOCK_NAME)
169}
170
171/// Path of the atomically published owner record beside the server lock
172/// file.
173///
174/// The record lives in its own file because the lock file itself is
175/// truncated and rewritten in place, so a concurrent reader could observe
176/// it empty and lose the ability to identify the running server.
177fn server_owner_path(lock_path: &Path) -> PathBuf {
178    let mut name = lock_path
179        .file_name()
180        .map(|name| name.to_os_string())
181        .unwrap_or_default();
182    name.push(".owner");
183    lock_path.with_file_name(name)
184}
185
186/// True when the error means "the call was interrupted by a signal" and can
187/// be retried unchanged.
188#[cfg(unix)]
189fn is_retryable_lock_error(error: &std::io::Error) -> bool {
190    error.raw_os_error() == Some(libc::EINTR)
191}
192
193#[cfg(not(unix))]
194fn is_retryable_lock_error(_error: &std::io::Error) -> bool {
195    false
196}
197
198/// Try to take the exclusive `flock` without blocking.
199///
200/// Returns `Ok(false)` when the lock is held by somebody else. A call
201/// interrupted by a signal (`EINTR`) is retried: it is a transient
202/// condition, not an I/O failure, and must not abort server startup with a
203/// misleading error.
204#[cfg(unix)]
205fn acquire_unix_lock(file: &File) -> std::io::Result<bool> {
206    use std::os::fd::AsRawFd;
207    loop {
208        let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
209        if rc == 0 {
210            return Ok(true);
211        }
212        let error = std::io::Error::last_os_error();
213        if is_retryable_lock_error(&error) {
214            continue;
215        }
216        if matches!(error.raw_os_error(), Some(libc::EWOULDBLOCK)) {
217            return Ok(false);
218        }
219        return Err(error);
220    }
221}
222
223impl ServerLock {
224    /// Try to acquire the singleton server lock without waiting.
225    pub fn try_acquire(state_dir: &Path) -> Result<Self, ServerLockError> {
226        let path = server_lock_path(state_dir);
227        if let Some(parent) = path.parent() {
228            std::fs::create_dir_all(parent)?;
229        }
230
231        let mut file = OpenOptions::new()
232            .read(true)
233            .write(true)
234            .create(true)
235            .truncate(false)
236            .open(&path)?;
237
238        #[cfg(unix)]
239        {
240            match acquire_unix_lock(&file) {
241                Ok(true) => {}
242                Ok(false) => {
243                    let owner = busy_owner(state_dir, &path);
244                    return Err(ServerLockError::Busy { owner });
245                }
246                Err(error) => return Err(ServerLockError::Io(error)),
247            }
248        }
249
250        #[cfg(windows)]
251        {
252            use std::os::windows::io::AsRawHandle;
253            use windows_sys::Win32::Storage::FileSystem::{
254                LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx,
255            };
256            let handle = file.as_raw_handle();
257            let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED =
258                unsafe { std::mem::zeroed() };
259            overlapped.Anonymous.Anonymous.Offset = LOCKED_BYTE_OFFSET;
260            overlapped.Anonymous.Anonymous.OffsetHigh = 0;
261            let ok = unsafe {
262                LockFileEx(
263                    handle,
264                    LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
265                    0,
266                    LOCKED_BYTE_COUNT,
267                    0,
268                    &mut overlapped,
269                )
270            };
271            if ok == 0 {
272                let err = std::io::Error::last_os_error();
273                if matches!(err.raw_os_error(), Some(33) | Some(32)) {
274                    let owner = busy_owner(state_dir, &path);
275                    return Err(ServerLockError::Busy { owner });
276                }
277                return Err(ServerLockError::Io(err));
278            }
279        }
280
281        #[cfg(not(any(unix, windows)))]
282        {
283            let _ = file;
284            return Err(ServerLockError::UnsupportedPlatform);
285        }
286
287        let identity = ServerLockIdentity {
288            schema_version: SERVER_LOCK_SCHEMA_VERSION,
289            pid: std::process::id(),
290            start_token: current_start_token(),
291            nonce: generate_nonce(),
292            acquired_at_unix_ms: unix_now_ms(),
293        };
294
295        #[cfg(unix)]
296        {
297            if let Ok(meta) = std::fs::metadata(&path) {
298                let mut perms = meta.permissions();
299                perms.set_mode(0o600);
300                let _ = std::fs::set_permissions(&path, perms);
301            }
302        }
303
304        if let Err(e) = publish_identity(&path, &mut file, &identity) {
305            #[cfg(unix)]
306            release_unix_lock(Some(&file));
307            #[cfg(windows)]
308            release_windows_lock(Some(&file));
309            return Err(ServerLockError::Io(e));
310        }
311
312        Ok(ServerLock {
313            file: Some(file),
314            path,
315            identity,
316        })
317    }
318}
319
320/// Publish the owner identity.
321///
322/// The authoritative record is written to a temporary file beside the owner
323/// path and renamed over it, so a concurrent reader always observes a
324/// complete record. The in-place copy inside the lock file is kept as a
325/// diagnostic record for operators.
326fn publish_identity(
327    lock_path: &Path,
328    file: &mut File,
329    identity: &ServerLockIdentity,
330) -> std::io::Result<()> {
331    let serialized = toml::to_string_pretty(identity)
332        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
333
334    publish_owner_sidecar(&server_owner_path(lock_path), serialized.as_bytes())?;
335
336    file.set_len(0)?;
337    file.seek(std::io::SeekFrom::Start(0))?;
338    file.write_all(serialized.as_bytes())?;
339    file.sync_all()?;
340    Ok(())
341}
342
343/// Write `contents` to `owner_path` atomically: a uniquely named temporary
344/// file next to the target is written, fsynced, and renamed over the target.
345fn publish_owner_sidecar(owner_path: &Path, contents: &[u8]) -> std::io::Result<()> {
346    let parent = owner_path.parent().unwrap_or_else(|| Path::new("."));
347    let file_name = owner_path
348        .file_name()
349        .map(|name| name.to_string_lossy().into_owned())
350        .unwrap_or_else(|| format!("{SERVER_LOCK_NAME}.owner"));
351    let temp_path = parent.join(format!("{file_name}.tmp-{}", uuid::Uuid::new_v4()));
352
353    let write_result = (|| -> std::io::Result<()> {
354        let mut temp = {
355            #[cfg(unix)]
356            {
357                // Owner-private permissions, set at creation time (no
358                // chmod window), like the lock file itself.
359                use std::os::unix::fs::OpenOptionsExt;
360                let mut options = OpenOptions::new();
361                options.write(true).create_new(true).mode(0o600);
362                options.open(&temp_path)
363            }
364            #[cfg(not(unix))]
365            {
366                OpenOptions::new()
367                    .write(true)
368                    .create_new(true)
369                    .open(&temp_path)
370            }
371        }?;
372        temp.write_all(contents)?;
373        temp.sync_all()?;
374        Ok(())
375    })();
376    if let Err(error) = write_result {
377        let _ = std::fs::remove_file(&temp_path);
378        return Err(error);
379    }
380
381    if let Err(error) = std::fs::rename(&temp_path, owner_path) {
382        let _ = std::fs::remove_file(&temp_path);
383        return Err(error);
384    }
385
386    // Make the rename itself durable.
387    if let Ok(directory) = File::open(parent) {
388        let _ = directory.sync_all();
389    }
390    Ok(())
391}
392
393/// Best-effort read of the on-disk server lock metadata.
394///
395/// The atomically published owner record is preferred; the in-place record
396/// inside the lock file is the fallback for metadata written by an older
397/// build.
398pub fn read_owner(path: &Path) -> Option<ServerLockIdentity> {
399    if let Some(identity) = read_identity_file(&server_owner_path(path)) {
400        return Some(identity);
401    }
402    read_identity_file(path)
403}
404
405fn read_identity_file(path: &Path) -> Option<ServerLockIdentity> {
406    let raw = std::fs::read_to_string(path).ok()?;
407    if raw.trim().is_empty() {
408        return None;
409    }
410    toml::from_str(&raw).ok()
411}
412
413/// Resolve the owner of a busy lock.
414///
415/// The published owner record is authoritative. When it cannot be read at
416/// all, the legacy PID file is consulted as a bounded upgrade fallback, so
417/// `stop` can still act on a live server instead of dead-ending on missing
418/// metadata.
419fn busy_owner(state_dir: &Path, lock_path: &Path) -> Option<ServerLockIdentity> {
420    read_owner(lock_path).or_else(|| legacy_pid_owner(state_dir))
421}
422
423/// Build an owner identity from a legacy PID file.
424fn legacy_pid_owner(state_dir: &Path) -> Option<ServerLockIdentity> {
425    let pid_path = state_dir.join(LEGACY_PID_FILE_NAME);
426    let (pid, start_token) = match crate::process::parse_pid_file(&pid_path) {
427        crate::process::ParsedPidFile::Structured(record) => (record.pid, record.start_token),
428        crate::process::ParsedPidFile::LegacyPid(pid) => (pid, None),
429        crate::process::ParsedPidFile::Empty | crate::process::ParsedPidFile::Malformed(_) => {
430            return None;
431        }
432    };
433    Some(ServerLockIdentity {
434        schema_version: SERVER_LOCK_SCHEMA_VERSION,
435        pid,
436        start_token,
437        nonce: format!("legacy-pid-{pid}"),
438        // The acquisition time of a legacy record is unknown; the moment the
439        // record was observed is recorded instead.
440        acquired_at_unix_ms: unix_now_ms(),
441    })
442}
443
444fn unix_now_ms() -> u64 {
445    std::time::SystemTime::now()
446        .duration_since(std::time::SystemTime::UNIX_EPOCH)
447        .map(|d| d.as_millis() as u64)
448        .unwrap_or(0)
449}
450
451fn generate_nonce() -> String {
452    use std::sync::atomic::{AtomicU64, Ordering};
453    static COUNTER: AtomicU64 = AtomicU64::new(0);
454    let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
455    let nanos = std::time::SystemTime::now()
456        .duration_since(std::time::SystemTime::UNIX_EPOCH)
457        .map(|d| d.as_nanos())
458        .unwrap_or(0);
459    format!("{:x}-{:x}-{:x}", std::process::id(), nanos, seq)
460}
461
462fn current_start_token() -> Option<String> {
463    #[cfg(target_os = "linux")]
464    {
465        let pid = std::process::id();
466        let stat_path = format!("/proc/{pid}/stat");
467        let content = std::fs::read_to_string(&stat_path).ok()?;
468        parse_linux_proc_start_token(&content)
469    }
470    #[cfg(target_os = "macos")]
471    {
472        use libc::{PROC_PIDTBSDINFO, c_int, proc_bsdinfo, proc_pidinfo};
473        let pid = std::process::id();
474        let mut info: proc_bsdinfo = unsafe { std::mem::zeroed() };
475        let ret = unsafe {
476            proc_pidinfo(
477                pid as c_int,
478                PROC_PIDTBSDINFO,
479                0,
480                &mut info as *mut _ as *mut _,
481                std::mem::size_of::<proc_bsdinfo>() as i32,
482            )
483        };
484        if ret <= 0 {
485            return None;
486        }
487        Some(format!(
488            "{}.{:06}",
489            info.pbi_start_tvsec, info.pbi_start_tvusec
490        ))
491    }
492    #[cfg(windows)]
493    {
494        use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
495        use windows_sys::Win32::System::Threading::{
496            GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
497        };
498        unsafe {
499            let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, std::process::id());
500            if handle.is_null() {
501                return None;
502            }
503            let mut creation: FILETIME = std::mem::zeroed();
504            let mut exit_time: FILETIME = std::mem::zeroed();
505            let mut kernel_time: FILETIME = std::mem::zeroed();
506            let mut user_time: FILETIME = std::mem::zeroed();
507            let ok = GetProcessTimes(
508                handle,
509                &mut creation,
510                &mut exit_time,
511                &mut kernel_time,
512                &mut user_time,
513            );
514            CloseHandle(handle);
515            if ok == 0 {
516                return None;
517            }
518            let creation =
519                ((creation.dwHighDateTime as u64) << 32) | (creation.dwLowDateTime as u64);
520            Some(creation.to_string())
521        }
522    }
523    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
524    {
525        let _ = std::process::id();
526        None
527    }
528}
529
530#[cfg(target_os = "linux")]
531fn parse_linux_proc_start_token(stat: &str) -> Option<String> {
532    let after_comm = stat.rfind(')')?;
533    let fields: Vec<&str> = stat.get(after_comm + 2..)?.split_whitespace().collect();
534    fields.get(19).map(|value| (*value).to_owned())
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540
541    #[cfg(target_os = "linux")]
542    #[test]
543    fn linux_start_token_parser_reads_field_22() {
544        let stat = "42 (name with ) parens) S f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 FIELD21 START22";
545        assert_eq!(parse_linux_proc_start_token(stat), Some("START22".into()));
546        assert_ne!(parse_linux_proc_start_token(stat), Some("FIELD21".into()));
547        assert_eq!(parse_linux_proc_start_token("1 (short) S f3"), None);
548    }
549
550    #[test]
551    fn first_acquisition_succeeds() {
552        let dir = tempfile::TempDir::new().unwrap();
553        let guard = ServerLock::try_acquire(dir.path()).unwrap();
554        assert_eq!(guard.identity().pid, std::process::id());
555        assert!(!guard.identity().nonce.is_empty());
556    }
557
558    #[test]
559    fn second_acquisition_in_same_process_returns_busy() {
560        let dir = tempfile::TempDir::new().unwrap();
561        let _first = ServerLock::try_acquire(dir.path()).unwrap();
562        let second = ServerLock::try_acquire(dir.path());
563        match second {
564            Err(ServerLockError::Busy { owner }) => {
565                assert!(owner.is_some());
566            }
567            other => panic!("expected Busy, got {other:?}"),
568        }
569    }
570
571    #[test]
572    fn drop_allows_later_acquisition() {
573        let dir = tempfile::TempDir::new().unwrap();
574        let first = ServerLock::try_acquire(dir.path()).unwrap();
575        let nonce1 = first.nonce().to_string();
576        drop(first);
577        let second = ServerLock::try_acquire(dir.path()).unwrap();
578        assert_ne!(second.nonce(), nonce1);
579    }
580
581    #[test]
582    fn canonical_file_persists_after_release() {
583        let dir = tempfile::TempDir::new().unwrap();
584        {
585            let _g = ServerLock::try_acquire(dir.path()).unwrap();
586        }
587        assert!(server_lock_path(dir.path()).exists());
588    }
589
590    #[test]
591    fn empty_metadata_does_not_block_acquisition_when_lock_free() {
592        let dir = tempfile::TempDir::new().unwrap();
593        let path = server_lock_path(dir.path());
594        std::fs::write(&path, "").unwrap();
595        let guard = ServerLock::try_acquire(dir.path()).unwrap();
596        let observed = read_owner(&path).unwrap();
597        assert_eq!(observed.nonce, guard.nonce());
598    }
599
600    #[test]
601    fn malformed_metadata_does_not_block_acquisition_when_lock_free() {
602        let dir = tempfile::TempDir::new().unwrap();
603        let path = server_lock_path(dir.path());
604        std::fs::write(&path, "not valid toml").unwrap();
605        let guard = ServerLock::try_acquire(dir.path()).unwrap();
606        let observed = read_owner(&path).unwrap();
607        assert_eq!(observed.nonce, guard.nonce());
608    }
609
610    #[test]
611    fn identity_roundtrip() {
612        let id = ServerLockIdentity {
613            schema_version: 1,
614            pid: 12345,
615            start_token: Some("tok".to_string()),
616            nonce: "nonce".to_string(),
617            acquired_at_unix_ms: 999,
618        };
619        let s = toml::to_string_pretty(&id).unwrap();
620        let back: ServerLockIdentity = toml::from_str(&s).unwrap();
621        assert_eq!(id, back);
622    }
623
624    #[test]
625    fn busy_path_recovers_the_owner_when_the_lock_file_record_is_torn() {
626        let dir = tempfile::TempDir::new().unwrap();
627        let guard = ServerLock::try_acquire(dir.path()).unwrap();
628        let path = server_lock_path(dir.path());
629        // Simulate the in-place record being observed while it is rewritten:
630        // the lock file is truncated while the owner is still running.
631        std::fs::write(&path, "").unwrap();
632
633        match ServerLock::try_acquire(dir.path()) {
634            Err(ServerLockError::Busy { owner }) => {
635                let owner = owner.expect("the busy path must resolve an owner");
636                assert_eq!(owner.pid, std::process::id());
637                assert_eq!(owner.nonce, guard.nonce());
638            }
639            other => panic!("expected Busy, got {other:?}"),
640        }
641    }
642
643    #[test]
644    fn busy_path_falls_back_to_the_legacy_pid_file() {
645        let dir = tempfile::TempDir::new().unwrap();
646        let _guard = ServerLock::try_acquire(dir.path()).unwrap();
647        let path = server_lock_path(dir.path());
648        // No owner record can be read at all: neither the atomically
649        // published record nor the in-place one.
650        std::fs::write(&path, "").unwrap();
651        std::fs::remove_file(server_owner_path(&path)).unwrap();
652        std::fs::write(
653            dir.path().join(LEGACY_PID_FILE_NAME),
654            format!("{}\n", std::process::id()),
655        )
656        .unwrap();
657
658        match ServerLock::try_acquire(dir.path()) {
659            Err(ServerLockError::Busy { owner }) => {
660                let owner = owner.expect("the legacy PID file must resolve an owner");
661                assert_eq!(owner.pid, std::process::id());
662            }
663            other => panic!("expected Busy, got {other:?}"),
664        }
665    }
666
667    #[cfg(unix)]
668    #[test]
669    fn retryable_lock_error_is_only_eintr() {
670        let interrupted = std::io::Error::from_raw_os_error(libc::EINTR);
671        assert!(is_retryable_lock_error(&interrupted));
672
673        let would_block = std::io::Error::from_raw_os_error(libc::EAGAIN);
674        assert!(!is_retryable_lock_error(&would_block));
675
676        let other = std::io::Error::other("not an errno");
677        assert!(!is_retryable_lock_error(&other));
678    }
679}