180 lines · 6.0 KB · RustRaw
//! One process owns a data folder. The stable file is never unlinked: flock//! belongs to its inode, while the JSON only tells a person who holds it.use serde::{Deserialize, Serialize};use std::collections::HashMap;use std::fs::{File, OpenOptions};use std::io::{Read, Seek, SeekFrom, Write};use std::os::fd::AsRawFd;use std::os::unix::fs::{MetadataExt, OpenOptionsExt};use std::path::Path;use std::sync::{Arc, Mutex, OnceLock, Weak};pub const LOCK_FILE: &str = ".cotton-process.lock";pub const HELD_TITLE: &str = "Another CottonDB has this folder open";#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Holder { pub pid: u32, pub bundle_path: String, pub started_at: String,}impl Holder { pub fn current(started_at: String) -> std::io::Result<Self> { let executable = std::env::current_exe()?; let bundle = executable .ancestors() .find(|p| p.extension().is_some_and(|e| e == "app")) .unwrap_or(&executable); Ok(Self { pid: std::process::id(), bundle_path: bundle.to_string_lossy().into_owned(), started_at, }) }}#[derive(Debug, thiserror::Error)]pub enum LockError { #[error("Another CottonDB has this folder open: {holder:?}")] Held { holder: Option<Holder> }, #[error("The data folder could not be locked: {0}")] Io(#[from] std::io::Error),}impl LockError { pub fn message(&self) -> String { match self { Self::Held { holder: Some(holder), } => holder.bundle_path.clone(), Self::Held { holder: None } => { format!("{HELD_TITLE}\nThe holder's path could not be read.") } Self::Io(error) => error.to_string(), } }}#[derive(Debug)]pub struct ProcessLock { _file: File, holder: Holder,}type Inode = (u64, u64);struct Claim { holder: Holder, lease: Weak<ProcessLock>,}fn shared() -> &'static Mutex<HashMap<Inode, Claim>> { static SHARED: OnceLock<Mutex<HashMap<Inode, Claim>>> = OnceLock::new(); SHARED.get_or_init(Mutex::default)}fn inode(file: &File) -> std::io::Result<Inode> { let m = file.metadata()?; Ok((m.dev(), m.ino()))}fn open(folder: &Path) -> std::io::Result<File> { std::fs::create_dir_all(folder)?; OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) .mode(0o600) .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW) .open(folder.join(LOCK_FILE))}fn lock(file: &mut File) -> Result<(), LockError> { // No truncation, PID judgement or metadata write until the kernel admits us. if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { return Ok(()); } let error = std::io::Error::last_os_error(); if error.kind() != std::io::ErrorKind::WouldBlock { return Err(error.into()); } let mut bytes = Vec::new(); let holder = (&mut *file) .take(64 * 1024) .read_to_end(&mut bytes) .ok() .and_then(|_| serde_json::from_slice(&bytes).ok()); Err(LockError::Held { holder })}impl ProcessLock { pub fn acquire(folder: &Path, holder: Holder) -> Result<Self, LockError> { Self::on_file(open(folder)?, holder) } fn on_file(mut file: File, holder: Holder) -> Result<Self, LockError> { lock(&mut file)?; let bytes = serde_json::to_vec(&holder).map_err(std::io::Error::other)?; file.seek(SeekFrom::Start(0))?; file.write_all(&bytes)?; // not a copy: the process lock's own file. file.set_len(bytes.len() as u64)?; file.sync_data()?; Ok(Self { _file: file, holder, }) } pub fn holder(&self) -> &Holder { &self.holder } /// Connections and controllers in ONE process share the lease. Inode keys /// also follow the one-time legacy-folder rename and symlink aliases. pub fn claim(folder: &Path, holder: Holder) -> Result<Arc<Self>, LockError> { let file = open(folder)?; let key = inode(&file)?; let mut held = shared().lock().unwrap_or_else(|e| e.into_inner()); if let Some(lock) = held.get(&key).and_then(|claim| claim.lease.upgrade()) { return Ok(lock); } let lock = Arc::new(Self::on_file(file, holder)?); held.insert( key, Claim { holder: lock.holder.clone(), lease: Arc::downgrade(&lock), }, ); Ok(lock) }}/// Retain the lease with every SQLite connection, including work that outlives/// runtime shutdown's timeout. A foreign live lease refuses BEFORE SQLite opens.pub(crate) fn for_store(path: &Path) -> Result<Option<Arc<ProcessLock>>, LockError> { for folder in path.parent().into_iter().flat_map(Path::ancestors) { let lock_path = folder.join(LOCK_FILE); if !lock_path.exists() { continue; } let mut file = OpenOptions::new() .read(true) .write(true) .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW) .open(lock_path)?; let key = inode(&file)?; let owned = { let held = shared().lock().unwrap_or_else(|e| e.into_inner()); held.get(&key) .map(|claim| (claim.lease.upgrade(), claim.holder.clone())) }; if let Some((lease, holder)) = owned { if let Some(lease) = lease { return Ok(Some(lease)); } // A late blocking job can open after core shutdown. Reclaim under // flock before SQLite; a newer process that got there first wins. drop(file); return ProcessLock::claim(folder, holder).map(Some); } lock(&mut file)?; return Err(std::io::Error::other( "claim the data folder process lock before opening its store", ) .into()); } Ok(None)}