Rust
Use Jazz from a Rust app or service: a client of your TypeScript main backend, with typed bindings generated from your app's schema.For apps and services: run your backend in TypeScript. A Rust program is a client of your app: it
signs in as one of your users and syncs through your main backend's /jazz, like a browser or a
mobile app, or it acts as a backend client with a machine
credential. Like every other language, it works from your app's TypeScript schema and permissions:
npx jazz-tools generate writes its typed bindings from them.
Install
Depend on the jazz-app-support crate:
Cargo.toml[dependencies]jazz-app-support = "=2.0.0-alpha.66"futures-util = "0.3"tokio = { version = "1", features = ["full"] }
Generate the bindings
Author your app's schema and permissions in TypeScript, in a schema.ts beside your Cargo.toml.
If your app's TypeScript side already has one, re-export it:
schema.tsexport { schema, permissions } from "../web/schema";
Then run npx jazz-tools generate there. It writes jazz.app.json, jazz.permissions.json and
src/jazz_app.rs, the typed bindings. The crate needs no package.json:
npx jazz-tools generate # writes jazz.app.json, jazz.permissions.json, src/jazz_app.rsnpx jazz-tools generate --check # in CI: fails if any of them is stale
Run it with npx: the standalone jazz-tools binary refuses to write beside a schema.ts, though
its generate --check still works. Commit schema.ts and the generated files, and declare the
bindings with mod jazz_app;. The Reading and
Writing pages have a Rust tab for each example.
Open the app as an end user
An end user's client syncs through your app's Jazz endpoint (its backend's handler), never with the
core directly. Open it with Config::user, signed in with a device account (the key is the account)
or with your own sign-in's bearer token:
src/main.rsuse futures_util::StreamExt;use jazz_app::{Auth, Config, DeviceKey, SessionState, Storage, TokenReason};// An end user's client syncs through your app's Jazz endpoint (its// backend's handler), never with the core directly.let auth = if signed_in_with_my_auth {// Your own sign-in's bearer token, asked for whenever one is needed:// on open, before it expires, and fresh after the backend refused it.Auth::bearer(|_reason: TokenReason| async { Ok(my_sign_in::current_token().await) })} else {// A device account: the key is the account. Keep it in your// platform's secure store; on a host without one, in a file only// this user can read.Auth::Device(DeviceKey::load_or_create("./jazz-data/device.key".as_ref(),)?)};let jazz = jazz_app::open(Config::new(app_id).server("https://app.example/jazz").storage(Storage::Dir("./jazz-data".into())) // or Storage::Memory.user(auth),).await?;let session = jazz.session().expect("an end user's client has a session");let mut states = session.changes();while let Some(state) = states.next().await {if let SessionState::SignedIn { user } = state {println!("signed in as {:?}", user.account);break;}}
To follow who is signed in, as TypeScript's createJazzClient does, open a JazzSession. With
.initial(Initial::Device) it starts with a device account (a guest); a user your sign-in names then
takes the guest's account over if they have none yet (link_guest, on by default):
src/main.rsuse futures_util::StreamExt;use jazz_app::{AppFiles, Initial, JazzSession, SessionConfig, SessionStatus, Storage, TokenReason,};// A session follows who is signed in: a device account (a guest) until// your sign-in names a user, who takes the guest's account over if they// have none yet. Call `session.refresh()` when your sign-in changes.let session = JazzSession::open(AppFiles::new(jazz_app::APP, None),SessionConfig::new(app_id).server("https://app.example/jazz")// Each account's store in a directory of its own, the device// account's key beside them..storage(Storage::Dir("./jazz-data".into()))// `None` while no one is signed in..bearer(|_reason: TokenReason| async { Ok(my_sign_in::current_token().await) }).initial(Initial::Device),).await?;let mut snapshots = session.changes();while let Some(snapshot) = snapshots.next().await {if snapshot.status == SessionStatus::Ready {println!("signed in as {:?}", snapshot.user.map(|user| user.account));break;}}// The client for the user signed in now. Get it again when// `client_epoch` changes: one kept from before fails with// `Error::Replaced`.let jazz = session.jazz()?;
jazz.session().state() and .changes() give the session's state: SignedIn, Expired or
SignedOut. When the backend ends a session, the client reconnects with a fresh bearer.
Storage
Storage::Memorykeeps the store for the life of the process only.Storage::Dir(dir)keeps it on disk. WithConfig::user,dirholds that one user's store; withJazzSession, each account's store sits indir/<account id>/, with the device key indir/device.key.jazz.delete_client_storage()deletes the store (one account's, under a session). It's refused withStoreHeldwhile another open client holds it.
Keep a device key in your platform's secure store: a DeviceKey reads and writes as
jazz-auth-v1:…, the same form as TypeScript's exportDeviceKey. DeviceKey::load_or_create(path)
keeps it in a file only this user can read, for hosts without a store.
Reads and sync
An end user's all, one, get and subscribe read local data first, and the first load waits up
to 5 seconds for the server, as TypeScript's browser and React Native clients do. Name a tier to
choose: all_with(query, ReadTier::Remote) or ReadTier::LocalOnly, or pass ReadOptions. See
Loading tiers.
jazz.sync_status() and jazz.sync_changes() give TypeScript's SyncStatus, with the same fields:
link, pendingUploads, oldestPendingAt, rejected, lastError and synced. The connection
falls back to an HTTP stream on its own when WebSockets can't get through, as the browser client
does.
Closing
jazz.shutdown()stops the client: calls already made finish (for up to 30 seconds), then subscriptions end. Call it before exiting withStorage::Dir, so the store is flushed and closed.jazz.close(timeout)first waits up totimeout(CLOSE_TIMEOUTis 10 seconds) for queued writes to reach the server, then shuts down. WithStorage::Memory, writes that never arrived are lost and reported asError::Unsynced { pending };Duration::ZEROcloses at once and accepts that.- With
JazzSession,session.sign_out()signs out and keeps the session usable, whilesession.close()ends it.
For a service acting with a machine credential instead of as a user, see Backend Client.
Not supported yet
- running your app's main backend (serving its
/jazzand publishing its permissions): run it in TypeScript withcreateJazz; - a built-in platform keychain or secure store for device keys: keep the key yourself (above);
- cookie sessions, and renewing a session over the open connection: a Rust client signs in with a bearer and reconnects with a fresh one;
JazzSession's browser-only parts: focus and visibility re-checks (callsession.refresh()when your sign-in changes), cross-tab sign-out,clearOnSignOut(sign-out keeps each account's store),linkDeviceAccountOnSignUp(following the backend links a guest by default instead, withlink_guest) and the thin-client upgrade;- the session snapshot's
client,localFirstandpendingfields: usesession.jazz()andclient_epoch.