use std::cell::Cell;
use std::fs::{File, OpenOptions, TryLockError};
use std::io;
use std::path::Path;
use std::time::{Duration, Instant};
use crate::StoreError;
const OPEN_WAIT: Duration = Duration::from_secs(5);
const OPEN_TRY: Duration = Duration::from_millis(10);
#[derive(Debug)]
pub(crate) struct SpaceLock {
file: File,
gate: File,
alone: Cell<bool>,
}
fn open(path: &Path) -> Result<File, StoreError> {
Ok(OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)?)
}
struct Gated<'a>(&'a File);
impl Drop for Gated<'_> {
fn drop(&mut self) {
let _ = self.0.unlock();
}
}
impl SpaceLock {
pub(crate) fn shared(path: &Path) -> Result<Self, StoreError> {
let file = open(path)?;
let gate = open(&path.with_file_name("gate"))?;
let waited = Instant::now();
loop {
match file.try_lock_shared() {
Ok(()) => {
return Ok(Self {
file,
gate,
alone: Cell::new(false),
});
}
Err(TryLockError::WouldBlock) if waited.elapsed() < OPEN_WAIT => {
std::thread::sleep(OPEN_TRY);
}
Err(TryLockError::WouldBlock) => return Err(StoreError::InUse),
Err(TryLockError::Error(error)) if error.kind() == io::ErrorKind::Unsupported => {
return Err(StoreError::Unsupported("file locks"));
}
Err(TryLockError::Error(error)) => return Err(error.into()),
}
}
}
fn gated(&self) -> Option<Gated<'_>> {
self.gate.lock().ok().map(|()| Gated(&self.gate))
}
pub(crate) fn alone(&self) -> bool {
if self.alone.get() {
return true;
}
let Some(_gated) = self.gated() else {
return false;
};
let _ = self.file.unlock();
if self.file.try_lock().is_ok() {
self.alone.set(true);
return true;
}
let _ = self.file.lock_shared();
false
}
pub(crate) fn shared_with_others(&self) -> bool {
if self.alone.get() {
return false;
}
let Some(_gated) = self.gated() else {
return true;
};
let _ = self.file.unlock();
let alone = self.file.try_lock().is_ok();
if alone {
let _ = self.file.unlock();
}
let _ = self.file.lock_shared();
!alone
}
pub(crate) fn is_alone(&self) -> bool {
self.alone.get()
}
pub(crate) fn share(&self) {
if self.alone.get() {
let _gated = self.gated();
let _ = self.file.unlock();
let _ = self.file.lock_shared();
self.alone.set(false);
}
}
}