@mark1russell7/otel-ts 0.8.3 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/pull.ts ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The entry `/pull`: the metrics of a process, read when the program asks. A {@link PullMetricReader} has no timer
3
+ * and no export. A program collects it at the times that it chooses, for example after the start and after each pass
4
+ * of a lab run, and {@link metricReadings} gives the value of each series at that time.
5
+ *
6
+ * The entry needs only `@opentelemetry/sdk-metrics`. It starts no SDK and sends nothing.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import {
11
+ AggregationTemporality,
12
+ DataPointType,
13
+ InstrumentType,
14
+ MetricReader,
15
+ type MetricData,
16
+ type ResourceMetrics,
17
+ } from "@opentelemetry/sdk-metrics";
18
+
19
+ /**
20
+ * The temporality of a pull reader. With `"cumulative"`, each collection gives the totals from the start. With
21
+ * `"delta"`, the counters and the histograms give the change after the last collection, and the up-down counters
22
+ * and the gauges stay cumulative, as with the OTLP delta preference.
23
+ */
24
+ export type PullTemporality = "cumulative" | "delta";
25
+
26
+ /** The options of a {@link PullMetricReader}. */
27
+ export interface PullMetricReaderOptions {
28
+ /** The temporality of each collection. The default is `"cumulative"`. */
29
+ readonly temporality?: PullTemporality;
30
+ }
31
+
32
+ /** The instruments that the delta preference reads as a change. The others stay cumulative. */
33
+ const DELTA_INSTRUMENTS: ReadonlySet<InstrumentType> = new Set([
34
+ InstrumentType.COUNTER,
35
+ InstrumentType.OBSERVABLE_COUNTER,
36
+ InstrumentType.HISTOGRAM,
37
+ ]);
38
+
39
+ /**
40
+ * A metric reader that collects only when the program asks. It has no timer and no export, and its flush and its
41
+ * shutdown do nothing. Give it to a `MeterProvider` in `readers`, or to the SDK as a metric reader.
42
+ *
43
+ * ```ts no-run
44
+ * const reader = new PullMetricReader();
45
+ * const provider = new MeterProvider({ readers: [reader] });
46
+ * const { readings } = await collectReadings(reader, Date.now());
47
+ * ```
48
+ */
49
+ export class PullMetricReader extends MetricReader {
50
+ constructor(options: PullMetricReaderOptions = {}) {
51
+ const delta = options.temporality === "delta";
52
+ super({
53
+ aggregationTemporalitySelector: (type) =>
54
+ delta && DELTA_INSTRUMENTS.has(type) ? AggregationTemporality.DELTA : AggregationTemporality.CUMULATIVE,
55
+ });
56
+ }
57
+
58
+ protected override onForceFlush(): Promise<void> {
59
+ return Promise.resolve();
60
+ }
61
+
62
+ protected override onShutdown(): Promise<void> {
63
+ return Promise.resolve();
64
+ }
65
+ }
66
+
67
+ /** One reading of a series: its key, the UTC time of the collection and its value. */
68
+ export interface MetricReading {
69
+ /**
70
+ * The key of the series. It is the name of the metric, then its attributes in the order of their keys, for example
71
+ * `http.requests{method="GET",status=200}`. With `attributes: "sum"`, it is the name only. A histogram gives the
72
+ * series `<name>.count` and `<name>.sum`.
73
+ */
74
+ readonly series: string;
75
+ /** The UTC time of the collection, in the ISO 8601 form. */
76
+ readonly at: string;
77
+ readonly value: number;
78
+ }
79
+
80
+ /** The options of {@link metricReadings}. */
81
+ export interface MetricReadingsOptions {
82
+ /**
83
+ * The series of a metric. With `"series"` (the default), each set of attributes is a series. With `"sum"`, the
84
+ * metric is one series: the sum of its data points over all attributes.
85
+ */
86
+ readonly attributes?: "series" | "sum";
87
+ }
88
+
89
+ /** This function gives the key of a series: the name, then the attributes in the order of their keys. */
90
+ const seriesKey = (name: string, attributes: Readonly<Record<string, unknown>>): string => {
91
+ const keys = Object.keys(attributes)
92
+ .filter((key) => attributes[key] !== undefined)
93
+ .sort();
94
+ if (keys.length === 0) return name;
95
+ return `${name}{${keys.map((key) => `${key}=${JSON.stringify(attributes[key])}`).join(",")}}`;
96
+ };
97
+
98
+ /** This function gives the named values of each data point of a metric, with the attributes of the point. */
99
+ const pointValues = (metric: MetricData): { attributes: Readonly<Record<string, unknown>>; values: [string, number][] }[] => {
100
+ const name = metric.descriptor.name;
101
+ switch (metric.dataPointType) {
102
+ case DataPointType.SUM:
103
+ case DataPointType.GAUGE:
104
+ return metric.dataPoints.map((point) => ({ attributes: point.attributes, values: [[name, point.value]] }));
105
+ case DataPointType.HISTOGRAM:
106
+ case DataPointType.EXPONENTIAL_HISTOGRAM:
107
+ return metric.dataPoints.map((point) => ({
108
+ attributes: point.attributes,
109
+ values: [[`${name}.count`, point.value.count], ...(point.value.sum === undefined ? [] : ([[`${name}.sum`, point.value.sum]] as [string, number][]))],
110
+ }));
111
+ }
112
+ };
113
+
114
+ /**
115
+ * This function gives the readings of one collection at the time `at`, in ms from the epoch. Each sum and each gauge
116
+ * gives one reading for each series. Each histogram gives its count and its sum. The readings are in the order of
117
+ * their series.
118
+ */
119
+ export function metricReadings(metrics: ResourceMetrics, at: number, options: MetricReadingsOptions = {}): MetricReading[] {
120
+ const time = new Date(at).toISOString();
121
+ const sum = options.attributes === "sum";
122
+ const values = new Map<string, number>();
123
+ for (const scope of metrics.scopeMetrics) {
124
+ for (const metric of scope.metrics) {
125
+ for (const point of pointValues(metric)) {
126
+ for (const [name, value] of point.values) {
127
+ const series = sum ? name : seriesKey(name, point.attributes);
128
+ values.set(series, (values.get(series) ?? 0) + value);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return [...values.keys()]
134
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
135
+ .map((series) => ({ series, at: time, value: values.get(series) ?? 0 }));
136
+ }
137
+
138
+ /** The result of one collection: the readings, and the count of the errors of the callbacks. */
139
+ export interface ReadingsCollection {
140
+ readonly readings: readonly MetricReading[];
141
+ readonly errors: number;
142
+ }
143
+
144
+ /** This function collects the reader and gives the readings at the time `at`. Each failed callback adds 1 to `errors`. */
145
+ export async function collectReadings(reader: MetricReader, at: number, options: MetricReadingsOptions = {}): Promise<ReadingsCollection> {
146
+ const result = await reader.collect();
147
+ return { readings: metricReadings(result.resourceMetrics, at, options), errors: result.errors.length };
148
+ }