use larust_core::AppError;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::future::Future;
use std::time::Duration;
fn cache_driver() -> &'static str {
larust_core::try_config()
.map(|config| config.cache_driver.as_str())
.unwrap_or("database")
}
pub async fn put<T: Serialize>(key: &str, value: &T, ttl: Duration) -> Result<(), AppError> {
match cache_driver() {
"redis" => crate::redis_store::put(key, value, ttl).await,
_ => crate::sql_store::put(key, value, ttl).await,
}
}
pub async fn get<T: DeserializeOwned>(key: &str) -> Result<Option<T>, AppError> {
match cache_driver() {
"redis" => crate::redis_store::get(key).await,
_ => crate::sql_store::get(key).await,
}
}
pub async fn forget(key: &str) -> Result<(), AppError> {
match cache_driver() {
"redis" => crate::redis_store::forget(key).await,
_ => crate::sql_store::forget(key).await,
}
}
pub async fn remember<T, F, Fut>(key: &str, ttl: Duration, f: F) -> Result<T, AppError>
where
T: Serialize + DeserializeOwned,
F: FnOnce() -> Fut,
Fut: Future<Output = Result<T, AppError>>,
{
if let Some(value) = get::<T>(key).await? {
return Ok(value);
}
let value = f().await?;
if let Err(error) = put(key, &value, ttl).await {
tracing::warn!(
%error,
key,
"failed to cache a freshly-fetched value - returning it uncached instead of failing \
the whole request"
);
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
async fn connect_test_db() {
let dir = tempfile::tempdir().unwrap().keep();
let database_url = format!("sqlite://{}/test.sqlite", dir.display());
larust_orm::connect(&database_url).await.unwrap();
}
#[tokio::test]
async fn cache_round_trips_through_the_database_driver_with_no_published_config() {
connect_test_db().await;
put("greeting", &"hello", Duration::from_secs(60))
.await
.unwrap();
let value: Option<String> = get("greeting").await.unwrap();
assert_eq!(value, Some("hello".to_string()));
forget("greeting").await.unwrap();
let value: Option<String> = get("greeting").await.unwrap();
assert_eq!(value, None);
let remembered = remember("computed", Duration::from_secs(60), || async {
Ok::<_, AppError>("computed value".to_string())
})
.await
.unwrap();
assert_eq!(remembered, "computed value");
struct AlwaysFailsToSerialize;
impl serde::Serialize for AlwaysFailsToSerialize {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Err(serde::ser::Error::custom("deliberate failure for the test"))
}
}
impl<'de> serde::Deserialize<'de> for AlwaysFailsToSerialize {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(AlwaysFailsToSerialize)
}
}
let result = remember("uncacheable", Duration::from_secs(60), || async {
Ok::<_, AppError>(AlwaysFailsToSerialize)
})
.await;
assert!(
result.is_ok(),
"remember must return the freshly-fetched value even when caching it fails, got: \
{:?}",
result.err()
);
}
}