Zero for Rust
A native Rust client for Zero. Your app queries a local replica of the server's data, and the replica stays in sync. Mutations apply to the replica right away and run again on your server, whose result wins.
It's a port of the JS client (@rocicorp/zero) and behaves the same:
conformance vectors generated from the JS client check it, and so do
end-to-end tests against zero-cache and Postgres.
[!NOTE] Before 1.0, minor versions may change the API.
Install
Rust 1.88 or later, and a zero-cache that speaks sync protocol 57 (Zero
1.12 or later). zero-rust codegen generates a row struct per table, the
schema, a typed query builder (zql), and typed CRUD for mutators
(mutate) from your TypeScript schema; --check fails in CI when the
output is stale.
Quick start
Write the queries and mutators your app runs in Rust, named as in your
TypeScript defineQueries and defineMutators: the client runs them on
the replica, and zero-cache has your server run the TypeScript ones.
use ;
use Rc;
use ;
use ;
use ;
use Ttl;
use Direction;
// from `zero-rust codegen`
use ;
/// What queries and mutators get besides their arguments.
type Context = ;
const OPEN_ISSUES: =
define_query;
const CLOSE_ISSUE: =
define_mutator;
// The client is single-threaded: make it, and call it, on a tokio `LocalSet`.
let zero = new?;
// Rows read as `Issue`s and kept current, until `issues` drops.
let issues = zero.live?;
let _remove = issues.add_listener;
// Applies to the replica before it returns, then runs on your server.
let result = zero.mutate_request;
// Every mutation's server outcome, in one place.
let _remove = zero.add_mutation_outcome_listener;
// `NeedsAuth` when the server rejects the token: get a new one, then connect with it.
let _unsubscribe = zero.connection.subscribe;
zero.connection.connect?;
API at a glance
The API reference documents every item. An
app uses client, define, typed (through generated code), ttl, and
testing.
| Concept | API | Notes |
|---|---|---|
| Client | Zero::new(schema, context, mutators, options, scheduler, socket_factory)? |
Not Send: one thread |
| Options | ZeroOptions { cache_url, user_id, auth, storage, mutate_url, query_url, log_level, .. } |
JS's options in snake case |
| Named queries | define_query(name, |args, ctx| query), called as Q.with(args) |
serde feature |
| Query builder | zql::issue(), .where_eq, .where_expr, .where_exists, .related, .order_by, .limit, .one |
Also count, sum, group_by, distinct |
| Read, kept current | zero.live(&query, &ttl)?, a LiveView<T>: value(), result_type(), error(), add_listener |
useQuery; dropping it destroys the view |
| Read otherwise | materialize(&query, &ttl)?, run(&query, RunType::Complete, None), preload(&query, &ttl) |
Untyped view, read once, sync without a view |
| Named mutators | define_mutator(name, |tx, args, ctx| ...), registered as M.mutator() |
Synchronous; runs again on each rebase |
| Writes in mutators | mutate::issue(tx).insert(&row)?, .upsert, .update, .delete; tx.run(&query)? |
Generated |
| Mutate | zero.mutate_request(M.with(args)), a MutatorResult with client and server outcomes |
zero.mutate(name, json) untyped |
| Server outcomes | zero.add_mutation_outcome_listener(|o| ...) |
Also hears mutations replayed after a reconnect |
| Connection | connection().state(), .subscribe(listener), .connect(ConnectAuth::Keep | Set(token) | Clear)? |
NeedsAuth when the server rejects the token |
| Background | set_visible(false), then hidden_disconnect_delay_ms |
5 minutes, as in JS; 0 on mobile |
| Storage | ZeroStorage::Memory (default), Sqlite { directory }, Custom; flush_storage(), delete() |
client::drop_all_databases |
| Inspector | zero.inspector(): metrics(), client().queries(), analyze_query(..), server_version() |
Logs slow materializations past slow_materialize_threshold_ms |
| Testing | testing::{ManualScheduler, MockSocketFactory, RecordingLogSink} |
A client without a server |
Features
The default build has no dependencies. Each of these is opt-in:
| Feature | Adds |
|---|---|
tokio-transport |
tokio_transport: a scheduler and a WebSocket transport on tokio |
tls |
wss:// for that transport, with rustls on ring |
sqlite |
ZeroStorage::Sqlite, on the system libsqlite3 |
sqlite-bundled |
sqlite, with SQLite compiled in |
serde |
define: typed define_query and define_mutator, and serde for json::Value |
Without the sqlite feature the client keeps nothing across restarts:
the default storage is memory only, so a restarted app starts with no
synced rows and no pending mutations. Without tokio-transport, bring your
own event loop with client::Scheduler and client::SocketFactory.
Differences from JS
- One thread.
Zerois neitherSendnorSync; it runs on your event loop (a tokioLocalSetwithtokio-transport). Views are current whenmutatereturns. - Queries and mutators are written in Rust, under the TypeScript names.
Mutators are synchronous functions. CRUD mutators
(
zero.mutate.issue.insert) aren't ported: write a mutator. - Storage defaults to memory, where JS uses IndexedDB.
- Background: the app calls
set_visible. The client disconnects afterhidden_disconnect_delay_mshidden, 5 minutes as in JS; a mobile app the system suspends sets 0. - No UI bindings.
LiveViewis the typeduseQuery, with listeners a UI wakes itself from. - An unnamed query only sees local data, as in JS without
enableLegacyQueries: the server syncs adefine_queryrequest.
PARITY.md maps each part of the JS API to its Rust name, and lists what isn't ported and each documented difference.
Compatibility
| zero-client | Sync protocol | zero-cache |
Conformance vectors from |
|---|---|---|---|
| 0.1+ | 57 | 1.12+ | Zero 1.12 |
A Zero 1.11 zero-cache rejects protocol 57 with VersionNotSupported.
Documentation
- Zero's docs, and for coding agents llms.txt
- API reference on docs.rs
- Coming from the JS client
- Benchmarks against the JS and Swift clients, and the design
- Example apps on one shared model
(
apps/zbugs-model):zbugs-runeandzbugs-gpui
Contributing
This directory is published from wevm/zero
(rust/); send changes there. From rust/ in that repository:
License
Apache-2.0