Updates
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
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 = 'credit-ledger/v1'
|
||||
|
||||
@@ -7,18 +9,51 @@ class HyperP2PCreditLedger extends EventEmitter {
|
||||
constructor (opts = {}) {
|
||||
super()
|
||||
this.topic = opts.topic || null
|
||||
this._stats = { created: 0, errors: 0 }
|
||||
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
|
||||
this._store = new Map()
|
||||
this._stats = { ops: 0, gossipIn: 0, gossipOut: 0 }
|
||||
this.swarm = null
|
||||
}
|
||||
|
||||
getStats () {
|
||||
return { ...this._stats, protocol: PROTOCOL, tier: 'scaffold' }
|
||||
put (key, value) {
|
||||
assertNonEmpty(key, 'key')
|
||||
this._store.set(key, value)
|
||||
this._stats.ops++
|
||||
sendGossip(this, { type: 'credit-ledger-sync', key, value })
|
||||
this.emit('update', { key, value })
|
||||
return true
|
||||
}
|
||||
|
||||
async ready () { return true }
|
||||
get (key) { return this._store.get(key) }
|
||||
|
||||
_notImplemented (method) {
|
||||
this._stats.errors++
|
||||
throw new Error(`not implemented: scaffold (${method})`)
|
||||
delete (key) {
|
||||
const ok = this._store.delete(key)
|
||||
if (ok) sendGossip(this, { type: 'credit-ledger-sync', key, value: null })
|
||||
return ok
|
||||
}
|
||||
|
||||
entries () { return [...this._store.entries()] }
|
||||
|
||||
_onGossip (d) {
|
||||
if (!d || d.type !== 'credit-ledger-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)
|
||||
}
|
||||
}
|
||||
|
||||
getStats () { return { ...this._stats, size: this._store.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) })
|
||||
return this
|
||||
}
|
||||
|
||||
async close () {
|
||||
if (this.swarm) await this.swarm.destroy().catch(() => {})
|
||||
this.swarm = null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user