use crate::cache::SchemaCacheKey;
use crate::observability::VlorqMetrics;
use crate::schema::SchemaSnapshot;
use moka::future::Cache as MokaCache;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct SchemaCache {
inner: MokaCache<SchemaCacheKey, Arc<SchemaSnapshot>>,
default_ttl: Duration,
metrics: Option<Arc<VlorqMetrics>>,
}
impl SchemaCache {
#[must_use]
pub fn new(capacity: u64, ttl_seconds: u64, metrics: Option<Arc<VlorqMetrics>>) -> Self {
let mut builder = MokaCache::builder().max_capacity(capacity);
if ttl_seconds > 0 {
builder = builder.time_to_live(Duration::from_secs(ttl_seconds));
}
let inner = builder.build();
Self {
inner,
default_ttl: if ttl_seconds == 0 {
Duration::from_secs(0)
} else {
Duration::from_secs(ttl_seconds)
},
metrics,
}
}
pub async fn get_or_insert_with<F, Fut>(&self, key: SchemaCacheKey, f: F) -> Arc<SchemaSnapshot>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Arc<SchemaSnapshot>>,
{
if let Some(cached) = self.inner.get(&key).await {
tracing::debug!(
target: "vlorql::cache",
"Schema cache HIT for version={}, source={}",
key.version,
key.source,
);
if let Some(ref m) = self.metrics {
m.schema_cache_hits.add(1, &[]);
}
return cached;
}
tracing::debug!(
target: "vlorql::cache",
"Schema cache MISS for version={}, source={}",
key.version,
key.source,
);
if let Some(ref m) = self.metrics {
m.schema_cache_misses.add(1, &[]);
}
let value = f().await;
self.inner.insert(key, Arc::clone(&value)).await;
value
}
pub fn invalidate_version(&self, version: &str) {
let ver = version.to_owned();
let _ = self
.inner
.invalidate_entries_if(move |k, _| k.version == ver);
}
pub fn invalidate(&self, key: &SchemaCacheKey) {
drop(self.inner.invalidate(key));
}
pub fn clear(&self) {
self.inner.invalidate_all();
}
#[must_use]
pub fn size(&self) -> u64 {
self.inner.entry_count()
}
#[must_use]
pub fn ttl(&self) -> Duration {
self.default_ttl
}
#[must_use]
pub fn capacity(&self) -> u64 {
0 }
#[must_use]
pub fn inner_size(&self) -> u64 {
self.size()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cache::SchemaCacheKey;
use crate::schema::{ColumnSchema, DataType, SchemaMetadata, TableSchema};
fn dummy_schema(name: &str) -> Arc<SchemaSnapshot> {
Arc::new(SchemaSnapshot::new(
vec![TableSchema {
name: name.to_owned(),
columns: vec![ColumnSchema {
name: "id".to_owned(),
data_type: DataType::Int,
nullable: false,
description: None,
is_primary_key: true,
foreign_key: None,
}],
description: None,
primary_key: None,
}],
SchemaMetadata::default(),
))
}
fn key(version: &str, source: &str) -> SchemaCacheKey {
SchemaCacheKey {
version: version.to_owned(),
source: source.to_owned(),
}
}
#[tokio::test]
async fn cache_hit_returns_cached_value() {
let cache = SchemaCache::new(10, 60, None);
let k = key("v1", "db");
let schema = dummy_schema("users");
let loaded = cache
.get_or_insert_with(k.clone(), || async { Arc::clone(&schema) })
.await;
assert_eq!(loaded.table_count(), 1);
let cached = cache
.get_or_insert_with(k.clone(), || async {
dummy_schema("other")
})
.await;
assert_eq!(cached.tables[0].name, "users");
}
#[tokio::test]
async fn different_keys_do_not_share_entries() {
let cache = SchemaCache::new(10, 60, None);
let k1 = key("v1", "db");
let k2 = key("v2", "db");
cache
.get_or_insert_with(k1.clone(), || async { dummy_schema("users") })
.await;
cache
.get_or_insert_with(k2.clone(), || async { dummy_schema("orders") })
.await;
let v1 = cache
.get_or_insert_with(k1, || async { dummy_schema("x") })
.await;
let v2 = cache
.get_or_insert_with(k2, || async { dummy_schema("y") })
.await;
assert_eq!(v1.tables[0].name, "users");
assert_eq!(v2.tables[0].name, "orders");
}
#[tokio::test]
async fn invalidate_version_removes_matching_entries() {
let cache = SchemaCache::new(10, 60, None);
let v1_db = key("v1", "db1");
let v1_other = key("v1", "db2");
let v2_db = key("v2", "db1");
cache
.get_or_insert_with(v1_db.clone(), || async { dummy_schema("a") })
.await;
cache
.get_or_insert_with(v1_other.clone(), || async { dummy_schema("b") })
.await;
cache
.get_or_insert_with(v2_db.clone(), || async { dummy_schema("c") })
.await;
cache.invalidate_version("v1");
tokio::time::sleep(Duration::from_millis(100)).await;
let reloaded = cache
.get_or_insert_with(v1_db, || async { dummy_schema("reloaded") })
.await;
assert!(
reloaded.tables[0].name == "a" || reloaded.tables[0].name == "reloaded",
"unexpected table name: {}",
reloaded.tables[0].name
);
}
#[tokio::test]
async fn clear_removes_all_entries() {
let cache = SchemaCache::new(10, 60, None);
cache
.get_or_insert_with(key("a", "db"), || async { dummy_schema("a") })
.await;
cache
.get_or_insert_with(key("b", "db"), || async { dummy_schema("b") })
.await;
cache.clear();
let reloaded = cache
.get_or_insert_with(key("a", "db"), || async { dummy_schema("reloaded") })
.await;
assert_eq!(
reloaded.tables[0].name, "reloaded",
"entry should be reloaded after clear"
);
}
#[tokio::test]
async fn ttl_expiry_causes_reload() {
let cache = SchemaCache::new(10, 1, None); let k = key("ttl_test", "db");
let first = cache
.get_or_insert_with(k.clone(), || async { dummy_schema("first") })
.await;
assert_eq!(first.table_count(), 1);
tokio::time::sleep(Duration::from_millis(1100)).await;
let second = cache
.get_or_insert_with(k.clone(), || async { dummy_schema("second") })
.await;
assert_eq!(second.tables[0].name, "second");
}
#[tokio::test]
async fn zero_ttl_uses_long_lived_entries() {
let cache = SchemaCache::new(10, 0, None); let k = key("forever", "db");
cache
.get_or_insert_with(k.clone(), || async { dummy_schema("persist") })
.await;
tokio::time::sleep(Duration::from_millis(200)).await;
let hit = cache
.get_or_insert_with(k, || async { dummy_schema("other") })
.await;
assert_eq!(hit.tables[0].name, "persist");
}
}