Skip to main content

Crate zero_client

Crate zero_client 

Source
Expand description

A native Rust client for Zero.

A port of the JS client (packages/zero-client), checked against the JS implementation by the conformance vectors in packages/zero-conformance. See rust/PARITY.md for what is ported so far and what is planned.

§Features

The default build has no dependencies. It has the whole client, client::Zero, which an app drives with its own Scheduler and SocketFactory. Opt-in features add:

  • tokio-transport: the tokio_transport module, a scheduler and a WebSocket transport on tokio and tokio-tungstenite.
  • tls: wss:// for that transport, with rustls on ring.
  • sqlite: SQLite storage, ZeroStorage::Sqlite, on the system libsqlite3; sqlite-bundled compiles SQLite in.
  • serde: the define module, typed named queries and mutators (define_query, define_mutator) over serde argument types, and serde for json::Value.

§Storage

A default build persists nothing across restarts: its storage is ZeroStorage::Memory, kept for the life of the thread by database name, like JS kvStore: 'mem'. SQLite storage, which keeps synced rows and pending mutations across restarts, is behind the sqlite feature, and an app can bring its own store with ZeroStorage::Custom.

§Modules

An app uses client, typed (through generated code), query, ttl, and testing; their items are all documented. The others (ast, ivm, protocol, and the primitives) are the engine’s parts, public so the conformance runner can check each against JS.

§Getting started

A client is made from the app’s schema (generated from its TypeScript schema by zero-rust codegen), its mutators, and a scheduler and socket factory for its event loop. Views stay current: when mutate returns, they show its writes. This one runs without a server, on the manual clock tests use; an app passes a cache_url and the tokio_transport types instead.

use zero_client::ast::System;
use zero_client::client::{Mutator, Zero, ZeroOptions};
use zero_client::json::{self, Object, Value};
use zero_client::query::AnyQuery;
use zero_client::schema::Schema;
use zero_client::testing::ManualScheduler;
use zero_client::ttl::Ttl;
use std::sync::Arc;

let schema = Arc::new(Schema::from_json(&json::parse(
    r#"{"tables": {"issue": {"name": "issue", "primaryKey": ["id"],
        "columns": {"id": {"type": "string"}, "title": {"type": "string"}}}}}"#,
)?)?);

// Runs on the client now, and on the server's API when it syncs.
let create = Mutator::new("issue.create", |tx, args, _ctx: &()| {
    let mut row = Object::new();
    row.insert("id", args.and_then(|a| a.get("id")).cloned().unwrap_or_default());
    row.insert("title", Value::from("Hello"));
    tx.table("issue").insert(&row)?;
    Ok(None)
});

let scheduler = ManualScheduler::new(1_700_000_000_000.0);
let zero = Zero::new(schema.clone(), (), vec![create], ZeroOptions::default(), scheduler, None)?;

let issues = AnyQuery::new(schema, "issue", System::Client);
let view = zero.materialize(&issues, &Ttl::default())?;
let mut args = Object::new();
args.insert("id", Value::from("i1"));
zero.mutate("issue.create", Some(Value::from(args)));

let rows = view.data();
assert_eq!(rows.entries().len(), 1);
assert_eq!(rows.entries()[0].row.get("title"), Some(&Value::from("Hello")));

With generated types, the query is zql::issue(), and Zero::live keeps its rows read as row structs; see the README.

Modules§

ast
The ZQL abstract syntax tree (packages/zero-protocol/src/ast.ts).
builder
Builds IVM pipelines from ASTs (packages/zql/src/builder/builder.ts).
client
The client engine (packages/zero-client/src/client): the connection, the replica and its pending mutations, and the query and mutation bookkeeping, on memory storage.
compare
Comparing row values (packages/zql/src/ivm/data.ts).
decode
Decoding Values into typed protocol values, following valita’s rules: optional fields may be absent but not null (unless declared nullable), and unknown keys are ignored (passthrough mode).
define
Typed named queries and mutators, behind the serde feature: define_query and define_mutator (defineQuery in packages/zql/src/query/query-registry.ts and defineMutator in packages/zql/src/mutate/mutator.ts, shaped like the Swift client’s).
format
The shape a query’s view materializes as (packages/zero-types/src/format.ts).
hash
The hashes Zero uses for identities: xxHash32 and its wider forms, and the query hashes built from it.
ivm
Incremental view maintenance (packages/zql/src/ivm): the operators a query’s pipeline is built from, the memory source they read, and the view that materializes their output.
json
JSON with JS semantics: JSON.parse, JSON.stringify, JS property order, and JS number formatting and parsing.
keys
Storage keys (packages/zero-client/src/client/keys.ts) and the names of synthetic aggregate tables.
like
LIKE and ILIKE (packages/zql/src/builder/like.ts).
map
OrderedMap: a map with string keys that keeps them in insertion order, so the crate needs no third-party map.
protocol
The zero-protocol wire messages (packages/zero-protocol/src), decoded as valita does in passthrough mode: unknown keys are accepted and dropped, and optional fields may be absent but not null unless they are nullable.
query
The untyped query builder (QueryImpl in packages/zql/src/query/query-impl.ts) and the builder of where conditions (ExpressionBuilder in packages/zql/src/query/expression.ts).
schema
A Zero schema’s tables and columns (packages/zero-types/src/schema.ts), and the names they map to on the server (packages/zero-types/src/name-mapper.ts).
sort
Array.prototype.sort as V8 implements it.
strings
The two string orders Zero uses.
tdigest
A t-digest, for the inspector’s percentiles (TDigest in packages/shared/src/tdigest.ts, itself a port of https://github.com/influxdata/tdigest, Apache License 2.0).
testing
Helpers for testing an app on Zero without a server or a real clock (ZeroTesting in the Swift client): a clock that only moves when told to, in-memory sockets a test plays the server on, and a log sink that keeps what was logged.
tokio_transport
A scheduler and a WebSocket transport on tokio, behind the tokio-transport feature, for apps that don’t bring their own.
ttl
Query time-to-live (packages/zql/src/query/ttl.ts).
typed
The typed query builder that zero-rust codegen generates code for: row structs read from views, columns and relationships named by typed constants, and Query, a typed wrapper of AnyQuery (Query in packages/zql/src/query/query.ts).

Macros§

json
Builds a Value from JSON-like syntax, for tests and fixtures: json!({"a": [1, null, "x"]}).