kovlet
Sync your Rust app's data with every other app on the same Kovlet Data Space. The person signs in once, your app keeps working offline, and changes from other apps arrive live. Your own database stays the source of truth.
This crate is also the engine behind the Swift and Kotlin packages and tauri-plugin-kovlet.
[]
= "0.1"
The crate re-exports serde_json, so kovlet::serde_json::json! works without adding it yourself. On Android, Windows, or Linux without libsqlite3-dev, add features = ["bundled-sqlite"].
Quick start (built-in store)
use ;
async
You should see
- On the first run, a line like
Open https://kovlet.com/activate and enter ABCD-1234. Approve it in any browser. Later runs skip this step.- The
Buy milkrow, printed straight away. The write doesn't wait for the network.- The status moving through
connectingandsyncingtolive. The row now shows in every other app on theTodosData Space.
A Data Space is a shared container of tables and files that several apps sync. find_or_create finds the one named Todos that this app can reach, or creates it.
How it works
The core signs in and keeps the session fresh. It holds one WebSocket per Data Space and reconnects with backoff. It uploads and downloads files.
Every change merges field by field: when two apps write the same field, the later write wins, judged by a hybrid logical clock (HLC) stamped on each change. Your writes wait in an outbox until the server acknowledges them.
Your app's database stays the source of truth. You implement one method, DataStore::apply, or use the built-in store. The core keeps only its bookkeeping: clocks, the outbox and a cursor into the space's history.
Live queries, atomic writes and end users (protocol 2)
The client speaks sync protocol 2 by default: one socket per space carries many subscriptions. A server that refuses protocol 2 gets protocol 1, remembered for a day. Client::builder(..).protocol(1) pins protocol 1.
use ;
// A live query (protocol reference §17). On a full replica it runs locally; open the
// space with `open_query` to hold only the rows your subscriptions match.
let open = space.subscribe?;
let result = open.rows?; // built-in store: { data: { todos: [..] }, page_info }
let _watch = open.observe?;
// All or nothing: applies locally at once, rolls back as one unit if the server rejects it.
let tx = space.transact?;
tx.settled.await?;
// End users of a public app: email codes, OAuth, ID tokens, guests.
let auth = kovlet.end_users;
auth.send_magic_code.await?;
auth.sign_in_with_magic_code.await?;
Client::open_query(space_id, tables, store)keeps a partial copy of the space. Rows no subscription holds any more reach your store asChange::Purge, unless a local write to them is pending or awaits judgement.- Subscriptions persist across restarts and resume from their last cursor.
LiveQuery::unsubscribeends one. space.query(&q)runs a query once over the built-in store, with the same matcher as the server.space.query_remote(q, params)asks the server.- A rejected batch takes along queued writes to rows it created (
dependency_rejected), and arrives asEvent::Transaction { status: "rejected", .. }.quota_exceededholds it;internalandrate_limitedretry it. On protocol 1 a batch is refused withunsupported_protocol. - End users always sync over protocol 2 with query subscriptions, filtered by the space's rules. Signing out, or another end user signing in, forgets every open space's synced rows, clocks and queued writes.
ClientBuilder::as_end_user(id)lets a machine session act as an end user.
Your own SQLite database
SqliteStore::shared puts Kovlet's tables in your database file. It runs your apply and its own bookkeeping in one transaction:
use ;
use ;
use ;
let db = new;
let store = new;
let space = kovlet.open?;
space.write.upsert?; // write-through
space.record?; // or: inside your own transaction (record mode)
open takes the store by value or as an Arc<SqliteStore>. Keep the Arc if you'll need the store again, for example for forget_space below.
SqliteStore::shared_batch(db, |tx, batch| …) is the same with one call per batch. Save the batch in one go, use change.table() and change.id(), and check batch.complete to know a full snapshot is in.
If your database type owns its connection and keeps derived state on write (indexes, totals, history), lend it one transaction at a time instead. Rows, derived state and Kovlet's bookkeeping then commit together, and space.record(&tx, …) works inside your own with_tx:
let lender = db.clone;
let store = lending?;
Writes from inside your storage layer, and batches
space.write(…) takes the space's merge lock and calls your DataStore on the calling thread. So it must not run while you hold a lock your apply needs. From inside your own storage layer (with your database lock held), queue the write instead:
use LocalWrite;
space.queue?; // durable when it returns
space.write.upsert_many?; // many rows, one transaction
queuestores the writes in Kovlet's own store in one transaction and returns. It never takes the merge lock or calls yourDataStoreon your thread.- A Kovlet worker then merges the writes and calls
applywithorigin: localshortly afterwards. Your store sees them then, in queue order. - Queued writes survive a crash and sync after a restart.
space.queued()counts writes not merged yet, andspace.flush_queue()merges them now.
Any other store implements kovlet::DataStore and is passed as SpaceStore::data(store). kovlet::testing::check_data_store checks a store against the contract: fields are patches, trashed rows keep their values, apply is idempotent, and changes arrive in order.
Linking a database that already has rows
// "Stop syncing": Kovlet forgets the space's cursor, clocks and queued writes. Your rows stay.
kovlet.close_space;
kovlet.forget_space?; // `store` is the Arc<SqliteStore> from above; refused while the space is open
// Link again (or link another database): upload only the rows the space doesn't have.
let space = kovlet.open?;
space.seed?; // (id, fields) pairs
The core decides which rows the space has when the first snapshot finishes, in the same transaction. Newer edits from other devices win over your older copies, and a new, empty space gets every row. Calling seed again with the same rows queues nothing new.
Sign-in
SignIn:: |
For |
|---|---|
device(on_code) |
CLIs and desktop apps. Uses a P-256 device key, so the session refreshes itself, and signing in again keeps the same machine. |
pkce(redirect_uri, authorize) |
Apps that can open a browser, with a loopback (http://127.0.0.1:<any port>/…) or private-use scheme (com.example.app:/cb) redirect. Or call client.pkce_begin and pkce_finish yourself. |
machine_key(key, client_id) |
Unattended servers. |
token(token) |
A token from kovletd dev seed. |
Device proofs, refresh-token rotation and device_revoked handling are built in. Tokens live in the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret Service). Where there is none, they go in 0600 files under data_dir.
Files
space.files() returns the space's Files:
use Path;
let files = space.files;
let scan = files.put?; // staged now, uploaded in the background
let pdf = files.put_file?; // streams from a local file
files.move_to?;
files.delete?; // to the Trash
files.restore?;
let local = files.all?; // metadata in the built-in store
let remote = files.list.await?; // metadata on the server, under a prefix
files.download.await?; // checked against its SHA-256
putandput_filereturn aFileState(id,path,sha256,size_bytes,mime_type,version, …). PassSome(id)to write a new version of an existing file; otherwise the file gets a new UUIDv7.- Writes are staged locally and uploaded in the background, so they work offline.
Mirror a folder
Apps that keep attachments as files in a folder can hand the whole sync to the core:
// Once, after opening the space: `attachments/<name>` in the space ↔ `<app_dir>/attachments/<name>` on disk.
let attachments = space.files.mirror?;
// At each place the app writes a new file into the folder:
attachments.notify_added?; // or an absolute path inside the folder
- The first pass uploads the files the space lacks and downloads the ones the folder lacks. After that, files other clients add or change are downloaded as they arrive. All of it runs on the core's runtime, not on the caller's thread.
- Files match by path and SHA-256. Mirroring the same folder again, after a restart or a re-link, uploads nothing twice. A changed local file becomes a new version of the same file record.
- When both sides changed a file, the newer one wins: the local file's modification time against the space file's HLC.
mirror.status()andwatch_status()reportready(first pass done),busy, upload and download counts, and the last error. A failed pass is retried with backoff, and again on every reconnect. Dropping the lastMirrorclone stops it.
Not handled for now: deletes and moves in either direction (a file removed on one side stays on the other), symlinks, and dot-files in the folder (.DS_Store and the like are never uploaded).
Offline
A signed-in app works offline from a cold start:
spaces().list()andfind_or_createfall back to the last list the client saw, markedoffline: true.- Cached rows stay readable, and writes queue in the outbox.
- Sync resumes with backoff when the server is back.
Lifecycle
client.pause(grace).awaitwhen the app goes to the background.client.resume()when it comes back.client.sync_once(deadline).awaitfrom a background task.
Features
| Feature | Default | What |
|---|---|---|
transport-native |
yes | tokio-tungstenite and ureq over rustls, with the platform certificate verifier |
sqlite |
yes | SqliteStore, the built-in store and record mode |
bundled-sqlite |
no | Compile SQLite in. Use it on Android and Windows, or on Linux without libsqlite3-dev. |
os-keychain |
yes | The OS keychain as the default secret store. Linux needs libdbus-1. |
Conformance
The crate passes every scenario of Kovlet's client conformance suite (protocol §14), protocol 2 included, with both the memory and the SQLite store. It skips only the rooms-* scenarios, because it doesn't implement rooms.
Its adapter is examples/conformance.rs. From the crate's source directory, with kovletd on your PATH:
KOVLET_CONFORMANCE_STORE=sqlite
examples/live.rs is an end-to-end smoke test against a real kovletd --dev --dev-auto-approve.
Links
- kovlet.com: sign in, create Data Spaces and manage connected apps.
- Documentation: quickstarts, guides and the reference. The Tauri quickstart uses this crate.
- Sync protocol reference.
- Terms and Privacy Policy of the hosted service at kovlet.com.
MIT licensed.