# API Reference

A flat index of the public types, hooks, and functions gpui-query exports

A compact index of the public surface, grouped by the crate's four layers. Import hooks and common types from the crate root; import layer-specific items from `gpui_query::core`, `gpui_query::client`, or `gpui_query::hook`. Persistence types live under `gpui_query::client` behind the `persist` feature.

```rust
// Hooks and common types at the crate root:
use gpui_query::{
    use_query, use_mutation, use_infinite_query, use_query_select,
    QueryOptions, InfiniteQueryOptions, MutationOptions, MutationCallbacks,
    QueryKey, QueryKeyFilter, QueryError, QueryErrorKind, QueryStatus,
    CachePolicy, RequestPolicy, RetryPolicy, QueryClient,
};
```

## core: Serde-only state machine

The `core` layer has no GPUI dependency. Everything here is `Serialize + Deserialize` (unless noted) and safe to persist.

### Keys and filters

| Item             | Kind    | Notes                                                |
| ---------------- | ------- | --------------------------------------------------- |
| `QueryKey`       | struct  | Hierarchical cache key, `Arc<[Arc<str>]>`-backed.   |
| `QueryKeyFilter` | enum    | `Exact(&k)` / `Prefix(&k)` / `All`. Used by bulk ops. |

### Policies and status

| Item              | Kind   | Notes                                              |
| ----------------- | ------ | ------------------------------------------------- |
| `CachePolicy`     | enum   | `NoCache` / `Ttl { ttl_ms }` / `StaleWhileRevalidate { ttl_ms, stale_ms }`. |
| `RequestPolicy`   | enum   | `LatestWins` (default) / `IgnoreWhileLoading`.    |
| `RetryPolicy`     | struct | `max_retries`, `retry_delay_ms`, `exponential_backoff`, `max_retry_delay_ms`. |
| `QueryStatus`     | enum   | `Idle` / `LoadingEmpty` / `LoadingWithData` / `Success` / `Failure` / `Cancelled`. |
| `MutationStatus`  | enum   | `Idle` / `Loading` / `Success` / `Failure`.        |
| `QueryFetchMode`  | enum   | `Normal` / `Force`.                                |
| `QueryBeginResult`| enum   | `Started` / `CacheHit` / `StaleCacheHit` / `IgnoredWhileLoading`. |
| `RequestId`       | struct | Monotonic per-resource request id.                 |
| `QuerySignal`     | struct | Cooperative-cancellation signal handed to fetchers. |

### Errors

| Item             | Kind   | Notes                                            |
| ---------------- | ------ | ----------------------------------------------- |
| `QueryError`     | struct | Default error type. `Display + Error`, `Arc<str>` message. Constructors: `response` / `transport` / `cancelled` / `unknown` / `sanitized`. |
| `QueryErrorKind` | enum   | `Cancelled` / `Response` / `Transport` / `Unknown`. |

### Resources

| Item                      | Kind   | Notes                                            |
| ------------------------- | ------ | ----------------------------------------------- |
| `QueryResource<T, E>`     | struct | The core cached resource. Accessors: `data`, `error`, `status`, `key`, `cache_policy`, `retry_count`, `last_updated_at_ms`, … |
| `MutationResource<V,T,E>` | struct | One mutation's lifecycle.                        |
| `InfiniteQueryResource<T,E>` | struct | Pages + pagination state. `pages`, `page_count`, `has_next_page`, `is_fetching_next_page`, … |
| `SelectTransform<T, U>`   | struct | `Fn(&T) -> U` wrapper for derived views.         |
| `MappedQueryResource<T,U,E>` | struct | A derived view applying a `SelectTransform`.   |

## client: GPUI registry

| Item                | Kind   | Notes                                            |
| ------------------- | ------ | ----------------------------------------------- |
| `QueryClient`       | struct | `Global` registry. `resource`, `query`, `get_query_data`, `set_query_data`, `with_query_data`, `invalidate_queries`, `cancel_queries`, `reset_queries`, `remove_queries`, `prepare_fetch_query`, `prepare_prefetch_query`, `gc`, `gc_with_time`, `diagnostics`. **Persistence (`persist`):** `persist_with`, `collect_persist_snapshot`, `register_serializer`, `register_deserializer`. |
| `Observer<R>`       | struct | Generic status-deduplicating observer.          |
| `QueryObserver<T,E>` | alias  | `Observer<QueryResource<T, E>>`.                |
| `InfiniteQueryObserver<T,E>` | alias | `Observer<InfiniteQueryResource<T, E>>`.     |
| `MutationObserver<V,T,E>` | alias | `Observer<MutationResource<V, T, E>>`.       |
| `ObserverConfig`    | struct | `notify_on_status_change_only` (default `true`). |
| `Persister` (`persist`) | trait | Async backend: `async load() -> Result<PersistSnapshot, PersistError>`, `async save(&PersistSnapshot) -> Result<(), PersistError>`. Non-object-safe; consumed generically by `persist_with`. |
| `PersistSnapshot` / `PersistedEntry` (`persist`) | structs | Value-carrying snapshot: `value` (`serde_json::Value`), `cached_at`, `cache_policy`, `meta`. |
| `PersistOptions` / `PersistFilter` (`persist`) | struct / enum | `persist_with` tuning: `filter` (`Exact` / `Prefix` / `All`), `max_age`, `debounce`. |
| `PersistHandle` / `NoopPersister` (`persist`) | struct / struct | Drop-guard from `persist_with` (drop stops new saves) / no-op backend for tests. |
| `SerializerRegistry` (`persist`) | struct | Typed `T -> serde_json::Value` registry driving snapshot collection. Register serializers *and* deserializers via `QueryClient::register_serializer` / `register_deserializer`. |
| `PersistError` / `PERSIST_VERSION` (`persist`) | enum / const | `Io` / `Serialize` / `Deserialize` / `VersionMismatch` / `BadPath` / `Permission`; snapshot format version (`1`). |
| `hydrate` (`persist`) | free fn | `async hydrate(client, &persister, &filter, max_age, cx) -> Result<PersistSnapshot, PersistError>`; cold-start restore. |
| `Fetched<T>` (`core`; meta under `persist`) | struct | Fetcher return wrapper for server-derived cache policy: `new`, `with_policy`, `with_meta`. |
| `PreparedFetch<T,E>` | struct | Imperative fetch handle: `entity`, `signal`, `request_id`, `now_ms`. |
| `QueryDiagnostic` / `MutationDiagnostic` / `ClientDiagnostic` | structs | DevTools snapshot types. |
| `DehydratedState` / `DehydratedEntry` | structs | Legacy metadata-only snapshot (the `dehydrate`/`restore` skeleton). Prefer the value-carrying `persist` types above. |
| `QueryPersister` | trait | Legacy sync persister (`load -> Vec<DehydratedEntry>`, `save(Vec<DehydratedEntry>)`). Superseded by `Persister`. |

## hook: Ergonomic subscriptions

All hooks return `(Entity<Resource>, Subscription)` (or a triple for `use_query_select`). Store both.

| Item                       | Returns                                                    | Notes                                   |
| -------------------------- | ---------------------------------------------------------- | --------------------------------------- |
| `use_query`                | `(Entity<QueryResource<T,E>>, Subscription)`               | Primary query hook, signal-always.      |
| `use_query_manual` / `_opts` | same                                                       | Lower-level: explicit params.           |
| `use_query_unsignalled` / `_opts` | same                                                | Fetcher takes no signal (legacy).       |
| `use_query_select`         | `(Entity<MappedQueryResource<T,U,E>>, Entity<QueryResource<T,E>>, (Subscription, Subscription))` | `select` pattern. |
| `use_infinite_query`       | `(Entity<InfiniteQueryResource<T,E>>, Subscription)`       | Pagination / load-more.                 |
| `fetch_next_page_infinite` | `()`                                                       | Grow an infinite query forward.         |
| `fetch_previous_page_infinite` | `()`                                                   | Grow an infinite query backward.        |
| `fetch_query` / `fetch_query_with_signal` | `()`                                           | Refetch on demand.                      |
| `use_mutation`             | `(Entity<MutationResource<V,T,E>>, Subscription)`          | Primary mutation hook.                  |
| `use_mutation_state`       | `Vec<Entity<MutationResource<V,T,E>>>`                     | All mutations of a type triple.         |
| `mutate`                   | `()`                                                       | Trigger with owned `V`.                 |
| `mutate_with_callbacks`    | `()`                                                       | Trigger + lifecycle callbacks.          |
| `mutate_by_ref`            | `()`                                                       | Trigger, mutator borrows `&V`.          |
| `mutate_arc`               | `()`                                                       | Trigger with shared `Arc<V>`.           |

## Companion crates

Two crates ship alongside `gpui-query` and publish independently:

| Crate | Purpose |
| ----- | ------- |
| `gpui-query-persist` | Reference disk `Persister`: `FilePersister` (atomic write, tolerant load), `PersistFormat::Json` / `Bincode`, `NoopPersister`. See [Persistence: reference adapter](/docs/guides/persistence#reference-adapter-filepersister). |
| `gpui-query-http` | HTTP cache headers → `CachePolicy`: `cache_policy_from_headers` (RFC 9111), `HttpCache<B>` over an `HttpBackend`, `CacheMeta` (ETag / `If-Modified-Since`), optional `ReqwestBackend`. See [HTTP cache headers](/docs/guides/http-caching). |

## Feature flags

The four layers are gated behind feature flags so you can compile only what you need:

| Flag     | Enables                                            |
| -------- | -------------------------------------------------- |
| `core`   | The Serde-only state machine (no GPUI dep).        |
| `client` | `QueryClient`, observers, devtools.      |
| `hook`   | `use_query` / `use_mutation` / `use_infinite_query` and friends. |
| `persist` | Async persistence: `Persister`, `persist_with`, `hydrate`, the (de)serializer registries. Adds `serde_json` + `thiserror`. |

`docsrs` enables `#[doc(cfg(...))]` gating on docs.rs builds so the rendered API docs annotate each item with its feature gate.

## Next steps

- The detailed pages in the sidebar cover each of these in depth. Start with [Queries](/docs/api/queries).
- For the full item-level documentation, build the Rust API docs with `cargo doc -p gpui-query --open`.
