use std::fs::File;
use std::os::fd::{AsRawFd, BorrowedFd};
use crate::error::{Error, Result};
#[allow(
dead_code,
reason = "Shared variant consumed by reader-slot acquisition (Stage 4)"
)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum LockKind {
Shared,
Exclusive,
}
pub(crate) fn try_acquire_byte_lock(fd: BorrowedFd<'_>, byte: u64, kind: LockKind) -> Result<bool> {
fcntl_setlk(fd, byte, kind, true)
}
pub(crate) fn release_byte_lock(fd: BorrowedFd<'_>, byte: u64) -> Result<()> {
let _ = fcntl_unlk(fd, byte)?;
Ok(())
}
#[cfg(unix)]
fn fcntl_setlk(fd: BorrowedFd<'_>, byte: u64, kind: LockKind, nonblocking: bool) -> Result<bool> {
#[allow(clippy::unnecessary_cast)]
let l_type = match kind {
LockKind::Shared => libc::F_RDLCK as i16,
LockKind::Exclusive => libc::F_WRLCK as i16,
};
let mut fl: libc::flock = unsafe { std::mem::zeroed() };
fl.l_type = l_type;
fl.l_whence = libc::SEEK_SET as i16;
fl.l_start = byte as libc::off_t;
fl.l_len = 1 as libc::off_t;
let cmd = pick_cmd(nonblocking);
let rc = unsafe { libc::fcntl(fd.as_raw_fd(), cmd, &mut fl) };
if rc == 0 {
Ok(true)
} else {
let err = std::io::Error::last_os_error();
match err.raw_os_error() {
Some(libc::EAGAIN) | Some(libc::EACCES) => Ok(false),
_ => Err(Error::Io(err)),
}
}
}
#[cfg(unix)]
fn fcntl_unlk(fd: BorrowedFd<'_>, byte: u64) -> Result<bool> {
let mut fl: libc::flock = unsafe { std::mem::zeroed() };
#[allow(clippy::unnecessary_cast)]
{
fl.l_type = libc::F_UNLCK as i16;
}
fl.l_whence = libc::SEEK_SET as i16;
fl.l_start = byte as libc::off_t;
fl.l_len = 1 as libc::off_t;
let cmd = pick_cmd(true);
let rc = unsafe { libc::fcntl(fd.as_raw_fd(), cmd, &mut fl) };
if rc == 0 {
Ok(true)
} else {
Err(Error::Io(std::io::Error::last_os_error()))
}
}
#[cfg(target_os = "linux")]
fn pick_cmd(nonblocking: bool) -> libc::c_int {
const F_OFD_SETLK: libc::c_int = 37;
const F_OFD_SETLKW: libc::c_int = 38;
if nonblocking {
F_OFD_SETLK
} else {
F_OFD_SETLKW
}
}
#[cfg(all(unix, not(target_os = "linux")))]
fn pick_cmd(nonblocking: bool) -> libc::c_int {
if nonblocking {
libc::F_SETLK
} else {
libc::F_SETLKW
}
}
#[cfg(not(unix))]
fn fcntl_setlk(
_fd: BorrowedFd<'_>,
_byte: u64,
_kind: LockKind,
_nonblocking: bool,
) -> Result<bool> {
Err(Error::Unsupported(
"byte-range advisory locks are only implemented on Unix".into(),
))
}
#[cfg(not(unix))]
fn fcntl_unlk(_fd: BorrowedFd<'_>, _byte: u64) -> Result<bool> {
Err(Error::Unsupported(
"byte-range advisory locks are only implemented on Unix".into(),
))
}
pub(crate) fn acquire_exclusive_blocking(
fd: BorrowedFd<'_>,
byte: u64,
max_attempts: u32,
) -> Result<u32> {
for attempt in 0..max_attempts {
if try_acquire_byte_lock(fd, byte, LockKind::Exclusive)? {
return Ok(attempt + 1);
}
let micros = (1u64 << attempt.min(11)).min(2000);
std::thread::sleep(std::time::Duration::from_micros(micros));
}
Err(Error::Busy(
"writer slot lock contended past max attempts".into(),
))
}
#[allow(dead_code, reason = "consumed by reader-slot pin in Stage 4")]
pub(crate) struct ByteLockGuard {
file: std::sync::Arc<File>,
byte: u64,
}
#[allow(dead_code, reason = "consumed by reader-slot pin in Stage 4")]
impl ByteLockGuard {
pub(crate) fn new(file: std::sync::Arc<File>, byte: u64) -> Self {
Self { file, byte }
}
}
impl Drop for ByteLockGuard {
fn drop(&mut self) {
let fd = unsafe { BorrowedFd::borrow_raw(self.file.as_raw_fd()) };
let _ = release_byte_lock(fd, self.byte);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::fd::AsFd;
#[test]
fn shared_lock_round_trip() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock.bin");
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&path)
.unwrap();
file.set_len(1024).unwrap();
let fd = file.as_fd();
assert!(try_acquire_byte_lock(fd, 100, LockKind::Shared).unwrap());
release_byte_lock(fd, 100).unwrap();
assert!(try_acquire_byte_lock(fd, 100, LockKind::Shared).unwrap());
release_byte_lock(fd, 100).unwrap();
}
#[test]
fn exclusive_lock_round_trip() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock-ex.bin");
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&path)
.unwrap();
file.set_len(1024).unwrap();
let fd = file.as_fd();
assert!(try_acquire_byte_lock(fd, 192, LockKind::Exclusive).unwrap());
release_byte_lock(fd, 192).unwrap();
}
#[test]
fn cross_fd_exclusive_contention_is_visible() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock-contention.bin");
let file_a = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&path)
.unwrap();
file_a.set_len(1024).unwrap();
let file_b = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&path)
.unwrap();
let fd_a = file_a.as_fd();
assert!(try_acquire_byte_lock(fd_a, 192, LockKind::Exclusive).unwrap());
let fd_b = file_b.as_fd();
let acquired_b = try_acquire_byte_lock(fd_b, 192, LockKind::Exclusive).unwrap();
#[cfg(target_os = "linux")]
assert!(!acquired_b, "OFD locks must enforce per-fd exclusion");
#[cfg(not(target_os = "linux"))]
let _ = acquired_b;
release_byte_lock(fd_a, 192).unwrap();
}
}