~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
317 lines · 19.3 KB Raw History
// Upgrades (spec/STORE.md, "Upgrades"): the server alone, started on the
// data directories the previous version wrote, in harness/upgrade/, with
// every read held to what that version answered there, and its writes
// carrying on from where that version's left off.
//
// `--upgrade-write` makes harness/upgrade/ with the server it is given,
// which is then the previous version: run with a release's binary when the
// release is tagged, and commit what it writes. `--upgrade` checks the
// server against it. A server whose own data the directory is passes as it
// would after a restart.

import { createHash } from 'node:crypto'
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { isDeepStrictEqual } from 'node:util'
import { cborDecodeMulti } from '@atproto/common'
import { readCarWithRoot } from '@atproto/repo'
import { cand, dataDir, plcUrl, server, waitReady } from '../lib/processes.mjs'
import { fail } from '../lib/plc.mjs'
import { count } from '../lib/report.mjs'
import { xrpcHttp } from '../lib/xrpc.mjs'

/// Where the previous version's data directories and answers are kept.
const FIXTURE = new URL('../upgrade/', import.meta.url).pathname
/// The data directories: shut down with SIGTERM, and killed with SIGKILL.
const DIRS = ['clean', 'killed']
/// The variables a data directory is bound to, kept with it: the server's
/// name and keys, and the admin's password.
const PINNED = ['PDS_HOSTNAME', 'PDS_PUBLIC_URL', 'PDS_HANDLE_DOMAINS', 'PDS_PLC_ROTATION_KEY_HEX', 'PDS_RECOVERY_DID_KEY', 'PDS_ADMIN_PASSWORD']
/// A backfill window of ten years on both runs, so that every event the
/// previous version made is in it whenever the check runs (spec/STORE.md).
const WINDOW = String(10 * 365 * 86_400_000)
/// The collections the accounts write.
const NOTE = 'com.example.upgrade.note'
const SC = 'com.example.upgrade.space'
const SP = 'com.atproto.space.'
const MS = 'com.atproto.memberspace.'
/// A PNG of one pixel, for an avatar.
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64')

const sha = (bytes) => createHash('sha256').update(bytes).digest('hex')
const admin = () => `Basic ${Buffer.from(`admin:${server.env.PDS_ADMIN_PASSWORD}`).toString('base64')}`

/// A call to the server: with a token, or the admin's auth with `admin`.
async function call(nsid, { params, body, token, asAdmin, raw, method } = {}) {
  if (!asAdmin) return xrpcHttp(cand, nsid, { params, body, token, raw, method })
  const url = new URL(`${cand.url}/xrpc/${nsid}`)
  for (const [k, v] of Object.entries(params ?? {})) url.searchParams.append(k, String(v))
  const res = await fetch(url, { method: body ? 'POST' : 'GET', headers: { authorization: admin(), ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined })
  const text = await res.text()
  return { status: res.status, body: text ? JSON.parse(text) : null }
}

/// A call made in writing the data, which must answer 200.
async function must(nsid, request, what) {
  const res = await call(nsid, request)
  if (res.status !== 200) await fail(cand, `${nsid}, writing the previous version's data`, request.params ?? request.body ?? {}, what, res.body)
  return res.body
}

/// Every page of a list, its items under `key`, or the first answer that
/// is not 200.
async function pages(nsid, params, key, token) {
  const all = []
  let cursor
  for (;;) {
    const res = await call(nsid, { params: { ...params, limit: 100, cursor }, token })
    if (res.status !== 200) return res
    all.push(...(res.body[key] ?? []))
    if (!res.body.cursor || !res.body[key]?.length) return { status: 200, body: all }
    cursor = res.body.cursor
  }
}

/// A repository as `getRepo` answers it: its root, and its blocks by CID.
async function repoOf(did) {
  const res = await call('com.atproto.sync.getRepo', { params: { did }, raw: true })
  if (!res.bytes) return res
  const car = await readCarWithRoot(res.bytes)
  const cids = []
  car.blocks.forEach((_, cid) => cids.push(cid.toString()))
  cids.sort()
  return { status: res.status, body: { root: car.root.toString(), blocks: cids.length, cids: sha(cids.join('\n')) } }
}

/// Every event from the start of the firehose until none comes for a
/// second and a half: each frame's `seq` and the SHA-256 of its bytes, and
/// the event that answers `until` if given.
function firehose(cursor = 0, until) {
  return new Promise((ok) => {
    const ws = new WebSocket(`${cand.url.replace(/^http/, 'ws')}/xrpc/com.atproto.sync.subscribeRepos?cursor=${cursor}`)
    ws.binaryType = 'arraybuffer'
    const events = []
    let idle
    const done = () => {
      clearTimeout(idle)
      ws.close()
      ok(events)
    }
    const rest = () => {
      clearTimeout(idle)
      idle = setTimeout(done, 1500)
    }
    ws.onmessage = (m) => {
      const bytes = new Uint8Array(m.data)
      const [header, body] = cborDecodeMulti(bytes)
      events.push({ t: header.t ?? null, seq: body.seq ?? null, sha: sha(bytes), body })
      if (until?.(body)) return done()
      rest()
    }
    ws.onerror = () => done()
    rest()
  })
}

/// Every read of the data, by what it is: the same requests on the
/// previous version and on this one. `accounts` as accounts.json keeps them.
async function readAll(accounts) {
  const reads = {}
  const read = async (key, fn) => {
    const res = await fn()
    reads[key] = { status: res.status, body: res.body }
  }
  await read('describeServer', () => call('com.atproto.server.describeServer'))
  await read('listRepos', () => pages('com.atproto.sync.listRepos', {}, 'repos'))
  for (const a of accounts) {
    const did = a.did
    await read(`${a.name} getLatestCommit`, () => call('com.atproto.sync.getLatestCommit', { params: { did } }))
    await read(`${a.name} getRepoStatus`, () => call('com.atproto.sync.getRepoStatus', { params: { did } }))
    await read(`${a.name} getRepo`, () => repoOf(did))
    await read(`${a.name} describeRepo`, () => call('com.atproto.repo.describeRepo', { params: { repo: did } }))
    for (const collection of [NOTE, 'app.bsky.actor.profile']) await read(`${a.name} listRecords ${collection}`, () => pages('com.atproto.repo.listRecords', { repo: did, collection }, 'records'))
    await read(`${a.name} listBlobs`, () => pages('com.atproto.sync.listBlobs', { did }, 'cids'))
    const blobs = reads[`${a.name} listBlobs`]
    for (const cid of blobs.status === 200 ? blobs.body : []) {
      await read(`${a.name} getBlob ${cid}`, async () => {
        const res = await fetch(`${cand.url}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(did)}&cid=${cid}`)
        return { status: res.status, body: { type: res.headers.get('content-type'), sha: sha(new Uint8Array(await res.arrayBuffer())) } }
      })
    }
    await read(`${a.name} getSubjectStatus`, () => call('com.atproto.admin.getSubjectStatus', { params: { did }, asAdmin: true }))
    if (a.takenDownRecord) await read(`${a.name} getSubjectStatus of a record`, () => call('com.atproto.admin.getSubjectStatus', { params: { uri: a.takenDownRecord }, asAdmin: true }))
    const session = await call('com.atproto.server.createSession', { body: { identifier: a.handle, password: a.password } })
    const { accessJwt, refreshJwt, ...kept } = session.body ?? {}
    reads[`${a.name} createSession`] = { status: session.status, body: kept }
    const token = accessJwt
    if (!token) continue
    await read(`${a.name} getSession`, () => call('com.atproto.server.getSession', { token }))
    await read(`${a.name} checkAccountStatus`, () => call('com.atproto.server.checkAccountStatus', { token }))
    await read(`${a.name} getPreferences`, () => call('app.bsky.actor.getPreferences', { token }))
    await read(`${a.name} listAppPasswords`, () => call('com.atproto.server.listAppPasswords', { token }))
    // Its space, carried as the rest is (spec/STORE.md, "How it is checked").
    if (a.space) {
      const space = a.space
      await read(`${a.name} listSpaces`, () => call(`${SP}listSpaces`, { token }))
      await read(`${a.name} getSpace`, () => call(`${SP}getSpace`, { params: { space }, token }))
      await read(`${a.name} listMembers`, () => call(`${MS}listMembers`, { params: { space }, token }))
      await read(`${a.name} space listRecords`, () => call(`${SP}listRecords`, { params: { space, repo: did, collection: SC }, token }))
      await read(`${a.name} space listRepoOps`, () => call(`${SP}listRepoOps`, { params: { space, repo: did }, token }))
      await read(`${a.name} space getLatestCommit`, () => call(`${SP}getLatestCommit`, { params: { space, repo: did }, token }))
    }
  }
  const events = await firehose()
  reads.firehose = { status: 200, body: events.map(({ t, seq, sha }) => ({ t, seq, sha })) }
  return reads
}

/// The accounts and what they hold, made on the previous version: records
/// written, rewritten and deleted, a blob, preferences, an app password, a
/// confirmed email, a handle changed, a space with records and a member; an
/// account deactivated, a record taken down, an account taken down.
async function makeData() {
  const accounts = []
  for (const name of ['alice', 'bob', 'carol', 'dave']) {
    const a = { name, handle: `${name}-up.test`, email: `${name}@upgrade.example`, password: `pw-${name}-upgrade` }
    const made = await must('com.atproto.server.createAccount', { body: { handle: a.handle, email: a.email, password: a.password } }, 'the account')
    a.did = made.did
    a.token = made.accessJwt
    for (let i = 0; i < 4; i++) await must('com.atproto.repo.createRecord', { body: { repo: a.did, collection: NOTE, record: { $type: NOTE, text: `${name} ${i}`, n: i } }, token: a.token }, 'the record')
    for (const rkey of ['a', 'b', 'c']) await must('com.atproto.repo.putRecord', { body: { repo: a.did, collection: NOTE, rkey, record: { $type: NOTE, text: `${name} ${rkey}` } }, token: a.token }, 'the record')
    await must('com.atproto.repo.putRecord', { body: { repo: a.did, collection: NOTE, rkey: 'a', record: { $type: NOTE, text: `${name} a, again` } }, token: a.token }, 'the record rewritten')
    await must('com.atproto.repo.deleteRecord', { body: { repo: a.did, collection: NOTE, rkey: 'b' }, token: a.token }, 'the record deleted')
    await must('com.atproto.repo.applyWrites', { body: { repo: a.did, writes: [0, 1, 2].map((i) => ({ $type: 'com.atproto.repo.applyWrites#create', collection: NOTE, rkey: `w${i}`, value: { $type: NOTE, text: `${name} batch ${i}` } })) }, token: a.token }, 'the batch')
    accounts.push(a)
  }
  const [alice, bob, carol, dave] = accounts

  const blob = await fetch(`${cand.url}/xrpc/com.atproto.repo.uploadBlob`, { method: 'POST', headers: { authorization: `Bearer ${alice.token}`, 'content-type': 'image/png' }, body: PNG }).then((r) => r.json())
  await must('com.atproto.repo.putRecord', { body: { repo: alice.did, collection: 'app.bsky.actor.profile', rkey: 'self', record: { $type: 'app.bsky.actor.profile', displayName: 'Alice', avatar: blob.blob } }, token: alice.token }, 'the profile')
  await must('app.bsky.actor.putPreferences', { body: { preferences: [{ $type: 'app.bsky.example.upgradePref', n: 1 }] }, token: alice.token }, 'the preferences')
  await must('com.atproto.server.createAppPassword', { body: { name: 'upgrade' }, token: alice.token }, 'the app password')
  await must('com.atproto.server.requestEmailConfirmation', { token: alice.token, method: 'POST' }, 'the email sent')
  const mail = (await cand.takeMail()).findLast((m) => m.to === alice.email)
  await must('com.atproto.server.confirmEmail', { body: { email: alice.email, token: mail.token }, token: alice.token }, 'the email confirmed')
  alice.handle = 'alice-renamed-up.test'
  await must('com.atproto.identity.updateHandle', { body: { handle: alice.handle }, token: alice.token }, 'the handle changed')
  const space = await must(`${SP}createSpace`, { body: { spaceType: 'com.example.group', skey: 'upgrade', policy: { $type: `${MS}policy` } }, token: alice.token }, 'the space')
  alice.space = space.space
  for (const rkey of ['s0', 's1', 's2']) await must(`${SP}putRecord`, { body: { space: alice.space, repo: alice.did, collection: SC, rkey, record: { $type: SC, text: `space ${rkey}` } }, token: alice.token }, 'the space record')
  await must(`${SP}deleteRecord`, { body: { space: alice.space, repo: alice.did, collection: SC, rkey: 's1' }, token: alice.token }, 'the space record deleted')
  await must(`${MS}putMembers`, { body: { space: alice.space, members: [{ did: bob.did, read: true, write: false }] }, token: alice.token }, 'the member')

  await must('com.atproto.server.deactivateAccount', { body: {}, token: bob.token }, 'the account deactivated')
  const td = await must('com.atproto.repo.putRecord', { body: { repo: carol.did, collection: NOTE, rkey: 'td', record: { $type: NOTE, text: 'taken down' } }, token: carol.token }, 'the record')
  carol.takenDownRecord = `at://${carol.did}/${NOTE}/td`
  await must('com.atproto.admin.updateSubjectStatus', { body: { subject: { $type: 'com.atproto.repo.strongRef', uri: carol.takenDownRecord, cid: td.cid }, takedown: { applied: true, ref: 'upgrade-record' } }, asAdmin: true }, 'the record taken down')
  await must('com.atproto.admin.updateSubjectStatus', { body: { subject: { $type: 'com.atproto.admin.defs#repoRef', did: dave.did }, takedown: { applied: true, ref: 'upgrade-account' } }, asAdmin: true }, 'the account taken down')
  return accounts.map(({ token, ...a }) => a)
}

/// Empty the data directory, and fill it from `from` if given.
function fillData(from) {
  for (const f of readdirSync(dataDir)) rmSync(join(dataDir, f), { recursive: true, force: true })
  if (from) cpSync(from, dataDir, { recursive: true })
}

/// Take out the empty directories under `dir`, as git keeps none: what is
/// checked is the directory as committed.
function pruneEmpty(dir) {
  for (const f of readdirSync(dir)) {
    const p = join(dir, f)
    if (statSync(p).isDirectory()) {
      pruneEmpty(p)
      if (!readdirSync(p).length) rmdirSync(p)
    }
  }
}

/// Start the server on its data directory with the pinned variables and
/// the long window, and wait until it answers: a start that exits, or does
/// not answer within 30 seconds, fails `at`.
async function startWith(pinned, at) {
  Object.assign(server.env, pinned, { PDS_REPO_BACKFILL_LIMIT_MS: WINDOW })
  server.start()
  for (let i = 0; i < 300; i++) {
    if (server.exited) await fail(cand, 'start', at, 'it serves', { exited: server.exited, stderr: readFileSync(server.errPath, 'utf8').slice(-400) })
    if ((await call('com.atproto.server.describeServer')).status === 200) return
    await new Promise((ok) => setTimeout(ok, 100))
  }
  await fail(cand, 'start', at, 'it serves within 30 s', 'no answer')
}

/// `--upgrade-write`: harness/upgrade/, made with the server given, which is
/// the previous version.
export async function upgradeWrite() {
  await server.kill()
  fillData()
  const pinned = Object.fromEntries(PINNED.filter((k) => server.env[k] !== undefined).map((k) => [k, server.env[k]]))
  await startWith(pinned, { data: 'empty' })
  const version = (await call('_health')).body.version
  const accounts = await makeData()
  const reads = await readAll(accounts)
  const plc = {}
  for (const a of accounts) plc[a.did] = await fetch(`${plcUrl}/${a.did}/log`).then((r) => r.json())
  rmSync(FIXTURE, { recursive: true, force: true })
  mkdirSync(FIXTURE, { recursive: true })
  await server.kill()
  cpSync(dataDir, join(FIXTURE, 'killed'), { recursive: true })
  server.start()
  await waitReady(server, cand.url)
  const ended = await server.stop('SIGTERM', 15000)
  if (ended?.code !== 0) await fail(cand, 'shutdown', { signal: 'SIGTERM' }, 'exit 0', ended)
  cpSync(dataDir, join(FIXTURE, 'clean'), { recursive: true })
  for (const d of DIRS) pruneEmpty(join(FIXTURE, d))
  const json = (name, value) => writeFileSync(join(FIXTURE, name), `${JSON.stringify(value, null, 2)}\n`)
  json('version.json', { version })
  json('env.json', pinned)
  json('accounts.json', accounts)
  json('plc.json', plc)
  json('reads.json', reads)
  return { version, accounts: accounts.length, reads: Object.keys(reads).length }
}

/// `--upgrade`: the server on each of the previous version's data
/// directories, every read as it answered, and its writes carrying on.
export async function upgradeRun() {
  if (!existsSync(join(FIXTURE, 'reads.json'))) await fail(cand, 'upgrade', {}, 'harness/upgrade/, written with --upgrade-write', 'none')
  const load = (name) => JSON.parse(readFileSync(join(FIXTURE, name), 'utf8'))
  const { version } = load('version.json')
  const pinned = load('env.json')
  const accounts = load('accounts.json')
  const want = load('reads.json')
  // Each DID's operations, as the previous version's directory held them.
  for (const [did, ops] of Object.entries(load('plc.json'))) {
    for (const op of ops) {
      const res = await fetch(`${plcUrl}/${did}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(op) })
      if (!res.ok) throw new Error(`the PLC directory refused ${did}'s operation: ${res.status} ${await res.text()}`)
    }
  }
  const last = want.firehose.body.at(-1)?.seq ?? 0
  for (const [i, dir] of DIRS.entries()) {
    await server.kill()
    fillData(join(FIXTURE, dir))
    const at = { data: `${dir}, written by ${version}` }
    await startWith(pinned, at)
    const got = await readAll(accounts)
    for (const key of Object.keys(want)) {
      if (!isDeepStrictEqual(got[key], want[key])) await fail(cand, `${key}, on the previous version's data`, at, want[key], got[key] ?? 'not read')
      count(`read as before: ${key.replace(/^\w+ /, '').replace(/ baf\w+$/, '')}`, true)
    }
    for (const key of Object.keys(got)) if (!(key in want)) await fail(cand, 'reads, on the previous version\'s data', at, 'only what the previous version answered', key)

    // A write carries on from the last: a later rev, the next event.
    const alice = accounts[0]
    const session = (await call('com.atproto.server.createSession', { body: { identifier: alice.handle, password: alice.password } })).body
    const before = want[`${alice.name} getLatestCommit`].body.rev
    const wrote = await call('com.atproto.repo.createRecord', { body: { repo: alice.did, collection: NOTE, record: { $type: NOTE, text: `after the upgrade ${i}` } }, token: session.accessJwt })
    if (wrote.status !== 200 || !(wrote.body.commit?.rev > before)) await fail(cand, 'createRecord, on the previous version\'s data', at, `a commit of a rev after ${before}`, wrote.body)
    const next = await firehose(last, (b) => b.repo === alice.did && b.rev === wrote.body.commit.rev)
    const ev = next.find((e) => e.body.repo === alice.did && e.body.rev === wrote.body.commit.rev)
    if (!ev || next.some((e) => e.seq !== null && e.seq <= last) || ev.body.since !== before) await fail(cand, 'the firehose, after a write on the previous version\'s data', { ...at, cursor: last }, `the write's #commit, of a seq after ${last}, since ${before}`, next.map(({ t, seq, body }) => ({ t, seq, repo: body.repo, rev: body.rev, since: body.since })))
    const erin = await call('com.atproto.server.createAccount', { body: { handle: `erin${i}-up.test`, email: `erin${i}@upgrade.example`, password: 'pw-erin-upgrade' } })
    if (erin.status !== 200) await fail(cand, 'createAccount, on the previous version\'s data', at, 'the account', erin.body)
    count('writes carry on', true)
  }
  return { version, reads: Object.keys(want).length }
}