Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Work offline

Keep query results on the device, queue writes that survive restarts, and decide what happens to a write the luna refuses.

A write made with mutate in a tunnel waits up to 30 seconds for a connection, then fails with Timeout. If the app closes first, the write is lost, and the app opens again on an empty screen.

Keep data on the device

Give createClient a store. webStore keeps everything in localStorage under a prefix you choose.

import { createClient, webStore } from "luna/client";

export function clientFor(account: string) {
  return createClient({
    url: import.meta.env.VITE_LUNA_URL,
    key: import.meta.env.VITE_LUNA_KEY,
    store: webStore(`luna:${account}`),
  });
}

The client saves each query’s result shortly after it arrives. On the next start a query shows the saved result at once, with stale set to true, until the live result replaces it.

Use one store for each account, so that one person’s data never shows to another. Any object with get, set, delete and keys can be a store, with each call sync or async, such as one over a mobile app’s own storage.

Queue a write

enqueue saves the write in the store before it sends it. The write survives a closed tab or a restarted app, and goes once the luna can be reached.

const list = client.luna<typeof List>("List", "groceries");
const { id, done } = list.enqueue("add", { text: "milk" });
await done;

done resolves with what the handler returned. Each write carries its id as an idempotency key, so a retry after a lost answer does not run the handler twice. enqueue throws Invalid when the client has no store.

Show a queued write at once

A write queued before a restart comes back with its handler and arguments, not with your code. So an optimistic update for queued writes is given to createClient by name, and enqueue names it.

export const client = createClient({
  url: import.meta.env.VITE_LUNA_URL,
  key: import.meta.env.VITE_LUNA_KEY,
  store: webStore("luna:ann"),
  optimistic: {
    addItem: (local, { luna, args }) => {
      local.update(luna.query("all"), (items) => [...items, { id: -1, text: args.text }]);
    },
  },
});

client.luna("List", "groceries").enqueue("add", { text: "milk" }, { optimistic: "addItem" });

The update shows while the write waits in the queue, after a restart too. It goes away once a live result includes the write, or when the write fails.

Know the order writes run in

Queued writes for one luna run one at a time, oldest first. Writes for different lunas do not wait for each other. What happens to a write that fails depends on why it failed.

  • The connection or Luna had trouble. Codes Unavailable, Overloaded, Timeout and OutcomeUnknown, or a dropped connection. The client tries again with growing waits, from 200 ms up to 15 seconds, and the same idempotency key.
  • The login is no longer good. Codes Unauthorized, Unauthenticated, Forbidden and Denied, or a refusal with status 401 or 403. The whole queue waits until you call resumeWrites().
  • The luna refused it. Any other code, such as a declared error from ctx.fail. The write is marked failed, its optimistic update goes away and done rejects. The next write for that luna goes on.

Fix a write that failed

writes() lists the queue, oldest first, with each write’s status and error. subscribeWrites hears every change to it.

client.subscribeWrites(() => {
  for (const w of client.writes()) {
    if (w.status === "failed") console.warn(w.handler, w.args, w.error?.code);
  }
});

Call retryWrite(id) to send a failed write again, or discardWrite(id) to drop it. A failed write stays in the queue until you do one or the other.

Resume after a new sign-in

A queue that waits for a login goes on when you call resumeWrites(), once the person has signed in again. params gives each new connection the current login, and currentToken stands for your own sign-in code.

const client = createClient({
  url: import.meta.env.VITE_LUNA_URL,
  key: import.meta.env.VITE_LUNA_KEY,
  store: webStore("luna:ann"),
  params: async () => ({ token: await currentToken() }),
});

// After the person signs in again.
client.resumeWrites();

Wipe the device on sign-out

client.wipe() empties the store and the queue. Writes still waiting reject with Closed.

await client.wipe();

Next steps

Was this page helpful?