Offline writes and sync
Apps built on phibac (web apps that store each user's data through the SDK, the JavaScript library your page uses) keep working without a network connection. This page explains what the SDK does with a write while the device is offline, how changes from several devices are combined, and what your app should show the user.
Writes are saved on the device first
When your app calls create, update or delete, the SDK does not wait for the server. It applies the change at once to its copy of the user's data (the user is the person whose data it is) in the browser, adds the change to the write queue, and returns.
The write queue is the list of changes the device has made that the server does not have yet. It is kept in the browser's storage, like the copy of the data, so it survives a page reload: the next time your app calls connect() in that browser, the SDK sends what is still queued.
Each record (one saved item, such as one note) your app gets has a status, which is one of two values:
pending: the record has a change the server has not confirmed yet. A note created offline ispending.synced: the server has confirmed the record's latest change.
Reads never wait for the network either. get and list answer from the copy in the browser at once, and queries and live updates (the SDK tells your page when data changes) include your pending changes, so a note the user just wrote shows up straight away, marked pending.
How the queue is sent
Whenever the device is online, the SDK sends the queue to the server in the order the changes were made. As each change is accepted, its record becomes synced.
If a change cannot be sent for a reason that may pass, it stays in the queue together with every change after it, and the SDK tries again later, waiting longer after each failure. Such reasons are no connection, a server error, a suspended app (app_suspended) and a sign-in the server no longer accepts (unauthorized). That last one passes only when the user signs in again: the SDK forgets the refused sign-in, so call connect() again from a click, and the queued changes are sent once the user has signed in.
backend.status() tells your app where things stand. It returns online (whether the server is reachable), pending (how many changes are queued) and, while something the user must fix holds up the queue or live updates, problem: the error to show them, such as app_suspended.
The server's order wins
When two devices change the same record, the server applies the changes in the order it receives them, and that order wins. Each change replaces only the fields it sets:
- A phone sets a note's
textwhile offline, and a laptop sets the same note'spinned. Both changes are kept, whatever order they arrive in. - Both devices set
text. The change that reaches the server last is the one that stays.
The version a change replaced is not thrown away: it goes into the record's history, where it is kept for 30 days and the user can restore it from their account area (see Collections and records). Your app gets no error for this; the record simply shows the server's result once it is synced.
Because the last write wins, do not keep a counter or a total in a record that several devices change: increments made offline on two devices overwrite each other. Store one record per event and add them up in your code instead.
When the server refuses a change: onConflict
Some changes can never succeed, however often they are retried. For example, the user edits a note offline on the phone while the laptop deletes it: when the phone comes back online, the server refuses the edit with record_deleted. Other such refusals are a record that breaks the schema, the description of the fields a collection's records may have (schema_violation), a write to a collection (a kind of data, such as notes) your app may not write (forbidden) and a record over the size limit (payload_too_large).
The SDK then drops the refused change from the queue, puts the record back to the server's state, and calls the function you passed to backend.onConflict(). It receives:
op: the dropped change, with its kind (create,updateordelete), its collection and its rkey (the key that identifies the record within its collection).error: why the server refused it, with acodesuch asrecord_deleted.localData: the record's data as your app had it with that change, so you can show it or save it again.
If a refused change was a create, the changes queued after it for the same record are dropped and reported too, since the record never existed on the server.
Register the function once, right after connect():
import { connect } from "@phibac/sdk";
interface Note {
text: string;
pinned?: boolean;
}
// The same value as SCHEMA_MAJORS in the file phibac generate writes (src/pb-types.ts).
const SCHEMA_MAJORS = { "com.example.notes.note": 1 } as const;
const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
const message = document.querySelector<HTMLParagraphElement>("#message")!;
signIn.addEventListener("click", async () => {
const backend = await connect({ app: "app_...", baseUrl: "http://localhost:8787", schemaMajors: SCHEMA_MAJORS });
const notes = backend.collection<Note>("com.example.notes.note");
// Called when the server refuses a queued change for good.
backend.onConflict(({ op, error, localData }) => {
const lost = localData as Note | null;
message.textContent = `A change to a note was not saved (${error.code}).` + (lost ? ` Its text was: ${lost.text}` : "");
console.log("dropped", op.kind, op.rkey);
});
// Live list: a note shows "(pending)" until the server has it.
notes.subscribe((records) => {
console.log(records.map((r) => `${r.data.text} (${r.status})`));
});
});
Two tabs and several devices
Tabs of the same app in the same browser, signed in as the same user, share one copy of the data and one write queue. A note saved in one tab appears in the other tab's live updates without reloading. Where the browser supports the lock the SDK uses to coordinate tabs, only one tab at a time sends the queue; where it does not, two tabs may send the same change. Either way the server applies each change once.
Another browser or device has its own copy and its own queue. Its changes reach this one through the server: once they are sent, live updates bring them to every other device that is online, and a device that was offline catches up when it reconnects.
Starting while offline
A user who has signed in to your app in this browser before can open it offline. connect() needs no network then: it finds the stored sign-in and returns at once. Your app shows the records that were copied to the browser earlier, and new changes wait in the queue until the device is back online.
Some things need the server and do not work offline:
- The first sign-in in a browser, which happens in a popup on the server.
- Asking for another app's data with
requestAccess(). - Uploading and deleting files. These are not queued: offline they fail at once, and your app should let the user try again later.
- Data the browser has not seen yet. Records saved on another device appear only after this device reconnects and catches up.
Signing out
backend.signOut() deletes this user's copy of the data and their queued changes for your app from the browser. Changes that are still pending at that moment are lost. If status().pending is above zero, warn the user before signing out, or wait until it reaches zero.