fix: early-exit guild mesh flush when a peer connects

Default DHT flush wait dropped to 1.2s and resolves as soon as any mesh
peer is live, cutting guild.open joinMesh from ~3s to sub-second on
warm 2-person meshes.
This commit is contained in:
Raven Scott
2026-07-13 16:12:52 -04:00
parent 5f473acdb0
commit b0793515f0
+47 -6
View File
@@ -2059,11 +2059,15 @@ class PearcordGuild extends EventEmitter {
}
if (!force && this._meshJoinedTopic === topicStr) {
this.reconcileMeshConnectionsFromSwarm()
// Already joined: only a short settle wait (or skip if peers already live).
if ((this.peers?.size ?? 0) > 0) {
return this.guild
}
const flushMs = Number(
opts.flushMs ??
process.env.PEARCORD_GUILD_SWARM_FLUSH_MS ??
process.env.PEARCORD_SWARM_FLUSH_MS ??
2500
800
)
const skipFlush =
opts.skipFlush === true || process.env.PEARCORD_GUILD_JOIN_SKIP_FLUSH === '1'
@@ -2098,26 +2102,63 @@ class PearcordGuild extends EventEmitter {
this._bindMeshConnectionHandler()
this.swarm.join(topic, { server: true, client: true })
this.reconcileMeshConnectionsFromSwarm()
// Prefer a short default: full 2500ms flush was blocking guild.open even when a
// peer had already connected mid-wait (common on 2-person meshes).
const flushMs = Number(
opts.flushMs ??
process.env.PEARCORD_GUILD_SWARM_FLUSH_MS ??
process.env.PEARCORD_SWARM_FLUSH_MS ??
2500
1200
)
const skipFlush =
opts.skipFlush === true || process.env.PEARCORD_GUILD_JOIN_SKIP_FLUSH === '1'
if (this.swarm.flush && !skipFlush) {
let flushed = false
await Promise.race([
this.swarm.flush().then(
let peerEarly = false
const flushPromise = this.swarm.flush().then(
() => {
flushed = true
},
() => {}
),
)
// Resolve as soon as any mesh peer is live — no need to sit on DHT flush budget.
const peerReady = new Promise((resolve) => {
const tick = () => {
this.reconcileMeshConnectionsFromSwarm?.()
if ((this.peers?.size ?? 0) > 0) {
peerEarly = true
resolve()
return true
}
return false
}
if (tick()) return
const onPeer = () => {
if (tick()) {
this.removeListener?.('peer', onPeer)
clearInterval(iv)
}
}
this.on?.('peer', onPeer)
const iv = setInterval(() => {
if (tick()) {
this.removeListener?.('peer', onPeer)
clearInterval(iv)
}
}, 50)
if (typeof iv.unref === 'function') iv.unref()
setTimeout(() => {
this.removeListener?.('peer', onPeer)
clearInterval(iv)
resolve()
}, flushMs).unref?.()
})
await Promise.race([
flushPromise,
peerReady,
new Promise((resolve) => setTimeout(resolve, flushMs))
])
if (!flushed) {
if (!flushed && !peerEarly) {
this.emit('mesh-flush-timeout', { flushMs, guildId: this.guild.id })
void this.swarm.flush().catch(() => {})
}