use std::collections::BTreeSet;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::SystemTime;
use opendal::Operator;
use crate::error::{Error, Missing, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Need {
Read,
Write,
Delete,
Stat,
List,
CreateIfAbsent,
AtomicReplace,
MaxValueSize(u64),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Needs(Vec<Need>);
impl Needs {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, need: Need) -> Self {
if !self.0.contains(&need) {
self.0.push(need);
}
self
}
pub(crate) fn contains(&self, need: Need) -> bool {
self.0.contains(&need)
}
pub(crate) fn iter(&self) -> impl Iterator<Item = Need> + '_ {
self.0.iter().copied()
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Config {
Memory,
Fs {
root: PathBuf,
atomic_write_dir: Option<PathBuf>,
},
Faulty {
inner: Box<Config>,
faults: Faults,
},
Masked {
inner: Box<Config>,
without: Vec<Need>,
},
}
#[derive(Debug, Clone, Default)]
pub struct Faults {
allow: Option<usize>,
interrupt: bool,
}
impl Faults {
pub fn none() -> Self {
Self::default()
}
pub fn fail_writes_after(n: usize) -> Self {
Self {
allow: Some(n),
interrupt: false,
}
}
pub fn interrupt_writes_after(n: usize) -> Self {
Self {
allow: Some(n),
interrupt: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Entry {
pub key: String,
pub len: u64,
pub modified: Option<SystemTime>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Page {
pub entries: Vec<Entry>,
pub next: Option<String>,
}
#[derive(Debug)]
pub struct Store {
op: Operator,
declared: Needs,
faults: Faults,
writes: AtomicUsize,
}
impl Store {
pub async fn open(config: Config, needs: Needs) -> Result<Store> {
let (config, masked, faults) = unmask(config);
let (op, name) = match &config {
Config::Memory => (
Operator::new(opendal::services::Memory::default()),
"memory",
),
Config::Fs {
root,
atomic_write_dir,
} => {
let mut b = opendal::services::Fs::default().root(&root.to_string_lossy());
if let Some(dir) = atomic_write_dir {
b = b.atomic_write_dir(&dir.to_string_lossy());
}
(Operator::new(b), "fs")
}
Config::Masked { .. } | Config::Faulty { .. } => {
unreachable!("unmask removes every wrapper layer")
}
};
let op = op.map_err(|e| Error::Backend(e.to_string()))?;
let cap = op.info().capability();
let atomic_dir_set = matches!(
&config,
Config::Fs {
atomic_write_dir: Some(_),
..
}
);
let missing: Vec<Missing> = needs
.iter()
.filter_map(|need| {
let detail = if masked.contains(&need) {
Some("masked by the test fake".to_string())
} else {
unmet(need, &cap, name, atomic_dir_set)
};
detail.map(|detail| Missing { need, detail })
})
.collect();
if !missing.is_empty() {
return Err(Error::Refused {
backend: name,
missing,
});
}
Ok(Store {
op,
declared: needs,
faults,
writes: AtomicUsize::new(0),
})
}
pub async fn read(&self, key: &str) -> Result<Vec<u8>> {
self.read_optional(key)
.await?
.ok_or_else(|| Error::NotFound(key.to_string()))
}
pub async fn replace(&self, key: &str, bytes: Vec<u8>) -> Result<()> {
let mut r = self.begin_replace(key).await?;
r.write(bytes).await?;
r.commit().await
}
pub async fn delete(&self, key: &str) -> Result<()> {
if !self.declared.contains(Need::Delete) {
return Err(Error::NotDeclared(Need::Delete));
}
self.op
.delete(key)
.await
.map_err(|e| Error::Backend(e.to_string()))
}
pub async fn stat(&self, key: &str) -> Result<Entry> {
if !self.declared.contains(Need::Stat) {
return Err(Error::NotDeclared(Need::Stat));
}
match self.op.stat(key).await {
Ok(m) if m.is_file() => Ok(Entry {
key: key.to_string(),
len: m.content_length(),
modified: m.last_modified().map(SystemTime::from),
}),
Ok(_) => Err(Error::NotFound(key.to_string())),
Err(e) if e.kind() == opendal::ErrorKind::NotFound => {
Err(Error::NotFound(key.to_string()))
}
Err(e) => Err(Error::Backend(e.to_string())),
}
}
pub async fn list(
&self,
prefix: &str,
after: Option<&str>,
limit: NonZeroUsize,
) -> Result<Page> {
for need in [Need::List, Need::Stat] {
if !self.declared.contains(need) {
return Err(Error::NotDeclared(need));
}
}
let limit = limit.get();
let dir = match prefix.rfind('/') {
Some(i) => &prefix[..=i],
None => "/",
};
let backend = |e: opendal::Error| Error::Backend(e.to_string());
let mut kept: BTreeSet<String> = BTreeSet::new();
let mut pending = vec![dir.to_string()];
while let Some(d) = pending.pop() {
let mut lister = match self.op.lister(&d).await {
Ok(l) => l,
Err(e) if e.kind() == opendal::ErrorKind::NotFound => continue,
Err(e) => return Err(backend(e)),
};
while let Some(entry) = futures_util::TryStreamExt::try_next(&mut lister)
.await
.map_err(backend)?
{
let path = entry.path();
if path == d || path == "/" {
continue;
}
if path.ends_with('/') || entry.metadata().is_dir() {
pending.push(path.to_string());
continue;
}
if !path.starts_with(prefix) || after.is_some_and(|a| path <= a) {
continue;
}
kept.insert(path.to_string());
if kept.len() > limit + 1 {
kept.pop_last();
}
}
}
let mut entries = Vec::with_capacity(limit.min(kept.len()));
let mut more = false;
for key in kept {
if entries.len() == limit {
more = true;
break;
}
match self.stat(&key).await {
Ok(e) => entries.push(e),
Err(Error::NotFound(_)) => {}
Err(e) => return Err(e),
}
}
let next = if more {
entries.last().map(|e| e.key.clone())
} else {
None
};
Ok(Page { entries, next })
}
pub async fn create_if_absent(&self, key: &str, bytes: Vec<u8>) -> Result<()> {
for need in [Need::Write, Need::CreateIfAbsent] {
if !self.declared.contains(need) {
return Err(Error::NotDeclared(need));
}
}
match self.op.write_with(key, bytes).if_not_exists(true).await {
Ok(_) => Ok(()),
Err(e)
if matches!(
e.kind(),
opendal::ErrorKind::ConditionNotMatch | opendal::ErrorKind::AlreadyExists
) =>
{
Err(Error::AlreadyExists(key.to_string()))
}
Err(e) => Err(Error::Backend(e.to_string())),
}
}
pub async fn put_record<R: Record>(&self, key: &str, record: &R) -> Result<()> {
self.replace(key, encode_record(record)?).await
}
pub async fn get_record<R: Record>(&self, key: &str) -> Result<Option<R>> {
match self.read_optional(key).await? {
Some(bytes) => decode_record(&bytes).map(Some),
None => Ok(None),
}
}
pub(crate) async fn read_optional(&self, key: &str) -> Result<Option<Vec<u8>>> {
if !self.declared.contains(Need::Read) {
return Err(Error::NotDeclared(Need::Read));
}
match self.op.read(key).await {
Ok(b) => Ok(Some(b.to_vec())),
Err(e) if e.kind() == opendal::ErrorKind::NotFound => Ok(None),
Err(e) => Err(Error::Backend(e.to_string())),
}
}
pub async fn begin_replace(&self, key: &str) -> Result<Replace> {
for need in [Need::Write, Need::AtomicReplace] {
if !self.declared.contains(need) {
return Err(Error::NotDeclared(need));
}
}
let w = self
.op
.writer(key)
.await
.map_err(|e| Error::Backend(e.to_string()))?;
let n = self.writes.fetch_add(1, Ordering::SeqCst);
let mut doomed = None;
if self.faults.allow.is_some_and(|allow| n >= allow) {
let msg = format!("write #{} to `{key}` failed", n + 1);
if !self.faults.interrupt {
return Err(Error::Injected(msg));
}
doomed = Some(msg);
}
Ok(Replace { w, doomed })
}
}
fn unmask(mut config: Config) -> (Config, Vec<Need>, Faults) {
let mut hidden = Vec::new();
let mut faults = None;
loop {
match config {
Config::Masked { inner, without } => {
hidden.extend(without);
config = *inner;
}
Config::Faulty { inner, faults: f } => {
faults.get_or_insert(f);
config = *inner;
}
plain => return (plain, hidden, faults.unwrap_or_default()),
}
}
}
pub(crate) fn encode_record<R: Record>(record: &R) -> Result<Vec<u8>> {
let envelope = serde_json::json!({
"kind": R::KIND,
"schema": R::SCHEMA,
"data": serde_json::to_value(record).map_err(|e| Error::Encode(e.to_string()))?,
});
serde_json::to_vec(&envelope).map_err(|e| Error::Encode(e.to_string()))
}
pub(crate) fn decode_record<R: Record>(bytes: &[u8]) -> Result<R> {
let mut env: serde_json::Value =
serde_json::from_slice(bytes).map_err(|e| Error::Corrupt(e.to_string()))?;
let kind = env["kind"]
.as_str()
.ok_or_else(|| Error::Corrupt("no `kind`".into()))?;
if kind != R::KIND {
return Err(Error::KindMismatch {
expected: R::KIND,
found: kind.to_string(),
});
}
let schema = env["schema"]
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.ok_or_else(|| Error::Corrupt("no `schema`".into()))?;
let mut data = env["data"].take();
if schema > R::SCHEMA {
return Err(Error::SchemaUnsupported {
kind: R::KIND,
found: schema,
expected: R::SCHEMA,
});
}
if schema < R::SCHEMA {
data = R::upgrade(schema, data)?;
return serde_json::from_value(data).map_err(|e| Error::UpgradeFailed {
kind: R::KIND,
from: schema,
expected: R::SCHEMA,
detail: e.to_string(),
});
}
serde_json::from_value(data).map_err(|e| Error::Corrupt(e.to_string()))
}
pub trait Record: serde::Serialize + serde::de::DeserializeOwned {
const KIND: &'static str;
const SCHEMA: u32;
fn upgrade(from: u32, data: serde_json::Value) -> Result<serde_json::Value> {
let _ = data;
Err(Error::SchemaUnsupported {
kind: Self::KIND,
found: from,
expected: Self::SCHEMA,
})
}
}
fn unmet(
need: Need,
cap: &opendal::Capability,
backend: &str,
atomic_dir_set: bool,
) -> Option<String> {
let lacks = |ok: bool, what: &str| {
(!ok).then(|| format!("backend `{backend}` does not advertise {what}"))
};
match need {
Need::Read => lacks(cap.read, "read"),
Need::Write => lacks(cap.write, "write"),
Need::Delete => lacks(cap.delete, "delete"),
Need::Stat => lacks(cap.stat, "stat"),
Need::List => lacks(cap.list, "list"),
Need::CreateIfAbsent => {
match lacks(cap.write_with_if_not_exists, "write_with_if_not_exists") {
Some(why) => Some(why),
None if backend == "fs" && atomic_dir_set => Some(
"fs create-if-absent is exclusive only without atomic_write_dir; with it the \
check and the rename are separate steps"
.to_string(),
),
None => None,
}
}
Need::AtomicReplace => match backend {
"fs" if atomic_dir_set => None,
"fs" => {
Some("fs writes atomically only with atomic_write_dir set; it is not".to_string())
}
"memory" => None,
other => Some(format!(
"atomic replace is not vetted for backend `{other}`"
)),
},
Need::MaxValueSize(n) => match cap.write_total_max_size {
Some(max) if (max as u64) < n => {
Some(format!("backend ceiling is {max} bytes, need {n}"))
}
_ => None,
},
}
}
pub struct Replace {
w: opendal::Writer,
doomed: Option<String>,
}
impl std::fmt::Debug for Replace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Replace").finish_non_exhaustive()
}
}
impl Replace {
pub async fn write(&mut self, bytes: Vec<u8>) -> Result<()> {
if let Some(msg) = &self.doomed {
let half = bytes[..bytes.len().div_ceil(2)].to_vec();
return self.w.write(half).await.map_err(|e| {
Error::Injected(format!("{msg} (and the partial write failed: {e})"))
});
}
self.w
.write(bytes)
.await
.map_err(|e| Error::Backend(e.to_string()))
}
pub async fn commit(mut self) -> Result<()> {
if let Some(msg) = self.doomed {
return Err(Error::Injected(msg));
}
self.w
.close()
.await
.map(|_| ())
.map_err(|e| Error::Backend(e.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn max_value_size_is_refused_only_above_the_advertised_ceiling() {
let cap = opendal::Capability {
write_total_max_size: Some(1000),
..Default::default()
};
assert!(unmet(Need::MaxValueSize(1000), &cap, "x", false).is_none());
assert!(unmet(Need::MaxValueSize(1001), &cap, "x", false).is_some());
let unlimited = opendal::Capability::default();
assert!(unmet(Need::MaxValueSize(u64::MAX), &unlimited, "x", false).is_none());
}
#[test]
fn unvetted_backend_is_refused_for_atomic_replace() {
let cap = opendal::Capability::default();
assert!(unmet(Need::AtomicReplace, &cap, "s3", true).is_some());
}
#[test]
fn nested_masks_are_all_honoured() {
let c = Config::Masked {
inner: Box::new(Config::Masked {
inner: Box::new(Config::Memory),
without: vec![Need::List],
}),
without: vec![Need::Stat],
};
let (inner, hidden, _) = unmask(c);
assert!(matches!(inner, Config::Memory));
assert_eq!(hidden, vec![Need::Stat, Need::List]);
}
}