use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::context::current_context;
use crate::error::TenancyError;
use crate::tenant::TenantId;
pub mod local;
pub mod memory;
#[cfg(feature = "redis")]
pub mod redis;
pub type Loader<'a> = Box<
dyn FnOnce() -> Pin<Box<dyn Future<Output = Result<Vec<u8>, TenancyError>> + Send + 'a>>
+ Send
+ 'a,
>;
#[async_trait]
pub trait CacheStore: Send + Sync {
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, TenancyError>;
async fn set(
&self,
key: &str,
value: Vec<u8>,
ttl: Option<Duration>,
) -> Result<(), TenancyError>;
async fn delete(&self, key: &str) -> Result<(), TenancyError>;
async fn delete_prefix(&self, prefix: &str) -> Result<(), TenancyError>;
async fn remember(
&self,
key: &str,
ttl: Option<Duration>,
loader: Loader<'_>,
) -> Result<Vec<u8>, TenancyError> {
if let Some(value) = self.get(key).await? {
return Ok(value);
}
let value = loader().await?;
self.set(key, value.clone(), ttl).await?;
Ok(value)
}
}
#[async_trait]
pub trait Storage: Send + Sync {
async fn put(&self, path: &str, data: Vec<u8>) -> Result<(), TenancyError>;
async fn get(&self, path: &str) -> Result<Vec<u8>, TenancyError>;
async fn exists(&self, path: &str) -> Result<bool, TenancyError>;
async fn delete(&self, path: &str) -> Result<(), TenancyError>;
async fn delete_prefix(&self, prefix: &str) -> Result<(), TenancyError>;
}
#[async_trait]
pub trait SessionStore: Send + Sync {
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, TenancyError>;
async fn set(&self, key: &str, value: Vec<u8>) -> Result<(), TenancyError>;
async fn delete(&self, key: &str) -> Result<(), TenancyError>;
async fn delete_prefix(&self, prefix: &str) -> Result<(), TenancyError>;
}
#[async_trait]
pub trait Encryptor: Send + Sync {
async fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>, TenancyError>;
async fn open(&self, ciphertext: &[u8]) -> Result<Vec<u8>, TenancyError>;
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TenantJob {
pub tenant_id: TenantId,
pub name: String,
pub payload: serde_json::Value,
}
#[async_trait]
pub trait JobQueue: Send + Sync {
async fn enqueue(&self, job: TenantJob) -> Result<(), TenancyError>;
}
#[derive(Clone)]
pub struct ScopedCache {
inner: Arc<dyn CacheStore>,
}
impl ScopedCache {
pub fn new(inner: Arc<dyn CacheStore>) -> Self {
Self { inner }
}
fn prefix() -> Result<String, TenancyError> {
current_context()
.map(|context| format!("{}:", context.cache_namespace()))
.ok_or(TenancyError::NotResolved)
}
}
#[async_trait]
impl CacheStore for ScopedCache {
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, TenancyError> {
let key = format!("{}{}", Self::prefix()?, key);
self.inner.get(&key).await
}
async fn set(
&self,
key: &str,
value: Vec<u8>,
ttl: Option<Duration>,
) -> Result<(), TenancyError> {
let key = format!("{}{}", Self::prefix()?, key);
self.inner.set(&key, value, ttl).await
}
async fn delete(&self, key: &str) -> Result<(), TenancyError> {
let key = format!("{}{}", Self::prefix()?, key);
self.inner.delete(&key).await
}
async fn delete_prefix(&self, prefix: &str) -> Result<(), TenancyError> {
let prefix = format!("{}{}", Self::prefix()?, prefix);
self.inner.delete_prefix(&prefix).await
}
}
#[derive(Clone)]
pub struct ScopedSession {
inner: Arc<dyn SessionStore>,
}
impl ScopedSession {
pub fn new(inner: Arc<dyn SessionStore>) -> Self {
Self { inner }
}
fn prefix() -> Result<String, TenancyError> {
current_context()
.map(|context| format!("{}:", context.session_namespace()))
.ok_or(TenancyError::NotResolved)
}
}
#[async_trait]
impl SessionStore for ScopedSession {
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, TenancyError> {
let key = format!("{}{}", Self::prefix()?, key);
self.inner.get(&key).await
}
async fn set(&self, key: &str, value: Vec<u8>) -> Result<(), TenancyError> {
let key = format!("{}{}", Self::prefix()?, key);
self.inner.set(&key, value).await
}
async fn delete(&self, key: &str) -> Result<(), TenancyError> {
let key = format!("{}{}", Self::prefix()?, key);
self.inner.delete(&key).await
}
async fn delete_prefix(&self, prefix: &str) -> Result<(), TenancyError> {
let prefix = format!("{}{}", Self::prefix()?, prefix);
self.inner.delete_prefix(&prefix).await
}
}
#[derive(Clone)]
pub struct ScopedStorage {
inner: Arc<dyn Storage>,
}
impl ScopedStorage {
pub fn new(inner: Arc<dyn Storage>) -> Self {
Self { inner }
}
fn prefix() -> Result<String, TenancyError> {
current_context()
.map(|context| format!("{}/", context.tenant().slug))
.ok_or(TenancyError::NotResolved)
}
}
#[async_trait]
impl Storage for ScopedStorage {
async fn put(&self, path: &str, data: Vec<u8>) -> Result<(), TenancyError> {
let path = format!("{}{}", Self::prefix()?, path);
self.inner.put(&path, data).await
}
async fn get(&self, path: &str) -> Result<Vec<u8>, TenancyError> {
let path = format!("{}{}", Self::prefix()?, path);
self.inner.get(&path).await
}
async fn exists(&self, path: &str) -> Result<bool, TenancyError> {
let path = format!("{}{}", Self::prefix()?, path);
self.inner.exists(&path).await
}
async fn delete(&self, path: &str) -> Result<(), TenancyError> {
let path = format!("{}{}", Self::prefix()?, path);
self.inner.delete(&path).await
}
async fn delete_prefix(&self, prefix: &str) -> Result<(), TenancyError> {
let prefix = format!("{}{}", Self::prefix()?, prefix);
self.inner.delete_prefix(&prefix).await
}
}