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
//! The conformance adapter for the Rust core (BORG-101): lets
//! `kovletd conformance` drive this crate through the language-neutral suite.
//!
//!   cargo build -p kovlet --example conformance
//!   go run ./cmd/kovletd conformance --client-cmd target/debug/examples/conformance
//!
//! One JSON command per line on stdin, one answer per line on stdout
//! (adapter protocol 1, docs/CONFORMANCE.md). Each command maps to the
//! crate's public API and nothing more.

use std::io::{BufRead, Write};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use base64::Engine;
use kovlet::transport::{default_transport, HttpRequest};
use std::collections::HashMap;

use kovlet::{Client, Error, Event, LiveQuery, LocalWrite, MemorySecretStore, SignIn, Space, Tables};
use serde_json::{json, Map, Value};

static OUT: Mutex<()> = Mutex::new(());

fn write(v: &Value) {
    let _g = OUT.lock().unwrap();
    let mut o = std::io::stdout().lock();
    let _ = writeln!(o, "{v}");
    let _ = o.flush();
}

struct Adapter {
    rt: tokio::runtime::Runtime,
    client: Option<Client>,
    space: Option<Space>,
    queries: HashMap<String, LiveQuery>,
}

fn arg<'a>(a: &'a Value, k: &str) -> &'a str {
    a.get(k).and_then(Value::as_str).unwrap_or_default()
}

fn sign_in(auth: &Value) -> Result<SignIn, Error> {
    Ok(match arg(auth, "type") {
        "machine_key" => SignIn::machine_key(arg(auth, "machine_key"), arg(auth, "client_id")),
        "device_code" => SignIn::Device {
            on_code: Arc::new(|c| eprintln!("device code {} at {}", c.user_code, c.verification_uri_complete)),
            machine_name: Some("conformance".into()),
            space_name: None,
            keyless: auth.get("device_key") == Some(&Value::Bool(false)),
        },
        "pkce" => SignIn::pkce(arg(auth, "redirect_uri"), |url: String| async move {
            // A real app opens the consent URL in a browser; the fake server
            // answers with the redirect straight away.
            let t = default_transport()?;
            let res = t.http(HttpRequest { method: "GET".into(), url, ..Default::default() }).await?;
            res.header("location").map(String::from).ok_or_else(|| {
                Error::new("consent_failed", format!("consent answered {} without a redirect", res.status))
            })
        }),
        other => return Err(Error::new("unsupported", format!("auth type {other}"))),
    })
}

impl Adapter {
    fn space(&self) -> Result<&Space, Error> {
        self.space.as_ref().ok_or_else(|| Error::new("not_connected", "send connect first"))
    }

    fn run(&mut self, cmd: &str, a: &Value) -> Result<Value, Error> {
        match cmd {
            "connect" => {
                if let Some(c) = &self.client {
                    c.resume();
                    return Ok(json!({}));
                }
                let tables = Tables::from_json(&a.get("tables").cloned().unwrap_or(json!({})).to_string())?;
                let mut b = Client::builder(arg(a, "app_name"))
                    .base_url(arg(a, "url"))
                    .console_url(arg(a, "console_url"))
                    .secret_store(Arc::new(MemorySecretStore::new()));
                // Scenarios that need protocol 2 say so, and get the default
                // (2, falling back to 1); every other one checks protocol 1.
                if a.get("protocol").and_then(Value::as_u64) != Some(2) {
                    b = b.protocol(1);
                }
                // KOVLET_CONFORMANCE_STORE=sqlite runs the suite against the SQLite
                // store in a fresh directory (the default for apps); otherwise memory.
                b = match std::env::var("KOVLET_CONFORMANCE_STORE").as_deref() {
                    Ok("sqlite") => {
                        let dir = std::env::temp_dir().join(format!("kovlet-conformance-{}", std::process::id()));
                        let _ = std::fs::remove_dir_all(&dir);
                        b.data_dir(dir)
                    }
                    _ => b.memory(),
                };
                let client = b.build()?;
                // `sync: "query"`: a partial replica of the app's query subscriptions.
                let space = match arg(a, "sync") {
                    "query" => client.open_query(arg(a, "space_id"), tables, kovlet::SpaceStore::Builtin)?,
                    _ => client.open_builtin(arg(a, "space_id"), tables)?,
                };
                let mut events = client.events();
                self.rt.spawn(async move {
                    while let Ok(ev) = events.recv().await {
                        let error = match ev {
                            Event::Rejected { error, .. } | Event::Error { error, .. } => error,
                            // A rejected atomic batch reaches the app as one error.
                            Event::Transaction { error: Some(error), .. } => error,
                            _ => continue,
                        };
                        let mut m = json!({"event": "error", "code": error.code, "message": error.message});
                        if let Some(id) = error.mutation_id {
                            m["mutation_id"] = json!(id);
                        }
                        write(&m);
                    }
                });
                // Sign-in and the first sync run in the background, like in an app.
                let how = sign_in(a.get("auth").unwrap_or(&Value::Null))?;
                let c = client.clone();
                self.rt.spawn(async move {
                    if let Err(e) = c.sign_in(how).await {
                        write(&json!({"event": "error", "code": e.code, "message": e.message}));
                    }
                });
                self.client = Some(client);
                self.space = Some(space);
                Ok(json!({}))
            }
            "disconnect" => {
                if let Some(c) = &self.client {
                    self.rt.block_on(c.pause(Duration::ZERO));
                }
                Ok(json!({}))
            }
            "transact" => {
                let mut writes = Vec::new();
                for w in a.get("writes").and_then(Value::as_array).into_iter().flatten() {
                    let (table, id) = (arg(w, "table"), arg(w, "id"));
                    writes.push(match arg(w, "op") {
                        "upsert" => LocalWrite::upsert(table, id, w.get("fields").cloned().unwrap_or(json!({}))),
                        "delete" => LocalWrite::delete(table, id),
                        "restore" => LocalWrite::restore(table, id),
                        op => return Err(Error::new("invalid_argument", format!("unknown write op {op}"))),
                    });
                }
                let tx = self.space()?.transact(writes)?;
                Ok(json!({ "batch_id": tx.id }))
            }
            "subscribe" => {
                let params = a.get("params").and_then(Value::as_object).cloned();
                let q = self.space()?.subscribe_with(a.get("query").cloned().unwrap_or(Value::Null), params)?;
                let sub = q.id().to_string();
                self.queries.insert(sub.clone(), q);
                Ok(json!({ "sub": sub }))
            }
            "unsubscribe" => {
                let q = self
                    .queries
                    .remove(arg(a, "sub"))
                    .ok_or_else(|| Error::new("not_found", "no such subscription"))?;
                q.unsubscribe()?;
                Ok(json!({}))
            }
            "upsert" => {
                self.space()?
                    .write(arg(a, "table"))
                    .upsert(arg(a, "id"), a.get("fields").cloned().unwrap_or(json!({})))?;
                Ok(json!({}))
            }
            "delete" => {
                self.space()?.write(arg(a, "table")).delete(arg(a, "id"))?;
                Ok(json!({}))
            }
            "restore" => {
                self.space()?.write(arg(a, "table")).restore(arg(a, "id"))?;
                Ok(json!({}))
            }
            "read" => {
                let mut rows = Map::new();
                for r in self.space()?.table(arg(a, "table")).all()? {
                    rows.insert(r.id, Value::Object(r.fields));
                }
                Ok(json!({ "rows": rows }))
            }
            "put_file" => {
                let bytes = base64::engine::general_purpose::STANDARD
                    .decode(arg(a, "data_base64"))
                    .map_err(|e| Error::new("invalid_argument", e.to_string()))?;
                let mime = Some(arg(a, "mime_type")).filter(|m| !m.is_empty()).unwrap_or("application/octet-stream");
                let id = Some(arg(a, "id")).filter(|s| !s.is_empty());
                let f = self.space()?.files().put(arg(a, "path"), &bytes, mime, id)?;
                Ok(json!({ "id": f.id }))
            }
            "files" => {
                let mut files = Map::new();
                for f in self.space()?.files().all()? {
                    files.insert(f.id.clone(), json!({"path": f.path, "sha256": f.sha256, "size_bytes": f.size_bytes, "mime_type": f.mime_type}));
                }
                Ok(json!({ "files": files }))
            }
            other => Err(Error::new("unsupported", format!("unknown command {other}"))),
        }
    }
}

fn main() {
    let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
    let mut ad = Adapter { rt, client: None, space: None, queries: HashMap::new() };
    write(
        &json!({"event": "ready", "protocol": 1, "name": "kovlet-rs", "features": ["files", "device_code", "pkce", "machine_key", "protocol_2", "atomic", "query"]}),
    );
    for line in std::io::stdin().lock().lines() {
        let Ok(line) = line else { break };
        if line.trim().is_empty() {
            continue;
        }
        let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
        let id = msg.get("id").cloned().unwrap_or(Value::Null);
        let cmd = msg.get("cmd").and_then(Value::as_str).unwrap_or_default().to_string();
        let args = msg.get("args").cloned().unwrap_or(json!({}));
        match ad.run(&cmd, &args) {
            Ok(result) => write(&json!({"id": id, "ok": true, "result": result})),
            Err(e) => write(&json!({"id": id, "ok": false, "error": {"code": e.code, "message": e.message}})),
        }
    }
    std::process::exit(0);
}