// Copyright The Prometheus Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Type definitions for @prometheus-io/client // Definitions by: Simon Nyberg http://twitter.com/siimon_nyberg export type Charset = 'utf-8'; export type PrometheusMIME = 'text/plain'; export type PrometheusMetricsVersion = '0.0.4'; export type OpenMetricsMIME = 'application/openmetrics-text'; export type OpenMetricsVersion = '1.0.0'; export type OpenMetricsContentType = `${OpenMetricsMIME}; version=${OpenMetricsVersion}; charset=${Charset}`; export type PrometheusContentType = `${PrometheusMIME}; version=${PrometheusMetricsVersion}; charset=${Charset}`; export type RegistryContentType = | PrometheusContentType | OpenMetricsContentType; /** * Container for all registered metrics */ export class Registry< BoundRegistryContentType extends RegistryContentType = RegistryContentType, > { /** * @param regContentType The content type of the registry */ constructor(regContentType?: RegistryContentType); /** * Get string representation for all metrics */ metrics(): Promise; /** * Remove all metrics from the registry */ clear(): void; /** * Reset all metrics in the registry */ resetMetrics(): void; /** * Register metric to register * @param metric Metric to add to register */ registerMetric(metric: Metric): void; /** * Get all metrics as objects */ getMetricsAsJSON(): Promise>[]>; /** * Get all metrics as objects * @param aggregator Filter by aggregator type */ getMetricsAsJSON( aggregator: string, ): Promise>[]>; /** * Get string representation for a metric * @param metric Metric to convert to a string */ getMetricsAsString(metric: Metric): Promise; /** * Get all metrics as objects */ getMetricsAsArray(): MetricObject[]; /** * Get all metrics as objects * @param aggregator Filter by aggregator type */ getMetricsAsArray(aggregator: string): MetricObject[]; /** * Remove a single metric * @param name The name of the metric to remove */ removeSingleMetric(name: string): void; /** * Get a single metric * @param name The name of the metric */ getSingleMetric(name: string): Metric | undefined; /** * Set static labels to every metric emitted by this registry * @param labels of name/value pairs: * { defaultLabel: "value", anotherLabel: "value 2" } */ setDefaultLabels(labels: object): void; /** * Get a string representation of a single metric by name * @param name The name of the metric */ getSingleMetricAsString(name: string): Promise; /** * Gets the Content-Type of the metrics for use in the response headers. */ readonly contentType: PrometheusContentType | OpenMetricsContentType; /** * Set the content type of a registry. Used to change between Prometheus and * OpenMetrics versions. * @param contentType The type of the registry */ setContentType( contentType: PrometheusContentType | OpenMetricsContentType, ): void; /** * Merge registers * @param registers The registers you want to merge together */ static merge(registers: Registry[]): Registry; /** * Creates a new Registry instance from an array of metrics that were * created by `registry.getMetricsAsJSON()`. Metrics are aggregated using * the method specified by their `aggregator` property, or by summation if * `aggregator` is undefined. * @param {Array} metricsArr Array of metrics, each of which created by * `registry.getMetricsAsJSON()`. * @returns {Registry} aggregated registry. */ static aggregate( metricsArr: Array, ): Registry; // TODO Promise? /** * HTTP Prometheus Content-Type for metrics response headers. */ static PROMETHEUS_CONTENT_TYPE: PrometheusContentType; /** * HTTP OpenMetrics Content-Type for metrics response headers. */ static OPENMETRICS_CONTENT_TYPE: OpenMetricsContentType; } export type Collector = () => void; /** * The register that contains all metrics */ export const register: Registry; /** * HTTP Content-Type for metrics response headers for the default registry, * defaults to Prometheus text format. */ export const contentType: RegistryContentType; /** * HTTP Prometheus Content-Type for metrics response headers. */ export const prometheusContentType: PrometheusContentType; /** * HTTP OpenMetrics Content-Type for metrics response headers. */ export const openMetricsContentType: OpenMetricsContentType; export class ClusterRegistry< T extends RegistryContentType, > extends Registry { /** * Gets aggregated metrics for all workers. * @returns {Promise} Promise that resolves with the aggregated * metrics. */ clusterMetrics(): Promise; /** * Sets the registry or registries to be aggregated. Call from workers to * use a registry/registries other than the default global registry. * @param {Array|Registry} regs Registry or registries to be * aggregated. * @returns {void} */ static setRegistries( regs: | Array< Registry | Registry > | Registry | Registry, ): void; } export class WorkerRegistry extends Registry { /** * Gets aggregated metrics for all workers. * @returns {Promise} Promise that resolves with the aggregated * metrics. */ workerMetrics(): Promise; /** * Orderly shutdown of the registry. * * This is meant to be called prior to`process.exit()` to facilitate accurate metrics. * * If this instance is the primary, then it will wait for any in-flight * metrics to finish collecting or time out prior to returning. * @returns {Promise} */ shutdown(): Promise; /** * Sets the registry or registries to be aggregated. Call from workers to * use a registry/registries other than the default global registry. * @param {Array|Registry} regs Registry or registries to be * aggregated. * @returns {void} */ static setRegistries( regs: | Array< Registry | Registry > | Registry | Registry, ): void; } /** * @deprecated */ export class AggregatorRegistry< T extends RegistryContentType, > extends Registry { /** * Gets aggregated metrics for all workers. * @returns {Promise} Promise that resolves with the aggregated * metrics. */ clusterMetrics(): Promise; /** * Orderly shutdown of the registry. * * This is meant to be called prior to`process.exit()` to facilitate accurate metrics. * * If this instance is the primary, then it will wait for any in-flight * metrics to finish collecting or time out prior to returning. * @returns {Promise} */ shutdown(): Promise; /** * Sets the registry or registries to be aggregated. Call from workers to * use a registry/registries other than the default global registry. * @param {Array|Registry} regs Registry or registries to be * aggregated. * @returns {void} */ static setRegistries( regs: | Array< Registry | Registry > | Registry | Registry, ): void; } type NoLabelNameType = never; /** * General metric type */ export type Metric = | Counter | Gauge | Summary | Histogram; /** * Aggregation methods, used for aggregating metrics in a Node.js cluster. */ export type Aggregator = 'omit' | 'sum' | 'first' | 'min' | 'max' | 'average'; /** * The metric type reported in metric objects, such as those returned by * `Registry#getMetricsAsJSON()`. Matches the runtime string values. */ export type MetricType = 'counter' | 'gauge' | 'histogram' | 'summary'; type CollectFunction = (this: T) => void | Promise; export interface MetricObject { name: string; help: string; type: MetricType; aggregator: Aggregator; collect: CollectFunction; } export interface MetricObjectWithValues< T extends MetricValue, > extends MetricObject { values: T[]; } export type MetricValue = { value: number; labels: LabelValues; }; export type MetricValueWithName = MetricValue & { metricName?: string; }; type LabelValues = T extends NoLabelNameType ? Partial> : Partial>; interface MetricConfiguration { name: string; help: string; labelNames?: T[] | readonly T[]; registers?: ( | Registry | Registry )[]; aggregator?: Aggregator; collect?: CollectFunction; enableExemplars?: boolean; } export interface CounterConfiguration< T extends string, > extends MetricConfiguration { collect?: CollectFunction>; } export interface IncreaseDataWithExemplar { value?: number; labels?: LabelValues; exemplarLabels?: LabelValues; } export interface ObserveDataWithExemplar { value: number; labels?: LabelValues; exemplarLabels?: LabelValues; } /** * A counter is a cumulative metric that represents a single numerical value that only ever goes up */ export class Counter { /** * @param configuration Configuration when creating a Counter metric. Name and Help is required. */ constructor(configuration: CounterConfiguration); /** * Increment for given labels * @param labels Object with label keys and values * @param value The number to increment with */ inc(labels: LabelValues, value?: number): void; /** * Increment with value * @param value The value to increment with */ inc(value?: number): void; /** * Increment with exemplars * @param incData Object with labels, value and exemplars for an increase */ inc(incData: IncreaseDataWithExemplar): void; /** * Get counter metric object */ get(): Promise>>; /** * Return the child for given labels * @param values Label values * @returns Configured counter with given labels */ labels(...values: string[]): Counter.Internal; /** * Return the child for given labels * @param labels Object with label keys and values * @returns Configured counter with given labels */ labels(labels: LabelValues): Counter.Internal; /** * Reset counter values */ reset(): void; /** * Remove metrics for the given label values * @param values Label values */ remove(...values: string[]): void; /** * Remove metrics for the given label values * @param labels Object with label keys and values */ remove(labels: LabelValues): void; } export namespace Counter { interface Internal { /** * Increment with value * @param value The value to increment with */ inc(value?: number): void; } } export interface GaugeConfiguration< T extends string, > extends MetricConfiguration { collect?: CollectFunction>; } /** * A gauge is a metric that represents a single numerical value that can arbitrarily go up and down. */ export class Gauge { /** * @param configuration Configuration when creating a Gauge metric. Name and Help is mandatory */ constructor(configuration: GaugeConfiguration); /** * Increment gauge for given labels * @param labels Object with label keys and values * @param value The value to increment with */ inc(labels: LabelValues, value?: number): void; /** * Increment gauge * @param value The value to increment with */ inc(value?: number): void; /** * Decrement gauge * @param labels Object with label keys and values * @param value Value to decrement with */ dec(labels: LabelValues, value?: number): void; /** * Decrement gauge * @param value The value to decrement with */ dec(value?: number): void; /** * Set gauge value for labels * @param labels Object with label keys and values * @param value The value to set */ set(labels: LabelValues, value: number): void; /** * Set gauge value * @param value The value to set */ set(value: number): void; /** * Get gauge metric object */ get(): Promise>>; /** * Set gauge value to current epoch time in seconds * @param labels Object with label keys and values */ setToCurrentTime(labels?: LabelValues): void; /** * Start a timer. Calling the returned function will set the gauge's value * to the observed duration in seconds. * @param labels Object with label keys and values * @returns Function to invoke when timer should be stopped. The value it * returns is the timed duration. */ startTimer(labels?: LabelValues): (labels?: LabelValues) => number; /** * Return the child for given labels * @param values Label values * @returns Configured gauge with given labels */ labels(...values: string[]): Gauge.Internal; /** * Return the child for given labels * @param labels Object with label keys and values * @returns Configured counter with given labels */ labels(labels: LabelValues): Gauge.Internal; /** * Reset gauge values */ reset(): void; /** * Remove metrics for the given label values * @param values Label values */ remove(...values: string[]): void; /** * Remove metrics for the given label values * @param labels Object with label keys and values */ remove(labels: LabelValues): void; } export namespace Gauge { interface Internal { /** * Increment gauge with value * @param value The value to increment with */ inc(value?: number): void; /** * Decrement with value * @param value The value to decrement with */ dec(value?: number): void; /** * Set gauges value * @param value The value to set */ set(value: number): void; /** * Set gauge value to current epoch time in ms */ setToCurrentTime(): void; /** * Start a timer. Calling the returned function will set the gauge's value * to the observed duration in seconds. * @returns Function to invoke when timer should be stopped. The value it * returns is the timed duration. */ startTimer(): (labels?: LabelValues) => number; } } export interface HistogramConfiguration< T extends string, > extends MetricConfiguration { buckets?: number[]; collect?: CollectFunction>; } /** * A histogram samples observations (usually things like request durations or response sizes) and counts them in configurable buckets */ export class Histogram { /** * @param configuration Configuration when creating the Histogram. Name and Help is mandatory */ constructor(configuration: HistogramConfiguration); /** * Observe value * @param value The value to observe */ observe(value: number): void; /** * Observe value for given labels * @param labels Object with label keys and values * @param value The value to observe */ observe(labels: LabelValues, value: number): void; /** * Observe with exemplars * @param observeData Object with labels, value and exemplars for an observation */ observe(observeData: ObserveDataWithExemplar): void; /** * Get histogram metric object */ get(): Promise>>; /** * Start a timer. Calling the returned function will observe the duration in * seconds in the histogram. * @param labels Object with label keys and values * @returns Function to invoke when timer should be stopped. The value it * returns is the timed duration. */ startTimer(labels?: LabelValues): (labels?: LabelValues) => number; /** * Start a timer with exemplar. Calling the returned function will observe the duration in * seconds in the histogram. * @param labels Object with label keys and values * @param exemplarLabels Object with label keys and values for exemplars * @returns Function to invoke when timer should be stopped. The value it * returns is the timed duration. */ startTimer( labels?: LabelValues, exemplarLabels?: LabelValues, ): (labels?: LabelValues, exemplarLabels?: LabelValues) => number; /** * Reset histogram values */ reset(): void; /** * Initialize the metrics for the given combination of labels to zero */ zero(labels: LabelValues): void; /** * Return the child for given labels * @param values Label values * @returns Configured histogram with given labels */ labels(...values: string[]): Histogram.Internal; /** * Return the child for given labels * @param labels Object with label keys and values * @returns Configured counter with given labels */ labels(labels: LabelValues): Histogram.Internal; /** * Remove metrics for the given label values * @param values Label values */ remove(...values: string[]): void; /** * Remove metrics for the given label values * @param labels Object with label keys and values */ remove(labels: LabelValues): void; } export namespace Histogram { interface Internal { /** * Observe value * @param value The value to observe */ observe(value: number): void; /** * Start a timer. Calling the returned function will observe the * duration in seconds in the histogram. * @returns Function to invoke when timer should be stopped. The value it * returns is the timed duration. */ startTimer(): (labels?: LabelValues) => void; } interface Config { /** * Buckets used in the histogram */ buckets?: number[]; } } export interface SummaryConfiguration< T extends string, > extends MetricConfiguration { percentiles?: number[]; maxAgeSeconds?: number; ageBuckets?: number; pruneAgedBuckets?: boolean; compressCount?: number; collect?: CollectFunction>; } /** * A summary samples observations */ export class Summary { /** * @param configuration Configuration when creating Summary metric. Name and Help is mandatory */ constructor(configuration: SummaryConfiguration); /** * Observe value in summary * @param value The value to observe */ observe(value: number): void; /** * Observe value for given labels * @param labels Object with label keys and values * @param value Value to observe */ observe(labels: LabelValues, value: number): void; /** * Get summary metric object */ get(): Promise>>; /** * Start a timer. Calling the returned function will observe the duration in * seconds in the summary. * @param labels Object with label keys and values * @returns Function to invoke when timer should be stopped */ startTimer(labels?: LabelValues): (labels?: LabelValues) => number; /** * Reset all values in the summary */ reset(): void; /** * Return the child for given labels * @param values Label values * @returns Configured summary with given labels */ labels(...values: string[]): Summary.Internal; /** * Return the child for given labels * @param labels Object with label keys and values * @returns Configured counter with given labels */ labels(labels: LabelValues): Summary.Internal; /** * Remove metrics for the given label values * @param values Label values */ remove(...values: string[]): void; /** * Remove metrics for the given label values * @param labels Object with label keys and values */ remove(labels: LabelValues): void; } export namespace Summary { interface Internal { /** * Observe value in summary * @param value The value to observe */ observe(value: number): void; /** * Start a timer. Calling the returned function will observe the * duration in seconds in the summary. * @returns Function to invoke when timer should be stopped. The value it * returns is the timed duration. */ startTimer(): (labels?: LabelValues) => number; } interface Config { /** * Configurable percentiles, values should never be greater than 1 */ percentiles?: number[]; } } /** * Push metrics to a Pushgateway */ export class Pushgateway { /** * @param url Complete url to the Pushgateway. If port is needed append url with :port * @param options Options * @param registry Registry */ constructor(url: string, registry: Registry); constructor( url: string, options?: Pushgateway.Options | null, registry?: Registry, ); /** * Add metric and overwrite old ones * @param params Push parameters */ pushAdd( params: Pushgateway.Parameters, ): Promise<{ resp?: unknown; body?: unknown }>; /** * Overwrite all metric (using PUT to Pushgateway) * @param params Push parameters */ push( params: Pushgateway.Parameters, ): Promise<{ resp?: unknown; body?: unknown }>; /** * Delete all metrics for jobName * @param params Push parameters */ delete( params: Pushgateway.Parameters, ): Promise<{ resp?: unknown; body?: unknown }>; } export namespace Pushgateway { interface Options { requireJobName?: boolean; [key: string]: unknown; } interface Parameters { /** * Jobname that is pushing the metric */ jobName: string; /** * Label sets used in the url when making a request to the Pushgateway, */ groupings?: { [key: string]: string; }; } } /** * Create an array with equal spacing between the elements. * @param start The first value in the array * @param width The spacing between the elements * @param count The number of items in array * @returns An array with the requested number of elements */ export function linearBuckets( start: number, width: number, count: number, ): number[]; /** * Create an array that grows exponentially. * @param start The first value in the array * @param factor The exponential factor * @param count The number of items in array * @returns An array with the requested number of elements */ export function exponentialBuckets( start: number, factor: number, count: number, ): number[]; export interface DefaultMetricsCollectorConfiguration< T extends RegistryContentType, > { register?: Registry; prefix?: string; gcDurationBuckets?: number[]; eventLoopMonitoringPrecision?: number; eventLoopUtilizationTimeout?: number; eventLoopUtilizationBuckets?: number[]; eventLoopUtilizationPercentiles?: number[]; eventLoopUtilizationAgeBuckets?: number; eventLoopUtilizationMaxAgeSeconds?: number; labels?: object; } export const collectDefaultMetrics: { /** * Configure default metrics * @param config Configuration object for default metrics collector */ ( config?: DefaultMetricsCollectorConfiguration, ): void; /** All available default metrics */ metricsList: string[]; }; /** * Validate a metric name. * @param name The name to validate * @returns True if the metric name is valid, false if not */ export function validateMetricName(name: string): boolean;