use std::io::{Read, Write};
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use ostrya_core::{KeyFile, RepoMode};
use rustix::fs::{AtFlags, Mode, OFlags};
use rustix::io::Errno;
use crate::access::{AuthItem, ClientAccess, ReadAccess};
use crate::config::{EX_OSTRYA, MinFreeSpace, REMOTES_CONFIG_DIR, RepoConfig, Tristate};
use crate::error::{Error, Result};
use crate::lock::{self, LockGuard, LockKind, RepoLock, UpdateLock, UpdateLockHeld, UpdateLocks};
use crate::perm;
use crate::remotes_dir;
use crate::staging::StagingDir;
use crate::transaction::Transaction;
const CONFIG: &str = "config";
pub(crate) const MAX_CONFIG_SIZE: u64 = 1024 * 1024;
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 enum RemotesDir {
Path(PathBuf),
Fd(Arc<OwnedFd>),
InRepo(PathBuf),
}
impl RemotesDir {
pub fn path(path: impl Into<PathBuf>) -> RemotesDir {
RemotesDir::Path(path.into())
}
fn check(&self) -> Result<()> {
match self {
RemotesDir::Path(path) | RemotesDir::InRepo(path)
if path.as_os_str().as_bytes().contains(&0) =>
{
Err(Error::InvalidInput(format!(
"the remotes directory path {} holds a NUL byte",
path.display()
)))
}
RemotesDir::Path(path) if path.as_os_str().is_empty() => Err(Error::InvalidInput(
"the remotes directory path is empty".into(),
)),
RemotesDir::InRepo(path) if path.as_os_str().is_empty() => Err(Error::InvalidInput(
"the in-repository remotes directory path is empty".into(),
)),
RemotesDir::InRepo(path) if path.is_absolute() => Err(Error::InvalidInput(format!(
"the in-repository remotes directory path {} is absolute",
path.display()
))),
_ => Ok(()),
}
}
}
impl From<PathBuf> for RemotesDir {
fn from(path: PathBuf) -> RemotesDir {
RemotesDir::Path(path)
}
}
impl From<OwnedFd> for RemotesDir {
fn from(fd: OwnedFd) -> RemotesDir {
RemotesDir::Fd(Arc::new(fd))
}
}
#[derive(Debug, Clone, Default)]
pub struct OpenOptions {
remotes_dir: Option<RemotesDir>,
default_remotes_dir: Option<RemotesDir>,
}
impl OpenOptions {
pub fn new() -> Self {
OpenOptions::default()
}
pub fn remotes_dir(mut self, dir: RemotesDir) -> Self {
self.remotes_dir = Some(dir);
self
}
pub fn default_remotes_dir(mut self, dir: RemotesDir) -> Self {
self.default_remotes_dir = Some(dir);
self
}
fn check(&self) -> Result<()> {
for dir in [&self.remotes_dir, &self.default_remotes_dir]
.into_iter()
.flatten()
{
dir.check()?;
}
Ok(())
}
pub async fn open(&self, path: &Path) -> Result<Repo> {
self.check()?;
let opts = self.clone();
let path = path.to_owned();
let stored = path.clone();
let materials =
ostrya_rt::unblock(move || open_materials(rustix::fs::CWD, &path, false, &opts))
.await?;
Ok(Repo::assemble(materials, stored))
}
pub async fn open_at(&self, dir: BorrowedFd<'_>, path: &Path) -> Result<Repo> {
self.check()?;
let opts = self.clone();
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, false, &opts)).await?;
Ok(Repo::assemble(materials, stored))
}
}
#[derive(Debug, Clone)]
pub struct CreateOptions {
mode: RepoMode,
collection_id: Option<String>,
remotes_dir: Option<RemotesDir>,
}
impl Default for CreateOptions {
fn default() -> Self {
CreateOptions::new(RepoMode::Bare)
}
}
impl CreateOptions {
pub fn new(mode: RepoMode) -> Self {
CreateOptions {
mode,
collection_id: None,
remotes_dir: None,
}
}
pub fn collection_id(mut self, id: impl Into<String>) -> Self {
self.collection_id = Some(id.into());
self
}
pub fn remotes_dir(mut self, dir: RemotesDir) -> Self {
self.remotes_dir = Some(dir);
self
}
pub async fn create(&self, path: &Path) -> Result<Repo> {
self.check()?;
let opts = self.clone();
let path = path.to_owned();
let stored = path.clone();
let materials =
ostrya_rt::unblock(move || create_materials(rustix::fs::CWD, &path, &opts)).await?;
Ok(Repo::assemble(materials, stored))
}
pub async fn create_at(&self, dir: BorrowedFd<'_>, path: &Path) -> Result<Repo> {
self.check()?;
let opts = self.clone();
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?;
Ok(Repo::assemble(materials, stored))
}
fn check(&self) -> Result<()> {
if let Some(id) = &self.collection_id
&& id.contains(['\n', '\r'])
{
return Err(Error::InvalidInput(format!(
"the collection id {id:?} holds a line break"
)));
}
let Some(dir) = &self.remotes_dir else {
return Ok(());
};
dir.check()?;
match dir {
RemotesDir::Path(path) | RemotesDir::InRepo(path) => utf8_key_value(path).map(drop),
RemotesDir::Fd(_) => Ok(()),
}
}
}
#[derive(Debug, Clone)]
pub struct Repo {
inner: Arc<RepoInner>,
}
#[derive(Debug)]
struct RepoInner {
repo_fd: OwnedFd,
objects_fd: OwnedFd,
config: RepoConfig,
path: PathBuf,
remotes_dir: Option<RemotesDir>,
strict: bool,
lock: Mutex<Option<Arc<RepoLock>>>,
update_lock: Mutex<Option<Arc<UpdateLock>>>,
implicit_reads: OnceLock<ReadAccess>,
}
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)
}
fn update_lock(&self) -> std::io::Result<Arc<UpdateLock>> {
let mut slot = self.update_lock.lock().unwrap();
if let Some(existing) = slot.as_ref() {
return Ok(existing.clone());
}
let lock = UpdateLock::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: RepoConfig,
remotes_dir: Option<RemotesDir>,
strict: bool,
}
impl Materials {
fn select_remotes_dir(
mut self,
first: Option<&RemotesDir>,
default: Option<&RemotesDir>,
) -> Result<Materials> {
let key = remotes_dir::from_key(&self.config)?;
let selected = first.cloned().or(key).or_else(|| default.cloned());
if let Some(dir) = &selected {
self.config = remotes_dir::read_remotes(self.config, self.repo_fd.as_fd(), dir)?;
}
self.remotes_dir = selected;
Ok(self)
}
}
impl Repo {
pub async fn open(path: &Path) -> Result<Repo> {
OpenOptions::new().open(path).await
}
pub async fn open_at(dir: BorrowedFd<'_>, path: &Path) -> Result<Repo> {
OpenOptions::new().open_at(dir, path).await
}
#[doc(hidden)]
pub async fn open_at_strict(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, true, &OpenOptions::default()))
.await?;
Ok(Repo::assemble(materials, stored))
}
pub(crate) fn open_strict_blocking(repo_fd: OwnedFd, path: PathBuf) -> Result<Repo> {
Ok(Repo::assemble(materials_from_repo(repo_fd, true)?, path))
}
pub async fn create(path: &Path, opts: CreateOptions) -> Result<Repo> {
opts.create(path).await
}
pub async fn create_at(dir: BorrowedFd<'_>, path: &Path, opts: CreateOptions) -> Result<Repo> {
opts.create_at(dir, path).await
}
pub fn mode(&self) -> RepoMode {
self.inner.config.mode()
}
pub fn config(&self) -> &RepoConfig {
&self.inner.config
}
pub(crate) fn implicit_reads(&self) -> &ReadAccess {
self.inner.implicit_reads.get_or_init(|| {
ReadAccess::new(
Arc::new(ClientAccess::implicit(self.config().collection_id())),
AuthItem::Anonymous,
None,
)
})
}
pub fn path(&self) -> &Path {
&self.inner.path
}
pub fn remotes_dir(&self) -> Option<&RemotesDir> {
self.inner.remotes_dir.as_ref()
}
pub fn objects_dir(&self) -> BorrowedFd<'_> {
self.objects_fd()
}
pub async fn seals_objects(&self) -> Result<bool> {
match self.inner.config.fsverity()? {
Tristate::Yes => Ok(true),
Tristate::No => Ok(false),
Tristate::Maybe => {
let repo = self.clone();
ostrya_rt::unblock(move || {
let tmp = crate::staging::open_tmp_dir(repo.repo_fd(), repo.mode())?;
crate::write::probe_seal_blocking(tmp.as_fd())
})
.await
}
}
}
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()?;
self.inner.config.generate_composefs()?;
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 cached = self.inner.lock.lock().unwrap().clone();
let lock = match cached {
Some(lock) => lock,
None => {
let repo = self.clone();
ostrya_rt::unblock(move || repo.inner.repo_lock()).await?
}
};
lock::acquire(lock, kind, lock_timeout(timeout_secs)).await
}
pub(crate) async fn lock_update(&self) -> Result<UpdateLockHeld> {
let timeout_secs = self.inner.config.lock_timeout_secs()?;
let cached = self.inner.update_lock.lock().unwrap().clone();
let lock = match cached {
Some(lock) => lock,
None => {
let repo = self.clone();
ostrya_rt::unblock(move || repo.inner.update_lock()).await?
}
};
lock::acquire_update(lock, lock_timeout(timeout_secs)).await
}
pub(crate) async fn lock_for_update(&self) -> Result<UpdateLocks> {
self.inner.config.locking()?;
self.inner.config.lock_timeout_secs()?;
let repo = self.lock_repo(LockKind::Shared).await?;
let update = self.lock_update().await?;
Ok(UpdateLocks { update, repo })
}
pub(crate) async fn write_locked<T, F>(&self, write: F) -> Result<T>
where
F: FnOnce(&Repo) -> Result<T> + Send + 'static,
T: Send + 'static,
{
let locks = self.lock_for_update().await?;
self.write_holding(locks, write).await
}
pub(crate) async fn write_holding<T, F>(&self, locks: UpdateLocks, write: F) -> Result<T>
where
F: FnOnce(&Repo) -> Result<T> + Send + 'static,
T: Send + 'static,
{
let repo = self.clone();
ostrya_rt::unblock(move || {
let written = write(&repo);
drop(locks);
written
})
.await
}
pub(crate) fn holds_update_lock(&self, held: &UpdateLockHeld) -> bool {
self.inner
.update_lock
.lock()
.unwrap()
.as_ref()
.is_some_and(|lock| held.is_of(lock))
}
pub(crate) async fn read_config_file(&self) -> Result<RepoConfig> {
let repo = self.clone();
ostrya_rt::unblock(move || read_config_blocking(repo.repo_fd(), repo.is_strict())).await
}
pub(crate) async fn read_config_and_remotes(&self) -> Result<RepoConfig> {
let repo = self.clone();
ostrya_rt::unblock(move || {
let config = read_config_blocking(repo.repo_fd(), repo.is_strict())?;
match repo.remotes_dir() {
Some(dir) => remotes_dir::read_remotes(config, repo.repo_fd(), dir),
None => Ok(config),
}
})
.await
}
pub(crate) fn is_strict(&self) -> bool {
self.inner.strict
}
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) -> Repo {
Repo {
inner: Arc::new(RepoInner {
repo_fd: materials.repo_fd,
objects_fd: materials.objects_fd,
config: materials.config,
path,
remotes_dir: materials.remotes_dir,
strict: materials.strict,
lock: Mutex::new(None),
update_lock: Mutex::new(None),
implicit_reads: OnceLock::new(),
}),
}
}
}
pub(crate) fn check_config_size(bytes: &[u8]) -> Result<()> {
if bytes.len() as u64 > MAX_CONFIG_SIZE {
return Err(Error::InvalidFormat(format!(
"config exceeds the {MAX_CONFIG_SIZE}-byte size cap"
)));
}
Ok(())
}
pub(crate) fn read_config_blocking(repo_fd: BorrowedFd<'_>, strict: bool) -> Result<RepoConfig> {
parse_config(&read_file(repo_fd, CONFIG, strict)?)
}
fn parse_config(bytes: &[u8]) -> Result<RepoConfig> {
check_config_size(bytes)?;
let text = std::str::from_utf8(bytes)
.map_err(|_| Error::InvalidFormat("config is not valid UTF-8".into()))?;
RepoConfig::parse(text)
}
fn lock_timeout(secs: i64) -> Option<Duration> {
u64::try_from(secs).ok().map(Duration::from_secs)
}
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,
strict: bool,
opts: &OpenOptions,
) -> Result<Materials> {
let repo_fd = open_dir(dir, path)?;
let materials = materials_from_repo(repo_fd, strict)?;
if strict {
return Ok(materials);
}
materials.select_remotes_dir(opts.remotes_dir.as_ref(), opts.default_remotes_dir.as_ref())
}
fn create_materials<Fd: AsFd>(dir: Fd, path: &Path, opts: &CreateOptions) -> Result<Materials> {
let config = initial_config_text(opts)?;
mkdir_idempotent(&dir, path, opts.mode)?;
let repo_fd = open_dir(&dir, path)?;
match rustix::fs::statat(&repo_fd, CONFIG, AtFlags::SYMLINK_NOFOLLOW) {
Ok(_) => return Err(Error::RepoExists(path.to_owned())),
Err(Errno::NOENT) => {}
Err(e) => return Err(e.into()),
}
for sub in LAYOUT_DIRS {
mkdir_idempotent(&repo_fd, Path::new(sub), opts.mode)?;
}
write_initial_config(&repo_fd, path, &config)?;
materials_from_repo(repo_fd, false)?.select_remotes_dir(opts.remotes_dir.as_ref(), None)
}
fn materials_from_repo(repo_fd: OwnedFd, strict: bool) -> Result<Materials> {
let objects_fd = match strict {
true => rustix::fs::openat(
&repo_fd,
"objects",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::empty(),
)?,
false => open_dir(&repo_fd, Path::new("objects"))?,
};
let config = read_config_blocking(repo_fd.as_fd(), strict)?;
Ok(Materials {
repo_fd,
objects_fd,
config,
remotes_dir: None,
strict,
})
}
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, strict: bool) -> std::io::Result<Vec<u8>> {
let fd = crate::object::open_regular_file(dir.as_fd(), path, strict)?;
let mut buf = Vec::new();
std::fs::File::from(fd)
.take(MAX_CONFIG_SIZE + 1)
.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, path: &Path, config: &str) -> 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 Err(Error::RepoExists(path.to_owned())),
Err(e) => return Err(e.into()),
};
rustix::fs::fchmod(&fd, Mode::from_raw_mode(CONFIG_MODE))?;
std::fs::File::from(fd).write_all(config.as_bytes())?;
Ok(())
}
fn initial_config_text(opts: &CreateOptions) -> Result<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');
}
if let Some(group) = remotes_dir_group(opts.remotes_dir.as_ref())? {
text.push('\n');
text.push_str(&group);
}
Ok(text)
}
fn utf8_key_value(path: &Path) -> Result<&str> {
path.to_str().ok_or_else(|| {
Error::InvalidInput(format!(
"the remotes directory path {} is not valid UTF-8",
path.display()
))
})
}
fn remotes_dir_group(dir: Option<&RemotesDir>) -> Result<Option<String>> {
let absolute;
let value = match dir {
Some(RemotesDir::Path(path)) => {
absolute = std::path::absolute(path)?;
&absolute
}
Some(RemotesDir::InRepo(path)) => path,
Some(RemotesDir::Fd(_)) | None => return Ok(None),
};
let value = utf8_key_value(value)?;
let mut group = KeyFile::default();
group.set_string(EX_OSTRYA, REMOTES_CONFIG_DIR, value)?;
Ok(Some(group.to_string()))
}
#[allow(dead_code)]
fn assert_send_sync() {
fn is_send_sync<T: Send + Sync>() {}
fn is_send<T: Send>(_: &T) {}
is_send_sync::<Repo>();
is_send_sync::<OpenOptions>();
is_send_sync::<CreateOptions>();
is_send_sync::<RemotesDir>();
let _ = |opts: &OpenOptions, path: &Path| is_send(&opts.open(path));
let _ =
|opts: &OpenOptions, dir: BorrowedFd<'_>, path: &Path| is_send(&opts.open_at(dir, path));
let _ = |opts: &CreateOptions, path: &Path| is_send(&opts.create(path));
let _ = |opts: &CreateOptions, dir: BorrowedFd<'_>, path: &Path| {
is_send(&opts.create_at(dir, path))
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lock_timeout_maps_the_config_value() {
assert_eq!(lock_timeout(-1), None);
assert_eq!(lock_timeout(0), Some(Duration::ZERO));
assert_eq!(lock_timeout(5), Some(Duration::from_secs(5)));
}
#[test]
fn initial_config_write_refuses_an_existing_config() {
let dir = std::env::temp_dir().join(format!(
"ostrya-initial-config-{}-{}",
std::process::id(),
crate::write::unique()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(CONFIG), b"race").unwrap();
let fd = open_dir(rustix::fs::CWD, &dir).unwrap();
let err = write_initial_config(&fd, Path::new("repo"), "[core]\n").unwrap_err();
assert!(
matches!(&err, Error::RepoExists(p) if p == Path::new("repo")),
"{err:?}"
);
assert_eq!(std::fs::read(dir.join(CONFIG)).unwrap(), b"race");
std::fs::remove_dir_all(&dir).unwrap();
}
}