use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use ostrya_core::{KeyFile, RepoMode};
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::remotes_dir;
use crate::repo_fs::{self, Publish, Published, RepoDir, RepoLayout, RootFile};
use crate::staging::StagingDir;
use crate::transaction::Transaction;
pub(crate) const MAX_CONFIG_SIZE: u64 = 1024 * 1024;
const INIT_KINDS: [RepoLayout; 5] = [
RepoLayout::Objects,
RepoLayout::Tmp,
RepoLayout::Refs,
RepoLayout::State,
RepoLayout::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::Path(path) if path.is_relative() => Err(Error::InvalidInput(format!(
"the remotes directory path {} is relative",
path.display()
))),
RemotesDir::InRepo(path) if path.is_absolute() => Err(Error::InvalidInput(format!(
"the in-repository remotes directory path {} is absolute",
path.display()
))),
RemotesDir::InRepo(path) if path.components().any(|c| c == Component::ParentDir) => {
Err(Error::InvalidInput(format!(
"the in-repository remotes directory path {} has a `..` component",
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 {
root: RepoDir,
objects: RepoDir,
config: RepoConfig,
path: PathBuf,
remotes_dir: Option<RemotesDir>,
lock: Mutex<Option<Arc<RepoLock>>>,
update_lock: Mutex<Option<Arc<UpdateLock>>>,
implicit_reads: OnceLock<ReadAccess>,
seal_probe: OnceLock<bool>,
}
impl RepoInner {
fn repo_lock(&self) -> 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.root)?;
*slot = Some(lock.clone());
Ok(lock)
}
fn update_lock(&self) -> 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.root)?;
*slot = Some(lock.clone());
Ok(lock)
}
}
struct Materials {
root: RepoDir,
objects: RepoDir,
config: RepoConfig,
remotes_dir: Option<RemotesDir>,
}
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.root.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(root: RepoDir, path: PathBuf) -> Result<Repo> {
Ok(Repo::assemble(materials_from_root(root)?, 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 => {
if let Some(sealed) = self.inner.seal_probe.get() {
return Ok(*sealed);
}
let repo = self.clone();
let sealed =
ostrya_rt::unblock(move || crate::write::probe_seal_blocking(repo.root_dir()))
.await?;
Ok(*self.inner.seal_probe.get_or_init(|| sealed))
}
}
}
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 || StagingDir::create(repo.root_dir(), expiry_secs)).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(repo.root_dir())).await
}
pub(crate) async fn read_config_and_remotes(&self) -> Result<RepoConfig> {
let repo = self.clone();
ostrya_rt::unblock(move || {
let config = read_config(repo.root_dir())?;
match repo.remotes_dir() {
Some(dir) => remotes_dir::read_remotes(config, repo.repo_fd(), dir),
None => Ok(config),
}
})
.await
}
pub(crate) fn root_dir(&self) -> &RepoDir {
&self.inner.root
}
pub(crate) fn repo_fd(&self) -> BorrowedFd<'_> {
self.inner.root.as_fd()
}
pub(crate) fn objects(&self) -> &RepoDir {
&self.inner.objects
}
pub(crate) fn objects_fd(&self) -> BorrowedFd<'_> {
self.inner.objects.as_fd()
}
fn assemble(materials: Materials, path: PathBuf) -> Repo {
Repo {
inner: Arc::new(RepoInner {
root: materials.root,
objects: materials.objects,
config: materials.config,
path,
remotes_dir: materials.remotes_dir,
lock: Mutex::new(None),
update_lock: Mutex::new(None),
implicit_reads: OnceLock::new(),
seal_probe: 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 is larger than its cap of {MAX_CONFIG_SIZE} bytes"
)));
}
Ok(())
}
pub(crate) fn read_config(root: &RepoDir) -> Result<RepoConfig> {
parse_config(&root.read_capped(RootFile::Config.name(), MAX_CONFIG_SIZE)?)
}
fn parse_config(bytes: &[u8]) -> Result<RepoConfig> {
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 (available, total) = repo_fs::fs_space(repo_fd)?;
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 materials = materials_from_root(RepoDir::open_root(dir, path)?)?;
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)?;
let root = RepoDir::create_root(dir, path, opts.mode, true)?;
if root.exists(RootFile::Config.name())? {
return Err(Error::RepoExists(path.to_owned()));
}
for kind in INIT_KINDS {
match kind {
RepoLayout::Tmp => root.tmp_dir(true)?,
kind => root.ensure_layout(kind, true)?,
};
}
write_initial_config(&root, path, &config)?;
materials_from_root(root)?.select_remotes_dir(opts.remotes_dir.as_ref(), None)
}
fn materials_from_root(root: RepoDir) -> Result<Materials> {
let config = read_config(&root)?;
let root = root.with_repo_mode(config.mode());
let objects = root.open_layout(RepoLayout::Objects)?;
Ok(Materials {
root,
objects,
config,
remotes_dir: None,
})
}
fn write_initial_config(root: &RepoDir, path: &Path, text: &str) -> Result<()> {
match root.write_root_file(
RootFile::Config,
text.as_bytes(),
Publish::KeepExisting,
true,
)? {
Published::Created => Ok(()),
Published::Existed => Err(Error::RepoExists(path.to_owned())),
}
}
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 value = match dir {
Some(RemotesDir::Path(path) | 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 = crate::repo_fs::TestDir::new("initial-config");
std::fs::write(dir.path().join("config"), b"race").unwrap();
let root = RepoDir::from_root_fd(rustix::io::dup(dir.fd()).unwrap());
let err = write_initial_config(&root, 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.path().join("config")).unwrap(), b"race");
let temps: Vec<_> = std::fs::read_dir(dir.path().join("tmp"))
.unwrap()
.map(|e| e.unwrap().file_name())
.filter(|name| name.as_bytes().starts_with(b".ostrya-tmp-"))
.collect();
assert!(temps.is_empty(), "{temps:?}");
}
#[test]
fn init_kinds_are_the_kinds_created_at_init() {
let all = [
RepoLayout::Root,
RepoLayout::Objects,
RepoLayout::Staging,
RepoLayout::Tmp,
RepoLayout::Refs,
RepoLayout::State,
RepoLayout::Extensions,
RepoLayout::Deltas,
RepoLayout::DeltaIndexes,
];
for kind in all {
match kind {
RepoLayout::Root
| RepoLayout::Objects
| RepoLayout::Staging
| RepoLayout::Tmp
| RepoLayout::Refs
| RepoLayout::State
| RepoLayout::Extensions
| RepoLayout::Deltas
| RepoLayout::DeltaIndexes => {}
}
}
let made: Vec<_> = all
.into_iter()
.filter(|kind| kind.rules().created_at_init && kind.rules().path.is_some())
.collect();
assert_eq!(made, INIT_KINDS);
}
}