use std::collections::BTreeSet;
use std::fmt::Write as _;
use std::fs::{self, File, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use nibkeep_base::{Hash, SpaceId};
use crate::file::{blob_keys_in, kept_blobs_in};
const BLOBS: &str = "blobs";
const TEMPORARY: &str = "tmp";
const LOCK: &str = "blobs.lock";
const DAMAGED: &str = "damaged";
const KEPT: &str = "kept";
const CHECK_CHUNK: usize = 1024 * 1024;
static TEMPORARY_FILES: AtomicU64 = AtomicU64::new(0);
pub(crate) struct BlobFiles {
directory: PathBuf,
temporary: PathBuf,
spaces: PathBuf,
space: SpaceId,
}
pub(crate) struct BlobLock(File);
impl Drop for BlobLock {
fn drop(&mut self) {
let _ = self.0.unlock();
}
}
impl BlobFiles {
pub(crate) fn of_log(log: &Path, space: SpaceId) -> Self {
let own = log.parent().unwrap_or(log);
let spaces = own.parent().unwrap_or(own);
Self {
directory: blob_directory(replica_of_log(log)),
temporary: own.join(TEMPORARY),
spaces: spaces.to_owned(),
space,
}
}
pub(crate) fn path(&self, sealed: &Hash) -> PathBuf {
place_in(&self.directory, sealed)
}
pub(crate) fn holds(&self, sealed: &Hash) -> bool {
self.path(sealed).is_file()
}
pub(crate) fn open(&self, sealed: &Hash) -> io::Result<File> {
File::open(self.path(sealed))
}
fn aside(&self, sealed: &Hash) -> PathBuf {
let replica = self.directory.parent().unwrap_or(&self.directory);
replica
.join(DAMAGED)
.join(sealed.algorithm().name())
.join(hex(sealed))
}
pub(crate) fn is_aside(&self, sealed: &Hash) -> bool {
self.aside(sealed).is_file()
}
fn kept_path(&self, sealed: &Hash) -> PathBuf {
let replica = self.directory.parent().unwrap_or(&self.directory);
replica
.join(KEPT)
.join(sealed.algorithm().name())
.join(hex(sealed))
}
pub(crate) fn is_kept(&self, sealed: &Hash) -> bool {
self.kept_path(sealed).is_file()
}
pub(crate) fn keep_apart(&self, sealed: &[Hash]) -> io::Result<()> {
let held: Vec<Hash> = sealed
.iter()
.copied()
.filter(|sealed| self.holds(sealed) || self.is_aside(sealed))
.collect();
if held.is_empty() {
return Ok(());
}
let _lock = self.lock()?;
let elsewhere = self.kept_elsewhere(&held);
let mut first = None;
for sealed in held.iter().filter(|sealed| !elsewhere.contains(sealed)) {
let path = self.path(sealed);
let kept = self.kept_path(sealed);
let moved = (|| {
if path.is_file() {
let directory = kept.parent().unwrap_or(&self.directory);
make_directory(directory)?;
fs::rename(&path, &kept)?;
sync_directory(directory);
if let Some(from) = path.parent() {
sync_directory(from);
}
}
ignore_missing(fs::remove_file(self.aside(sealed)))
})();
if let Err(error) = moved {
first.get_or_insert(error);
}
}
first.map_or(Ok(()), Err)
}
pub(crate) fn take_back(&self, sealed: &Hash) -> io::Result<bool> {
let _lock = self.lock()?;
let kept = self.kept_path(sealed);
if !kept.is_file() {
return Ok(self.holds(sealed));
}
if self.holds(sealed) {
fs::remove_file(&kept)?;
return Ok(true);
}
let path = self.path(sealed);
let directory = path.parent().unwrap_or(&self.directory);
make_directory(directory)?;
fs::rename(&kept, &path)?;
sync_directory(directory);
Ok(true)
}
pub(crate) fn destroy_kept(&self, sealed: &[Hash]) -> io::Result<Vec<Hash>> {
let held: Vec<Hash> = sealed
.iter()
.copied()
.filter(|sealed| self.is_kept(sealed))
.collect();
if held.is_empty() {
return Ok(Vec::new());
}
let _lock = self.lock()?;
let elsewhere = self.kept_apart_elsewhere(&held);
let mut destroyed = Vec::new();
let mut first = None;
for sealed in held.iter().filter(|sealed| !elsewhere.contains(sealed)) {
match ignore_missing(fs::remove_file(self.kept_path(sealed))) {
Ok(()) => destroyed.push(*sealed),
Err(error) => {
first.get_or_insert(error);
}
}
}
match first {
Some(error) if destroyed.is_empty() => Err(error),
_ => Ok(destroyed),
}
}
pub(crate) fn kept_files(&self) -> Vec<Hash> {
let replica = self.directory.parent().unwrap_or(&self.directory);
let mut found = Vec::new();
for algorithm in entries(&replica.join(KEPT)).unwrap_or_default() {
let Some(name) = algorithm.file_name().and_then(|name| name.to_str()) else {
continue;
};
let name = name.to_owned();
for path in entries(&algorithm).unwrap_or_default() {
if let Some(sealed) = path
.file_name()
.and_then(|digest| digest.to_str())
.and_then(|digest| format!("{name}:{digest}").parse::<Hash>().ok())
.filter(|sealed| self.kept_path(sealed) == path && path.is_file())
{
found.push(sealed);
}
}
}
found.sort_unstable();
found
}
pub(crate) fn kept_size(&self, sealed: &Hash) -> Option<u64> {
fs::metadata(self.kept_path(sealed))
.ok()
.map(|metadata| metadata.len())
}
fn kept_apart_elsewhere(&self, sealed: &[Hash]) -> BTreeSet<Hash> {
let mut kept = BTreeSet::new();
let own = self.space.to_string();
let Ok(entries) = fs::read_dir(&self.spaces) else {
return sealed.iter().copied().collect();
};
for entry in entries {
let Ok(entry) = entry else {
return sealed.iter().copied().collect();
};
if entry.file_name().to_str() == Some(own.as_str()) {
continue;
}
let log = entry.path().join("log.sqlite");
if !log.is_file() {
continue;
}
match kept_blobs_in(&log, sealed) {
Ok(found) => kept.extend(found),
Err(_) => return sealed.iter().copied().collect(),
}
}
kept
}
pub(crate) fn set_aside(&self, sealed: &Hash) -> io::Result<bool> {
let _lock = self.lock()?;
let path = self.path(sealed);
if !path.is_file() {
return Ok(false);
}
let aside = self.aside(sealed);
let directory = aside.parent().unwrap_or(&self.directory);
make_directory(directory)?;
fs::rename(&path, &aside)?;
sync_directory(directory);
if let Some(from) = path.parent() {
sync_directory(from);
}
Ok(true)
}
pub(crate) fn hash_file(
&self,
sealed: &Hash,
stop: &dyn Fn() -> bool,
) -> io::Result<Option<(Hash, u64)>> {
hash_file(&self.path(sealed), stop)
}
pub(crate) fn aside_files(&self) -> Vec<Hash> {
let replica = self.directory.parent().unwrap_or(&self.directory);
let mut found = Vec::new();
for algorithm in entries(&replica.join(DAMAGED)).unwrap_or_default() {
let Some(name) = algorithm.file_name().and_then(|name| name.to_str()) else {
continue;
};
let name = name.to_owned();
for path in entries(&algorithm).unwrap_or_default() {
if let Some(sealed) = path
.file_name()
.and_then(|digest| digest.to_str())
.and_then(|digest| format!("{name}:{digest}").parse::<Hash>().ok())
.filter(|sealed| self.aside(sealed) == path && path.is_file())
{
found.push(sealed);
}
}
}
found.sort_unstable();
found
}
pub(crate) fn hash_aside(
&self,
sealed: &Hash,
stop: &dyn Fn() -> bool,
) -> io::Result<Option<(Hash, u64)>> {
hash_file(&self.aside(sealed), stop)
}
pub(crate) fn restore(&self, sealed: &Hash) -> io::Result<bool> {
let _lock = self.lock()?;
let aside = self.aside(sealed);
if self.holds(sealed) || !aside.is_file() {
return Ok(false);
}
let path = self.path(sealed);
let directory = path.parent().unwrap_or(&self.directory);
make_directory(directory)?;
fs::rename(&aside, &path)?;
sync_directory(directory);
Ok(true)
}
pub(crate) fn temporary(&self) -> io::Result<(PathBuf, File)> {
make_directory(&self.temporary)?;
let path = self.temporary.join(format!(
"{}-{}.tmp",
std::process::id(),
TEMPORARY_FILES.fetch_add(1, Ordering::Relaxed)
));
let file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)?;
Ok((path, file))
}
pub(crate) fn stage(&self, written: &Path, sealed: &Hash) -> io::Result<PathBuf> {
let staged = self.temporary.join(staged_name(sealed));
fs::rename(written, &staged)?;
sync_directory(&self.temporary);
if let Some(directory) = self.path(sealed).parent() {
make_directory(directory)?;
}
Ok(staged)
}
pub(crate) fn place(&self, staged: &Path, sealed: &Hash) -> io::Result<()> {
let path = self.path(sealed);
let directory = path.parent().unwrap_or(&self.directory);
make_directory(directory)?;
fs::rename(staged, &path)?;
sync_directory(directory);
let _ = fs::remove_file(self.aside(sealed));
Ok(())
}
pub(crate) fn temporary_files(&self) -> io::Result<Vec<(PathBuf, Option<Hash>)>> {
staged_files(&self.temporary)
}
pub(crate) fn files(&self) -> io::Result<Vec<Result<Hash, PathBuf>>> {
files_in(&self.directory)
}
pub(crate) fn lock(&self) -> io::Result<BlobLock> {
let parent = self.directory.parent().unwrap_or(&self.directory);
make_directory(parent)?;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(parent.join(LOCK))?;
file.lock()?;
Ok(BlobLock(file))
}
pub(crate) fn release(&self, sealed: &[Hash]) -> io::Result<()> {
let held: Vec<Hash> = sealed
.iter()
.copied()
.filter(|sealed| self.holds(sealed) || self.is_aside(sealed))
.collect();
match self.delete(&held, true)?.1 {
Some(error) => Err(error),
None => Ok(()),
}
}
pub(crate) fn remove(&self, sealed: &[Hash]) -> io::Result<Vec<Hash>> {
let held: Vec<Hash> = sealed
.iter()
.copied()
.filter(|sealed| self.holds(sealed))
.collect();
Ok(self.delete(&held, false)?.0)
}
fn delete(&self, held: &[Hash], aside: bool) -> io::Result<(Vec<Hash>, Option<io::Error>)> {
if held.is_empty() {
return Ok((Vec::new(), None));
}
let _lock = self.lock()?;
let kept = self.kept_elsewhere(held);
let (mut deleted, mut failed) = (Vec::new(), None);
let mut directories = BTreeSet::new();
for sealed in held.iter().filter(|sealed| !kept.contains(sealed)) {
let path = self.path(sealed);
let mut result = ignore_missing(fs::remove_file(&path));
if aside && result.is_ok() {
result = ignore_missing(fs::remove_file(self.aside(sealed)));
}
match result {
Ok(()) => {
if let Some(parent) = path.parent() {
directories.insert(parent.to_owned());
}
deleted.push(*sealed);
}
Err(error) => {
failed.get_or_insert(error);
}
}
}
for directory in directories {
sync_directory(&directory);
}
Ok((deleted, failed))
}
pub(crate) fn kept_elsewhere(&self, sealed: &[Hash]) -> BTreeSet<Hash> {
let mut kept = BTreeSet::new();
let own = self.space.to_string();
let Ok(entries) = fs::read_dir(&self.spaces) else {
return sealed.iter().copied().collect();
};
for entry in entries {
let Ok(entry) = entry else {
return sealed.iter().copied().collect();
};
if entry.file_name().to_str() == Some(own.as_str()) {
continue;
}
let log = entry.path().join("log.sqlite");
if !log.is_file() {
continue;
}
match blob_keys_in(&log, sealed) {
Ok(found) => kept.extend(found),
Err(_) => return sealed.iter().copied().collect(),
}
}
kept
}
}
#[must_use]
pub fn place_in(directory: &Path, sealed: &Hash) -> PathBuf {
let digest = hex(sealed);
directory
.join(sealed.algorithm().name())
.join(&digest[..2])
.join(digest)
}
#[must_use]
pub fn blob_directory(replica: &Path) -> PathBuf {
replica.join(BLOBS)
}
pub fn hash_file(path: &Path, stop: &dyn Fn() -> bool) -> io::Result<Option<(Hash, u64)>> {
let mut file = File::open(path)?;
let mut hasher = nibkeep_base::Hasher::new();
let mut buffer = vec![0; CHECK_CHUNK];
let mut size = 0_u64;
loop {
if stop() {
return Ok(None);
}
let count = io::Read::read(&mut file, &mut buffer)?;
if count == 0 {
return Ok(Some((hasher.finalize(), size)));
}
hasher.update(&buffer[..count]);
size += count as u64;
}
}
pub fn blobs_starting_with(replica: &Path, like: &Hash, byte: u8) -> io::Result<Vec<(Hash, u64)>> {
let algorithm = like.algorithm().name();
let directory = blob_directory(replica);
let mut found = Vec::new();
for path in entries(&directory.join(algorithm).join(format!("{byte:02x}")))? {
let Some(sealed) = path
.file_name()
.and_then(|digest| digest.to_str())
.and_then(|digest| format!("{algorithm}:{digest}").parse::<Hash>().ok())
.filter(|sealed| place_in(&directory, sealed) == path)
else {
continue;
};
match fs::metadata(&path) {
Ok(metadata) if metadata.is_file() => found.push((sealed, metadata.len())),
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
found.sort_unstable();
Ok(found)
}
pub(crate) fn replica_of_log(log: &Path) -> &Path {
let own = log.parent().unwrap_or(log);
let spaces = own.parent().unwrap_or(own);
spaces.parent().unwrap_or(spaces)
}
fn make_directory(directory: &Path) -> io::Result<()> {
if directory.is_dir() {
return Ok(());
}
let mut missing = vec![directory];
while let Some(parent) = missing.last().and_then(|last| last.parent()) {
if parent.as_os_str().is_empty() || parent.is_dir() {
break;
}
missing.push(parent);
}
fs::create_dir_all(directory)?;
for made in missing.into_iter().rev() {
if let Some(parent) = made.parent() {
sync_directory(parent);
}
}
Ok(())
}
fn staged_name(sealed: &Hash) -> String {
format!("{}-{}", sealed.algorithm().name(), hex(sealed))
}
fn staged_files(directory: &Path) -> io::Result<Vec<(PathBuf, Option<Hash>)>> {
let entries = match fs::read_dir(directory) {
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
entries => entries?,
};
let mut files = Vec::new();
for entry in entries {
let path = entry?.path();
let staged = path
.file_name()
.and_then(|name| name.to_str())
.and_then(|name| name.replacen('-', ":", 1).parse().ok());
files.push((path, staged));
}
Ok(files)
}
fn files_in(directory: &Path) -> io::Result<Vec<Result<Hash, PathBuf>>> {
let mut files = Vec::new();
for algorithm in entries(directory)? {
let Some(name) = algorithm.file_name().and_then(|name| name.to_str()) else {
files.push(Err(algorithm));
continue;
};
if !algorithm.is_dir() {
files.push(Err(algorithm));
continue;
}
let name = name.to_owned();
for prefix in entries(&algorithm)? {
if !prefix.is_dir() {
files.push(Err(prefix));
continue;
}
for path in entries(&prefix)? {
let sealed = path
.file_name()
.and_then(|digest| digest.to_str())
.and_then(|digest| format!("{name}:{digest}").parse::<Hash>().ok())
.filter(|sealed| path.is_file() && place_in(directory, sealed) == path);
files.push(sealed.ok_or(path));
}
}
}
Ok(files)
}
fn hex(hash: &Hash) -> String {
hash.digest().iter().fold(String::new(), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
})
}
fn entries(directory: &Path) -> io::Result<Vec<PathBuf>> {
let entries = match fs::read_dir(directory) {
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
entries => entries?,
};
entries.map(|entry| Ok(entry?.path())).collect()
}
fn ignore_missing(result: io::Result<()>) -> io::Result<()> {
match result {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
other => other,
}
}
fn sync_directory(directory: &Path) {
#[cfg(unix)]
{
let _ = File::open(directory).and_then(|directory| directory.sync_all());
}
#[cfg(not(unix))]
let _ = directory;
}