use std::time::{Duration, Instant};
use kovlet::{col, Client, SignIn, Space, Tables};
use serde_json::json;
fn tables() -> Tables {
Tables::new().table("todos", [("title", col::string()), ("done", col::boolean().optional())])
}
async fn client(base: &str, name: &str, dir: &std::path::Path) -> kovlet::Result<Client> {
let c = Client::builder("Live Smoke")
.base_url(base)
.console_url(format!("{base}/v1/dev"))
.data_dir(dir.join(name))
.secret_store(std::sync::Arc::new(kovlet::FileSecretStore::new(dir.join(name).join("secrets"))?))
.build()?;
if !c.signed_in() {
let s = c
.sign_in(SignIn::Device {
on_code: std::sync::Arc::new(|code| eprintln!(" code {} (auto-approved)", code.user_code)),
machine_name: Some(format!("live-{name}")),
space_name: Some("Live Smoke".into()),
keyless: false,
})
.await?;
assert!(s.device_bound && s.refresh_token.is_some(), "a keyed device code gives a refreshable session");
}
Ok(c)
}
async fn wait(what: &str, mut f: impl FnMut() -> bool) {
let t = Instant::now();
while !f() {
if t.elapsed() > Duration::from_secs(15) {
panic!("timed out waiting for {what}");
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
eprintln!("ok {what} ({} ms)", t.elapsed().as_millis());
}
fn titles(s: &Space) -> Vec<String> {
s.table("todos").all().unwrap().iter().map(|r| r.fields["title"].as_str().unwrap_or_default().to_string()).collect()
}
#[tokio::main]
async fn main() -> kovlet::Result<()> {
let base = std::env::args().nth(1).unwrap_or_else(|| "http://127.0.0.1:8080".into());
let dir = tempfile::tempdir().unwrap();
let a = client(&base, "a", dir.path()).await?;
eprintln!("ok client A signed in ({})", a.session().unwrap().machine_id);
let space = a.spaces().find_or_create("Live Smoke").await?;
eprintln!("ok space {} ({})", space.name, space.id);
let list = a.spaces().list().await?;
assert!(list.spaces.iter().any(|s| s.id == space.id), "list shows the space");
let b = client(&base, "b", dir.path()).await?;
let sa = a.open_builtin(&space.id, tables())?;
let sb = b.open_builtin(&space.id, tables())?;
let id = uuid::Uuid::now_v7().to_string();
let title = format!("From A {id}");
sa.write("todos").upsert(&id, json!({"title": title, "done": false}))?;
wait("B sees A's row", || titles(&sb).contains(&title)).await;
sb.write("todos").upsert(&id, json!({"done": true}))?;
wait("A sees B's field edit", || sa.table("todos").get(&id).unwrap().is_some_and(|r| r.fields["done"] == true))
.await;
sa.write("todos").delete(&id)?;
wait("B sees the delete", || !titles(&sb).contains(&title)).await;
sb.write("todos").restore(&id)?;
wait("A sees the restore", || titles(&sa).contains(&title)).await;
wait("both outboxes drain", || sa.pending() == 0 && sb.pending() == 0).await;
let f = sa.files().put(&format!("notes/{id}.txt"), b"hello from kovlet-rs\n", "text/plain", None)?;
wait("B sees the file", || sb.files().all().unwrap().iter().any(|x| x.id == f.id)).await;
let to = dir.path().join("hello.txt");
b.runtime().spawn(async {}).await.ok();
sb.files().download(&f.id, &to).await?;
assert_eq!(std::fs::read(&to).unwrap(), b"hello from kovlet-rs\n");
eprintln!("ok B downloaded and verified the file");
let listed = sb.files().list(Some("notes/")).await?;
assert!(listed.iter().any(|x| x.id == f.id));
eprintln!("ok files list");
let shared = format!("shared-{id}");
sa.write("todos").upsert(&shared, json!({"title": "A's old copy", "done": false}))?;
wait("B sees the shared row", || sb.table("todos").get(&shared).unwrap().is_some()).await;
wait("A drains before unlinking", || sa.pending() == 0).await;
a.close_space(&space.id);
a.forget_space(&space.id, kovlet::SpaceStore::Builtin)?;
sb.write("todos").upsert(&shared, json!({"title": "B's newer edit"}))?;
wait("B uploads while A is unlinked", || sb.pending() == 0).await;
let only_a = format!("only-a-{id}");
let mut local: Vec<(String, serde_json::Value)> =
sa.table("todos").all()?.into_iter().map(|r| (r.id, serde_json::Value::Object(r.fields))).collect();
local.push((only_a.clone(), json!({"title": "Only on A", "done": false})));
let sa = a.open_builtin(&space.id, tables())?;
sa.seed("todos", local)?;
let title_of = |s: &Space, id: &str| {
s.table("todos").get(id).unwrap().and_then(|r| r.fields["title"].as_str().map(String::from))
};
wait("A gets B's edit after re-linking", || title_of(&sa, &shared).as_deref() == Some("B's newer edit")).await;
wait("B gets A's local-only row", || title_of(&sb, &only_a).as_deref() == Some("Only on A")).await;
wait("A's seed drains", || sa.pending() == 0).await;
assert_eq!(title_of(&sb, &shared).as_deref(), Some("B's newer edit"), "A's old copy must not win");
assert_eq!(title_of(&sa, &id).as_deref(), Some(title.as_str()), "rows the space had are kept");
let c = Client::builder("Live Smoke").base_url(&base).console_url(format!("{base}/v1/dev")).memory().build()?;
let s = c
.sign_in(SignIn::pkce("http://127.0.0.1:53124/callback", |url: String| async move {
let t = kovlet::transport::default_transport()?;
let r = t.http(kovlet::transport::HttpRequest { method: "GET".into(), url, ..Default::default() }).await?;
r.header("location")
.map(String::from)
.ok_or_else(|| kovlet::Error::new("consent_failed", format!("HTTP {}", r.status)))
}))
.await?;
assert!(s.device_bound && !s.spaces.is_empty(), "PKCE gives a device-bound session with slots: {s:?}");
let sc = c.open_builtin(&s.spaces["main"].space_id, tables())?;
wait("the PKCE client syncs", || sc.status().state == kovlet::SyncState::Live).await;
eprintln!("ok PKCE sign-in ({} slot(s))", s.spaces.len());
drop(sa);
drop(a);
let a2 = client(&base, "a", dir.path()).await?;
let sa2 = a2.open_builtin(&space.id, tables())?;
assert!(titles(&sa2).contains(&title), "rows survive a restart");
wait("A reconnects with its stored session", || a2.status().state == kovlet::SyncState::Live).await;
let summary = a2.sync_once(Duration::from_secs(10)).await;
assert!(summary.completed, "{summary:?}");
eprintln!("ok sync_once");
a2.pause(Duration::from_secs(2)).await;
a2.resume();
wait("resume reconnects", || a2.status().state == kovlet::SyncState::Live).await;
eprintln!("PASS live smoke against {base}");
Ok(())
}