All files metrics.ts

93.91% Statements 139/148
89.18% Branches 66/74
100% Functions 20/20
93.91% Lines 139/148

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305                                3x     3x                                                   1x 1x 1x 1x       1x 1x 1x       1x 1x 1x           41x   41x   41x 41x 41x   41x     41x 41x 4x 4x   37x         6x 2x 2x   4x 4x 1x   4x 2x   4x 1x   4x 4x 1x   4x 4x 4x 4x     4x 4x 4x 4x       6x 1x 1x   5x 1x 1x   4x 4x 4x       6x 1x 1x   5x 1x 1x   4x 4x 4x       11x 1x 1x   10x 1x 1x   9x 9x 9x 9x       5x 1x 1x   4x 1x 1x   3x 3x 1x 1x   2x 2x 2x 2x       5x 5x       2x         41x 41x 41x 41x     41x 8x             33x 25x 8x 8x       41x       37x 37x 37x     37x 37x       37x         37x 10x   37x 37x       37x 37x 37x 37x 37x 37x 37x 37x 37x                   12x 4x     8x 2x   6x   8x 8x       4x 1x   3x 3x 3x       4x 1x   3x 3x 3x               1x       3x       3x      
// SPDX-FileCopyrightText: 2025-2026 Anaconda, Inc
// SPDX-License-Identifier: Apache-2.0
 
import { type AttrMap } from './types.js';
import { Configuration, type EndpointTuple } from './config.js';
import { ResourceAttributes } from './attributes.js';
import { AnacondaCommon } from "./common.js";
import { MetricExporterShim } from './exporter_shims.js';
 
// ----- your value imports (keep as-is) -----
import { diag, DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api';
import * as sdkMetricsNS from '@opentelemetry/sdk-metrics';
const {
  MeterProvider,
  PeriodicExportingMetricReader,
  ConsoleMetricExporter,
} = sdkMetricsNS;
 
import * as httpNS from '@opentelemetry/exporter-metrics-otlp-http';
const { OTLPMetricExporter: OTLPMetricExporterHTTP } = httpNS;
 
 
// ----- type-only imports -----
import type {
  Meter,
  UpDownCounter,
  Counter,
  Histogram,
  Gauge,
} from '@opentelemetry/api';
 
import type {
  PushMetricExporter,
  ResourceMetrics,
  MeterProvider as _MeterProvider,
  PeriodicExportingMetricReader as _PeriodicExportingMetricReader,
  PeriodicExportingMetricReaderOptions as _PeriodicExportingMetricReaderOptions,
} from '@opentelemetry/sdk-metrics';
 
// ----- local type aliases that REUSE the value names -----
type MeterProvider = _MeterProvider;
type PeriodicExportingMetricReader = _PeriodicExportingMetricReader;
type PeriodicExportingMetricReaderOptions = _PeriodicExportingMetricReaderOptions;
 
export class CounterArgs {
    name: string = "";
    by?: number = 1;
    forceUpDownCounter?: boolean = false;
    attributes?: AttrMap = {}
}
 
export class HistogramArgs {
    name: string = "";
    value: number = 0;
    attributes?: AttrMap = {};
}
 
export class GaugeArgs {
    name: string = "";
    value: number = 0;
    attributes?: AttrMap = {};
}
 
export class AnacondaMetrics extends AnacondaCommon {
    private reader: PeriodicExportingMetricReader | undefined;
    /** @internal Exposed for test assertions only; not part of the public API. */
    mapOfCounters: Record<string, [UpDownCounter | Counter, boolean]> = {};
    /** @internal Exposed for test assertions only; not part of the public API. */
    mapOfHistograms: Record<string, Histogram> = {};
    /** @internal Exposed for test assertions only; not part of the public API. */
    mapOfGauges: Record<string, Gauge> = {};
    meterProvider: MeterProvider | undefined = undefined
    meter: Meter | null = null;
    parentExporter: MetricExporterShim | undefined
    testLastBy: number = 0
 
    constructor(config: Configuration, attributes: ResourceAttributes) {
        super(config, attributes);
        if (this.isValidOtelUrl(this.config.getMetricsEndpointTuple()[0].href) === false) {
            console.error(`The metrics endpoint URL is not valid: ${this.config.getMetricsEndpointTuple()[0].href}`)
            return
        }
        this.setup()
    }
 
    async changeConnection(endpoint: URL | undefined, authToken: string | undefined,
                           certFile: string | undefined, userId: string | undefined): Promise<boolean> {
        if (endpoint && this.isValidOtelUrl(endpoint!.href) === false) {
            console.error(`The metrics endpoint URL is not valid: ${endpoint!.href}`)
            return false
        }
        let [url, token, cert] = this.config.getMetricsEndpointTuple()
        if (endpoint !== url && endpoint !== undefined) {
            this.config.metricsEndpoint![0] = endpoint
        }
        if (authToken !== token) {
            this.config.metricsEndpoint![1] = authToken
        }
        if (certFile !== cert) {
            this.config.metricsEndpoint![2] = certFile
        }
        let id = userId?.trim()
        if (typeof id === 'string' && id.length > 0) {
            this.attributes.userId = id
        }
        var [scheme, ep] = this.transformURL(this.config.metricsEndpoint![0])
        var headers = this.makeHeaders(scheme, authToken)
        var exporter = this.makeExporter(scheme, ep, headers)
        Iif (exporter === undefined) {
            return false
        }
        await this.reader?.forceFlush()
        var oldExporter = await this.parentExporter?.swapExporter(exporter!)
        await oldExporter?.shutdown()
        return true
    }
 
    recordHistogram(args: HistogramArgs): boolean {
        if (!this.meter) {
            this._warn("Meter is not initialized properly. Ensure that the AnacondaMetrics instance is properly set up.")
            return false
        }
        if (!this.isValidName(args.name)) {
            this._warn(`Metric name '${args.name}' is not a valid name (^[A-Za-z][A-Za-z_0-9]+$).`)
            return false
        }
        var histogram = this.getHistogram(args.name)
        histogram.record(args.value!, this.makeEventAttributes(args.attributes));
        return true
    }
 
    recordGauge(args: GaugeArgs): boolean {
        if (!this.meter) {
            this._warn("Meter is not initialized properly. Ensure that the AnacondaMetrics instance is properly set up.")
            return false
        }
        if (!this.isValidName(args.name)) {
            this._warn(`Metric name '${args.name}' is not a valid name (^[A-Za-z][A-Za-z_0-9]+$).`)
            return false
        }
        var gauge = this.getGauge(args.name)
        gauge.record(args.value, this.makeEventAttributes(args.attributes));
        return true
    }
 
    incrementCounter(args: CounterArgs): boolean {
        if (!this.meter) {
            this._warn("Meter is not initialized properly. Ensure that the AnacondaMetrics instance is properly set up.")
            return false
        }
        if (!this.isValidName(args.name)) {
            this._warn(`Metric name '${args.name}' is not a valid name (^[A-Za-z][A-Za-z_0-9]+$).`)
            return false
        }
        var [counter, isUpDown] = this.getCounter(args.name, args.forceUpDownCounter!)
        let by: number = args.by ? Math.abs(args.by!) : 1;
        counter.add(by, this.makeEventAttributes(args.attributes))
        return true
    }
 
    decrementCounter(args: CounterArgs): boolean {
        if (!this.meter) {
            this._warn("Meter is not initialized properly. Ensure that the AnacondaMetrics instance is properly set up.")
            return false
        }
        if (!this.isValidName(args.name)) {
            this._warn(`Metric name '${args.name}' is not a valid name (^[A-Za-z][A-Za-z_0-9]+$).`)
            return false
        }
        var [counter, isUpDown] = this.getCounter(args.name, true)
        if (isUpDown === false) {
            this._warn(`Metric name '${args.name}' is not a UpDownCounter, decrement is not allowed.`)
            return false
        }
        let by: number = args.by ? -Math.abs(args.by!) : -1;
        this.testLastBy = by
        counter.add(by, this.makeEventAttributes(args.attributes))
        return true
    }
 
    async flush(): Promise<void> {
        try {
            await this.reader?.forceFlush()
        } catch (error) {
            // Log export failures instead of crashing the application
            // This matches Python SDK behavior where export failures are logged
            this._warn(`Metric export failed: ${this.errorMessage(error)}`)
        }
    }
 
    private makeExporter(scheme: string, url: URL, httpHeaders: Record<string,string>): PushMetricExporter | undefined {
        var urlStr = url.href
        var exporter: PushMetricExporter | undefined = undefined
        this._debug(`Creating metrics exporter at endpoint ${urlStr}`)
        Iif (scheme === 'grpc:' || scheme === 'grpcs:') {
            this._warn(`GRPC endpoints are no longer supported. Please use HTTP/HTTPS endpoints instead: ${urlStr}`)
            return undefined
        } else if (scheme === 'http:' || scheme === 'https:') {
            exporter = new OTLPMetricExporterHTTP({
                url: urlStr,
                headers: httpHeaders,
                temporalityPreference: this.config.getUseCumulativeMetrics() ?
                    httpNS.AggregationTemporalityPreference.CUMULATIVE :
                    httpNS.AggregationTemporalityPreference.DELTA
            });
        } else if (scheme === 'console:') {
            exporter = new ConsoleMetricExporter()
        } else if (scheme === 'devnull:') {
            exporter = new NoopMetricExporter()
        } else E{
            this._warn(`Received bad scheme for metrics: ${scheme}!`)
        }
        return exporter
    }
 
    private makeReader(scheme: string, url: URL, httpHeaders: Record<string,string>): PeriodicExportingMetricReader | undefined {
        this._debug(`Creating Reader for endpoint type '${scheme}'.`)
        var exporter = this.makeExporter(scheme, url, httpHeaders)
        Iif (exporter === undefined) {
            return undefined
        }
        this.parentExporter = new MetricExporterShim(exporter!)
        const reader = new PeriodicExportingMetricReader({
            exporter: this.parentExporter!,
            exportIntervalMillis: this.metricsExportIntervalMs
        });
        return reader
    }
 
 
    private setup(): void {
        if (this.config.useDebug) {
            diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
        }
        var [endpoint, authToken, certFile] = this.config.getMetricsEndpointTuple()
        Iif (!this.isValidOtelUrl(endpoint.href)) {
            console.error(`The metrics endpoint URL is not valid: ${endpoint.href}`)
            return
        }
        var [scheme, ep] = this.transformURL(endpoint)
        var headers = this.makeHeaders(scheme, authToken)
        const reader: PeriodicExportingMetricReader | undefined = this.makeReader(scheme, ep, headers)
        if (reader != undefined) {
            this.reader = reader
            this.meterProvider = new MeterProvider({ readers: [this.reader!], resource: this.resources })
            this.meter = this.meterProvider.getMeter(this.serviceName, this.serviceVersion)
            if (this.meter) {
                this._debug("Meter created successfully.")
            } else E{
                this._warn("Meter was not created!")
            }
        } else E{
            this._warn("Periodic Metric Reader was not created!")
        }
    }
 
    private getCounter(metricName: string, forceUpDownCounter: boolean): [UpDownCounter | Counter, boolean] {
        if (metricName in this.mapOfCounters) {
            return this.mapOfCounters[metricName]
        }
        var counter: Counter | UpDownCounter
        if (forceUpDownCounter) {
            counter = this.meter!.createUpDownCounter(metricName)
        } else {
            counter = this.meter!.createCounter(metricName)
        }
        this.mapOfCounters[metricName] = [counter, forceUpDownCounter]
        return [counter, forceUpDownCounter]
    }
 
    private getHistogram(metricName: string): Histogram {
        if (metricName in this.mapOfHistograms) {
            return this.mapOfHistograms[metricName]
        }
        var histogram: Histogram = this.meter!.createHistogram(metricName)
        this.mapOfHistograms[metricName] = histogram
        return histogram
    }
 
    private getGauge(metricName: string): Gauge {
        if (metricName in this.mapOfGauges) {
            return this.mapOfGauges[metricName]
        }
        var gauge: Gauge = this.meter!.createGauge(metricName)
        this.mapOfGauges[metricName] = gauge
        return gauge
    }
}
 
export class NoopMetricExporter implements PushMetricExporter {
    constructor(_options?: any) {}
 
    export(_metrics: ResourceMetrics, resultCallback: (result: { code: number }) => void): void {
        resultCallback({ code: 0 });
    }
 
    async shutdown(): Promise<void> {
        return Promise.resolve();
    }
 
    async forceFlush(): Promise<void> {
        return Promise.resolve();
    }
}