use std::collections::HashMap;
use std::os::fd::{BorrowedFd, OwnedFd};
use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError, 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;
mod update;
#[cfg(test)]
pub(crate) use update::held_in_process as update_lock_held_in_process;
pub(crate) use update::{UpdateLock, UpdateLockHeld, acquire_update};
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: Option<OwnedFd>,
state: Mutex<LockState>,
}
#[derive(Debug)]
enum Registered {
Repo(Weak<RepoLock>),
Update(Weak<UpdateLock>),
}
impl Registered {
fn repo(&self) -> Option<&Weak<RepoLock>> {
match self {
Registered::Repo(weak) => Some(weak),
Registered::Update(_) => None,
}
}
fn update(&self) -> Option<&Weak<UpdateLock>> {
match self {
Registered::Update(weak) => Some(weak),
Registered::Repo(_) => None,
}
}
}
#[derive(Debug)]
struct Entry {
lock: Registered,
parked: Vec<OwnedFd>,
}
type LockRegistry = HashMap<(u64, u64), Entry>;
struct Registry {
map: Mutex<LockRegistry>,
gone: Condvar,
}
fn registry() -> &'static Registry {
static REGISTRY: OnceLock<Registry> = OnceLock::new();
REGISTRY.get_or_init(|| Registry {
map: Mutex::new(HashMap::new()),
gone: Condvar::new(),
})
}
fn probe<'r>(reg: &'r LockRegistry, repo_fd: BorrowedFd<'_>, name: &str) -> Option<&'r Entry> {
let stat = rustix::fs::statat(repo_fd, name, AtFlags::empty()).ok()?;
reg.get(&(stat.st_dev, stat.st_ino))
}
enum Found<T> {
Live(Arc<T>),
Dying,
Other,
}
fn find<T>(entry: &Entry, view: fn(&Registered) -> Option<&Weak<T>>) -> Found<T> {
match view(&entry.lock) {
Some(weak) => weak.upgrade().map_or(Found::Dying, Found::Live),
None => Found::Other,
}
}
fn get_or_register<T>(
repo_fd: BorrowedFd<'_>,
name: &str,
repo_mode: RepoMode,
view: fn(&Registered) -> Option<&Weak<T>>,
make: impl FnOnce(OwnedFd, (u64, u64)) -> (Arc<T>, Registered),
) -> std::io::Result<Arc<T>> {
let registry = registry();
let mut reg = registry.map.lock().unwrap();
loop {
match probe(®, repo_fd, name).map(|entry| find(entry, view)) {
Some(Found::Live(existing)) => return Ok(existing),
Some(Found::Other) => return Err(shared_inode(name)),
Some(Found::Dying) => {
reg = registry.gone.wait(reg).unwrap();
continue;
}
None => {}
}
let (fd, key) = open_lock_file(repo_fd, name, repo_mode)?;
let Some(entry) = reg.get_mut(&key) else {
let (lock, registered) = make(fd, key);
reg.insert(
key,
Entry {
lock: registered,
parked: Vec::new(),
},
);
return Ok(lock);
};
let found = find(entry, view);
entry.parked.push(fd);
match found {
Found::Live(existing) => return Ok(existing),
Found::Other => return Err(shared_inode(name)),
Found::Dying => reg = registry.gone.wait(reg).unwrap(),
}
}
}
fn unregister(key: (u64, u64), fd: Option<OwnedFd>) {
let registry = registry();
let mut reg = registry.map.lock().unwrap_or_else(PoisonError::into_inner);
drop(fd);
drop(reg.remove(&key));
drop(reg);
registry.gone.notify_all();
}
fn open_lock_file(
repo_fd: BorrowedFd<'_>,
name: &str,
repo_mode: RepoMode,
) -> std::io::Result<(OwnedFd, (u64, u64))> {
let fd = match rustix::fs::openat(
repo_fd,
name,
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, name, OFlags::RDWR | OFlags::CLOEXEC, Mode::empty())?
}
Err(e) => return Err(e.into()),
};
let stat = rustix::fs::fstat(&fd)?;
Ok((fd, (stat.st_dev, stat.st_ino)))
}
fn shared_inode(name: &str) -> std::io::Error {
std::io::Error::other(format!(
"lock file {name} shares its inode with another lock file of the repository"
))
}
impl RepoLock {
pub(crate) fn get_or_create(
repo_fd: BorrowedFd<'_>,
repo_mode: RepoMode,
) -> std::io::Result<Arc<RepoLock>> {
get_or_register(
repo_fd,
LOCK_FILE,
repo_mode,
Registered::repo,
|fd, key| {
let lock = Arc::new(RepoLock {
key,
fd: Some(fd),
state: Mutex::new(LockState {
shared: 0,
exclusive: 0,
os: OsLock::Unlocked,
}),
});
let registered = Registered::Repo(Arc::downgrade(&lock));
(lock, registered)
},
)
}
fn fd(&self) -> &OwnedFd {
self.fd
.as_ref()
.expect("the descriptor stays open until the drop")
}
fn try_acquire(&self, kind: LockKind) -> std::io::Result<TryOutcome> {
let mut st = self.state.lock().unwrap();
match kind {
LockKind::Shared => {
if st.exclusive > 0 {
return Ok(TryOutcome::WouldBlock);
}
if st.os == OsLock::Shared {
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.shared > 0 || st.exclusive > 0 {
return Ok(TryOutcome::WouldBlock);
}
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 _ = rustix::fs::fcntl_lock(self.fd(), FlockOperation::Unlock);
st.os = target;
}
}
impl Drop for RepoLock {
fn drop(&mut self) {
unregister(self.key, self.fd.take());
}
}
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);
}
}
}
#[derive(Debug)]
pub(crate) struct UpdateLocks {
#[allow(dead_code)]
pub(crate) update: UpdateLockHeld,
#[allow(dead_code)]
pub(crate) repo: LockGuard,
}
pub(crate) async fn acquire(
lock: Arc<RepoLock>,
kind: LockKind,
timeout: Option<Duration>,
) -> Result<LockGuard> {
let deadline = timeout.and_then(|t| Some((Instant::now().checked_add(t)?, t.as_secs() as i64)));
loop {
match lock.try_acquire(kind)? {
TryOutcome::Acquired => {
return Ok(LockGuard {
hold: Some((lock, kind)),
});
}
TryOutcome::WouldBlock => {
let wait = match deadline {
Some((deadline, secs)) => {
let now = Instant::now();
if now >= deadline {
return Err(Error::LockTimeout { secs });
}
POLL_INTERVAL.min(deadline - now)
}
None => POLL_INTERVAL,
};
ostrya_rt::Timer::after(wait).await;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::fd::{AsFd, AsRawFd};
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
}
fn counts(lock: &RepoLock) -> (usize, usize) {
let st = lock.state.lock().unwrap();
(st.shared, st.exclusive)
}
#[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_waits_for_a_shared_holder() {
let scratch = Scratch::new("wait");
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);
assert!(matches!(
lock.try_acquire(LockKind::Exclusive).unwrap(),
TryOutcome::WouldBlock
));
assert_eq!(os_lock(&lock), OsLock::Shared);
assert_eq!(counts(&lock), (1, 0));
lock.release(LockKind::Shared);
assert_eq!(os_lock(&lock), OsLock::Unlocked);
assert!(matches!(
lock.try_acquire(LockKind::Exclusive).unwrap(),
TryOutcome::Acquired
));
assert_eq!(os_lock(&lock), OsLock::Exclusive);
lock.release(LockKind::Exclusive);
assert_eq!(os_lock(&lock), OsLock::Unlocked);
}
#[test]
fn shared_waits_for_an_exclusive_holder() {
let scratch = Scratch::new("shared-waits");
let lock = RepoLock::get_or_create(scratch.repo_fd(), RepoMode::Bare).unwrap();
assert!(matches!(
lock.try_acquire(LockKind::Exclusive).unwrap(),
TryOutcome::Acquired
));
assert_eq!(os_lock(&lock), OsLock::Exclusive);
assert!(matches!(
lock.try_acquire(LockKind::Shared).unwrap(),
TryOutcome::WouldBlock
));
assert_eq!(os_lock(&lock), OsLock::Exclusive);
assert_eq!(counts(&lock), (0, 1));
lock.release(LockKind::Exclusive);
assert_eq!(os_lock(&lock), OsLock::Unlocked);
assert_eq!(counts(&lock), (0, 0));
assert!(matches!(
lock.try_acquire(LockKind::Shared).unwrap(),
TryOutcome::Acquired
));
assert_eq!(os_lock(&lock), OsLock::Shared);
assert_eq!(counts(&lock), (1, 0));
lock.release(LockKind::Shared);
assert_eq!(os_lock(&lock), OsLock::Unlocked);
}
#[test]
fn a_second_exclusive_waits_for_the_first() {
let scratch = Scratch::new("exclusive-waits");
let lock = RepoLock::get_or_create(scratch.repo_fd(), RepoMode::Bare).unwrap();
assert!(matches!(
lock.try_acquire(LockKind::Exclusive).unwrap(),
TryOutcome::Acquired
));
assert!(matches!(
lock.try_acquire(LockKind::Exclusive).unwrap(),
TryOutcome::WouldBlock
));
assert_eq!(os_lock(&lock), OsLock::Exclusive);
assert_eq!(counts(&lock), (0, 1));
lock.release(LockKind::Exclusive);
assert_eq!(os_lock(&lock), OsLock::Unlocked);
assert_eq!(counts(&lock), (0, 0));
assert!(matches!(
lock.try_acquire(LockKind::Exclusive).unwrap(),
TryOutcome::Acquired
));
assert_eq!(os_lock(&lock), OsLock::Exclusive);
assert_eq!(counts(&lock), (0, 1));
lock.release(LockKind::Exclusive);
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().map.lock().unwrap().contains_key(&key),
"registry entry is reclaimed once the last handle drops"
);
}
fn holds_write_lock(lock: &RepoLock) -> bool {
let path = format!("/proc/self/fdinfo/{}", lock.fd().as_raw_fd());
let info = std::fs::read_to_string(path).unwrap();
info.lines().any(|line| {
let fields: Vec<&str> = line.split_whitespace().collect();
fields.len() > 4 && fields[0] == "lock:" && fields[2] == "POSIX" && fields[4] == "WRITE"
})
}
#[test]
fn a_new_lock_survives_the_close_of_a_dropped_one() {
for _ in 0..20 {
let scratch = Scratch::new("redrop");
let old = RepoLock::get_or_create(scratch.repo_fd(), RepoMode::Bare).unwrap();
let weak = Arc::downgrade(&old);
let reg = registry().map.lock().unwrap();
let dropper = std::thread::spawn(move || drop(old));
while weak.strong_count() > 0 {
std::thread::yield_now();
}
drop(reg);
let new = RepoLock::get_or_create(scratch.repo_fd(), RepoMode::Bare).unwrap();
assert!(matches!(
new.try_acquire(LockKind::Exclusive).unwrap(),
TryOutcome::Acquired
));
dropper.join().unwrap();
assert!(holds_write_lock(&new), "the close dropped the new lock");
new.release(LockKind::Exclusive);
}
}
}