kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
# 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`](https://crates.io/crates/tauri-plugin-kovlet).

```toml
[dependencies]
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)

```rust
use kovlet::{col, serde_json::json, Client, SignIn, Tables};

async fn run() -> kovlet::Result<()> {
    let kovlet = Client::builder("Todos").data_dir("./todos-data").build()?; // https://api.kovlet.com by default
    if !kovlet.signed_in() {
        kovlet.sign_in(SignIn::device(|c| println!("Open {} and enter {}", c.verification_uri, c.user_code))).await?;
    }
    let space_id = kovlet.spaces().find_or_create("Todos").await?.id;
    let space = kovlet.open_builtin(&space_id, Tables::new().table("todos", [("title", col::string()), ("done", col::boolean())]))?;
    space.write("todos").upsert("t1", json!({ "title": "Buy milk", "done": false }))?;
    println!("{:?}", space.table("todos").all()?);                            // or .observe(|rows| …)
    let mut status = kovlet.watch_status();
    while status.changed().await.is_ok() {
        println!("{:?}", status.borrow().state); // signed_out | authorizing | connecting | syncing | live | offline | error
    }
    Ok(())
}
```

> **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 milk` row, printed straight away. The write doesn't wait for the network.
> - The status moving through `connecting` and `syncing` to `live`. The row now shows in every other app on the `Todos` Data 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.

```rust
use kovlet::{serde_json::json, LocalWrite};

// 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(json!({ "todos": { "$": { "where": { "done": false }, "limit": 50 }, "owner": {} } }))?;
let result = open.rows()?;                      // built-in store: { data: { todos: [..] }, page_info }
let _watch = open.observe(|r| println!("{}", r.data["todos"].len()))?;

// All or nothing: applies locally at once, rolls back as one unit if the server rejects it.
let tx = space.transact([
    LocalWrite::upsert("teams", "t1", json!({ "name": "Core" })),
    LocalWrite::upsert("members", "m1", json!({ "team": "t1" })),
])?;
tx.settled().await?;

// End users of a public app: email codes, OAuth, ID tokens, guests.
let auth = kovlet.end_users(&space_id, "app_…");
auth.send_magic_code("ada@example.com").await?;
auth.sign_in_with_magic_code("ada@example.com", "123456").await?;
```

- `Client::open_query(space_id, tables, store)` keeps a partial copy of the space. Rows no subscription holds any more reach your store as `Change::Purge`, unless a local write to them is pending or awaits judgement.
- Subscriptions persist across restarts and resume from their last cursor. `LiveQuery::unsubscribe` ends 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 as `Event::Transaction { status: "rejected", .. }`. `quota_exceeded` holds it; `internal` and `rate_limited` retry it. On protocol 1 a batch is refused with `unsupported_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:

```rust
use std::sync::{Arc, Mutex};
use kovlet::sqlite::{rusqlite::Connection, SqliteStore};
use kovlet::{serde_json::json, Change};

let db = Arc::new(Mutex::new(Connection::open("app.db")?));
let store = Arc::new(SqliteStore::shared(db.clone(), |tx, _batch, change| {
    match change {
        Change::Upsert { id, fields, deleted, .. } => { /* INSERT … ON CONFLICT DO UPDATE the fields present */ }
        Change::Delete { id, .. } | Change::Restore { id, .. } => { /* set or clear your trash flag */ }
        Change::Purge { id, .. } => { /* DELETE */ }
        _ => {}
    }
    Ok(())
})?);
let space = kovlet.open(&space_id, tables, store.clone())?;
space.write("items").upsert(&id, json!({ "text": text }))?;   // write-through
space.record(&tx, "items", &id, json!({ "text": text }))?;     // 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`:

```rust
let lender = db.clone();
let store = SqliteStore::lending(move |f| lender.with_tx(|tx| f(tx)), |tx, batch| { /* write batch.changes */ Ok(()) })?;
```

### 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:

```rust
use kovlet::LocalWrite;

space.queue([LocalWrite::upsert("items", &id, json!({ "text": text }))])?; // durable when it returns
space.write("items").upsert_many(rows)?;                                     // many rows, one transaction
```

- `queue` stores the writes in Kovlet's own store in one transaction and returns. It never takes the merge lock or calls your `DataStore` on your thread.
- A Kovlet worker then merges the writes and calls `apply` with `origin: local` shortly 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, and `space.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

```rust
// "Stop syncing": Kovlet forgets the space's cursor, clocks and queued writes. Your rows stay.
kovlet.close_space(&space_id);
kovlet.forget_space(&space_id, store.clone())?;     // `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_id, tables, store)?;
space.seed("items", my_rows)?;                      // (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`:

```rust
use std::path::Path;

let files = space.files();
let scan = files.put("scans/a.png", &bytes, "image/png", None)?;                     // staged now, uploaded in the background
let pdf = files.put_file("docs/q3.pdf", Path::new("/tmp/q3.pdf"), "application/pdf", None)?; // streams from a local file
files.move_to(&scan.id, "archive/a.png")?;
files.delete(&pdf.id)?;                                                            // to the Trash
files.restore(&pdf.id)?;
let local = files.all()?;                                                          // metadata in the built-in store
let remote = files.list(Some("archive/")).await?;                                  // metadata on the server, under a prefix
files.download(&scan.id, Path::new("/tmp/a.png")).await?;                          // checked against its SHA-256
```

- `put` and `put_file` return a `FileState` (`id`, `path`, `sha256`, `size_bytes`, `mime_type`, `version`, …). Pass `Some(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:

```rust
// Once, after opening the space: `attachments/<name>` in the space ↔ `<app_dir>/attachments/<name>` on disk.
let attachments = space.files().mirror(app_dir.join("attachments"), "attachments/")?;
// At each place the app writes a new file into the folder:
attachments.notify_added("scan.png")?;   // 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()` and `watch_status()` report `ready` (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 last `Mirror` clone 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()` and `find_or_create` fall back to the last list the client saw, marked `offline: true`.
- Cached rows stay readable, and writes queue in the outbox.
- Sync resumes with backoff when the server is back.

## Lifecycle

- `client.pause(grace).await` when the app goes to the background.
- `client.resume()` when it comes back.
- `client.sync_once(deadline).await` from 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](https://kovlet.com/docs/protocol#14-client-checklist)), 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](https://kovlet.com/docs/run-locally) on your `PATH`:

```sh
cargo build --features bundled-sqlite --example conformance
kovletd conformance --client-cmd target/debug/examples/conformance
KOVLET_CONFORMANCE_STORE=sqlite kovletd conformance --client-cmd target/debug/examples/conformance
```

`examples/live.rs` is an end-to-end smoke test against a real `kovletd --dev --dev-auto-approve`.

## Links

- [kovlet.com]https://kovlet.com: sign in, create Data Spaces and manage connected apps.
- [Documentation]https://kovlet.com/docs: quickstarts, guides and the reference. The [Tauri quickstart]https://kovlet.com/docs/quickstart-tauri uses this crate.
- [Sync protocol reference]https://kovlet.com/docs/protocol.
- [Terms]https://kovlet.com/legal/terms and [Privacy Policy]https://kovlet.com/legal/privacy of the hosted service at kovlet.com.

MIT licensed.