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 the changes after the last sequence that it processed. Store that sequence together with the epoch of its database, because a sequence from another database marks no position in this database's history.

Serve an orders table

The complete resume.ts program below creates a temporary file and a loopback server on a port that the operating system allocates. The server accepts SQL only for this local demonstration. Install the server peer from getting started before you execute the program.

The program receives one order and disconnects, then writes two more orders before it resumes from the earlier cursor. Last, it supplies the epoch of another database, so that the server resets the subscription. The finally block closes every client, shuts down the server and the registry, and removes the temporary directory.

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, 'customer-1'])
  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, 'customer-2'],
    [3, 'customer-3'],
  ])
 
  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 })
    }
  }
}

waitFor gives each delivery five seconds so that the example ends when a delivery fails, although Sirannon itself sets no delivery deadline. The arrays in the example stand in for the processing of an application, while a durable application has to commit its state and its cursor together.

Subscribe and store the cursor

A raw WebSocket subscriber sends a subscribe message with an ID and a table. The server's subscribed reply contains seq and epoch. When the subscriber has no earlier cursor, use that sequence as the baseline, even while the table receives no writes.

The raw protocol sends each sequence as a non-negative decimal string, which the SDK converts to a bigint. Without sinceSeq, the subscription starts from the current position, while a sinceSeq of zero counts as a cursor.

Advance the cursor with each change

Advance the application cursor only after your application applies that change. When the derived state and the cursor have to agree after a crash, persist them in one atomic write.

The SDK calls the next subscription callback without awaiting the promise that the previous one returns, so your application has to order its asynchronous writes itself. When the position that the SDK receives can differ from the state that your application commits, use getResumeSeq to return the durable cursor on each reconnection.

The SDK passes a callback failure to onError when you configure one. A sequence that the client receives shows only that the client received the change, so your application has to record separately that it saved the derived state.

Resume after a disconnect

Send sinceSeq and its matching epoch with the new subscription. The server confirms the subscription before it replays the retained events after that cursor, and it then sends the live events in order.

With autoReconnect on, the SDK restores the active subscriptions after a temporary disconnect. When your application restarts its process, it has to supply its persisted cursor and epoch again.

Replayed events have the same shape as live events, so one handler can apply both. When a crash can make the server replay a change that your application applied before, make that processing idempotent.

Force a resync and recover

The server reports resync: true in four cases: the epoch differs, the cursor is beyond the newest sequence in the change log, the retained history starts after the cursor, or the replay fails.

The server refuses a malformed cursor with INVALID_MESSAGE. It resets a well-formed cursor beyond the log, because the database contains no change after its newest sequence.

After a reset, the subscription can go on delivering live changes, so treat the earlier state as out of date and load a replacement. Queue the changes that the client receives during the reload, and apply them against the cursor of the reloaded state. In the example, no other process writes while the program rereads the table; in general, a plain SELECT returns no cursor, so you cannot match the rows that it returns to a position in the change stream.

Use a live query when your application needs a query result that the server updates as the rows change. Use device sync recovery when you replace a whole local database.

A database's cdcRetention overrides the server's cdcRetentionMs for the change history that Sirannon retains for that database. Both default to 3,600,000 milliseconds. Device cursors follow separate retention rules. When the server deletes the cursor of a connected device, it closes that device's connection with 4410 at its next acknowledgement or log scan.

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.

When the server refuses a subscription while the client restores it, the client reports the refusal through onError and ends that subscription. After a temporary connection failure, the client can reconnect, while after a final refusal of the credential you have to construct a new client with a valid credential.

Client SDK explains credentials and the lifecycle of the transport. Server lists the raw message fields for clients in other languages, and the Python client and the Go client send those messages for you.