~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
320 lines · 16.1 KB Raw History
// The firehose: each side's subscribeRepos, one sequence across all its
// accounts, every event checked as a consumer would and the server's held to
// the reference's (spec/SYNC.md, spec/ACCOUNTS.md).

import { isDeepStrictEqual } from 'node:util'
import { readCarWithRoot, verifyProofs, verifyCommitSig, MST, MemoryBlockstore } from '@atproto/repo'
import { cborDecode, cborDecodeMulti } from '@atproto/common'
import { BACKFILL_MS } from '../lib/args.mjs'
import { chance, pick, rand } from '../lib/random.mjs'
import { cand, ref, wait } from '../lib/processes.mjs'
import { fail } from '../lib/plc.mjs'
import { count, differ } from '../lib/report.mjs'
import { accountNamed, accounts, didOf } from '../lib/state.mjs'
import { strip, xrpc } from '../lib/xrpc.mjs'

/// A subscription to the server's `subscribeRepos`, adding every event it
/// sends to `events`.
export function subscribe(side, cursor, events = []) {
  const url = `${side.url.replace(/^http/, 'ws')}/xrpc/com.atproto.sync.subscribeRepos${cursor === undefined ? '' : `?cursor=${cursor}`}`
  const ws = new WebSocket(url)
  ws.binaryType = 'arraybuffer'
  const sub = { ws, events, open: true }
  ws.onmessage = (m) => {
    try {
      const [header, body] = cborDecodeMulti(new Uint8Array(m.data))
      events.push({ header, body })
    } catch (err) {
      events.push({ header: { op: -1 }, body: { error: 'Undecodable', message: String(err) } })
    }
  }
  sub.closed = new Promise((ok) => (ws.onclose = () => ((sub.open = false), ok())))
  ws.onerror = () => {}
  return sub
}

/// What the harness has seen of each side's firehose: every event, how many
/// it has checked, the last seq, and by DID, the rev and tree root the
/// account's last commit or sync event left, and how many events of the
/// account it has seen.
const firehose = { reference: null, server: null }

/// Subscribe to both firehoses from the start, before any account is made.
export async function startFirehose() {
  for (const side of [ref, cand]) {
    firehose[side.name] = { side, events: [], seen: 0, lastSeq: 0, chains: new Map(), born: new Map(), identities: new Map() }
    firehose[side.name].sub = subscribe(side, 0, firehose[side.name].events)
  }
}

/// After a restart, carry on from the last event received.
export function resubscribe() {
  const f = firehose.server
  const last = f.events.findLast((e) => e.body.seq !== undefined)?.body.seq
  f.sub = subscribe(cand, last ?? 0, f.events)
}

const kind = (e) => (e.header.op === -1 ? `error ${e.body.error}` : e.header.t)
// Each side gives a record created without a key a TID of its own; no key
// the harness chooses has a TID's shape.
const sameKey = (path) => path.replace(/\/[234567a-z]{13}$/, '/<tid>')
const opKey = (op) => `${op.action} ${sameKey(op.path)} ${op.cid?.toString() ?? '-'} ${op.prev?.toString() ?? '-'}`

/// The event's account as both sides name it, `<did:n>`.
const whose = (side, e) => strip(side, String(e.body.repo ?? e.body.did))

/// The events a new account starts with, in order (spec/ACCOUNTS.md,
/// "createAccount").
const BIRTH = ['#identity', '#account', '#commit', '#sync']

function describeEvent(f, e) {
  const b = e.body
  return {
    type: kind(e),
    did: whose(f.side, e),
    seq: b.seq,
    rev: b.rev,
    since: b.since,
    prevData: b.prevData?.toString(),
    commit: b.commit?.toString(),
    ops: b.ops?.map(opKey),
    ...(e.header.op === -1 ? { error: b.error, message: b.message } : {}),
  }
}

/// Check one event on its own terms: what the sync spec says a consumer
/// checks, and that it continues the chain of events before it. The
/// reference's events are checked too, which checks the checks
/// (spec/SYNC.md, "The firehose").
async function checkEvent(f, e) {
  const { header, body } = e
  const fail = (why) => differ(`the ${f.side.name}'s firehose`, { event: kind(e), seq: body.seq }, why, describeEvent(f, e))
  if (header.op === -1) return fail('no error frame')
  if (!(body.seq > f.lastSeq)) return fail(`a seq after ${f.lastSeq}, after every event before it`)
  f.lastSeq = body.seq
  if (!['#identity', '#account', '#commit', '#sync'].includes(header.t)) return fail('a #commit, #sync, #identity or #account event')
  const did = body.repo ?? body.did
  const acct = accountNamed(f.side, did)
  if (typeof did !== 'string' || !acct || didOf(f.side, acct) !== did) return fail(`the DID of an account it made`)
  // A new account's first events, in order.
  const born = f.born.get(did) ?? 0
  if (born < BIRTH.length) {
    f.born.set(did, born + 1)
    if (header.t !== BIRTH[born]) return fail(`a new account's events, ${BIRTH.join(', ')}: ${BIRTH[born]} next`)
  }
  // Each #identity carries the handle the account had been given by then,
  // in order (spec/IDENTITY.md, "updateHandle").
  if (header.t === '#identity') {
    const i = f.identities.get(did) ?? 0
    f.identities.set(did, i + 1)
    const want = acct.handles[f.side.name][i]
    if (body.handle !== want) return fail(`#identity with the handle ${want}`)
  }
  if (born < BIRTH.length) {
    if (header.t === '#account' && (body.active !== true || body.status !== undefined)) return fail('#account with active: true and no status')
    if (header.t === '#commit' && (body.ops?.length !== 0 || body.since != null)) return fail(`the empty repository's first commit, with no ops and no since`)
  }
  if (header.t === '#identity' || header.t === '#account') return
  const key = acct.sides[f.side.name].key
  let car
  try {
    car = await readCarWithRoot(body.blocks)
  } catch (err) {
    return fail(`blocks that are a CAR file (${err.message})`)
  }
  let commit
  try {
    commit = cborDecode(car.blocks.get(car.root))
  } catch {
    return fail('blocks holding the commit they name as root')
  }
  if (header.t === '#commit' && body.commit?.toString() !== car.root.toString()) return fail('a commit that is the root of its blocks')
  if (commit.did !== did || commit.rev !== body.rev || commit.version !== 3) return fail(`a version 3 commit with the event's did and rev`)
  if (!(await verifyCommitSig(commit, key))) return fail(`a commit signed with the account's key`)
  const prev = f.chains.get(did)
  if (header.t === '#sync') {
    if (prev && !(body.rev >= prev.rev)) return fail(`a rev not before ${prev.rev}`)
    f.chains.set(did, { rev: body.rev, data: commit.data.toString() })
    return
  }
  if (prev && !(body.rev > prev.rev)) return fail(`a rev after ${prev.rev}`)
  if (body.rebase || body.tooBig) return fail('rebase and tooBig false')
  if ((body.since ?? null) !== (prev?.rev ?? null)) return fail(`since ${prev?.rev ?? null}`)
  if (prev) {
    if (body.prevData?.toString() !== prev.data) return fail(`prevData ${prev.data}`)
    // Undo the ops on the tree in the event's blocks: the root must be the
    // previous commit's, so the event alone shows what changed.
    try {
      let mst = MST.load(new MemoryBlockstore(car.blocks), commit.data)
      for (const op of [...body.ops].reverse()) {
        if (op.action === 'create') mst = await mst.delete(op.path)
        else if (op.action === 'update') mst = await mst.update(op.path, op.prev)
        else if (op.action === 'delete') mst = await mst.add(op.path, op.prev)
        else return fail('ops that are create, update or delete')
      }
      const root = (await mst.getPointer()).toString()
      if (root !== prev.data) return fail(`ops that undo to the previous tree, ${prev.data}, not ${root}`)
    } catch (err) {
      return fail(`blocks that let the ops be undone (${err.message})`)
    }
    const claims = body.ops.map((op) => {
      const [collection, rkey] = op.path.split('/')
      return { collection, rkey, cid: op.action === 'delete' ? null : op.cid }
    })
    try {
      await verifyProofs(body.blocks, claims, did, key)
    } catch (err) {
      return fail(`blocks that prove every op (${err.message})`)
    }
  }
  f.chains.set(did, { rev: body.rev, data: commit.data.toString() })
}

/// Both firehoses caught up with every account's latest commit, each new
/// event checked, and the same events on both sides since the last check:
/// the commits, by account and ops, and the other events, by account, in
/// order (spec/SYNC.md, "The firehose").
export async function checkFirehose() {
  const fresh = {}
  for (const side of [ref, cand]) {
    const f = firehose[side.name]
    for (const acct of accounts) {
      const did = didOf(side, acct)
      const latest = await xrpc(side, 'com.atproto.sync.getLatestCommit', { params: { did } })
      // The latest commit, the #sync that follows the account's first, and
      // an #identity for each handle it was given.
      const has = () =>
        f.events.some((e) => e.header.t === '#commit' && e.body.commit?.toString() === latest.body.cid) &&
        f.events.some((e) => e.header.t === '#sync' && e.body.did === did) &&
        f.events.filter((e) => e.header.t === '#identity' && e.body.did === did).length >= acct.handles[side.name].length
      const started = Date.now()
      while (!has() && Date.now() - started < 3000) await wait(20)
      if (!has()) await differ(`the ${side.name}'s firehose`, { did: `<did:${acct.n}>` }, `an event for the account's latest commit, ${latest.body.cid}, its #sync, and ${acct.handles[side.name].length} #identity events, within 3s`, f.events.slice(-3).map((e) => describeEvent(f, e)))
    }
    fresh[side.name] = f.events.slice(f.seen)
    f.seen = f.events.length
    // A turn of the event loop after each: a backlog of hundreds checked in
    // one go would hold up the harness's own OTLP receiver past the export
    // timeout, and the server rightly drop those spans (spec/OPERATIONS.md).
    for (const e of fresh[side.name]) {
      await checkEvent(f, e)
      await new Promise(setImmediate)
    }
  }
  // Writes sent at once may be committed in either order.
  const commits = (side) => fresh[side.name].filter((e) => e.header.t === '#commit').map((e) => `${whose(side, e)}: ${e.body.ops.map(opKey).sort().join(' | ')}`).sort()
  const [a, b] = [commits(ref), commits(cand)]
  if (!isDeepStrictEqual(a, b)) await differ('the firehose', { since: 'the last check' }, a, b, 'the commits since the last check, by account and ops')
  const others = (side) => fresh[side.name].filter((e) => e.header.t !== '#commit').map((e) => `${kind(e)} ${whose(side, e)}`)
  if (!isDeepStrictEqual(others(ref), others(cand))) await differ('the firehose', { since: 'the last check' }, others(ref), others(cand), 'events other than commits, in order')
  count('firehose check', true)
}

/// A new subscription from a cursor must replay exactly the events after it,
/// or with a backfill window, as it says (spec/STORE.md, "The backfill
/// window"); and one from the future must be refused as the reference
/// refuses it (spec/SYNC.md, "The firehose").
export async function checkReplay() {
  if (BACKFILL_MS) await windowReplay()
  else {
    const all = firehose.server.events
    const from = chance(0.2) ? 0 : pick(all).body.seq
    const line = (e) => `${e.body.seq} ${kind(e)} ${e.body.commit ?? ''}`
    const want = all.filter((e) => e.body.seq > from).map(line)
    const replay = subscribe(cand, from)
    const started = Date.now()
    while (replay.events.length < want.length && Date.now() - started < 3000) await wait(20)
    await wait(50)
    replay.ws.close()
    const got = replay.events.map(line)
    if (!isDeepStrictEqual(got, want)) await differ('subscribeRepos from a cursor', { cursor: from }, want, got)
    count('firehose replay', true)
  }

  const future = firehose.server.lastSeq + 1000
  const answers = {}
  for (const side of [ref, cand]) {
    const sub = subscribe(side, future)
    const t = Date.now()
    while (sub.open && Date.now() - t < 2000) await wait(20)
    sub.ws.close()
    answers[side.name] = { events: sub.events.map(kind), closed: !sub.open }
  }
  if (!isDeepStrictEqual(answers.reference, answers.server)) await differ('subscribeRepos from a cursor in the future', { cursor: future }, answers.reference, answers.server)

  // A cursor that is not an integer is refused as the reference refuses it
  // (spec/SYNC.md, "What the reference does that the specs leave open").
  const odd = {}
  for (const side of [ref, cand]) {
    const sub = subscribe(side, 'abc')
    const t = Date.now()
    while (sub.open && Date.now() - t < 2000) await wait(20)
    sub.ws.close()
    odd[side.name] = { events: sub.events.map(kind), closed: !sub.open }
  }
  if (!isDeepStrictEqual(odd.reference, odd.server)) await differ('subscribeRepos from a cursor that is not an integer', { cursor: 'abc' }, odd.reference, odd.server)
}

/// How near the window's edge, in milliseconds, an event may be on either
/// side of it: the two clocks, and the time a subscription takes to start.
const EDGE = 1500

/// subscribeRepos from a cursor with the backfill window (spec/STORE.md,
/// "The backfill window"), on both sides, each held to the rule on its own:
/// a cursor whose next event is well out of the window (`old`, or `0`) gets
/// `#info OutdatedCursor` first, then every event from somewhere at the
/// window's edge to the last, with no gap; one whose next event is well
/// within it (`recent`), every event after it and no `#info`. Each side's
/// cursor is one of its own events'; the sides must agree on whether there
/// was an `#info`.
export async function windowReplay() {
  const which = pick(['old', 'recent', 'zero'])
  const at = rand()
  const info = {}
  const line = (e) => (e.header.t === '#info' ? `#info ${e.body.name}` : `${e.body.seq} ${kind(e)}`)
  for (const side of [ref, cand]) {
    const f = firehose[side.name]
    const known = f.events.filter((e) => e.body.seq !== undefined)
    if (!known.length) continue
    const now = Date.now()
    const age = (e) => now - Date.parse(e.body.time)
    const old = (e) => age(e) > BACKFILL_MS + EDGE
    const recent = (e) => age(e) < BACKFILL_MS - EDGE
    let cursor
    if (which === 'zero') cursor = old(known[0]) ? 0 : undefined
    else {
      const fits = known.slice(0, -1).filter((_, i) => (which === 'old' ? old : recent)(known[i + 1]))
      cursor = fits.length ? fits[Math.floor(at * fits.length)].body.seq : undefined
    }
    if (cursor === undefined) continue
    const last = known.at(-1).body.seq
    const sub = subscribe(side, cursor)
    const started = Date.now()
    const done = () => sub.events.some((e) => e.body.seq >= last) || (which !== 'recent' && sub.events.length && known.every((e) => !recent(e)))
    while (!done() && Date.now() - started < 3000) await wait(20)
    await wait(100)
    sub.ws.close()
    const got = sub.events.filter((e) => e.header.t === '#info' || !(e.body.seq > last))
    const request = { cursor: which === 'zero' ? 0 : `an event of the ${side.name}'s whose next is ${which === 'old' ? 'out of' : 'within'} the window` }
    const seqs = (es) => es.map((e) => e.body.seq)
    if (which === 'recent') {
      const want = known.filter((e) => e.body.seq > cursor)
      if (!isDeepStrictEqual(got.map(line), want.map(line))) await fail(side, 'subscribeRepos from a cursor within the backfill window', request, want.map(line), got.map(line))
    } else {
      const [first, ...rest] = got
      if (first?.header.t !== '#info' || first.body.name !== 'OutdatedCursor') await fail(side, 'subscribeRepos from a cursor out of the backfill window', request, '#info OutdatedCursor first', got.slice(0, 3).map(line))
      const from = rest.length ? known.findIndex((e) => e.body.seq === rest[0].body.seq) : known.length
      const sent = known.slice(Math.max(0, from))
      const left = known.slice(0, Math.max(0, from))
      const why = from === -1 ? 'events it had sent' : left.some(recent) ? `every event less than ${BACKFILL_MS - EDGE} ms old` : sent.some(old) ? `no event more than ${BACKFILL_MS + EDGE} ms old` : null
      if (why || !isDeepStrictEqual(seqs(rest), seqs(sent))) {
        await fail(side, 'subscribeRepos from a cursor out of the backfill window', request, `after the #info, ${why ?? 'every event from the first sent on, with no gap'}`, rest.map((e) => `${line(e)} ${e.body.time}`))
      }
    }
    info[side.name] = got[0]?.header.t === '#info'
    count(`firehose replay, ${which} cursor`, true)
  }
  if (info.reference !== undefined && info.server !== undefined && info.reference !== info.server) {
    await differ('subscribeRepos from a cursor, with the backfill window', { cursor: which }, { info: info.reference }, { info: info.server })
  }
}