Skip to content

Commit

Permalink
Use a map to store hypercores
Browse files Browse the repository at this point in the history
  • Loading branch information
HDegroote committed Sep 2, 2024
1 parent 7f37735 commit 2734287
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
16 changes: 13 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const b4a = require('b4a')

class HypercoreStats {
constructor ({ cacheExpiryMs = 5000 } = {}) {
this.cores = []
this.cores = new Map()
this.cacheExpiryMs = cacheExpiryMs

// DEVNOTE: We calculate the stats all at once to avoid iterating over
Expand All @@ -20,7 +22,15 @@ class HypercoreStats {
}

addCore (core) {
this.cores.push(core)
if (!core.key) {
throw new Error('Can only add a core after its key is set (await ready)')
}

// Note: if a core with that key was already added,
// it gets overwritten
// DEVNOTE: this assumes we do not add any state to the hypercores
// (so no event handlers)
this.cores.set(b4a.from(core.key, 'hex'), core)
}

get totalCores () {
Expand Down Expand Up @@ -129,7 +139,7 @@ class HypercoreStats {
return this._cachedStats
}

this._cachedStats = new HypercoreStatsSnapshot(this.cores)
this._cachedStats = new HypercoreStatsSnapshot([...this.cores.values()])
this._lastStatsCalcTime = Date.now()
return this._cachedStats
}
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@
"corestore": "^6.18.4",
"hypercore": "^10.37.19",
"prom-client": "^15.1.3",
"random-access-memory": "^6.2.1",
"standard": "^17.1.0"
},
"dependencies": {
"random-access-memory": "^6.2.1"
"b4a": "^1.6.6"
}
}
3 changes: 3 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ test('Can register and get prometheus metrics', async (t) => {
const store = new Corestore(RAM)
const core = store.get({ name: 'core' })
const core2 = store.get({ name: 'core2' })
await core.ready()
await core2.ready()

const stats = new HypercoreStats()
stats.registerPrometheusMetrics(promClient)
Expand Down Expand Up @@ -112,6 +114,7 @@ function getMetricValue (lines, name) {
test('Cache-expiry logic', async (t) => {
const store = new Corestore(RAM)
const core = store.get({ name: 'core' })
await core.ready()

const stats = new HypercoreStats({ cacheExpiryMs: 1000 })
stats.registerPrometheusMetrics(promClient)
Expand Down

0 comments on commit 2734287

Please sign in to comment.