use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, RwLock};
use chrono::TimeDelta;
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::config::Config;
use crate::db::migration::Schema;
use crate::db::{self, Sql, Timestamp, Value};
use crate::error::{Error, Result};
use crate::jobs::Delay;
use crate::model::Model;
const TABLE: &str = "glacier_cache";
const NEAR: TimeDelta = TimeDelta::seconds(5);
const MEMORY_LIMIT: usize = 10_000;
pub fn create_table(s: &mut Schema) {
s.create_table(TABLE, |t| {
t.string("key").not_null().unique();
t.text("value").not_null();
t.timestamp("expires_at");
t.timestamps();
});
s.add_index(TABLE, &["expires_at"]);
}
#[derive(Clone, Debug)]
struct Entry {
value: String,
written_at: Timestamp,
expires_at: Option<Timestamp>,
}
impl Entry {
fn live(&self, now: Timestamp) -> bool {
self.expires_at.is_none_or(|at| at > now)
}
}
type Pending<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
trait Store: Send + Sync {
fn get<'a>(&'a self, key: &'a str) -> Pending<'a, Option<Entry>>;
fn set<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, ()>;
fn delete<'a>(&'a self, key: &'a str) -> Pending<'a, ()>;
}
#[derive(Default)]
struct Memory(Mutex<HashMap<String, Entry>>);
impl Memory {
fn get_now(&self, key: &str) -> Option<Entry> {
let now = crate::time::now();
let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
match map.get(key) {
Some(entry) if entry.live(now) => Some(entry.clone()),
Some(_) => {
map.remove(key);
None
}
None => None,
}
}
fn set_now(&self, key: &str, entry: Entry) {
let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
if map.len() >= MEMORY_LIMIT && !map.contains_key(key) {
let now = crate::time::now();
map.retain(|_, entry| entry.live(now));
if map.len() >= MEMORY_LIMIT {
let mut ages: Vec<(Timestamp, String)> =
map.iter().map(|(k, e)| (e.written_at, k.clone())).collect();
ages.sort();
for (_, old) in ages.into_iter().take(MEMORY_LIMIT / 10) {
map.remove(&old);
}
}
}
map.insert(key.to_owned(), entry);
}
}
impl Store for Memory {
fn get<'a>(&'a self, key: &'a str) -> Pending<'a, Option<Entry>> {
let entry = self.get_now(key);
Box::pin(async move { Ok(entry) })
}
fn set<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, ()> {
self.set_now(key, entry);
Box::pin(async { Ok(()) })
}
fn delete<'a>(&'a self, key: &'a str) -> Pending<'a, ()> {
self.0.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
Box::pin(async { Ok(()) })
}
}
struct Null;
impl Store for Null {
fn get<'a>(&'a self, _key: &'a str) -> Pending<'a, Option<Entry>> {
Box::pin(async { Ok(None) })
}
fn set<'a>(&'a self, _key: &'a str, _entry: Entry) -> Pending<'a, ()> {
Box::pin(async { Ok(()) })
}
fn delete<'a>(&'a self, _key: &'a str) -> Pending<'a, ()> {
Box::pin(async { Ok(()) })
}
}
#[derive(Default)]
struct Database {
near: Memory,
}
impl Store for Database {
fn get<'a>(&'a self, key: &'a str) -> Pending<'a, Option<Entry>> {
Box::pin(async move {
if let Some(entry) = self.near.get_now(key) {
return Ok(Some(entry));
}
let mut sql = Sql::new();
sql.push(&format!(
"SELECT value, updated_at, expires_at FROM {TABLE} WHERE key = "
));
sql.push_value(Value::Text(key.to_owned()));
let rows = db::current()?.fetch_all(&sql).await?;
let Some(row) = rows.first() else {
return Ok(None);
};
let entry = Entry {
value: row.get("value")?,
written_at: row.get("updated_at")?,
expires_at: row.get("expires_at")?,
};
if !entry.live(crate::time::now()) {
return Ok(None);
}
self.near.set_now(key, near_copy(&entry));
Ok(Some(entry))
})
}
fn set<'a>(&'a self, key: &'a str, entry: Entry) -> Pending<'a, ()> {
Box::pin(async move {
let mut sql = Sql::new();
sql.push(&format!(
"INSERT INTO {TABLE} (key, value, expires_at, inserted_at, updated_at) VALUES ("
));
sql.push_value(Value::Text(key.to_owned()));
sql.push(", ");
sql.push_value(Value::Text(entry.value.clone()));
sql.push(", ");
sql.push_value(entry.expires_at.map_or(Value::Null, Value::Timestamp));
sql.push(", ");
sql.push_value(Value::Timestamp(entry.written_at));
sql.push(", ");
sql.push_value(Value::Timestamp(entry.written_at));
sql.push(
") ON CONFLICT (key) DO UPDATE SET value = excluded.value, \
expires_at = excluded.expires_at, updated_at = excluded.updated_at",
);
db::current()?.execute(&sql).await?;
self.near.set_now(key, near_copy(&entry));
Ok(())
})
}
fn delete<'a>(&'a self, key: &'a str) -> Pending<'a, ()> {
Box::pin(async move {
self.near
.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(key);
let mut sql = Sql::new();
sql.push(&format!("DELETE FROM {TABLE} WHERE key = "));
sql.push_value(Value::Text(key.to_owned()));
db::current()?.execute(&sql).await?;
Ok(())
})
}
}
fn near_copy(entry: &Entry) -> Entry {
let soon = crate::time::now() + NEAR;
Entry {
expires_at: Some(entry.expires_at.map_or(soon, |at| at.min(soon))),
..entry.clone()
}
}
static STORE: RwLock<Option<Arc<dyn Store>>> = RwLock::new(None);
tokio::task_local! {
static TEST_STORE: Arc<Memory>;
}
fn store() -> Arc<dyn Store> {
if let Ok(store) = TEST_STORE.try_with(Arc::clone) {
return store;
}
if let Some(store) = STORE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
return store.clone();
}
let store: Arc<dyn Store> = Arc::new(Memory::default());
*STORE.write().unwrap_or_else(|e| e.into_inner()) = Some(store.clone());
store
}
#[doc(hidden)]
pub async fn with_test_store<F: Future>(fut: F) -> F::Output {
TEST_STORE.scope(Arc::default(), fut).await
}
pub(crate) fn configure(config: &Config) -> Result<()> {
let store: Arc<dyn Store> = match config.get_opt::<String>("cache.store")?.as_deref() {
None | Some("memory") => Arc::new(Memory::default()),
Some("database") => Arc::new(Database::default()),
Some("null") => Arc::new(Null),
Some(other) => {
return Err(Error::internal(format!(
"cache.store `{other}`: expected memory, database or null"
)));
}
};
*STORE.write().unwrap_or_else(|e| e.into_inner()) = Some(store);
Ok(())
}
pub async fn read<T: DeserializeOwned>(key: &str) -> Result<Option<T>> {
Ok(store()
.get(key)
.await?
.and_then(|entry| serde_json::from_str(&entry.value).ok()))
}
pub async fn write<T: Serialize + ?Sized>(key: &str, value: &T, ttl: impl Delay) -> Result<()> {
let value = serde_json::to_string(value)
.map_err(|e| Error::internal(format!("caching `{key}`: {e}")))?;
let now = crate::time::now();
store()
.set(
key,
Entry {
value,
written_at: now,
expires_at: Some(now + ttl.delay()),
},
)
.await
}
pub async fn delete(key: &str) -> Result<()> {
store().delete(key).await
}
static COMPUTING: Mutex<Option<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> = Mutex::new(None);
fn lock_name(key: &str) -> String {
format!("{:p}/{key}", Arc::as_ptr(&store()).cast::<()>())
}
fn computing(key: &str) -> Arc<tokio::sync::Mutex<()>> {
let mut map = COMPUTING.lock().unwrap_or_else(|e| e.into_inner());
map.get_or_insert_with(HashMap::new)
.entry(lock_name(key))
.or_default()
.clone()
}
fn done_computing(key: &str) {
let name = lock_name(key);
let mut map = COMPUTING.lock().unwrap_or_else(|e| e.into_inner());
if let Some(map) = map.as_mut()
&& map
.get(&name)
.is_some_and(|lock| Arc::strong_count(lock) <= 1)
{
map.remove(&name);
}
}
pub async fn fetch<T, F, Fut>(key: &str, ttl: impl Delay, compute: F) -> Result<T>
where
T: Serialize + DeserializeOwned,
F: FnOnce() -> Fut,
Fut: Future<Output = Result<T>>,
{
if let Some(value) = read(key).await? {
return Ok(value);
}
let ttl = ttl.delay();
let lock = computing(key);
let guard = lock.lock().await;
let outcome = match read(key).await? {
Some(value) => Ok(value),
None => match compute().await {
Ok(value) => write(key, &value, ttl).await.map(|()| value),
Err(err) => Err(err),
},
};
drop(guard);
drop(lock);
done_computing(key);
outcome
}
pub async fn fetch_flexible<T, F, Fut>(
key: &str,
fresh: impl Delay,
stale: impl Delay,
compute: F,
) -> Result<T>
where
T: Serialize + DeserializeOwned,
F: FnOnce() -> Fut,
Fut: Future<Output = Result<T>>,
{
let (fresh, stale) = (fresh.delay(), stale.delay());
let now = crate::time::now();
if let Some(entry) = store().get(key).await?
&& let Ok(value) = serde_json::from_str::<T>(&entry.value)
{
if now - entry.written_at < fresh {
return Ok(value);
}
let lock = computing(key);
let Ok(guard) = lock.try_lock() else {
return Ok(value);
};
let outcome = match compute().await {
Ok(fresh_value) => write(key, &fresh_value, fresh + stale)
.await
.map(|()| fresh_value),
Err(_) => Ok(value),
};
drop(guard);
drop(lock);
done_computing(key);
return outcome;
}
fetch(key, fresh + stale, compute).await
}
pub fn key<M: Model>(record: &M, suffix: &str) -> String {
let id = record.id_value().to_text();
let version = M::UPDATED_AT
.and_then(|column| {
record
.values()
.into_iter()
.find(|(name, _)| *name == column)
})
.map(|(_, value)| value.to_text().replace([' ', ':', '-'], ""))
.unwrap_or_default();
let mut key = format!("{}/{id}", M::TABLE);
if !version.is_empty() {
key.push('-');
key.push_str(&version);
}
if !suffix.is_empty() {
key.push('/');
key.push_str(suffix);
}
key
}
pub async fn prune() -> Result<u64> {
let mut sql = Sql::new();
sql.push(&format!("DELETE FROM {TABLE} WHERE expires_at < "));
sql.push_value(Value::Timestamp(crate::time::now()));
Ok(db::current()?.execute(&sql).await?)
}