use crate::cache::CompileCacheKey;
use crate::compile::CompiledQuery;
use crate::errors::{ConfigErrorKind, VlorQLError};
use crate::schema::DialectProfile;
use crate::validate::ValidatedPlan;
use moka::future::Cache as MokaCache;
use serde_json::json;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
#[derive(Debug)]
pub struct CompileCache {
inner: MokaCache<CompileCacheKey, Arc<CompiledQuery>>,
entries: Mutex<HashMap<CompileCacheKey, CompiledQuery>>,
max_size: u64,
persist_path: Option<PathBuf>,
}
impl CompileCache {
#[must_use]
pub fn new(max_size: u64, ttl_seconds: u64) -> Self {
let mut builder = MokaCache::builder()
.weigher(|_k, v: &Arc<CompiledQuery>| -> u32 {
let len = v.sql.len() as u64;
len.min(u64::from(u32::MAX)) as u32
})
.max_capacity(max_size);
if ttl_seconds > 0 {
builder = builder.time_to_live(std::time::Duration::from_secs(ttl_seconds));
}
let inner = builder.build();
Self {
inner,
entries: Mutex::new(HashMap::new()),
max_size,
persist_path: None,
}
}
pub async fn get(
&self,
plan: &ValidatedPlan,
profile: &DialectProfile,
) -> Option<Arc<CompiledQuery>> {
let key = CompileCacheKey::new(plan, profile);
let result = self.inner.get(&key).await;
let hit = result.is_some();
tracing::debug!(
target: "vlorql::cache",
"Compile cache {} for plan_hash={:016x}, dialect={:?}",
if hit { "HIT" } else { "MISS" },
key.plan_hash,
key.dialect,
);
result
}
pub async fn insert(
&self,
plan: &ValidatedPlan,
profile: &DialectProfile,
query: CompiledQuery,
) {
let key = CompileCacheKey::new(plan, profile);
tracing::debug!(
target: "vlorql::cache",
"Compile cache INSERT for plan_hash={:016x}, dialect={:?}",
key.plan_hash,
key.dialect,
);
self.inner
.insert(key.clone(), Arc::new(query.clone()))
.await;
self.entries
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key, query);
}
pub async fn invalidate_plan(&self, plan: &ValidatedPlan, profile: &DialectProfile) {
let key = CompileCacheKey::new(plan, profile);
self.inner.invalidate(&key).await;
self.entries
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&key);
}
pub fn clear(&self) {
self.inner.invalidate_all();
self.entries
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
#[must_use]
pub fn size(&self) -> u64 {
self.inner.entry_count()
}
#[must_use]
pub fn max_size(&self) -> u64 {
self.max_size
}
#[must_use]
pub fn with_persistence(max_size: u64, ttl_seconds: u64, path: PathBuf) -> Self {
let mut cache = Self::new(max_size, ttl_seconds);
cache.persist_path = Some(path);
cache
}
pub async fn persist(&self) -> Result<(), VlorQLError> {
let Some(ref path) = self.persist_path else {
return Ok(());
};
let bytes = {
let entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
bincode::serialize(&*entries).map_err(|e| {
VlorQLError::config(
ConfigErrorKind::ConfigFileError {
path: path.to_string_lossy().to_string(),
reason: e.to_string(),
},
json!({"operation": "serialize"}),
)
})?
};
let tmp = path.with_extension("tmp");
tokio::fs::write(&tmp, &bytes).await.map_err(|e| {
VlorQLError::config(
ConfigErrorKind::ConfigFileError {
path: tmp.to_string_lossy().to_string(),
reason: e.to_string(),
},
json!({"operation": "write_tmp"}),
)
})?;
tokio::fs::rename(&tmp, path).await.map_err(|e| {
VlorQLError::config(
ConfigErrorKind::ConfigFileError {
path: path.to_string_lossy().to_string(),
reason: e.to_string(),
},
json!({"operation": "rename"}),
)
})?;
Ok(())
}
#[must_use]
pub async fn load(path: &Path, max_size: u64, ttl_seconds: u64) -> Self {
let mut cache = Self::new(max_size, ttl_seconds);
cache.persist_path = Some(path.to_path_buf());
let bytes = match tokio::fs::read(path).await {
Ok(b) => b,
Err(_) => return cache,
};
let entries: HashMap<CompileCacheKey, CompiledQuery> = match bincode::deserialize(&bytes) {
Ok(e) => e,
Err(_) => {
tracing::warn!(target: "vlorql::cache", "corrupt compile cache file, starting fresh");
return cache;
}
};
for (key, query) in &entries {
cache
.inner
.insert(key.clone(), Arc::new(query.clone()))
.await;
cache
.entries
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(key.clone(), query.clone());
}
cache
}
pub fn set_persist_path(&mut self, path: PathBuf) {
self.persist_path = Some(path);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::{FromClause, Projection, QueryPlan, SqlDialect};
use std::sync::Arc;
fn make_plan() -> ValidatedPlan {
ValidatedPlan(Arc::new(QueryPlan {
select: vec![Projection::Column {
table: None,
column: "id".to_owned(),
alias: None,
}],
from: FromClause::table("users".to_owned(), None),
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: None,
ctes: None,
distinct: false,
distinct_on: None,
set_operation: None,
}))
}
fn make_compiled(dialect: SqlDialect) -> CompiledQuery {
match dialect {
SqlDialect::Postgres => CompiledQuery {
sql: "SELECT \"id\" FROM \"users\"".to_owned(),
parameters: vec![],
dialect: SqlDialect::Postgres,
},
SqlDialect::Sqlite => CompiledQuery {
sql: "SELECT \"id\" FROM \"users\"".to_owned(),
parameters: vec![],
dialect: SqlDialect::Sqlite,
},
SqlDialect::MySql => CompiledQuery {
sql: "SELECT `id` FROM `users`".to_owned(),
parameters: vec![],
dialect: SqlDialect::MySql,
},
}
}
#[tokio::test]
async fn same_plan_same_dialect_hits() {
let cache = CompileCache::new(1024, 60);
let plan = make_plan();
let profile = DialectProfile::default();
let compiled = make_compiled(SqlDialect::Postgres);
assert!(cache.get(&plan, &profile).await.is_none());
cache.insert(&plan, &profile, compiled.clone()).await;
let cached = cache.get(&plan, &profile).await;
assert_eq!(cached, Some(Arc::new(compiled)));
}
#[tokio::test]
async fn same_plan_different_dialect_misses() {
let cache = CompileCache::new(1024, 60);
let plan = make_plan();
let pg_profile = DialectProfile::default();
let sqlite_profile = DialectProfile {
dialect: SqlDialect::Sqlite,
..DialectProfile::default()
};
let pg_compiled = make_compiled(SqlDialect::Postgres);
cache.insert(&plan, &pg_profile, pg_compiled).await;
assert!(
cache.get(&plan, &sqlite_profile).await.is_none(),
"a different dialect must not return the cached value"
);
}
#[tokio::test]
async fn different_plan_different_key() {
let cache = CompileCache::new(1024, 60);
let profile = DialectProfile::default();
let plan_a = make_plan();
let plan_b = ValidatedPlan(Arc::new(QueryPlan {
select: vec![Projection::Column {
table: None,
column: "email".to_owned(),
alias: None,
}],
from: FromClause::table("users".to_owned(), None),
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: None,
ctes: None,
distinct: false,
distinct_on: None,
set_operation: None,
}));
let compiled_a = make_compiled(SqlDialect::Postgres);
let compiled_b = CompiledQuery {
sql: "SELECT \"email\" FROM \"users\"".to_owned(),
parameters: vec![],
dialect: SqlDialect::Postgres,
};
cache.insert(&plan_a, &profile, compiled_a).await;
cache.insert(&plan_b, &profile, compiled_b.clone()).await;
let cached = cache.get(&plan_b, &profile).await;
assert_eq!(cached, Some(Arc::new(compiled_b)));
}
#[cfg(not(miri))]
#[tokio::test]
async fn cache_evicts_under_lru_weight_limit() {
let cache = CompileCache::new(50, 60); let profile = DialectProfile::default();
for i in 0..20 {
let plan = ValidatedPlan(Arc::new(QueryPlan {
select: vec![Projection::Column {
table: None,
column: format!("col_{i}"),
alias: None,
}],
from: FromClause::table("t".to_owned(), None),
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: None,
ctes: None,
distinct: false,
distinct_on: None,
set_operation: None,
}));
let compiled = CompiledQuery {
sql: format!("SELECT \"col_{i}\" FROM \"t\""),
parameters: vec![],
dialect: SqlDialect::Postgres,
};
cache.insert(&plan, &profile, compiled).await;
}
let size = cache.size();
assert!(
size < 20,
"cache should have evicted entries under tight weight limit, got {size}"
);
}
#[tokio::test]
async fn invalidate_plan_removes_entry() {
let cache = CompileCache::new(1024, 60);
let plan = make_plan();
let profile = DialectProfile::default();
let compiled = make_compiled(SqlDialect::Postgres);
cache.insert(&plan, &profile, compiled).await;
assert!(cache.get(&plan, &profile).await.is_some());
cache.invalidate_plan(&plan, &profile).await;
assert!(
cache.get(&plan, &profile).await.is_none(),
"entry should be removed after invalidation"
);
}
#[tokio::test]
async fn clear_removes_all_entries() {
let cache = CompileCache::new(1024, 60);
let plan = make_plan();
let profile = DialectProfile::default();
let compiled = make_compiled(SqlDialect::Postgres);
cache.insert(&plan, &profile, compiled).await;
assert!(cache.get(&plan, &profile).await.is_some());
cache.clear();
assert!(
cache.get(&plan, &profile).await.is_none(),
"entry should be removed after clear"
);
}
#[tokio::test]
async fn ttl_expiry_causes_miss() {
let cache = CompileCache::new(1024, 1); let plan = make_plan();
let profile = DialectProfile::default();
let compiled = make_compiled(SqlDialect::Postgres);
cache.insert(&plan, &profile, compiled).await;
assert!(cache.get(&plan, &profile).await.is_some());
tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
assert!(
cache.get(&plan, &profile).await.is_none(),
"entry should have expired after TTL"
);
}
#[tokio::test]
async fn concurrent_access_is_safe() {
let cache = std::sync::Arc::new(CompileCache::new(1024, 60));
let profile = DialectProfile::default();
let mut handles = Vec::new();
for i in 0..20 {
let cache = Arc::clone(&cache);
let profile = profile.clone();
handles.push(tokio::spawn(async move {
let plan = ValidatedPlan(Arc::new(QueryPlan {
select: vec![Projection::Column {
table: None,
column: format!("col_{i}"),
alias: None,
}],
from: FromClause::table("t".to_owned(), None),
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: None,
ctes: None,
distinct: false,
distinct_on: None,
set_operation: None,
}));
let compiled = CompiledQuery {
sql: format!("SELECT \"col_{i}\" FROM \"t\""),
parameters: vec![],
dialect: SqlDialect::Postgres,
};
cache.insert(&plan, &profile, compiled).await;
let result = cache.get(&plan, &profile).await;
assert!(result.is_some(), "concurrent insert+get should succeed");
}));
}
for handle in handles {
handle.await.expect("concurrent task should not panic");
}
}
#[tokio::test]
async fn persist_then_load_roundtrip() {
let dir = std::env::temp_dir();
let path = dir.join(format!("compile_cache_test_persist_{}", std::process::id()));
std::fs::remove_file(&path).ok();
std::fs::remove_file(dir.join("compile_cache_test_persist_.tmp")).ok();
let cache = CompileCache::with_persistence(1024, 60, path.clone());
let plan = make_plan();
let profile = DialectProfile::default();
let compiled = make_compiled(SqlDialect::Postgres);
cache.insert(&plan, &profile, compiled.clone()).await;
cache.persist().await.expect("persist should succeed");
let loaded = CompileCache::load(&path, 1024, 60).await;
let cached = loaded.get(&plan, &profile).await;
assert_eq!(cached, Some(Arc::new(compiled)));
std::fs::remove_file(&path).ok();
}
#[tokio::test]
async fn corrupt_file_loads_gracefully() {
let dir = std::env::temp_dir();
let path = dir.join(format!("compile_cache_test_corrupt_{}", std::process::id()));
std::fs::remove_file(&path).ok();
tokio::fs::write(&path, b"not valid bincode data")
.await
.expect("write");
let cache = CompileCache::load(&path, 1024, 60).await;
assert_eq!(cache.size(), 0, "corrupt file should load as empty");
std::fs::remove_file(&path).ok();
}
#[tokio::test]
async fn missing_file_loads_gracefully() {
let dir = std::env::temp_dir();
let path = dir.join(format!("compile_cache_test_missing_{}", std::process::id()));
std::fs::remove_file(&path).ok();
let cache = CompileCache::load(&path, 1024, 60).await;
assert_eq!(cache.size(), 0, "missing file should load as empty");
}
#[tokio::test]
async fn invalidate_removes_from_persist_state() {
let cache = CompileCache::new(1024, 60);
let plan = make_plan();
let profile = DialectProfile::default();
let compiled = make_compiled(SqlDialect::Postgres);
cache.insert(&plan, &profile, compiled).await;
assert_eq!(cache.entries.lock().unwrap().len(), 1);
cache.invalidate_plan(&plan, &profile).await;
assert_eq!(cache.entries.lock().unwrap().len(), 0);
}
}