Skip to content

Commit

Permalink
Add fromCorestore init
Browse files Browse the repository at this point in the history
  • Loading branch information
HDegroote committed Sep 2, 2024
1 parent 2734287 commit 5dbfa84
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 11 deletions.
24 changes: 24 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,30 @@ class HypercoreStats {
}
})
}

static fromCorestore (store) {
const hypercoreStats = new this()
store.on('core-open', core => {
hypercoreStats.addCore(core)
})

// TODO: we never delete cores when they close
// since we care mostly about the history (sum) of metrics.
// A proper solution is to detect when a core closes,
// sum each metric to a separate variable,
// and then deleting the hypercore

// Add already-opened cores
for (const core of [...store.cores.values()]) {
// DEVNOTE: core-open is emitted after a core is ready
// so if not yet opened, we will process it then
if (core.opened === true) {
this.metrics.addCore(core)
}
}

return hypercoreStats
}
}

class HypercoreStatsSnapshot {
Expand Down
35 changes: 24 additions & 11 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const RAM = require('random-access-memory')
const HypercoreStats = require('.')
const promClient = require('prom-client')

const DEBUG = true
const DEBUG = false

test('Can register and get prometheus metrics', async (t) => {
const store = new Corestore(RAM)
Expand Down Expand Up @@ -101,16 +101,6 @@ test('Can register and get prometheus metrics', async (t) => {
}
})

function getMetricValue (lines, name) {
const match = lines.find((l) => l.startsWith(`${name} `))
if (!match) throw new Error(`No match for ${name}`)

const value = parseInt(match.split(' ')[1])
if (DEBUG) console.log(name, '->', value)

return value
}

test('Cache-expiry logic', async (t) => {
const store = new Corestore(RAM)
const core = store.get({ name: 'core' })
Expand Down Expand Up @@ -146,3 +136,26 @@ test('Cache-expiry logic', async (t) => {
t.is(getMetricValue(lines, 'hypercore_total_cores'), 1, 'cache busted after expire time')
}
})

test('fromCorestore init', async (t) => {
const store = new Corestore(RAM)
const core = store.get({ name: 'core' })

const stats = HypercoreStats.fromCorestore(store)
await core.ready()
t.is(stats.cores.size, 1, 'init core added')

const core2 = store.get({ name: 'core2' })
await core2.ready()
t.is(stats.cores.size, 2, 'new core added')
})

function getMetricValue (lines, name) {
const match = lines.find((l) => l.startsWith(`${name} `))
if (!match) throw new Error(`No match for ${name}`)

const value = parseInt(match.split(' ')[1])
if (DEBUG) console.log(name, '->', value)

return value
}

0 comments on commit 5dbfa84

Please sign in to comment.