use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use greentic_types::{ErrorCode, GResult, GreenticError};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum StoreKind {
Session,
State,
}
impl StoreKind {
fn as_str(self) -> &'static str {
match self {
Self::Session => "session",
Self::State => "state",
}
}
}
pub(crate) struct Offloaded<T: ?Sized + Send + Sync + 'static> {
inner: Arc<T>,
kind: StoreKind,
degraded: Arc<AtomicBool>,
}
impl<T: ?Sized + Send + Sync + 'static> Clone for Offloaded<T> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
kind: self.kind,
degraded: Arc::clone(&self.degraded),
}
}
}
impl<T: ?Sized + Send + Sync + 'static> Offloaded<T> {
pub(crate) fn new(inner: Arc<T>, kind: StoreKind) -> Self {
Self {
inner,
kind,
degraded: Arc::new(AtomicBool::new(false)),
}
}
pub(crate) async fn call<F, R>(&self, f: F) -> GResult<R>
where
F: for<'a> FnOnce(&'a T) -> GResult<R> + Send + 'static,
R: Send + 'static,
{
let inner = Arc::clone(&self.inner);
let joined = tokio::task::spawn_blocking(move || f(inner.as_ref())).await;
let result = match joined {
Ok(result) => result,
Err(err) => Err(GreenticError::new(
ErrorCode::Internal,
format!(
"{} store call panicked or was cancelled: {err}",
self.kind.as_str()
),
)),
};
match &result {
Ok(_) => {
if self.degraded.swap(false, Ordering::Relaxed) {
tracing::info!(
store = self.kind.as_str(),
"storage backend recovered; resuming normal operation"
);
}
}
Err(err) => {
if self.degraded.swap(true, Ordering::Relaxed) {
tracing::debug!(
store = self.kind.as_str(),
error = %err,
"storage backend still failing"
);
} else {
tracing::warn!(
store = self.kind.as_str(),
error = %err,
"storage backend call failed; the host keeps serving and every \
affected turn reports the error rather than reading as an empty \
session"
);
}
}
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
use std::thread::ThreadId;
struct ThreadProbe {
seen: Mutex<Vec<ThreadId>>,
fail: AtomicBool,
}
impl ThreadProbe {
fn new() -> Arc<Self> {
Arc::new(Self {
seen: Mutex::new(Vec::new()),
fail: AtomicBool::new(false),
})
}
fn record(&self) -> GResult<()> {
if let Ok(mut seen) = self.seen.lock() {
seen.push(std::thread::current().id());
}
if self.fail.load(Ordering::Relaxed) {
return Err(GreenticError::new(ErrorCode::Internal, "probe failure"));
}
Ok(())
}
}
#[tokio::test]
async fn a_store_call_runs_on_a_different_thread_than_the_caller() {
let probe = ThreadProbe::new();
let handle = Offloaded::new(Arc::clone(&probe), StoreKind::State);
let caller = std::thread::current().id();
handle.call(|probe| probe.record()).await.expect("call");
let seen = probe.seen.lock().expect("probe lock");
assert_eq!(seen.len(), 1, "the closure must run exactly once");
assert_ne!(
seen[0], caller,
"the store call ran on the awaiting thread; spawn_blocking was bypassed"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_offload_holds_on_a_multi_thread_runtime_too() {
let probe = ThreadProbe::new();
let handle = Offloaded::new(Arc::clone(&probe), StoreKind::Session);
let caller = std::thread::current().id();
handle.call(|probe| probe.record()).await.expect("call");
let seen = probe.seen.lock().expect("probe lock");
assert_ne!(seen[0], caller);
}
#[tokio::test]
async fn a_failing_store_still_returns_its_error_to_the_caller() {
let probe = ThreadProbe::new();
probe.fail.store(true, Ordering::Relaxed);
let handle = Offloaded::new(Arc::clone(&probe), StoreKind::State);
assert!(handle.call(|probe| probe.record()).await.is_err());
assert!(handle.call(|probe| probe.record()).await.is_err());
assert!(
handle.degraded.load(Ordering::Relaxed),
"a failing store must be marked degraded"
);
probe.fail.store(false, Ordering::Relaxed);
assert!(handle.call(|probe| probe.record()).await.is_ok());
assert!(
!handle.degraded.load(Ordering::Relaxed),
"recovery must rearm the warning"
);
}
}