QueryClient
QueryClient is a GPUI Global that holds every query, infinite query, and mutation entity in your application. You set it up once during app initialization and access it from any GPUI context through cx.global::<QueryClient>().
use gpui_query::{CachePolicy, QueryClient, RequestPolicy};
let client = QueryClient::with_policies( CachePolicy::Ttl { ttl_ms: 60_000 }, RequestPolicy::LatestWins,).with_gc_time(300_000); // 5 minutes (this is the default)
cx.set_global(client);QueryClient::new() takes no arguments. The default policies are already CachePolicy::Ttl { ttl_ms: 60_000 } and RequestPolicy::LatestWins; use QueryClient::with_policies(cache_policy, request_policy) when you want different defaults. Every query resource created through resource() inherits these unless you override them per-resource. The client holds no default retry policy: mutation retries are set per resource with MutationOptions::retry_policy (default no_retries()) passed to use_mutation.
Constructor
Section titled “Constructor”| Method | Description |
|---|---|
new() |
Create a client with the default policies (Ttl { ttl_ms: 60_000 }, LatestWins) |
with_policies(cache_policy, request_policy) |
Create a client with custom default policies |
.with_gc_time(ms) |
Set the garbage-collection age cutoff: idle resources older than this are collected (default: 300,000 ms; Success resources survive twice as long, values below 1,000 ms are clamped) |
Typed query access
Section titled “Typed query access”resource
Section titled “resource”fn resource<T, E>(&mut self, key: impl Into<QueryKey>, cx: &mut App) -> Entity<QueryResource<T, E>>Get or create a QueryResource<T, E> entity for the given key. The key is generic: &str, String, [&str; N], Vec<&str>, Vec<String>, and QueryKey all convert. If a resource already exists for that key and type pair, it returns the existing entity. Otherwise it creates a new one with the client’s default policies.
let client = cx.global_mut::<QueryClient>();let user = client.resource::<User, MyError>( QueryKey::from(["users", "42"]), cx,);resource_with_policies
Section titled “resource_with_policies”fn resource_with_policies<T, E>( &mut self, key: impl Into<QueryKey>, cache_policy: CachePolicy, request_policy: RequestPolicy, cx: &mut App,) -> Entity<QueryResource<T, E>>Same as resource, but with explicit per-resource policies that override the client defaults.
fn query<T, E>(&self, key: &QueryKey) -> Option<Entity<QueryResource<T, E>>>Read-only lookup: return the existing resource for the given key and type pair, or None if none exists. Creates nothing.
all_queries
Section titled “all_queries”fn all_queries<T, E>(&self) -> Vec<Entity<QueryResource<T, E>>>Return all query entities for a specific (T, E) type pair. Returns an empty vec if no bucket exists for that type.
get_query_data
Section titled “get_query_data”fn get_query_data<T, E>(&self, key: &QueryKey, cx: &App) -> Option<T>Clone the stored data for the given key. Returns None if no resource exists for the key, the entity was collected, or the resource has not completed a fetch.
with_query_data
Section titled “with_query_data”fn with_query_data<T, E, R>( &self, key: &QueryKey, cx: &App, f: impl FnOnce(&T) -> R,) -> Option<R>Zero-clone counterpart to get_query_data: f receives &T for the duration of the call. Same None conditions.
prepare_fetch_query
Section titled “prepare_fetch_query”fn prepare_fetch_query<T, E>( &mut self, key: impl Into<QueryKey>, cx: &mut App,) -> Option<PreparedFetch<T, E>>Imperatively begin a fetch. Creates the resource if needed, then starts a request that always runs in Force mode, so it never short-circuits on a fresh cache and no separate force variant exists. Returns None only when the request policy ignored the start (IgnoreWhileLoading). No observer is attached.
The returned PreparedFetch carries the public fields entity, request_id, and signal (an owned QuerySignal). Run your async fetcher with the signal, then complete the request via prepared.complete_success(data, cx) or prepared.complete_failure(e, cx).
For refetches on an entity that already has an observer attached, use the hook-layer free function gpui_query::fetch_query(entity, fetcher, cx) (plus fetch_query_with_policy and fetch_query_with_signal).
prepare_prefetch_query
Section titled “prepare_prefetch_query”fn prepare_prefetch_query<T, E>( &mut self, key: impl Into<QueryKey>, cache_policy: CachePolicy, request_policy: RequestPolicy, cx: &mut App,) -> Option<PreparedFetch<T, E>>Prefetch a query in the background. T and E require Clone + Send + Sync + 'static; the timestamp is captured internally, so there is no now_ms parameter. None means a fresh cache hit (read the cached value via get_query_data) or that the request policy ignored the start. Some(prepared) binds the request: run your async fetcher with prepared.signal and complete it via prepared.complete_success(data, cx) / prepared.complete_failure(e, cx). Useful for warming the cache before a user navigates to a new view.
Optimistic updates
Section titled “Optimistic updates”set_query_data
Section titled “set_query_data”fn set_query_data<T, E>(&mut self, key: impl Into<QueryKey>, data: T, cx: &mut App)Set data on a resource without completing a request. The resource is created if it does not exist, and the previous data is kept so a later write can restore it. Observers are notified and the persist snapshot is marked dirty.
Use this for optimistic updates: update the cache immediately, then let the mutation result or a refetch correct it later.
let client = cx.global_mut::<QueryClient>();
// Optimistically add the new user to the listclient.set_query_data::<Vec<User>, MyError>( users_key.clone(), updated_user_list, cx,);Rolling back an optimistic update
Section titled “Rolling back an optimistic update”QueryClient has no dedicated rollback method. Capture the previous value with get_query_data (returns None when no data is stored) before the optimistic write, then restore it with set_query_data if the mutation fails:
let client = cx.global_mut::<QueryClient>();let previous = client.get_query_data::<Vec<User>, MyError>(&key, cx);client.set_query_data::<Vec<User>, MyError>(key.clone(), optimistic_data, cx);
// ... later, if the mutation fails ...if let Some(previous) = previous { client.set_query_data::<Vec<User>, MyError>(key.clone(), previous, cx);}set_query_data notifies observers, so mounted views re-render with the restored data and the persist driver saves the change. Calling rollback_to_previous() on the resource entity restores the same value but does not notify observers.
Bulk operations
Section titled “Bulk operations”Bulk operations use QueryKeyFilter to target resources across all type-partitioned buckets. They work on every (T, E) type pair at once.
QueryKeyFilter
Section titled “QueryKeyFilter”pub enum QueryKeyFilter<'a> { Exact(&'a QueryKey), // match one specific key Prefix(&'a QueryKey), // match all keys that start with this prefix All, // match everything}Prefix is useful for invalidating all queries under a namespace. For example, Prefix(&QueryKey::from(["users"])) matches ["users", "42"], ["users", "42", "posts"], and so on.
invalidate_queries
Section titled “invalidate_queries”fn invalidate_queries(&mut self, filter: &QueryKeyFilter, cx: &mut App)Mark matching resources as stale by clearing their cache freshness. Does not cancel active requests. The next time a stale resource is accessed, it will trigger a refetch.
let client = cx.global_mut::<QueryClient>();
// Invalidate all user queriesclient.invalidate_queries( &QueryKeyFilter::Prefix(&QueryKey::from(["users"])), cx,);
// Invalidate one specific queryclient.invalidate_queries( &QueryKeyFilter::Exact(&QueryKey::from(["users", "42"])), cx,);reset_queries
Section titled “reset_queries”fn reset_queries(&mut self, filter: &QueryKeyFilter, cx: &mut App)Clear data and error state on matching resources, resetting them to idle while keeping the entity registered. Each resource’s in-flight signal is cancelled, so cooperative fetchers abort early and late results are ignored. Contrast invalidate_queries, which only clears cache freshness and leaves active requests running.
remove_queries
Section titled “remove_queries”fn remove_queries(&mut self, filter: &QueryKeyFilter)Remove matching resources from the registry entirely. This drops each registry entry, the weak entity reference and its co-located sequencer; an entity still held by a mounted view through a strong Entity handle survives until its last handle is released. Unlike reset_queries, removed keys are no longer registered, and accessing one again creates the resource fresh with a new sequencer. Only query and infinite-query buckets are swept; mutation buckets are left untouched.
// Remove everythingclient.remove_queries(&QueryKeyFilter::All);cancel_queries
Section titled “cancel_queries”fn cancel_queries(&mut self, filter: &QueryKeyFilter, cx: &mut App)Cancel the in-flight signal of matching loading requests and ignore their late results. No QueryError::cancelled error is set; the resource’s status and error are left untouched. Use QueryKeyFilter::Exact(&key) to cancel a single key.
client.cancel_queries(&QueryKeyFilter::Exact(&key), cx);Mutation management
Section titled “Mutation management”register_mutation
Section titled “register_mutation”fn register_mutation<V, T, E>( &mut self, entity: &Entity<MutationResource<V, T, E>>, cx: &App,)Register an already-created mutation entity in the client’s (V, T, E) bucket. The three type parameters are: V (variables/input), T (success result), and E (error type). use_mutation calls this automatically, so you rarely call it by hand. The retry policy is set per mutation through MutationOptions (default no retries, override with .retry_policy(...)), not by the client.
all_mutations
Section titled “all_mutations”fn all_mutations<V, T, E>(&self) -> Vec<Entity<MutationResource<V, T, E>>>Return all mutation entities for a specific (V, T, E) type triple. Returns an empty vec if no mutations of that type exist.
Garbage collection
Section titled “Garbage collection”fn gc(&mut self, cx: &App)Collect idle query and mutation resources older than the client’s gc_time_ms, reading the clock itself. Resources with active requests are never collected: Loading mutations always survive, Success mutations survive twice the gc time, and Idle/Failure mutations survive the gc time (floored at 1 second during GC). There is no separate mutation GC pass; gc sweeps mutation buckets too. Call this periodically (every 30 seconds is reasonable).
let client = cx.global_mut::<QueryClient>();client.gc(cx);gc_with_time
Section titled “gc_with_time”fn gc_with_time(&mut self, now_ms: u64, cx: &App)Same sweep with a caller-supplied timestamp, for when you already hold a time value.
let client = cx.global_mut::<QueryClient>();let now_ms = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_millis() as u64;client.gc_with_time(now_ms, cx);Diagnostics
Section titled “Diagnostics”diagnostics
Section titled “diagnostics”fn diagnostics(&self, cx: &App) -> ClientDiagnosticReturn a Clone + Debug snapshot of the entire client state as plain data structs; implement your own serialization or logging on top. Useful for devtools panels or logging. This is the only diagnostics entry point on QueryClient; per-type and per-bucket counts are not exposed.
ClientDiagnostic contains:
| Field | Type | Description |
|---|---|---|
query_count |
usize |
Query and infinite-query resources across all type buckets |
mutation_count |
usize |
Total mutation resources |
queries |
Vec<QueryDiagnostic> |
Per-query details, covering both query and infinite-query resources; QueryDiagnostic has no field distinguishing the two |
mutations |
Vec<MutationDiagnostic> |
Per-mutation details |
How type partitioning works
Section titled “How type partitioning works”Rust’s type system treats Entity<QueryResource<User>> and Entity<QueryResource<Post>> as different types. You cannot store them in the same HashMap. QueryClient solves this by partitioning resources into type-specific buckets keyed by TypeId of (T, E).
Each bucket is stored as a type-erased Box<dyn ErasedBucket> trait object keyed by TypeId of (T, E); mutation buckets use the analogous ErasedMutationBucket. Both erased traits are crate-private implementation details, not public API. Bulk operations like invalidate_queries iterate across all buckets through the trait, without needing to know the concrete types. Typed access methods like resource::<User, MyError>() downcast to the correct bucket.
This means invalidate_queries with QueryKeyFilter::All will touch every query regardless of its data type, which is usually what you want after a logout or a global state reset.