54 lines
1.7 KiB
JavaScript
54 lines
1.7 KiB
JavaScript
require('bare-process/global')
|
|
const EventEmitter = require('bare-events')
|
|
const { assertNonEmpty } = require('../../_shared/lib/errors.js')
|
|
const { attachGossip, sendGossip } = require('../../_shared/storage-gossip-base.js')
|
|
|
|
const PROTOCOL = 'sla-budget/v1'
|
|
|
|
class HyperP2PSlaBudget extends EventEmitter {
|
|
constructor (opts = {}) {
|
|
super()
|
|
this.topic = opts.topic || null
|
|
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
|
|
this._samples = []
|
|
this._stats = { samples: 0, gossipIn: 0, gossipOut: 0 }
|
|
this.swarm = null
|
|
}
|
|
|
|
record (value) {
|
|
if (typeof value !== 'number') throw new Error('value must be a number')
|
|
this._samples.push({ value, at: Date.now() })
|
|
this._stats.samples++
|
|
sendGossip(this, { type: 'sla-budget-sync', value })
|
|
return true
|
|
}
|
|
|
|
summarize () {
|
|
if (!this._samples.length) return null
|
|
const vals = this._samples.map((s) => s.value)
|
|
const sum = vals.reduce((a, b) => a + b, 0)
|
|
return { count: vals.length, min: Math.min(...vals), max: Math.max(...vals), avg: sum / vals.length }
|
|
}
|
|
|
|
_onGossip (d) {
|
|
if (!d || d.type !== 'sla-budget-sync') return
|
|
this._stats.gossipIn++
|
|
if (typeof d.value === 'number') this._samples.push({ value: d.value, at: Date.now() })
|
|
}
|
|
|
|
getStats () { return { ...this._stats, 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) })
|
|
return this
|
|
}
|
|
|
|
async close () {
|
|
if (this.swarm) await this.swarm.destroy().catch(() => {})
|
|
this.swarm = null
|
|
}
|
|
}
|
|
|
|
module.exports = { HyperP2PSlaBudget, PROTOCOL }
|