OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-proto-peer / scripts / swarm-reachability.mjs

54 lines · javascript ref:
// Swarm reachability diagnostic — do two machines connect over plain Hyperswarm on a shared topic,
// and HOW LONG does it take? Run the SAME command on both boxes; they discover each other, ping/pong,
// and report time-to-connect. This is the SAME transport pgh/pear-git-v3 already use between these
// machines, so it isolates "can they swarm at all + how fast" from atproto/bridge-specific timeouts.
//
//   bare scripts/swarm-reachability.mjs <label> [--topic <str>] [--timeout <ms>]
//
// A connection within a few seconds → the bridge's 15s PeerFront.discover timeout is the problem, not
// reachability. A slow (20-40s) connect → discover just needs a longer timeout. No connect → real block.

import '../lib/bare-globals.js'
import Hyperswarm from 'hyperswarm'
import DHT from 'hyperdht'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'

const argv = (typeof Bare !== 'undefined' && Bare.argv) ? Bare.argv : process.argv
const opt = (name, def) => { const i = argv.indexOf('--' + name); return i >= 0 ? argv[i + 1] : def }
const has = (name) => argv.indexOf('--' + name) >= 0
const label = argv.slice(2).find((a) => a && !a.startsWith('--')) || 'peer'
const topicStr = opt('topic', 'hpp-swarm-reachability-test-v1')
const timeoutMs = parseInt(opt('timeout', '60000'), 10)

// LAN levers: --host <ip> binds the DHT socket to one interface (excludes docker 172.x);
// --open declares firewalled:false so peers connect directly (bypasses the same-public-IP gate).
const host = opt('host', null)
const dhtOpts = {}
if (host) dhtOpts.host = host
if (has('open')) dhtOpts.firewalled = false

const topic = crypto.hash(b4a.from(topicStr))
const swarm = Object.keys(dhtOpts).length ? new Hyperswarm({ dht: new DHT(dhtOpts) }) : new Hyperswarm()
console.log(JSON.stringify({ event: 'config', label, dhtOpts }))
const t0 = Date.now()
let connections = 0

swarm.on('connection', (conn, info) => {
  connections++
  console.log(JSON.stringify({ event: 'connected', ms: Date.now() - t0, remote: b4a.toString(info.publicKey, 'hex').slice(0, 12), label }))
  conn.on('error', () => {})
  conn.write(b4a.from('ping:' + label))
  conn.on('data', (d) => console.log(JSON.stringify({ event: 'recv', from: b4a.toString(d), label })))
})

const disc = swarm.join(topic, { server: true, client: true })
await disc.flushed()
console.log(JSON.stringify({ event: 'joined', label, topic: b4a.toString(topic, 'hex').slice(0, 16), timeoutMs }))

setTimeout(async () => {
  console.log(JSON.stringify({ event: connections > 0 ? 'RESULT_ok' : 'RESULT_no_connection', connections, ms: Date.now() - t0, label }))
  try { await swarm.destroy() } catch {}
  process.exit(connections > 0 ? 0 : 1)
}, timeoutMs)