@twin.org/telemetry-connector-opentelemetry 0.0.3-next.10
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 +21 -0
- package/dist/es/index.js +9 -0
- package/dist/es/index.js.map +1 -0
- package/dist/es/models/IOpenTelemetryPrometheusReaderConfig.js +2 -0
- package/dist/es/models/IOpenTelemetryPrometheusReaderConfig.js.map +1 -0
- package/dist/es/models/IOpenTelemetryReaderConfig.js +3 -0
- package/dist/es/models/IOpenTelemetryReaderConfig.js.map +1 -0
- package/dist/es/models/IOpenTelemetryTelemetryConnectorConfig.js +2 -0
- package/dist/es/models/IOpenTelemetryTelemetryConnectorConfig.js.map +1 -0
- package/dist/es/models/IOpenTelemetryTelemetryConnectorConstructorOptions.js +2 -0
- package/dist/es/models/IOpenTelemetryTelemetryConnectorConstructorOptions.js.map +1 -0
- package/dist/es/models/openTelemetryReaderTypes.js +13 -0
- package/dist/es/models/openTelemetryReaderTypes.js.map +1 -0
- package/dist/es/openTelemetryTelemetryConnector.js +307 -0
- package/dist/es/openTelemetryTelemetryConnector.js.map +1 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/models/IOpenTelemetryPrometheusReaderConfig.d.ts +31 -0
- package/dist/types/models/IOpenTelemetryReaderConfig.d.ts +6 -0
- package/dist/types/models/IOpenTelemetryTelemetryConnectorConfig.d.ts +24 -0
- package/dist/types/models/IOpenTelemetryTelemetryConnectorConstructorOptions.d.ts +27 -0
- package/dist/types/models/openTelemetryReaderTypes.d.ts +13 -0
- package/dist/types/openTelemetryTelemetryConnector.d.ts +122 -0
- package/docs/changelog.md +100 -0
- package/docs/examples.md +172 -0
- package/docs/reference/classes/OpenTelemetryTelemetryConnector.md +364 -0
- package/docs/reference/index.md +20 -0
- package/docs/reference/interfaces/IOpenTelemetryPrometheusReaderConfig.md +63 -0
- package/docs/reference/interfaces/IOpenTelemetryTelemetryConnectorConfig.md +45 -0
- package/docs/reference/interfaces/IOpenTelemetryTelemetryConnectorConstructorOptions.md +50 -0
- package/docs/reference/type-aliases/IOpenTelemetryReaderConfig.md +6 -0
- package/docs/reference/type-aliases/OpenTelemetryReaderTypes.md +5 -0
- package/docs/reference/variables/OpenTelemetryReaderTypes.md +13 -0
- package/locales/en.json +13 -0
- package/package.json +70 -0
package/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# TWIN Telemetry Connector OpenTelemetry
|
|
2
|
+
|
|
3
|
+
OpenTelemetry connector for pushing telemetry metrics to OTEL-compatible backends such as Prometheus and Grafana.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```shell
|
|
8
|
+
npm install @twin.org/telemetry-connector-opentelemetry
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
Usage of the APIs is shown in the examples [docs/examples.md](docs/examples.md)
|
|
14
|
+
|
|
15
|
+
## Reference
|
|
16
|
+
|
|
17
|
+
Detailed reference documentation for the API can be found in [docs/reference/index.md](docs/reference/index.md)
|
|
18
|
+
|
|
19
|
+
## Changelog
|
|
20
|
+
|
|
21
|
+
The changes between each version can be found in [docs/changelog.md](docs/changelog.md)
|
package/dist/es/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Copyright 2026 IOTA Stiftung.
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0.
|
|
3
|
+
export * from "./models/IOpenTelemetryPrometheusReaderConfig.js";
|
|
4
|
+
export * from "./models/IOpenTelemetryReaderConfig.js";
|
|
5
|
+
export * from "./models/IOpenTelemetryTelemetryConnectorConfig.js";
|
|
6
|
+
export * from "./models/IOpenTelemetryTelemetryConnectorConstructorOptions.js";
|
|
7
|
+
export * from "./models/openTelemetryReaderTypes.js";
|
|
8
|
+
export * from "./openTelemetryTelemetryConnector.js";
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,kDAAkD,CAAC;AACjE,cAAc,wCAAwC,CAAC;AACvD,cAAc,oDAAoD,CAAC;AACnE,cAAc,gEAAgE,CAAC;AAC/E,cAAc,sCAAsC,CAAC;AACrD,cAAc,sCAAsC,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./models/IOpenTelemetryPrometheusReaderConfig.js\";\nexport * from \"./models/IOpenTelemetryReaderConfig.js\";\nexport * from \"./models/IOpenTelemetryTelemetryConnectorConfig.js\";\nexport * from \"./models/IOpenTelemetryTelemetryConnectorConstructorOptions.js\";\nexport * from \"./models/openTelemetryReaderTypes.js\";\nexport * from \"./openTelemetryTelemetryConnector.js\";\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IOpenTelemetryPrometheusReaderConfig.js","sourceRoot":"","sources":["../../../src/models/IOpenTelemetryPrometheusReaderConfig.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { OpenTelemetryReaderTypes } from \"./openTelemetryReaderTypes.js\";\n\n/**\n * Configuration for a Prometheus scrape-endpoint reader.\n * The connector instantiates a PrometheusExporter from these options in start().\n */\nexport interface IOpenTelemetryPrometheusReaderConfig {\n\t/**\n\t * Type.\n\t */\n\ttype: typeof OpenTelemetryReaderTypes.Prometheus;\n\n\t/**\n\t * TCP port the Prometheus HTTP server listens on.\n\t * @default 9464\n\t */\n\tport?: number;\n\n\t/**\n\t * HTTP path that Prometheus scrapes.\n\t * @default /metrics\n\t */\n\tendpoint?: string;\n\n\t/**\n\t * Whether to start the built-in HTTP server automatically.\n\t * Set to false if you manage the server externally.\n\t * @default true\n\t */\n\tstartServer?: boolean;\n\n\t/**\n\t * Optional string prepended to every exported metric name.\n\t */\n\tprefix?: string;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IOpenTelemetryReaderConfig.js","sourceRoot":"","sources":["../../../src/models/IOpenTelemetryReaderConfig.ts"],"names":[],"mappings":";AASA,+EAA+E","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IOpenTelemetryPrometheusReaderConfig } from \"./IOpenTelemetryPrometheusReaderConfig.js\";\n\n/**\n * Discriminated union of all supported metric-reader configurations.\n * Add new members here when additional exporter types are implemented.\n */\nexport type IOpenTelemetryReaderConfig = IOpenTelemetryPrometheusReaderConfig;\n// Future: | IOpenTelemetryOtlpReaderConfig | IOpenTelemetryConsoleReaderConfig\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IOpenTelemetryTelemetryConnectorConfig.js","sourceRoot":"","sources":["../../../src/models/IOpenTelemetryTelemetryConnectorConfig.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IOpenTelemetryReaderConfig } from \"./IOpenTelemetryReaderConfig.js\";\n\n/**\n * The options for the OpenTelemetry telemetry connector constructor.\n */\nexport interface IOpenTelemetryTelemetryConnectorConfig {\n\t/**\n\t * The name of the OpenTelemetry meter used to create instruments.\n\t * @default twin-telemetry\n\t */\n\tmeterName?: string;\n\n\t/**\n\t * The version reported by the OpenTelemetry meter.\n\t * @default 1.0.0\n\t */\n\tmeterVersion?: string;\n\n\t/**\n\t * Named metric-reader configurations keyed by an arbitrary id.\n\t * Each entry's `type` field determines which exporter the connector instantiates\n\t * in start(). Omit or pass an empty object for a no-op provider (useful for tests).\n\t */\n\treaders?: { [id: string]: IOpenTelemetryReaderConfig };\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IOpenTelemetryTelemetryConnectorConstructorOptions.js","sourceRoot":"","sources":["../../../src/models/IOpenTelemetryTelemetryConnectorConstructorOptions.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IOpenTelemetryTelemetryConnectorConfig } from \"./IOpenTelemetryTelemetryConnectorConfig.js\";\n\n/**\n * The options for the OpenTelemetry telemetry connector constructor.\n */\nexport interface IOpenTelemetryTelemetryConnectorConstructorOptions {\n\t/**\n\t * The component type to use for logging inside the connector and the inner\n\t * entity-storage connector. When omitted logging is disabled.\n\t */\n\tloggingComponentType?: string;\n\n\t/**\n\t * The entity storage connector type to use for storing metric definitions.\n\t * Must be registered in `EntityStorageConnectorFactory` before calling `start()`.\n\t * @default telemetry-metric\n\t */\n\ttelemetryMetricStorageConnectorType?: string;\n\n\t/**\n\t * The entity storage connector type to use for storing metric values.\n\t * Must be registered in `EntityStorageConnectorFactory` before calling `start()`.\n\t * @default telemetry-metric-value\n\t */\n\ttelemetryMetricValueStorageConnectorType?: string;\n\n\t/**\n\t * The config for the telemetry connector.\n\t */\n\tconfig?: IOpenTelemetryTelemetryConnectorConfig;\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Copyright 2026 IOTA Stiftung.
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0.
|
|
3
|
+
/**
|
|
4
|
+
* The types of readers.
|
|
5
|
+
*/
|
|
6
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
7
|
+
export const OpenTelemetryReaderTypes = {
|
|
8
|
+
/**
|
|
9
|
+
* Prometheus.
|
|
10
|
+
*/
|
|
11
|
+
Prometheus: "prometheus"
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=openTelemetryReaderTypes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openTelemetryReaderTypes.js","sourceRoot":"","sources":["../../../src/models/openTelemetryReaderTypes.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AAEvC;;GAEG;AACH,gEAAgE;AAChE,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC;;OAEG;IACH,UAAU,EAAE,YAAY;CACf,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * The types of readers.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const OpenTelemetryReaderTypes = {\n\t/**\n\t * Prometheus.\n\t */\n\tPrometheus: \"prometheus\"\n} as const;\n\n/**\n * The types of readers.\n */\nexport type OpenTelemetryReaderTypes =\n\t(typeof OpenTelemetryReaderTypes)[keyof typeof OpenTelemetryReaderTypes];\n"]}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { MeterProvider } from "@opentelemetry/sdk-metrics";
|
|
2
|
+
import { AlreadyExistsError, BaseError, ComponentFactory, GeneralError, Is } from "@twin.org/core";
|
|
3
|
+
import { EntityStorageTelemetryConnector } from "@twin.org/telemetry-connector-entity-storage";
|
|
4
|
+
import { MetricCounterOperation, MetricType } from "@twin.org/telemetry-models";
|
|
5
|
+
/**
|
|
6
|
+
* Class for performing telemetry operations using OpenTelemetry instruments.
|
|
7
|
+
* Metric definitions and value history are persisted via an internal
|
|
8
|
+
* EntityStorageTelemetryConnector instance created at construction time.
|
|
9
|
+
* Call `start()` to initialise the MeterProvider and exporters; metrics can be
|
|
10
|
+
* created and queried before start() — OTEL forwarding is simply skipped until
|
|
11
|
+
* the MeterProvider is running.
|
|
12
|
+
*/
|
|
13
|
+
export class OpenTelemetryTelemetryConnector {
|
|
14
|
+
/**
|
|
15
|
+
* The namespace supported by the telemetry connector.
|
|
16
|
+
*/
|
|
17
|
+
static NAMESPACE = "opentelemetry";
|
|
18
|
+
/**
|
|
19
|
+
* Runtime name for the class.
|
|
20
|
+
*/
|
|
21
|
+
static CLASS_NAME = "OpenTelemetryTelemetryConnector";
|
|
22
|
+
/**
|
|
23
|
+
* Config options, stored so start() can initialise the MeterProvider.
|
|
24
|
+
* @internal
|
|
25
|
+
*/
|
|
26
|
+
_config;
|
|
27
|
+
/**
|
|
28
|
+
* Internal entity-storage connector that owns all metric metadata and value history.
|
|
29
|
+
* Created at construction time — fails fast if entity storage is not set up.
|
|
30
|
+
* @internal
|
|
31
|
+
*/
|
|
32
|
+
_inner;
|
|
33
|
+
/**
|
|
34
|
+
* Live OTEL instrument handles keyed by metric id, paired with the metric type
|
|
35
|
+
* so addMetricValue can dispatch without querying storage.
|
|
36
|
+
* These are runtime objects and cannot be persisted.
|
|
37
|
+
* @internal
|
|
38
|
+
*/
|
|
39
|
+
_instruments;
|
|
40
|
+
/**
|
|
41
|
+
* The MeterProvider that owns all instruments. Set by start(), cleared by stop().
|
|
42
|
+
* @internal
|
|
43
|
+
*/
|
|
44
|
+
_meterProvider;
|
|
45
|
+
/**
|
|
46
|
+
* The Meter used to create instruments. Set by start(), cleared by stop().
|
|
47
|
+
* @internal
|
|
48
|
+
*/
|
|
49
|
+
_meter;
|
|
50
|
+
/**
|
|
51
|
+
* Create a new instance of OpenTelemetryTelemetryConnector.
|
|
52
|
+
* Eagerly constructs the inner EntityStorageTelemetryConnector — if the required
|
|
53
|
+
* entity storage types are not registered this constructor will throw (fail fast).
|
|
54
|
+
* @param options The options for the connector.
|
|
55
|
+
*/
|
|
56
|
+
constructor(options) {
|
|
57
|
+
this._config = options?.config ?? {};
|
|
58
|
+
this._inner = new EntityStorageTelemetryConnector({
|
|
59
|
+
loggingComponentType: options?.loggingComponentType,
|
|
60
|
+
telemetryMetricStorageConnectorType: options?.telemetryMetricStorageConnectorType,
|
|
61
|
+
telemetryMetricValueStorageConnectorType: options?.telemetryMetricValueStorageConnectorType
|
|
62
|
+
});
|
|
63
|
+
this._instruments = new Map();
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Returns the class name of the component.
|
|
67
|
+
* @returns The class name of the component.
|
|
68
|
+
*/
|
|
69
|
+
className() {
|
|
70
|
+
return OpenTelemetryTelemetryConnector.CLASS_NAME;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Initialise the MeterProvider and configured exporters.
|
|
74
|
+
* @param nodeLoggingComponentType The node logging component type.
|
|
75
|
+
* @returns Nothing.
|
|
76
|
+
*/
|
|
77
|
+
async start(nodeLoggingComponentType) {
|
|
78
|
+
if (!Is.undefined(this._meterProvider)) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const readers = [];
|
|
82
|
+
for (const [, config] of Object.entries(this._config.readers ?? {})) {
|
|
83
|
+
if (config.type === "prometheus") {
|
|
84
|
+
// Dynamic import so @opentelemetry/exporter-prometheus is an optional peer dep;
|
|
85
|
+
// consumers only need to install it if they actually configure a Prometheus reader.
|
|
86
|
+
const { PrometheusExporter: prometheusExporterClass } = await import("@opentelemetry/exporter-prometheus");
|
|
87
|
+
readers.push(new prometheusExporterClass({
|
|
88
|
+
port: config.port,
|
|
89
|
+
endpoint: config.endpoint,
|
|
90
|
+
// PrometheusExporter uses preventServerStart (inverted); our config
|
|
91
|
+
// exposes the more intuitive startServer (defaults to true).
|
|
92
|
+
preventServerStart: !(config.startServer ?? true),
|
|
93
|
+
prefix: config.prefix
|
|
94
|
+
}));
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
throw new GeneralError(OpenTelemetryTelemetryConnector.CLASS_NAME, "unknownReaderType", {
|
|
98
|
+
type: config.type
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
this._meterProvider = new MeterProvider({ readers });
|
|
103
|
+
this._meter = this._meterProvider.getMeter(this._config.meterName ?? "twin-telemetry", this._config.meterVersion ?? "1.0.0");
|
|
104
|
+
const nodeLogging = ComponentFactory.getIfExists(nodeLoggingComponentType);
|
|
105
|
+
await nodeLogging?.log({
|
|
106
|
+
source: OpenTelemetryTelemetryConnector.CLASS_NAME,
|
|
107
|
+
message: "connectorStarted",
|
|
108
|
+
level: "info",
|
|
109
|
+
data: { readerCount: Object.keys(this._config.readers ?? {}).length }
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Shut down the MeterProvider and release resources.
|
|
114
|
+
* Calling stop() on a connector that has not been started is a no-op.
|
|
115
|
+
* @param nodeLoggingComponentType The node logging component type.
|
|
116
|
+
* @returns Nothing.
|
|
117
|
+
*/
|
|
118
|
+
async stop(nodeLoggingComponentType) {
|
|
119
|
+
if (!Is.undefined(this._meterProvider)) {
|
|
120
|
+
await this._meterProvider.shutdown();
|
|
121
|
+
this._meterProvider = undefined;
|
|
122
|
+
this._meter = undefined;
|
|
123
|
+
this._instruments.clear();
|
|
124
|
+
const nodeLogging = ComponentFactory.getIfExists(nodeLoggingComponentType);
|
|
125
|
+
await nodeLogging?.log({
|
|
126
|
+
source: OpenTelemetryTelemetryConnector.CLASS_NAME,
|
|
127
|
+
message: "connectorStopped",
|
|
128
|
+
level: "info",
|
|
129
|
+
data: {}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Create a new metric.
|
|
135
|
+
* The definition is always persisted via the inner entity-storage connector.
|
|
136
|
+
* If the MeterProvider is running the corresponding OTEL instrument is also registered.
|
|
137
|
+
* @param metric The metric details.
|
|
138
|
+
* @returns Nothing.
|
|
139
|
+
*/
|
|
140
|
+
async createMetric(metric) {
|
|
141
|
+
try {
|
|
142
|
+
await this._inner.createMetric(metric);
|
|
143
|
+
}
|
|
144
|
+
catch (err) {
|
|
145
|
+
// Entity storage performs all validation and throws AlreadyExistsError on duplicates.
|
|
146
|
+
// OTP doesn't care about duplicates and will create a new instrument instance on each call
|
|
147
|
+
// so we catch this error and ignore it to allow the OTEL instruments to be registered.
|
|
148
|
+
if (!BaseError.isErrorName(err, AlreadyExistsError.CLASS_NAME)) {
|
|
149
|
+
throw err;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// Register an OTEL instrument when the MeterProvider is running.
|
|
153
|
+
// This runs even when the metric already exists in storage so instruments
|
|
154
|
+
// survive process restarts (AlreadyExistsError path).
|
|
155
|
+
const meter = this._meter;
|
|
156
|
+
if (meter !== undefined && !this._instruments.has(metric.id)) {
|
|
157
|
+
const instrumentOptions = {
|
|
158
|
+
description: metric.description,
|
|
159
|
+
unit: metric.unit
|
|
160
|
+
};
|
|
161
|
+
let instrument;
|
|
162
|
+
if (metric.type === MetricType.Counter) {
|
|
163
|
+
instrument = meter.createCounter(metric.id, instrumentOptions);
|
|
164
|
+
}
|
|
165
|
+
else if (metric.type === MetricType.IncDecCounter) {
|
|
166
|
+
instrument = meter.createUpDownCounter(metric.id, instrumentOptions);
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
instrument = meter.createGauge(metric.id, instrumentOptions);
|
|
170
|
+
}
|
|
171
|
+
this._instruments.set(metric.id, { metricType: metric.type, instrument });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Get the metric details and its most recent value.
|
|
176
|
+
* @param id The metric id.
|
|
177
|
+
* @returns The metric details and its most recent value.
|
|
178
|
+
*/
|
|
179
|
+
async getMetric(id) {
|
|
180
|
+
const result = await this._inner.getMetric(id);
|
|
181
|
+
// When the metric has no recorded values yet the inner connector returns
|
|
182
|
+
// entities[0] = undefined via queryValues. Return a placeholder so callers
|
|
183
|
+
// are not surprised by a null value field — treat id="" as "no measurements yet".
|
|
184
|
+
const value = result.value ?? { id: "", ts: 0, value: 0 };
|
|
185
|
+
return { metric: result.metric, value };
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Update the metric metadata.
|
|
189
|
+
* Note: OpenTelemetry instrument descriptors are immutable once created.
|
|
190
|
+
* This method updates the persisted metadata mirror; the description/unit changes
|
|
191
|
+
* are NOT propagated to the registered MeterProvider and will not appear at the
|
|
192
|
+
* OTEL backend (Prometheus, OTLP, etc.).
|
|
193
|
+
* @param metric The metric details (type cannot be changed).
|
|
194
|
+
* @returns Nothing.
|
|
195
|
+
*/
|
|
196
|
+
async updateMetric(metric) {
|
|
197
|
+
return this._inner.updateMetric(metric);
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Record a metric value.
|
|
201
|
+
* Entity storage always receives the value first and performs all validation.
|
|
202
|
+
* If the MeterProvider is running the measurement is also forwarded to the OTEL instrument.
|
|
203
|
+
* Counter accepts positive integers or "inc".
|
|
204
|
+
* UpDownCounter accepts integers (positive or negative) or "inc"/"dec".
|
|
205
|
+
* Gauge accepts any number.
|
|
206
|
+
* @param id The id of the metric.
|
|
207
|
+
* @param value The value for the operation.
|
|
208
|
+
* @param customData Optional custom data forwarded as OTEL attributes.
|
|
209
|
+
* @returns The id of the new metric value entry.
|
|
210
|
+
*/
|
|
211
|
+
async addMetricValue(id, value, customData) {
|
|
212
|
+
// Entity storage validates and persists first; throws NotFoundError if metric not found.
|
|
213
|
+
const valueId = await this._inner.addMetricValue(id, value, customData);
|
|
214
|
+
// Forward to the OTEL instrument only when the MeterProvider is running.
|
|
215
|
+
if (this._meter !== undefined) {
|
|
216
|
+
const entry = this._instruments.get(id);
|
|
217
|
+
if (entry !== undefined) {
|
|
218
|
+
const attributes = this.toAttributes(customData);
|
|
219
|
+
const { metricType, instrument } = entry;
|
|
220
|
+
// Value already validated by inner connector — dispatch unconditionally.
|
|
221
|
+
if (metricType === MetricType.Counter) {
|
|
222
|
+
instrument.add(value === MetricCounterOperation.Increment ? 1 : value, attributes);
|
|
223
|
+
}
|
|
224
|
+
else if (metricType === MetricType.IncDecCounter) {
|
|
225
|
+
let delta;
|
|
226
|
+
if (value === MetricCounterOperation.Increment) {
|
|
227
|
+
delta = 1;
|
|
228
|
+
}
|
|
229
|
+
else if (value === MetricCounterOperation.Decrement) {
|
|
230
|
+
delta = -1;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
delta = value;
|
|
234
|
+
}
|
|
235
|
+
instrument.add(delta, attributes);
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
instrument.record(value, attributes);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return valueId;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Remove a metric and its persisted value history.
|
|
246
|
+
* Note: OpenTelemetry exposes no API to deregister an instrument from a Meter,
|
|
247
|
+
* so the underlying Counter/UpDownCounter/Gauge remains resident for the lifetime
|
|
248
|
+
* of the process. Re-creating a metric with the same id but a different MetricType
|
|
249
|
+
* is therefore not safe.
|
|
250
|
+
* @param id The id of the metric.
|
|
251
|
+
* @returns Nothing.
|
|
252
|
+
*/
|
|
253
|
+
async removeMetric(id) {
|
|
254
|
+
this._instruments.delete(id);
|
|
255
|
+
// The inner connector cascades and removes all associated metric values.
|
|
256
|
+
return this._inner.removeMetric(id);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Query the registered metrics, optionally filtered by type.
|
|
260
|
+
* @param type The type of the metric.
|
|
261
|
+
* @param cursor The cursor to request the next page.
|
|
262
|
+
* @param limit Limit the number of entities to return.
|
|
263
|
+
* @returns The matching metrics and an optional cursor for the next page.
|
|
264
|
+
*/
|
|
265
|
+
async query(type, cursor, limit) {
|
|
266
|
+
return this._inner.query(type, cursor, limit);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Query the recorded values for a metric, ordered by most recent first.
|
|
270
|
+
* @param id The id of the metric.
|
|
271
|
+
* @param timeStart The inclusive start time (epoch ms).
|
|
272
|
+
* @param timeEnd The inclusive end time (epoch ms).
|
|
273
|
+
* @param cursor The cursor returned by the previous call.
|
|
274
|
+
* @param limit Limit the number of values to return.
|
|
275
|
+
* @returns The metric details, matching values, and an optional cursor for the next page.
|
|
276
|
+
*/
|
|
277
|
+
async queryValues(id, timeStart, timeEnd, cursor, limit) {
|
|
278
|
+
return this._inner.queryValues(id, timeStart, timeEnd, cursor, limit);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Convert customData to OTEL-compatible Attributes.
|
|
282
|
+
* Scalar values (string, number, boolean) and uniform primitive arrays
|
|
283
|
+
* (string[], number[], boolean[]) are forwarded; other values are silently dropped.
|
|
284
|
+
* @param customData The raw custom data map.
|
|
285
|
+
* @returns An OTEL Attributes object.
|
|
286
|
+
* @internal
|
|
287
|
+
*/
|
|
288
|
+
toAttributes(customData) {
|
|
289
|
+
if (Is.empty(customData)) {
|
|
290
|
+
return {};
|
|
291
|
+
}
|
|
292
|
+
const attrs = {};
|
|
293
|
+
for (const [key, val] of Object.entries(customData)) {
|
|
294
|
+
if (Is.string(val) || Is.number(val) || Is.boolean(val)) {
|
|
295
|
+
attrs[key] = val;
|
|
296
|
+
}
|
|
297
|
+
else if (Is.arrayValue(val)) {
|
|
298
|
+
if ((Is.string(val[0]) || Is.number(val[0]) || Is.boolean(val[0])) &&
|
|
299
|
+
val.every(el => typeof el === typeof val[0])) {
|
|
300
|
+
attrs[key] = val;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return attrs;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
//# sourceMappingURL=openTelemetryTelemetryConnector.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openTelemetryTelemetryConnector.js","sourceRoot":"","sources":["../../src/openTelemetryTelemetryConnector.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAqB,MAAM,4BAA4B,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,gBAAgB,EAAE,YAAY,EAAE,EAAE,EAAE,MAAM,gBAAgB,CAAC;AAGnG,OAAO,EAAE,+BAA+B,EAAE,MAAM,8CAA8C,CAAC;AAC/F,OAAO,EAIN,sBAAsB,EACtB,UAAU,EACV,MAAM,4BAA4B,CAAC;AAIpC;;;;;;;GAOG;AACH,MAAM,OAAO,+BAA+B;IAC3C;;OAEG;IACI,MAAM,CAAU,SAAS,GAAW,eAAe,CAAC;IAE3D;;OAEG;IACI,MAAM,CAAU,UAAU,qCAAqD;IAEtF;;;OAGG;IACc,OAAO,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,CAAC,GAAG,CAAC,GAAG,GAAsC,CAAC;gBACrD,CAAC;YACF,CAAC;QACF,CAAC;QACD,OAAO,KAAK,CAAC;IACd,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { Attributes, Counter, Gauge, Meter, UpDownCounter } from \"@opentelemetry/api\";\nimport { MeterProvider, type MetricReader } from \"@opentelemetry/sdk-metrics\";\nimport { AlreadyExistsError, BaseError, ComponentFactory, GeneralError, Is } from \"@twin.org/core\";\nimport type { ILoggingComponent } from \"@twin.org/logging-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { EntityStorageTelemetryConnector } from \"@twin.org/telemetry-connector-entity-storage\";\nimport {\n\ttype ITelemetryConnector,\n\ttype ITelemetryMetric,\n\ttype ITelemetryMetricValue,\n\tMetricCounterOperation,\n\tMetricType\n} from \"@twin.org/telemetry-models\";\nimport type { IOpenTelemetryTelemetryConnectorConfig } from \"./models/IOpenTelemetryTelemetryConnectorConfig.js\";\nimport type { IOpenTelemetryTelemetryConnectorConstructorOptions } from \"./models/IOpenTelemetryTelemetryConnectorConstructorOptions.js\";\n\n/**\n * Class for performing telemetry operations using OpenTelemetry instruments.\n * Metric definitions and value history are persisted via an internal\n * EntityStorageTelemetryConnector instance created at construction time.\n * Call `start()` to initialise the MeterProvider and exporters; metrics can be\n * created and queried before start() — OTEL forwarding is simply skipped until\n * the MeterProvider is running.\n */\nexport class OpenTelemetryTelemetryConnector implements ITelemetryConnector {\n\t/**\n\t * The namespace supported by the telemetry connector.\n\t */\n\tpublic static readonly NAMESPACE: string = \"opentelemetry\";\n\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<OpenTelemetryTelemetryConnector>();\n\n\t/**\n\t * Config options, stored so start() can initialise the MeterProvider.\n\t * @internal\n\t */\n\tprivate readonly _config: IOpenTelemetryTelemetryConnectorConfig;\n\n\t/**\n\t * Internal entity-storage connector that owns all metric metadata and value history.\n\t * Created at construction time — fails fast if entity storage is not set up.\n\t * @internal\n\t */\n\tprivate readonly _inner: EntityStorageTelemetryConnector;\n\n\t/**\n\t * Live OTEL instrument handles keyed by metric id, paired with the metric type\n\t * so addMetricValue can dispatch without querying storage.\n\t * These are runtime objects and cannot be persisted.\n\t * @internal\n\t */\n\tprivate readonly _instruments: Map<\n\t\tstring,\n\t\t{ metricType: MetricType; instrument: Counter | UpDownCounter | Gauge }\n\t>;\n\n\t/**\n\t * The MeterProvider that owns all instruments. Set by start(), cleared by stop().\n\t * @internal\n\t */\n\tprivate _meterProvider?: MeterProvider;\n\n\t/**\n\t * The Meter used to create instruments. Set by start(), cleared by stop().\n\t * @internal\n\t */\n\tprivate _meter?: Meter;\n\n\t/**\n\t * Create a new instance of OpenTelemetryTelemetryConnector.\n\t * Eagerly constructs the inner EntityStorageTelemetryConnector — if the required\n\t * entity storage types are not registered this constructor will throw (fail fast).\n\t * @param options The options for the connector.\n\t */\n\tconstructor(options?: IOpenTelemetryTelemetryConnectorConstructorOptions) {\n\t\tthis._config = options?.config ?? {};\n\t\tthis._inner = new EntityStorageTelemetryConnector({\n\t\t\tloggingComponentType: options?.loggingComponentType,\n\t\t\ttelemetryMetricStorageConnectorType: options?.telemetryMetricStorageConnectorType,\n\t\t\ttelemetryMetricValueStorageConnectorType: options?.telemetryMetricValueStorageConnectorType\n\t\t});\n\t\tthis._instruments = new Map();\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn OpenTelemetryTelemetryConnector.CLASS_NAME;\n\t}\n\n\t/**\n\t * Initialise the MeterProvider and configured exporters.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns Nothing.\n\t */\n\tpublic async start(nodeLoggingComponentType?: string): Promise<void> {\n\t\tif (!Is.undefined(this._meterProvider)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst readers: MetricReader[] = [];\n\t\tfor (const [, config] of Object.entries(this._config.readers ?? {})) {\n\t\t\tif (config.type === \"prometheus\") {\n\t\t\t\t// Dynamic import so @opentelemetry/exporter-prometheus is an optional peer dep;\n\t\t\t\t// consumers only need to install it if they actually configure a Prometheus reader.\n\t\t\t\tconst { PrometheusExporter: prometheusExporterClass } =\n\t\t\t\t\tawait import(\"@opentelemetry/exporter-prometheus\");\n\t\t\t\treaders.push(\n\t\t\t\t\tnew prometheusExporterClass({\n\t\t\t\t\t\tport: config.port,\n\t\t\t\t\t\tendpoint: config.endpoint,\n\t\t\t\t\t\t// PrometheusExporter uses preventServerStart (inverted); our config\n\t\t\t\t\t\t// exposes the more intuitive startServer (defaults to true).\n\t\t\t\t\t\tpreventServerStart: !(config.startServer ?? true),\n\t\t\t\t\t\tprefix: config.prefix\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow new GeneralError(OpenTelemetryTelemetryConnector.CLASS_NAME, \"unknownReaderType\", {\n\t\t\t\t\ttype: config.type\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tthis._meterProvider = new MeterProvider({ readers });\n\t\tthis._meter = this._meterProvider.getMeter(\n\t\t\tthis._config.meterName ?? \"twin-telemetry\",\n\t\t\tthis._config.meterVersion ?? \"1.0.0\"\n\t\t);\n\n\t\tconst nodeLogging = ComponentFactory.getIfExists<ILoggingComponent>(nodeLoggingComponentType);\n\t\tawait nodeLogging?.log({\n\t\t\tsource: OpenTelemetryTelemetryConnector.CLASS_NAME,\n\t\t\tmessage: \"connectorStarted\",\n\t\t\tlevel: \"info\",\n\t\t\tdata: { readerCount: Object.keys(this._config.readers ?? {}).length }\n\t\t});\n\t}\n\n\t/**\n\t * Shut down the MeterProvider and release resources.\n\t * Calling stop() on a connector that has not been started is a no-op.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns Nothing.\n\t */\n\tpublic async stop(nodeLoggingComponentType?: string): Promise<void> {\n\t\tif (!Is.undefined(this._meterProvider)) {\n\t\t\tawait this._meterProvider.shutdown();\n\t\t\tthis._meterProvider = undefined;\n\t\t\tthis._meter = undefined;\n\t\t\tthis._instruments.clear();\n\n\t\t\tconst nodeLogging = ComponentFactory.getIfExists<ILoggingComponent>(nodeLoggingComponentType);\n\t\t\tawait nodeLogging?.log({\n\t\t\t\tsource: OpenTelemetryTelemetryConnector.CLASS_NAME,\n\t\t\t\tmessage: \"connectorStopped\",\n\t\t\t\tlevel: \"info\",\n\t\t\t\tdata: {}\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Create a new metric.\n\t * The definition is always persisted via the inner entity-storage connector.\n\t * If the MeterProvider is running the corresponding OTEL instrument is also registered.\n\t * @param metric The metric details.\n\t * @returns Nothing.\n\t */\n\tpublic async createMetric(metric: ITelemetryMetric): Promise<void> {\n\t\ttry {\n\t\t\tawait this._inner.createMetric(metric);\n\t\t} catch (err) {\n\t\t\t// Entity storage performs all validation and throws AlreadyExistsError on duplicates.\n\t\t\t// OTP doesn't care about duplicates and will create a new instrument instance on each call\n\t\t\t// so we catch this error and ignore it to allow the OTEL instruments to be registered.\n\t\t\tif (!BaseError.isErrorName(err, AlreadyExistsError.CLASS_NAME)) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\t// Register an OTEL instrument when the MeterProvider is running.\n\t\t// This runs even when the metric already exists in storage so instruments\n\t\t// survive process restarts (AlreadyExistsError path).\n\t\tconst meter = this._meter;\n\t\tif (meter !== undefined && !this._instruments.has(metric.id)) {\n\t\t\tconst instrumentOptions = {\n\t\t\t\tdescription: metric.description,\n\t\t\t\tunit: metric.unit\n\t\t\t};\n\t\t\tlet instrument: Counter | UpDownCounter | Gauge;\n\t\t\tif (metric.type === MetricType.Counter) {\n\t\t\t\tinstrument = meter.createCounter(metric.id, instrumentOptions);\n\t\t\t} else if (metric.type === MetricType.IncDecCounter) {\n\t\t\t\tinstrument = meter.createUpDownCounter(metric.id, instrumentOptions);\n\t\t\t} else {\n\t\t\t\tinstrument = meter.createGauge(metric.id, instrumentOptions);\n\t\t\t}\n\t\t\tthis._instruments.set(metric.id, { metricType: metric.type, instrument });\n\t\t}\n\t}\n\n\t/**\n\t * Get the metric details and its most recent value.\n\t * @param id The metric id.\n\t * @returns The metric details and its most recent value.\n\t */\n\tpublic async getMetric(id: string): Promise<{\n\t\tmetric: ITelemetryMetric;\n\t\tvalue: ITelemetryMetricValue;\n\t}> {\n\t\tconst result = await this._inner.getMetric(id);\n\n\t\t// When the metric has no recorded values yet the inner connector returns\n\t\t// entities[0] = undefined via queryValues. Return a placeholder so callers\n\t\t// are not surprised by a null value field — treat id=\"\" as \"no measurements yet\".\n\t\tconst value = result.value ?? { id: \"\", ts: 0, value: 0 };\n\t\treturn { metric: result.metric, value };\n\t}\n\n\t/**\n\t * Update the metric metadata.\n\t * Note: OpenTelemetry instrument descriptors are immutable once created.\n\t * This method updates the persisted metadata mirror; the description/unit changes\n\t * are NOT propagated to the registered MeterProvider and will not appear at the\n\t * OTEL backend (Prometheus, OTLP, etc.).\n\t * @param metric The metric details (type cannot be changed).\n\t * @returns Nothing.\n\t */\n\tpublic async updateMetric(metric: Omit<ITelemetryMetric, \"type\">): Promise<void> {\n\t\treturn this._inner.updateMetric(metric);\n\t}\n\n\t/**\n\t * Record a metric value.\n\t * Entity storage always receives the value first and performs all validation.\n\t * If the MeterProvider is running the measurement is also forwarded to the OTEL instrument.\n\t * Counter accepts positive integers or \"inc\".\n\t * UpDownCounter accepts integers (positive or negative) or \"inc\"/\"dec\".\n\t * Gauge accepts any number.\n\t * @param id The id of the metric.\n\t * @param value The value for the operation.\n\t * @param customData Optional custom data forwarded as OTEL attributes.\n\t * @returns The id of the new metric value entry.\n\t */\n\tpublic async addMetricValue(\n\t\tid: string,\n\t\tvalue: MetricCounterOperation | number,\n\t\tcustomData?: { [key: string]: unknown }\n\t): Promise<string> {\n\t\t// Entity storage validates and persists first; throws NotFoundError if metric not found.\n\t\tconst valueId = await this._inner.addMetricValue(id, value, customData);\n\n\t\t// Forward to the OTEL instrument only when the MeterProvider is running.\n\t\tif (this._meter !== undefined) {\n\t\t\tconst entry = this._instruments.get(id);\n\t\t\tif (entry !== undefined) {\n\t\t\t\tconst attributes = this.toAttributes(customData);\n\t\t\t\tconst { metricType, instrument } = entry;\n\n\t\t\t\t// Value already validated by inner connector — dispatch unconditionally.\n\t\t\t\tif (metricType === MetricType.Counter) {\n\t\t\t\t\t(instrument as Counter).add(\n\t\t\t\t\t\tvalue === MetricCounterOperation.Increment ? 1 : (value as number),\n\t\t\t\t\t\tattributes\n\t\t\t\t\t);\n\t\t\t\t} else if (metricType === MetricType.IncDecCounter) {\n\t\t\t\t\tlet delta: number;\n\t\t\t\t\tif (value === MetricCounterOperation.Increment) {\n\t\t\t\t\t\tdelta = 1;\n\t\t\t\t\t} else if (value === MetricCounterOperation.Decrement) {\n\t\t\t\t\t\tdelta = -1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelta = value;\n\t\t\t\t\t}\n\t\t\t\t\t(instrument as UpDownCounter).add(delta, attributes);\n\t\t\t\t} else {\n\t\t\t\t\t(instrument as Gauge).record(value as number, attributes);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn valueId;\n\t}\n\n\t/**\n\t * Remove a metric and its persisted value history.\n\t * Note: OpenTelemetry exposes no API to deregister an instrument from a Meter,\n\t * so the underlying Counter/UpDownCounter/Gauge remains resident for the lifetime\n\t * of the process. Re-creating a metric with the same id but a different MetricType\n\t * is therefore not safe.\n\t * @param id The id of the metric.\n\t * @returns Nothing.\n\t */\n\tpublic async removeMetric(id: string): Promise<void> {\n\t\tthis._instruments.delete(id);\n\t\t// The inner connector cascades and removes all associated metric values.\n\t\treturn this._inner.removeMetric(id);\n\t}\n\n\t/**\n\t * Query the registered metrics, optionally filtered by type.\n\t * @param type The type of the metric.\n\t * @param cursor The cursor to request the next page.\n\t * @param limit Limit the number of entities to return.\n\t * @returns The matching metrics and an optional cursor for the next page.\n\t */\n\tpublic async query(\n\t\ttype?: MetricType,\n\t\tcursor?: string,\n\t\tlimit?: number\n\t): Promise<{\n\t\tentities: ITelemetryMetric[];\n\t\tcursor?: string;\n\t}> {\n\t\treturn this._inner.query(type, cursor, limit);\n\t}\n\n\t/**\n\t * Query the recorded values for a metric, ordered by most recent first.\n\t * @param id The id of the metric.\n\t * @param timeStart The inclusive start time (epoch ms).\n\t * @param timeEnd The inclusive end time (epoch ms).\n\t * @param cursor The cursor returned by the previous call.\n\t * @param limit Limit the number of values to return.\n\t * @returns The metric details, matching values, and an optional cursor for the next page.\n\t */\n\tpublic async queryValues(\n\t\tid: string,\n\t\ttimeStart?: number,\n\t\ttimeEnd?: number,\n\t\tcursor?: string,\n\t\tlimit?: number\n\t): Promise<{\n\t\tmetric: ITelemetryMetric;\n\t\tentities: ITelemetryMetricValue[];\n\t\tcursor?: string;\n\t}> {\n\t\treturn this._inner.queryValues(id, timeStart, timeEnd, cursor, limit);\n\t}\n\n\t/**\n\t * Convert customData to OTEL-compatible Attributes.\n\t * Scalar values (string, number, boolean) and uniform primitive arrays\n\t * (string[], number[], boolean[]) are forwarded; other values are silently dropped.\n\t * @param customData The raw custom data map.\n\t * @returns An OTEL Attributes object.\n\t * @internal\n\t */\n\tprivate toAttributes(customData?: { [key: string]: unknown }): Attributes {\n\t\tif (Is.empty(customData)) {\n\t\t\treturn {};\n\t\t}\n\t\tconst attrs: Attributes = {};\n\t\tfor (const [key, val] of Object.entries(customData)) {\n\t\t\tif (Is.string(val) || Is.number(val) || Is.boolean(val)) {\n\t\t\t\tattrs[key] = val;\n\t\t\t} else if (Is.arrayValue(val)) {\n\t\t\t\tif (\n\t\t\t\t\t(Is.string(val[0]) || Is.number(val[0]) || Is.boolean(val[0])) &&\n\t\t\t\t\tval.every(el => typeof el === typeof val[0])\n\t\t\t\t) {\n\t\t\t\t\tattrs[key] = val as string[] | number[] | boolean[];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn attrs;\n\t}\n}\n"]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export * from "./models/IOpenTelemetryPrometheusReaderConfig.js";
|
|
2
|
+
export * from "./models/IOpenTelemetryReaderConfig.js";
|
|
3
|
+
export * from "./models/IOpenTelemetryTelemetryConnectorConfig.js";
|
|
4
|
+
export * from "./models/IOpenTelemetryTelemetryConnectorConstructorOptions.js";
|
|
5
|
+
export * from "./models/openTelemetryReaderTypes.js";
|
|
6
|
+
export * from "./openTelemetryTelemetryConnector.js";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { OpenTelemetryReaderTypes } from "./openTelemetryReaderTypes.js";
|
|
2
|
+
/**
|
|
3
|
+
* Configuration for a Prometheus scrape-endpoint reader.
|
|
4
|
+
* The connector instantiates a PrometheusExporter from these options in start().
|
|
5
|
+
*/
|
|
6
|
+
export interface IOpenTelemetryPrometheusReaderConfig {
|
|
7
|
+
/**
|
|
8
|
+
* Type.
|
|
9
|
+
*/
|
|
10
|
+
type: typeof OpenTelemetryReaderTypes.Prometheus;
|
|
11
|
+
/**
|
|
12
|
+
* TCP port the Prometheus HTTP server listens on.
|
|
13
|
+
* @default 9464
|
|
14
|
+
*/
|
|
15
|
+
port?: number;
|
|
16
|
+
/**
|
|
17
|
+
* HTTP path that Prometheus scrapes.
|
|
18
|
+
* @default /metrics
|
|
19
|
+
*/
|
|
20
|
+
endpoint?: string;
|
|
21
|
+
/**
|
|
22
|
+
* Whether to start the built-in HTTP server automatically.
|
|
23
|
+
* Set to false if you manage the server externally.
|
|
24
|
+
* @default true
|
|
25
|
+
*/
|
|
26
|
+
startServer?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Optional string prepended to every exported metric name.
|
|
29
|
+
*/
|
|
30
|
+
prefix?: string;
|
|
31
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { IOpenTelemetryPrometheusReaderConfig } from "./IOpenTelemetryPrometheusReaderConfig.js";
|
|
2
|
+
/**
|
|
3
|
+
* Discriminated union of all supported metric-reader configurations.
|
|
4
|
+
* Add new members here when additional exporter types are implemented.
|
|
5
|
+
*/
|
|
6
|
+
export type IOpenTelemetryReaderConfig = IOpenTelemetryPrometheusReaderConfig;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { IOpenTelemetryReaderConfig } from "./IOpenTelemetryReaderConfig.js";
|
|
2
|
+
/**
|
|
3
|
+
* The options for the OpenTelemetry telemetry connector constructor.
|
|
4
|
+
*/
|
|
5
|
+
export interface IOpenTelemetryTelemetryConnectorConfig {
|
|
6
|
+
/**
|
|
7
|
+
* The name of the OpenTelemetry meter used to create instruments.
|
|
8
|
+
* @default twin-telemetry
|
|
9
|
+
*/
|
|
10
|
+
meterName?: string;
|
|
11
|
+
/**
|
|
12
|
+
* The version reported by the OpenTelemetry meter.
|
|
13
|
+
* @default 1.0.0
|
|
14
|
+
*/
|
|
15
|
+
meterVersion?: string;
|
|
16
|
+
/**
|
|
17
|
+
* Named metric-reader configurations keyed by an arbitrary id.
|
|
18
|
+
* Each entry's `type` field determines which exporter the connector instantiates
|
|
19
|
+
* in start(). Omit or pass an empty object for a no-op provider (useful for tests).
|
|
20
|
+
*/
|
|
21
|
+
readers?: {
|
|
22
|
+
[id: string]: IOpenTelemetryReaderConfig;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { IOpenTelemetryTelemetryConnectorConfig } from "./IOpenTelemetryTelemetryConnectorConfig.js";
|
|
2
|
+
/**
|
|
3
|
+
* The options for the OpenTelemetry telemetry connector constructor.
|
|
4
|
+
*/
|
|
5
|
+
export interface IOpenTelemetryTelemetryConnectorConstructorOptions {
|
|
6
|
+
/**
|
|
7
|
+
* The component type to use for logging inside the connector and the inner
|
|
8
|
+
* entity-storage connector. When omitted logging is disabled.
|
|
9
|
+
*/
|
|
10
|
+
loggingComponentType?: string;
|
|
11
|
+
/**
|
|
12
|
+
* The entity storage connector type to use for storing metric definitions.
|
|
13
|
+
* Must be registered in `EntityStorageConnectorFactory` before calling `start()`.
|
|
14
|
+
* @default telemetry-metric
|
|
15
|
+
*/
|
|
16
|
+
telemetryMetricStorageConnectorType?: string;
|
|
17
|
+
/**
|
|
18
|
+
* The entity storage connector type to use for storing metric values.
|
|
19
|
+
* Must be registered in `EntityStorageConnectorFactory` before calling `start()`.
|
|
20
|
+
* @default telemetry-metric-value
|
|
21
|
+
*/
|
|
22
|
+
telemetryMetricValueStorageConnectorType?: string;
|
|
23
|
+
/**
|
|
24
|
+
* The config for the telemetry connector.
|
|
25
|
+
*/
|
|
26
|
+
config?: IOpenTelemetryTelemetryConnectorConfig;
|
|
27
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The types of readers.
|
|
3
|
+
*/
|
|
4
|
+
export declare const OpenTelemetryReaderTypes: {
|
|
5
|
+
/**
|
|
6
|
+
* Prometheus.
|
|
7
|
+
*/
|
|
8
|
+
readonly Prometheus: "prometheus";
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The types of readers.
|
|
12
|
+
*/
|
|
13
|
+
export type OpenTelemetryReaderTypes = (typeof OpenTelemetryReaderTypes)[keyof typeof OpenTelemetryReaderTypes];
|