Skip to content

Client sync and offline

Akter.clientSync gives a browser its own replica of an actor. The client runs the actor’s command handlers at once, keeps commands through reloads and offline periods, and converges on the server’s order when it reconnects. Synced tables can also fill a read-only SQLite database in the browser.

Declare client sync on an actor⁠

Add sync to the actor with the callers that may subscribe and the tables that reach the client. Each synced table must also appear in tables.

src/stock.actor.ts
import { Effect, Schema } from "effect"
import { Akter } from "@akterjs/effect/contract"
import type { ImplementationOf } from "@akterjs/effect/contract"

export const Buyer = Akter.caller("user", Schema.Struct({ id: Akter.PrincipalId }))

export const InStock = Schema.TaggedStruct("InStock", { units: Schema.Int })

export const SoldOut = Schema.TaggedStruct("SoldOut", {})

export const OrdersTable = Akter.table("orders", {
  columns: { id: Schema.String, note: Schema.String },
  indexes: [],
  primaryKey: ["id"],
})

export const Stock = Akter.make("Stock", {
  callers: [Buyer],
  commands: {
    buy: Akter.command({
      callers: [Buyer],
      errors: [],
      from: [InStock],
      input: Schema.Struct({ ticket: Schema.String }),
      output: Schema.Int,
      to: [InStock, SoldOut],
    }),
  },
  initial: { input: Schema.Struct({ units: Schema.Int }), to: InStock },
  key: Schema.String,
  parent: Akter.Root,
  queries: {},
  states: [InStock, SoldOut],
  sync: Akter.clientSync({ callers: [Buyer], tables: [OrdersTable] }),
  tables: [OrdersTable],
})

export const stockHandlers: ImplementationOf<typeof Stock> = {
  commands: {
    buy: ({ units }) =>
      Effect.succeed(
        units === 1
          ? { next: SoldOut.make({}), output: 0 }
          : { next: InStock.make({ units: units - 1 }), output: units - 1 },
      ),
  },
  initial: ({ units }) => ({ next: InStock.make({ units }) }),
  queries: {},
}

The server runs Stock.toLayer(stockHandlers). The browser imports the same stockHandlers, so each command has one handler.

Open a synced actor in the browser⁠

  1. Import syncedActor from @akterjs/client/sync.
  2. Pass the actor, its handlers, the key, the caller, and the server URL.
  3. Pass storage to keep the replica in IndexedDB across reloads.

This example connects to a running akter dev as ada:

src/stock-client.ts
import { Akter } from "@akterjs/effect/contract"
import { syncedActor } from "@akterjs/client/sync"
import { Stock, stockHandlers } from "./stock.actor"

export const stock = await syncedActor({
  actor: Stock,
  headers: () => ({ "akter-principal": "ada" }),
  implementation: stockHandlers,
  key: "concert",
  principal: { id: Akter.PrincipalId.make("ada") },
  storage: { database: "akter-replicas", factory: indexedDB },
  url: "http://localhost:4000",
})

const { commandId, outcome } = stock.submit("buy", { ticket: "a-12" })

console.log(commandId, await outcome)

submit updates the view before it returns. outcome resolves to an Exit when the server commits or rejects the command. If the connection drops before the reply arrives, the client asks again with the same command id, so the outcome still resolves. Call close() when the page no longer needs the actor. close() saves the replica and fails each outcome that is still open with ConnectionLostError.

Without storage, the replica lives in memory and a reload loses pending commands. With storage, the client stores one replica for each actor, key and caller, so a second user of the same browser starts empty.

Open each replica in one tab at a time. Two tabs that share an actor, key and caller overwrite each other’s stored commands.

Render a synced actor in React, Solid or Svelte⁠

Each UI package reads the view of a synced actor and follows every change.

ReactSolidSvelte
useSyncedView(stock)createSyncedView(stock)syncedView(stock)
src/stock-button.tsx
import { useSyncedView } from "@akterjs/react"
import { Option } from "effect"
import { stock } from "./stock-client"

export const StockButton = () => {
  const view = useSyncedView(stock)
  const units = Option.match(view.state, {
    onNone: () => "loading",
    onSome: (state) => (state._tag === "InStock" ? String(state.units) : "sold out"),
  })

  return (
    <button onClick={() => stock.submit("buy", { ticket: crypto.randomUUID() })}>
      {units} left{view.pending > 0 ? " (saving)" : ""}
    </button>
  )
}

To show a rolled-back command, read view.rejection. It holds the command id, the member and the typed failure of the last rejected command.

Query synced tables with SQL⁠

mountClientDb from @akterjs/client/db keeps the synced tables in a browser SQLite database. It stores the database in the origin private file system when the browser has one, and in memory otherwise.

src/orders.ts
import { mountClientDb } from "@akterjs/client/db"
import { Stock } from "./stock.actor"
import { stock } from "./stock-client"

const db = await mountClientDb({ name: "concert-orders", replica: stock, sync: Stock.sync })

const orders = await db.query("SELECT id, note FROM orders ORDER BY id", [])

const stop = db.subscribe(() => {
  console.log(db.version())
})

The database applies each authoritative batch in one transaction. Optimistic commands do not write rows, because only the server writes synced tables. A query that writes fails.

The database stores rows on disk, so include the user in name. One database holds one actor key at a time. A reset for another key replaces its rows. A database mounted after the synced actor connects receives a fresh reset snapshot.

To see the tables that the twin creates, print the DDL of each synced table:

src/print-sync-tables.ts
import { Effect } from "effect"
import { syncTableContracts } from "@akterjs/effect/contract/sync"
import { Stock } from "./stock.actor"

const tables = await Effect.runPromise(syncTableContracts(Stock.sync))

console.log(tables.map(({ ddl }) => ddl).join("\n"))
Text
CREATE TABLE "orders" ("id" TEXT NOT NULL, "note" TEXT NOT NULL, PRIMARY KEY ("id")) STRICT

Reference⁠

The replica view⁠

FieldMeaning
stateThe confirmed state with every pending command applied. None until the first batch or stored replica.
confirmedThe last state that the server committed.
pendingThe number of commands whose outcome the client has not received.
refusedThe failure that ended the subscription, such as a caller that may not sync the actor. The client stops reconnecting, and open and later outcomes fail with it.
rejectionThe last rejected command as { commandId, member, failure }, or None.
onlinetrue while the sync subscription is open.
versionThe actor version of the confirmed state.

What runs on the client⁠

FacetOn the client
The state passed to the handler, the input, and Effect codeRuns as on the server.
Akter.db, Akter.fs, Akter.search and channel membersServer-only. The command waits for the server and changes nothing locally.
Channel publishDoes nothing locally. The server publishes when it commits.
New ids and timersGet a local- id until the confirmed state replaces it.

Convergence⁠

The server’s commit order decides the final state. When a batch arrives, the client drops the committed commands and applies the pending commands again over the new state. A rejected command leaves the pending list, and its optimistic effect disappears from state.

The published contract counts these changes as breaking: removing sync, dropping a sync caller, and dropping a sync table.