use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
const WORKERS: &str = "workers";
const LOCK: &str = "worker.lock";
static MADE: AtomicU64 = AtomicU64::new(0);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Worker {
name: String,
instance: String,
}
impl Worker {
#[must_use]
pub fn named(name: &str) -> Self {
let cleaned: String = name
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_') {
character
} else {
'-'
}
})
.collect();
let name = if cleaned.trim_matches('-').is_empty() {
token()
} else {
cleaned
};
Self {
name,
instance: token(),
}
}
#[must_use]
pub fn unnamed() -> Self {
let instance = token();
Self {
name: instance.clone(),
instance,
}
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn instance(&self) -> &str {
&self.instance
}
}
fn token() -> String {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_nanos());
let serial = MADE.fetch_add(1, Ordering::Relaxed);
let mut hasher = blake3::Hasher::new();
hasher.update(&nanos.to_le_bytes());
hasher.update(&std::process::id().to_le_bytes());
hasher.update(&serial.to_le_bytes());
hasher.finalize().to_hex()[..8].to_string()
}
#[derive(Debug)]
pub enum LockError {
Held {
root: PathBuf,
holder: String,
},
Io {
path: PathBuf,
source: io::Error,
},
}
impl fmt::Display for LockError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Held { root, holder } => write!(
f,
"the cache at {} is held by {holder}.\n\
Two workers must not share a cache directory: the index is \
SQLite, and SQLite over a network filesystem is the failure \
D43 names. Give each worker its own --cache, or drop --cache \
and let --worker choose one.\n\
If that worker is gone, delete {}.",
root.display(),
root.join(LOCK).display()
),
Self::Io { path, source } => {
write!(f, "{}: {source}", path.display())
}
}
}
}
impl std::error::Error for LockError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Held { .. } => None,
}
}
}
#[derive(Debug)]
pub struct Lock {
path: PathBuf,
}
impl Lock {
#[must_use]
pub fn directory(root: &Path, worker: &Worker) -> PathBuf {
root.join(WORKERS).join(worker.name())
}
pub fn take(root: &Path, worker: &Worker) -> Result<Self, LockError> {
let path = root.join(LOCK);
let io = |source: io::Error| LockError::Io {
path: path.clone(),
source,
};
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(mut file) => {
use std::io::Write;
let note = format!(
"{} (instance {}, pid {})\n",
worker.name(),
worker.instance(),
std::process::id()
);
file.write_all(note.as_bytes()).map_err(io)?;
Ok(Self { path })
}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
let holder = fs::read_to_string(&path)
.map(|text| text.trim().to_owned())
.unwrap_or_default();
Err(LockError::Held {
root: root.to_path_buf(),
holder: if holder.is_empty() {
"another worker".to_owned()
} else {
holder
},
})
}
Err(error) => Err(io(error)),
}
}
}
impl Drop for Lock {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}