use std::{
collections::HashMap,
fmt,
fs::{self, File, OpenOptions},
future::Future,
io::{self, Write},
path::{Path, PathBuf},
pin::Pin,
sync::{Arc, Mutex, PoisonError, Weak},
};
use alloy_primitives::{Address, hex, keccak256};
use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
use crate::{Error, Result, error::StoreError, types::EscrowEnvironment};
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = io::Result<T>> + Send + 'a>>;
pub trait Store: Send + Sync + 'static {
fn load<'a>(&'a self, key: &'a str) -> StoreFuture<'a, Option<Vec<u8>>>;
fn save<'a>(&'a self, key: &'a str, value: &'a [u8]) -> StoreFuture<'a, ()>;
fn delete<'a>(&'a self, key: &'a str) -> StoreFuture<'a, ()>;
}
#[derive(Clone)]
pub struct Journal {
inner: Arc<JournalInner>,
}
struct JournalInner {
backend: Box<dyn Store>,
locks: KeyedLocks,
}
impl Journal {
pub fn new(backend: impl Store) -> Self {
Self {
inner: Arc::new(JournalInner {
backend: Box::new(backend),
locks: KeyedLocks::default(),
}),
}
}
}
impl Journal {
pub(crate) async fn lock(&self, key: &str) -> KeyGuard {
self.inner.locks.lock(key).await
}
pub(crate) async fn load(&self, key: &str) -> io::Result<Option<Vec<u8>>> {
self.inner.backend.load(key).await
}
pub(crate) async fn save(&self, key: &str, value: &[u8]) -> io::Result<()> {
self.inner.backend.save(key, value).await
}
pub(crate) async fn delete(&self, key: &str) -> io::Result<()> {
self.inner.backend.delete(key).await
}
}
impl<S: Store> From<S> for Journal {
fn from(backend: S) -> Self {
Self::new(backend)
}
}
impl fmt::Debug for Journal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Journal").finish_non_exhaustive()
}
}
pub(crate) fn scoped_key(environment: EscrowEnvironment, signer: Address, record: &str) -> String {
format!("{environment}/{signer:#x}/{record}")
}
pub(crate) type KeyGuard = OwnedMutexGuard<()>;
#[derive(Default)]
struct KeyedLocks {
locks: Mutex<HashMap<String, Weak<AsyncMutex<()>>>>,
}
impl KeyedLocks {
async fn lock(&self, key: &str) -> KeyGuard {
let lock = {
let mut locks = self.locks.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(lock) = locks.get(key).and_then(Weak::upgrade) {
lock
} else {
locks.retain(|_, lock| lock.strong_count() > 0);
let lock = Arc::new(AsyncMutex::new(()));
locks.insert(key.to_owned(), Arc::downgrade(&lock));
lock
}
};
lock.lock_owned().await
}
}
#[derive(Debug, Default)]
pub struct MemoryStore {
values: Mutex<HashMap<String, Vec<u8>>>,
}
impl MemoryStore {
pub fn new() -> Self {
Self::default()
}
fn values(&self) -> std::sync::MutexGuard<'_, HashMap<String, Vec<u8>>> {
self.values.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Store for MemoryStore {
fn load<'a>(&'a self, key: &'a str) -> StoreFuture<'a, Option<Vec<u8>>> {
let value = self.values().get(key).cloned();
Box::pin(std::future::ready(Ok(value)))
}
fn save<'a>(&'a self, key: &'a str, value: &'a [u8]) -> StoreFuture<'a, ()> {
self.values().insert(key.to_owned(), value.to_vec());
Box::pin(std::future::ready(Ok(())))
}
fn delete<'a>(&'a self, key: &'a str) -> StoreFuture<'a, ()> {
self.values().remove(key);
Box::pin(std::future::ready(Ok(())))
}
}
pub struct FileStore {
inner: Arc<FileInner>,
gate: Arc<AsyncMutex<()>>,
}
struct FileInner {
dir: PathBuf,
_lock: File,
#[cfg(test)]
before_write: Mutex<Option<Box<dyn FnOnce() + Send>>>,
}
impl FileStore {
pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
let dir = dir.as_ref().to_path_buf();
let lock_path = dir.join(".lock");
let store_error = |source| {
Error::Store(Box::new(StoreError::new(lock_path.display().to_string(), false, source)))
};
fs::create_dir_all(&dir).map_err(store_error)?;
let lock = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&lock_path)
.map_err(store_error)?;
lock.try_lock().map_err(|error| store_error(io::Error::from(error)))?;
Ok(Self {
inner: Arc::new(FileInner {
dir,
_lock: lock,
#[cfg(test)]
before_write: Mutex::new(None),
}),
gate: Arc::new(AsyncMutex::new(())),
})
}
async fn run<T: Send + 'static>(
&self,
operation: impl FnOnce(&FileInner) -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
let turn = Arc::clone(&self.gate).lock_owned().await;
let inner = Arc::clone(&self.inner);
tokio::task::spawn_blocking(move || {
let _turn = turn;
operation(&inner)
})
.await
.map_err(io::Error::other)?
}
}
impl FileInner {
fn path(&self, key: &str) -> PathBuf {
self.dir.join(hex::encode(keccak256(key.as_bytes())))
}
fn load(&self, key: &str) -> io::Result<Option<Vec<u8>>> {
match fs::read(self.path(key)) {
Ok(value) => Ok(Some(value)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}
fn save(&self, key: &str, value: &[u8]) -> io::Result<()> {
#[cfg(test)]
if let Some(hook) = self.before_write.lock().unwrap_or_else(PoisonError::into_inner).take()
{
hook();
}
let path = self.path(key);
let temporary = path.with_extension("tmp");
let mut file = File::create(&temporary)?;
file.write_all(value)?;
file.sync_all()?;
drop(file);
fs::rename(&temporary, &path)?;
self.sync_dir()
}
fn delete(&self, key: &str) -> io::Result<()> {
match fs::remove_file(self.path(key)) {
Ok(()) => self.sync_dir(),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
fn sync_dir(&self) -> io::Result<()> {
#[cfg(unix)]
File::open(&self.dir)?.sync_all()?;
Ok(())
}
}
impl Store for FileStore {
fn load<'a>(&'a self, key: &'a str) -> StoreFuture<'a, Option<Vec<u8>>> {
let key = key.to_owned();
Box::pin(self.run(move |inner| inner.load(&key)))
}
fn save<'a>(&'a self, key: &'a str, value: &'a [u8]) -> StoreFuture<'a, ()> {
let (key, value) = (key.to_owned(), value.to_vec());
Box::pin(self.run(move |inner| inner.save(&key, &value)))
}
fn delete<'a>(&'a self, key: &'a str) -> StoreFuture<'a, ()> {
let key = key.to_owned();
Box::pin(self.run(move |inner| inner.delete(&key)))
}
}
impl fmt::Debug for FileStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FileStore").field("dir", &self.inner.dir).finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests;