use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;
use laravel::Application;
use laravel::cache::{self, MemoryStore, Store};
use laravel::config::Env;
use laravel::config::cache::StoreConfig;
use laravel::foundation::StartupError;
use crate::logging::Lines;
const MINUTE: Duration = Duration::from_secs(60);
#[derive(Clone, Default)]
struct FlakyStore {
values: MemoryStore,
down: Arc<AtomicBool>,
calls: Arc<AtomicUsize>,
}
impl FlakyStore {
fn set_down(&self, down: bool) {
self.down.store(down, Ordering::SeqCst);
}
fn calls(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
fn check(&self) -> laravel::Result<()> {
self.calls.fetch_add(1, Ordering::SeqCst);
if self.down.load(Ordering::SeqCst) {
return Err(laravel::abort_with(503, "The flaky store is down"));
}
Ok(())
}
}
impl Store for FlakyStore {
async fn get(&self, key: &str) -> laravel::Result<Option<String>> {
self.check()?;
self.values.get(key).await
}
async fn put(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<()> {
self.check()?;
self.values.put(key, value, ttl).await
}
async fn add(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<bool> {
self.check()?;
self.values.add(key, value, ttl).await
}
async fn increment(&self, key: &str, by: i64) -> laravel::Result<Option<i64>> {
self.check()?;
self.values.increment(key, by).await
}
async fn forget(&self, key: &str) -> laravel::Result<bool> {
self.check()?;
self.values.forget(key).await
}
async fn flush(&self) -> laravel::Result<()> {
self.check()?;
self.values.flush().await
}
async fn acquire_lock(&self, name: &str, owner: &str, ttl: Duration) -> laravel::Result<bool> {
self.check()?;
self.values.acquire_lock(name, owner, ttl).await
}
async fn release_lock(&self, name: &str, owner: &str) -> laravel::Result<bool> {
self.check()?;
self.values.release_lock(name, owner).await
}
async fn force_release_lock(&self, name: &str) -> laravel::Result<()> {
self.check()?;
self.values.force_release_lock(name).await
}
async fn refresh_lock(&self, name: &str, owner: &str, ttl: Duration) -> laravel::Result<bool> {
self.check()?;
self.values.refresh_lock(name, owner, ttl).await
}
async fn lock_owner(&self, name: &str) -> laravel::Result<Option<String>> {
self.check()?;
self.values.lock_owner(name).await
}
}
fn app() -> (Application, FlakyStore, FlakyStore) {
let (primary, backup) = (FlakyStore::default(), FlakyStore::default());
let app = Application::configure()
.replace_env(Env::from_iter([("CACHE_STORE", "failover")]))
.with_config(|config, _| {
config
.cache
.add_store("primary", StoreConfig::custom("primary"))
.add_store("backup", StoreConfig::custom("backup"))
.add_store("failover", StoreConfig::failover(["primary", "backup"]));
})
.with_services({
let (primary, backup) = (primary.clone(), backup.clone());
move |app| {
app.cache()
.extend("primary", move |_app, _definition| {
let primary = primary.clone();
async move { Ok(primary) }
})
.extend("backup", move |_app, _definition| {
let backup = backup.clone();
async move { Ok(backup) }
});
}
})
.create();
(app, primary, backup)
}
#[tokio::test]
async fn the_first_store_that_works_is_used() -> laravel::Result<()> {
let (app, primary, _backup) = app();
app.scope(async || {
cache::put("user", "Taylor", MINUTE).await?;
assert_eq!(
cache::store("primary")?.get::<String>("user").await?.as_deref(),
Some("Taylor")
);
assert_eq!(cache::store("backup")?.get::<String>("user").await?, None);
primary.set_down(true);
cache::put("user", "Abigail", MINUTE).await?;
assert_eq!(cache::get::<String>("user").await?.as_deref(), Some("Abigail"));
assert_eq!(
cache::store("backup")?.get::<String>("user").await?.as_deref(),
Some("Abigail")
);
primary.set_down(false);
app.travel(Duration::from_secs(10));
assert_eq!(
cache::get::<String>("user").await?.as_deref(),
Some("Taylor"),
"the first store is used again once it works"
);
Ok(())
})
.await
}
#[tokio::test]
async fn a_store_that_starts_failing_is_logged_once() -> laravel::Result<()> {
let (lines, _guard) = Lines::capture();
let (app, primary, _backup) = app();
let warnings = || {
lines
.json()
.into_iter()
.filter(|line| line["fields"]["message"] == "The cache failed over to its next store")
.collect::<Vec<_>>()
};
app.scope(async || {
primary.set_down(true);
cache::put("a", 1, MINUTE).await?;
cache::get::<i64>("a").await?;
cache::forget("a").await?;
Ok::<_, laravel::Error>(())
})
.await?;
let logged = warnings();
assert_eq!(logged.len(), 1);
assert_eq!(logged[0]["level"], "WARN");
assert_eq!(logged[0]["target"], "laravel::cache");
assert_eq!(logged[0]["fields"]["store"], "failover");
assert_eq!(logged[0]["fields"]["failed_store"], "primary");
assert!(logged[0]["fields"]["error"].as_str().unwrap().contains("down"));
assert_eq!(
crate::cache_logging::logged(&lines, "Cache hit")[0]["fields"]["store"],
"failover"
);
app.scope(async || {
primary.set_down(false);
app.travel(Duration::from_secs(10));
cache::get::<i64>("a").await?;
primary.set_down(true);
cache::get::<i64>("a").await
})
.await?;
assert_eq!(
warnings().len(),
2,
"a store that recovered and fails again is logged again"
);
Ok(())
}
#[tokio::test]
async fn a_failed_store_is_skipped_until_its_cooldown_passes() -> laravel::Result<()> {
let (app, primary, _backup) = app();
app.freeze_time();
primary.set_down(true);
app.scope(async || {
for _ in 0..3 {
cache::put("user", "Taylor", MINUTE).await?;
}
assert_eq!(primary.calls(), 1, "an outage costs one attempt, not one per operation");
primary.set_down(false);
app.travel(Duration::from_secs(9));
cache::put("user", "Abigail", MINUTE).await?;
assert_eq!(primary.calls(), 1, "the store is skipped for 10 seconds");
app.travel(Duration::from_secs(1));
cache::put("user", "Taylor", MINUTE).await?;
assert_eq!(primary.calls(), 2, "the store is tried again after 10 seconds");
assert_eq!(
cache::store("primary")?.get::<String>("user").await?.as_deref(),
Some("Taylor")
);
Ok(())
})
.await
}
#[tokio::test]
async fn values_a_store_cant_use_are_errors_rather_than_outages() -> laravel::Result<()> {
let (lines, _guard) = Lines::capture();
let (app, _primary, backup) = app();
app.scope(async || {
cache::put("visits", "many", MINUTE).await?;
let error = cache::increment("visits", 1).await.unwrap_err();
assert!(error.to_string().contains("isn't an integer"), "{error}");
assert!(cache::increment_or_add("visits", 1, MINUTE).await.is_err());
cache::put("visits", i64::MAX, MINUTE).await?;
let error = cache::increment("visits", 1).await.unwrap_err();
assert!(error.to_string().contains("overflows"), "{error}");
Ok::<_, laravel::Error>(())
})
.await?;
assert_eq!(backup.calls(), 0, "the backup store wasn't used");
assert!(
lines
.json()
.iter()
.all(|line| line["fields"]["message"] != "The cache failed over to its next store")
);
Ok(())
}
#[tokio::test]
async fn when_every_store_fails_the_last_error_is_returned() -> laravel::Result<()> {
let (app, primary, backup) = app();
primary.set_down(true);
backup.set_down(true);
app.scope(async || {
let error = cache::get::<i64>("a").await.unwrap_err();
assert_eq!(error.status(), 503);
assert!(error.to_string().contains("The flaky store is down"));
Ok(())
})
.await
}
#[tokio::test]
async fn locks_always_use_the_first_store() -> laravel::Result<()> {
let (app, primary, _backup) = app();
primary.set_down(true);
app.scope(async || {
let lock = cache::lock("reports", MINUTE)?;
let error = lock.acquire().await.unwrap_err();
assert_eq!(error.status(), 503);
assert!(lock.is_locked().await.is_err());
assert!(!cache::store("backup")?.lock("reports", MINUTE).is_locked().await?);
assert!(cache::add("claim", true, MINUTE).await?, "values still fail over");
primary.set_down(false);
assert!(lock.acquire().await?);
assert!(!cache::lock("reports", MINUTE)?.acquire().await?);
assert!(cache::store("primary")?.lock("reports", MINUTE).is_locked().await?);
assert!(lock.release().await?);
Ok(())
})
.await
}
#[tokio::test]
async fn the_default_failover_store_falls_back_to_memory() -> laravel::Result<()> {
let app = Application::configure()
.replace_env(Env::from_iter([("CACHE_STORE", "failover")]))
.create();
app.scope(async || {
cache::put("user", "Taylor", MINUTE).await?;
assert_eq!(cache::get::<String>("user").await?.as_deref(), Some("Taylor"));
assert_eq!(
cache::store("memory")?.get::<String>("user").await?.as_deref(),
Some("Taylor"),
"the database isn't configured, so the memory store was used"
);
Ok(())
})
.await
}
fn startup_error(stores: &[(&'static str, StoreConfig)]) -> StartupError {
let stores = stores.to_vec();
Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
for (name, store) in stores {
config.cache.add_store(name, store);
}
})
.try_create()
.unwrap_err()
}
#[test]
fn invalid_failover_stores_stop_the_application_from_starting() {
let unknown = startup_error(&[("failover", StoreConfig::failover(["missing"]))]);
assert!(
unknown
.to_string()
.contains("failover cache store `failover` uses store `missing`, which isn't defined")
);
let cycle = startup_error(&[
("a", StoreConfig::failover(["memory", "b"])),
("b", StoreConfig::failover(["a"])),
]);
assert!(matches!(cycle, StartupError::Cache(_)));
assert!(cycle.to_string().contains("fails over to itself"), "{cycle}");
let empty = startup_error(&[("failover", StoreConfig::failover(Vec::<String>::new()))]);
assert!(
empty
.to_string()
.contains("failover cache store `failover` has no stores")
);
}