pub struct RequestCache { /* private fields */ }Expand description
A type-keyed store scoped to one GraphQL request.
At most one value of each Rust type is stored. Insertion returns an Arc, so cloning a
value out of the cache (or handing it to several resolvers) does not clone the value itself.
RequestCache is cheap to clone: every clone refers to the same store, which means passing
one into the execution context and one into a resolver is the same cache. A new request must
call RequestCache::new to get an isolated store.
Reads take a shared lock and writes take an exclusive one, so resolvers running on several worker threads can share the cache without copying it. Contention is normally limited to the first access for each type, which is where the value is built.
use gurafi::RequestCache;
let cache = RequestCache::new();
let first = cache.get_or_insert_with(|| String::from("shared"));
let second = cache.get_or_insert_with(|| String::from("unused"));
assert!(std::sync::Arc::ptr_eq(&first, &second));
assert_eq!(&*first, "shared");Implementations§
Source§impl RequestCache
impl RequestCache
Sourcepub fn new() -> Self
pub fn new() -> Self
Create an empty request cache.
Create exactly one of these per GraphQL request. Sharing a cache between requests leaks values across them; that is sometimes desirable for immutable metadata, but it is not what this type promises.
Sourcepub fn get<T>(&self) -> Option<Arc<T>>
pub fn get<T>(&self) -> Option<Arc<T>>
Borrow a stored value, if one of type T has been inserted.
The returned Arc keeps the value alive even if the entry is simultaneously removed from
the cache.
Sourcepub fn get_or_insert_with<T>(&self, init: impl FnOnce() -> T) -> Arc<T> ⓘ
pub fn get_or_insert_with<T>(&self, init: impl FnOnce() -> T) -> Arc<T> ⓘ
Return the stored value of type T, building it with init if it is absent.
When several threads race for the same missing type exactly one calls init; every
caller receives the same Arc. The common case for a loader is therefore one
construction per request, not one per resolver.
init runs while the cache is write-locked. It must not call back into this cache (that
would deadlock) and should not block; construct the value and return it.
Sourcepub fn insert<T>(&self, value: T) -> Option<Arc<T>>
pub fn insert<T>(&self, value: T) -> Option<Arc<T>>
Store value, returning the value it replaced.
Handles already given out for the previous value stay valid; only future lookups observe the replacement.