unleash-server
Version:
Unleash is an enterprise ready feature flag service. It provides different strategies for handling feature flags.
86 lines • 3.37 kB
JavaScript
import { Gauge as PromGauge } from 'prom-client';
/**
* Creates a wrapped instance of prom-client's Gauge, overriding some of its methods for enhanced functionality and type-safety.
*
* @param options - The configuration options for the Gauge, as defined in prom-client's GaugeConfiguration.
* See prom-client documentation for detailed options: https://github.com/siimon/prom-client#gauge
* @returns An object containing the wrapped Gauge instance and custom methods.
*/
export const createGauge = (options) => {
const { ttlMs, fetchValue, ...gaugeOptions } = options;
// If fetchValue is provided, attach a TTL-cached collect. We preserve any existing collect
// by calling it afterwards.
if (fetchValue && typeof fetchValue === 'function') {
const ttl = typeof ttlMs === 'number' && Number.isFinite(ttlMs) ? ttlMs : 0;
const last = {
ts: 0,
value: null,
};
const originalCollect = gaugeOptions.collect;
// Assign a custom collect that obeys TTL caching semantics
gaugeOptions.collect = async function () {
const now = Date.now();
const fresh = ttl > 0 && now - last.ts < ttl && last.value !== null;
if (fresh) {
// Serve cached value
this.set(last.value);
}
else {
try {
const v = await fetchValue();
last.ts = now;
last.value = v;
if (v === null) {
// Indicate unknown; Prometheus won’t treat it as zero.
this.set(Number.NaN);
}
else {
this.set(v);
}
}
catch {
last.ts = now;
last.value = null;
this.set(Number.NaN);
}
}
// Call any original collect afterwards, allowing additional instrumentation if present
if (typeof originalCollect === 'function') {
try {
await originalCollect.call(this);
}
catch {
// ignore errors from original collect to avoid breaking the scrape
}
}
};
}
const gauge = new PromGauge(gaugeOptions);
/**
* Applies given labels to the gauge. Labels are key-value pairs.
* This method wraps the original Gauge's labels method for additional type-safety, requiring all configured labels to be specified.
*
* @param labels - An object where keys are label names and values are the label values.
* @returns The Gauge instance with the applied labels, allowing for method chaining.
*/
const labels = (labels) => gauge.labels(labels);
/**
* Resets the gauge value.
* Wraps the original Gauge's reset method.
*/
const reset = () => gauge.reset();
/**
* Sets the gauge to a specified value.
* Wraps the original Gauge's set method.
*
* @param value - The value to set the gauge to.
*/
const set = (value) => gauge.set(value);
return {
gauge,
labels,
reset,
set,
};
};
//# sourceMappingURL=createGauge.js.map