Rust guide
Use the native Rust client for local-first sync in desktop apps, CLIs and services, with types generated from your schema.
spooky-core (lib spooky_core) is the native Rust client for sp00ky, for desktop apps, CLIs and
services. It runs the same engine as the TypeScript and Dart clients, so a Rust desktop app, a
Flutter app and a web tab sync the same rows the same way. Rows live in a local SQLite store, one
file per signed-in account: queries paint from it before the network answers and stay live as
anyone writes, and writes apply at once and sync through an outbox that survives restarts. The
engine runs on its own thread, so the client works from GPUI, smol, tokio or a plain block_on.
The crate is not on crates.io yet. Install it from git, and pin a rev for reproducible builds.
It needs Rust 1.85 or newer.
Install
Two features, both on by default: remote (the SurrealDB WebSocket transport; without it the client
is local-only) and codegen (schema to Rust, for build scripts). The generated code needs nothing
but spooky_core.
Generate types from the schema
The examples on this page use this schema, the same one tests/live_stack.rs runs against:
Generate Rust from it in a build script and include the output as a module:
The generated db.rs holds:
| Item | What it is |
|---|---|
schema(), SURQL_SCHEMA | The runtime schema and the SurrealQL for the local store, server-only (-- @nosync) fields stripped. |
config(DatabaseConfig) | A Sp00kyConfig for this schema. Start every client from it. |
Note, NotePatch | A serde struct per table (id plus every synced field) and an all-Option partial update. |
Note::rank, Note::owner, … | Typed field tokens: each only takes operands of its column’s type. |
AuthApi | sign_in_<access> / sign_up_<access> per DEFINE ACCESS, params as &str. |
Backends | One method per backend route, when you pass OpenAPI specs (see Backend jobs). |
AppDb | The facade: AppDb::new(client.clone()).note(), .auth(), .run(). |
record<..> fields are Strings holding table:id, datetime fields are spooky_core::typed::Datetime,
option<..> fields are Options.
Open the client
Sp00kyClient::open starts the engine thread and runs the local half of boot: the store opens, the
schema is provisioned, the circuit is restored from its snapshot and the cached session is restored.
It returns once a query registered next can paint from the local cache. Connecting, verifying the
session and registering queries with the server run in the background.
Without .endpoint(..) the client is local-only: writes and live queries work, nothing syncs. That is
also the quickest way to test your own code (see Tests). For a local spky dev stack the
endpoint is ws://127.0.0.1:8666/rpc.
The other knobs are public fields on the config:
| Field | Default | What it does |
|---|---|---|
database.store | StoreType::Memory | StoreType::File(path): sqlite files derived from path (spooky.db becomes spooky.<bucket>.db, one per account). |
database.max_concurrent_queries | 6 | Remote reads in flight at once. Writes go one at a time in a lane of their own. |
database.token | None | A token to authenticate with on connect. |
persistence | PersistenceConfig::Session | Where the boot hint and auth token live: a session database next to the store, or Memory. |
blob_cache | in memory, 256 MB | BlobCacheConfig { directory, max_bytes, clear_on_sign_out } for bucket files. |
stream_debounce_ms | 50 | Minimum gap between two re-materializations of one query. |
ref_sync_interval_ms | 500 | Base cadence of the membership poll. |
enable_anonymous_live_queries | false | Realtime sync while signed out. Must match the server’s anonymousLiveQueries. |
sync_health | degraded after 3 failures | SyncHealthConfig::DISABLED never reports degraded. |
reconnect | 15 s backoff cap, 20 s heartbeat | ReconnectConfig: backoff, heartbeat interval and timeout, connect timeout, and the 3 s probe after a wake(). |
circuit_checkpoint_ms | 30000 | How often a changed circuit is snapshotted to the store. |
channels | None | Peer to peer channels (see Channels). |
Authentication
sign_in and sign_up go through DEFINE ACCESS <access> with the params it declares. They resolve
after the account switch: that user’s local store is open and the registered queries run against it.
sign_out pushes queued writes first while the session is still valid.
auth_state() (and auth_watch()) carries the user id, the user row (current_user), the token, the
access method, is_loading, is_impersonating and a deferred verification_error (the restored
session stays usable). check_auth(None) verifies the session against the server now;
authenticate(token) / deauthenticate() drive the socket with a token from outside the client.
Expired and refused tokens
A token the server refuses, because it was revoked, is past its DURATION FOR TOKEN, or its session
is past DURATION FOR SESSION, signs the client out. The socket that was refused is closed rather
than kept open anonymously (an anonymous read of a user’s views comes back empty), the token is
dropped, and user_watch() turns to None, so the app can sign in again. While the server cannot be
reached, a restored session stays usable and is verified once it answers.
Signing in with a device key
A desktop app or a CLI should not keep the user’s password. Let your API issue a long-lived key once the user approves the device in the browser, keep it in the OS keychain, and give it a record access of its own with short sessions. A revoked key then stops at the next sign-in.
The app signs in with the key whenever it has no session, and again before the token runs out (its
exp claim, from client.token()):
Live queries
Build a query on a table, then live registers it and subscribes in one call. The query stays
registered, and its rows live, while the returned LiveQuery does.
A LiveQuery reads like a watch channel: the latest rows are always there, a slow consumer never builds
a backlog.
| Method | Returns |
|---|---|
rows() | Arc<Vec<Row>>, the latest rows. Row is a BTreeMap<String, Value>. |
rows_as::<T>() | The latest rows decoded into your Deserialize type. |
changed().await | Waits for the next change; Err(Error::Closed) once the client is gone. |
status() | QueryStatus::Fetching while bodies are being pulled, else Idle. |
is_authoritative() | True once server membership is known. Only then does an empty list mean “empty”. |
rows_watch(), status_watch(), authority_watch() | The underlying tokio::sync::watch receivers. |
into_stream() | The current rows, then every change, as a futures::Stream. |
Rows hold plain JSON shapes: record links are table:id strings and datetimes are ISO strings.
The builder covers filters, ordering, paging and joins. Conditions are AND-joined, one per field;
a repeated field replaces the earlier condition. String values for record<..> and datetime columns
are re-typed from the schema, so where_eq("owner", "user:ada") matches on the server.
.related(field) follows a relationship from the schema: a forward record<x> field joins one row
under the same name, the reverse direction joins a list. Use .related_with(field, |q| q.limit(5))
to shape the joined rows. .one() limits to one row, .select([..]) projects fields.
Raw SurrealQL
live_raw registers any SELECT the stream processor can run. Raw params are sent as given, so pass
record links as RecordId values. QueryOptions::ttl sets how long the server keeps the view after
the last subscriber leaves (10m by default).
query_raw registers without subscribing and returns the hash; subscribe(hash) attaches a
LiveQuery to it later. preload_query(builder) (or preload(sql, params, options)) prewarms a query:
it returns at once when the query resolved before on this device, otherwise once the server’s
membership and every row are local. query_remote(sql, vars) is a one-shot server read that is not
synced into the local store: use it for counts and other reads a view cannot express. For a read a
screen is waiting on (a search box, a detail lookup) use query_interactive(sql, vars): the same
call, in a small pool of its own that never queues behind the sync’s registrations and row fetches.
Typed rows
rows_as decodes into any Deserialize type, your own or a generated one:
The generated AppDb adds typed filters and writes. Its query() gives a TypedQuery that
client.live_typed(..) runs:
AppDb writes go through the TypedClient trait, whose futures are not Send. Await them in place
(a GPUI task, block_on, a tokio::main body or a LocalSet), not inside tokio::spawn. The plain
client methods (client.create(..) and friends) are Send.
Writes
create, update and delete are optimistic: the row changes in the local store and in every live
query before the call returns, and the write is queued in the outbox, which is pushed in order in the
background and survives restarts. Record ids are full table:key strings; spooky_core::value::generate_id()
makes a fresh key.
Writes take anything IntoObject: a serde_json::json!({..}) object, a serde_json::Map, or an
Object. spooky_core::to_object(&value) turns your own Serialize type into one. A record<..>
field may be given as its table:id string: the schema re-types it before it reaches the server.
update merges the given fields into the row. read_row(id) reads one row as the local store holds it.
Debounced updates
For a text field saved as the user types, fold rapid updates into one outbox write:
A debounced update applies locally at once, then writes the merged patch after the pause (300 ms by
default). By default one write is kept per record and set of fields (DebounceKey::RecordIdXFields);
DebounceKey::RecordId keeps one per record.
Failed writes
A write the server rejects is undone locally and parked in a tray, so the app can show it and let the user retry or drop it:
Each FailedMutationRow has the mutation type, the record id, the data, the row as it was before
(before_record), the error (message and kind), the attempt count and how much was reverted.
retry_failed_mutation(id) re-applies it as a new optimistic write; discard_failed_mutation(id) drops it.
Sync indicators
Every indicator is a value you can read now plus a tokio::sync::watch receiver for every change
after. Watch receivers need no tokio runtime on your side, so they work on any executor.
| What | Now | Every change |
|---|---|---|
| Sync health (the “can’t reach the server” banner) | sync_health() | sync_health_watch() |
| Queued writes | pending_mutation_count() | pending_mutations_watch() |
| Queries a user waits on | fetching_query_count() | fetch_activity_watch() |
| Rejected writes | failed_mutation_count() | failed_mutations_watch() |
| Records with unacknowledged writes | unsynced_record_ids() | unsynced_records_watch() |
| Signed-in user / auth session | user_id() / auth_state() | user_watch() / auth_watch() |
SyncHealth has status (Healthy or Degraded), consecutive_failures, kind (network or
application) and error while degraded, ever_connected, and connection (the socket’s own
state, independent of health). client.events() is a broadcast of every engine event
(records, statuses, mutations, health, logs) for diagnostics; a slow receiver skips.
See Offline & sync health for what each signal means.
Buckets
read goes through the blob cache: a warm read never touches the socket. Give
BlobCacheConfig::directory a path to keep files on disk between runs; without one the cache is in
memory. Files never expire by age: the least recently used go past max_bytes, files are kept per
signed-in user, and put / delete on a path invalidate it. get always reads the server,
evict(path) drops the cached copy, and client.blob_cache_stats() reports hits, misses and size.
Buckets need a remote endpoint; see File buckets for defining them.
Feature flags and releases
feature(key, fallback) is live: variant() is the assigned variant, or the fallback while the user
has none, enabled() is true for any variant other than off, and payload_as::<T>() decodes the
flag’s payload. app_release(app) watches the latest release announced for app; update_available
compares it with your version. Both need a remote endpoint and stay live while the handle lives. See
Feature flags and
Telling clients a new version shipped.
Backend jobs
run(backend, path, payload, options) enqueues a job for a backend: a row in the backend’s outbox table,
written through the same optimistic path as any other write, so it queues while offline.
The backend must be in the client schema. Pass its OpenAPI spec to codegen, which also generates a
typed method per route (app.run().api().spookify(..)): required args are plain parameters,
optional ones Options.
RunOptions sets assigned_to, max_retries, retry_strategy, timeout and delay (ms). See
Add a backend for the server side.
Peer to peer channels
Channels are experimental. The Rust client speaks the same wire protocol as the web and Flutter clients, so all three connect to each other.
Tables marked -- @channel can carry writes straight between devices over WebRTC, so a peer’s change
(a cursor, a chat message, a move) shows up before the server has it. The core has no WebRTC stack of
its own: the app adapts one (webrtc-rs, libwebrtc bindings, …) to the RtcPeerConnection and
RtcDataChannel traits in spooky_core::modules::channel and hands the factory in through the config.
Without a factory (or a custom transport) channels report ChannelStatus::Unsupported.
Open a channel with the queries whose rows it carries and the users it connects to. Only the queries’
where counts, evaluated against each row; they are never registered. A connection forms only when
both sides list each other, your own id is skipped, and the transport starts once a user is signed in.
Plain client.update(..) on a matching row reaches the peers of every open channel whose filter the
row matches; channel.create/update/delete reach that channel’s peers only. -- @ephemeral fields
travel between peers and never reach the database. The channel closes when dropped.
channel.set_peers(..) and channel.set_queries(..) change it in place. See
Peer to peer channels for the model, accept rules and TURN servers.
Your own devices
ChannelsConfig::share sends this user’s optimistic writes straight to their other devices through
the room relay, whatever those run: a Rust app, a browser tab and a Flutter
app of one user sit in one room. It needs no -- @channel mark and no WebRTC stack, only the
default remote feature.
share("note")shares every row of the table,share_rows("task", |row| ..)only the rows the test passes (asked on the device that writes and on the one that receives). A table not named is not shared.- A device is only sent writes its live queries can show. Prefer
live(query)overlive_raw: raw SurrealQL counts as showing every shared row. client.share_state()andshare_state_watch()report the link:Connectedwhile another device of the user is in the room,Connectingwhile alone,Failedwhen the relay refuses or cannot be reached,Unsupportedwithoutrelayor without theremotefeature.- A native client always talks through the relay. The direct link two browsers open between themselves is for browsers.
See Your own devices for what is sent and why.
Native push
Native push is experimental. The core registers the device with the server; getting the device token from APNs or FCM is up to the app.
Call client.push() once at startup: the first call installs the sign-out hook that unregisters this
device while the session is still valid. register stores the device for the signed-in user and
remembers the choice; sync (call it on every launch) brings the server in line after a token rotation
and never fails, it answers a PushSyncStatus. unsubscribe(all), update(changes), devices(),
notify(message), cancel(id) and test(title, body) cover the rest. Errors are PushError with a
code (SignedOut, Disabled, NotSubscribed, Server, …). A client without an endpoint answers
every call with PushErrorCode::Server. See Native push for the server setup.
Lifecycle
The core cannot see the network or the app’s lifecycle, so the app reports both:
wake()on a resume or a returning network: reset the reconnect backoff and probe the socket now. A socket that died during a sleep is replaced within about 3 s (ReconnectConfig::wake_probe_timeout_ms).set_offline(true)when the OS reports no network: apreloadthat never resolved on this device returns at once instead of waiting for the server, so an app holding its first screen on it still opens. Report it before the firstpreload.checkpoint().awaitwhen the app goes to the background: snapshots the circuit so the next boot restores it instead of re-reading every row. The client also checkpoints on its own (5 s after boot, then everycircuit_checkpoint_ms), and it is free when nothing changed.detach().awaitwhen this install goes away for good: hands its views back to the server instead of leaving them to expire.close().awaitbefore the process exits.
Dropping the last Sp00kyClient handle closes the client in the background, and a process that exits
right after may kill the engine thread before the snapshot is written. Await client.close() before
main returns.
GPUI and other executors
The engine never runs on your executor. Sp00kyClient talks to its thread over a channel, so any
async runtime can await it, and a UI thread never blocks on sqlite or the socket. In GPUI, hold the
client in your app state and pump a LiveQuery from a foreground task:
The same works with no async runtime at all:
client.live(..) returns a Send + 'static future, so you can build it on one thread and await it on
another. A LiveQuery is Send too: hand it to a background task with tokio::spawn if that is
where your app lives.
The in-process engine
spooky_core::Engine is the engine itself, without the thread: single-threaded on a tokio LocalSet,
with the same calls returning non-Send futures and callback subscriptions. Use it when you already own
a LocalSet (tests, embedding in a single-threaded runtime).
Engine::open returns an Rc<Engine>. Its builder is bound to the engine, so query(..).run(ttl)
registers and query(..).subscribe(ttl, cb) registers and watches in one call; TypedQuery::watch
works the same way. Writes take an Object (use object_from_json(json!(..))), close() returns
nothing, and the generated AppDb drives Sp00kyClient only.
Tests
Inside your app, a local-only client (no endpoint, memory store, memory persistence) is a full engine with no server: writes land and live queries see them.
The crate’s own suite runs from the monorepo:
tests/live_stack.rs signs up two clients of one user against a running stack and checks that
creates, edits, ordering and deletes reach the other client live. It is skipped unless
SPOOKY_IT_ENDPOINT is set, and the stack’s database (SPOOKY_IT_NS / SPOOKY_IT_DB, default main /
rustcore) must hold the schema at the top of this page. tests/ws_client_live.rs tests the raw
WebSocket transport against a plain SurrealDB (SURREAL_IT_ENDPOINT), and the codegen goldens are
refreshed with SPOOKY_UPDATE_GOLDENS=1.