~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
263 lines · 12.6 KB Raw History
// The repositories' records: the com.atproto.repo methods (spec/REPO.md,
// "What the reference does that the specs leave open"), one at a time and
// several at once. Each step writes to or reads one account's repository,
// with that account's token.

import { isDeepStrictEqual } from 'node:util'
import { COLLECTIONS, RKEYS, below, chance, goodRecord, pick, rand, record, rkey, word } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, cids, didOf, exists, nextBatch, noteCommit, noteWrite } from '../lib/state.mjs'
import { both, normalize, shown, xrpc } from '../lib/xrpc.mjs'
import { checkDidDoc } from '../lib/plc.mjs'

export async function createRecord(acct) {
  const collection = pick(COLLECTIONS)
  const key = rkey()
  const body = { repo: acct.handle, collection, rkey: key, record: record(collection, cids) }
  const [a, b] = await both('createRecord', 'com.atproto.repo.createRecord', { body, token: acct })
  noteWrite(acct, collection, key, a)
  noteCommit(ref, acct, a)
  noteCommit(cand, acct, b)
}

function swap(acct, collection, key) {
  const r = rand()
  if (r < 0.2) return acct.records.get(`${collection}/${key}`) ?? null
  if (r < 0.3 && cids.length) return pick(cids)
  if (r < 0.4) return null
  return undefined
}

export async function putRecord(acct) {
  const collection = pick(COLLECTIONS)
  const key = rkey()
  const same = acct.lastValues.get(`${collection}/${key}`)
  const body = { repo: acct.handle, collection, rkey: key, record: same && chance(0.25) ? same : record(collection, cids) }
  acct.lastValues.set(`${collection}/${key}`, body.record)
  const s = swap(acct, collection, key)
  if (s !== undefined) body.swapRecord = s
  const [a, b] = await both('putRecord', 'com.atproto.repo.putRecord', { body, token: acct })
  noteWrite(acct, collection, key, a)
  noteCommit(ref, acct, a)
  noteCommit(cand, acct, b)
}

export async function deleteRecord(acct) {
  const collection = pick(COLLECTIONS)
  const key = rkey()
  const body = { repo: acct.handle, collection, rkey: key }
  const s = swap(acct, collection, key)
  if (s) body.swapRecord = s
  const [a, b] = await both('deleteRecord', 'com.atproto.repo.deleteRecord', { body, token: acct })
  if (a.status < 400) acct.records.delete(`${collection}/${key}`)
  noteCommit(ref, acct, a)
  noteCommit(cand, acct, b)
}

/// A batch every write of which should succeed: creates of keys that do not
/// exist, updates and deletes of ones that do, each key once.
function goodBatch(acct) {
  const used = new Set()
  const writes = []
  for (let i = 0; i < 1 + below(5); i++) {
    const collection = pick(COLLECTIONS)
    const existing = RKEYS.filter((k) => exists(acct, collection, k) && !used.has(`${collection}/${k}`))
    const fresh = RKEYS.filter((k) => !exists(acct, collection, k) && !used.has(`${collection}/${k}`))
    const kind = existing.length && (!fresh.length || chance(0.5)) ? pick(['update', 'delete']) : 'create'
    const key = kind === 'create' ? fresh.length && pick(fresh) : pick(existing)
    if (!key) continue
    used.add(`${collection}/${key}`)
    const w = { $type: `com.atproto.repo.applyWrites#${kind}`, collection, rkey: key }
    if (kind !== 'delete') w.value = goodRecord(collection)
    writes.push(w)
  }
  return writes.length ? writes : null
}

export async function applyWrites(acct) {
  const good = chance(0.6) ? goodBatch(acct) : null
  const writes = good ?? Array.from({ length: 1 + below(5) }, () => {
    const collection = pick(COLLECTIONS)
    const key = rkey()
    const kind = pick(['create', 'update', 'delete'])
    const w = { $type: `com.atproto.repo.applyWrites#${kind}`, collection, rkey: key }
    if (kind !== 'delete') w.value = record(collection, cids)
    return w
  })
  // No two values in a batch, and no value and a record it replaces, may be
  // the same: the reference loses a record from its index when one write in
  // a batch gives it the content another write in the batch replaces
  // (spec/REPO.md, "What the reference does that the specs leave open").
  for (const w of writes) if (w.value && typeof w.value === 'object') w.value = { ...w.value, batch: nextBatch() }
  const body = { repo: acct.handle, writes }
  // A swap names each side's own commit, so it is set per side.
  const r = rand()
  const which = good ? (r < 0.3 ? 1 : 0) : r < 0.2 ? 1 : r < 0.3 ? 2 : 0
  const swapFor = (side) => {
    const h = acct.heads[side.name]
    return which && h.length >= which ? h[h.length - which] : undefined
  }
  const [a, b] = await Promise.all(
    [ref, cand].map((side) =>
      xrpc(side, 'com.atproto.repo.applyWrites', {
        body: swapFor(side) ? { ...body, swapCommit: swapFor(side) } : body,
        token: acct,
      }),
    ),
  )
  const [na, nb] = [normalize(ref, a), normalize(cand, b)]
  if (!isDeepStrictEqual(na, nb)) await differ('com.atproto.repo.applyWrites', { body, swapCommit: which ? `the commit ${which} back` : 'none' }, na, nb)
  count('applyWrites', a.status < 400)
  if (a.status < 400) {
    writes.forEach((w, i) => {
      const k = `${w.collection}/${w.rkey}`
      if (w.$type.endsWith('#delete')) acct.records.delete(k)
      else if (a.body.results?.[i]?.cid) {
        acct.records.set(k, a.body.results[i].cid)
        cids.push(a.body.results[i].cid)
      }
    })
  }
  noteCommit(ref, acct, a)
  noteCommit(cand, acct, b)
}

/// Each query names the repository by its handle or, as often, its DID
/// (spec/ACCOUNTS.md, "Queries").
const repoOf = (acct) => (chance(0.5) ? () => acct.handle : (side) => didOf(side, acct))

export async function getRecord(acct) {
  const collection = pick(COLLECTIONS)
  const key = chance(0.7) && acct.records.size ? pick([...acct.records.keys()]).split('/')[1] : rkey()
  const repo = repoOf(acct)
  const cid = chance(0.15) && cids.length ? pick(cids) : undefined
  await both('getRecord', 'com.atproto.repo.getRecord', (side) => ({ params: { repo: repo(side), collection, rkey: key, cid } }))
}

export async function listRecords(acct) {
  const collection = pick(COLLECTIONS)
  const repo = repoOf(acct)
  const params = { collection }
  if (chance(0.7)) params.limit = 1 + below(5)
  if (chance(0.3)) params.reverse = true
  let cursors = [undefined, undefined]
  for (let page = 0; page < 30; page++) {
    const [a, b] = await Promise.all([
      xrpc(ref, 'com.atproto.repo.listRecords', { params: { repo: repo(ref), ...params, cursor: cursors[0] } }),
      xrpc(cand, 'com.atproto.repo.listRecords', { params: { repo: repo(cand), ...params, cursor: cursors[1] } }),
    ])
    const [na, nb] = [normalize(ref, a), normalize(cand, b)]
    if (!isDeepStrictEqual(na, nb)) await differ('com.atproto.repo.listRecords', shown({ params: { repo: repo(ref), ...params, page } }), na, nb)
    count('listRecords', a.status < 400)
    if (a.status >= 400 || !a.body.cursor || !(a.body.records?.length)) break
    cursors = [a.body.cursor, b.body.cursor]
  }
}

/// describeRepo, whose `didDoc` on each side must be the PLC directory's
/// (spec/IDENTITY.md, "describeRepo's didDoc and handleIsCorrect").
export async function describeRepo(acct) {
  const repo = repoOf(acct)
  const answers = await both('describeRepo', 'com.atproto.repo.describeRepo', (side) => ({ params: { repo: repo(side) } }))
  for (const [side, res] of [[ref, answers[0]], [cand, answers[1]]]) {
    if (res.status === 200) await checkDidDoc(side, didOf(side, acct), res.body.didDoc, 'com.atproto.repo.describeRepo', shown({ params: { repo: repo(ref) } }))
  }
}

const TID = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/

export async function createWithTid(acct) {
  const collection = pick(COLLECTIONS)
  const body = { repo: acct.handle, collection, record: { $type: collection, text: word() } }
  const [a, b] = await Promise.all([ref, cand].map((side) => xrpc(side, 'com.atproto.repo.createRecord', { body, token: acct })))
  const strip = (side, res) => {
    const n = normalize(side, res)
    if (n.body?.uri) n.body.uri = n.body.uri.replace(/[^/]+$/, '<tid>')
    return n
  }
  if (!isDeepStrictEqual(strip(ref, a), strip(cand, b))) await differ('createRecord without rkey', body, strip(ref, a), strip(cand, b))
  count('createRecord without rkey', a.status < 400)
  if (a.status >= 400) return
  const tid = b.body.uri.split('/').pop()
  if (!TID.test(tid)) await differ('createRecord without rkey', body, 'a TID', tid, 'the record key is not a TID')
  if (tid <= acct.lastTid) await differ('createRecord without rkey', body, `a TID after ${acct.lastTid}`, tid, 'TIDs must increase')
  acct.lastTid = tid
  noteCommit(ref, acct, a)
  noteCommit(cand, acct, b)
  // Delete it again on both, so the two repos keep the same keys.
  for (const [side, res] of [[ref, a], [cand, b]]) {
    const del = await xrpc(side, 'com.atproto.repo.deleteRecord', { body: { repo: acct.handle, collection, rkey: res.body.uri.split('/').pop() }, token: acct })
    if (del.status >= 400) await differ('deleting a TID record', {}, 'ok', del, `on the ${side.name}`)
    noteCommit(side, acct, del)
  }
}

// ---- Concurrency --------------------------------------------------------

/// Distinct keys, as `[collection, rkey]`, for writes sent at once.
function distinctKeys(n) {
  const all = COLLECTIONS.flatMap((c) => RKEYS.map((k) => [c, k]))
  const out = []
  while (out.length < n && all.length) out.push(all.splice(below(all.length), 1)[0])
  return out
}

/// Writes sent to the server at once, chosen so that the right answer to each
/// does not depend on the order they land in: puts of different keys, to
/// one account or several, or batches that race on the same commit, of
/// which exactly one may land.
export async function concurrent(acct) {
  if (rand() < 0.7) return concurrentPuts()
  return commitRace(acct)
}

async function concurrentPuts() {
  const writes = distinctKeys(2 + below(6)).map(([collection, key]) => ({ acct: pick(accounts), body: { collection, rkey: key, record: goodRecord(collection) } }))
  for (const w of writes) w.body = { repo: w.acct.handle, ...w.body }
  const answers = await Promise.all([ref, cand].map((side) => Promise.all(writes.map(({ acct, body }) => xrpc(side, 'com.atproto.repo.putRecord', { body, token: acct })))))
  for (const [i, { acct, body }] of writes.entries()) {
    const [a, b] = [answers[0][i], answers[1][i]]
    const [na, nb] = [normalize(ref, a), normalize(cand, b)]
    if (!isDeepStrictEqual(na, nb)) await differ('com.atproto.repo.putRecord, sent at once with others', { body, alongside: writes.length - 1, accounts: new Set(writes.map((w) => w.acct)).size }, na, nb)
    count('puts at once', a.status < 400)
    noteWrite(acct, body.collection, body.rkey, a)
  }
  for (const acct of new Set(writes.map((w) => w.acct))) await syncHeads(acct)
}

async function commitRace(acct) {
  await syncHeads(acct)
  const head = acct.heads.server.at(-1)
  const batches = distinctKeys(2 + below(4)).map(([collection, key]) => [
    { $type: 'com.atproto.repo.applyWrites#create', collection, rkey: key, value: goodRecord(collection) },
  ]).filter(([w]) => !exists(acct, w.collection, w.rkey))
  if (batches.length < 2) return
  const answers = await Promise.all(batches.map((writes) => xrpc(cand, 'com.atproto.repo.applyWrites', { body: { repo: acct.handle, writes, swapCommit: head }, token: acct })))
  const won = answers.map((a, i) => [a, i]).filter(([a]) => a.status === 200)
  const lost = answers.filter((a) => a.status !== 200)
  if (won.length !== 1 || lost.some((a) => a.status !== 400 || a.body?.error !== 'InvalidSwap')) {
    await differ('applyWrites racing on one commit', { batches: batches.length, swapCommit: head }, 'exactly one lands, the rest InvalidSwap', answers.map((a) => normalize(cand, a)))
  }
  const [b, i] = won[0]
  const a = await xrpc(ref, 'com.atproto.repo.applyWrites', { body: { repo: acct.handle, writes: batches[i], swapCommit: acct.heads.reference.at(-1) }, token: acct })
  const [na, nb] = [normalize(ref, a), normalize(cand, b)]
  if (!isDeepStrictEqual(na, nb)) await differ('the batch that won a race', batches[i], na, nb)
  count('commit races', true)
  const w = batches[i][0]
  if (a.status < 400) {
    acct.records.set(`${w.collection}/${w.rkey}`, a.body.results[0].cid)
    cids.push(a.body.results[0].cid)
  }
  noteCommit(ref, acct, a)
  noteCommit(cand, acct, b)
}

/// Each side's head of the account's repository as it now stands, after
/// writes whose order the harness did not see.
export async function syncHeads(acct) {
  for (const side of [ref, cand]) {
    const latest = await xrpc(side, 'com.atproto.sync.getLatestCommit', { params: { did: didOf(side, acct) } })
    if (latest.status === 200 && latest.body.cid !== acct.heads[side.name].at(-1)) acct.heads[side.name].push(latest.body.cid)
  }
}