chadtmiller.com/monolith
An atproto PDS
0
0
// Blobs in a bucket (spec/BLOBS.md, "Where blobs are kept"), with --s3: both
// sides keep their blobs in buckets of the S3 store the harness runs
// (lib/s3.mjs), each its own. The store fails as the steps ask, for both
// sides alike, and the answers are compared. What the server keeps in its
// bucket and in its data directory is held to spec/BLOBS.md, which the
// reference, keeping its uploads under keys of its own, cannot say: every
// object a blob's bytes under its key, every blob the harness knows the
// account holds with its object, and none of a blob it no longer holds, of
// an account deleted, or of an upload the server was killed during; and no
// blob's bytes in a file of the data directory.
import { createHash } from 'node:crypto'
import { readdirSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { isDeepStrictEqual } from 'node:util'
import { below, pick } from '../lib/random.mjs'
import { cand, dataDir, metricsUrl, ref, s3, server, wait } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { BUCKETS, S3_TIMEOUT_MS } from '../lib/s3.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { normalize, xrpc } from '../lib/xrpc.mjs'
import { compareGetBlob, hold, landed, model, plainBody, rawCid, referenceAgain, referenced, referencedCids, reuploadAtOnce, soleRefs, uploadOn } from './blobs.mjs'
const UPLOAD = 'com.atproto.repo.uploadBlob'
const SPEC = 'spec/BLOBS.md, "Where blobs are kept"'
const STORE_REQUESTS = 'spec/BLOBS.md, "Requests to the store"'
/// How long the server has to bring its bucket to what it holds.
const WITHIN_MS = 60_000
/// The ways the store fails a request: an S3 error, the connection reset,
/// or no answer, past both sides' timeouts.
const FAILURES = [
['an S3 500', { status: 500, code: 'InternalError' }],
['an S3 503', { status: 503, code: 'SlowDown' }],
['the connection reset', 'reset'],
['no answer', 'hang'],
]
/// The operations that store an object, whichever a side uses.
const PUTS = ['PutObject', 'CreateMultipartUpload', 'UploadPart', 'CompleteMultipartUpload', 'CopyObject']
const READS = ['GetObject', 'HeadObject']
const DELETES = ['DeleteObject', 'DeleteObjects']
/// Uploads the server was killed during, whose objects the store kept:
/// `blocks/<did>/<cid>` keys the bucket must lose within a minute.
const orphans = new Set()
/// When the server last started, for what its metrics count.
let lastStart = 0
const serverKey = (acct, cid) => `blocks/${didOf(cand, acct)}/${cid}`
/// The reference's key for the account's blob `cid`, which it keeps under
/// a key of its own that ends in the CID once a record references it.
function referenceKey(acct, cid) {
const did = didOf(ref, acct)
const key = [...s3.objects(BUCKETS.reference).keys()].find((k) => k.endsWith(`/${cid}`) && k.includes(did))
if (!key) throw new Error(`the reference keeps no object for ${did}'s blob ${cid}; its keys: ${[...s3.objects(BUCKETS.reference).keys()].slice(0, 20).join(', ')}`)
return key
}
const logSize = () => statSync(server.logPath).size
/// The server's log lines since `offset`, parsed.
const logSince = (offset) =>
readFileSync(server.logPath)
.subarray(offset)
.toString('utf8')
.split('\n')
.filter(Boolean)
.flatMap((l) => {
try {
return [JSON.parse(l)]
} catch {
return []
}
})
/// A `blobstore failure` line of `op` since `offset`, with `status` when
/// the store answered one (spec/OPERATIONS.md).
async function loggedFailure(op, offset, status, request) {
for (let i = 0; i < 40; i++) {
const line = logSince(offset).find((l) => l.msg === 'blobstore failure' && l.op === op)
if (line) {
if (line.level !== 'warn' || typeof line.error !== 'string' || typeof line.did !== 'string' || (status !== undefined && line.status !== status)) await differ('log', { ...request, op }, { msg: 'blobstore failure', level: 'warn', op, status, error: 'why', did: 'the account' }, line, 'spec/OPERATIONS.md')
return count(`a \`blobstore failure\` line, ${op}`, true)
}
await wait(50)
}
await differ('log', { ...request, op }, 'a `blobstore failure` line', 'none', 'spec/OPERATIONS.md')
}
// ---- Steps ---------------------------------------------------------------
/// uploadBlob of a body of the run's own while the store fails to keep it,
/// one way for both sides: answered alike, and held by neither.
export async function failedUpload(acct) {
const [how, mode] = pick(FAILURES)
const bytes = plainBody('failed upload ')
const offset = logSize()
s3.fail({ op: PUTS, mode })
const [a, b] = await Promise.all([ref, cand].map((side) => uploadOn(side, { bytes, type: 'text/plain', token: acct })))
s3.clearFailures()
const request = { bytes: `${bytes.length} bytes`, store: how }
const [na, nb] = [normalize(ref, a, UPLOAD), normalize(cand, b, UPLOAD)]
if (!isDeepStrictEqual(na, nb)) await differ(`${UPLOAD}, the store failing`, request, na, nb, SPEC)
count(`uploadBlob, the store failing with ${how}`, a.status === 200)
if (b.status !== 200) await loggedFailure('put', offset, typeof mode === 'object' ? mode.status : undefined, request)
const cid = await rawCid(bytes)
await compareGetBlob('getBlob of an upload the store failed', (side) => ({ did: didOf(side, acct), cid }))
}
/// getBlob of a blob a record references while the store fails to read it,
/// one way for both sides; then again once it reads. Given no answer, the
/// reference waits on past its timeout, so the server alone is held to
/// spec/BLOBS.md then: `500 InternalServerError` within its timeout.
export async function failedRead(acct) {
const cid = await referencedBlob(acct)
if (!cid) return
const [how, mode] = pick(FAILURES)
const offset = logSize()
s3.fail({ op: READS, mode })
if (mode === 'hang') {
const t = Date.now()
const got = await xrpc(cand, 'com.atproto.sync.getBlob', { params: { did: didOf(cand, acct), cid }, raw: true })
const ms = Date.now() - t
if (got.status !== 500 || got.body?.error !== 'InternalServerError' || ms > S3_TIMEOUT_MS + 3000) await differ('getBlob, the store never answering', { cid }, { status: 500, error: 'InternalServerError', within: `${S3_TIMEOUT_MS} ms and 3 s` }, { status: got.status, error: got.body?.error, ms }, SPEC)
count('getBlob, the store never answering', false)
} else await compareGetBlob(`getBlob, the store failing with ${how}`, (side) => ({ did: didOf(side, acct), cid }))
s3.clearFailures()
await loggedFailure('get', offset, typeof mode === 'object' ? mode.status : undefined, { cid, store: how })
await compareGetBlob('getBlob once the store reads again', (side) => ({ did: didOf(side, acct), cid }))
}
/// getBlob, on the server alone, of a blob a record references of 2 bytes
/// or more, while the store sends the head of its read and half its bytes
/// and drops the connection, which the reference is not compared on:
/// `200` with the blob's `Content-Length`, the answer ending short of it
/// (spec/BLOBS.md, "The objects"). Its `request` line's `bytes`, fewer than
/// the size, is checked with the rest of the log (checks/logging.mjs).
export async function cutRead(acct) {
const m = model(acct)
const cids = referencedCids(m).filter((c) => !m.takedowns.has(c) && (m.stored.get(c)?.size ?? 0) >= 2)
if (!cids.length) return
const cid = pick(cids)
const size = m.stored.get(cid).size
const url = new URL(`${cand.url}/xrpc/com.atproto.sync.getBlob`)
url.searchParams.set('did', didOf(cand, acct))
url.searchParams.set('cid', cid)
s3.fail({ bucket: BUCKETS.server, op: 'GetObject', mode: 'cut' })
const got = { status: 0, 'content-length': null, read: 0, ended: 'whole' }
try {
const res = await fetch(url, { headers: { 'accept-encoding': 'identity' } })
Object.assign(got, { status: res.status, 'content-length': res.headers.get('content-length') })
try {
for await (const chunk of res.body ?? []) got.read += chunk.byteLength
} catch {
got.ended = 'short'
}
} catch (err) {
got.ended = `request failed: ${err.message}`
}
s3.clearFailures()
const ok = got.status === 200 && got['content-length'] === String(size) && got.ended === 'short' && got.read < size
if (!ok) await differ('getBlob, the store cutting its read short', { cid, size }, { status: 200, 'content-length': String(size), ended: 'short', read: `fewer than ${size}` }, got, SPEC)
count('getBlob, the store cutting its read short', ok)
}
/// getBlob of a blob a record references whose object something other
/// than the server deleted, on both sides, as a backup brought back finds
/// one (spec/DURABILITY.md); then the objects put back.
export async function objectGone(acct) {
const cid = await referencedBlob(acct)
if (!cid) return
const keys = [[BUCKETS.reference, referenceKey(acct, cid)], [BUCKETS.server, serverKey(acct, cid)]]
const saved = keys.map(([bucket, key]) => s3.objects(bucket).get(key))
if (!saved[1]) return differ('the server\'s bucket', { cid }, `an object ${keys[1][1]}`, 'none', SPEC)
for (const [bucket, key] of keys) s3.remove(bucket, key)
await compareGetBlob('getBlob of a blob whose object is gone', (side) => ({ did: didOf(side, acct), cid }))
keys.forEach(([bucket, key], i) => s3.put(bucket, key, saved[i].bytes, saved[i].contentType))
await compareGetBlob('getBlob of a blob whose object is back', (side) => ({ did: didOf(side, acct), cid }))
}
/// A write that stops the account holding a blob while the store fails the
/// server's deletes: answered alike, as no write waits on a delete. The
/// server must delete the object once the store answers again (bucketHolds).
export async function failedDelete(acct) {
const m = model(acct)
const C = 'com.example.blob'
const sole = await soleRefs(acct)
if (!sole.length) return
const [rkey] = pick(sole)
const [how, mode] = pick(FAILURES)
const offset = logSize()
const failing = s3.fail({ bucket: BUCKETS.server, op: DELETES, mode })
const [a, b] = await Promise.all([ref, cand].map((side) => xrpc(side, 'com.atproto.repo.deleteRecord', { body: { repo: acct.handle, collection: C, rkey }, token: acct })))
const request = { nsid: 'com.atproto.repo.deleteRecord', rkey, store: `failing the server's deletes with ${how}` }
if (!isDeepStrictEqual(normalize(ref, a, 'com.atproto.repo.deleteRecord'), normalize(cand, b, 'com.atproto.repo.deleteRecord'))) await differ('deleteRecord, the store failing deletes', request, a.body, b.body, SPEC)
if (a.status < 400) {
acct.records.delete(`${C}/${rkey}`)
landed(acct, m, a, b, [{ rkey, value: null }])
}
// Long enough for a delete to be tried, as the server deletes within a
// minute; then the store answers again.
for (let i = 0; i < 20 && !failing.count; i++) await wait(100 + below(100))
s3.clearFailures()
if (failing.count && mode !== 'hang') await loggedFailure('delete', offset, typeof mode === 'object' ? mode.status : undefined, request)
count(`a delete the store failed with ${how}`, failing.count > 0)
}
/// A blob uploaded again while the write that stops the account holding it
/// lands: on the server, its store answers the upload's `PUT` late, so that
/// the write lands while the upload is on its way and the delete of the
/// object the write makes owed comes while it is; on the reference, the
/// write then the upload. Answered after the write, the upload holds the
/// blob on both: a record referencing it is taken and it reads back whole,
/// and the server's bucket keeps its object (spec/BLOBS.md, "The objects":
/// an object is never deleted for a blob held again).
export async function uploadDuringDelete(acct) {
const m = model(acct)
const sole = await soleRefs(acct)
if (!sole.length) return
const [rkey, cid] = pick(sole)
const up = m.uploads.find((u) => u.cid === cid)
const C = 'com.example.blob'
const slow = s3.fail({ bucket: BUCKETS.server, op: PUTS, key: serverKey(acct, cid), mode: { delayMs: 500 }, times: 1 })
const uploading = uploadOn(cand, { bytes: up.bytes, type: up.type, token: acct })
for (let i = 0; i < 50 && !slow.count; i++) await wait(10)
const del = (side) => xrpc(side, 'com.atproto.repo.deleteRecord', { body: { repo: acct.handle, collection: C, rkey }, token: acct })
const [a, b] = await Promise.all([del(ref), del(cand)])
if (!isDeepStrictEqual(normalize(ref, a, 'com.atproto.repo.deleteRecord'), normalize(cand, b, 'com.atproto.repo.deleteRecord'))) await differ('deleteRecord while an upload of its blob is on its way', { rkey }, a.body, b.body, SPEC)
if (a.status >= 400) {
await uploading
return s3.clearFailures()
}
acct.records.delete(`${C}/${rkey}`)
landed(acct, m, a, b, [{ rkey, value: null }])
const nb = normalize(cand, await uploading, UPLOAD)
s3.clearFailures()
const ua = await uploadOn(ref, { bytes: up.bytes, type: up.type, token: acct })
const na = normalize(ref, ua, UPLOAD)
if (!isDeepStrictEqual(na, nb)) await differ(`${UPLOAD} answered after a write that stopped its blob being held`, { bytes: `${up.bytes.length} bytes`, type: up.type, server: 'the store answering its PUT late, the write landing meanwhile' }, na, nb, SPEC)
count('an upload on its way as its blob stops being held', slow.count > 0)
if (ua.status !== 200) return
hold(m, cid, ua.body.blob)
await referenceAgain(acct, m, cid, 'on its way as the blob stopped being held', 'uploaded as it stopped being held')
}
/// getBlob of a blob a record references while the store resets the
/// connection of each side's first read of it, once: sent again over a
/// connection of its own, it is read back whole, on both sides alike
/// (spec/BLOBS.md, "Requests to the store").
export async function resetOnce(acct) {
const cid = await referencedBlob(acct)
if (!cid) return
const rules = [BUCKETS.reference, BUCKETS.server].map((bucket) => s3.fail({ bucket, op: READS, mode: 'reset', times: 1 }))
const a = await compareGetBlob('getBlob, the store resetting its first read once', (side) => ({ did: didOf(side, acct), cid }))
s3.clearFailures()
if (rules.some((r) => r.count !== 1) || a.status !== 200) await differ('getBlob, the store resetting its first read once', { cid }, { reset: [1, 1], status: 200 }, { reset: rules.map((r) => r.count), status: a.status }, STORE_REQUESTS)
}
/// Two getBlobs of the server's 3 s apart, past the 2 s a client might keep
/// a connection and within the 5 s the store keeps one: the second read
/// goes over the connection the first left open (spec/BLOBS.md, "Requests
/// to the store").
export async function keptConnection(acct) {
const cid = await referencedBlob(acct)
if (!cid) return
const key = serverKey(acct, cid)
const read = async () => {
const got = await xrpc(cand, 'com.atproto.sync.getBlob', { params: { did: didOf(cand, acct), cid }, raw: true })
if (got.status !== 200) await differ('getBlob, for the store\'s connections', { cid }, 200, got.status, STORE_REQUESTS)
return s3.requests.findLast((r) => r.bucket === BUCKETS.server && r.op === 'GetObject' && r.key === key)
}
const first = await read()
await wait(3000)
const second = await read()
const kept = Boolean(first && second && second !== first && second.connection === first.connection)
if (!kept) await differ('the server\'s reads from the store, 3 s apart', { cid }, 'the second over the connection the first left open', { first: first?.connection ?? 'no read', second: second && second !== first ? second.connection : 'no read' }, STORE_REQUESTS)
count('a connection to the store kept between reads', true)
}
/// A blob a record of the account references, not taken down: one it has,
/// or one made.
async function referencedBlob(acct) {
const m = model(acct)
const known = referencedCids(m).filter((c) => !m.takedowns.has(c))
if (known.length) return pick(known)
const made = await soleRefs(acct)
return made.length ? pick(made)[1] : null
}
// ---- Crashes -------------------------------------------------------------
/// Before a kill: an upload to the server alone whose object the store
/// keeps and never answers, so that the server is killed with nothing of
/// it but what it logged before. After the restart the server holds none
/// of it, so a record referencing it is refused, and its object must go
/// (bucketHolds).
export async function orphanUpload() {
const acct = pick(accounts)
const bytes = plainBody('orphan ')
const cid = await rawCid(bytes)
const key = serverKey(acct, cid)
s3.fail({ bucket: BUCKETS.server, op: PUTS, key, mode: 'store-then-hang', times: 1 })
const sent = uploadOn(cand, { bytes, type: 'text/plain', token: acct }).catch(() => null)
for (let i = 0; i < 100 && !s3.objects(BUCKETS.server).has(key); i++) await wait(20)
const stored = s3.objects(BUCKETS.server).has(key)
return {
async settle() {
await sent
s3.clearFailures()
if (!stored) return
orphans.add(key)
const record = { $type: 'com.example.blob', img: { $type: 'blob', ref: { $link: cid }, mimeType: 'text/plain', size: bytes.length } }
const got = await xrpc(cand, 'com.atproto.repo.createRecord', { body: { repo: didOf(cand, acct), collection: 'com.example.blob', record }, token: acct })
if (got.status !== 400 || got.body?.error !== 'BlobNotFound') await differ('createRecord referencing an upload the server was killed during, its object kept by the store', { cid }, { status: 400, error: 'BlobNotFound' }, { status: got.status, body: got.body }, SPEC)
count('an upload the server was killed during, its object kept by the store', false)
},
}
}
/// After a restart: noted, for the metrics, then the bucket held.
export async function afterRestart() {
lastStart = Date.now()
await bucketHolds('after a restart')
await dataDirHoldsNoBlobs('after a restart')
}
// ---- What the server keeps -----------------------------------------------
/// What is wrong with the server's bucket now, if anything: each object a
/// blob's bytes under `blocks/<did>/<cid>` of an account here; each blob the
/// harness knows an account holds with its object; and none of a blob it
/// stopped holding, of an account deleted, or of an upload the server was
/// killed during. And no request of the server's refused, or of an
/// operation the store does not know: the store refuses one not signed
/// (spec/BLOBS.md, "Requests to the store").
async function wrongs() {
const out = []
for (const r of s3.rejected.filter((x) => x.bucket === BUCKETS.server || !x.bucket)) out.push({ refused: r })
for (const r of s3.requests.filter((x) => x.op === 'Unknown')) out.push({ unknownOperation: r })
const byDid = new Map(accounts.map((a) => [didOf(cand, a), a]))
const objects = s3.objects(BUCKETS.server)
for (const [key, o] of objects) {
const k = /^blocks\/(did:[a-z]+:[^/]+)\/([a-z2-7]+)$/.exec(key)
if (!k) {
out.push({ key, wrong: 'a key of another form than blocks/<did>/<cid>' })
continue
}
const acct = byDid.get(k[1])
if (!acct) out.push({ key, wrong: 'an object of no account here' })
if ((await rawCid(o.bytes)) !== k[2]) out.push({ key, wrong: `bytes whose CID is ${await rawCid(o.bytes)}` })
if (acct?.deleted) out.push({ key, wrong: 'an object of an account deleted' })
if (acct?.blobs?.dropped.has(k[2]) && !acct.blobs.stored.has(k[2])) out.push({ key, wrong: 'an object of a blob the account no longer holds' })
if (orphans.has(key)) out.push({ key, wrong: 'an object of an upload the server was killed during, which it does not hold' })
}
for (const acct of accounts) {
if (acct.deleted || !acct.blobs) continue
for (const cid of acct.blobs.stored.keys()) if (!objects.has(serverKey(acct, cid))) out.push({ key: serverKey(acct, cid), wrong: `no object, of a blob the account holds${referenced(acct.blobs, cid) ? ', a record referencing it' : ''}` })
}
return out
}
/// The server's bucket, within a minute, as spec/BLOBS.md says it is.
export async function bucketHolds(when) {
const by = Date.now() + WITHIN_MS
for (;;) {
const w = await wrongs()
if (!w.length) {
for (const k of orphans) orphans.delete(k)
return count(`the server's bucket, ${when}`, true)
}
if (w.some((x) => x.refused || x.unknownOperation) || Date.now() > by) return differ(`the server's bucket, ${when}`, { bucket: BUCKETS.server, objects: s3.objects(BUCKETS.server).size }, 'what spec/BLOBS.md says, within a minute', w.slice(0, 20), SPEC)
await wait(250)
}
}
/// No file of the data directory is the bytes of a blob an account holds:
/// with a bucket, they are all the store's.
export async function dataDirHoldsNoBlobs(when) {
const held = new Map()
for (const acct of accounts) for (const u of acct.blobs?.uploads ?? []) if (u.bytes.length && acct.blobs.stored.has(u.cid)) held.set(createHash('sha256').update(u.bytes).digest('hex'), { cid: u.cid, size: u.bytes.length })
const sizes = new Set([...held.values()].map((h) => h.size))
const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(dir, e.name)) : e.isFile() ? [join(dir, e.name)] : []))
for (const path of walk(dataDir)) {
let size
try {
size = statSync(path).size
} catch {
continue
}
if (!sizes.has(size)) continue
const h = held.get(createHash('sha256').update(readFileSync(path)).digest('hex'))
if (h) await differ(`the data directory, ${when}`, { file: path.slice(dataDir.length + 1) }, 'no file of a blob\'s bytes: they are the bucket\'s', `the bytes of ${h.cid}`, SPEC)
}
count(`the data directory holds no blob, ${when}`, true)
}
/// The requests to the bucket since the server last started, in its
/// metrics: at least each upload the store kept for it (spec/OPERATIONS.md).
export async function blobstoreCounted() {
const puts = s3.requests.filter((r) => r.bucket === BUCKETS.server && r.op === 'PutObject' && r.status >= 200 && r.status < 300 && r.at >= lastStart).length
const text = await (await fetch(metricsUrl)).text()
const value = (outcome) => Number(new RegExp(`^pds_outbound_requests_total\\{(?=[^}]*target="blobstore")(?=[^}]*outcome="${outcome}")[^}]*\\} (\\d+)`, 'm').exec(text)?.[1] ?? 0)
if (value('ok') < puts) await differ('metrics', { metric: 'pds_outbound_requests_total{target="blobstore",outcome="ok"}' }, `at least the ${puts} uploads the store kept since the server started`, value('ok'), 'spec/OPERATIONS.md')
count('requests to the bucket, counted', true)
}
/// The steps a run with --s3 adds, by weight.
export const S3_STEPS = [[failedUpload, 3], [failedRead, 2], [cutRead, 1], [objectGone, 1], [failedDelete, 2], [reuploadAtOnce, 2], [uploadDuringDelete, 2], [resetOnce, 1], [keptConnection, 1]]