use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use crate::hash::ContentHash;
use super::{BlobStore, ObjectKey, StoreError};
#[derive(Clone, Debug)]
pub struct FsStore {
root: PathBuf,
}
impl FsStore {
pub fn open(root: &Path) -> Result<Self, StoreError> {
create_dir(root)?;
Ok(Self {
root: root.to_path_buf(),
})
}
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
#[must_use]
pub fn path_of(&self, key: &ObjectKey) -> PathBuf {
let hex = key.hash.to_hex();
self.root
.join(&hex[..2])
.join(format!("{}{}", &hex[2..], key.suffix))
}
pub fn keys(&self) -> Result<Vec<ObjectKey>, StoreError> {
let mut keys = Vec::new();
for shard in read_dir(&self.root)? {
let Some(prefix) = shard
.file_name()
.map(|name| name.to_string_lossy().into_owned())
else {
continue;
};
if prefix.len() != 2 || !shard.is_dir() {
continue;
}
for object in read_dir(&shard)? {
let Some(name) = object
.file_name()
.map(|name| name.to_string_lossy().into_owned())
else {
continue;
};
let (rest, suffix) = match name.find('.') {
Some(at) => (&name[..at], &name[at..]),
None => (name.as_str(), ""),
};
if let Some(hash) = ContentHash::parse(&format!("{prefix}{rest}")) {
keys.push(ObjectKey::new(hash, suffix));
}
}
}
keys.sort_unstable();
Ok(keys)
}
fn install(&self, staged: &Path, key: &ObjectKey) -> Result<(), StoreError> {
let path = self.path_of(key);
if let Some(parent) = path.parent() {
create_dir(parent)?;
}
match fs::hard_link(staged, &path) {
Ok(()) => {
remove(staged)?;
make_read_only(&path)
}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => remove(staged),
Err(_) => {
if path.is_file() {
return remove(staged);
}
move_file(staged, &path)?;
make_read_only(&path)
}
}
}
}
impl BlobStore for FsStore {
fn has(&self, key: &ObjectKey) -> Result<bool, StoreError> {
Ok(self.path_of(key).is_file())
}
fn get(&self, key: &ObjectKey) -> Result<Option<Vec<u8>>, StoreError> {
let path = self.path_of(key);
match fs::read(&path) {
Ok(bytes) => Ok(Some(bytes)),
Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(StoreError::Io { path, source }),
}
}
fn put(&self, key: &ObjectKey, bytes: &[u8]) -> Result<(), StoreError> {
if self.has(key)? {
return Ok(());
}
let staged = self.root.join(format!(".partial-{key}.{}", writer()));
if let Some(parent) = staged.parent() {
create_dir(parent)?;
}
fs::write(&staged, bytes).map_err(|source| StoreError::Io {
path: staged.clone(),
source,
})?;
self.install(&staged, key)
}
fn put_file(&self, staged: &Path, suffix: &str) -> Result<ObjectKey, StoreError> {
let hash = ContentHash::of_file(staged).map_err(|source| StoreError::Io {
path: staged.to_path_buf(),
source,
})?;
let key = ObjectKey::new(hash, suffix);
self.install(staged, &key)?;
Ok(key)
}
fn put_file_as(&self, staged: &Path, key: &ObjectKey) -> Result<(), StoreError> {
let found = ContentHash::of_file(staged).map_err(|source| StoreError::Io {
path: staged.to_path_buf(),
source,
})?;
if found != key.hash {
return Err(StoreError::Mismatch {
expected: key.hash,
found,
at: staged.to_path_buf(),
});
}
self.install(staged, key)
}
fn local_path(&self, key: &ObjectKey) -> Result<Option<PathBuf>, StoreError> {
let path = self.path_of(key);
Ok(path.is_file().then_some(path))
}
}
fn writer() -> String {
static NEXT: AtomicU64 = AtomicU64::new(0);
format!(
"{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
)
}
fn read_dir(path: &Path) -> Result<Vec<PathBuf>, StoreError> {
match fs::read_dir(path) {
Ok(entries) => Ok(entries.filter_map(Result::ok).map(|e| e.path()).collect()),
Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
Err(source) => Err(StoreError::Io {
path: path.to_path_buf(),
source,
}),
}
}
fn create_dir(path: &Path) -> Result<(), StoreError> {
fs::create_dir_all(path).map_err(|source| StoreError::Io {
path: path.to_path_buf(),
source,
})
}
fn remove(path: &Path) -> Result<(), StoreError> {
fs::remove_file(path).map_err(|source| StoreError::Io {
path: path.to_path_buf(),
source,
})
}
fn move_file(from: &Path, to: &Path) -> Result<(), StoreError> {
match fs::rename(from, to) {
Ok(()) => Ok(()),
Err(_) => {
fs::copy(from, to).map_err(|source| StoreError::Io {
path: to.to_path_buf(),
source,
})?;
remove(from)
}
}
}
fn make_read_only(path: &Path) -> Result<(), StoreError> {
let metadata = fs::metadata(path).map_err(|source| StoreError::Io {
path: path.to_path_buf(),
source,
})?;
let mut permissions = metadata.permissions();
permissions.set_readonly(true);
fs::set_permissions(path, permissions).map_err(|source| StoreError::Io {
path: path.to_path_buf(),
source,
})
}