Skip to main content

QueryResultCache

Struct QueryResultCache 

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

Thread-safe W-TinyLFU cache for query results.

Backed by moka::sync::Cache which provides lock-free reads via Concurrent TinyLFU. Reverse DashMap indexes enable O(k) invalidation.

§Thread Safety

moka::sync::Cache is Send + Sync. All reverse indexes use DashMap (fine-grained shard locking) and DashSet (also shard-locked). There is no global mutex on the read path.

§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(
    12345_u64,
    result.clone(),
    vec!["v_user".to_string()],
    None, // use global TTL
    None, // no entity type index
).unwrap();

// Retrieve from cache
if let Some(cached) = cache.get(12345).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 const fn is_enabled(&self) -> bool

Returns whether caching is enabled.

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

Source

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

Look up a cached result by its cache key.

Returns None when caching is disabled or the key is not present or expired. Moka handles TTL expiry internally — if get() returns Some, the entry is live.

§Errors

This method is infallible. The Result return type is kept for API compatibility.

Source

pub fn put_arc( &self, cache_key: u64, result: Arc<Vec<JsonbValue>>, accessed_views: Vec<String>, ttl_override: Option<u64>, entity_type: Option<&str>, ) -> Result<()>

Store query result in cache, accepting an already-Arc-wrapped result.

Preferred over put on the hot miss path: callers that already hold an Arc<Vec<JsonbValue>> (e.g. CachedDatabaseAdapter) can store it without an extra Vec clone.

§Arguments
  • cache_key - Cache key (from generate_cache_key())
  • result - Arc-wrapped query result to cache
  • accessed_views - List of views accessed by this query
  • ttl_override - Per-entry TTL in seconds; None uses CacheConfig::ttl_seconds
  • entity_type - Optional GraphQL type name for entity-ID indexing
§Errors

This method is infallible. The Result return type is kept for API compatibility.

Source

pub fn put( &self, cache_key: u64, result: Vec<JsonbValue>, accessed_views: Vec<String>, ttl_override: Option<u64>, entity_type: Option<&str>, ) -> Result<()>

Store query result in cache.

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

Wraps result in an Arc and delegates to put_arc. Prefer put_arc when the caller already holds an Arc.

§Arguments
  • cache_key - Cache key (from generate_cache_key())
  • result - Query result to cache
  • accessed_views - List of views accessed by this query
  • ttl_override - Per-entry TTL in seconds; None uses CacheConfig::ttl_seconds
  • entity_type - Optional GraphQL type name (e.g. "User") for entity-ID indexing. When provided, each row’s "id" field is extracted and stored in entity_index so that invalidate_by_entity() can perform selective eviction.
§Errors

This method is infallible. The Result return type is kept for API compatibility.

§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": "uuid-1"}))];
cache.put(0xabc123, result, vec!["v_user".to_string()], None, Some("User"))?;
Source

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

Invalidate entries accessing specified views.

Uses the view_index for O(k) lookup instead of O(n) full-cache scan. Keys accessing multiple views in views are deduplicated before invalidation.

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

Number of cache entries invalidated.

§Errors

This method is infallible. The Result return type is kept for API compatibility.

§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 invalidate_list_queries(&self, views: &[String]) -> Result<u64>

Evict only list (multi-row) cache entries for the given views.

Unlike invalidate_views(), this method leaves single-entity point-lookup entries intact. Used for CREATE mutations: creating a new entity does not affect queries that fetch a different existing entity by UUID, but it does invalidate queries that return a variable-length list of entities.

Uses the list_index for O(k) lookup.

§Errors

This method is infallible. The Result return type is kept for API compatibility.

Source

pub fn invalidate_by_entity( &self, entity_type: &str, entity_id: &str, ) -> Result<u64>

Evict cache entries that contain a specific entity UUID.

Uses the entity_index for O(k) lookup. Entries not referencing this entity are left untouched.

§Arguments
  • entity_type - GraphQL type name (e.g. "User")
  • entity_id - UUID string of the mutated entity
§Returns

Number of cache entries evicted.

§Errors

This method is infallible. The Result return type is kept for API compatibility.

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

This method is infallible. 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.

Resets the store, reverse indexes, and memory_bytes synchronously. The eviction listener will still fire asynchronously for each evicted entry, but its index-cleanup operations will be no-ops on the already-cleared maps.

§Errors

This method is infallible. The Result return type is kept for API compatibility.

§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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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