use std::collections::BTreeSet;
use std::os::fd::BorrowedFd;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use ostrya_core::{Checksum, KeyFile, Ref};
use rustix::fs::AtFlags;
use rustix::io::Errno;
use crate::config::{
RemoteSource, RepoConfig, remote_group, remote_group_name, remote_keyring_name,
valid_remote_name,
};
use crate::error::{Error, Result};
use crate::lock::UpdateLocks;
use crate::refs::{
put_alias_blocking, put_ref_blocking, ref_relpath, refspec_to_relpath, relative_link,
sync_dirs_all,
};
use crate::remotes_dir::{self, DirWriter};
use crate::repo::{RemotesDir, Repo, check_config_size, read_config_blocking};
use crate::summary::put_root_file_blocking;
const CONFIG_FILE: &str = "config";
const ROOT_DIR: &str = ".";
const KEY_CHECK_GROUP: &str = "remote";
#[derive(Debug)]
pub struct UpdateGuard {
held: Arc<Held>,
}
#[derive(Debug)]
struct Held {
repo: Repo,
fsync: bool,
state: Mutex<Writes>,
config: Mutex<()>,
idle: Condvar,
locks: Mutex<Option<UpdateLocks>>,
}
#[derive(Debug, Default)]
struct Writes {
in_flight: usize,
dirs: BTreeSet<String>,
}
impl Held {
fn writes(&self) -> MutexGuard<'_, Writes> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn finish_blocking(&self) -> Result<()> {
let mut writes = self.writes();
while writes.in_flight > 0 {
writes = self
.idle
.wait(writes)
.unwrap_or_else(PoisonError::into_inner);
}
let dirs = std::mem::take(&mut writes.dirs);
drop(writes);
let synced = sync_dirs_all(self.repo.repo_fd(), dirs.into_iter().collect());
self.release();
synced
}
fn release(&self) {
let locks = self
.locks
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
drop(locks);
}
}
impl Drop for Held {
fn drop(&mut self) {
let writes = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
let dirs = std::mem::take(&mut writes.dirs);
let _ = sync_dirs_all(self.repo.repo_fd(), dirs.into_iter().collect());
}
}
struct InFlight {
held: Arc<Held>,
}
impl InFlight {
fn start(held: &Arc<Held>) -> InFlight {
held.writes().in_flight += 1;
InFlight { held: held.clone() }
}
}
impl Drop for InFlight {
fn drop(&mut self) {
let mut writes = self.held.writes();
writes.in_flight -= 1;
if writes.in_flight == 0 {
self.held.idle.notify_all();
}
}
}
impl Repo {
pub async fn begin_update(&self) -> Result<UpdateGuard> {
let fsync = self.config().fsync()?;
let locks = self.lock_for_update().await?;
Ok(UpdateGuard {
held: Arc::new(Held {
repo: self.clone(),
fsync,
state: Mutex::new(Writes::default()),
config: Mutex::new(()),
idle: Condvar::new(),
locks: Mutex::new(Some(locks)),
}),
})
}
}
impl UpdateGuard {
fn repo(&self) -> &Repo {
&self.held.repo
}
pub async fn read_ref(&self, r: &Ref) -> Result<Option<Checksum>> {
self.repo().resolve_ref_tip(r).await
}
pub async fn set_ref(&self, r: &Ref, checksum: Option<&Checksum>) -> Result<()> {
let relpath = ref_relpath(self.repo().config().collection_id(), r)?;
self.set_relpath(relpath, checksum).await
}
pub async fn set_ref_alias(&self, refspec: &str, target: &str) -> Result<()> {
let relpath = refspec_to_relpath(refspec)?;
let link = relative_link(&relpath, &refspec_to_relpath(target)?);
let repo_mode = self.repo().mode();
self.write(move |repo_fd, fsync, dirs| {
put_alias_blocking(repo_fd, &relpath, &link, fsync, repo_mode, dirs)
})
.await
}
pub async fn read_config(&self) -> Result<RepoConfig> {
self.repo().read_config_and_remotes().await
}
#[doc(hidden)]
pub async fn read_config_file(&self) -> Result<RepoConfig> {
self.repo().read_config_file().await
}
pub async fn write_config(&self, keyfile: &KeyFile) -> Result<()> {
let bytes = config_bytes(keyfile)?;
let names = remotes_dir::config_remote_names(keyfile);
let dir = self.repo().remotes_dir().cloned();
self.edit_config(move |repo_fd, fsync, dirs| {
remotes_dir::check_config_remotes(repo_fd, dir.as_ref(), &names)?;
put_config_blocking(repo_fd, &bytes, fsync, dirs)
})
.await
}
pub async fn add_remote(&self, name: &str, keys: &[(&str, &str)]) -> Result<()> {
if !valid_remote_name(name) {
return Err(Error::InvalidInput(format!("invalid remote name: {name}")));
}
if keys.is_empty() {
return Err(Error::InvalidInput(format!(
"remote {name} is added with no keys"
)));
}
let name = name.to_owned();
let keys: Vec<(String, String)> = keys
.iter()
.map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
.collect();
let dir = self.repo().remotes_dir().cloned();
self.edit_config(move |repo_fd, fsync, dirs| {
let (config, writer) = read_sources(repo_fd, dir.as_ref(), fsync)?;
if config.remote(&name).is_some() {
return Err(Error::RemoteExists(name));
}
let writer = match writer {
Some(writer) if config.add_remotes_config_dir()? => Some(writer),
_ => None,
};
let group = remote_group(&name);
let mut keyfile = match writer {
Some(_) => KeyFile::default(),
None => config.into_keyfile(),
};
for (key, value) in &keys {
check_key(key)?;
keyfile.set_string(&group, key, value)?;
}
match writer {
Some(writer) => {
let file = remote_file_name(&name);
writer.check_absent(&file)?;
writer.put(&file, keyfile.to_string().as_bytes(), None)
}
None => put_config_blocking(repo_fd, &config_bytes(&keyfile)?, fsync, dirs),
}
})
.await
}
pub async fn set_remote_key(&self, name: &str, key: &str, value: &str) -> Result<()> {
let name = name.to_owned();
let key = key.to_owned();
let value = value.to_owned();
let dir = self.repo().remotes_dir().cloned();
self.edit_config(move |repo_fd, fsync, dirs| {
let group = remote_group(&name);
let mut source = Source::read(repo_fd, dir.as_ref(), fsync, &name)?;
check_key(&key)?;
let keyfile = source.keyfile_mut();
if matches!(keyfile.get_string(&group, &key), Ok(Some(held)) if held == value) {
return Ok(());
}
keyfile.set_string(&group, &key, &value)?;
source.put(repo_fd, fsync, dirs)
})
.await
}
pub async fn unset_remote_key(&self, name: &str, key: &str) -> Result<bool> {
let name = name.to_owned();
let key = key.to_owned();
let dir = self.repo().remotes_dir().cloned();
self.edit_config(move |repo_fd, fsync, dirs| {
let group = remote_group(&name);
let mut source = Source::read(repo_fd, dir.as_ref(), fsync, &name)?;
if !source.keyfile_mut().remove_key(&group, &key) {
return Ok(false);
}
source.put(repo_fd, fsync, dirs)?;
Ok(true)
})
.await
}
pub async fn replace_remote(&self, name: &str, keys: &[(&str, &str)]) -> Result<()> {
if !valid_remote_name(name) {
return Err(Error::InvalidInput(format!("invalid remote name: {name}")));
}
if keys.is_empty() {
return Err(Error::InvalidInput(format!(
"remote {name} is replaced with no keys"
)));
}
let name = name.to_owned();
let keys: Vec<(String, String)> = keys
.iter()
.map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
.collect();
let dir = self.repo().remotes_dir().cloned();
self.edit_config(move |repo_fd, fsync, dirs| {
let group = remote_group(&name);
let mut source = Source::read(repo_fd, dir.as_ref(), fsync, &name)?;
let keyfile = source.keyfile_mut();
keyfile.remove_group(&group);
for (key, value) in &keys {
check_key(key)?;
keyfile.set_string(&group, key, value)?;
}
source.put(repo_fd, fsync, dirs)
})
.await
}
pub async fn delete_remote(&self, name: &str) -> Result<()> {
if !valid_remote_name(name) {
return Err(Error::InvalidInput(format!("invalid remote name: {name}")));
}
let name = name.to_owned();
let dir = self.repo().remotes_dir().cloned();
self.edit_config(move |repo_fd, fsync, dirs| {
let group = remote_group(&name);
let keyring = remote_keyring_name(&name);
match Source::read(repo_fd, dir.as_ref(), fsync, &name)? {
Source::Config(mut keyfile) => {
keyfile.remove_group(&group);
let bytes = config_bytes(&keyfile)?;
let removed = remove_keyring_blocking(repo_fd, &keyring)?;
let put = put_root_file_blocking(repo_fd, CONFIG_FILE, &bytes, fsync);
if fsync && (removed || put.is_ok()) {
dirs.push(ROOT_DIR.to_owned());
}
put
}
Source::File {
writer,
file,
mut keyfile,
} => {
keyfile.remove_group(&group);
let rewrite = if keyfile.groups().any(|g| remote_group_name(g).is_some()) {
let bytes = keyfile.to_string().into_bytes();
writer.check_size(&file, &bytes)?;
Some((writer.mode_of(&file)?, bytes))
} else {
None
};
if remove_keyring_blocking(repo_fd, &keyring)? && fsync {
dirs.push(ROOT_DIR.to_owned());
}
match rewrite {
Some((mode, bytes)) => writer.put(&file, &bytes, Some(mode)),
None => writer.remove(&file),
}
}
}
})
.await
}
pub async fn finish(self) -> Result<()> {
let held = self.held;
{
let writes = held.writes();
if writes.in_flight == 0 && writes.dirs.is_empty() {
drop(writes);
held.release();
return Ok(());
}
}
ostrya_rt::unblock(move || held.finish_blocking()).await
}
async fn set_relpath(&self, relpath: String, checksum: Option<&Checksum>) -> Result<()> {
let checksum = checksum.copied();
let repo_mode = self.repo().mode();
self.write(move |repo_fd, fsync, dirs| {
put_ref_blocking(repo_fd, &relpath, checksum, fsync, repo_mode, dirs)
})
.await
}
async fn edit_config<T, F>(&self, edit: F) -> Result<T>
where
F: FnOnce(BorrowedFd<'_>, bool, &mut Vec<String>) -> Result<T> + Send + 'static,
T: Send + 'static,
{
let held = self.held.clone();
self.write(move |repo_fd, fsync, dirs| {
let _config = held.config.lock().unwrap_or_else(PoisonError::into_inner);
edit(repo_fd, fsync, dirs)
})
.await
}
async fn write<T, F>(&self, put: F) -> Result<T>
where
F: FnOnce(BorrowedFd<'_>, bool, &mut Vec<String>) -> Result<T> + Send + 'static,
T: Send + 'static,
{
let flight = InFlight::start(&self.held);
ostrya_rt::unblock(move || {
let held = &flight.held;
let mut dirs = Vec::new();
let written = put(held.repo.repo_fd(), held.fsync, &mut dirs);
if held.fsync {
held.writes().dirs.extend(dirs);
}
drop(flight);
written
})
.await
}
}
fn check_key(key: &str) -> Result<()> {
KeyFile::default()
.set_string(KEY_CHECK_GROUP, key, "")
.map_err(|e| Error::InvalidInput(e.to_string()))
}
fn remote_file_name(name: &str) -> String {
format!("{name}.conf")
}
fn read_sources<'a>(
repo_fd: BorrowedFd<'a>,
dir: Option<&'a RemotesDir>,
fsync: bool,
) -> Result<(RepoConfig, Option<DirWriter<'a>>)> {
let config = read_config_blocking(repo_fd, false)?;
match dir {
Some(dir) => remotes_dir::open_for_write(config, repo_fd, dir, fsync)
.map(|(config, writer)| (config, Some(writer))),
None => Ok((config, None)),
}
}
enum Source<'a> {
Config(KeyFile),
File {
writer: DirWriter<'a>,
file: String,
keyfile: KeyFile,
},
}
impl<'a> Source<'a> {
fn read(
repo_fd: BorrowedFd<'a>,
dir: Option<&'a RemotesDir>,
fsync: bool,
name: &str,
) -> Result<Source<'a>> {
let (config, writer) = read_sources(repo_fd, dir, fsync)?;
let not_found = || Error::RemoteNotFound(name.to_owned());
let file = match config.remote(name).ok_or_else(not_found)?.source() {
RemoteSource::Config => None,
RemoteSource::File(file) => Some(file.to_owned()),
};
let Some(file) = file else {
return Ok(Source::Config(config.into_keyfile()));
};
let keyfile = config.into_remote_file(&file).ok_or_else(not_found)?;
Ok(Source::File {
writer: writer.ok_or_else(not_found)?,
file,
keyfile,
})
}
fn keyfile_mut(&mut self) -> &mut KeyFile {
match self {
Source::Config(keyfile) | Source::File { keyfile, .. } => keyfile,
}
}
fn put(&self, repo_fd: BorrowedFd<'_>, fsync: bool, dirs: &mut Vec<String>) -> Result<()> {
match self {
Source::Config(keyfile) => {
put_config_blocking(repo_fd, &config_bytes(keyfile)?, fsync, dirs)
}
Source::File {
writer,
file,
keyfile,
} => {
let mode = writer.mode_of(file)?;
writer.put(file, keyfile.to_string().as_bytes(), Some(mode))
}
}
}
}
fn config_bytes(keyfile: &KeyFile) -> Result<Vec<u8>> {
let bytes = keyfile.to_string().into_bytes();
check_config_size(&bytes)?;
Ok(bytes)
}
fn put_config_blocking(
repo_fd: BorrowedFd<'_>,
bytes: &[u8],
fsync: bool,
dirs: &mut Vec<String>,
) -> Result<()> {
put_root_file_blocking(repo_fd, CONFIG_FILE, bytes, fsync)?;
if fsync {
dirs.push(ROOT_DIR.to_owned());
}
Ok(())
}
fn remove_keyring_blocking(repo_fd: BorrowedFd<'_>, name: &str) -> Result<bool> {
match rustix::fs::unlinkat(repo_fd, name, AtFlags::empty()) {
Ok(()) => Ok(true),
Err(Errno::NOENT | Errno::NAMETOOLONG) => Ok(false),
Err(e) => Err(e.into()),
}
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
fn assert_send<T: Send>(_: &T) {}
assert_send_sync::<UpdateGuard>();
let _ = |repo: &Repo| assert_send(&repo.begin_update());
let _ = |guard: &UpdateGuard, r: &Ref, c: &Checksum| assert_send(&guard.set_ref(r, Some(c)));
let _ = |guard: &UpdateGuard, k: &KeyFile| assert_send(&guard.write_config(k));
let _ = |guard: &UpdateGuard| assert_send(&guard.add_remote("r", &[("url", "u")]));
let _ = |guard: &UpdateGuard| assert_send(&guard.set_remote_key("r", "url", "u"));
let _ = |guard: &UpdateGuard| assert_send(&guard.unset_remote_key("r", "url"));
let _ = |guard: &UpdateGuard| assert_send(&guard.replace_remote("r", &[("url", "u")]));
let _ = |guard: &UpdateGuard| assert_send(&guard.delete_remote("r"));
let _ = |guard: UpdateGuard| assert_send(&guard.finish());
};
#[cfg(test)]
mod tests {
use super::*;
use crate::lock::LockKind;
use crate::refs::test_syncs;
use crate::{CreateOptions, RepoMode};
use futures_lite::future::poll_once;
use std::path::PathBuf;
struct Scratch {
dir: PathBuf,
}
impl Scratch {
fn new(label: &str) -> Scratch {
let dir = std::env::temp_dir().join(format!(
"ostrya-update-guard-{label}-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
Scratch { dir }
}
fn path(&self) -> PathBuf {
self.dir.join("repo")
}
fn create(&self) -> Repo {
ostrya_rt::block_on(Repo::create(
&self.path(),
CreateOptions::new(RepoMode::BareUser),
))
.unwrap()
}
fn create_with(&self, line: &str) -> Repo {
drop(self.create());
let config = self.path().join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(line);
text.push('\n');
std::fs::write(&config, text).unwrap();
ostrya_rt::block_on(Repo::open(&self.path())).unwrap()
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn checksum() -> Checksum {
Checksum::from_bytes([7; 32])
}
async fn syncs_when_free(repo: &Repo, root: &std::path::Path) -> usize {
let held = repo.lock_update().await.unwrap();
let exclusive = repo.lock_repo(LockKind::Exclusive).await.unwrap();
let count = test_syncs::count(root);
drop((exclusive, held));
count
}
async fn write_three_dirs(guard: &UpdateGuard) {
guard
.set_ref(&Ref::local("a/one"), Some(&checksum()))
.await
.unwrap();
guard
.set_ref(&Ref::local("b"), Some(&checksum()))
.await
.unwrap();
let keyfile = guard.read_config().await.unwrap().keyfile().clone();
guard.write_config(&keyfile).await.unwrap();
}
#[test]
fn a_dropped_guard_syncs_before_the_locks_go() {
let scratch = Scratch::new("drop");
let repo = scratch.create();
ostrya_rt::block_on(async {
let guard = repo.begin_update().await.unwrap();
write_three_dirs(&guard).await;
let before = test_syncs::count(&scratch.path());
drop(guard);
assert_eq!(syncs_when_free(&repo, &scratch.path()).await, before + 3);
assert_eq!(test_syncs::unlocked(&scratch.path()), 0);
});
}
#[test]
fn a_finish_polled_once_and_dropped_syncs_before_the_locks_go() {
let scratch = Scratch::new("finish-dropped");
let repo = scratch.create();
ostrya_rt::block_on(async {
let guard = repo.begin_update().await.unwrap();
write_three_dirs(&guard).await;
let before = test_syncs::count(&scratch.path());
let mut finish = Box::pin(guard.finish());
let _ = poll_once(&mut finish).await;
drop(finish);
assert_eq!(syncs_when_free(&repo, &scratch.path()).await, before + 3);
assert_eq!(test_syncs::unlocked(&scratch.path()), 0);
});
}
#[test]
fn a_finish_never_polled_syncs_before_the_locks_go() {
let scratch = Scratch::new("finish-unpolled");
let repo = scratch.create();
ostrya_rt::block_on(async {
let guard = repo.begin_update().await.unwrap();
write_three_dirs(&guard).await;
let before = test_syncs::count(&scratch.path());
drop(guard.finish());
assert_eq!(syncs_when_free(&repo, &scratch.path()).await, before + 3);
assert_eq!(test_syncs::unlocked(&scratch.path()), 0);
});
}
#[test]
fn finish_syncs_each_directory_once() {
let scratch = Scratch::new("finish");
let repo = scratch.create();
ostrya_rt::block_on(async {
let guard = repo.begin_update().await.unwrap();
write_three_dirs(&guard).await;
guard
.set_ref(&Ref::local("a/two"), Some(&checksum()))
.await
.unwrap();
let before = test_syncs::count(&scratch.path());
guard.finish().await.unwrap();
assert_eq!(test_syncs::count(&scratch.path()), before + 3);
assert_eq!(test_syncs::unlocked(&scratch.path()), 0);
});
}
#[test]
fn finish_waits_for_a_write_whose_future_was_dropped() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::Duration;
let scratch = Scratch::new("in-flight");
let repo = scratch.create_with("lock-timeout-secs=0");
let root = scratch.path();
ostrya_rt::block_on(async {
let guard = repo.begin_update().await.unwrap();
let (started_tx, started_rx) = mpsc::channel();
let (go_tx, go_rx) = mpsc::channel::<()>();
let ended = Arc::new(AtomicBool::new(false));
let ended_in = ended.clone();
let mut write = Box::pin(guard.write(move |repo_fd, fsync, dirs| {
started_tx.send(()).unwrap();
go_rx.recv().unwrap();
let written = put_ref_blocking(
repo_fd,
"refs/heads/late/one",
Some(checksum()),
fsync,
RepoMode::BareUser,
dirs,
);
ended_in.store(true, Ordering::SeqCst);
written
}));
assert!(poll_once(&mut write).await.is_none());
started_rx
.recv_timeout(Duration::from_secs(10))
.expect("the write started on the blocking pool");
drop(write);
let before = test_syncs::count(&root);
let mut finish = Box::pin(guard.finish());
assert!(poll_once(&mut finish).await.is_none(), "finish waits");
ostrya_rt::Timer::after(Duration::from_millis(100)).await;
assert!(poll_once(&mut finish).await.is_none(), "finish waits");
assert!(crate::lock::update_lock_held_in_process(repo.repo_fd()));
go_tx.send(()).unwrap();
finish.await.unwrap();
assert!(ended.load(Ordering::SeqCst), "the write ended first");
assert_eq!(test_syncs::count(&root), before + 2);
assert_eq!(test_syncs::unlocked(&root), 0);
assert!(!crate::lock::update_lock_held_in_process(repo.repo_fd()));
let exclusive = repo.lock_repo(LockKind::Exclusive).await.unwrap();
drop(exclusive);
});
}
#[test]
fn fsync_off_records_no_directory() {
let scratch = Scratch::new("no-fsync");
let repo = scratch.create_with("fsync=false");
ostrya_rt::block_on(async {
let guard = repo.begin_update().await.unwrap();
write_three_dirs(&guard).await;
let before = test_syncs::count(&scratch.path());
guard.finish().await.unwrap();
assert_eq!(test_syncs::count(&scratch.path()), before);
});
}
}