use std::collections::{HashMap, HashSet};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex, PoisonError, RwLock, RwLockWriteGuard};
use std::time::Duration;
use super::ids::Ids;
use crate::durable::sync_directory;
use crate::sync::lock;
use crate::{Error, Result};
pub(crate) const UPLOADS: &str = "uploads";
pub(crate) const OBJECTS: &str = "objects";
const IDS_PER_DIR: u32 = 12;
const RENAME_TRIES: u32 = 5;
#[cfg(test)]
thread_local! {
pub(crate) static SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) struct Disk {
dir: PathBuf,
durable: bool,
made: Mutex<HashSet<i64>>,
syncs: Mutex<HashMap<PathBuf, Arc<DirSync>>>,
removals: RwLock<()>,
}
impl Disk {
pub(crate) fn dir(&self) -> &Path {
&self.dir
}
pub(crate) fn new(dir: PathBuf, durable: bool) -> Disk {
Disk {
dir,
durable,
made: Mutex::new(HashSet::new()),
syncs: Mutex::new(HashMap::new()),
removals: RwLock::new(()),
}
}
pub(crate) fn durable(&self) -> bool {
self.durable
}
pub(crate) fn fan(id: i64) -> i64 {
id >> IDS_PER_DIR
}
pub(crate) fn object_name(id: i64) -> String {
format!("{OBJECTS}/{:x}/{id:x}", Disk::fan(id))
}
pub(crate) fn span(fan: i64) -> (i64, i64) {
(fan << IDS_PER_DIR, ((fan + 1) << IDS_PER_DIR) - 1)
}
pub(crate) fn upload_path(&self, id: i64) -> PathBuf {
self.dir.join(UPLOADS).join(format!("{id:x}"))
}
pub(crate) fn object_path(&self, id: i64) -> PathBuf {
self.fan_dir(Disk::fan(id)).join(format!("{id:x}"))
}
fn fan_dir(&self, fan: i64) -> PathBuf {
self.dir.join(OBJECTS).join(format!("{fan:x}"))
}
pub(crate) fn create_upload(&self, id: i64) -> Result<std::fs::File> {
let path = self.upload_path(id);
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.map_err(|error| Error::io(format!("blobs: create {}", path.display()), error))
}
pub(crate) fn place(&self, id: i64) -> Result<()> {
let fan = Disk::fan(id);
self.make_fan(fan)?;
let (from, to) = (self.upload_path(id), self.object_path(id));
for attempt in 0.. {
match std::fs::rename(&from, &to) {
Ok(()) => break,
Err(error) if held_elsewhere(&error) && attempt + 1 < RENAME_TRIES => {
std::thread::sleep(Duration::from_millis(1 << attempt));
}
Err(error) => return Err(Error::io(format!("blobs: publish {}", to.display()), error)),
}
}
Ok(())
}
pub(crate) fn sync_placed(&self, id: i64) -> Result<()> {
self.sync_dir(self.fan_dir(Disk::fan(id)))
}
fn make_fan(&self, fan: i64) -> Result<()> {
if lock(&self.made).contains(&fan) {
return Ok(());
}
let dir = self.fan_dir(fan);
match std::fs::create_dir(&dir) {
Ok(()) => self.sync_dir(self.dir.join(OBJECTS))?,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(Error::io(format!("blobs: create {}", dir.display()), error)),
}
lock(&self.made).insert(fan);
Ok(())
}
fn sync_dir(&self, dir: PathBuf) -> Result<()> {
if !self.durable {
return Ok(());
}
#[cfg(test)]
if SYNC_FAILS.get() {
return Err(Error::io(format!("blobs: sync {}", dir.display()), io::Error::other("a disk that fails")));
}
let shared = Arc::clone(lock(&self.syncs).entry(dir.clone()).or_default());
shared.run(|| sync_directory(&dir)).map_err(|error| Error::io(format!("blobs: sync {}", dir.display()), error))
}
pub(crate) fn remove_object(&self, id: i64) -> Result<()> {
let _removing = self.removals.read().unwrap_or_else(PoisonError::into_inner);
remove(&self.object_path(id))
}
pub(crate) fn hold_removals(&self) -> RwLockWriteGuard<'_, ()> {
self.removals.write().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn link_object(&self, id: i64, into: &Path) -> Result<Option<String>> {
let name = Disk::object_name(id);
let (source, target) = (self.object_path(id), into.join(&name));
let failed = |error: io::Error| Error::io(format!("snapshot blobs: {name}"), error);
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent).map_err(failed)?;
}
match std::fs::hard_link(&source, &target) {
Ok(()) => Ok(Some(name)),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
tracing::warn!(target: "tinystore", content = id, "blobs: a file the snapshot names is missing");
Ok(None)
}
Err(_) => {
std::fs::copy(&source, &target).map_err(failed)?;
Ok(Some(name))
}
}
}
pub(crate) fn remove_upload(&self, id: i64) -> Result<()> {
remove(&self.upload_path(id))
}
pub(crate) fn sweep_uploads(&self, ids: &Ids) -> Result<usize> {
let mut removed = 0;
for (name, id) in self.names_in(&self.dir.join(UPLOADS))? {
if id.is_some_and(|id| ids.holds(id)) {
continue;
}
let path = self.dir.join(UPLOADS).join(&name);
std::fs::remove_file(&path)
.map_err(|error| Error::io(format!("blobs: remove {}", path.display()), error))?;
removed += 1;
}
Ok(removed)
}
pub(crate) fn ids_in(&self, fan: i64) -> Result<Vec<i64>> {
Ok(self.names_in(&self.fan_dir(fan))?.into_iter().filter_map(|(_, id)| id).collect())
}
fn names_in(&self, dir: &Path) -> Result<Vec<(String, Option<i64>)>> {
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(Error::io(format!("blobs: list {}", dir.display()), error)),
};
let mut names = Vec::new();
for entry in entries {
let entry = entry.map_err(|error| Error::io(format!("blobs: list {}", dir.display()), error))?;
let name = entry.file_name().to_string_lossy().into_owned();
let id = i64::from_str_radix(&name, 16).ok().filter(|id| *id > 0 && format!("{id:x}") == name);
names.push((name, id));
}
Ok(names)
}
}
fn remove(path: &Path) -> Result<()> {
match std::fs::remove_file(path) {
Err(error) if error.kind() != io::ErrorKind::NotFound => {
Err(Error::io(format!("blobs: remove {}", path.display()), error))
}
_ => Ok(()),
}
}
#[derive(Default)]
struct DirSync {
state: Mutex<SyncState>,
done: Condvar,
}
#[derive(Default)]
struct SyncState {
running: bool,
begun: u64,
synced: u64,
failure: Option<(io::ErrorKind, String)>,
}
impl DirSync {
fn run(&self, flush: impl Fn() -> io::Result<()>) -> io::Result<()> {
let mut state = lock(&self.state);
let wanted = state.begun + 1;
while state.synced < wanted {
if state.running {
state = self.done.wait(state).unwrap_or_else(std::sync::PoisonError::into_inner);
continue;
}
state.running = true;
state.begun += 1;
let mine = state.begun;
drop(state);
let outcome = flush();
state = lock(&self.state);
state.running = false;
state.synced = mine;
state.failure = outcome.err().map(|error| (error.kind(), error.to_string()));
self.done.notify_all();
}
match &state.failure {
Some((kind, what)) => Err(io::Error::new(*kind, what.clone())),
None => Ok(()),
}
}
}
#[cfg(windows)]
fn held_elsewhere(error: &io::Error) -> bool {
const ERROR_SHARING_VIOLATION: i32 = 32;
error.kind() == io::ErrorKind::PermissionDenied || error.raw_os_error() == Some(ERROR_SHARING_VIOLATION)
}
#[cfg(not(windows))]
fn held_elsewhere(_: &io::Error) -> bool {
false
}
#[cfg(windows)]
pub(crate) fn being_removed(error: &io::Error) -> bool {
error.kind() == io::ErrorKind::PermissionDenied
}
#[cfg(not(windows))]
pub(crate) fn being_removed(_: &io::Error) -> bool {
false
}
#[cfg(unix)]
pub(crate) fn read_at(file: &std::fs::File, bytes: &mut [u8], offset: u64) -> io::Result<usize> {
std::os::unix::fs::FileExt::read_at(file, bytes, offset)
}
#[cfg(windows)]
pub(crate) fn read_at(file: &std::fs::File, bytes: &mut [u8], offset: u64) -> io::Result<usize> {
std::os::windows::fs::FileExt::seek_read(file, bytes, offset)
}