Skip to main content

QueryResultCache

Struct QueryResultCache 

Source
pub struct QueryResultCache { /* private fields */ }
Expand description

Thread-safe LRU cache for query results.

§Thread Safety

The LRU structure uses a single Mutex for correctness. Metrics counters use AtomicU64 / AtomicUsize so no second lock is acquired in the hot path. Under high concurrency this eliminates the double-lock contention that caused cache hits to be slower than cache misses.

§Memory Safety

  • Hard LRU limit: Configured via max_entries, automatically evicts least-recently-used entries when limit is reached
  • TTL expiry: Entries older than ttl_seconds are considered expired and removed on next access
  • Memory tracking: Metrics include estimated memory usage

§Example

use fraiseql_core::cache::{QueryResultCache, CacheConfig};
use fraiseql_core::db::types::JsonbValue;
use serde_json::json;

let cache = QueryResultCache::new(CacheConfig::default());

// Cache a result
let result = vec![JsonbValue::new(json!({"id": 1, "name": "Alice"}))];
cache.put(
    "cache_key_123".to_string(),
    result.clone(),
    vec!["v_user".to_string()]
).unwrap();

// Retrieve from cache
if let Some(cached) = cache.get("cache_key_123").unwrap() {
    println!("Cache hit! {} results", cached.len());
}

Implementations§

Source§

impl QueryResultCache

Source

pub fn new(config: CacheConfig) -> Self

Create new cache with configuration.

§Panics

Panics if config.max_entries is 0 (invalid configuration).

§Example
use fraiseql_core::cache::{QueryResultCache, CacheConfig};

let cache = QueryResultCache::new(CacheConfig::default());
Source

pub fn is_enabled(&self) -> bool

Get cached result by key.

Returns None if:

  • Caching is disabled (config.enabled = false)
  • Entry not in cache (cache miss)
  • Entry expired (TTL exceeded)
§Errors

Returns error if cache mutex is poisoned (should never happen).

§Example
use fraiseql_core::cache::{QueryResultCache, CacheConfig};

let cache = QueryResultCache::new(CacheConfig::default());

if let Some(result) = cache.get("cache_key_abc123")? {
    // Cache hit - use result
    println!("Found {} results in cache", result.len());
} else {
    // Cache miss - execute query
    println!("Cache miss, executing query");
}

Returns whether caching is enabled.

Used by CachedDatabaseAdapter to short-circuit the SHA-256 key generation and result clone overhead when caching is disabled.

Source

pub fn get(&self, cache_key: &str) -> Result<Option<Arc<Vec<JsonbValue>>>>

Source

pub fn put( &self, cache_key: String, result: Vec<JsonbValue>, accessed_views: Vec<String>, ) -> Result<()>

Store query result in cache.

If caching is disabled, this is a no-op.

§Arguments
  • cache_key - Cache key (from generate_cache_key())
  • result - Query result to cache
  • accessed_views - List of views accessed by this query
§Errors

Returns error if cache mutex is poisoned.

§Example
use fraiseql_core::cache::{QueryResultCache, CacheConfig};
use fraiseql_core::db::types::JsonbValue;
use serde_json::json;

let cache = QueryResultCache::new(CacheConfig::default());

let result = vec![JsonbValue::new(json!({"id": 1}))];
cache.put(
    "cache_key_abc123".to_string(),
    result,
    vec!["v_user".to_string()]
)?;
Source

pub fn invalidate_views(&self, views: &[String]) -> Result<u64>

Invalidate entries accessing specified views.

Called after mutations to invalidate affected cache entries.

§Arguments
  • views - List of view/table names modified by mutation
§Returns

Number of cache entries invalidated

§Errors

Returns error if cache mutex is poisoned.

§Example
use fraiseql_core::cache::{QueryResultCache, CacheConfig};

let cache = QueryResultCache::new(CacheConfig::default());

// After createUser mutation
let invalidated = cache.invalidate_views(&["v_user".to_string()])?;
println!("Invalidated {} cache entries", invalidated);
Source

pub fn metrics(&self) -> Result<CacheMetrics>

Get cache metrics snapshot.

Returns a consistent snapshot of current counters. Individual fields may be updated independently (atomics), so the snapshot is not a single atomic transaction, but is accurate enough for monitoring.

§Errors

Always returns Ok. The Result return type is kept for API compatibility.

§Example
use fraiseql_core::cache::{QueryResultCache, CacheConfig};

let cache = QueryResultCache::new(CacheConfig::default());
let metrics = cache.metrics()?;

println!("Hit rate: {:.1}%", metrics.hit_rate() * 100.0);
println!("Size: {} / {} entries", metrics.size, 10_000);
Source

pub fn clear(&self) -> Result<()>

Clear all cache entries.

Used for testing and manual cache flush.

§Errors

Returns error if cache mutex is poisoned.

§Example
use fraiseql_core::cache::{QueryResultCache, CacheConfig};

let cache = QueryResultCache::new(CacheConfig::default());
cache.clear()?;

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more