Networked access

Subscription resumption

Resume retained changes with a sequence and epoch, and reload application state when replay is unavailable.

A reconnecting subscriber can request changes after its last processed sequence. Store that sequence together with its database epoch, because a sequence from another database cannot establish where this database's history begins.

Serve an orders table

The complete resume.ts example creates a temporary file and a loopback server on an automatically allocated port. It uses SQL only inside this local demonstration. Install the server peer from getting started before executing it.

The example receives one order, disconnects, writes two more orders, and resumes from the earlier cursor. It then supplies a foreign epoch to demonstrate a reset. All clients and the temporary database close at the end.

resume.ts
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { setTimeout } from 'node:timers/promises'
import { type ChangeEvent, Sirannon } from '@delali/sirannon-db'
import { SirannonClient } from '@delali/sirannon-db/client'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { createServer } from '@delali/sirannon-db/server'
 
const waitFor = async (condition: () => boolean): Promise<void> => {
  const deadline = Date.now() + 5000
  while (!condition()) {
    if (Date.now() >= deadline) throw new Error('Delivery exceeded the example deadline')
    await setTimeout(20)
  }
}
 
const directory = await mkdtemp(join(tmpdir(), 'sirannon-resume-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
const clients: SirannonClient[] = []
const server = createServer(sirannon, { host: '127.0.0.1', port: 0, acceptSql: true })
 
try {
  const shop = await sirannon.open('shop', join(directory, 'shop.db'))
  await shop.execute('CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT NOT NULL)')
  await shop.watch('orders')
  await server.listen()
  const url = `http://127.0.0.1:${server.listeningPort}`
 
  let cursor: bigint | undefined
  let epoch: string | undefined
  const firstEvents: ChangeEvent[] = []
  const first = new SirannonClient(url)
  clients.push(first)
  await first.database('shop').on('orders').subscribe((event: ChangeEvent): void => {
    firstEvents.push(event)
    cursor = event.seq
  }, {
    onSubscribed: (info): void => {
      cursor = info.seq
      epoch = info.epoch
    },
  })
 
  await shop.execute('INSERT INTO orders (id, customer) VALUES (?, ?)', [1, 'Anna Kowalska'])
  await waitFor((): boolean => firstEvents.length === 1)
  if (cursor === undefined || epoch === undefined) throw new Error('The server supplied no resume position')
  const resumeSeq = cursor
  const resumeEpoch = epoch
  first.close()
 
  await shop.executeBatch('INSERT INTO orders (id, customer) VALUES (?, ?)', [
    [2, 'Stefan Becker'],
    [3, 'Sunita Verma'],
  ])
 
  const replayed: ChangeEvent[] = []
  const second = new SirannonClient(url)
  clients.push(second)
  await second.database('shop').on('orders').subscribe((event: ChangeEvent): void => {
    replayed.push(event)
  }, { sinceSeq: resumeSeq, epoch: resumeEpoch })
  await waitFor((): boolean => replayed.length === 2)
  second.close()
 
  let didReset = false
  const third = new SirannonClient(url)
  clients.push(third)
  await third.database('shop').on('orders').subscribe((event: ChangeEvent): void => {
    console.log('A later live change:', event.row.id)
  }, {
    sinceSeq: resumeSeq,
    epoch: 'another-database',
    onReset: (): void => { didReset = true },
  })
  await waitFor((): boolean => didReset)
  const refreshed = await third.database('shop').query('SELECT id, customer FROM orders ORDER BY id')
  console.log(JSON.stringify({
    replayedIds: replayed.map((event: ChangeEvent): unknown => event.row.id),
    didReset,
    refreshedRows: refreshed.length,
  }, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
  for (const client of clients) client.close()
  try {
    await server.close()
  } finally {
    try {
      await sirannon.shutdown()
    } finally {
      await rm(directory, { recursive: true, force: true })
    }
  }
}

The five-second wait is an example deadline, not a delivery guarantee. The local array represents application processing within this process; a durable application needs to commit its state and cursor together.

Subscribe and store the cursor

A raw WebSocket subscriber sends a subscribe message with an ID and table. The subscribed reply contains seq and epoch. With no earlier cursor, use that sequence as the baseline, including when the table remains idle.

Raw protocol sequences use non-negative decimal strings. The SDK converts them to bigint. A missing sinceSeq starts from the current position; zero is a supplied cursor.

Advance the cursor with each change

Advance the application cursor only after applying that change. Persist the derived state and cursor atomically when they need to remain consistent through a crash.

The SDK does not wait for a subscription callback's returned promise. An asynchronous persistence operation therefore needs application-controlled ordering. Use getResumeSeq to return the durable cursor on each reconnection when the SDK's received position differs from committed application state.

Callback failures reach onError when configured. They do not turn a received sequence into proof that the application saved its derived state.

Resume after a disconnect

Send sinceSeq and its matching epoch with the new subscription. The server confirms the subscription before replaying retained events above that cursor, then continues with live events in order.

The SDK automatically restores active subscriptions on a temporary disconnect when autoReconnect is enabled. An application restarting its process must supply its persisted cursor and epoch again.

Replayed events have the same shape as live events, so the same application handler can apply both. Make application processing idempotent when a crash can cause replay of a previously applied change.

Force a resync and recover

The server reports resync: true when the epoch differs, the requested cursor exceeds the change log's assigned sequence, retained history cannot cover the gap, or replay fails.

A syntactically invalid cursor fails with INVALID_MESSAGE. A correctly formatted cursor beyond the log requires reset, because a client cannot confirm changes that the database has never assigned.

The subscription can continue live after a reset, so treat the earlier state as stale and obtain a replacement. Queue changes that arrive during replacement and coordinate their application with the replacement's cursor. The demonstration has no concurrent writers while it rereads; a plain SELECT alone provides no general snapshot-and-stream coordination.

Use a live query when the application needs the maintained result of a supported query. Use device sync recovery when replacing a complete local database.

A database's cdcRetention overrides the server's cdcRetentionMs for its retained change history. The default is 3,600,000 milliseconds. Device cursors have additional retention rules; if the server deletes a connected device's cursor, its next acknowledgement or log scan closes with 4410.

Let the client SDK resume for you

SubscribeOptions accepts sinceSeq, epoch, getResumeSeq, onSubscribed, onReset, and onError. Store the baseline from onSubscribed, handle a reset explicitly, and close the subscription when its consumer ends.

The transport reports a server refusal during restoration through onError and ends that subscription. A temporary connection failure can retry. A terminal authentication refusal requires a fresh client with a valid credential.

Client SDK explains credentials and transport lifecycle. Server lists the raw message fields for clients in other languages.