@mark1russell7/otel-ts 0.8.4 → 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/README.md CHANGED
@@ -320,6 +320,28 @@ A shorter interval sends more samples. Each series then costs more in Mimir and
320
320
 
321
321
  By default, the exporter requests cumulative temporality. In its default configuration, Mimir rejects delta sums and delta histograms. Keep `metricsTemporality` at `"cumulative"` for Mimir and Prometheus.
322
322
 
323
+ ## Read metrics when you ask
324
+
325
+ The entry `/pull` reads the metrics of a process at the times that the program chooses. A lab run, for example, reads them after the start and after each pass. The entry starts no SDK and sends nothing.
326
+
327
+ ```ts
328
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
329
+ import { collectReadings, PullMetricReader } from "@mark1russell7/otel-ts/pull";
330
+
331
+ const reader = new PullMetricReader();
332
+ const provider = new MeterProvider({ readers: [reader] });
333
+ provider.getMeter("app").createCounter("requests").add(1, { route: "/a" });
334
+
335
+ const { readings, errors } = await collectReadings(reader, Date.now());
336
+ // readings: [{ series: 'requests{route="/a"}', at: "2026-11-24T12:00:00.000Z", value: 1 }]
337
+ ```
338
+
339
+ - `PullMetricReader` has no timer and no export. Give it to a `MeterProvider`, or to the SDK as a metric reader.
340
+ - The option `temporality` is `"cumulative"` (the default) or `"delta"`. With `"delta"`, counters and histograms give the change after the last collection.
341
+ - Each set of attributes is a series. With `{ attributes: "sum" }`, each metric is one series, the sum over its attributes.
342
+ - A histogram gives the series `<name>.count` and `<name>.sum`.
343
+ - `errors` is the count of the callbacks that failed in the collection.
344
+
323
345
  ## Page lifecycle
324
346
 
325
347
  The library follows the state of the page with [`page-lifecycle-tracker`](https://github.com/mark1russell7/page-lifecycle-tracker). It uses the tracker that the page shares (`getPageLifecycle()`), and it subscribes in the `export` phase:
package/dist/pull.d.ts ADDED
@@ -0,0 +1,70 @@
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 { MetricReader, type ResourceMetrics } from "@opentelemetry/sdk-metrics";
11
+ /**
12
+ * The temporality of a pull reader. With `"cumulative"`, each collection gives the totals from the start. With
13
+ * `"delta"`, the counters and the histograms give the change after the last collection, and the up-down counters
14
+ * and the gauges stay cumulative, as with the OTLP delta preference.
15
+ */
16
+ export type PullTemporality = "cumulative" | "delta";
17
+ /** The options of a {@link PullMetricReader}. */
18
+ export interface PullMetricReaderOptions {
19
+ /** The temporality of each collection. The default is `"cumulative"`. */
20
+ readonly temporality?: PullTemporality;
21
+ }
22
+ /**
23
+ * A metric reader that collects only when the program asks. It has no timer and no export, and its flush and its
24
+ * shutdown do nothing. Give it to a `MeterProvider` in `readers`, or to the SDK as a metric reader.
25
+ *
26
+ * ```ts no-run
27
+ * const reader = new PullMetricReader();
28
+ * const provider = new MeterProvider({ readers: [reader] });
29
+ * const { readings } = await collectReadings(reader, Date.now());
30
+ * ```
31
+ */
32
+ export declare class PullMetricReader extends MetricReader {
33
+ constructor(options?: PullMetricReaderOptions);
34
+ protected onForceFlush(): Promise<void>;
35
+ protected onShutdown(): Promise<void>;
36
+ }
37
+ /** One reading of a series: its key, the UTC time of the collection and its value. */
38
+ export interface MetricReading {
39
+ /**
40
+ * The key of the series. It is the name of the metric, then its attributes in the order of their keys, for example
41
+ * `http.requests{method="GET",status=200}`. With `attributes: "sum"`, it is the name only. A histogram gives the
42
+ * series `<name>.count` and `<name>.sum`.
43
+ */
44
+ readonly series: string;
45
+ /** The UTC time of the collection, in the ISO 8601 form. */
46
+ readonly at: string;
47
+ readonly value: number;
48
+ }
49
+ /** The options of {@link metricReadings}. */
50
+ export interface MetricReadingsOptions {
51
+ /**
52
+ * The series of a metric. With `"series"` (the default), each set of attributes is a series. With `"sum"`, the
53
+ * metric is one series: the sum of its data points over all attributes.
54
+ */
55
+ readonly attributes?: "series" | "sum";
56
+ }
57
+ /**
58
+ * This function gives the readings of one collection at the time `at`, in ms from the epoch. Each sum and each gauge
59
+ * gives one reading for each series. Each histogram gives its count and its sum. The readings are in the order of
60
+ * their series.
61
+ */
62
+ export declare function metricReadings(metrics: ResourceMetrics, at: number, options?: MetricReadingsOptions): MetricReading[];
63
+ /** The result of one collection: the readings, and the count of the errors of the callbacks. */
64
+ export interface ReadingsCollection {
65
+ readonly readings: readonly MetricReading[];
66
+ readonly errors: number;
67
+ }
68
+ /** This function collects the reader and gives the readings at the time `at`. Each failed callback adds 1 to `errors`. */
69
+ export declare function collectReadings(reader: MetricReader, at: number, options?: MetricReadingsOptions): Promise<ReadingsCollection>;
70
+ //# sourceMappingURL=pull.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull.d.ts","sourceRoot":"","sources":["../src/pull.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAIL,YAAY,EAEZ,KAAK,eAAe,EACrB,MAAM,4BAA4B,CAAC;AAEpC;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,YAAY,GAAG,OAAO,CAAC;AAErD,iDAAiD;AACjD,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,QAAQ,CAAC,WAAW,CAAC,EAAE,eAAe,CAAC;CACxC;AASD;;;;;;;;;GASG;AACH,qBAAa,gBAAiB,SAAQ,YAAY;gBACpC,OAAO,GAAE,uBAA4B;cAQ9B,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;cAI7B,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAG/C;AAED,sFAAsF;AACtF,MAAM,WAAW,aAAa;IAC5B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,6CAA6C;AAC7C,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,GAAG,KAAK,CAAC;CACxC;AA2BD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,eAAe,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,aAAa,EAAE,CAiBzH;AAED,gGAAgG;AAChG,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,QAAQ,EAAE,SAAS,aAAa,EAAE,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,0HAA0H;AAC1H,wBAAsB,eAAe,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAGxI"}
package/dist/pull.js ADDED
@@ -0,0 +1,93 @@
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 { AggregationTemporality, DataPointType, InstrumentType, MetricReader, } from "@opentelemetry/sdk-metrics";
11
+ /** The instruments that the delta preference reads as a change. The others stay cumulative. */
12
+ const DELTA_INSTRUMENTS = new Set([
13
+ InstrumentType.COUNTER,
14
+ InstrumentType.OBSERVABLE_COUNTER,
15
+ InstrumentType.HISTOGRAM,
16
+ ]);
17
+ /**
18
+ * A metric reader that collects only when the program asks. It has no timer and no export, and its flush and its
19
+ * shutdown do nothing. Give it to a `MeterProvider` in `readers`, or to the SDK as a metric reader.
20
+ *
21
+ * ```ts no-run
22
+ * const reader = new PullMetricReader();
23
+ * const provider = new MeterProvider({ readers: [reader] });
24
+ * const { readings } = await collectReadings(reader, Date.now());
25
+ * ```
26
+ */
27
+ export class PullMetricReader extends MetricReader {
28
+ constructor(options = {}) {
29
+ const delta = options.temporality === "delta";
30
+ super({
31
+ aggregationTemporalitySelector: (type) => delta && DELTA_INSTRUMENTS.has(type) ? AggregationTemporality.DELTA : AggregationTemporality.CUMULATIVE,
32
+ });
33
+ }
34
+ onForceFlush() {
35
+ return Promise.resolve();
36
+ }
37
+ onShutdown() {
38
+ return Promise.resolve();
39
+ }
40
+ }
41
+ /** This function gives the key of a series: the name, then the attributes in the order of their keys. */
42
+ const seriesKey = (name, attributes) => {
43
+ const keys = Object.keys(attributes)
44
+ .filter((key) => attributes[key] !== undefined)
45
+ .sort();
46
+ if (keys.length === 0)
47
+ return name;
48
+ return `${name}{${keys.map((key) => `${key}=${JSON.stringify(attributes[key])}`).join(",")}}`;
49
+ };
50
+ /** This function gives the named values of each data point of a metric, with the attributes of the point. */
51
+ const pointValues = (metric) => {
52
+ const name = metric.descriptor.name;
53
+ switch (metric.dataPointType) {
54
+ case DataPointType.SUM:
55
+ case DataPointType.GAUGE:
56
+ return metric.dataPoints.map((point) => ({ attributes: point.attributes, values: [[name, point.value]] }));
57
+ case DataPointType.HISTOGRAM:
58
+ case DataPointType.EXPONENTIAL_HISTOGRAM:
59
+ return metric.dataPoints.map((point) => ({
60
+ attributes: point.attributes,
61
+ values: [[`${name}.count`, point.value.count], ...(point.value.sum === undefined ? [] : [[`${name}.sum`, point.value.sum]])],
62
+ }));
63
+ }
64
+ };
65
+ /**
66
+ * This function gives the readings of one collection at the time `at`, in ms from the epoch. Each sum and each gauge
67
+ * gives one reading for each series. Each histogram gives its count and its sum. The readings are in the order of
68
+ * their series.
69
+ */
70
+ export function metricReadings(metrics, at, options = {}) {
71
+ const time = new Date(at).toISOString();
72
+ const sum = options.attributes === "sum";
73
+ const values = new Map();
74
+ for (const scope of metrics.scopeMetrics) {
75
+ for (const metric of scope.metrics) {
76
+ for (const point of pointValues(metric)) {
77
+ for (const [name, value] of point.values) {
78
+ const series = sum ? name : seriesKey(name, point.attributes);
79
+ values.set(series, (values.get(series) ?? 0) + value);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ return [...values.keys()]
85
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
86
+ .map((series) => ({ series, at: time, value: values.get(series) ?? 0 }));
87
+ }
88
+ /** This function collects the reader and gives the readings at the time `at`. Each failed callback adds 1 to `errors`. */
89
+ export async function collectReadings(reader, at, options = {}) {
90
+ const result = await reader.collect();
91
+ return { readings: metricReadings(result.resourceMetrics, at, options), errors: result.errors.length };
92
+ }
93
+ //# sourceMappingURL=pull.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull.js","sourceRoot":"","sources":["../src/pull.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,sBAAsB,EACtB,aAAa,EACb,cAAc,EACd,YAAY,GAGb,MAAM,4BAA4B,CAAC;AAepC,+FAA+F;AAC/F,MAAM,iBAAiB,GAAgC,IAAI,GAAG,CAAC;IAC7D,cAAc,CAAC,OAAO;IACtB,cAAc,CAAC,kBAAkB;IACjC,cAAc,CAAC,SAAS;CACzB,CAAC,CAAC;AAEH;;;;;;;;;GASG;AACH,MAAM,OAAO,gBAAiB,SAAQ,YAAY;IAChD,YAAY,UAAmC,EAAE;QAC/C,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,KAAK,OAAO,CAAC;QAC9C,KAAK,CAAC;YACJ,8BAA8B,EAAE,CAAC,IAAI,EAAE,EAAE,CACvC,KAAK,IAAI,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAC,sBAAsB,CAAC,UAAU;SAC1G,CAAC,CAAC;IACL,CAAC;IAEkB,YAAY;QAC7B,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3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D,OAAO,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;SACtB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAC5C,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;AAC7E,CAAC;AAQD,0HAA0H;AAC1H,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,MAAoB,EAAE,EAAU,EAAE,UAAiC,EAAE;IACzG,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IACtC,OAAO,EAAE,QAAQ,EAAE,cAAc,CAAC,MAAM,CAAC,eAAe,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;AACzG,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/otel-ts",
4
- "version": "0.8.4",
4
+ "version": "0.8.5",
5
5
  "description": "Frontend observability in one init() call — OpenTelemetry + Grafana Faro for any TypeScript web app",
6
6
  "license": "MIT",
7
7
  "author": "Mark Russell (https://github.com/mark1russell7)",
@@ -51,6 +51,10 @@
51
51
  "./lag": {
52
52
  "types": "./dist/lag.d.ts",
53
53
  "import": "./dist/lag.js"
54
+ },
55
+ "./pull": {
56
+ "types": "./dist/pull.d.ts",
57
+ "import": "./dist/pull.js"
54
58
  }
55
59
  },
56
60
  "files": [
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
+ }