use std::io::{Read, Write};
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use ostrya_core::RepoMode;
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
use crate::config::{MinFreeSpace, RepoConfig};
use crate::error::{Error, Result};
use crate::lock::{self, LockGuard, LockKind, RepoLock};
use crate::perm;
use crate::staging::StagingDir;
use crate::transaction::Transaction;
const CONFIG: &str = "config";
const DIR_MODE: u32 = 0o775;
const CONFIG_MODE: u32 = 0o644;
const LAYOUT_DIRS: &[&str] = &[
"objects",
"tmp",
"tmp/cache",
"refs",
"refs/heads",
"refs/remotes",
"refs/mirrors",
"state",
"extensions",
];
#[derive(Debug, Clone)]
pub struct CreateOptions {
pub mode: RepoMode,
pub collection_id: Option<String>,
}
impl Default for CreateOptions {
fn default() -> Self {
CreateOptions {
mode: RepoMode::Bare,
collection_id: None,
}
}
}
impl CreateOptions {
pub fn new(mode: RepoMode) -> Self {
CreateOptions {
mode,
collection_id: None,
}
}
}
#[derive(Debug, Clone)]
pub struct Repo {
inner: Arc<RepoInner>,
}
#[derive(Debug)]
struct RepoInner {
repo_fd: OwnedFd,
objects_fd: OwnedFd,
config: RepoConfig,
path: PathBuf,
lock: Mutex<Option<Arc<RepoLock>>>,
}
impl RepoInner {
fn repo_lock(&self) -> std::io::Result<Arc<RepoLock>> {
let mut slot = self.lock.lock().unwrap();
if let Some(existing) = slot.as_ref() {
return Ok(existing.clone());
}
let lock = RepoLock::get_or_create(self.repo_fd.as_fd(), self.config.mode())?;
*slot = Some(lock.clone());
Ok(lock)
}
}
struct Materials {
repo_fd: OwnedFd,
objects_fd: OwnedFd,
config: Vec<u8>,
}
impl Repo {
pub async fn open(path: &Path) -> Result<Repo> {
let path = path.to_owned();
let stored = path.clone();
let materials = ostrya_rt::unblock(move || open_materials(rustix::fs::CWD, &path)).await?;
Repo::assemble(materials, stored)
}
pub async fn open_at(dir: BorrowedFd<'_>, path: &Path) -> Result<Repo> {
let dir = dir.try_clone_to_owned()?;
let path = path.to_owned();
let stored = path.clone();
let materials = ostrya_rt::unblock(move || open_materials(&dir, &path)).await?;
Repo::assemble(materials, stored)
}
pub async fn create(path: &Path, opts: CreateOptions) -> Result<Repo> {
let path = path.to_owned();
let stored = path.clone();
let materials =
ostrya_rt::unblock(move || create_materials(rustix::fs::CWD, &path, &opts)).await?;
Repo::assemble(materials, stored)
}
pub async fn create_at(dir: BorrowedFd<'_>, path: &Path, opts: CreateOptions) -> Result<Repo> {
let dir = dir.try_clone_to_owned()?;
let path = path.to_owned();
let stored = path.clone();
let materials = ostrya_rt::unblock(move || create_materials(&dir, &path, &opts)).await?;
Repo::assemble(materials, stored)
}
pub fn mode(&self) -> RepoMode {
self.inner.config.mode()
}
pub fn config(&self) -> &RepoConfig {
&self.inner.config
}
pub fn path(&self) -> &Path {
&self.inner.path
}
pub async fn transaction(&self) -> Result<Transaction> {
self.transaction_with_lock(LockKind::Shared).await
}
pub async fn transaction_with_lock(&self, kind: LockKind) -> Result<Transaction> {
let expiry_secs = self.inner.config.tmp_expiry_secs()?;
let min_free = self.inner.config.min_free_space()?;
let guard = self.lock_repo(kind).await?;
let repo = self.clone();
let staging = ostrya_rt::unblock(move || {
let mode = repo.inner.config.mode();
StagingDir::create(repo.inner.repo_fd.as_fd(), expiry_secs, mode)
})
.await?;
let repo_fd = self.repo_fd().try_clone_to_owned()?;
let budget = ostrya_rt::unblock(move || free_budget(repo_fd.as_fd(), min_free)).await?;
Ok(Transaction::new(self.clone(), guard, staging, budget))
}
pub(crate) async fn lock_repo(&self, kind: LockKind) -> Result<LockGuard> {
let locking = self.inner.config.locking()?;
let timeout_secs = self.inner.config.lock_timeout_secs()?;
if !locking {
return Ok(LockGuard::disabled());
}
let repo = self.clone();
let lock = ostrya_rt::unblock(move || repo.inner.repo_lock()).await?;
let timeout = Duration::from_secs(timeout_secs.max(0) as u64);
lock::acquire(lock, kind, timeout).await
}
pub(crate) fn repo_fd(&self) -> BorrowedFd<'_> {
self.inner.repo_fd.as_fd()
}
pub(crate) fn objects_fd(&self) -> BorrowedFd<'_> {
self.inner.objects_fd.as_fd()
}
fn assemble(materials: Materials, path: PathBuf) -> Result<Repo> {
let text = std::str::from_utf8(&materials.config)
.map_err(|_| Error::InvalidFormat("config is not valid UTF-8".into()))?;
let config = RepoConfig::parse(text)?;
Ok(Repo {
inner: Arc::new(RepoInner {
repo_fd: materials.repo_fd,
objects_fd: materials.objects_fd,
config,
path,
lock: Mutex::new(None),
}),
})
}
}
fn free_budget(repo_fd: BorrowedFd<'_>, min_free: MinFreeSpace) -> Result<u64> {
let stat = rustix::fs::fstatvfs(repo_fd)?;
let available = stat.f_bavail.saturating_mul(stat.f_frsize);
let total = stat.f_blocks.saturating_mul(stat.f_frsize);
let reserved = match min_free {
MinFreeSpace::Percent(percent) => ((u128::from(total) * u128::from(percent)) / 100) as u64,
MinFreeSpace::Size(spec) => spec.bytes(),
};
Ok(available.saturating_sub(reserved))
}
fn open_materials<Fd: AsFd>(dir: Fd, path: &Path) -> std::io::Result<Materials> {
let repo_fd = open_dir(dir, path)?;
materials_from_repo(repo_fd)
}
fn create_materials<Fd: AsFd>(
dir: Fd,
path: &Path,
opts: &CreateOptions,
) -> std::io::Result<Materials> {
mkdir_idempotent(&dir, path, opts.mode)?;
let repo_fd = open_dir(&dir, path)?;
for sub in LAYOUT_DIRS {
mkdir_idempotent(&repo_fd, Path::new(sub), opts.mode)?;
}
write_initial_config(&repo_fd, opts)?;
materials_from_repo(repo_fd)
}
fn materials_from_repo(repo_fd: OwnedFd) -> std::io::Result<Materials> {
let objects_fd = open_dir(&repo_fd, Path::new("objects"))?;
let config = read_file(&repo_fd, CONFIG)?;
Ok(Materials {
repo_fd,
objects_fd,
config,
})
}
fn open_dir<Fd: AsFd>(dir: Fd, path: &Path) -> std::io::Result<OwnedFd> {
let fd = rustix::fs::openat(
dir,
path,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?;
Ok(fd)
}
fn read_file<Fd: AsFd>(dir: Fd, path: &str) -> std::io::Result<Vec<u8>> {
let fd = rustix::fs::openat(dir, path, OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty())?;
let mut buf = Vec::new();
std::fs::File::from(fd).read_to_end(&mut buf)?;
Ok(buf)
}
fn mkdir_idempotent<Fd: AsFd>(dir: Fd, path: &Path, mode: RepoMode) -> std::io::Result<()> {
match rustix::fs::mkdirat(&dir, path, Mode::from_raw_mode(DIR_MODE)) {
Ok(()) => perm::force_created_dir(&dir, path, mode),
Err(Errno::EXIST) => Ok(()),
Err(e) => Err(e.into()),
}
}
fn write_initial_config<Fd: AsFd>(repo_fd: Fd, opts: &CreateOptions) -> std::io::Result<()> {
let fd = match rustix::fs::openat(
repo_fd,
CONFIG,
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC,
Mode::from_raw_mode(CONFIG_MODE),
) {
Ok(fd) => fd,
Err(Errno::EXIST) => return Ok(()),
Err(e) => return Err(e.into()),
};
rustix::fs::fchmod(&fd, Mode::from_raw_mode(CONFIG_MODE))?;
std::fs::File::from(fd).write_all(initial_config_text(opts).as_bytes())
}
fn initial_config_text(opts: &CreateOptions) -> String {
let mut text = String::from("[core]\nrepo_version=1\nmode=");
text.push_str(opts.mode.as_mode_str());
text.push('\n');
if let Some(id) = &opts.collection_id {
text.push_str("collection-id=");
text.push_str(id);
text.push('\n');
}
text
}
#[allow(dead_code)]
fn assert_send_sync() {
fn is_send_sync<T: Send + Sync>() {}
is_send_sync::<Repo>();
}