#![allow(dead_code)]
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use futures_io::AsyncWrite;
pub mod composefs;
pub mod modes;
pub mod pipe;
#[cfg(feature = "receive")]
pub mod receive;
#[cfg(feature = "s3")]
pub mod s3;
pub fn anyone() -> ostrya::access::ReadAccess {
read_access("", "anonymous")
}
pub fn read_access(groups: &str, item: &str) -> ostrya::access::ReadAccess {
let text = format!("[core]\nrepo_version=1\nmode=archive-z2\n{groups}");
let config = ostrya::RepoConfig::parse(&text).unwrap();
let access = ostrya::access::ClientAccess::from_config(&config).unwrap();
let item = ostrya::access::AuthItem::parse(item).unwrap();
ostrya::access::ReadAccess::new(Arc::new(access), item, None)
}
pub fn repo_access(repo: &ostrya::Repo, item: &str) -> ostrya::access::ReadAccess {
let access = ostrya::access::ClientAccess::from_config(repo.config()).unwrap();
let item = ostrya::access::AuthItem::parse(item).unwrap();
ostrya::access::ReadAccess::new(Arc::new(access), item, None)
}
pub fn fixture_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/generated")
}
pub fn fixture_repo(mode: &str) -> PathBuf {
match mode {
"bare-user" | "canon" | "xattr" => unpack_fixture(mode).join("repo"),
_ => fixture_root().join(mode).join("repo"),
}
}
pub fn add_empty_ref_dirs(repo: &Path) {
for sub in ["refs/remotes", "refs/mirrors"] {
std::fs::create_dir_all(repo.join(sub)).unwrap();
}
}
pub fn unpack_fixture(name: &str) -> PathBuf {
static REGISTRY: OnceLock<Mutex<HashMap<String, PathBuf>>> = OnceLock::new();
let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new()));
let mut map = registry.lock().unwrap();
if let Some(dir) = map.get(name) {
return dir.clone();
}
let dir = std::env::temp_dir()
.join(format!("ostrya-fixtures-{}", std::process::id()))
.join(name);
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("create fixture unpack dir");
let tar = fixture_root().join(format!("{name}.tar"));
let status = Command::new("tar")
.args(["--xattrs", "--xattrs-include=user.*", "-xf"])
.arg(&tar)
.arg("-C")
.arg(&dir)
.status()
.expect("run tar to unpack fixture");
assert!(status.success(), "tar failed to unpack {}", tar.display());
map.insert(name.to_owned(), dir.clone());
dir
}
pub const COMMIT: &str = "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89";
pub const CONTENT: &str = "d79e5560a90877b47660b639e3d7c88c20ca5a7604f867960e155c552025e104";
pub const ROOT_DIRTREE: &str = "1075002e681eb1fe7ff54ae6b76b1f65285e514b54d96deaa0952330b10c7983";
pub const ROOT_DIRMETA: &str = "446a0ef11b7cc167f3b603e585c7eeeeb675faa412d5ec73f62988eb0b6c5488";
pub const EMPTY_TXT: &str = "cc700d46f407c6c5ab2d5dde474366a928b7398277e61162e7f8ec06f469f07e";
pub const HELLO_TXT: &str = "cfffd52f38d14c87cf46e18d5260074421ba5961f0895954e9921f165f9c91db";
pub const LINK: &str = "f66efa496a72379413c44593de510dc344beb045294f1a543da87b2b6118db35";
pub const SUBDIR_DIRTREE: &str = "78154b9650d2a28716fd4a83584a2d9cba1833be4851714d8a0e89e8933c875a";
pub const NESTED_TXT: &str = "a4d80a620354908d76238bea8185775d2f6d60f55a1506d16ee06af212b4a125";
pub const SIZES_COMMIT: &str = "3ecadc59022c36743e1b233afbf3bde7b25239b77035185a3acc2af9d84478f0";
pub struct TmpDir(PathBuf);
impl TmpDir {
pub fn new(tag: &str) -> TmpDir {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("ostrya-read-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create scratch dir");
TmpDir(path)
}
pub fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TmpDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
pub const GUARD_WAIT: Duration = Duration::from_secs(30);
pub async fn within<T>(what: &str, fut: impl Future<Output = T>) -> T {
futures_lite::future::or(fut, async {
ostrya_rt::Timer::after(GUARD_WAIT).await;
panic!("{what} took longer than {GUARD_WAIT:?}");
})
.await
}
pub const GUARD_HOLD: Duration = Duration::from_millis(500);
pub async fn wait_for_commit_under_guard<F>(
repo: &ostrya::Repo,
commit: &ostrya::Checksum,
task: &mut F,
) where
F: Future + Unpin,
F::Output: std::fmt::Debug,
{
let deadline = Instant::now() + GUARD_WAIT;
while !repo
.has_object(ostrya::ObjectType::Commit, commit)
.await
.unwrap()
{
if let Some(result) = futures_lite::future::poll_once(&mut *task).await {
panic!("the pull ended under the guard: {result:?}");
}
assert!(Instant::now() < deadline, "no commit after {GUARD_WAIT:?}");
ostrya_rt::Timer::after(Duration::from_millis(10)).await;
}
ostrya_rt::Timer::after(GUARD_HOLD).await;
}
const FOREIGN_LOCK_REPO: &str = "OSTRYA_TEST_FOREIGN_LOCK_REPO";
const FOREIGN_LOCK_FILE: &str = "OSTRYA_TEST_FOREIGN_LOCK_FILE";
const FOREIGN_LOCK_MARKER: &str = ".foreign-held";
pub const LOCK_HOLDER_TEST: &str = "lock_holder_subprocess";
pub struct ChildGuard(std::process::Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn wait_for_marker(marker: &Path, what: &str) {
let started = Instant::now();
while !marker.exists() {
assert!(started.elapsed() < Duration::from_secs(10), "{what}");
std::thread::sleep(Duration::from_millis(20));
}
}
pub fn foreign_holder(repo: &Path, lock_file: &str) -> ChildGuard {
let holder = ChildGuard(
Command::new(std::env::current_exe().unwrap())
.args([LOCK_HOLDER_TEST, "--exact", "--ignored", "--nocapture"])
.env(FOREIGN_LOCK_REPO, repo)
.env(FOREIGN_LOCK_FILE, lock_file)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn the lock holder"),
);
wait_for_marker(
&repo.join(FOREIGN_LOCK_MARKER),
"the holder never took the lock",
);
holder
}
pub fn lock_holder_main() {
use rustix::fs::{FlockOperation, Mode, OFlags};
use std::io::Read;
let (Ok(repo), Ok(lock_file)) = (
std::env::var(FOREIGN_LOCK_REPO),
std::env::var(FOREIGN_LOCK_FILE),
) else {
return;
};
let repo = Path::new(&repo);
let fd = rustix::fs::open(
repo.join(lock_file),
OFlags::RDWR | OFlags::CREATE,
Mode::from_raw_mode(0o660),
)
.expect("open the lock file");
rustix::fs::fcntl_lock(&fd, FlockOperation::LockExclusive).expect("take the record lock");
std::fs::write(repo.join(FOREIGN_LOCK_MARKER), b"1").expect("write the readiness marker");
let mut sink = Vec::new();
let _ = std::io::stdin().read_to_end(&mut sink);
}
const GUARD_HOLDER_REPO: &str = "OSTRYA_TEST_GUARD_HOLDER_REPO";
pub const GUARD_HELD_MARKER: &str = ".guard-held";
pub const GUARD_RELEASING_MARKER: &str = ".guard-releasing";
pub const GUARD_HOLDER_TEST: &str = "guard_holder_subprocess";
pub struct GuardHolder {
child: Option<std::process::Child>,
}
impl GuardHolder {
pub fn release(mut self) {
let mut child = self.child.take().unwrap();
drop(child.stdin.take());
let output = child.wait_with_output().unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"the guard holder reported {}:\n{stdout}",
output.status
);
}
pub fn pid(&self) -> u32 {
self.child.as_ref().unwrap().id()
}
}
impl Drop for GuardHolder {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
pub fn guard_holder(repo: &Path) -> GuardHolder {
let child = Command::new(std::env::current_exe().unwrap())
.args([GUARD_HOLDER_TEST, "--exact", "--ignored", "--nocapture"])
.env(GUARD_HOLDER_REPO, repo)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn the guard holder");
let holder = GuardHolder { child: Some(child) };
wait_for_marker(
&repo.join(GUARD_HELD_MARKER),
"the holder never took the guard",
);
holder
}
pub fn guard_holder_main() {
use std::io::Read;
let Some(path) = std::env::var_os(GUARD_HOLDER_REPO).map(PathBuf::from) else {
return;
};
ostrya_rt::block_on(async {
let repo = ostrya::Repo::open(&path).await.unwrap();
let guard = repo.begin_update().await.unwrap();
std::fs::write(path.join(GUARD_HELD_MARKER), b"1").unwrap();
let mut sink = Vec::new();
let _ = std::io::stdin().read_to_end(&mut sink);
std::fs::write(path.join(GUARD_RELEASING_MARKER), b"1").unwrap();
guard.finish().await.unwrap();
});
}
const WRITER_CHILD_REPO: &str = "OSTRYA_TEST_WRITER_CHILD_REPO";
const WRITER_CHILD_ARG: &str = "OSTRYA_TEST_WRITER_CHILD_ARG";
pub const WRITER_CHILD_TEST: &str = "writer_child_subprocess";
pub struct WriterChild {
child: Option<std::process::Child>,
}
impl WriterChild {
pub fn wait(mut self) {
let child = self.child.take().unwrap();
let output = child.wait_with_output().unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"the writer reported {}:\n{stdout}",
output.status
);
}
pub fn finished(&mut self) -> bool {
let child = self.child.as_mut().unwrap();
child.try_wait().unwrap().is_some()
}
}
impl Drop for WriterChild {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
pub fn writer_child(repo: &Path, arg: &str) -> WriterChild {
writer_child_with(repo, arg, |_| {})
}
pub fn writer_child_with(
repo: &Path,
arg: &str,
configure: impl FnOnce(&mut Command),
) -> WriterChild {
let mut command = Command::new(std::env::current_exe().unwrap());
command
.args([WRITER_CHILD_TEST, "--exact", "--ignored", "--nocapture"])
.env(WRITER_CHILD_REPO, repo)
.env(WRITER_CHILD_ARG, arg)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
configure(&mut command);
let child = command.spawn().expect("spawn the writer");
WriterChild { child: Some(child) }
}
pub fn writer_child_main(write: impl FnOnce(&Path, &str)) {
let (Some(path), Ok(arg)) = (
std::env::var_os(WRITER_CHILD_REPO).map(PathBuf::from),
std::env::var(WRITER_CHILD_ARG),
) else {
return;
};
write(&path, &arg);
}
pub const REQUIRE_OSTREE: &str = "OSTRYA_REQUIRE_OSTREE";
pub fn ostree_available() -> bool {
let found = Command::new("ostree")
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false);
assert!(
found || std::env::var_os(REQUIRE_OSTREE).is_none(),
"{REQUIRE_OSTREE} is set and `ostree` is not installed, so the \
tool-comparison tests cannot run"
);
found
}
pub fn tool_fsck(root: &Path) {
let out = tool_fsck_output(root, &[]);
assert!(
out.status.success(),
"ostree fsck failed on {}: {}",
root.display(),
String::from_utf8_lossy(&out.stderr)
);
}
pub fn tool_fsck_output(root: &Path, args: &[&str]) -> std::process::Output {
Command::new("ostree")
.arg("fsck")
.arg(format!("--repo={}", root.display()))
.args(args)
.output()
.unwrap()
}
#[cfg(feature = "s3")]
pub async fn dump_bucket(bucket: &ostrya::remote::s3::Bucket, dir: &Path) {
let mut keys: Vec<String> = ["config", "summary", "summary.sig"]
.into_iter()
.map(str::to_owned)
.collect();
for prefix in ["objects/", "refs/", "deltas/", "delta-indexes/", "state/"] {
let listing = bucket.list(prefix).await.unwrap();
keys.extend(listing.objects.into_iter().map(|listed| listed.key));
}
for key in keys {
let Some(stream) = bucket.get_stream(&key).await.unwrap() else {
continue;
};
let path = dir.join(&key);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let file = futures_lite::io::AssertAsync::new(std::fs::File::create(&path).unwrap());
futures_lite::io::copy(stream, file).await.unwrap();
}
for sub in s3::REPO_DIRS {
std::fs::create_dir_all(dir.join(sub)).unwrap();
}
}
pub const REQUIRE_OSTREE_ED25519: &str = "OSTRYA_REQUIRE_OSTREE_ED25519";
pub fn ostree_supports_ed25519() -> bool {
let supported = ostree_available()
&& Command::new("ostree")
.arg("--version")
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).contains("sign-ed25519"))
.unwrap_or(false);
assert!(
supported || std::env::var_os(REQUIRE_OSTREE_ED25519).is_none(),
"{REQUIRE_OSTREE_ED25519} is set and the installed `ostree` carries no \
ed25519 engine, so the ed25519 cross-check tests cannot run"
);
supported
}
pub const REQUIRE_OSTREE_SPKI: &str = "OSTRYA_REQUIRE_OSTREE_SPKI";
pub fn ostree_supports_spki() -> bool {
let supported = ostree_available()
&& Command::new("ostree")
.arg("--version")
.output()
.map(|o| {
let stdout = String::from_utf8_lossy(&o.stdout);
let has = |feature: &str| stdout.lines().any(|line| line.trim() == feature);
has("- openssl") && has("- sign-spki")
})
.unwrap_or(false);
assert!(
supported || std::env::var_os(REQUIRE_OSTREE_SPKI).is_none(),
"{REQUIRE_OSTREE_SPKI} is set and the installed `ostree` carries no \
spki engine, so the spki cross-check tests cannot run"
);
supported
}
pub fn openssl_available() -> bool {
Command::new("openssl")
.arg("version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
pub fn wrap_pem(kind: &str, b64: &str) -> String {
let mut body = String::new();
for chunk in b64.as_bytes().chunks(64) {
body.push_str(std::str::from_utf8(chunk).unwrap());
body.push('\n');
}
format!("-----BEGIN {kind}-----\n{body}-----END {kind}-----\n")
}
pub const REQUIRE_GNUPG: &str = "OSTRYA_REQUIRE_GNUPG";
pub fn gnupg_available(programs: &[&str]) -> bool {
for program in programs {
let found = Command::new(program)
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false);
if !found {
assert!(
std::env::var_os(REQUIRE_GNUPG).is_none(),
"{REQUIRE_GNUPG} is set and `{program}` is not available, so \
the GPG tests cannot run"
);
eprintln!("skipping: {program} not available");
return false;
}
}
true
}
pub fn remove_gnupg_sockets(dir: &Path) {
for action in [&["--kill", "all"][..], &["--remove-socketdir"][..]] {
let _ = Command::new("gpgconf")
.arg("--homedir")
.arg(dir)
.args(action)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
}
}
#[cfg(feature = "verify-gpg")]
pub struct GnupgHome {
pub dir: std::path::PathBuf,
}
#[cfg(feature = "verify-gpg")]
impl GnupgHome {
pub fn new(dir: &Path, uid: &str) -> GnupgHome {
use std::os::unix::fs::DirBuilderExt;
std::fs::DirBuilder::new().mode(0o700).create(dir).unwrap();
let status = std::process::Command::new("gpg")
.arg("--homedir")
.arg(dir)
.args(["--batch", "--pinentry-mode", "loopback", "--passphrase", ""])
.args(["--quick-gen-key", uid, "ed25519", "sign", "never"])
.status()
.unwrap();
assert!(status.success(), "gpg --quick-gen-key failed");
GnupgHome {
dir: dir.to_owned(),
}
}
pub fn export(&self) -> Vec<u8> {
let out = std::process::Command::new("gpg")
.arg("--homedir")
.arg(&self.dir)
.args(["--batch", "--export"])
.output()
.unwrap();
assert!(
out.status.success() && !out.stdout.is_empty(),
"gpg --export failed"
);
out.stdout
}
}
#[cfg(feature = "verify-gpg")]
impl Drop for GnupgHome {
fn drop(&mut self) {
remove_gnupg_sockets(&self.dir);
}
}
pub fn file_inventory(root: &Path, sub: &str) -> Vec<(String, Vec<u8>)> {
let mut out = Vec::new();
let mut stack = vec![root.join(sub)];
while let Some(dir) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let kind = entry.file_type().unwrap();
let name = path
.strip_prefix(root)
.unwrap()
.to_string_lossy()
.into_owned();
if kind.is_dir() {
stack.push(path);
} else if kind.is_symlink() {
let target = std::fs::read_link(&path).unwrap();
out.push((name, target.into_os_string().into_encoded_bytes()));
} else {
out.push((name, std::fs::read(&path).unwrap()));
}
}
}
out.sort();
out
}
pub fn mark_partial(repo: &ostrya::Repo, commit: &ostrya::Checksum) {
std::fs::write(
repo.path().join(format!("state/{commit}.commitpartial")),
b"",
)
.unwrap();
}
pub type Field2Entry<'a> = (&'a str, &'a [u8]);
pub async fn store_with_field2(
repo: &ostrya::Repo,
source: &ostrya::Checksum,
related: &[Field2Entry<'_>],
) -> ostrya::Checksum {
let (mut commit, _) = repo.load_commit(source).await.unwrap();
commit.related = related
.iter()
.map(|(name, bytes)| ((*name).to_owned(), bytes.to_vec()))
.collect();
let bytes = commit.serialize().unwrap();
let txn = repo.transaction().await.unwrap();
let written = txn
.write_metadata(ostrya::ObjectType::Commit, None, &bytes)
.await
.unwrap();
txn.commit().await.unwrap();
written
}
pub async fn store_with_undecodable_field2(
repo: &ostrya::Repo,
source: &ostrya::Checksum,
) -> ostrya::Checksum {
let name = b"lib/undecodable\0";
let (mut commit, _) = repo.load_commit(source).await.unwrap();
commit.related = vec![("lib/undecodable".to_owned(), source.as_bytes().to_vec())];
let mut bytes = commit.serialize().unwrap();
let at = bytes
.windows(name.len())
.position(|window| window == name)
.unwrap();
bytes[at + name.len() - 1] = b'!';
let txn = repo.transaction().await.unwrap();
let written = txn
.write_metadata(ostrya::ObjectType::Commit, None, &bytes)
.await
.unwrap();
txn.commit().await.unwrap();
written
}
pub fn attachment_error(err: ostrya::Error) -> (Option<ostrya::Checksum>, String) {
match err {
ostrya::Error::InvalidRelations {
commit,
field: ostrya::RelationField::Attachments,
reason,
} => (commit, reason),
other => panic!("expected InvalidRelations in field 2, got {other:?}"),
}
}
pub fn attachment_warning(commit: ostrya::Checksum, reason: &str) -> ostrya::RelationWarning {
ostrya::RelationWarning {
commit,
field: ostrya::RelationField::Attachments,
reason: reason.to_owned(),
}
}
pub const CHAIN_C: &str = "container/fe";
pub const CHAIN_D: &str = "details/fe";
pub const DIAMOND_A: &str = "lib/a";
pub const DIAMOND_B: &str = "lib/b";
pub const DIAMOND_D: &str = "lib/d";
pub struct Chain {
pub r: ostrya::Checksum,
pub c: ostrya::Checksum,
pub d: ostrya::Checksum,
}
pub struct Diamond {
pub r: ostrya::Checksum,
pub a: ostrya::Checksum,
pub b: ostrya::Checksum,
pub d: ostrya::Checksum,
}
pub async fn write_chain(repo: &ostrya::Repo, base: &Path, branch: &str) -> Chain {
let d = write_labelled(repo, base, &format!("{branch}-d"), &[], None).await;
let c = write_labelled(repo, base, &format!("{branch}-c"), &[(CHAIN_D, d)], None).await;
let r = write_labelled(
repo,
base,
&format!("{branch}-r"),
&[(CHAIN_C, c)],
Some(branch),
)
.await;
Chain { r, c, d }
}
pub async fn write_diamond(repo: &ostrya::Repo, base: &Path, branch: &str) -> Diamond {
let d = write_labelled(repo, base, &format!("{branch}-d"), &[], None).await;
let a = write_labelled(repo, base, &format!("{branch}-a"), &[(DIAMOND_D, d)], None).await;
let b = write_labelled(repo, base, &format!("{branch}-b"), &[(DIAMOND_D, d)], None).await;
let r = write_labelled(
repo,
base,
&format!("{branch}-r"),
&[(DIAMOND_A, a), (DIAMOND_B, b)],
Some(branch),
)
.await;
Diamond { r, a, b, d }
}
async fn write_labelled(
repo: &ostrya::Repo,
base: &Path,
label: &str,
attachments: &[(&str, ostrya::Checksum)],
branch: Option<&str>,
) -> ostrya::Checksum {
use std::os::fd::AsFd;
let dir = base.join(label);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("payload.txt"), label).unwrap();
let txn = repo.transaction().await.unwrap();
let mut mtree = ostrya::MutableTree::new();
let mut modifier = ostrya::CommitModifier::new(
ostrya::CommitModifierFlags::SKIP_XATTRS
| ostrya::CommitModifierFlags::CANONICAL_PERMISSIONS,
);
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(
dfd.as_fd(),
Path::new(label),
&mut mtree,
Some(&mut modifier),
)
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
ostrya::CommitOptions {
subject: Some(label.to_owned()),
timestamp: Some(1_700_000_000),
attachments: attachments
.iter()
.map(|(name, checksum)| ((*name).to_owned(), *checksum))
.collect(),
..ostrya::CommitOptions::default()
},
&root,
)
.await
.unwrap();
if let Some(branch) = branch {
txn.set_ref(&branch.parse::<ostrya::Ref>().unwrap(), Some(&commit));
}
txn.commit().await.unwrap();
commit
}
pub fn is_sealed(path: &Path) -> bool {
std::fs::OpenOptions::new().write(true).open(path).is_err()
}
pub fn regular_objects(root: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
for fanout in std::fs::read_dir(root.join("objects")).unwrap().flatten() {
if !fanout.file_type().unwrap().is_dir() {
continue;
}
for entry in std::fs::read_dir(fanout.path()).unwrap().flatten() {
if entry.file_type().unwrap().is_file() {
out.push(entry.path());
}
}
}
out
}
pub struct Untouchable {
pub calls: Arc<AtomicU64>,
}
impl Untouchable {
fn call<T>(&self) -> Poll<io::Result<T>> {
self.calls.fetch_add(1, Ordering::Relaxed);
Poll::Ready(Err(io::Error::other("the output must not be used")))
}
}
impl AsyncWrite for Untouchable {
fn poll_write(self: Pin<&mut Self>, _: &mut Context<'_>, _: &[u8]) -> Poll<io::Result<usize>> {
self.call()
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
self.call()
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
self.call()
}
}
pub struct Counting<W> {
pub inner: W,
pub written: Arc<AtomicU64>,
}
impl<W: AsyncWrite + Unpin> AsyncWrite for Counting<W> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let me = self.get_mut();
let n = std::task::ready!(Pin::new(&mut me.inner).poll_write(cx, buf))?;
me.written.fetch_add(n as u64, Ordering::Relaxed);
Poll::Ready(Ok(n))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_close(cx)
}
}
#[derive(Clone)]
pub struct ThreadRecorder {
key: &'static str,
threads: Arc<Mutex<Vec<std::thread::ThreadId>>>,
}
impl ThreadRecorder {
pub fn new(key: &'static str) -> ThreadRecorder {
ThreadRecorder {
key,
threads: Arc::default(),
}
}
pub fn threads(&self) -> Vec<std::thread::ThreadId> {
self.threads.lock().unwrap().clone()
}
pub fn assert_one_foreign_call(&self) {
let threads = self.threads();
assert_eq!(threads.len(), 1, "{threads:?}");
assert_ne!(threads[0], std::thread::current().id());
}
}
impl ostrya::Verifier for ThreadRecorder {
fn metadata_key(&self) -> &str {
self.key
}
fn verify(
&self,
_data: &[u8],
signatures: &[Vec<u8>],
) -> ostrya::sign::Result<ostrya::VerifyOutcome> {
self.threads
.lock()
.unwrap()
.push(std::thread::current().id());
let mut outcome = ostrya::VerifyOutcome::default();
outcome.valid = !signatures.is_empty();
Ok(outcome)
}
}