OverviewFilesCommitsIssuesDocsReleasesPeers

keet-daemon / test / test-add-writer.mjs

75 lines · javascript ref:
import Pipe from 'bare-pipe'
import FramedStream from 'framed-stream'
import b4a from 'b4a'

const SOCKET = '/tmp/keet-daemon.sock'
const ASHATRON_KEY = 'c93dccd343cbd87859a84825888ecfa2985f4eeaf6158790053d97ed9393c91c'
let rpcId = 0

function connect () {
  const pipe = new Pipe(SOCKET)
  const framed = new FramedStream(pipe)
  const pending = new Map()
  framed.on('data', (buf) => {
    try {
      const msg = JSON.parse(b4a.toString(buf))
      const cb = pending.get(msg.id)
      if (cb) {
        pending.delete(msg.id)
        if (msg.ok !== undefined && msg.data !== undefined) msg.result = msg.data
        cb(msg)
      }
    } catch {}
  })
  function call (method, params = {}, timeoutMs = 15000) {
    return new Promise((resolve, reject) => {
      const id = ++rpcId
      const timeout = setTimeout(() => {
        pending.delete(id)
        reject(new Error(`RPC timeout: ${method}`))
      }, timeoutMs)
      pending.set(id, (msg) => {
        clearTimeout(timeout)
        if (msg.error) reject(new Error(msg.error.message || msg.error))
        else resolve(msg.result)
      })
      const payload = JSON.stringify({ jsonrpc: '2.0', id, method, params })
      framed.write(b4a.from(payload))
    })
  }
  function close () { framed.destroy(); pipe.destroy() }
  return { call, close }
}

async function run () {
  console.log('=== Add ashatron as writer + write sync marker ===\n')
  const client = connect()

  // Add ashatron as indexer
  console.log('--- Adding ashatron writer as indexer ---')
  const result = await client.call('meta.writers.add', { key: ASHATRON_KEY, indexer: true })
  console.log('  result:', JSON.stringify(result))

  // Write a sync marker from tabertron
  console.log('\n--- Writing sync marker from tabertron ---')
  const rooms = await client.call('rooms')
  if (rooms.length > 0) {
    const roomId = rooms[0].roomId || rooms[0].id
    const marker = 'tabertron-sync-' + Date.now()
    await client.call('meta.set', { roomId, metadata: { topics: [marker], syncTest: true } })
    const meta = await client.call('meta.get', { roomId })
    console.log('  room:', roomId.slice(0, 16) + '...')
    console.log('  marker:', marker)
    console.log('  written:', meta.topics?.includes(marker))
    console.log('\n  Now check ashatron: meta.get should show this marker after sync')
  }

  client.close()
  setTimeout(() => Bare.exit(0), 500)
}

run().catch(err => {
  console.error('FATAL:', err.message)
  Bare.exit(1)
})