~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zlay

atproto relay in zig · mirror of https://tangled.org/zat.dev/zlay

0
0
135 lines · 7.7 KB Raw History
import { readFile, writeFile, readdir, stat } from 'node:fs/promises'
import { execFileSync } from 'node:child_process'
import WebSocket from '/opt/canary/node_modules/ws/wrapper.mjs'
import { decodeAll } from '/opt/canary/node_modules/@atproto/lex-cbor/dist/index.js'

const origin = new URL(process.argv[2])
const liveSeconds = Number(process.argv[3] || 180)
const expiredOverride = process.argv[4] === undefined ? null : Number(process.argv[4])
if (!Number.isInteger(liveSeconds) || liveSeconds < 10 || liveSeconds > 180 || (expiredOverride !== null && (!Number.isSafeInteger(expiredOverride) || expiredOverride < 0))) throw new Error('invalid probe bounds')
const endpoint = (base, cursor) => {
  const url = new URL('/xrpc/com.atproto.sync.subscribeRepos', base)
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
  if (cursor !== undefined) url.searchParams.set('cursor', String(cursor))
  return url.href
}
const pairs = new Map()
const samples = []
const result = { origin: origin.href, ok: false }
async function collect(url, milliseconds, infoOnly = false, Client = WebSocket) {
  return new Promise((resolve, reject) => {
    const socket = new Client(url)
    socket.binaryType = 'arraybuffer'
    const counts = { messages: 0, malformed: 0, reversals: 0, gaps: 0, duplicates: 0, firstSeq: null, lastSeq: null, info: [] }
    let timer = setTimeout(() => { socket.close(); reject(new Error('WebSocket did not open')) }, 10000)
    let planned = false
    const finish = () => { planned = true; clearTimeout(timer); if (infoOnly && socket.terminate) socket.terminate(); else socket.close(); resolve(counts) }
    socket.addEventListener('open', () => { clearTimeout(timer); timer = setTimeout(finish, milliseconds) })
    socket.addEventListener('error', event => { clearTimeout(timer); reject(new Error(`WebSocket connection error: ${event.error?.message || event.message || 'unknown'}`)) })
    socket.on?.('unexpected-response', (_request, response) => {
      clearTimeout(timer)
      let body = ''
      response.on('data', chunk => { if (body.length < 2048) body += chunk.toString() })
      response.on('end', () => reject(new Error(`WebSocket HTTP ${response.statusCode}: ${body}`)))
    })
    socket.addEventListener('close', () => { if (!planned) { clearTimeout(timer); reject(new Error('Unexpected WebSocket close')) } })
    socket.addEventListener('message', event => {
      if (planned) return
      counts.messages++
      try {
        const [head, body] = decodeAll(new Uint8Array(event.data))
        if (head.op === -1) throw new Error(`Relay error: ${body.error}`)
        if (head.t === '#info') {
          counts.info.push(body.name)
          if (infoOnly) finish()
        }
        if (typeof body.seq === 'number') {
          if (counts.firstSeq === null) counts.firstSeq = body.seq
          if (counts.lastSeq !== null) {
            if (body.seq < counts.lastSeq) counts.reversals++
            if (body.seq === counts.lastSeq) counts.duplicates++
            if (body.seq > counts.lastSeq + 1) counts.gaps++
          }
          counts.lastSeq = body.seq
        }
        if (head.t === '#account' && body.active === false) {
          for (const [key,pair] of pairs) if (pair.did === body.did) pairs.delete(key)
        }
        if (head.t === '#commit' && /^did:plc:[a-z2-7]{24}$/.test(body.repo || '')) {
          for (const op of body.ops || []) {
            if (op.action !== 'create' && op.action !== 'update') continue
            const collection = op.path?.split('/')[0]
            if (!collection) continue
            const key = `${body.repo}/${collection}`
            pairs.delete(key)
            pairs.set(key, { did: body.repo, collection })
            while (pairs.size > 8) pairs.delete(pairs.keys().next().value)
          }
        }
      } catch (error) {
        counts.malformed++
        if (infoOnly) { clearTimeout(timer); socket.close(); reject(error) }
      }
    })
  })
}
const pid = execFileSync('pgrep', ['-x', 'zlay'], { encoding: 'utf8' }).trim()
let sampling = false
async function sample() {
  if (sampling) return
  sampling = true
  try {
    const response = await fetch('http://127.0.0.1:3001/metrics', { signal: AbortSignal.timeout(2500) })
    samples.push({ time: new Date().toISOString(), metrics: await response.text(), status: await readFile(`/proc/${pid}/status`, 'utf8') })
  } catch (error) { samples.push({ time: new Date().toISOString(), error: error.message }) }
  finally { sampling = false }
}
const interval = setInterval(sample, 10000)
try {
  result.health = (await fetch(new URL('/_healthz', origin), { signal: AbortSignal.timeout(5000) })).status
  result.admin = (await fetch(new URL('/admin/ingest-stall', origin), { signal: AbortSignal.timeout(5000) })).status
  await sample()
  result.nativePublic = await collect(endpoint(origin), 3000, false, globalThis.WebSocket)
  result.publicLive = await collect(endpoint(origin), 3000)
  result.live = await collect(endpoint('http://127.0.0.1:3000'), liveSeconds * 1000)
  const cursor = result.live.lastSeq - 256
  result.publicReplay = await collect(endpoint(origin, cursor), 10000)
  const refs = execFileSync('psql', ['-h','127.0.0.1','-U','postgres','-d','relay','-Atc','SELECT min(seq_start),count(*) FROM log_file_refs'], { encoding: 'utf8' }).trim().split('|').map(Number)
  result.oldestSeq = refs[0]
  result.retainedFiles = refs[1]
  result.expiredCursor = expiredOverride ?? result.live.firstSeq
  result.expired = await collect(endpoint(origin, result.expiredCursor), 5000, true)
  result.membership = []
  for (const pair of [...pairs.values()]) {
    const url = new URL('/xrpc/com.atproto.sync.listReposByCollection', origin)
    url.searchParams.set('collection',pair.collection)
    url.searchParams.set('cursor',pair.did.slice(0,-1))
    url.searchParams.set('limit','100')
    const response = await fetch(url, { signal: AbortSignal.timeout(5000) })
    const page = await response.json()
    const present = response.ok && page.repos?.some(row=>row.did===pair.did)
    let removedAsExpected = false
    if (!present) {
      const statusUrl = new URL('/xrpc/com.atproto.sync.getRepoStatus',origin)
      statusUrl.searchParams.set('did',pair.did)
      const statusResponse = await fetch(statusUrl,{signal:AbortSignal.timeout(5000)})
      const status = await statusResponse.json()
      removedAsExpected = statusResponse.ok && status.active===false
    }
    result.membership.push({ ...pair, ok:present || removedAsExpected, removedAsExpected })
  }
  await sample()
  result.eventBytes = 0
  for (const name of await readdir('/opt/canary/data/events')) {
    if (name.startsWith('evts-')) result.eventBytes += (await stat(`/opt/canary/data/events/${name}`)).size
  }
  const histories = samples.flatMap(s => [...(s.metrics || '').matchAll(/^relay_history_entries (\d+)/gm)].map(m=>Number(m[1])))
  result.ok = result.health===200 && [403,404].includes(result.admin) && result.live.messages>1000 && result.live.malformed===0 && result.live.gaps===0 && result.live.reversals===0 && result.publicReplay.firstSeq===cursor+1 && result.publicReplay.malformed===0 && result.publicReplay.gaps===0 && result.publicReplay.reversals===0 && result.oldestSeq>result.expiredCursor && result.expired.info.includes('OutdatedCursor') && result.membership.length>0 && result.membership.every(row=>row.ok) && histories.length>0 && histories.every(n=>n===0) && result.eventBytes>0 && result.eventBytes<300*1024**2
} catch (error) { result.error = error.stack }
finally {
  clearInterval(interval)
  result.samples = samples
  await writeFile('/opt/canary/probe.json', JSON.stringify(result,null,2)+'\n')
}
console.log(JSON.stringify({ ok:result.ok, live:result.live, replay:result.publicReplay, expired:result.expired, eventBytes:result.eventBytes, error:result.error }))
if (!result.ok) process.exitCode = 1