OverviewFilesCommitsIssuesDocsReleasesPeers

favela-peer / probe-weight.mjs

64 lines · javascript ref:
// What does autobee actually report as isIndexer, for the genesis writer and for one added
// inside apply? Measured, because apply-calls.js only sets isGenesis when NOT applying.
import Autobee from 'autobee'
import Corestore from 'corestore'
import b4a from 'b4a'
import fs from '#node:fs'
import os from '#node:os'
import { join } from '#node:path'

const tmp = () => fs.mkdtempSync(join(os.tmpdir(), 'probe-'))

function make (store, key, grants) {
  return new Autobee(store, key, {
    optimistic: true,
    fastForward: false,
    apply: async (batch, view, host) => {
      const w = view.write()
      for (const node of batch) {
        let op
        try { op = JSON.parse(b4a.toString(node.value, 'utf8')) } catch { continue }
        if (op.t === 'ack') { try { host.ackWriter(node.key) } catch {} }
        if (op.t === 'add' && op.writer) {
          try { host.addWriter(b4a.from(op.writer, 'hex'), { isIndexer: true }) } catch (e) { console.log('addWriter threw', e.message) }
        }
        w.tryPut(b4a.from('op/' + (op.t || '?') + '/' + Math.random(), 'utf8'), b4a.from('1'))
      }
      await w.flush()
    }
  })
}

const sA = new Corestore(tmp())
const a = make(sA.namespace('n'), null)
await a.ready()
console.log('A genesis  isIndexer=', a.isIndexer, ' writable=', a.writable, ' local=', b4a.toString(a.local.key, 'hex').slice(0, 8))
console.log('A system info for own local:', JSON.stringify(await a.system.get(a.local.key)))

// a second peer on the same namespace
const sB = new Corestore(tmp())
const b = make(sB.namespace('n'), a.key)
await b.ready()
const s1 = a.replicate(true); const s2 = b.replicate(false)
s1.pipe(s2).pipe(s1)
await a.update(); await b.update()
console.log('B before   isIndexer=', b.isIndexer, ' writable=', b.writable)

// B appends optimistically; A's apply acks it
await b.append(b4a.from(JSON.stringify({ t: 'ack' })), { optimistic: true })
await new Promise(r => setTimeout(r, 500))
await a.update(); await b.update()
console.log('B acked    isIndexer=', b.isIndexer, ' writable=', b.writable)
console.log('B system info (from A):', JSON.stringify(await a.system.get(b.local.key)))

// now A adds B as an indexer
await a.append(b4a.from(JSON.stringify({ t: 'add', writer: b4a.toString(b.local.key, 'hex') })))
await new Promise(r => setTimeout(r, 800))
await a.update(); await b.update()
console.log('B added    isIndexer=', b.isIndexer, ' writable=', b.writable)
console.log('B system info (from A):', JSON.stringify(await a.system.get(b.local.key)))
console.log('A system info (from A):', JSON.stringify(await a.system.get(a.local.key)))
console.log('A final    isIndexer=', a.isIndexer, ' writable=', a.writable)
console.log('B ack-only writable stayed false? see above')
await a.close(); await b.close()