@manifest-cyber/observability-ts 0.2.11 → 0.2.12

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
@@ -299,6 +299,36 @@ extractMessageTraceContext(message.MessageAttributes);
299
299
  | `OTEL_TRACING_ENABLED` | Enable/disable tracing | `true` |
300
300
  | `ENV` | Environment (dev/staging/prod) | `'development'` |
301
301
 
302
+ ## Process Exit Interceptor
303
+
304
+ When tracing is enabled, `process.exit()` is automatically intercepted to flush tracing data before termination (default: enabled, 2s timeout). This prevents telemetry loss on abrupt exits.
305
+
306
+ ```typescript
307
+ import { initObservability } from '@manifest-cyber/observability-ts';
308
+
309
+ await initObservability({
310
+ serviceName: 'my-service',
311
+ interceptProcessExit: true, // default: true
312
+ exitFlushTimeoutMs: 2000, // default: 2000ms
313
+ });
314
+
315
+ // Tracing automatically flushed on exit
316
+ if (failed) process.exit(1);
317
+ ```
318
+
319
+ **Configuration:**
320
+ - `interceptProcessExit: boolean` - Enable/disable (default: `true`)
321
+ - `exitFlushTimeoutMs: number` - Flush timeout in ms (default: `2000`)
322
+ - `logger: Logger` - Optional logger for diagnostics
323
+
324
+ **To disable:**
325
+ ```typescript
326
+ await initObservability({
327
+ serviceName: 'my-service',
328
+ interceptProcessExit: false,
329
+ });
330
+ ```
331
+
302
332
  ## Example: Express API
303
333
 
304
334
  ```typescript
@@ -360,6 +390,43 @@ app.get('/api/users/:id', async (req, res) => {
360
390
  app.listen(3000);
361
391
  ```
362
392
 
393
+ ## Migration from prom-client (v0.2.x → v0.3.x)
394
+
395
+ v0.3.0 migrates from `prom-client` to OpenTelemetry SDK for metrics.
396
+
397
+ ### Breaking Changes
398
+
399
+ | Change | Before | After |
400
+ |--------|--------|-------|
401
+ | `startMetricsServer()` | Sync | Async (`await`) |
402
+ | `getRegistry()` / `resetRegistry()` | Exported | Removed |
403
+ | `reset()` / `remove()` on metrics | Functional | No-op (API compat) |
404
+ | prom-client type re-exports | Available | Removed |
405
+
406
+ ### New: Auto-instrumentation
407
+
408
+ ```typescript
409
+ await initObservability({
410
+ serviceName: 'my-api',
411
+ autoInstrument: ['http', 'express', 'mongo'],
412
+ });
413
+ ```
414
+
415
+ ### Optional Peer Dependencies
416
+
417
+ ```bash
418
+ # Runtime metrics
419
+ npm install @opentelemetry/host-metrics @opentelemetry/instrumentation-runtime-node
420
+
421
+ # OTLP export (choose gRPC or HTTP)
422
+ npm install @opentelemetry/exporter-metrics-otlp-grpc
423
+ # or
424
+ npm install @opentelemetry/exporter-metrics-otlp-http
425
+
426
+ # Auto-instrumentation (as needed)
427
+ npm install @opentelemetry/instrumentation-http @opentelemetry/instrumentation-express
428
+ ```
429
+
363
430
  ## Migration from @manifest-cyber/metrics
364
431
 
365
432
  ```bash
package/dist/index.d.ts CHANGED
@@ -41,13 +41,13 @@
41
41
  * import { initTracing } from '@manifest-cyber/observability-ts/tracing';
42
42
  * ```
43
43
  */
44
- export { getRegistry, resetRegistry } from './metrics/registry';
44
+ export { initMetricsProvider, getSharedMeterProvider, getSharedResource, getMeter, } from './metrics/provider';
45
+ export type { MetricsProviderOptions, MetricsProviderInitResult, AutoInstrumentKey, } from './metrics/provider';
45
46
  export { startMetricsServer } from './metrics/server';
46
47
  export type { MetricsServerOptions } from './metrics/server';
47
48
  export { createCounter, createHistogram, createGauge, BUCKETS, ENV_KEY_SERVICE_NAME, } from './metrics/builders';
48
- export type { HistogramConfig } from './metrics/builders';
49
+ export type { HistogramConfig, ServiceCounter, ServiceHistogram, ServiceGauge, } from './metrics/builders';
49
50
  export { Timer, MetricsContext, instrumentAsync, trackOperation, } from './metrics/instrumentation';
50
- export type { Counter, Histogram, Gauge, Registry } from 'prom-client';
51
51
  export { initTracing, isTracingInitialized, getTracerProvider, shutdownTracing, } from './tracing/setup';
52
52
  export { getTracer, createSpan, withSpan, withSpanResult, getCurrentSpan, getCurrentTraceId, getCurrentSpanId, addSpanEvent, setSpanAttributes, recordException, withActiveSpan, withActiveSpanAsync, } from './tracing/spans';
53
53
  export { injectTraceContext, extractTraceContext, getTraceparent, parseTraceparent, createContextFromTraceparent, createMessageTraceContext, extractMessageTraceContext, withExtractedContext, withExtractedContextAsync, } from './tracing/context';
@@ -57,4 +57,6 @@ export type { ServiceMetricsConfig, MetricLabels, DurationMetricOptions, Logger,
57
57
  export type { TracingConfig, ExporterConfig, SamplingConfig, SpanOptions, TracedResult, HttpSpanAttributes, DbSpanAttributes, MessagingSpanAttributes, TraceContext, } from './tracing/types';
58
58
  export { initObservability } from './init';
59
59
  export type { InitObservabilityConfig, InitObservabilityResult } from './init';
60
+ export type { MeterProvider } from '@opentelemetry/sdk-metrics';
61
+ export type { Meter } from '@opentelemetry/api';
60
62
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AAOH,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGhE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,YAAY,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAG7D,OAAO,EACL,aAAa,EACb,eAAe,EACf,WAAW,EACX,OAAO,EACP,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EACL,KAAK,EACL,cAAc,EACd,eAAe,EACf,cAAc,GACf,MAAM,2BAA2B,CAAC;AAGnC,YAAY,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAOvE,OAAO,EACL,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,GAChB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,SAAS,EACT,UAAU,E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,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,YAAY,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -43,14 +43,16 @@
43
43
  * ```
44
44
  */
45
45
  Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.initObservability = exports.SpanKind = exports.SpanStatusCode = exports.withExtractedContextAsync = exports.withExtractedContext = exports.extractMessageTraceContext = exports.createMessageTraceContext = exports.createContextFromTraceparent = exports.parseTraceparent = exports.getTraceparent = exports.extractTraceContext = exports.injectTraceContext = exports.withActiveSpanAsync = exports.withActiveSpan = exports.recordException = exports.setSpanAttributes = exports.addSpanEvent = exports.getCurrentSpanId = exports.getCurrentTraceId = exports.getCurrentSpan = exports.withSpanResult = exports.withSpan = exports.createSpan = exports.getTracer = exports.shutdownTracing = exports.getTracerProvider = exports.isTracingInitialized = exports.initTracing = exports.trackOperation = exports.instrumentAsync = exports.MetricsContext = exports.Timer = exports.ENV_KEY_SERVICE_NAME = exports.BUCKETS = exports.createGauge = exports.createHistogram = exports.createCounter = exports.startMetricsServer = exports.resetRegistry = exports.getRegistry = void 0;
46
+ exports.initObservability = exports.SpanKind = exports.SpanStatusCode = exports.withExtractedContextAsync = exports.withExtractedContext = exports.extractMessageTraceContext = exports.createMessageTraceContext = exports.createContextFromTraceparent = exports.parseTraceparent = exports.getTraceparent = exports.extractTraceContext = exports.injectTraceContext = exports.withActiveSpanAsync = exports.withActiveSpan = exports.recordException = exports.setSpanAttributes = exports.addSpanEvent = exports.getCurrentSpanId = exports.getCurrentTraceId = exports.getCurrentSpan = exports.withSpanResult = exports.withSpan = exports.createSpan = exports.getTracer = exports.shutdownTracing = exports.getTracerProvider = exports.isTracingInitialized = exports.initTracing = exports.trackOperation = exports.instrumentAsync = exports.MetricsContext = exports.Timer = exports.ENV_KEY_SERVICE_NAME = exports.BUCKETS = exports.createGauge = exports.createHistogram = exports.createCounter = exports.startMetricsServer = exports.getMeter = exports.getSharedResource = exports.getSharedMeterProvider = exports.initMetricsProvider = void 0;
47
47
  // ====================
48
48
  // METRICS EXPORTS
49
49
  // ====================
50
- // Registry management
51
- var registry_1 = require("./metrics/registry");
52
- Object.defineProperty(exports, "getRegistry", { enumerable: true, get: function () { return registry_1.getRegistry; } });
53
- Object.defineProperty(exports, "resetRegistry", { enumerable: true, get: function () { return registry_1.resetRegistry; } });
50
+ // Provider initialization (advanced)
51
+ var provider_1 = require("./metrics/provider");
52
+ Object.defineProperty(exports, "initMetricsProvider", { enumerable: true, get: function () { return provider_1.initMetricsProvider; } });
53
+ Object.defineProperty(exports, "getSharedMeterProvider", { enumerable: true, get: function () { return provider_1.getSharedMeterProvider; } });
54
+ Object.defineProperty(exports, "getSharedResource", { enumerable: true, get: function () { return provider_1.getSharedResource; } });
55
+ Object.defineProperty(exports, "getMeter", { enumerable: true, get: function () { return provider_1.getMeter; } });
54
56
  // Server setup
55
57
  var server_1 = require("./metrics/server");
56
58
  Object.defineProperty(exports, "startMetricsServer", { enumerable: true, get: function () { return server_1.startMetricsServer; } });
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;;;AAEH,uBAAuB;AACvB,kBAAkB;AAClB,uBAAuB;AAEvB,sBAAsB;AACtB,+CAAgE;AAAvD,uGAAA,WAAW,OAAA;AAAE,yGAAA,aAAa,OAAA;AAEnC,eAAe;AACf,2CAAsD;AAA7C,4GAAA,kBAAkB,OAAA;AAG3B,kBAAkB;AAClB,+CAM4B;AAL1B,yGAAA,aAAa,OAAA;AACb,2GAAA,eAAe,OAAA;AACf,uGAAA,WAAW,OAAA;AACX,mGAAA,OAAO,OAAA;AACP,gHAAA,oBAAoB,OAAA;AAItB,0BAA0B;AAC1B,6DAKmC;AAJjC,wGAAA,KAAK,OAAA;AACL,iHAAA,cAAc,OAAA;A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AArD,qGAAA,cAAc,OAAA;AAAE,+FAAA,QAAQ,OAAA;AAyBjC,uBAAuB;AACvB,yBAAyB;AACzB,uBAAuB;AAEvB,+BAA2C;AAAlC,yGAAA,iBAAiB,OAAA"}
package/dist/init.d.ts CHANGED
@@ -2,6 +2,8 @@
2
2
  * High-level initialization helpers for observability setup.
3
3
  * Simplifies the setup of tracing, metrics, and logging for services.
4
4
  */
5
+ import { type AutoInstrumentKey } from './metrics/provider';
6
+ import type { Logger } from './tracing/types';
5
7
  export interface InitObservabilityConfig {
6
8
  /** Service name for telemetry */
7
9
  serviceName: string;
@@ -13,6 +15,38 @@ export interface InitObservabilityConfig {
13
15
  samplingRatio?: number;
14
16
  /** OTLP endpoint for traces (default: http://localhost:4317) */
15
17
  otlpEndpoint?: string;
18
+ /** Enable/disable default Node.js metrics (default: true, first call wins) */
19
+ enableDefaultMetrics?: boolean;
20
+ /**
21
+ * Auto-instrumentation to enable. Explicit opt-in only - no defaults.
22
+ *
23
+ * Each instrumentation requires its corresponding `@opentelemetry/instrumentation-*`
24
+ * package to be installed in your project. Missing packages are gracefully skipped.
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * // Express API with MongoDB
29
+ * autoInstrument: ['http', 'express', 'mongo']
30
+ *
31
+ * // Job with AWS SDK and MongoDB
32
+ * autoInstrument: ['mongo', 'aws-sdk']
33
+ * ```
34
+ */
35
+ autoInstrument?: AutoInstrumentKey[];
36
+ /**
37
+ * Intercept process.exit() to flush tracing data before termination.
38
+ * @default true
39
+ */
40
+ interceptProcessExit?: boolean;
41
+ /**
42
+ * Timeout (ms) for flushing tracing data on process.exit().
43
+ * @default 2000
44
+ */
45
+ exitFlushTimeoutMs?: number;
46
+ /**
47
+ * Optional logger for observability operations.
48
+ */
49
+ logger?: Logger;
16
50
  }
17
51
  export interface InitObservabilityResult {
18
52
  /** Service name used */
@@ -21,11 +55,16 @@ export interface InitObservabilityResult {
21
55
  tracingInitialized: boolean;
22
56
  /** Metrics server port */
23
57
  metricsPort: number;
58
+ /** Whether default metrics are currently registered (first call wins) */
59
+ defaultMetricsEnabled: boolean;
24
60
  }
25
61
  /**
26
62
  * Initialize observability for a service (metrics + tracing).
27
63
  * Call this once at service startup.
28
64
  *
65
+ * By default, this will collect Node.js runtime metrics (event loop, heap, GC, etc.)
66
+ * which are useful for monitoring service health even when idle.
67
+ *
29
68
  * @example
30
69
  * ```typescript
31
70
  * import { initObservability } from '@manifest-cyber/observability-ts';
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,MAAM,WAAW,uBAAuB;IACtC,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,8CAA8C;IAC9C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,8EAA8E;IAC9E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gEAAgE;IAChE,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,uBAAuB;IACtC,wBAAwB;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,sCAAsC;IACtC,kBAAkB,EAAE,OAAO,CAAC;IAC5B,0BAA0B;IAC1B,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,uBAAuB,GAC9B,OAAO,CAAC,uBAAuB,CAAC,CAsClC"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAuB,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACjF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAE9C,MAAM,WAAW,uBAAuB;IACtC,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,8CAA8C;IAC9C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,8EAA8E;IAC9E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gEAAgE;IAChE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,8EAA8E;IAC9E,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B;;;;;;;;;;;;;;OAcG;IACH,cAAc,CAAC,EAAE,iBAAiB,EAAE,CAAC;IACrC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,uBAAuB;IACtC,wBAAwB;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,sCAAsC;IACtC,kBAAkB,EAAE,OAAO,CAAC;IAC5B,0BAA0B;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,yEAAyE;IACzE,qBAAqB,EAAE,OAAO,CAAC;CAChC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,uBAAuB,GAC9B,OAAO,CAAC,uBAAuB,CAAC,CA4DlC"}
package/dist/init.js CHANGED
@@ -7,10 +7,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.initObservability = initObservability;
8
8
  const setup_1 = require("./tracing/setup");
9
9
  const server_1 = require("./metrics/server");
10
+ const provider_1 = require("./metrics/provider");
10
11
  /**
11
12
  * Initialize observability for a service (metrics + tracing).
12
13
  * Call this once at service startup.
13
14
  *
15
+ * By default, this will collect Node.js runtime metrics (event loop, heap, GC, etc.)
16
+ * which are useful for monitoring service health even when idle.
17
+ *
14
18
  * @example
15
19
  * ```typescript
16
20
  * import { initObservability } from '@manifest-cyber/observability-ts';
@@ -24,8 +28,17 @@ const server_1 = require("./metrics/server");
24
28
  * ```
25
29
  */
26
30
  async function initObservability(config) {
27
- const { serviceName, metricsPort = 9090, tracingEnabled = process.env.OTEL_TRACING_ENABLED !== 'false', samplingRatio = getSamplingRatio(), otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4317', } = config;
31
+ const { serviceName, metricsPort = 9090, tracingEnabled = process.env.OTEL_TRACING_ENABLED !== 'false', samplingRatio = getSamplingRatio(), otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4317', enableDefaultMetrics = true, autoInstrument, interceptProcessExit = true, exitFlushTimeoutMs = 2000, logger, } = config;
28
32
  let tracingInitialized = false;
33
+ // Initialize OpenTelemetry metrics provider with optional auto-instrumentation
34
+ await (0, provider_1.initMetricsProvider)({
35
+ serviceName,
36
+ environment: process.env.ENV,
37
+ prometheusPort: metricsPort,
38
+ prometheusDisableServer: true,
39
+ enableRuntimeMetrics: enableDefaultMetrics,
40
+ autoInstrument,
41
+ });
29
42
  // Initialize tracing
30
43
  if (tracingEnabled) {
31
44
  await (0, setup_1.initTracing)({
@@ -41,6 +54,10 @@ async function initObservability(config) {
41
54
  });
42
55
  tracingInitialized = true;
43
56
  }
57
+ // Install process.exit interceptor if tracing is enabled
58
+ if (tracingInitialized && interceptProcessExit) {
59
+ installExitInterceptor(exitFlushTimeoutMs, logger);
60
+ }
44
61
  // Start metrics server
45
62
  await (0, server_1.startMetricsServer)({
46
63
  serviceName,
@@ -50,6 +67,8 @@ async function initObservability(config) {
50
67
  serviceName,
51
68
  tracingInitialized,
52
69
  metricsPort,
70
+ // Runtime metrics enabled via OpenTelemetry host-metrics/runtime-metrics packages
71
+ defaultMetricsEnabled: enableDefaultMetrics,
53
72
  };
54
73
  }
55
74
  /**
@@ -74,4 +93,54 @@ function getSamplingRatio() {
74
93
  // 10% sampling in production
75
94
  return 0.1;
76
95
  }
96
+ // Symbol to mark process.exit as already intercepted
97
+ const EXIT_INTERCEPTOR_INSTALLED = Symbol('__exitInterceptorInstalled');
98
+ /**
99
+ * Intercepts process.exit() to flush tracing data before termination.
100
+ * This function is idempotent - calling it multiple times is safe.
101
+ */
102
+ function installExitInterceptor(timeoutMs, logger) {
103
+ // Check if our interceptor is already installed using a symbol property
104
+ if (process.exit[EXIT_INTERCEPTOR_INSTALLED]) {
105
+ return;
106
+ }
107
+ // Capture the original process.exit only once
108
+ const originalExit = process.exit.bind(process);
109
+ let isExiting = false;
110
+ const interceptedExit = ((code) => {
111
+ if (isExiting) {
112
+ originalExit(code);
113
+ return;
114
+ }
115
+ isExiting = true;
116
+ logger?.info('Process exiting, flushing tracing data...', { exitCode: code });
117
+ const forceExitTimer = setTimeout(() => {
118
+ logger?.warn?.('Tracing flush timed out, forcing exit', {
119
+ exitCode: code,
120
+ timeoutMs,
121
+ });
122
+ originalExit(code);
123
+ }, timeoutMs);
124
+ void (0, setup_1.shutdownTracing)(logger)
125
+ .then(() => {
126
+ logger?.info('Tracing data flushed successfully', { exitCode: code });
127
+ })
128
+ .catch((error) => {
129
+ logger?.error('Error flushing tracing data', { error, exitCode: code });
130
+ })
131
+ .finally(() => {
132
+ clearTimeout(forceExitTimer);
133
+ originalExit(code);
134
+ });
135
+ });
136
+ // Mark the intercepted function with a non-enumerable symbol property
137
+ Object.defineProperty(interceptedExit, EXIT_INTERCEPTOR_INSTALLED, {
138
+ value: true,
139
+ writable: false,
140
+ enumerable: false,
141
+ configurable: false,
142
+ });
143
+ process.exit = interceptedExit;
144
+ logger?.info('Process.exit interceptor installed', { timeoutMs });
145
+ }
77
146
  //# sourceMappingURL=init.js.map
package/dist/init.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AA2CH,8CAwCC;AAjFD,2CAA8C;AAC9C,6CAAsD;AAwBtD;;;;;;;;;;;;;;;GAeG;AACI,KAAK,UAAU,iBAAiB,CACrC,MAA+B;IAE/B,MAAM,EACJ,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oCAAoC,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;AACpE,CAAC"}
@@ -1,4 +1,3 @@
1
- import { CounterConfiguration, HistogramConfiguration, GaugeConfiguration } from 'prom-client';
2
1
  /**
3
2
  * Environment variable key for service name
4
3
  * Should match the key used in @manifest-cyber/logger-ts
@@ -41,197 +40,89 @@ export declare const BUCKETS: {
41
40
  };
42
41
  };
43
42
  /**
44
- * Wraps a Counter to automatically inject service_name label
43
+ * Reset cached service name (for testing)
44
+ * @internal
45
45
  */
46
- declare class ServiceAwareCounter<T extends string> {
47
- private counter;
48
- private serviceName;
49
- constructor(config: CounterConfiguration<T>, serviceName: string);
46
+ export declare function resetCachedServiceName(): void;
47
+ /**
48
+ * Set service name explicitly (used as fallback when environment variable is not set)
49
+ * @internal
50
+ */
51
+ export declare function setServiceName(name: string): void;
52
+ /**
53
+ * Public interface for a service-aware counter metric.
54
+ */
55
+ export interface ServiceCounter<T extends string = string> {
56
+ /** Increment the counter */
50
57
  inc(labels?: Partial<Record<T, string | number>>, value?: number): void;
51
58
  inc(value?: number): void;
59
+ /** Reset the counter (no-op for OTel counters, retained for API compatibility) */
52
60
  reset(): void;
53
- remove(...labelValues: string[]): void;
54
61
  }
55
62
  /**
56
- * Wraps a Histogram to automatically inject service_name label
63
+ * Public interface for a service-aware histogram metric.
57
64
  */
58
- declare class ServiceAwareHistogram<T extends string> {
59
- private histogram;
60
- private serviceName;
61
- constructor(config: HistogramConfiguration<T>, serviceName: string);
65
+ export interface ServiceHistogram<T extends string = string> {
66
+ /** Record an observation */
62
67
  observe(value: number): void;
63
68
  observe(labels: Partial<Record<T, string | number>>, value: number): void;
69
+ /** Reset the histogram (no-op for OTel histograms, retained for API compatibility) */
64
70
  reset(): void;
65
- remove(...labelValues: string[]): void;
71
+ /** Start a timer that records duration on completion */
66
72
  startTimer(labels?: Partial<Record<T, string | number>>): (labels?: Partial<Record<T, string | number>>) => number;
67
- zero(labels: Partial<Record<T, string | number>>): void;
73
+ /** Initialize bucket to zero (no-op for OTel, retained for API compatibility) */
74
+ zero(_labels: Partial<Record<T, string | number>>): void;
68
75
  }
69
76
  /**
70
- * Wraps a Gauge to automatically inject service_name label
77
+ * Public interface for a service-aware gauge metric.
71
78
  */
72
- declare class ServiceAwareGauge<T extends string> {
73
- private gauge;
74
- private serviceName;
75
- constructor(config: GaugeConfiguration<T>, serviceName: string);
76
- private addServiceLabel;
79
+ export interface ServiceGauge<T extends string = string> {
80
+ /** Increment the gauge */
77
81
  inc(labels?: Partial<Record<T, string | number>>, value?: number): void;
78
82
  inc(value?: number): void;
83
+ /** Decrement the gauge */
79
84
  dec(labels?: Partial<Record<T, string | number>>, value?: number): void;
80
85
  dec(value?: number): void;
86
+ /** Set the gauge to a specific value */
81
87
  set(labels: Partial<Record<T, string | number>>, value: number): void;
82
88
  set(value: number): void;
89
+ /** Set the gauge to current Unix timestamp */
83
90
  setToCurrentTime(labels?: Partial<Record<T, string | number>>): void;
91
+ /** Start a timer that sets duration on completion */
84
92
  startTimer(labels?: Partial<Record<T, string | number>>): (labels?: Partial<Record<T, string | number>>) => number;
93
+ /** Reset the gauge */
85
94
  reset(): void;
95
+ /** Remove a label set */
86
96
  remove(...labelValues: string[]): void;
87
97
  }
88
98
  /**
89
99
  * Creates a counter metric
90
- *
91
- * Counters are cumulative metrics that only increase.
92
- * Use for counting events like requests, errors, items processed, etc.
93
- *
94
- * The metric name will be automatically suffixed with '_total' if not already present.
95
- * A service_name label is automatically added to all observations.
96
- *
97
- * @param config Counter configuration (name, help, labelNames)
98
- * @returns A new Counter instance registered with the custom registry
99
- *
100
- * @example
101
- * ```typescript
102
- * import { createCounter } from '@manifest-cyber/observability-ts';
103
- *
104
- * // Simple counter - automatically suffixed with _total
105
- * export const requestsTotal = createCounter({
106
- * name: 'http_requests',
107
- * help: 'Total number of HTTP requests',
108
- * labelNames: ['method', 'status'],
109
- * });
110
- *
111
- * // Or provide the full name (won't duplicate suffix)
112
- * export const requestsTotal = createCounter({
113
- * name: 'http_requests_total',
114
- * help: 'Total number of HTTP requests',
115
- * labelNames: ['method', 'status'],
116
- * });
117
- *
118
- * // Later in code (service_name is automatically added):
119
- * requestsTotal.inc({ method: 'GET', status: '200' });
120
- * // Results in: http_requests_total{service_name="my-service",method="GET",status="200"}
121
- * ```
122
100
  */
123
- export declare function createCounter(config: Omit<CounterConfiguration<string>, 'registers'>): ServiceAwareCounter<string>;
101
+ export declare function createCounter(config: {
102
+ name: string;
103
+ help: string;
104
+ labelNames?: readonly string[];
105
+ }): ServiceCounter<string>;
124
106
  /**
125
107
  * Extended histogram configuration with optional unit parameter
126
108
  */
127
- export interface HistogramConfig extends Omit<HistogramConfiguration<string>, 'registers'> {
128
- /**
129
- * Optional unit for the metric (e.g., 'bytes', 'milliseconds', 'percent')
130
- * Default: 'seconds'
131
- *
132
- * Unit detection behavior:
133
- * - If the metric name already contains a unit suffix (e.g., '_seconds', '_bytes'),
134
- * that unit will be used and this parameter is ignored (with a warning if they differ)
135
- * - If no unit suffix is detected in the name, this unit will be appended
136
- * - If neither name has a unit nor this parameter is provided, '_seconds' is used as default
137
- *
138
- * @example
139
- * name: 'request_duration' → request_duration_seconds (default)
140
- * name: 'file_size', unit: 'bytes' → file_size_bytes
141
- * name: 'request_duration_milliseconds', unit: 'seconds' → request_duration_milliseconds (warns about conflict)
142
- */
109
+ export interface HistogramConfig {
110
+ name: string;
111
+ help: string;
112
+ labelNames?: readonly string[];
113
+ buckets?: number[];
143
114
  unit?: string;
144
115
  }
145
116
  /**
146
117
  * Creates a histogram metric
147
- *
148
- * Histograms track distributions of values, commonly used for durations.
149
- * They automatically track count, sum, and buckets.
150
- *
151
- * The metric name will be automatically suffixed with a unit (default: '_seconds') if not already present.
152
- * A service_name label is automatically added to all observations.
153
- *
154
- * **Unit detection and auto-suffixing:**
155
- * - If name already has a unit suffix (e.g., '_seconds', '_bytes'), it's used as-is
156
- * - If name lacks a unit suffix, the `unit` parameter is appended (default: 'seconds')
157
- * - If name has a unit AND `unit` parameter differs, a warning is logged and name's unit wins
158
- *
159
- * @param config Histogram configuration (name, help, labelNames, buckets, unit)
160
- * @returns A new Histogram instance registered with the custom registry
161
- *
162
- * @example
163
- * ```typescript
164
- * import { createHistogram, BUCKETS } from '@manifest-cyber/observability-ts';
165
- *
166
- * // Duration metric - automatically suffixed with _seconds (default)
167
- * export const requestDuration = createHistogram({
168
- * name: 'http_request_duration',
169
- * help: 'HTTP request duration in seconds',
170
- * labelNames: ['method', 'route'],
171
- * buckets: BUCKETS.DURATION.HTTP,
172
- * });
173
- * // Result: http_request_duration_seconds
174
- *
175
- * // File size metric with custom unit
176
- * export const fileSize = createHistogram({
177
- * name: 'file_size',
178
- * help: 'File size in bytes',
179
- * unit: 'bytes',
180
- * buckets: BUCKETS.SIZE.MEDIUM,
181
- * });
182
- * // Result: file_size_bytes
183
- *
184
- * // Provide full name (won't duplicate suffix)
185
- * export const fileSize2 = createHistogram({
186
- * name: 'file_size_bytes',
187
- * help: 'File size in bytes',
188
- * buckets: BUCKETS.SIZE.MEDIUM,
189
- * });
190
- * // Result: file_size_bytes
191
- *
192
- * // Conflict scenario (logs warning, uses name's unit)
193
- * export const duration = createHistogram({
194
- * name: 'processing_time_milliseconds',
195
- * unit: 'seconds', // Warning: conflicts with _milliseconds in name
196
- * buckets: BUCKETS.DURATION.FAST,
197
- * });
198
- * // Result: processing_time_milliseconds (name wins, warning logged)
199
- *
200
- * // Later in code (service_name is automatically added):
201
- * const duration = (Date.now() - start) / 1000;
202
- * requestDuration.observe({ method: 'GET', route: '/api/users' }, duration);
203
- * ```
204
118
  */
205
- export declare function createHistogram(config: HistogramConfig): ServiceAwareHistogram<string>;
119
+ export declare function createHistogram(config: HistogramConfig): ServiceHistogram<string>;
206
120
  /**
207
121
  * Creates a gauge metric
208
- *
209
- * Gauges represent a value that can go up or down.
210
- * Use for measuring current state like memory usage, active connections, queue depth, etc.
211
- *
212
- * The metric name should follow Prometheus naming conventions.
213
- * A service_name label is automatically added to all observations.
214
- *
215
- * @param config Gauge configuration (name, help, labelNames)
216
- * @returns A new Gauge instance registered with the custom registry
217
- *
218
- * @example
219
- * ```typescript
220
- * import { createGauge } from '@manifest-cyber/observability-ts';
221
- *
222
- * // Simple gauge metric
223
- * export const activeConnections = createGauge({
224
- * name: 'active_connections',
225
- * help: 'Number of active connections',
226
- * labelNames: ['type'],
227
- * });
228
- *
229
- * // Later in code (service_name is automatically added):
230
- * activeConnections.inc({ type: 'websocket' }); // increment
231
- * activeConnections.dec({ type: 'websocket' }); // decrement
232
- * activeConnections.set({ type: 'http' }, 42); // set to specific value
233
- * ```
234
122
  */
235
- export declare function createGauge(config: Omit<GaugeConfiguration<string>, 'registers'>): ServiceAwareGauge<string>;
236
- export {};
123
+ export declare function createGauge(config: {
124
+ name: string;
125
+ help: string;
126
+ labelNames?: readonly string[];
127
+ }): ServiceGauge<string>;
237
128
  //# sourceMappingURL=builders.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"builders.d.ts","sourceRoot":"","sources":["../../src/metrics/builders.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,oBAAoB,EACpB,sBAAsB,EACtB,kBAAkB,EACnB,MAAM,aAAa,CAAC;AAGrB;;;GAGG;AACH,eAAO,MAAM,oBAAoB,iBAAiB,CAAC;AAEnD;;;;;GAKG;AACH,eAAO,MAAM,OAAO;IAClB;;OAEG;;QAED,8DAA8D;;QAG9D,iEAAiE;;QAGjE,gFAAgF;;QAGhF,uEAAuE;;QAGvE,sEAAsE;;;IAIxE;;OAEG;;QAED,wDAAwD;;QAGxD,mDAAmD;;QAGnD,wDAAwD;;QAGxD,uDAAuD;;;CAG1D,CAAC;AAmDF;;GAEG;AACH,cAAM,mBAAmB,CAAC,CAAC,SAAS,MAAM;IACxC,OAAO,CAAC,OAAO,CAAa;IAC5B,OAAO,CAAC,WAAW,CAAS;gBAEhB,MAAM,EAAE,oBAAoB,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM;IAKhE,GAAG,CAAC,M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