@libp2p/interface-mocks
Version:
Mock implementations of several libp2p interfaces
115 lines • 3.23 kB
JavaScript
class DefaultMetric {
value = 0;
update(value) {
this.value = value;
}
increment(value = 1) {
this.value += value;
}
decrement(value = 1) {
this.value -= value;
}
reset() {
this.value = 0;
}
timer() {
const start = Date.now();
return () => {
this.value = Date.now() - start;
};
}
}
class DefaultGroupMetric {
values = {};
update(values) {
Object.entries(values).forEach(([key, value]) => {
this.values[key] = value;
});
}
increment(values) {
Object.entries(values).forEach(([key, value]) => {
this.values[key] = this.values[key] ?? 0;
const inc = typeof value === 'number' ? value : 1;
this.values[key] += Number(inc);
});
}
decrement(values) {
Object.entries(values).forEach(([key, value]) => {
this.values[key] = this.values[key] ?? 0;
const dec = typeof value === 'number' ? value : 1;
this.values[key] -= Number(dec);
});
}
reset() {
this.values = {};
}
timer(key) {
const start = Date.now();
return () => {
this.values[key] = Date.now() - start;
};
}
}
class MockMetrics {
metrics = new Map();
trackMultiaddrConnection(maConn) {
}
trackProtocolStream(stream, connection) {
}
registerMetric(name, opts) {
if (name == null ?? name.trim() === '') {
throw new Error('Metric name is required');
}
if (opts?.calculate != null) {
// calculated metric
this.metrics.set(name, opts.calculate);
return;
}
const metric = new DefaultMetric();
this.metrics.set(name, metric);
return metric;
}
registerCounter(name, opts) {
if (name == null ?? name.trim() === '') {
throw new Error('Metric name is required');
}
if (opts?.calculate != null) {
// calculated metric
this.metrics.set(name, opts.calculate);
return;
}
const metric = new DefaultMetric();
this.metrics.set(name, metric);
return metric;
}
registerMetricGroup(name, opts) {
if (name == null ?? name.trim() === '') {
throw new Error('Metric name is required');
}
if (opts?.calculate != null) {
// calculated metric
this.metrics.set(name, opts.calculate);
return;
}
const metric = new DefaultGroupMetric();
this.metrics.set(name, metric);
return metric;
}
registerCounterGroup(name, opts) {
if (name == null ?? name.trim() === '') {
throw new Error('Metric name is required');
}
if (opts?.calculate != null) {
// calculated metric
this.metrics.set(name, opts.calculate);
return;
}
const metric = new DefaultGroupMetric();
this.metrics.set(name, metric);
return metric;
}
}
export function mockMetrics() {
return () => new MockMetrics();
}
//# sourceMappingURL=metrics.js.map