use crate::container::ContainerInternals as _;
use std::collections::HashMap;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;
use jiff::Timestamp;
use super::{Store, add_to_integer};
use crate::config::cache::DatabaseStore as DatabaseStoreConfig;
use crate::container::Container;
use crate::db::{AnyConnection, Builder, DatabaseManager, Driver, Values, col, values};
use crate::error::Result;
pub(super) struct DatabaseStore {
database: Arc<DatabaseManager>,
connection: Option<String>,
table: String,
lock_connection: Option<String>,
lock_table: String,
prune_every: Option<Duration>,
next_prune_check: AtomicI64,
this: Weak<Self>,
}
const PRUNE_BATCH: u64 = 1000;
pub(super) fn create(services: &Container, config: &DatabaseStoreConfig) -> Result<Arc<dyn super::ErasedStore>> {
let Some(database) = services.built::<DatabaseManager>() else {
return Err(crate::error::fail(
"the database cache store needs the database manager",
));
};
Ok(DatabaseStore::new(database, config)?)
}
impl DatabaseStore {
pub(super) fn new(database: Arc<DatabaseManager>, config: &DatabaseStoreConfig) -> Result<Arc<Self>> {
for table in [&config.table, &config.lock_table] {
if !crate::db::identifier::is_identifier_path(table) {
return Err(crate::error::fail(format!(
"the cache table `{table}` must be letters, digits and underscores, optionally schema-qualified"
)));
}
}
Ok(Arc::new_cyclic(|this| Self {
database,
connection: config.connection.clone(),
table: config.table.clone(),
lock_connection: config.lock_connection.clone(),
lock_table: config.lock_table.clone(),
prune_every: config.prune_every.map(Duration::from),
next_prune_check: AtomicI64::new(0),
this: this.clone(),
}))
}
fn connection(&self) -> Result<AnyConnection> {
self.connection.as_ref().map_or_else(
|| self.database.default_connection(),
|name| self.database.connection(name),
)
}
fn lock_connection(&self) -> Result<AnyConnection> {
let connection = self
.lock_connection
.as_ref()
.map_or_else(|| self.connection(), |name| self.database.connection(name))?;
Ok(match connection.driver() {
Driver::Sqlite => connection,
_ => connection.outside_transaction(),
})
}
fn values(&self) -> Result<Builder> {
Ok(self.connection()?.table(self.table.as_str()))
}
fn locks(&self) -> Result<Builder> {
Ok(self.lock_connection()?.table(self.lock_table.as_str()))
}
fn value_expiration(&self, ttl: Duration) -> Result<Timestamp> {
Ok(expiration(ttl, self.connection()?.configuration().time_precision))
}
fn lock_expiration(&self, ttl: Duration) -> Result<Timestamp> {
Ok(expiration(ttl, self.lock_connection()?.configuration().time_precision))
}
fn prune_when_due(&self) {
let Some(interval) = self.prune_every else {
return;
};
let now = now().as_second();
let next = self.next_prune_check.load(Ordering::Relaxed);
let following = now.saturating_add(i64::try_from(interval.as_secs()).unwrap_or(i64::MAX));
if now < next
|| self
.next_prune_check
.compare_exchange(next, following, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return;
}
let Some(store) = self.this.upgrade() else {
return;
};
let _ = crate::task::background(async move {
if let Err(error) = store.prune_once_per_interval(interval).await {
crate::foundation::telemetry::logging(
&error,
|| tracing::warn!(%error, table = %store.table, "The cache couldn't prune expired entries"),
);
}
Ok(())
});
}
async fn prune_once_per_interval(&self, interval: Duration) -> Result<()> {
let name = format!("laravel:cache:prune:{}", self.table);
if !self.acquire_lock(&name, &super::owner_token(), interval).await? {
return Ok(());
}
self.prune_expired().await
}
async fn prune_expired(&self) -> Result<()> {
for table in [self.values()?, self.locks()?] {
loop {
let expired = table.clone().filter(col("expiration").le(now()));
let keys: Vec<String> = expired.clone().limit(PRUNE_BATCH).pluck("key").await?;
expired.filter(col("key").is_in(&keys)).delete().await?;
if keys.len() < PRUNE_BATCH as usize {
break;
}
}
}
Ok(())
}
}
impl Store for DatabaseStore {
async fn get(&self, key: &str) -> Result<Option<String>> {
let values = self.values()?.filter(col("key").eq(key));
let row = values
.clone()
.select(["value", "expiration"])
.into_query()
.retry_on_lost_connection()
.select_one_as::<(String, Timestamp)>()
.await?;
let Some((value, expiration)) = row else {
return Ok(None);
};
let now = now();
if expiration <= now {
values.filter(col("expiration").le(now)).delete().await?;
return Ok(None);
}
Ok(Some(value))
}
async fn put(&self, key: &str, value: String, ttl: Duration) -> Result<()> {
self.put_many(vec![(key.to_owned(), value)], ttl).await
}
async fn add(&self, key: &str, value: String, ttl: Duration) -> Result<bool> {
self.prune_when_due();
let values = self.values()?;
values
.clone()
.filter(col("key").eq(key) & col("expiration").le(now()))
.delete()
.await?;
let inserted = values
.insert_or_ignore(values! { key: key, value: value, expiration: self.value_expiration(ttl)? })
.await?;
Ok(inserted > 0)
}
async fn increment(&self, key: &str, by: i64) -> Result<Option<i64>> {
let values = self.values()?.filter(col("key").eq(key));
loop {
let row = values
.clone()
.select(["value", "expiration"])
.lock_for_update()
.first::<(String, Timestamp)>()
.await?;
let Some((current, expires)) = row else {
return Ok(None);
};
if expires <= now() {
return Ok(None);
}
let value = add_to_integer(key, ¤t, by)?;
if by == 0 {
return Ok(Some(value));
}
let updated = values
.clone()
.filter(col("value").eq(current))
.update(values! { value: value.to_string() })
.await?;
if updated > 0 {
return Ok(Some(value));
}
}
}
async fn forget(&self, key: &str) -> Result<bool> {
let values = self.values()?.filter(col("key").eq(key));
let now = now();
let removed = values.clone().filter(col("expiration").gt(now)).delete().await?;
if removed > 0 {
return Ok(true);
}
values.filter(col("expiration").le(now)).delete().await?;
Ok(false)
}
async fn flush(&self) -> Result<()> {
self.values()?.delete().await?;
Ok(())
}
async fn compare_and_swap(&self, key: &str, current: Option<&str>, new: String, ttl: Duration) -> Result<bool> {
let Some(current) = current else {
return self.add(key, new, ttl).await;
};
let swapped = self
.values()?
.filter(col("key").eq(key) & col("value").eq(current) & col("expiration").gt(now()))
.update(values! { value: new, expiration: self.value_expiration(ttl)? })
.await?;
Ok(swapped > 0)
}
async fn touch(&self, key: &str, ttl: Duration) -> Result<bool> {
let touched = self
.values()?
.filter(col("key").eq(key) & col("expiration").gt(now()))
.update(values! { expiration: self.value_expiration(ttl)? })
.await?;
Ok(touched > 0)
}
async fn many(&self, keys: &[String]) -> Result<Vec<Option<String>>> {
if keys.is_empty() {
return Ok(Vec::new());
}
let rows = self
.values()?
.select(["key", "value", "expiration"])
.filter(col("key").is_in(keys))
.into_query()
.retry_on_lost_connection()
.select_as::<(String, String, Timestamp)>()
.await?;
let now = now();
let found: HashMap<String, String> = rows
.into_iter()
.filter(|(_, _, expiration)| *expiration > now)
.map(|(key, value, _)| (key, value))
.collect();
Ok(keys.iter().map(|key| found.get(key).cloned()).collect())
}
async fn put_many(&self, values: Vec<(String, String)>, ttl: Duration) -> Result<()> {
self.prune_when_due();
let mut unique: Vec<(String, String)> = Vec::with_capacity(values.len());
let mut positions = HashMap::new();
for (key, value) in values {
if let Some(&position) = positions.get(&key) {
unique[position] = (key, value);
} else {
positions.insert(key.clone(), unique.len());
unique.push((key, value));
}
}
let expiration = self.value_expiration(ttl)?;
let rows: Vec<Values> = unique
.into_iter()
.map(|(key, value)| values! { key: key, value: value, expiration: expiration })
.collect();
self.values()?.upsert(rows, ["key"], ["value", "expiration"]).await?;
Ok(())
}
async fn prune(&self) -> Result<()> {
self.prune_expired().await
}
async fn acquire_lock(&self, name: &str, owner: &str, ttl: Duration) -> Result<bool> {
self.prune_when_due();
let locks = self.locks()?;
let expiration = self.lock_expiration(ttl)?;
let inserted = locks
.insert_or_ignore(values! { key: name, owner: owner, expiration: expiration })
.await?;
let acquired = inserted > 0
|| locks
.filter(col("key").eq(name) & col("expiration").le(now()))
.update(values! { owner: owner, expiration: expiration })
.await?
> 0;
Ok(acquired)
}
async fn release_lock(&self, name: &str, owner: &str) -> Result<bool> {
let released = self
.locks()?
.filter(col("key").eq(name) & col("owner").eq(owner) & col("expiration").gt(now()))
.delete()
.await?;
Ok(released > 0)
}
async fn force_release_lock(&self, name: &str) -> Result<()> {
self.locks()?.filter(col("key").eq(name)).delete().await?;
Ok(())
}
async fn refresh_lock(&self, name: &str, owner: &str, ttl: Duration) -> Result<bool> {
let refreshed = self
.locks()?
.filter(col("key").eq(name) & col("owner").eq(owner) & col("expiration").gt(now()))
.update(values! { expiration: self.lock_expiration(ttl)? })
.await?;
Ok(refreshed > 0)
}
async fn lock_owner(&self, name: &str) -> Result<Option<String>> {
self.locks()?
.filter(col("key").eq(name) & col("expiration").gt(now()))
.use_write_connection()
.value("owner")
.await
}
}
fn now() -> Timestamp {
crate::clock::system_timestamp()
}
fn expiration(ttl: Duration, precision: u8) -> Timestamp {
let Ok(expires) = now().checked_add(ttl) else {
return Timestamp::MAX;
};
let step = 10_i128.pow(9 - u32::from(precision.min(9)));
let nanoseconds = expires.as_nanosecond();
let rounded = nanoseconds + (step - nanoseconds.rem_euclid(step)) % step;
Timestamp::from_nanosecond(rounded).unwrap_or(Timestamp::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expirations_round_up_to_the_connections_precision() {
let now = now();
let whole = expiration(Duration::from_millis(1500), 0);
assert!(whole >= now + Duration::from_millis(1500) && whole.subsec_nanosecond() == 0);
let micros = expiration(Duration::from_nanos(1), 6);
assert!(micros > now && micros.subsec_nanosecond() % 1000 == 0);
assert_eq!(expiration(Duration::MAX, 6), Timestamp::MAX);
}
}