This commit is contained in:
Raven Scott
2026-05-20 22:28:59 -04:00
parent 341542f41b
commit e4400872c0
82 changed files with 2533 additions and 775 deletions
@@ -1,59 +1,123 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const { setInterval, clearInterval } = require('bare-timers')
const b4a = require('b4a')
const { assertNonEmpty } = require('../../_shared/lib/errors.js')
const { attachGossip, sendGossip } = require('../../_shared/storage-gossip-base.js')
const { initModuleSwarm, gossipSend } = require('../../_shared/p2p-bare.js')
const PROTOCOL = 'subscription-lease/v1'
const DEFAULT_LEASE_MS = 60000
class HyperP2PSubscriptionLease extends EventEmitter {
constructor (opts = {}) {
super()
this.topic = opts.topic || null
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
this._store = new Map()
this._stats = { ops: 0, gossipIn: 0, gossipOut: 0 }
this.ownerHex = b4a.toString(this.keyPair.publicKey, 'hex')
this.leaseMs = opts.leaseMs ?? DEFAULT_LEASE_MS
this.enableBackgroundTimers = opts.enableBackgroundTimers === true
this._leases = new Map()
this._timer = null
this._stats = { acquired: 0, released: 0, gossipIn: 0, gossipOut: 0 }
this.swarm = null
this._peerMsgs = null
}
put (key, value) {
assertNonEmpty(key, 'key')
this._store.set(key, value)
this._stats.ops++
sendGossip(this, { type: 'subscription-lease-sync', key, value })
this.emit('update', { key, value })
acquire (channel) {
assertNonEmpty(channel, 'channel')
const now = Date.now()
const current = this._leases.get(channel)
if (current && current.expiresAt > now && current.holder !== this.ownerHex) {
return { ok: false, holder: current.holder }
}
const lease = { channel, holder: this.ownerHex, acquiredAt: now, expiresAt: now + this.leaseMs }
this._leases.set(channel, lease)
this._stats.acquired++
if (this._peerMsgs) {
gossipSend(this, { type: 'sub-lease', lease })
this._stats.gossipOut++
}
this.emit('acquire', lease)
return { ok: true, ...lease }
}
renew (channel) {
const lease = this._leases.get(channel)
if (!lease || lease.holder !== this.ownerHex) return false
lease.expiresAt = Date.now() + this.leaseMs
if (this._peerMsgs) {
gossipSend(this, { type: 'sub-lease', lease })
this._stats.gossipOut++
}
return true
}
get (key) { return this._store.get(key) }
delete (key) {
const ok = this._store.delete(key)
if (ok) sendGossip(this, { type: 'subscription-lease-sync', key, value: null })
return ok
release (channel) {
const lease = this._leases.get(channel)
if (!lease || lease.holder !== this.ownerHex) return false
this._leases.delete(channel)
this._stats.released++
if (this._peerMsgs) {
gossipSend(this, { type: 'sub-release', channel, holder: this.ownerHex })
this._stats.gossipOut++
}
return true
}
entries () { return [...this._store.entries()] }
holder (channel) {
const lease = this._leases.get(channel)
if (!lease || lease.expiresAt < Date.now()) return null
return lease.holder
}
_onGossip (d) {
if (!d || d.type !== 'subscription-lease-sync') return
this._stats.gossipIn++
if (d.key !== undefined) {
if (d.value === null) this._store.delete(d.key)
else this._store.set(d.key, d.value)
_expireSweep () {
const now = Date.now()
for (const [ch, lease] of this._leases) {
if (lease.expiresAt < now) {
this._leases.delete(ch)
this.emit('expired', { channel: ch })
}
}
}
getStats () { return { ...this._stats, size: this._store.size, protocol: PROTOCOL } }
getStats () {
return { ...this._stats, active: this._leases.size, protocol: PROTOCOL }
}
async ready () {
if (this.swarm || !this.topic) return this
await attachGossip(this, { keyPair: this.keyPair, topic: this.topic, protocol: PROTOCOL, onmessage: (d) => this._onGossip(d) })
await initModuleSwarm(this, {
keyPair: this.keyPair,
topic: this.topic,
protocol: PROTOCOL,
onmessage: (data) => {
if (data && data.type === 'sub-lease' && data.lease) {
const cur = this._leases.get(data.lease.channel)
if (!cur || data.lease.expiresAt > cur.expiresAt) {
this._leases.set(data.lease.channel, data.lease)
}
this._stats.gossipIn++
} else if (data && data.type === 'sub-release') {
const cur = this._leases.get(data.channel)
if (cur && cur.holder === data.holder) this._leases.delete(data.channel)
this._stats.gossipIn++
}
}
})
if (this.enableBackgroundTimers && !this._timer) {
this._timer = setInterval(() => this._expireSweep(), 5000)
}
return this
}
async close () {
if (this._timer) {
clearInterval(this._timer)
this._timer = null
}
if (this.swarm) await this.swarm.destroy().catch(() => {})
this.swarm = null
this.emit('closed')
}
}
@@ -4,23 +4,44 @@ const { HyperP2PSubscriptionLease, PROTOCOL } = require('../index.js')
test('exports', (t) => {
t.ok(HyperP2PSubscriptionLease)
t.ok(PROTOCOL)
t.is(PROTOCOL, 'subscription-lease/v1')
})
test('basic operation', async (t) => {
const m = new HyperP2PSubscriptionLease()
m.put('k', 1); t.is(m.get('k'), 1)
await m.close()
test('acquire and holder', async (t) => {
const l = new HyperP2PSubscriptionLease({ leaseMs: 5000 })
const r = l.acquire('chan-a')
t.ok(r.ok)
t.is(l.holder('chan-a'), r.holder)
await l.release('chan-a')
await l.close()
})
test('conflict when held', async (t) => {
const l = new HyperP2PSubscriptionLease()
l._leases.set('c1', {
channel: 'c1',
holder: 'other-peer',
expiresAt: Date.now() + 60000
})
const r = l.acquire('c1')
t.not(r.ok)
await l.close()
})
test('validation', async (t) => {
const m = new HyperP2PSubscriptionLease()
try { m.put(null, 1) } catch (e) { t.ok(e) }
await m.close()
const l = new HyperP2PSubscriptionLease()
try {
l.acquire(null)
t.fail('expected throw')
} catch (e) {
t.ok(e instanceof Error)
}
await l.close()
})
test('getStats', async (t) => {
const m = new HyperP2PSubscriptionLease()
t.ok(m.getStats().protocol)
await m.close()
const l = new HyperP2PSubscriptionLease()
l.acquire('x')
t.ok(l.getStats().protocol)
await l.close()
})