anbot

root / test / browser / harness.html

6339 bytes

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ANBot browser harness</title>
</head>
<body>
<div id="result">RUNNING</div>
<pre id="details"></pre>
<script type="module">
import {
  authorFromPrivateKey, blockId, concat, createManifest, createRecord,
  generatePrivateKey, splitChunks, validateManifest, verifyBlock, verifyRecord
} from '/core.mjs'
import { memoryStore } from '/store.mjs'
import { createBrowserStore } from '/store-browser.mjs'
import { pull, reassembleBundle } from '/sync.mjs'

const params = {}
for (const part of location.hash.slice(1).split('&')) {
  const eq = part.indexOf('=')
  if (eq > 0) params[part.slice(0, eq)] = decodeURIComponent(part.slice(eq + 1))
}
const lines = []
function check(name, condition) {
  lines.push(`${condition ? 'ok' : 'FAIL'} ${name}`)
  if (!condition) throw new Error(`check failed: ${name}`)
}
try {
  // 1. Sign/verify round-trip with WebCrypto.
  const privateKey = await generatePrivateKey()
  const author = await authorFromPrivateKey(privateKey)
  const record = await createRecord({ author, privateKey }, { anbot: 1, type: 'harness', n: 42 })
  const body = await verifyRecord(record, author)
  check('sign/verify round-trip', body.n === 42)

  // 2. AndFS round-trip over core chunking and manifest validation.
  const bytes = new Uint8Array(600 * 1024)
  for (let i = 0; i < bytes.length; i++) bytes[i] = i % 251
  const chunks = splitChunks(bytes)
  check('chunk count', chunks.length === 3)
  const hashes = []
  for (const chunk of chunks) hashes.push(await blockId(chunk))
  const manifestBytes = createManifest(bytes.length, hashes)
  const manifest = validateManifest(manifestBytes)
  check('manifest size', manifest.size === bytes.length)
  const rebuilt = concat(...chunks)
  check('chunks rebuild bytes', rebuilt.length === bytes.length && rebuilt.every((b, i) => b === bytes[i]))
  for (let i = 0; i < chunks.length; i++) check('chunk hash', await verifyBlock(chunks[i], hashes[i]))

  // 2b. AndFS via the memory store and bundle reassembly.
  const memory = memoryStore()
  const manifestId = await blockId(manifestBytes)
  await memory.putBlock(manifestId, manifestBytes)
  for (let i = 0; i < chunks.length; i++) await memory.putBlock(hashes[i], chunks[i])
  const reassembled = await reassembleBundle(memory, manifestId)
  check('reassembleBundle round-trip', reassembled.length === bytes.length && reassembled.every((b, i) => b === bytes[i]))

  // 3+4. Browser stores, both backends: records, blocks, size cap, selection.
  for (const backend of ['opfs', 'idb']) {
    const store = await createBrowserStore({ backend, name: `anbot-harness-${backend}` })
    const encoded = new TextEncoder().encode(JSON.stringify(record))
    check(`${backend} record put`, await store.putRecord(record.id, encoded) === true)
    check(`${backend} record no-overwrite`, await store.putRecord(record.id, new TextEncoder().encode('x')) === false)
    const got = await store.getRecord(record.id)
    check(`${backend} record get`, got !== undefined && new TextDecoder().decode(got) === JSON.stringify(record))
    check(`${backend} missing record`, (await store.getRecord('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=')) === undefined)
    check(`${backend} post put`, await store.putPost(record.id, encoded) === true)
    check(`${backend} post no-overwrite`, await store.putPost(record.id, new TextEncoder().encode('x')) === false)
    const gotPost = await store.getPost(record.id)
    check(`${backend} post get`, gotPost !== undefined && new TextDecoder().decode(gotPost) === JSON.stringify(record))
    check(`${backend} missing post`, (await store.getPost('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=')) === undefined)
    check(`${backend} block put`, await store.putBlock(hashes[0], chunks[0]) === true)
    check(`${backend} block get`, (await store.getBlock(hashes[0], chunks[0].length)).length === chunks[0].length)
    let capped = false
    try { await store.getBlock(hashes[0], 1) } catch (error) { capped = /Block exceeds size limit/.test(error.message) }
    check(`${backend} block size cap`, capped)
    await store.putSelection({ repoId: 'r', ref: 'refs/heads/main', updateId: 'u' })
    check(`${backend} selection`, (await store.getSelection()).updateId === 'u')
  }

  // 5. Pull against the local node, then re-pull as a no-op.
  const store = await createBrowserStore({ backend: 'auto', name: 'anbot-harness-pull' })
  const result = await pull(store, params.node)
  check('pull repo', result.repoId === params.repo)
  check('pull update', result.updateId === params.update)
  check('pull stored records', result.stored >= 2)
  check('pull fetched blocks', result.fetched >= 2)
  check('pull stored post', result.posts === 1)
  const postBytes = await store.getPost(params.post)
  check('post held', postBytes !== undefined)
  const postRecord = JSON.parse(new TextDecoder().decode(postBytes))
  check('post text', JSON.parse(postRecord.content).text === params.postText)
  const selection = await store.getSelection()
  check('selection advanced', selection !== undefined && selection.updateId === params.update && selection.repoId === params.repo)
  check('repo record held', (await store.getRecord(params.repo)) !== undefined)
  const second = await pull(store, params.node)
  check('re-pull no-op', second.stored === 0 && second.fetched === 0 && second.posts === 0)
  const updateRecord = JSON.parse(new TextDecoder().decode(await store.getRecord(params.update)))
  const updateBody = JSON.parse(updateRecord.content)
  const bundle = await reassembleBundle(store, updateBody.bundle.id)
  check('bundle bytes held', bundle.length > 0)
  check('bundle is a git bundle', new TextDecoder().decode(bundle.subarray(0, 15)) === '# v2 git bundle')

  document.getElementById('result').textContent = 'PASS'
} catch (error) {
  lines.push(`FAIL ${error.message}`)
  document.getElementById('result').textContent = 'FAIL'
}
document.getElementById('details').textContent = lines.join('\n')
// Beacon the outcome to the static server so the test runner can read it
// without racing the page's async work.
const status = document.getElementById('result').textContent
await fetch('/__harness-result', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ status, lines })
})
</script>
</body>
</html>

Git ยท Social feed