feat(sync-only): add support for removing async runtime dependency altogether (#56)

This commit is contained in:
Kat Marchán 2023-09-11 12:15:16 -07:00 committed by GitHub
parent 2c98f08a98
commit 6062226789
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 190 additions and 33 deletions

View File

@ -31,7 +31,7 @@ tokio = { version = "1.12.0", features = [
"fs",
"io-util",
"macros",
"rt"
"rt",
], optional = true }
tokio-stream = { version = "0.1.7", features = ["io-util"], optional = true }
walkdir = "2.3.2"
@ -49,7 +49,7 @@ tokio = { version = "1.12.0", features = [
"macros",
"rt",
"rt-multi-thread",
]}
] }
[[bench]]
name = "benchmarks"

View File

@ -38,7 +38,11 @@ Minimum supported Rust version is `1.43.0`.
## Features
- First-class async support, using either [`async-std`](https://crates.io/crates/async-std) or [`tokio`](https://crates.io/crates/tokio) as its runtime. Sync APIs are available but secondary
- First-class async support, using either
[`async-std`](https://crates.io/crates/async-std) or
[`tokio`](https://crates.io/crates/tokio) as its runtime. Sync APIs are
available but secondary. You can also use sync APIs only and remove the
async runtime dependency.
- `std::fs`-style API
- Extraction by key or by content address (shasum, etc)
- [Subresource Integrity](#integrity) web standard support
@ -56,11 +60,20 @@ Minimum supported Rust version is `1.43.0`.
- [`miette`](https://crates.io/crates/miette) integration for detailed, helpful error reporting.
- Punches nazis
`async-std` is the default async runtime. To use `tokio` instead, turn off default features and enable the `tokio-runtime` feature, like this:
`async-std` is the default async runtime. To use `tokio` instead, turn off
default features and enable the `tokio-runtime` feature, like this:
```toml
[dependencies]
cacache = { version = "*", default-features = false, features = ["tokio-runtime"] }
cacache = { version = "*", default-features = false, features = ["tokio-runtime", "mmap"] }
```
You can also remove async APIs altogether, including removing async runtime
dependency:
```toml
[dependencies]
cacache = { version = "*", default-features = false, features = ["mmap"] }
```
Experimental support for symlinking to existing files is provided via the
@ -68,9 +81,16 @@ Experimental support for symlinking to existing files is provided via the
## Contributing
The cacache team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear.
The cacache team enthusiastically welcomes contributions and project
participation! There's a bunch of things you can do if you want to contribute!
The [Contributor Guide](CONTRIBUTING.md) has all the information you need for
everything from reporting bugs to contributing entire new features. Please
don't hesitate to jump in if you'd like to, or even ask us questions if
something isn't clear.
All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other.
All participants and maintainers in this project are expected to follow [Code
of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each
other.
Happy hacking!

View File

@ -62,6 +62,7 @@ fn baseline_read_many_sync(c: &mut Criterion) {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn baseline_read_async(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("test_file");
@ -74,6 +75,7 @@ fn baseline_read_async(c: &mut Criterion) {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn baseline_read_many_async(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let paths: Vec<_> = (0..)
@ -188,6 +190,7 @@ fn read_hash_sync_big_data_xxh3(c: &mut Criterion) {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn read_hash_many_async(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path().to_owned();
@ -209,6 +212,7 @@ fn read_hash_many_async(c: &mut Criterion) {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn read_hash_async(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path().to_owned();
@ -219,6 +223,7 @@ fn read_hash_async(c: &mut Criterion) {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn read_async(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path().to_owned();
@ -229,6 +234,7 @@ fn read_async(c: &mut Criterion) {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn read_hash_async_big_data(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path().to_owned();
@ -271,6 +277,8 @@ fn write_hash_xxh3(c: &mut Criterion) {
})
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn write_hash_async(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path().to_owned();
@ -285,6 +293,7 @@ fn write_hash_async(c: &mut Criterion) {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn write_hash_async_xxh3(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path().to_owned();
@ -316,6 +325,7 @@ fn create_tmpfile(tmp: &tempfile::TempDir, buf: &[u8]) -> PathBuf {
}
#[cfg(feature = "link_to")]
#[cfg(any(feature = "async-std", feature = "tokio"))]
fn link_to_async(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let target = create_tmpfile(&tmp, b"hello world");
@ -338,7 +348,7 @@ fn link_to_async(c: &mut Criterion) {
});
}
#[cfg(feature = "link_to")]
#[cfg(all(feature = "link_to", any(feature = "async-std", feature = "tokio")))]
fn link_to_hash_async(c: &mut Criterion) {
let tmp = tempfile::tempdir().unwrap();
let target = create_tmpfile(&tmp, b"hello world");
@ -384,35 +394,55 @@ criterion_group!(
benches,
baseline_read_sync,
baseline_read_many_sync,
baseline_read_async,
baseline_read_many_async,
read_hash_async,
read_hash_many_async,
read_async,
write_hash,
write_hash_xxh3,
write_hash_async,
write_hash_async_xxh3,
read_hash_sync,
read_hash_sync_xxh3,
read_hash_many_sync,
read_hash_many_sync_xxh3,
read_sync,
read_hash_async_big_data,
read_hash_sync_big_data,
read_hash_sync_big_data_xxh3,
);
#[cfg(feature = "link_to")]
#[cfg(any(feature = "async-std", feature = "tokio"))]
criterion_group!(
link_to_benches,
link_to_async,
link_to_hash_async,
link_to_sync,
link_to_hash_sync
benches_async,
baseline_read_async,
baseline_read_many_async,
read_hash_async,
read_hash_many_async,
read_async,
write_hash_async,
write_hash_async_xxh3,
read_hash_async_big_data,
);
#[cfg(all(feature = "link_to", any(feature = "async-std", feature = "tokio")))]
criterion_group!(link_to_benches_async, link_to_async, link_to_hash_async,);
#[cfg(feature = "link_to")]
criterion_group!(link_to_benches, link_to_sync, link_to_hash_sync);
#[cfg(all(
feature = "link_to",
not(any(feature = "async-std", feature = "tokio"))
))]
criterion_main!(benches, link_to_benches);
#[cfg(not(feature = "link_to"))]
#[cfg(all(
not(feature = "link_to"),
any(feature = "async-std", feature = "tokio")
))]
criterion_main!(benches, benches_async);
#[cfg(all(feature = "link_to", any(feature = "async-std", feature = "tokio")))]
criterion_main!(
benches,
benches_async,
link_to_benches,
link_to_benches_async
);
#[cfg(all(
not(feature = "link_to"),
not(any(feature = "async-std", feature = "tokio"))
))]
criterion_main!(benches);

View File

@ -121,8 +121,8 @@ pub async fn create_named_tempfile(tmp_path: std::path::PathBuf) -> crate::Resul
#[inline]
pub async fn create_named_tempfile(tmp_path: std::path::PathBuf) -> crate::Result<NamedTempFile> {
let cloned = tmp_path.clone();
Ok(spawn_blocking(|| NamedTempFile::new_in(tmp_path))
spawn_blocking(|| NamedTempFile::new_in(tmp_path))
.await
.unwrap()
.with_context(|| format!("Failed to create a temp file at {}", cloned.display()))?)
.with_context(|| format!("Failed to create a temp file at {}", cloned.display()))
}

View File

@ -2,9 +2,12 @@ use ssri::{Algorithm, Integrity, IntegrityOpts};
use std::fs::DirBuilder;
use std::fs::File;
use std::path::{Path, PathBuf};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::pin::Pin;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::task::{Context, Poll};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::AsyncRead;
use crate::content::path;
use crate::errors::{IoErrorExt, Result};
@ -103,6 +106,7 @@ impl std::io::Read for ToLinker {
/// An `AsyncRead`-like type that calculates the integrity of a file as it is
/// read. When the linker is committed, a symlink is created from the cache to
/// the target file using the integrity computed from the file's contents.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub struct AsyncToLinker {
/// The path to the target file that will be symlinked from the cache.
target: PathBuf,
@ -114,6 +118,7 @@ pub struct AsyncToLinker {
builder: IntegrityOpts,
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncRead for AsyncToLinker {
#[cfg(feature = "async-std")]
fn poll_read(
@ -143,6 +148,7 @@ impl AsyncRead for AsyncToLinker {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncToLinker {
pub async fn new(cache: &Path, algo: Algorithm, target: &Path) -> Result<Self> {
let file = crate::async_lib::File::open(target)
@ -216,6 +222,7 @@ mod tests {
assert_eq!(std::fs::read(cpath).unwrap(), b"hello world");
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn basic_async_link() {
let tmp = tempfile::tempdir().unwrap();

View File

@ -1,7 +1,9 @@
use std::fs::{self, File};
use std::io::Read;
use std::path::Path;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::pin::Pin;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::task::{Context, Poll};
#[cfg(feature = "async-std")]
@ -11,6 +13,7 @@ use tokio::io::AsyncReadExt;
use ssri::{Algorithm, Integrity, IntegrityChecker};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::AsyncRead;
use crate::content::path;
use crate::errors::{IoErrorExt, Result};
@ -34,11 +37,13 @@ impl Reader {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub struct AsyncReader {
fd: crate::async_lib::File,
checker: IntegrityChecker,
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncRead for AsyncReader {
#[cfg(feature = "async-std")]
fn poll_read(
@ -68,6 +73,7 @@ impl AsyncRead for AsyncReader {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncReader {
pub fn check(self) -> Result<Algorithm> {
Ok(self.checker.result()?)
@ -87,6 +93,7 @@ pub fn open(cache: &Path, sri: Integrity) -> Result<Reader> {
})
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn open_async(cache: &Path, sri: Integrity) -> Result<AsyncReader> {
let cpath = path::content_path(cache, &sri);
Ok(AsyncReader {
@ -112,6 +119,7 @@ pub fn read(cache: &Path, sri: &Integrity) -> Result<Vec<u8>> {
Ok(ret)
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn read_async<'a>(cache: &'a Path, sri: &'a Integrity) -> Result<Vec<u8>> {
let cpath = path::content_path(cache, sri);
let ret = crate::async_lib::read(&cpath).await.with_context(|| {
@ -158,6 +166,7 @@ pub fn copy(cache: &Path, sri: &Integrity, to: &Path) -> Result<u64> {
Ok(size as u64)
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy_unchecked_async<'a>(
cache: &'a Path,
sri: &'a Integrity,
@ -176,6 +185,7 @@ pub async fn copy_unchecked_async<'a>(
Ok(())
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy_async<'a>(cache: &'a Path, sri: &'a Integrity, to: &'a Path) -> Result<u64> {
copy_unchecked_async(cache, sri, to).await?;
let mut reader = open_async(cache, sri.clone()).await?;
@ -230,6 +240,7 @@ pub fn hard_link(cache: &Path, sri: &Integrity, to: &Path) -> Result<()> {
Ok(())
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn hard_link_async(cache: &Path, sri: &Integrity, to: &Path) -> Result<()> {
hard_link_unchecked(cache, sri, to)?;
let mut reader = open_async(cache, sri.clone()).await?;
@ -259,6 +270,7 @@ pub fn has_content(cache: &Path, sri: &Integrity) -> Option<Integrity> {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn has_content_async(cache: &Path, sri: &Integrity) -> Option<Integrity> {
if crate::async_lib::metadata(path::content_path(cache, sri))
.await

View File

@ -16,6 +16,7 @@ pub fn rm(cache: &Path, sri: &Integrity) -> Result<()> {
Ok(())
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn rm_async(cache: &Path, sri: &Integrity) -> Result<()> {
crate::async_lib::remove_file(path::content_path(cache, sri))
.await

View File

@ -1,16 +1,21 @@
use std::fs::DirBuilder;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::pin::Pin;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::sync::Mutex;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::task::{Context, Poll};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use futures::prelude::*;
#[cfg(feature = "mmap")]
use memmap2::MmapMut;
use ssri::{Algorithm, Integrity, IntegrityOpts};
use tempfile::NamedTempFile;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::{AsyncWrite, JoinHandle};
use crate::content::path;
use crate::errors::{IoErrorExt, Result};
@ -122,13 +127,16 @@ impl Write for Writer {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub struct AsyncWriter(Mutex<State>);
#[cfg(any(feature = "async-std", feature = "tokio"))]
enum State {
Idle(Option<Inner>),
Busy(JoinHandle<State>),
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
struct Inner {
cache: PathBuf,
builder: IntegrityOpts,
@ -138,11 +146,13 @@ struct Inner {
last_op: Option<Operation>,
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
enum Operation {
Write(std::io::Result<usize>),
Flush(std::io::Result<()>),
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncWriter {
#[allow(clippy::new_ret_no_self)]
#[allow(clippy::needless_lifetimes)]
@ -252,6 +262,7 @@ impl AsyncWriter {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncWrite for AsyncWriter {
fn poll_write(
self: Pin<&mut Self>,
@ -374,6 +385,7 @@ impl AsyncWrite for AsyncWriter {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncWriter {
#[inline]
fn poll_close_impl(
@ -459,6 +471,7 @@ fn make_mmap(_: &mut NamedTempFile, _: Option<usize>) -> Result<Option<MmapMut>>
#[cfg(test)]
mod tests {
use super::*;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::AsyncWriteExt;
use tempfile;
@ -481,6 +494,7 @@ mod tests {
);
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn basic_async_write() {
let tmp = tempfile::tempdir().unwrap();

View File

@ -1,10 +1,13 @@
//! Functions for reading from cache.
use std::path::Path;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::pin::Pin;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::task::{Context as TaskContext, Poll};
use ssri::{Algorithm, Integrity};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::AsyncRead;
use crate::content::read;
use crate::errors::{Error, Result};
@ -18,10 +21,12 @@ use crate::index::{self, Metadata};
///
/// Make sure to call `.check()` when done reading to verify that the
/// extracted data passes integrity verification.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub struct Reader {
reader: read::AsyncReader,
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncRead for Reader {
#[cfg(feature = "async-std")]
fn poll_read(
@ -42,6 +47,7 @@ impl AsyncRead for Reader {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl Reader {
/// Checks that data read from disk passes integrity checks. Returns the
/// algorithm that was used verified the data. Should be called only after
@ -145,6 +151,7 @@ impl Reader {
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn read<P, K>(cache: P, key: K) -> Result<Vec<u8>>
where
P: AsRef<Path>,
@ -175,6 +182,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn read_hash<P>(cache: P, sri: &Integrity) -> Result<Vec<u8>>
where
P: AsRef<Path>,
@ -199,6 +207,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy<P, K, Q>(cache: P, key: K, to: Q) -> Result<u64>
where
P: AsRef<Path>,
@ -232,6 +241,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy_unchecked<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
P: AsRef<Path>,
@ -266,6 +276,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy_hash<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<u64>
where
P: AsRef<Path>,
@ -292,6 +303,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn copy_hash_unchecked<P, Q>(cache: P, sri: &Integrity, to: Q) -> Result<()>
where
P: AsRef<Path>,
@ -301,6 +313,7 @@ where
}
/// Hard links a cache entry by key to a specified location.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn hard_link<P, K, Q>(cache: P, key: K, to: Q) -> Result<()>
where
P: AsRef<Path>,
@ -322,6 +335,7 @@ where
/// Note that the existence of a metadata entry is not a guarantee that the
/// underlying data exists, since they are stored and managed independently.
/// To verify that the underlying associated data exists, use `exists()`.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn metadata<P, K>(cache: P, key: K) -> Result<Option<Metadata>>
where
P: AsRef<Path>,
@ -331,6 +345,7 @@ where
}
/// Returns true if the given hash exists in the cache.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn exists<P: AsRef<Path>>(cache: P, sri: &Integrity) -> bool {
read::has_content_async(cache.as_ref(), sri).await.is_some()
}
@ -669,6 +684,7 @@ pub fn exists_sync<P: AsRef<Path>>(cache: P, sri: &Integrity) -> bool {
#[cfg(test)]
mod tests {
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::AsyncReadExt;
use std::fs;
@ -677,6 +693,7 @@ mod tests {
#[cfg(feature = "tokio")]
use tokio::test as async_test;
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_open() {
let tmp = tempfile::tempdir().unwrap();
@ -690,6 +707,7 @@ mod tests {
assert_eq!(str, String::from("hello world"));
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_open_hash() {
let tmp = tempfile::tempdir().unwrap();
@ -731,6 +749,7 @@ mod tests {
assert_eq!(str, String::from("hello world"));
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_read() {
let tmp = tempfile::tempdir().unwrap();
@ -741,6 +760,7 @@ mod tests {
assert_eq!(data, b"hello world");
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_read_hash() {
let tmp = tempfile::tempdir().unwrap();
@ -771,6 +791,7 @@ mod tests {
assert_eq!(data, b"hello world");
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_copy() {
let tmp = tempfile::tempdir().unwrap();
@ -783,6 +804,7 @@ mod tests {
assert_eq!(data, b"hello world");
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_copy_hash() {
let tmp = tempfile::tempdir().unwrap();

View File

@ -9,6 +9,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use digest::Digest;
use either::{Left, Right};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use futures::stream::StreamExt;
use serde_derive::{Deserialize, Serialize};
use serde_json::Value;
@ -17,6 +18,7 @@ use sha2::Sha256;
use ssri::Integrity;
use walkdir::WalkDir;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::{AsyncBufReadExt, AsyncWriteExt};
use crate::errors::{IoErrorExt, Result};
use crate::put::WriteOpts;
@ -100,6 +102,7 @@ pub fn insert(cache: &Path, key: &str, opts: WriteOpts) -> Result<Integrity> {
.unwrap())
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
/// Asynchronous raw insertion into the cache index.
pub async fn insert_async<'a>(cache: &'a Path, key: &'a str, opts: WriteOpts) -> Result<Integrity> {
let bucket = bucket_path(cache, key);
@ -171,6 +174,7 @@ pub fn find(cache: &Path, key: &str) -> Result<Option<Metadata>> {
}))
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
/// Asynchronous raw index Metadata access.
pub async fn find_async(cache: &Path, key: &str) -> Result<Option<Metadata>> {
let bucket = bucket_path(cache, key);
@ -219,6 +223,7 @@ pub fn delete(cache: &Path, key: &str) -> Result<()> {
.map(|_| ())
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
/// Asynchronously deletes an index entry, without deleting the actual cache
/// data entry.
pub async fn delete_async(cache: &Path, key: &str) -> Result<()> {
@ -325,7 +330,7 @@ fn bucket_entries(bucket: &Path) -> std::io::Result<Vec<SerializableMetadata>> {
.map(|file| {
BufReader::new(file)
.lines()
.filter_map(std::result::Result::ok)
.map_while(std::result::Result::ok)
.filter_map(|entry| {
let entry_str = match entry.split('\t').collect::<Vec<&str>>()[..] {
[hash, entry_str] if hash_entry(entry_str) == hash => entry_str,
@ -345,6 +350,7 @@ fn bucket_entries(bucket: &Path) -> std::io::Result<Vec<SerializableMetadata>> {
})
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
async fn bucket_entries_async(bucket: &Path) -> std::io::Result<Vec<SerializableMetadata>> {
let file_result = crate::async_lib::File::open(bucket).await;
let file = if let Err(err) = file_result {
@ -406,6 +412,7 @@ mod tests {
assert_eq!(entry, MOCK_ENTRY);
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn insert_async_basic() {
let tmp = tempfile::tempdir().unwrap();
@ -462,6 +469,7 @@ mod tests {
assert_eq!(find(&dir, "hello").unwrap(), None);
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn delete_async_basic() {
let tmp = tempfile::tempdir().unwrap();
@ -498,6 +506,7 @@ mod tests {
);
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn round_trip_async() {
let tmp = tempfile::tempdir().unwrap();

View File

@ -113,6 +113,15 @@
//! once. If you're only reading and writing one thing at a time across your
//! application, you probably want to use these instead.
//!
//! If you wish to _only_ use sync APIs and not pull in an async runtime, you
//! can disable default features:
//!
//! ```toml
//! # Cargo.toml
//! [dependencies]
//! cacache = { version = "X.Y.Z", default-features = false, features = ["mmap"] }
//! ```
//!
//! ```no_run
//! fn main() -> cacache::Result<()> {
//! cacache::write_sync("./my-cache", "key", b"my-data").unwrap();
@ -124,10 +133,10 @@
//!
//! ### Linking to existing files
//!
//! The `link_to` feature enables an additional set of APIs for adding existing
//! files into the cache via symlinks, without having to duplicate their data.
//! Once the cache links to them, these files can be accessed by key just like
//! other cached data, with the same integrity checking.
//! The `link_to` feature enables an additional set of APIs for adding
//! existing files into the cache via symlinks, without having to duplicate
//! their data. Once the cache links to them, these files can be accessed by
//! key just like other cached data, with the same integrity checking.
//!
//! The `link_to` methods are available in both async and sync variants, using
//! the same suffixes as the other APIs.
@ -144,15 +153,13 @@
//! ```
#![warn(missing_docs)]
#[cfg(not(any(feature = "async-std", feature = "tokio-runtime")))]
compile_error!("Either feature \"async-std\" or \"tokio-runtime\" must be enabled for this crate.");
#[cfg(all(feature = "async-std", feature = "tokio-runtime"))]
compile_error!("Only either feature \"async-std\" or \"tokio-runtime\" must be enabled for this crate, not both.");
pub use serde_json::Value;
pub use ssri::{Algorithm, Integrity};
#[cfg(any(feature = "async-std", feature = "tokio"))]
mod async_lib;
mod content;

View File

@ -1,3 +1,4 @@
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::AsyncRead;
use crate::content::linkto;
use crate::errors::{Error, IoErrorExt, Result};
@ -5,7 +6,9 @@ use crate::{index, WriteOpts};
use ssri::{Algorithm, Integrity};
use std::io::Read;
use std::path::{Path, PathBuf};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::pin::Pin;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::task::{Context as TaskContext, Poll};
#[cfg(feature = "async-std")]
@ -30,6 +33,7 @@ const PROBE_SIZE: usize = 8;
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn link_to<P, K, T>(cache: P, key: K, target: T) -> Result<Integrity>
where
P: AsRef<Path>,
@ -53,6 +57,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn link_to_hash<P, T>(cache: P, target: T) -> Result<Integrity>
where
P: AsRef<Path>,
@ -108,6 +113,7 @@ where
/// `SyncToLinker` instances.
impl WriteOpts {
/// Opens the target file handle for reading, returning a ToLinker instance.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn link_to<P, K, T>(self, cache: P, key: K, target: T) -> Result<ToLinker>
where
P: AsRef<Path>,
@ -138,6 +144,7 @@ impl WriteOpts {
/// Opens the target file handle for reading, without a key, returning a
/// ToLinker instance.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn link_to_hash<P, T>(self, cache: P, target: T) -> Result<ToLinker>
where
P: AsRef<Path>,
@ -213,6 +220,7 @@ impl WriteOpts {
///
/// Make sure to call `.commit()` when done reading to actually add the file to
/// the cache.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub struct ToLinker {
cache: PathBuf,
key: Option<String>,
@ -221,6 +229,7 @@ pub struct ToLinker {
opts: WriteOpts,
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncRead for ToLinker {
#[cfg(feature = "async-std")]
fn poll_read(
@ -253,6 +262,7 @@ fn filesize(target: &Path) -> Result<usize> {
.len() as usize)
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl ToLinker {
/// Creates a new asynchronous readable file handle into the cache.
pub async fn open<P, K, T>(cache: P, key: K, target: T) -> Result<Self>
@ -499,6 +509,7 @@ mod tests {
target
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_link() {
let tmp = tempfile::tempdir().unwrap();
@ -512,6 +523,7 @@ mod tests {
assert_eq!(buf, b"hello world");
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_link_to_hash() {
let tmp = tempfile::tempdir().unwrap();
@ -551,6 +563,7 @@ mod tests {
assert_eq!(buf, b"hello world");
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_open() {
let tmp = tempfile::tempdir().unwrap();
@ -569,6 +582,7 @@ mod tests {
assert_eq!(buf, b"hello world");
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_open_hash() {
let tmp = tempfile::tempdir().unwrap();

View File

@ -1,16 +1,19 @@
//! Functions for writing to cache.
use std::io::prelude::*;
use std::path::{Path, PathBuf};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::pin::Pin;
use serde_json::Value;
use ssri::{Algorithm, Integrity};
#[cfg(any(feature = "async-std", feature = "tokio"))]
use crate::async_lib::{AsyncWrite, AsyncWriteExt};
use crate::content::write;
use crate::errors::{Error, IoErrorExt, Result};
use crate::index;
#[cfg(any(feature = "async-std", feature = "tokio"))]
use std::task::{Context as TaskContext, Poll};
/// Writes `data` to the `cache`, indexing it under `key`.
@ -25,6 +28,7 @@ use std::task::{Context as TaskContext, Poll};
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn write<P, D, K>(cache: P, key: K, data: D) -> Result<Integrity>
where
P: AsRef<Path>,
@ -47,6 +51,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn write_with_algo<P, D, K>(
algo: Algorithm,
cache: P,
@ -71,6 +76,7 @@ where
}
inner(algo, cache.as_ref(), key.as_ref(), data.as_ref()).await
}
/// Writes `data` to the `cache`, skipping associating an index key with it.
///
/// ## Example
@ -83,6 +89,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn write_hash<P, D>(cache: P, data: D) -> Result<Integrity>
where
P: AsRef<Path>,
@ -104,6 +111,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn write_hash_with_algo<P, D>(algo: Algorithm, cache: P, data: D) -> Result<Integrity>
where
P: AsRef<Path>,
@ -124,6 +132,7 @@ where
inner(algo, cache.as_ref(), data.as_ref()).await
}
/// A reference to an open file writing to the cache.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub struct Writer {
cache: PathBuf,
key: Option<String>,
@ -132,6 +141,7 @@ pub struct Writer {
opts: WriteOpts,
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl AsyncWrite for Writer {
fn poll_write(
mut self: Pin<&mut Self>,
@ -161,6 +171,7 @@ impl AsyncWrite for Writer {
}
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
impl Writer {
/// Creates a new writable file handle into the cache.
///
@ -361,6 +372,7 @@ impl WriteOpts {
}
/// Opens the file handle for writing, returning an Writer instance.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn open<P, K>(self, cache: P, key: K) -> Result<Writer>
where
P: AsRef<Path>,
@ -384,6 +396,7 @@ impl WriteOpts {
}
/// Opens the file handle for writing, without a key returning an Writer instance.
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn open_hash<P>(self, cache: P) -> Result<Writer>
where
P: AsRef<Path>,
@ -597,6 +610,7 @@ mod tests {
#[cfg(feature = "tokio")]
use tokio::test as async_test;
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn round_trip() {
let tmp = tempfile::tempdir().unwrap();
@ -629,6 +643,7 @@ mod tests {
assert_eq!(result, original, "we did not read back what we wrote");
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn hash_write_async() {
let tmp = tempfile::tempdir().unwrap();

View File

@ -31,6 +31,7 @@ use crate::index;
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn remove<P, K>(cache: P, key: K) -> Result<()>
where
P: AsRef<Path>,
@ -63,6 +64,7 @@ where
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn remove_hash<P: AsRef<Path>>(cache: P, sri: &Integrity) -> Result<()> {
rm::rm_async(cache.as_ref(), sri).await
}
@ -89,6 +91,7 @@ pub async fn remove_hash<P: AsRef<Path>>(cache: P, sri: &Integrity) -> Result<()
/// Ok(())
/// }
/// ```
#[cfg(any(feature = "async-std", feature = "tokio"))]
pub async fn clear<P: AsRef<Path>>(cache: P) -> Result<()> {
async fn inner(cache: &Path) -> Result<()> {
for entry in cache
@ -213,6 +216,7 @@ mod tests {
#[cfg(feature = "tokio")]
use tokio::test as async_test;
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_remove() {
futures::executor::block_on(async {
@ -230,6 +234,7 @@ mod tests {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_remove_data() {
futures::executor::block_on(async {
@ -247,6 +252,7 @@ mod tests {
});
}
#[cfg(any(feature = "async-std", feature = "tokio"))]
#[async_test]
async fn test_clear() {
futures::executor::block_on(async {