From 5dbfa84fecca71d143e994310e11bbed2fa7bb65 Mon Sep 17 00:00:00 2001 From: HDegroote <75906619+HDegroote@users.noreply.github.com> Date: Mon, 2 Sep 2024 14:31:37 +0200 Subject: [PATCH] Add fromCorestore init --- index.js | 24 ++++++++++++++++++++++++ test.js | 35 ++++++++++++++++++++++++----------- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index 951fb49..cbd8abf 100644 --- a/index.js +++ b/index.js @@ -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 { diff --git a/test.js b/test.js index b2c4ca9..bd91b43 100644 --- a/test.js +++ b/test.js @@ -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) @@ -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' }) @@ -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 +}