use std::collections::HashMap;
use std::os::fd::{BorrowedFd, OwnedFd};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::time::{Duration, Instant};
use ostrya_core::RepoMode;
use rustix::fs::{AtFlags, FlockOperation, Mode, OFlags};
use rustix::io::Errno;
use crate::error::{Error, Result};
use crate::perm;
const LOCK_FILE: &str = ".lock";
const LOCK_MODE: u32 = 0o660;
const POLL_INTERVAL: Duration = Duration::from_millis(100);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockKind {
Shared,
Exclusive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OsLock {
Unlocked,
Shared,
Exclusive,
}
#[derive(Debug)]
struct LockState {
shared: usize,
exclusive: usize,
os: OsLock,
}
enum TryOutcome {
Acquired,
WouldBlock,
}
#[derive(Debug)]
pub(crate) struct RepoLock {
key: (u64, u64),
fd: OwnedFd,
state: Mutex<LockState>,
}
type LockRegistry = HashMap<(u64, u64), Weak<RepoLock>>;
fn registry() -> &'static Mutex<LockRegistry> {
static REGISTRY: OnceLock<Mutex<LockRegistry>> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
impl RepoLock {
pub(crate) fn get_or_create(
repo_fd: BorrowedFd<'_>,
repo_mode: RepoMode,
) -> std::io::Result<Arc<RepoLock>> {
let mut reg = registry().lock().unwrap();
if let Ok(stat) = rustix::fs::statat(repo_fd, LOCK_FILE, AtFlags::empty()) {
let key = (stat.st_dev, stat.st_ino);
if let Some(existing) = reg.get(&key).and_then(Weak::upgrade) {
return Ok(existing);
}
}
let fd = match rustix::fs::openat(
repo_fd,
LOCK_FILE,
OFlags::RDWR | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC,
Mode::from_raw_mode(LOCK_MODE),
) {
Ok(fd) => {
perm::force_created_mode(&fd, repo_mode, perm::SHARED_LOCK_MODE)?;
fd
}
Err(Errno::EXIST) => rustix::fs::openat(
repo_fd,
LOCK_FILE,
OFlags::RDWR | OFlags::CLOEXEC,
Mode::empty(),
)?,
Err(e) => return Err(e.into()),
};
let stat = rustix::fs::fstat(&fd)?;
let key = (stat.st_dev, stat.st_ino);
let lock = Arc::new(RepoLock {
key,
fd,
state: Mutex::new(LockState {
shared: 0,
exclusive: 0,
os: OsLock::Unlocked,
}),
});
reg.insert(key, Arc::downgrade(&lock));
Ok(lock)
}
fn try_acquire(&self, kind: LockKind) -> std::io::Result<TryOutcome> {
let mut st = self.state.lock().unwrap();
match kind {
LockKind::Shared => {
if matches!(st.os, OsLock::Shared | OsLock::Exclusive) {
st.shared += 1;
return Ok(TryOutcome::Acquired);
}
match rustix::fs::fcntl_lock(&self.fd, FlockOperation::NonBlockingLockShared) {
Ok(()) => {
st.os = OsLock::Shared;
st.shared += 1;
Ok(TryOutcome::Acquired)
}
Err(e) if would_block(e) => Ok(TryOutcome::WouldBlock),
Err(e) => Err(e.into()),
}
}
LockKind::Exclusive => {
if st.os == OsLock::Exclusive {
st.exclusive += 1;
return Ok(TryOutcome::Acquired);
}
match rustix::fs::fcntl_lock(&self.fd, FlockOperation::NonBlockingLockExclusive) {
Ok(()) => {
st.os = OsLock::Exclusive;
st.exclusive += 1;
Ok(TryOutcome::Acquired)
}
Err(e) if would_block(e) => Ok(TryOutcome::WouldBlock),
Err(e) => Err(e.into()),
}
}
}
}
fn release(&self, kind: LockKind) {
let mut st = self.state.lock().unwrap();
match kind {
LockKind::Shared => st.shared = st.shared.saturating_sub(1),
LockKind::Exclusive => st.exclusive = st.exclusive.saturating_sub(1),
}
let target = if st.exclusive > 0 {
OsLock::Exclusive
} else if st.shared > 0 {
OsLock::Shared
} else {
OsLock::Unlocked
};
if target == st.os {
return;
}
let op = match target {
OsLock::Unlocked => FlockOperation::Unlock,
OsLock::Shared => FlockOperation::LockShared,
OsLock::Exclusive => FlockOperation::LockExclusive,
};
let _ = rustix::fs::fcntl_lock(&self.fd, op);
st.os = target;
}
}
impl Drop for RepoLock {
fn drop(&mut self) {
if let Ok(mut reg) = registry().lock()
&& let Some(weak) = reg.get(&self.key)
&& weak.strong_count() == 0
{
reg.remove(&self.key);
}
}
}
fn would_block(e: Errno) -> bool {
e == Errno::AGAIN || e == Errno::ACCESS
}
#[derive(Debug)]
pub(crate) struct LockGuard {
hold: Option<(Arc<RepoLock>, LockKind)>,
}
impl LockGuard {
pub(crate) fn disabled() -> LockGuard {
LockGuard { hold: None }
}
}
impl Drop for LockGuard {
fn drop(&mut self) {
if let Some((lock, kind)) = &self.hold {
lock.release(*kind);
}
}
}
pub(crate) async fn acquire(
lock: Arc<RepoLock>,
kind: LockKind,
timeout: Duration,
) -> Result<LockGuard> {
let deadline = Instant::now() + timeout;
loop {
let probe = lock.clone();
match ostrya_rt::unblock(move || probe.try_acquire(kind)).await? {
TryOutcome::Acquired => {
return Ok(LockGuard {
hold: Some((lock, kind)),
});
}
TryOutcome::WouldBlock => {
let now = Instant::now();
if now >= deadline {
return Err(Error::LockTimeout {
secs: timeout.as_secs() as i64,
});
}
let wait = POLL_INTERVAL.min(deadline - now);
ostrya_rt::Timer::after(wait).await;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::fd::AsFd;
struct Scratch {
_dir: std::path::PathBuf,
fd: OwnedFd,
}
impl Scratch {
fn new(tag: &str) -> Scratch {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir =
std::env::temp_dir().join(format!("ostrya-lock-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let fd = rustix::fs::openat(
rustix::fs::CWD,
&dir,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.unwrap();
Scratch { _dir: dir, fd }
}
fn repo_fd(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self._dir);
}
}
fn os_lock(lock: &RepoLock) -> OsLock {
lock.state.lock().unwrap().os
}
#[test]
fn shared_holders_share_one_descriptor_lock() {
let scratch = Scratch::new("shared");
let lock = RepoLock::get_or_create(scratch.repo_fd(), RepoMode::Bare).unwrap();
assert!(matches!(
lock.try_acquire(LockKind::Shared).unwrap(),
TryOutcome::Acquired
));
assert!(matches!(
lock.try_acquire(LockKind::Shared).unwrap(),
TryOutcome::Acquired
));
assert_eq!(os_lock(&lock), OsLock::Shared);
lock.release(LockKind::Shared);
assert_eq!(os_lock(&lock), OsLock::Shared); lock.release(LockKind::Shared);
assert_eq!(os_lock(&lock), OsLock::Unlocked);
}
#[test]
fn exclusive_upgrades_and_downgrades_around_a_shared_holder() {
let scratch = Scratch::new("upgrade");
let lock = RepoLock::get_or_create(scratch.repo_fd(), RepoMode::Bare).unwrap();
lock.try_acquire(LockKind::Shared).unwrap();
assert_eq!(os_lock(&lock), OsLock::Shared);
lock.try_acquire(LockKind::Exclusive).unwrap();
assert_eq!(os_lock(&lock), OsLock::Exclusive);
lock.release(LockKind::Exclusive);
assert_eq!(os_lock(&lock), OsLock::Shared);
lock.release(LockKind::Shared);
assert_eq!(os_lock(&lock), OsLock::Unlocked);
}
#[test]
fn one_repo_lock_is_shared_across_handles_and_reclaimed() {
let scratch = Scratch::new("registry");
let a = RepoLock::get_or_create(scratch.repo_fd(), RepoMode::Bare).unwrap();
let b = RepoLock::get_or_create(scratch.repo_fd(), RepoMode::Bare).unwrap();
assert!(Arc::ptr_eq(&a, &b), "same repo yields one shared lock");
let key = a.key;
drop(a);
drop(b);
assert!(
!registry().lock().unwrap().contains_key(&key),
"registry entry is reclaimed once the last handle drops"
);
}
}