swr-rs
UI-agnostic stale-while-revalidate async cache for Rust, aligned with the
semantics of SWR and TanStack Query. The core is a
headless SwrClient over a pure synchronous state machine (sans-io); async
runtimes and UI frameworks plug in as thin layers.
Crates
swr— the batteries-included entry point: re-exports the fullswr-coreAPI and picks the default runtime per platform (swr::client()).swr-core— state machine, cache, and the public client API. Compiles on native andwasm32-unknown-unknown.swr-runtime-tokio— tokioRuntimeimplementation for native targets.swr-reqwest— reqwest fetchers:JsonFetchermaps cache keys to HTTP requests with JSON decoding (reqwest::Erroras the query error type).swr-ureq— the same for the blocking ureq client, bridged onto per-request worker threads (runtime-agnostic;ureq::Erroras the query error type). This worker-thread + oneshot bridge is the general answer for any blocking fetcher —Runtimedeliberately has nospawn_blocking, which would tie the core to tokio.swr-gpui— GPUI adapter:GpuiRuntimeruns fetches/timers on GPUI's executors (no tokio needed; virtual-clock test support viaadvance_clock), andQuerybridges watch changes into an entity that views observe and read lock-free during render. Seecrates/swr-gpui/examples/status.rs.swr-runtime-web— browserRuntime(spawn_local+setTimeouttimers) plus a reference-counted focus/online event source (WebEventSource::attachforwardsfocus/visibilitychange/onlinetoSwrClient::broadcast). wasm32-only; an empty crate on native targets.
Usage
use ReadPolicy;
async
async
To supply your own [Runtime] (clock/spawn/timers), depend on swr-core
plus a runtime crate directly and use SwrClient::builder().
Fetchers are plain closures, so any HTTP client works inline. For reqwest
(swr-reqwest) and ureq (swr-ureq, same shape), the integration crates
remove the boilerplate:
use JsonFetcher;
let users: =
get;
let user = client.fetch.await?;
A fuller walkthrough (caching, background refresh, optimistic mutation, prefix
invalidation) is in crates/swr-runtime-tokio/examples/bff.rs:
Development
# wasm smoke tests; needs wasm-bindgen-cli matching the locked
# wasm-bindgen version, plus Node for smoke.rs / a browser for browser.rs
CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER=wasm-bindgen-test-runner \