Persistence and the offline queue

Copy Markdown View Source

Steps 7 and 8 of the walkthrough that starts in Getting started: persisted keys, the queue of server actions made offline, and what happens to calls that fail or are cancelled.

7. Persisted state

persist keeps the confirmed values of some keys in the browser and restores them when the store is created again, for example after a reload:

import { createStore } from "live_slice";

const settings = createStore("settings", {
  state: { theme: "light", sidebarOpen: true, draft: "" },
  persist: {
    keys: ["theme", "sidebarOpen"], // only these keys are stored
    version: 2, // an integer, 1 by default
    // Optional: turns a record stored by another version into the current state.
    migrate: (stored, storedVersion) => (storedVersion === 1 ? { theme: stored.colors } : {}),
    // Optional: decides which queued server actions survive a version change (see step 8).
    migratePending: (entry, storedVersion) => entry,
  },
});

await settings.ready; // resolves once the stored values were restored; never rejects
settings.hydrated; // true from then on
  • Storage is IndexedDB by default (database live_slice, object store stores, one record per store name), and memory when the page has no IndexedDB. Pass persist.storage to use another adapter: createIndexedDBStorage({ database }), createMemoryStorage(), or any object with async get(name), set(name, record) and remove(name), and preferably update(name, fn), an atomic read-modify-write that stores what fn(storedRecord) returns (nothing when it returns undefined). Both built-in adapters have it. Without it, a write is a get followed by a set, and a write another tab makes between the two is lost (see Multiple tabs).
  • Restoring is asynchronous. Until ready resolves, the state holds the initial values. A persisted key written before then (by setState, a client-only action, a server patch or a confirmed server action) keeps that newer value, and the stored value is ignored for that key. The bridge waits for ready before its mount-time mirror push and before sending server actions; patches are applied from the start.
  • Only confirmed values are written, never optimistic ones. The first change schedules one write 100 ms later that carries every change made until then; await store.flush() writes at once, and a scheduled write is flushed when the page is hidden (pagehide, visibilitychange). A store writes only when the confirmed value of a persisted key or its queue of server actions changed: a change of another key, also one made before ready, writes no record (nor replaces a clear's marker, see Stores that come and go).
  • The state of a record stored with another version is discarded, unless migrate returns the state to use.
  • Pending server actions are persisted too (see step 8), so actions made offline survive a reload.
  • Persisted values must survive the structured clone algorithm, which IndexedDB uses: plain JSON data always does; functions, DOM nodes and class instances do not. A storage failure (quota, private mode, a value that cannot be cloned) is reported once with console.error, and the store keeps working in memory without persisting anything more. A connection that another tab's upgrade or the browser closed is not a failure: the IndexedDB storage opens a new one and tries the call once more, and an open blocked by another tab waits for it (10 seconds at most, createIndexedDBStorage({ blockedTimeout })).

8. Offline queue

Server actions keep working while the LiveView is disconnected: they apply at once, wait in a queue, and reach the server after the reconnect.

const tasks = createStore("tasks", {
  state: { tasks: [] },
  actions: {
    addTask: { apply: (state, id, title) => ({ tasks: [...state.tasks, { id, title }] }), server: "add_task" },
  },
  persist: { keys: ["tasks"] }, // also keeps the queue across reloads
  maxAttempts: 3, // the default
});

// Promises of a previous page are gone after a reload: these listeners see every outcome.
tasks.onSettled(({ id, status, reason }) => console.log(id, status, reason)); // "confirmed" or "rejected"
tasks.onRejected(({ action, reason }) => showError(action, reason));
  • The bridge sends one action at a time, in call order, and the next one only after the reply to the previous one. It starts on mount (after hydration), whenever an action is called, on reconnected(), and when the browser is back online. Actions called while the queue drains join its end.
  • Nothing is pushed while the LiveView is disconnected or while the browser reports being offline (navigator.onLine is false, which LiveView may not have noticed yet). The online event sends what waited, mirrored keys first.
  • A push that LiveView refuses because it is not connected, or whose reply is lost because the socket dropped while it waited (disconnected()), leaves the action pending and stops the queue until the next reconnect. A push that gets no reply within 30 seconds while its LiveView never rejoined makes LiveView 1.2 reload the page; see Known limits.
  • On reconnect, mirrored keys are pushed first and the queued actions after them: the new LiveView process starts from its defaults, so the actions then run against the client's current context.
  • A server refusal rolls back only that action, and the queue goes on with the next one.
  • Retry limit: an action pushed maxAttempts times without a reply is no longer sent: it is kept as failed, to be retried with its id or discarded, and the queue goes on with the calls it does not hold back (see Failed pushes). This keeps an action that crashes the LiveView from being replayed forever. The count is persisted with the action. With keepFailed: false the action is rolled back with the reason "push_failed" instead.
  • Delivery is at least once. An action whose reply was lost is sent again with the same meta.id, after a reconnect, a live navigation or a reload, and meta.attempt counts the sends from 1. Make handle_action/4 idempotent with meta.id wherever running a call twice would be wrong.
  • With persist, the queue is stored with the state ({id, action, args, attempts, at} per action, plus base, record, resubmits, parked, failures and retries where they apply; see Conflicts and Failed pushes) and restored on hydration before any action called meanwhile. Promises cannot survive a reload, so after one onRejected and onSettled are the only feed.
  • A stored action that cannot be restored is reported like a rejected one, through onRejected and onSettled: "unknown_action" when its action is no longer a server action of the store (apply is looked up by action name, and server is then null), "version_mismatch" when a version change drops it. On a version change, queued actions are kept when migrate is given and dropped otherwise, unless persist.migratePending(entry, storedVersion) decides: it returns the entry to keep (its args may be changed) or null to drop it. version describes the shape of the state; the server has to accept the arguments that older pages send anyway.
  • These reports, like onPending for restored actions, happen while the store hydrates. Register the listeners right after createStore, before awaiting ready, or they miss them.

onSettled(listener) receives {id, action, server, args, at, status, reason?} for every confirmed or rejected action, after the onRejected listeners. With onPending it is enough for a "saving" indicator. The store also exposes the transport API the bridge uses for the queue: maxAttempts, attempts(id), recordAttempt(id), exhausted(id), pushFailed(id, reason), markQueued(id) and claimQueue(onGranted) (see below).

Offline promises and the time of a call

The promise of an action settles with the server's answer, so offline it waits until the call is sent and answered, maybe after a reload, when it is gone. It carries what a caller needs meanwhile:

const call = tasks.actions.addTask("t1", "Tea");
call.id; // the call's mutation id, as in pending(), for cancel(id)
call.queued.then((queued) => {
  if (queued) showNotice("Saved on this device; sent when the connection is back");
});
await call; // unchanged: the server's answer
tasks.onQueued(({ id, action, args }) => markWaiting(id)); // every call that waits for a connection
tasks.pending(); // [{ id, action, server, args, at, ... }]: at is when the call was made, in milliseconds
  • call.queued resolves once: true as soon as the bridge that sends the store's actions cannot reach the server while the call is pending (the browser is offline, the LiveView is disconnected or mounted offline, or a push got no reply and the queue waits for the reconnect), false when the call settles first, which is the usual case online. Waiting behind another call in flight, or for another tab that sends the queue, is not "queued". Without a bridge, nothing reports: queued resolves when the call settles.
  • onQueued(listener) receives {id, action, server, args, at, base?, record?} once per call and page when the bridge reports it, also for calls restored after a reload, whose promises are gone.
  • call.id stays the id of the original call; a conflict resubmission goes on under a new id (see Conflicts), while its promise and queued follow it. Only the promise the action returned carries these fields, not the promises that .then() returns.
  • pending() entries carry at, the time the call was made (Date.now()). It is persisted and shared between tabs with the call and kept by its resubmissions, so it is the time the person acted; an entry stored by an older version of the library has none.
  • Every listener event about a call carries the same at: onPending, onQueued, onFailed, onRetry, onConflict (parked or not), onRejected and onSettled (whatever the status), and so does the context of an onConflict resolver. It is the value pending() reports, also for a call restored after a reload, one dropped by it ("unknown_action", "version_mismatch"), and one another tab made or settled. The event shapes in these guides list it as at; it is absent only for an entry stored by an older version.

Draining the queue on every page

A store's queued server actions are sent only by a bridge rendered for a LiveView that handles them (the bridge carries data-actions). With one use LiveSlice per LiveView, every page that should drain a store's queue had to declare the store and repeat handle_action/4. Define the actions once instead:

defmodule MyAppWeb.TaskActions do
  use LiveSlice.Actions, store: :tasks, actions: [:add_task, :rename_task]

  @impl LiveSlice.Actions
  def handle_action(:add_task, [title], %{id: mutation_id}, socket) do
    # the same arguments and replies as LiveSlice.handle_action/4
  end
end

Attach it to a LiveView with on_mount MyAppWeb.TaskActions, or to every LiveView of a live_session with live_session :default, on_mount: [MyAppWeb.TaskActions], and render its bridge in every LiveView that attaches it:

<LiveSlice.bridge id="tasks-store" module={MyAppWeb.TaskActions} />

A layout is the place for it only when every LiveView that renders the layout attaches the module (give that live_session its own layout:). A connected LiveView that renders a bridge sending a module's actions without attaching the module raises an ArgumentError at its first render, naming the on_mount to add: otherwise every queued action would be refused and rolled back. Where the module is not attached, render <LiveSlice.bridge id="tasks-store" store={:tasks} />, which leaves the queue waiting for a page that sends it.

  • The actions run in the LiveView that rendered the bridge, with its socket. That LiveView may use LiveSlice for another store, whose mirror, actions and collaborative keys keep working, or not use it at all.
  • Actions of a store that no attached module and no use LiveSlice handles are refused with "unknown_store", as before. Declaring a store's actions with use LiveSlice and attaching a module for the same store raises at mount; attaching one module twice (from the live_session and the LiveView) attaches it once.
  • A LiveView that uses use LiveSlice for the same store (to mirror keys, say) without declaring its actions leaves them to the attached module; name the module in its bridge, so one bridge mirrors and sends the queue: <LiveSlice.bridge id="tasks-store" module={__MODULE__} actions={MyAppWeb.TaskActions} /> (the module must handle the bridge's store and be attached, as above).
  • On the client, a bridge whose page has no bridge that sends the store's actions logs a warning, once per store and page, when server actions are queued: they stay queued (and persisted, with persist) until a page that sends them.

Failed pushes

An action pushed maxAttempts times without a reply is kept as failed, with its mutation id, until the application retries or discards it. Rolling it back instead (keepFailed: false, the behaviour before this version) loses the user's change unless they redo it, and the redone call has a new id: if one of the pushes did reach the server and only its reply was lost, the server cannot tell the new call from the first one, and an action with a base conflicts with the user's own change.

const tasks = createStore("tasks", {
  state: { tasks: [] },
  actions: { renameTask: { apply, server: "rename_task", base, record: (id) => ["task", id] } },
  persist: { keys: ["tasks"] },
  // keepFailed: true is the default; false rolls failed calls back with "push_failed"
});

tasks.onFailed(({ id, action, args }) => showRetry(id, action, args));
tasks.pending(); // [{ id, action, server, args, base, record, failed: true }, ...]
tasks.retry(id); // sent again: same id, args, base and record, for maxAttempts more pushes
tasks.discard(id); // or rolled back: its promise rejects with "discarded"
  • Kept as failed. The call stays pending and applied, with its id, arguments, base and record, and its promise waits. pending() lists it with failed: true, and onFailed(listener) receives {id, action, server, args, at, base?, record?, failed: true, reason} when it fails (in this tab, or in another tab that holds it).
  • retry(id) makes it sendable again. The server receives the same meta.id, the same meta.base, and meta.attempt counting on from the earlier pushes (4, 5, ... with the default maxAttempts); it gets maxAttempts more pushes before it fails again. onRetry(listener) is called, and the bridge sends it from there, at once, also when the queue had stopped after a push that failed without a disconnect (a timeout). Returns false for an id that is not a failed call.
  • discard(id) rolls it back like a rejection, rejects its promise with "discarded" and reports it to onSettled with the status "discarded" (not to onRejected: the user chose it). Returns false for an id that is not a failed call.
  • Order. A failed call holds back every later call that may concern the same record: a later call with the same record, or one where either call declares none. They wait, listed with blocked: true in pending(), until the failed call is retried (it is then sent first, since it comes first in the queue) or discarded. A later call that declares another record than the failed one goes on. So a later edit never overtakes a failed edit of the same record, while the rest of the queue is not stuck behind it. Declare record on your actions (see Conflicts) to let unrelated calls go on.
  • Persisted and shared. The failed state is stored with the queue (failures and retries counts in the entry), so a reload restores the call as failed (announced through onPending with failed: true) and does not send it until it is retried. Tabs announce failures, retries and discards to each other.
  • On the server, nothing is built in: deduplicate by meta.id in handle_action/4. Look the id up before anything else and answer a call already applied as the first time (the reply state included), as in Conflicts; record the id in the same transaction as the change. A retried call then never conflicts with its own first push, and a call whose first push did not land is applied once.
  • An application that never retries nor discards. Nothing retries or discards on its own. A failed call stays applied (the user keeps seeing the change), pending and persisted, so it is still there after a reload and in every tab, its promise never settles, and it holds back for good every later call that may concern its record: the later calls of the same record and those that declare none, or, when the failed call declares no record, every later call of the store, so the queue stops there. Calls of other records go on, and new failures add up. They show in pending() (failed: true on the call, blocked: true on the calls it holds back), through onFailed when they fail and onPending (with failed: true) when a reload restores them. When a call is kept as failed only because of this default (the store does not set keepFailed) and the store has no onFailed listener, it is reported once per store and page with console.warn. Offer retry and discard where the user sees their changes, or set keepFailed: false.

A store created with keepFailed: false treats a call stored as failed by a page that kept it (a configuration change) as used up: it is rejected with "push_failed" when the queue reaches it. A tab still running a version before this default does the same.

Cancelling

cancel(id) takes back a queued call that was never sent: made offline, or waiting behind other calls. That is all an "undo" needs:

const call = tasks.actions.renameTask("t1", "Typo");
undoButton.onclick = () => tasks.cancel(call.id); // false once it was sent
  • The call is rolled back, its promise rejects with "cancelled", and onSettled reports it with the status "cancelled" (not onRejected: the user chose it). It leaves the persisted queue and is announced to the other tabs, which drop it too.
  • In flight: not cancellable. A call pushed at least once (waiting for its reply, or sent without one before a disconnect) may already have reached the server, so cancel returns false and changes nothing. Undo its effect with another action once it settled (a compensating rename back, for example). cancel also returns false for an unknown or settled id, for a failed call (use discard, see Failed pushes) and for a call parked on a conflict (use resolveConflict, see Conflicts).
  • Later calls stay queued with their base and are replayed without the cancelled one: their apply runs again on the state without it. Cancel them too (newest first) when they only made sense on top of it.
  • A resubmitted call (see Conflicts) can be cancelled by the id of the original call, as long as the resubmission was not pushed yet.
  • Tabs. The tab that sends the queue announces each push, so cancel in another tab returns false for a call that tab pushed, parked or saw fail, as it does for its own. Only a push and a cancel that cross (neither tab heard of the other yet) race: the sending tab keeps the call and settles it with the server's answer, and when that answer is a confirmation, the tab that cancelled applies the call's change and the reply's state after all and reports it to onSettled with the status "confirmed" (its promise stays rejected). discard behaves the same: a failed call that the sending tab retried before the discard reached it is kept there and answered. Cancel in the tab that sends the queue (the one whose bridge holds it, see Multiple tabs) for a certain answer; offline, no tab sends anything, so a cancel always holds.