@routr/common 2.24.1 → 2.25.1

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/dist/tracer.d.ts CHANGED
@@ -1,20 +1,34 @@
1
1
  import { Tracer } from "@opentelemetry/api";
2
2
  /**
3
- * Whether tracing is on: an OTLP endpoint is configured and the SDK is not disabled.
3
+ * Whether telemetry is on: an OTLP endpoint is configured and the SDK is not disabled.
4
4
  *
5
5
  * @param {NodeJS.ProcessEnv} env - The environment to read.
6
- * @return {boolean} True when spans should be exported.
6
+ * @return {boolean} True when traces, metrics and logs should be exported.
7
7
  */
8
8
  export declare function tracingEnabled(env?: NodeJS.ProcessEnv): boolean;
9
9
  /**
10
- * Starts tracing for the service, exporting spans over OTLP/HTTP to the endpoint in the
11
- * standard OTEL_EXPORTER_OTLP_* variables. Without one it registers nothing and returns a
12
- * no-op tracer. Call it before anything loads @grpc/grpc-js, so the gRPC instrumentation
13
- * can propagate the W3C trace context between services. Only the first call in a process
14
- * starts tracing (Routr One loads several services).
10
+ * Starts telemetry for the service: traces, metrics and logs over OTLP/HTTP to the endpoint
11
+ * in the standard OTEL_EXPORTER_OTLP_* variables. Without one it registers nothing and
12
+ * returns a no-op tracer. Call it before anything loads @grpc/grpc-js or creates a logger,
13
+ * so the gRPC instrumentation can propagate the W3C trace context between services and
14
+ * every Winston logger also sends its records. Only the first call in a process starts
15
+ * telemetry (Routr One loads several services).
15
16
  *
16
17
  * @param {string} serviceName - The service's name, unless OTEL_SERVICE_NAME is set.
17
18
  * @param {NodeJS.ProcessEnv} env - The environment to read.
18
19
  * @return {Tracer} The tracer object.
19
20
  */
20
21
  export declare function init(serviceName: string, env?: NodeJS.ProcessEnv): Tracer;
22
+ /**
23
+ * Exports what is still buffered (spans, metrics, log records).
24
+ *
25
+ * @return {Promise<void>} Resolves once every signal was flushed.
26
+ */
27
+ export declare function flush(): Promise<void>;
28
+ /**
29
+ * Flushes and stops every provider and unregisters them and the instrumentations, so a later
30
+ * init starts telemetry afresh (tests).
31
+ *
32
+ * @return {Promise<void>} Resolves once every provider stopped.
33
+ */
34
+ export declare function shutdown(): Promise<void>;
package/dist/tracer.js CHANGED
@@ -1,10 +1,51 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
4
43
  };
5
44
  Object.defineProperty(exports, "__esModule", { value: true });
6
45
  exports.tracingEnabled = tracingEnabled;
7
46
  exports.init = init;
47
+ exports.flush = flush;
48
+ exports.shutdown = shutdown;
8
49
  /*
9
50
  * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
10
51
  * http://github.com/fonoster/routr
@@ -23,19 +64,25 @@ exports.init = init;
23
64
  * See the License for the specific language governing permissions and
24
65
  * limitations under the License.
25
66
  */
26
- const api_1 = __importDefault(require("@opentelemetry/api"));
67
+ const api_1 = __importStar(require("@opentelemetry/api"));
68
+ const context_async_hooks_1 = require("@opentelemetry/context-async-hooks");
69
+ const core_1 = require("@opentelemetry/core");
27
70
  const instrumentation_1 = require("@opentelemetry/instrumentation");
28
71
  const instrumentation_grpc_1 = require("@opentelemetry/instrumentation-grpc");
29
- const sdk_trace_node_1 = require("@opentelemetry/sdk-trace-node");
30
- const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
72
+ const instrumentation_winston_1 = require("@opentelemetry/instrumentation-winston");
73
+ const sdk_trace_1 = require("@opentelemetry/sdk-trace");
74
+ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
75
+ const sdk_logs_1 = require("@opentelemetry/sdk-logs");
31
76
  const resources_1 = require("@opentelemetry/resources");
32
77
  const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
33
78
  const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
79
+ const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http");
80
+ const exporter_logs_otlp_http_1 = require("@opentelemetry/exporter-logs-otlp-http");
34
81
  /**
35
- * Whether tracing is on: an OTLP endpoint is configured and the SDK is not disabled.
82
+ * Whether telemetry is on: an OTLP endpoint is configured and the SDK is not disabled.
36
83
  *
37
84
  * @param {NodeJS.ProcessEnv} env - The environment to read.
38
- * @return {boolean} True when spans should be exported.
85
+ * @return {boolean} True when traces, metrics and logs should be exported.
39
86
  */
40
87
  function tracingEnabled(env = process.env) {
41
88
  if (env.OTEL_SDK_DISABLED === "true")
@@ -43,44 +90,119 @@ function tracingEnabled(env = process.env) {
43
90
  return !!(env.OTEL_EXPORTER_OTLP_ENDPOINT || env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT);
44
91
  }
45
92
  /**
46
- * The traces endpoint, as the OTLP exporter would derive it from process.env.
93
+ * A signal's endpoint, as the OTLP exporters derive it from the environment: the
94
+ * signal's own variable, else the base endpoint plus `/v1/<signal>`.
47
95
  *
48
96
  * @param {NodeJS.ProcessEnv} env - The environment to read.
49
- * @return {string} The URL spans are posted to.
97
+ * @param {Signal} signal - traces, metrics or logs.
98
+ * @return {string} The URL the signal is posted to.
50
99
  */
51
- function tracesUrl(env) {
100
+ function signalUrl(env, signal) {
52
101
  var _a;
53
- if (env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT)
54
- return env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT;
55
- return `${(_a = env.OTEL_EXPORTER_OTLP_ENDPOINT) === null || _a === void 0 ? void 0 : _a.replace(/\/$/, "")}/v1/traces`;
102
+ const own = env[`OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_ENDPOINT`];
103
+ if (own)
104
+ return own;
105
+ // With only a traces endpoint, the other signals go to the same collector.
106
+ const base = env.OTEL_EXPORTER_OTLP_ENDPOINT ||
107
+ ((_a = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) === null || _a === void 0 ? void 0 : _a.replace(/\/v1\/traces\/?$/, ""));
108
+ return `${base === null || base === void 0 ? void 0 : base.replace(/\/$/, "")}/v1/${signal}`;
56
109
  }
57
- let started = false;
110
+ let providers = [];
111
+ let unregisterInstrumentations;
58
112
  /**
59
- * Starts tracing for the service, exporting spans over OTLP/HTTP to the endpoint in the
60
- * standard OTEL_EXPORTER_OTLP_* variables. Without one it registers nothing and returns a
61
- * no-op tracer. Call it before anything loads @grpc/grpc-js, so the gRPC instrumentation
62
- * can propagate the W3C trace context between services. Only the first call in a process
63
- * starts tracing (Routr One loads several services).
113
+ * Starts telemetry for the service: traces, metrics and logs over OTLP/HTTP to the endpoint
114
+ * in the standard OTEL_EXPORTER_OTLP_* variables. Without one it registers nothing and
115
+ * returns a no-op tracer. Call it before anything loads @grpc/grpc-js or creates a logger,
116
+ * so the gRPC instrumentation can propagate the W3C trace context between services and
117
+ * every Winston logger also sends its records. Only the first call in a process starts
118
+ * telemetry (Routr One loads several services).
64
119
  *
65
120
  * @param {string} serviceName - The service's name, unless OTEL_SERVICE_NAME is set.
66
121
  * @param {NodeJS.ProcessEnv} env - The environment to read.
67
122
  * @return {Tracer} The tracer object.
68
123
  */
69
124
  function init(serviceName, env = process.env) {
70
- if (started || !tracingEnabled(env))
125
+ if (providers.length || !tracingEnabled(env))
71
126
  return api_1.default.trace.getTracer("routr-tracer");
72
- started = true;
73
- const provider = new sdk_trace_node_1.NodeTracerProvider({
74
- resource: (0, resources_1.resourceFromAttributes)({
75
- [semantic_conventions_1.ATTR_SERVICE_NAME]: env.OTEL_SERVICE_NAME || serviceName
76
- }),
127
+ const resource = (0, resources_1.resourceFromAttributes)({
128
+ [semantic_conventions_1.ATTR_SERVICE_NAME]: env.OTEL_SERVICE_NAME || serviceName
129
+ });
130
+ api_1.context.setGlobalContextManager(new context_async_hooks_1.AsyncLocalStorageContextManager().enable());
131
+ api_1.propagation.setGlobalPropagator(new core_1.CompositePropagator({
132
+ propagators: [new core_1.W3CTraceContextPropagator(), new core_1.W3CBaggagePropagator()]
133
+ }));
134
+ const tracerProvider = new sdk_trace_1.TracerProvider({
135
+ resource,
77
136
  spanProcessors: [
78
- new sdk_trace_base_1.BatchSpanProcessor(new exporter_trace_otlp_http_1.OTLPTraceExporter({ url: tracesUrl(env) }))
137
+ new sdk_trace_1.BatchSpanProcessor({
138
+ exporter: new exporter_trace_otlp_http_1.OTLPTraceExporter({ url: signalUrl(env, "traces") })
139
+ })
79
140
  ]
80
141
  });
81
- provider.register();
82
- (0, instrumentation_1.registerInstrumentations)({
83
- instrumentations: [new instrumentation_grpc_1.GrpcInstrumentation()]
142
+ api_1.default.trace.setGlobalTracerProvider(tracerProvider);
143
+ const meterProvider = new sdk_metrics_1.MeterProvider({
144
+ resource,
145
+ readers: [
146
+ new sdk_metrics_1.PeriodicExportingMetricReader({
147
+ exporter: new exporter_metrics_otlp_http_1.OTLPMetricExporter({ url: signalUrl(env, "metrics") }),
148
+ exportIntervalMillis: Number(env.OTEL_METRIC_EXPORT_INTERVAL) || 15000
149
+ })
150
+ ]
151
+ });
152
+ api_1.default.metrics.setGlobalMeterProvider(meterProvider);
153
+ const loggerProvider = new sdk_logs_1.LoggerProvider({
154
+ resource,
155
+ processors: [
156
+ new sdk_logs_1.BatchLogRecordProcessor({
157
+ exporter: new exporter_logs_otlp_http_1.OTLPLogExporter({ url: signalUrl(env, "logs") })
158
+ })
159
+ ]
84
160
  });
161
+ api_1.default.logs.setGlobalLoggerProvider(loggerProvider);
162
+ providers = [tracerProvider, meterProvider, loggerProvider];
163
+ unregisterInstrumentations = (0, instrumentation_1.registerInstrumentations)({
164
+ instrumentations: [new instrumentation_grpc_1.GrpcInstrumentation(), new instrumentation_winston_1.WinstonInstrumentation()]
165
+ });
166
+ // Flush what is buffered when the process stops: beforeExit for a natural end, and SIGTERM
167
+ // and SIGINT (a rollout, Ctrl-C), re-raised once flushed when nothing else handles them.
168
+ process.once("beforeExit", () => void shutdown());
169
+ const flushOn = (signal) => process.once(signal, () => {
170
+ void flush().finally(() => {
171
+ if (process.listenerCount(signal) === 0)
172
+ process.kill(process.pid, signal);
173
+ });
174
+ });
175
+ flushOn("SIGTERM");
176
+ flushOn("SIGINT");
85
177
  return api_1.default.trace.getTracer("routr-tracer");
86
178
  }
179
+ /**
180
+ * Exports what is still buffered (spans, metrics, log records).
181
+ *
182
+ * @return {Promise<void>} Resolves once every signal was flushed.
183
+ */
184
+ function flush() {
185
+ return __awaiter(this, void 0, void 0, function* () {
186
+ yield Promise.all(providers.map((p) => p.forceFlush()));
187
+ });
188
+ }
189
+ /**
190
+ * Flushes and stops every provider and unregisters them and the instrumentations, so a later
191
+ * init starts telemetry afresh (tests).
192
+ *
193
+ * @return {Promise<void>} Resolves once every provider stopped.
194
+ */
195
+ function shutdown() {
196
+ return __awaiter(this, void 0, void 0, function* () {
197
+ const stopping = providers;
198
+ providers = [];
199
+ unregisterInstrumentations === null || unregisterInstrumentations === void 0 ? void 0 : unregisterInstrumentations();
200
+ unregisterInstrumentations = undefined;
201
+ api_1.default.trace.disable();
202
+ api_1.default.metrics.disable();
203
+ api_1.default.logs.disable();
204
+ api_1.context.disable();
205
+ api_1.propagation.disable();
206
+ yield Promise.all(stopping.map((p) => p.shutdown().catch(() => undefined)));
207
+ });
208
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@routr/common",
3
- "version": "2.24.1",
3
+ "version": "2.25.1",
4
4
  "description": "Common package",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/routr#readme",
@@ -16,14 +16,21 @@
16
16
  "@fonoster/logger": "0.6.0",
17
17
  "@grpc/grpc-js": "~1.14.6",
18
18
  "@grpc/proto-loader": "~0.7.10",
19
- "@opentelemetry/api": "^1.9.0",
20
- "@opentelemetry/exporter-trace-otlp-http": "^0.223.0",
21
- "@opentelemetry/instrumentation": "^0.223.0",
22
- "@opentelemetry/instrumentation-grpc": "^0.223.0",
23
- "@opentelemetry/resources": "^2.12.0",
24
- "@opentelemetry/sdk-trace-base": "^2.12.0",
25
- "@opentelemetry/sdk-trace-node": "^2.12.0",
19
+ "@opentelemetry/api": "^1.10.0",
20
+ "@opentelemetry/context-async-hooks": "^3.0.0",
21
+ "@opentelemetry/core": "^3.0.0",
22
+ "@opentelemetry/exporter-logs-otlp-http": "^0.300.0",
23
+ "@opentelemetry/exporter-metrics-otlp-http": "^0.300.0",
24
+ "@opentelemetry/exporter-trace-otlp-http": "^0.300.0",
25
+ "@opentelemetry/instrumentation": "^0.300.0",
26
+ "@opentelemetry/instrumentation-grpc": "^0.300.0",
27
+ "@opentelemetry/instrumentation-winston": "^0.69.0",
28
+ "@opentelemetry/resources": "^3.0.0",
29
+ "@opentelemetry/sdk-logs": "^3.0.0",
30
+ "@opentelemetry/sdk-metrics": "^3.0.0",
31
+ "@opentelemetry/sdk-trace": "^3.0.0",
26
32
  "@opentelemetry/semantic-conventions": "^1.43.0",
33
+ "@opentelemetry/winston-transport": "^0.35.0",
27
34
  "ajv": "^6.12.6",
28
35
  "fp-ts": "^2.11.8",
29
36
  "grpc-health-check": "^2.1.0",
@@ -53,5 +60,5 @@
53
60
  "devDependencies": {
54
61
  "@types/js-yaml": "^4.0.5"
55
62
  },
56
- "gitHead": "924e294f39229388f67969633b16d204dc33aa67"
63
+ "gitHead": "5373e48aed0f3e4ddb7a3c99a16109e272fa7252"
57
64
  }