use super::Backend;
use crate::artifact::validate_key;
use std::{
fs::{self, File, OpenOptions},
io::{self, Read, Write},
path::{Path, PathBuf},
};
pub(super) struct Filesystem {
root: PathBuf,
}
impl Filesystem {
pub(super) fn new(root: &Path) -> io::Result<Self> {
if !root.is_absolute() {
return Err(io::Error::other("filesystem destination must be absolute"));
}
Ok(Self { root: root.into() })
}
fn path(&self, key: &str) -> io::Result<PathBuf> {
validate_key(key)?;
let path = self.root.join(key);
let mut current = self.root.clone();
if current
.symlink_metadata()
.is_ok_and(|m| m.file_type().is_symlink())
{
return Err(io::Error::other("symlink destination root"));
}
for component in Path::new(key).components() {
current.push(component);
if current
.symlink_metadata()
.is_ok_and(|m| m.file_type().is_symlink())
{
return Err(io::Error::other("symlink storage entry"));
}
}
Ok(path)
}
}
impl Backend for Filesystem {
fn read(&self, key: &str) -> io::Result<Box<dyn Read + Send>> {
Ok(Box::new(File::open(self.path(key)?)?))
}
fn write(&self, key: &str, path: &Path, create_only: bool) -> io::Result<()> {
self.write_stream(
key,
Box::new(File::open(path)?),
path.metadata()?.len(),
create_only,
)
}
fn write_stream(
&self,
key: &str,
reader: Box<dyn Read + Send>,
bytes: u64,
create_only: bool,
) -> io::Result<()> {
let target = self.path(key)?;
let parent = target.parent().unwrap();
fs::create_dir_all(parent)?;
let temporary = parent.join(format!(
".upload-{}-{}",
std::process::id(),
super::run_id()
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
let result = (|| {
let copied = io::copy(&mut reader.take(bytes.saturating_add(1)), &mut file)?;
if copied != bytes {
return Err(io::Error::other(
"storage stream length differs from declared length",
));
}
file.flush()?;
file.sync_all()?;
drop(file);
if create_only {
fs::hard_link(&temporary, &target)?;
fs::remove_file(&temporary)?;
} else {
fs::rename(&temporary, &target)?;
}
File::open(parent)?.sync_all()
})();
if result.is_err() {
let _ = fs::remove_file(temporary);
}
result
}
fn remove(&self, key: &str) -> io::Result<()> {
let path = self.path(key)?;
match fs::remove_file(&path) {
Ok(()) => File::open(path.parent().unwrap())?.sync_all(),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
fn list(&self, prefix: &str) -> io::Result<Vec<String>> {
fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) -> io::Result<()> {
if !dir.exists() {
return Ok(());
}
for entry in fs::read_dir(dir)? {
let e = entry?;
if e.file_type()?.is_symlink() {
return Err(io::Error::other("symlink in destination"));
}
if e.file_type()?.is_dir() {
walk(root, &e.path(), out)?;
} else {
out.push(
e.path()
.strip_prefix(root)
.unwrap()
.to_string_lossy()
.replace('\\', "/"),
);
}
}
Ok(())
}
let mut out = Vec::new();
walk(&self.root, &self.root, &mut out)?;
out.retain(|s| s.starts_with(prefix));
out.sort();
Ok(out)
}
}