use crate::policy::PolicyConfig;
use crate::schema::{DialectProfile, SqlDialect};
use moka::future::Cache as MokaCache;
use std::hash::Hash;
use std::hash::Hasher;
use xxhash_rust::xxh3::Xxh3;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PromptCacheKey {
pub schema_version: String,
pub dialect: SqlDialect,
pub policy_hash: u64,
pub table_hash: u64,
}
impl PromptCacheKey {
pub fn new(
schema_version: &str,
dialect: &DialectProfile,
policy_hash: u64,
table_hash: u64,
) -> Self {
Self {
schema_version: schema_version.to_owned(),
dialect: dialect.dialect,
policy_hash,
table_hash,
}
}
}
pub(crate) fn hash_policy(policy: &PolicyConfig) -> u64 {
let json = serde_json::to_value(policy).expect("PolicyConfig should serialize to JSON");
let canonical = serde_json::to_string(&json).expect("JSON should serialize to string");
let mut hasher = Xxh3::new();
canonical.hash(&mut hasher);
hasher.finish()
}
#[derive(Debug, Clone)]
pub struct PromptCache {
inner: MokaCache<PromptCacheKey, String>,
}
impl PromptCache {
#[must_use]
pub fn new(capacity: u64, ttl_seconds: u64) -> Self {
let mut builder = MokaCache::builder().max_capacity(capacity);
if ttl_seconds > 0 {
builder = builder.time_to_live(std::time::Duration::from_secs(ttl_seconds));
}
let inner = builder.build();
Self { inner }
}
pub async fn get(&self, key: &PromptCacheKey) -> Option<String> {
let result = self.inner.get(key).await;
let hit = result.is_some();
tracing::debug!(
target: "vlorql::cache",
"Prompt cache {} for version={}, dialect={:?}",
if hit { "HIT" } else { "MISS" },
key.schema_version,
key.dialect,
);
result
}
pub async fn insert(&self, key: PromptCacheKey, prompt: String) {
tracing::debug!(
target: "vlorql::cache",
"Prompt cache INSERT for version={}, dialect={:?}",
key.schema_version,
key.dialect,
);
self.inner.insert(key, prompt).await;
}
pub async fn invalidate(&self, key: &PromptCacheKey) {
self.inner.invalidate(key).await;
}
pub fn clear(&self) {
self.inner.invalidate_all();
}
#[must_use]
pub fn size(&self) -> u64 {
self.inner.entry_count()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::policy::{PolicyConfig, TablePolicy};
use crate::schema::DialectProfile;
use std::collections::HashMap;
fn key_v1() -> PromptCacheKey {
PromptCacheKey::new(
"v1",
&DialectProfile::default(),
hash_policy(&PolicyConfig::default()),
0,
)
}
fn key_v2() -> PromptCacheKey {
PromptCacheKey::new(
"v2",
&DialectProfile::default(),
hash_policy(&PolicyConfig::default()),
0,
)
}
#[test]
fn same_config_same_key() {
let a = key_v1();
let b = PromptCacheKey::new(
"v1",
&DialectProfile::default(),
hash_policy(&PolicyConfig::default()),
0,
);
assert_eq!(a, b);
}
#[test]
fn different_version_different_key() {
let a = key_v1();
let b = key_v2();
assert_ne!(a, b);
}
#[test]
fn different_dialect_different_key() {
let pg = PromptCacheKey::new(
"v1",
&DialectProfile::default(),
hash_policy(&PolicyConfig::default()),
0,
);
let sqlite = PromptCacheKey::new(
"v1",
&DialectProfile {
dialect: SqlDialect::Sqlite,
..DialectProfile::default()
},
hash_policy(&PolicyConfig::default()),
0,
);
assert_ne!(pg, sqlite);
}
#[test]
fn different_policy_different_key() {
let strict = PolicyConfig {
table_policies: HashMap::from([(
"secrets".to_owned(),
TablePolicy {
allowed: false,
..TablePolicy::default()
},
)]),
..PolicyConfig::default()
};
let default_key = PromptCacheKey::new(
"v1",
&DialectProfile::default(),
hash_policy(&PolicyConfig::default()),
0,
);
let strict_key =
PromptCacheKey::new("v1", &DialectProfile::default(), hash_policy(&strict), 0);
assert_ne!(default_key, strict_key);
}
#[tokio::test]
async fn cache_hit_returns_cached_prompt() {
let cache = PromptCache::new(10, 60);
let key = key_v1();
assert!(cache.get(&key).await.is_none());
cache
.insert(key.clone(), "SELECT * FROM users".to_owned())
.await;
let cached = cache.get(&key).await;
assert_eq!(cached, Some("SELECT * FROM users".to_owned()));
}
#[tokio::test]
async fn different_keys_do_not_share() {
let cache = PromptCache::new(10, 60);
let k1 = key_v1();
let k2 = key_v2();
cache.insert(k1.clone(), "prompt_v1".to_owned()).await;
cache.insert(k2.clone(), "prompt_v2".to_owned()).await;
assert_eq!(cache.get(&k1).await, Some("prompt_v1".to_owned()));
assert_eq!(cache.get(&k2).await, Some("prompt_v2".to_owned()));
}
#[tokio::test]
async fn clear_removes_all_entries() {
let cache = PromptCache::new(10, 60);
let key = key_v1();
cache.insert(key.clone(), "data".to_owned()).await;
assert!(cache.get(&key).await.is_some());
cache.clear();
assert!(cache.get(&key).await.is_none());
}
}