@lodestar/beacon-node
Version:
A Typescript implementation of the beacon chain
93 lines • 3.33 kB
JavaScript
import { JsonType } from "./types.js";
/**
* Static property that can be used to define hard-coded values
*/
export class StaticProperty {
definition;
constructor(definition) {
this.definition = definition;
}
getRecord() {
return { key: this.definition.jsonKey, value: this.definition.value };
}
}
/**
* Dynamic property that can be used to get value from a provider function
*/
export class DynamicProperty {
definition;
constructor(definition) {
this.definition = definition;
}
getRecord() {
return { key: this.definition.jsonKey, value: this.definition.provider() };
}
}
/**
* Metric property that can be used to get value from an existing prometheus metric
*/
export class MetricProperty {
definition;
cachedValue;
constructor(definition) {
this.definition = definition;
}
async getRecord(register) {
if (this.cachedValue != null) {
return { key: this.definition.jsonKey, value: this.cachedValue };
}
const metric = register.getSingleMetric(this.definition.metricName);
if (metric) {
const metricObject = await metric.get();
const metricValue = this.extractMetricValue(metricObject);
if (metricValue != null) {
const formattedValue = this.formatMetricValue(metricValue);
const typedValue = this.convertMetricValue(formattedValue);
if (this.definition.cacheResult) {
this.cachedValue = typedValue;
}
return { key: this.definition.jsonKey, value: typedValue };
}
}
return { key: this.definition.jsonKey, value: this.definition.defaultValue };
}
extractMetricValue(metricObject) {
const { withLabel, fromLabel } = this.definition;
if (withLabel) {
// get value from metric with specific label, e.g. protocol="global received"
return metricObject.values.find((v) => v.labels[withLabel.name] === withLabel.value)?.value;
}
if (fromLabel) {
// get value from label, e.g. lodestar_version{version="v1.3.0/2d0938e"} => v1.3.0/2d0938e
return metricObject.values[0].labels[fromLabel];
}
// metric value e.g. beacon_head_slot 5603174 => 5603174
return metricObject.values[0].value;
}
formatMetricValue(value) {
if (!this.definition.formatter) {
return value;
}
return this.definition.formatter(value);
}
convertMetricValue(value) {
if (typeof value === "number") {
switch (this.definition.jsonType) {
case JsonType.String:
return value.toString();
case JsonType.Number:
return Math.round(value);
case JsonType.Boolean:
if (this.definition.rangeValue != null) {
return value === this.definition.rangeValue;
}
if (this.definition.threshold != null) {
return value >= this.definition.threshold;
}
return value > 0;
}
}
return value;
}
}
//# sourceMappingURL=properties.js.map