A device needs recovery when the server cannot support sync, the local copy needs replacement, or the device's schema differs from the server's schema. Handle each condition before enabling edits, because a snapshot replaces local tables.
Confirm the server can sync
Before opening the pull, start() checks capabilities. The required tokens are sync.push, sync.echo-suppression, sync.ack, sync.resume, sync.snapshot, sync.migrations, sync.schema-gate, and sync.stream-apply. The last token covers transaction boundaries, row IDs, and acknowledgement-paced delivery.
The optional sync.staged-stream token enables packed frames and pacing by individual changes. Without it, a compatible server sends one frame per change.
A missing required capability fails with SYNC_UNSUPPORTED. A server with device sync disabled fails with DEVICE_SYNC_NOT_ACCEPTED. Catch these RemoteError codes around start() and show a server compatibility message. Authentication refusals such as UNAUTHORIZED and FORBIDDEN also need application action.
An unreachable server is a different condition. start() resolves with state: 'running' and an error in lastError, while the controller retries with back-off. A device that already has a usable copy can continue saving locally.
Give a device a full copy of the database
A first start() subscribes from the server's current position; it does not copy rows that already exist there. Call downloadSnapshot() before accepting edits on a fresh device.
The complete recovering-device.ts file connects to the single-account server from device sync. It uses a separate browser database and a durable bootstrap marker. Load it through your browser application's bundler. Its exported functions let the application save a note, request another copy, and close its database.
The example sets autoResync: false so that the application controls replacement. Present a reload action when resyncRequired is true and call replaceLocalCopy() from that action. With automatic recovery enabled, the controller schedules downloads after a resync signal, after an interrupted load on startup, and after a failed download.
import { Sirannon } from '@delali/sirannon-db'
import { waSqlite } from '@delali/sirannon-db/driver/wa-sqlite'
import {
LWWResolver,
RemoteError,
type SnapshotOutcome,
type SnapshotProgress,
type SyncStatus,
SyncController,
} from '@delali/sirannon-db/client'
const session = window.prompt('Enter the notes session token')
if (!session || !/^[a-f0-9]{64}$/.test(session)) {
throw new Error('A 64-character hexadecimal session token is required')
}
const BOOTSTRAP_KEY = 'notes-account:recovering-notes:bootstrapped'
const sirannon = new Sirannon({ driver: waSqlite() })
const db = await sirannon.open('notes', 'recovering-notes.db')
const hasPendingLoad = await db.deviceSync().snapshotLoadPending()
const hasSavedPull = (await db.deviceSync().getPullState()) !== null
if (!hasSavedPull) localStorage.removeItem(BOOTSTRAP_KEY)
if (!hasPendingLoad) {
await db.execute('CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, author TEXT NOT NULL, body TEXT NOT NULL)')
await db.watch('notes')
}
let canSave = !hasPendingLoad && localStorage.getItem(BOOTSTRAP_KEY) === 'yes'
let isReplacing = false
const sync = new SyncController(db, {
url: 'http://localhost:9876',
databaseId: 'notes',
tables: ['notes'],
headers: { Authorization: `Bearer ${session}` },
webSocketProtocols: [session],
resolver: new LWWResolver(),
autoResync: false,
onResyncRequired: (): void => {
canSave = false
console.log('Request a fresh server copy before editing')
},
onStatusChange: (status: SyncStatus): void => {
console.log(status.state, status.resyncRequired, status.lastError)
},
onSnapshotProgress: (progress: SnapshotProgress): void => {
console.log(progress.table, progress.loadedRows, progress.totalRows)
},
onSnapshotComplete: (outcome: SnapshotOutcome): void => {
canSave = outcome.databaseUsable && localStorage.getItem(BOOTSTRAP_KEY) === 'yes'
if (!outcome.ok) console.error(outcome.error.code, outcome.retrying)
},
})
export const replaceLocalCopy = async (): Promise<void> => {
if (isReplacing) return
isReplacing = true
canSave = false
try {
await sync.downloadSnapshot()
localStorage.setItem(BOOTSTRAP_KEY, 'yes')
canSave = true
} catch (error: unknown) {
console.error('The server copy could not be loaded', error)
throw error
} finally {
isReplacing = false
}
}
export const saveNote = async (author: string, body: string): Promise<void> => {
if (!canSave || isReplacing) throw new Error('Wait until the local copy is ready')
await db.execute('INSERT INTO notes (id, author, body) VALUES (?, ?, ?)', [
crypto.randomUUID(),
author,
body,
])
sync.triggerPush()
}
export const closeNotes = async (): Promise<void> => {
try {
await sync.stop()
} finally {
await sirannon.shutdown()
}
}
try {
await sync.start()
const status = await sync.status()
if (!canSave || status.resyncRequired) await replaceLocalCopy()
} catch (error: unknown) {
canSave = false
if (
error instanceof RemoteError &&
(error.code === 'SYNC_UNSUPPORTED' || error.code === 'DEVICE_SYNC_NOT_ACCEPTED')
) {
console.error('This server cannot synchronise the notes database', error.message)
} else {
console.error('Check sync status before enabling edits', error)
}
}The bootstrap marker records a completed first copy, so an intentionally empty table does not cause repeated downloads. If the database has no saved pull position, the example clears a leftover browser marker before starting the controller. Check snapshotLoadPending() before ordinary schema setup, because an interrupted replacement blocks that setup with SNAPSHOT_IN_PROGRESS. The example skips it until the controller recovers the copy. Use separate database paths and marker keys for different accounts.
downloadSnapshot() requires a started controller and drains pending pushes before replacement. Its onProgress argument overrides the controller's onSnapshotProgress callback for that download. Both report the number of loaded rows; no fixed output panel applies because the server's contents determine those values.
The loader marks the database as loading, disables foreign key checks, and replaces application tables in dependency order. It verifies each page checksum before saving it. After copying, it replaces migration history, restores capture, updates the pull cursor and epoch, and clears the loading marker. PRAGMA user_version then matches the highest migration version.
An interrupted replacement retains its loading marker. A later successful download makes the database usable again. A server refuses snapshots of an in-memory database with SNAPSHOT_UNSUPPORTED; a page checksum mismatch fails with SNAPSHOT_CHECKSUM_MISMATCH.
Turn saving back on when a copy finishes
While the loader replaces tables, reads and writes fail with SNAPSHOT_IN_PROGRESS before executing SQL. Disable edits before requesting a snapshot, because a write that commits immediately before replacement can disappear with the old tables.
onSnapshotComplete reports completion for manual and automatic downloads. Inspect databaseUsable before enabling database access. It is true after success and after a failure that leaves the earlier copy intact. A failure after replacement begins can leave it false until a later copy succeeds.
A failed outcome includes error.code, error.message, and retrying. When retrying is false, the application needs to request another copy. A manual downloadSnapshot() also rejects, so handle its promise as well as its completion callback.
onResyncRequired reports a requirement for a fresh copy. Disable editing in that callback when using automatic resync. For a manual request, disable editing before calling downloadSnapshot(), as the example does.
The server can expire a device cursor when its acknowledgement is too old, its retained history is too old, or its retained change count exceeds maxChangesHeldForDevice. The default device retention is 30 days. A connected device then receives close code 4410 on its next acknowledgement or log scan and must resync.
Keep every device on the same schema
Share a SQL migration set across the server, browser, and mobile builds. Pass that set to new Sirannon({ driver, migrations }) so that the registry can apply it to each database and the server can supply its SQL to devices. Migrations explains the complete setup.
A device sends its highest applied migration version on pushes and subscriptions. When the server is ahead, it refuses with MIGRATION_REQUIRED. The controller fetches missing migrations, verifies checksums, applies the SQL, and retries the request. The deployed device bundle can therefore receive SQL migrations newer than that bundle.
A device ahead of the server receives SCHEMA_AHEAD. Deploy the matching server schema before resuming that device.
A full snapshot is necessary when migration histories differ, when the server cannot provide a migration as SQL, or when a baseline omits migrations that the device needs. The baseline case reports MIGRATION_BASELINE_GAP. A function-based migration cannot pass through this SQL handshake.
Create and watch the starting tables before syncing. The handshake updates an existing starting schema; it does not replace that setup. Keep migrations in the server's registry, because migrating its database directly leaves the server without the SQL definitions that devices request.
Resume after a connection failure
The controller retains durable push and pull positions through pauses, restarts, and temporary failures. A stale epoch or unavailable cursor requires a snapshot. A cursor beyond the available sequence is also invalid; it cannot confirm changes that the server has not stored.
Subscription resumption explains cursor and epoch validation. Device sync explains transaction staging, conflict resolution, and status callbacks.