~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
258 lines · 11.9 KB Raw History
// The store benchmark's ladder over HTTP (README.md, "A record read, a
// stage at a time"): the stage after `store-bench ladder`'s, the record read
// through the server. Prints a Markdown table.
//
//   node ladder.mjs <accounts> <records>
//
// The server (`../../target/release/pds`, built already with `just build`,
// or `PDS_BIN`) is given `accounts` accounts, made with `createAccount`
// against a directory of DIDs this script serves, and the records
// `store-bench ladder-records` prints, `records` each, the records
// `store-bench ladder` reads, written with `applyWrites`, 50 to a call and
// 16 calls at once (a call a sync). Its backfill window is
// half a second, so that once the writes stop an account's next write
// folds its log into its table: the records are read from tables, as the
// stages before read them. Then, on one kept-alive connection, one pass over
// every record, and `_health` and `getRecord` timed one at a time; then each
// 16 at once, a connection each. Its data directory is under `BENCH_DIR`, by
// default `target/data` here, and is removed after.

import { spawn, execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, closeSync } from 'node:fs'
import { Agent, createServer as httpServer, request } from 'node:http'
import { createServer } from 'node:net'
import { createHash } from 'node:crypto'
import { join, resolve } from 'node:path'

const here = new URL('.', import.meta.url).pathname
const BIN = resolve(process.env.PDS_BIN ?? join(here, '../../target/release/pds'))
const BENCH = join(here, 'target/release/store-bench')
const ROOT = resolve(process.env.BENCH_DIR ?? join(here, 'target/data'))
const [ACCOUNTS, RECORDS] = process.argv.slice(2).map(Number)
if (!(ACCOUNTS >= 1 && RECORDS >= 1)) {
  console.error('node ladder.mjs <accounts> <records>')
  process.exit(2)
}
for (const [bin, how] of [[BIN, '`just build` first, or set PDS_BIN'], [BENCH, '`cargo build --release` here first']]) {
  if (!existsSync(bin)) {
    console.error(`no ${bin}: ${how}`)
    process.exit(1)
  }
}

/// The reads one at a time, and on each of the connections at once, as
/// `store-bench ladder` makes them.
const LOOKUPS = 20000
const AT_ONCE = 16
const EACH = 2000
const BATCH = 50
const COLLECTION = 'app.bsky.feed.post'

const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms))
const sha256 = (s) => createHash('sha256').update(s).digest()

/// Numbers that are the same for the same seed (splitmix64).
function rng(seed) {
  let x = BigInt(seed)
  return (n) => {
    x = (x + 0x9e3779b97f4a7c15n) & 0xffffffffffffffffn
    let z = x
    z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & 0xffffffffffffffffn
    z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & 0xffffffffffffffffn
    z ^= z >> 31n
    return Number((z * BigInt(n)) >> 64n)
  }
}

const freePort = () => new Promise((ok) => {
  const s = createServer().listen(0, '127.0.0.1', () => {
    const { port } = s.address()
    s.close(() => ok(port))
  })
})

/// A directory of DIDs: it takes every operation posted to it, and serves
/// each DID's document as its last operation makes it.
async function directory() {
  const ops = new Map()
  const doc = (did, op) => ({
    '@context': ['https://www.w3.org/ns/did/v1', 'https://w3id.org/security/multikey/v1', 'https://w3id.org/security/suites/secp256k1-2019/v1'],
    id: did,
    alsoKnownAs: op.alsoKnownAs,
    verificationMethod: Object.entries(op.verificationMethods).map(([name, key]) => ({
      id: `${did}#${name}`, type: 'Multikey', controller: did, publicKeyMultibase: key.slice('did:key:'.length),
    })),
    service: Object.entries(op.services).map(([name, s]) => ({ id: `#${name}`, type: s.type, serviceEndpoint: s.endpoint })),
  })
  const server = httpServer((req, res) => {
    const chunks = []
    req.on('data', (c) => chunks.push(c))
    req.on('end', () => {
      const [did, ...rest] = decodeURIComponent(req.url.slice(1)).split('/')
      const answer = (status, body) => {
        res.writeHead(status, { 'content-type': 'application/json' })
        res.end(body === undefined ? '' : JSON.stringify(body))
      }
      if (req.method === 'POST') {
        ops.set(did, [...(ops.get(did) ?? []), JSON.parse(Buffer.concat(chunks))])
        return answer(200)
      }
      const log = ops.get(did)
      if (!log) return answer(404, { message: `DID not registered: ${did}` })
      const last = log.at(-1)
      switch (rest.join('/')) {
        case '': return answer(200, doc(did, last))
        case 'data': return answer(200, { did, ...last })
        case 'log/last': return answer(200, last)
        case 'log/audit': return answer(200, log.map((operation) => ({ did, operation, nullified: false })))
        default: return answer(404)
      }
    })
  })
  await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
  return { url: `http://127.0.0.1:${server.address().port}`, close: () => server.close() }
}

/// A request on `agent`: its status and body.
const call = (agent, port, method, path, body, headers = {}) => new Promise((ok, fail) => {
  const data = body === undefined ? undefined : Buffer.from(JSON.stringify(body))
  const req = request({ host: '127.0.0.1', port, method, path, agent, headers: data ? { 'content-type': 'application/json', 'content-length': data.length, ...headers } : headers }, (res) => {
    const chunks = []
    res.on('data', (c) => chunks.push(c))
    res.on('end', () => ok({ status: res.statusCode, body: Buffer.concat(chunks) }))
    res.on('error', fail)
  })
  req.on('error', fail)
  req.end(data)
})

const dir = join(ROOT, 'ladder')
rmSync(dir, { recursive: true, force: true })
mkdirSync(dir, { recursive: true })
const plc = await directory()
const port = await freePort()
const url = `http://127.0.0.1:${port}`
const out = openSync(`${dir}.out`, 'w')
const proc = spawn(BIN, ['serve'], {
  env: {
    PATH: process.env.PATH, PDS_PORT: String(port), PDS_DATA_DIR: dir, PDS_HOSTNAME: 'localhost', PDS_PUBLIC_URL: url,
    PDS_HANDLE_DOMAINS: '.test', PDS_PLC_URL: plc.url, PDS_PLC_ROTATION_KEY_HEX: sha256('rotation').toString('hex'),
    PDS_ADMIN_PASSWORD: 'admin-pass', PDS_INVITE_REQUIRED: 'false', PDS_RATE_LIMITS_ENABLED: 'false',
    PDS_REPO_BACKFILL_LIMIT_MS: '500',
  },
  stdio: ['ignore', out, out],
})
let exited = null
proc.on('exit', (code) => (exited = code ?? 'killed'))
const failed = (what) => new Error(`${what}${exited === null ? '' : `; the server exited ${exited}`}: ${readFileSync(`${dir}.out`, 'utf8').slice(-2000)}`)

const one = new Agent({ keepAlive: true, maxSockets: 1 })
const many = new Agent({ keepAlive: true, maxSockets: AT_ONCE })
for (;;) {
  if (exited !== null) throw failed('starting')
  try {
    if ((await call(one, port, 'GET', '/xrpc/_health')).status === 200) break
  } catch {}
  await sleep(5)
}

// The accounts, and their records, 16 at once.
const accounts = []
for (let i = 0; i < ACCOUNTS; i++) {
  const res = await call(one, port, 'POST', '/xrpc/com.atproto.server.createAccount', { handle: `ladder${i}.test`, email: `ladder${i}@example.com`, password: `ladder-${i}` })
  if (res.status !== 200) throw failed(`createAccount: ${res.status} ${res.body}`)
  const { did, accessJwt } = JSON.parse(res.body)
  accounts.push({ did, auth: { authorization: `Bearer ${accessJwt}` } })
}
const records = execFileSync(BENCH, ['ladder-records', String(ACCOUNTS), String(RECORDS)], { maxBuffer: 1 << 30 })
  .toString().trim().split('\n').map((l) => JSON.parse(l))
const write = async (account, body, method) => {
  const a = accounts[account]
  const res = await call(many, port, 'POST', `/xrpc/com.atproto.repo.${method}`, { repo: a.did, validate: false, ...body }, a.auth)
  if (res.status !== 200) throw failed(`${method}: ${res.status} ${res.body}`)
  return JSON.parse(res.body)
}
const written = []
// An account's records, in order, at most `BATCH` to a call: one commit,
// and one sync, each.
const batches = []
for (let a = 0; a < ACCOUNTS; a++) {
  for (let i = 0; i < RECORDS; i += BATCH) batches.push(records.slice(a * RECORDS + i, a * RECORDS + Math.min(i + BATCH, RECORDS)))
}
await Promise.all(Array.from({ length: AT_ONCE }, async () => {
  while (batches.length) {
    const mine = batches.shift()
    const writes = mine.map(({ rkey, value }) => ({ $type: 'com.atproto.repo.applyWrites#create', collection: COLLECTION, rkey, value }))
    const { results } = await write(mine[0].account, { writes }, 'applyWrites')
    mine.forEach((r, j) => written.push({ path: `/xrpc/com.atproto.repo.getRecord?repo=${accounts[r.account].did}&collection=${COLLECTION}&rkey=${r.rkey}`, cid: results[j].cid }))
  }
}))

// Past the backfill window twice over, one more record each, which folds
// the log of each into its table; then until every fold is in place.
await sleep(1200)
await Promise.all(accounts.map((_, account) => write(account, { collection: COLLECTION, record: records[account * RECORDS].value }, 'createRecord')))
for (const at = performance.now(); ; await sleep(20)) {
  const folded = accounts.every(({ did }) => {
    const files = readdirSync(join(dir, 'repos', did))
    return files.includes('repo.checkpoint') && !files.includes('repo.checkpoint.tmp') && files.filter((f) => f.endsWith('.log')).length === 1
  })
  if (folded) break
  if (performance.now() - at > 30000) throw failed('the accounts\' logs not folded in 30 s')
}

// One pass over every record, each checked.
for (const w of written) {
  const res = await call(one, port, 'GET', w.path)
  if (res.status !== 200 || JSON.parse(res.body).cid !== w.cid) throw failed(`getRecord: ${res.status} ${res.body}`)
}

const draws = (seed, n) => {
  const below = rng(seed)
  return Array.from({ length: n }, () => written[below(written.length)].path)
}
/// Each of `paths` one after another on one connection: the times in µs, sorted.
const timed = async (paths) => {
  const times = []
  for (const path of paths) {
    const at = performance.now()
    const res = await call(one, port, 'GET', path)
    times.push((performance.now() - at) * 1000)
    if (res.status !== 200) throw failed(`${path}: ${res.status}`)
  }
  return times.sort((a, b) => a - b)
}
/// `paths` for each of 16 connections, at once: requests per second.
const rate = async (paths) => {
  const started = performance.now()
  await Promise.all(paths.map(async (mine) => {
    for (const path of mine) {
      const res = await call(many, port, 'GET', path)
      if (res.status !== 200) throw failed(`${path}: ${res.status}`)
    }
  }))
  return (AT_ONCE * EACH) / ((performance.now() - started) / 1000)
}
const health = Array.from({ length: LOOKUPS }, () => '/xrpc/_health')
await timed(health.slice(0, 2000))
const rows = [
  ['5a', 'a request answered with no record, `GET /xrpc/_health`: HTTP, the server\'s router and the client', await timed(health), await rate(Array.from({ length: AT_ONCE }, () => health.slice(0, EACH)))],
  ['5b', 'stage 4 over HTTP, `com.atproto.repo.getRecord`: that, and the server\'s own work around the store', await timed(draws(1, LOOKUPS)), await rate(Array.from({ length: AT_ONCE }, (_, t) => draws(2 + t, EACH)))],
]

proc.kill('SIGTERM')
await new Promise((ok) => (exited === null ? proc.on('exit', ok) : ok()))
one.destroy()
many.destroy()
plc.close()
closeSync(out)
rmSync(dir, { recursive: true, force: true })
rmSync(`${dir}.out`, { force: true })

const at = (sorted, perCent) => sorted[Math.min(Math.floor((sorted.length * perCent) / 100), sorted.length - 1)]
console.log(`Over HTTP, from the server (\`target/release/pds\`): ${ACCOUNTS} accounts of ${RECORDS} of the same records each, written with \`applyWrites\` and folded into their tables, after one pass over every record. One at a time: ${LOOKUPS} requests on one kept-alive connection from Node's \`http\` client; at once, ${AT_ONCE} connections of ${EACH} requests each.\n`)
console.log(`| stage | is | one at a time: p50 µs | p99 µs | ${AT_ONCE} at once: per s |`)
console.log('|--:|---|--:|--:|--:|')
for (const [stage, adds, times, perS] of rows) {
  console.log(`| ${stage} | ${adds} | ${at(times, 50).toFixed(1)} | ${at(times, 99).toFixed(1)} | ${perS.toFixed(0)} |`)
}