Skip to content

v0.5.0

Choose a tag to compare

@github-actions github-actions released this 03 Dec 05:30
85a3971

The public API settles: models named by their createSchema key with relations as fields, $ as a rule argument, sessions with claims and read-only access, restricted fields, server queries, lazy clients with eviction, writes that apply at most once across long offline periods, retention, a round of security fixes and a faster sequencer. Old APIs are removed, not deprecated. Wire protocol v2 and schema IR v2: 0.4 and 0.5 clients and servers don't talk to each other, and open tabs reload once when you deploy. Breaking changes are listed first, each with what to change; the Swift client follows every change.

Breaking changes

  • Schema. model(fields, options) takes no name, and createSchema({ user, todo }, { viewer: "user" }) names models by their key. Relations are fields: project: t.belongsTo("project", { inverse: "todos", foreignKey, onDelete, eager }) replaces schema(models, (relations) => …) and relations.belongsTo.

    Migrating: move each model into the createSchema object under its name, and each relations.belongsTo(…) onto the child as a t.belongsTo field.

  • owned is removed; cascades come from onDelete. t.belongsTo("todo", { inverse: "comments", onDelete: "cascade" }) is the one way to cascade (default "setNull" for nullable relations, "restrict" otherwise). With fromPrisma, the relation's onDelete in schema.prisma decides: Cascade cascades, SetNull clears the key, anything else restricts. Client deletes, undo, ensureUndoable and archive inheritance follow every cascading relation, and a model may cascade from several parents (archived while any of them is). Schema metadata has cascadingParents / cascadingChildren instead of owner / ownedChildren; the schema IR drops owned.

    Migrating: replace owned: true with onDelete: "cascade", or give the Prisma relation onDelete: Cascade.

  • Load modes are "eager" and "lazy". "eager:critical" and "partial" are gone: a lazy model loads by its id, unique fields and foreign keys, and eager: true on a relation loads children with their parent. db.$ready() takes no level, and <DatabaseProvider ready> is a boolean.

    Migrating: "eager:critical" becomes "eager", "partial" becomes "lazy", ready="critical" becomes ready.

  • fromPrisma options per model. models: { Todo: { load, id: { prefix }, restricted, archivable, relations: { project: { eager } } } } replaces the top-level load and owned lists; eager is the only relation option. Mistakes are type errors on the offending key, including misspelled model names in models, omit and notSecret.

  • Permissions take $ as an argument. defineModelRules(schema, "todo", { read: (todo, $) => { … } }), defineRule(schema, "project", (project, $) => …, { name }) and definePermissions(schema, [rules…], { strict, groups }) replace createRules, rules(…) and rules.fn; explicit groups move to definePermissions' groups.

  • $.canRead(row.relation), and nothing is readable implicitly. $.canRead(comment.todo) (or $.canRead(comment.todo, { except })), in read and write rules, replaces comment.todo.canRead(). Children no longer inherit their parent's read rule: every synced model needs a read rule, and outside production (strict) definePermissions fails without one. read: (comment, $) => { return $.canRead(comment.todo); } reads exactly like the parent and is re-tagged in bulk when the parent's access changes.

    Migrating: add that rule to each formerly owned child.

  • update rules are field groups: { when, fields } or a list of them. Each changed field must belong to a group whose when holds before and after the write.

  • Sessions replace viewers. The handlers' viewer(request) option is now session(request), returning { viewer, claims?, readOnly?, tenant? } or null, and verifyJwt({ viewer }) is verifyJwt({ session }). Sync tokens carry the whole session. On the client, db.$viewerId is db.$session.viewerId. Engine methods (bootstrap, pull, push, partial, connect) take a Session from createSession(viewer, { claims, readOnly, tenant }) instead of tenant and viewer ids, engine.viewerGroups is engine.sessionGroups(session), and sync ids are opaque strings.

    Migrating: rename viewer: to session: and return { viewer: id }.

  • Server mutators are removed, with createEngine({ mutators }), db.$call and the call operation. Keep server logic in your own server actions or routes and call them through db.$action(fn).

  • EntitiesOf<Schema> (DB["Todo"]) replaces the public EntityOf<Schema, "todo">.

  • db.$sync() resolves only after a pull that started after the call (a barrier on live sockets), not after one already in flight.

  • Stricter security defaults, each refusing something 0.4 accepted:

    • Sync token secrets (tokens.secret, mintSyncToken) and verifyJwt({ secret }) need at least 32 characters (openssl rand -base64 32).
    • POST bodies must be application/json; other media types get 415.
    • ?token= is read only on WebSocket upgrades, never on plain HTTP requests.
    • Without cors, a WebSocket from another origin needs a sync token: cookies alone get 403. Pass cors if pages on other origins call the server.
  • Custom Reactivity implementations need a reaction(onInvalidate) method; signals and mobxReactivity() have it.

  • Engine: sequenceOnce() is removed. sequenceNow() takes no arguments and drainChanges() resolves once the backlog is empty; both return nothing.

  • Upgrading the database. Run npx clientdb migrate <engine module> when you deploy (--dry-run first prints the plan). On engine-owned tables it adds the new columns itself. Prisma apps first re-run npx clientdb-prisma models and migrate, for the new clientdb_row.field_readers, clientdb_log.created_at and nonce, clientdb_head.transactions_horizon and clientdb_transactions.head columns (clientdb migrate names any that are missing), and regenerate the capture triggers with npx clientdb-prisma triggers src/sync/schema.ts: they now cover serverOnly models, key changes, TRUNCATE and cascaded rows, and wake the sequencer.

Features

  • Restricted fields: .restricted() (or models.X.restricted with Prisma) and per-field read rules, read: { when, fields: { inviteCode: (project, $) => { … } } }. Hidden fields are undefined on the client and routed in their own field_readers column.

  • Claims and read-only sessions: declareClaim("staff"), granted by the session callback, used as a condition in rules and checked on the client with db.$session.hasClaim($staff). readOnly: true on a session or route refuses writes with ReadOnly (ReadOnlyError on the client), and createDatabaseClient({ readOnly: true }) types a client without writes. Live sockets check their session again every token lifetime and renew sync tokens, and changed claims move rows on and off the device.

  • Writes apply at most once, also after long offline periods. Applied transaction ids are kept for retention.transactions (default the longer of retention.log and 90 days). A pull from a client behind the pruned log is answered with reset before anything it sent is applied, and a resend the server may have applied after its id was pruned is refused with the new Stale code instead of applied twice. The client stamps each transaction with the sync position it is first sent from.

  • Server queries: db.todo.query({ where, orderBy, limit }) over POST /query, with keyset pages and per-model query: { fields, maxLimit } rules. where gains text operators (contains, startsWith, endsWith).

  • Lazy clients and eviction: createDatabaseClient({ load: "lazy" }) starts with no rows, and eviction: { maxRows } drops the loads used longest ago that nothing observes.

  • Fields: t.uuid({ prefix }), t.decimal(), .unique() and .generated() (Prisma autoincrement and dbgenerated() columns).

  • db.$action(fn, { optimistic }) previews a server action's outcome on the device until the server answers.

  • Engine: retention: { log, transactions, archived } applied by engine.prune() (hourly in start(), and by clientdb migrate); clients behind the pruned log start over. hooks: { onWriteRejected, onAccessRemoved } (no row data, safe to log), bootstrapRowWarning, cascadeRowLimit and recentLogActions. clientdb migrate --dry-run and engine.migrationPlan() show what a migration would do.

  • Prisma archives: models.X.archivable with archivedAt/archivedBy columns, so Prisma tables support archive(), unarchive() and retention.archived.

  • Transient database failures (a lost connection, shutdown, statement timeout or deadlock) throw Unavailable: HTTP answers 503, a live socket closes with 1011, and the client keeps the transaction and resends it, instead of dropping a write that was never wrong.

Fixes

  • Security:

    • Cross-site WebSockets authenticated by cookies are refused (browsers attach cookies to any site's upgrade), and an opaque null Origin no longer crashes the server.
    • Non-JSON POST bodies get 415, so another site can't push transactions with the viewer's cookies through a form or a no-cors fetch.
    • Tokens are no longer read from URLs of plain HTTP requests, and the Swift client sends its token as a header on the WebSocket too.
    • Secrets under 32 characters are refused. Malformed JWTs and JWKS keys that don't fit the token's algorithm answer 401 instead of 500.
    • Written values are checked against their field (type, enum, nullability) before rules run, so a rule can't be passed with "0" that Postgres then stores as 0.
    • Client archives, and creates or restores of archived rows, are stamped with the server's clock and the viewer and need the archive rule, so a back-dated archive can't make retention delete a row.
    • Writes to rows the viewer can't read get the same NotFound as writes to missing rows, and an unreadable restricted field is refused in no-op updates too, so neither reveals hidden data.
    • Rejections no longer carry Postgres messages (which name tables and constraints), and names such as __proto__ are unknown models and fields.
    • Rows are routed no wider than their read rules: $.public next to other conditions, and claim or viewer conditions through related rows, no longer widen who receives a row; a negated membership inside another membership is refused when compiling.
  • Sync and the server:

    • A database restored from a backup is detected through per-entry nonces in sync positions: clients past the backup start over, and servers drop their in-memory recent log.
    • A process that would miss log entries pruned before it published them drops the affected connections, and a failed delivery drops the live connection instead of skipping the batch; the client resumes from its last position.
    • A process still routing with an access plan that another process migrated away from answers Unavailable instead of granting rows with old rules.
    • Non-default tenants are refused on external (Prisma) tables, which hold one set of rows.
    • Updates are recorded with the row as the database stored it (numeric scale, triggers, updatedAt).
    • A connection Postgres terminates no longer crashes the process, a bootstrap or pull stream the consumer stops reading is rolled back, and concurrent capture drains no longer deadlock (the background loop survives a failed pass).
    • FsSnapshotStore names files by a hash of the key, so a long client-chosen id can't break bootstraps.
  • Client:

    • Tabs and IndexedDB stay consistent across fresh loads, sign-out ($clear() stops every tab and wipes storage), stale models and storage upgrades; unsent writes survive an upgrade.
    • Moved rows stay out, load answers drop rows they no longer hold, and a reset replaces local state.
    • Observed lazy reads and server queries load again after access changes, and upserts kept aside for a load are dropped when the viewer loses their groups.
    • Eviction keeps every load holding an observed row and settles only unsent transactions as AccessLost.
    • Undo compares with the row's state without previews, and useLive / live() keep data observed across re-renders.
  • Prisma: capture triggers record key changes (the old id is deleted), TRUNCATE, and rows that foreign-key cascades or app triggers change during engine writes; captureDrift reports older triggers as missing. Captured writes to serverOnly models re-route the rows they affect, and fields required by Prisma's tables are checked only when writing to them.

Performance

  • Captured writes are drained in batches, in the same step that sequences the outbox, interleaved so a backlog delays the log instead of stopping it (before, past ~1,000 Prisma writes/s nothing reached clients). Postgres notifications wake the sequencer and followers instead of the 250 ms poll (kept as a fallback); concurrent sequenceNow calls share one run, and a process publishes its own batches from memory.
  • Each log batch is delivered only to the connections it can reach, serialized once per group set.
  • Polls and reconnects catch up from an in-memory log of recent actions (recentLogActions, default 50,000), indexed by group so a catch-up visits only its viewer's rows.
  • Routing prefetches each step's rows a page at a time, side-table rows are looked up by key (adopting millions of Prisma rows is no longer quadratic), and routing metadata is written by key also on tables without statistics.

Published to npm