// The WORKLET ANALOGUE. Opens a real Corestore + Hyperbee off the main thread, writes, reads back,
// and closes — reporting everything over the same message port a bare-kit worklet would use.
//
// This is the half of spike 2 that does not need Android: bare-kit's worklet IS a Bare thread with an
// IPC bridge (`BareKit.IPC` there, `Bare.IPC` here — the same primitive). If rocksdb could not open off
// the main thread, no amount of Android would save it.
const Worker = require('bare-worker')
const Corestore = require('corestore')
const Hyperbee = require('hyperbee')
const { dir, n } = Worker.workerData
const send = (m) => Worker.parentPort.postMessage(m)
async function main () {
const t0 = Date.now()
const store = new Corestore(dir)
await store.ready()
send({ step: 'corestore-ready', ms: Date.now() - t0 })
// A Hyperbee is what favela's appview actually is, so exercise that shape and not a bare core.
const bee = new Hyperbee(store.get({ name: 'probe' }), { keyEncoding: 'utf-8', valueEncoding: 'json' })
await bee.ready()
send({ step: 'hyperbee-ready', ms: Date.now() - t0 })
const batch = bee.batch()
for (let i = 0; i < n; i++) await batch.put(`k${String(i).padStart(5, '0')}`, { i, pad: 'x'.repeat(64) })
await batch.flush()
send({ step: 'wrote', n, ms: Date.now() - t0 })
// Read back through a range scan — the operation the timeline does, and the one that actually exercises
// rocksdb iterators rather than a single point lookup.
let seen = 0
let firstBad = null
for await (const { key, value } of bee.createReadStream()) {
if (value.i !== Number(key.slice(1))) firstBad = firstBad || key
seen++
}
send({ step: 'read', seen, firstBad, ms: Date.now() - t0 })
// The core's key proves the store is real and lets the parent re-derive it after we exit.
const core = store.get({ name: 'probe' })
await core.ready()
const key = core.key.toString('hex')
await store.close()
send({ step: 'closed', key, ms: Date.now() - t0 })
}
main().catch((e) => send({ step: 'ERROR', error: (e && e.stack) || String(e) }))