All files metrics.ts

95.03% Statements 134/141
88.15% Branches 67/76
100% Functions 18/18
95.03% Lines 134/141

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                                3x     3x     3x     3x                                                     1x 1x 1x 1x       1x 1x 1x         47x 47x 47x 47x   47x     47x 47x 4x 4x   43x         6x 2x 2x   4x 4x 1x   4x 2x   4x 1x   4x 4x 1x   4x 4x 4x 4x 4x     4x 4x 4x 4x       6x 1x 1x   5x 1x 1x   4x 4x 4x       11x 1x 1x   10x 5x 5x   5x 5x 5x 5x       5x 1x 1x   4x 1x 1x   3x 3x 1x 1x   2x 2x 2x 2x       5x 5x       2x           47x 47x 47x 47x 8x 8x             39x 8x             31x 23x 8x 8x       47x       43x 43x 43x     43x 43x       43x       47x 47x 2x 2x 1x   1x     47x       43x 9x   43x 43x       43x 43x 43x 43x 43x 43x 43x 43x 43x 43x                   8x 4x     4x 2x   2x   4x 4x       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;
 
import * as grpcExporterNS from '@opentelemetry/exporter-metrics-otlp-grpc';
const { OTLPMetricExporter: OTLPMetricExporterGRPC } = grpcExporterNS;
 
import grpc from '@grpc/grpc-js';
const { ChannelCredentials } = grpc;
 
// ----- type-only imports -----
import type {
  Meter,
  UpDownCounter,
  Counter,
  Histogram,
} from '@opentelemetry/api';
 
import type {
  PushMetricExporter,
  ResourceMetrics,
  MeterProvider as _MeterProvider,
  PeriodicExportingMetricReader as _PeriodicExportingMetricReader,
  PeriodicExportingMetricReaderOptions as _PeriodicExportingMetricReaderOptions,
} from '@opentelemetry/sdk-metrics';
 
import type { ChannelCredentials as _ChannelCredentials } from '@grpc/grpc-js';
 
// ----- local type aliases that REUSE the value names -----
type MeterProvider = _MeterProvider;
type PeriodicExportingMetricReader = _PeriodicExportingMetricReader;
type ChannelCredentials = _ChannelCredentials;
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 AnacondaMetrics extends AnacondaCommon {
    private reader: PeriodicExportingMetricReader | undefined;
    mapOfCounters: Record<string, [UpDownCounter | Counter, boolean]> = {};
    mapOfHistograms: Record<string, Histogram> = {};
    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 creds: ChannelCredentials | undefined = this.readCredentials(scheme, this.config.metricsEndpoint![2])
        var headers = this.makeHeaders(scheme, authToken)
        var exporter = this.makeExporter(scheme, ep, headers, creds)
        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
    }
 
    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>,
                         creds?: ChannelCredentials): PushMetricExporter | undefined {
        var urlStr = url.href
        var exporter: PushMetricExporter | undefined = undefined
        this._debug(`Creating metrics exporter at endpoint ${urlStr}`)
        if (scheme === 'grpc:' || scheme === 'grpcs:') {
            urlStr = `${url.hostname}:${url.port}`
            exporter = new OTLPMetricExporterGRPC({
                url: urlStr,
                credentials: creds,
                temporalityPreference: this.config.getUseCumulativeMetrics() ?
                    httpNS.AggregationTemporalityPreference.CUMULATIVE :
                    httpNS.AggregationTemporalityPreference.DELTA
            });
        } 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>, creds?: ChannelCredentials): PeriodicExportingMetricReader | undefined {
        this._debug(`Creating Reader for endpoint type '${scheme}'.`)
        var exporter = this.makeExporter(scheme, url, httpHeaders, creds)
        Iif (exporter === undefined) {
            return undefined
        }
        this.parentExporter = new MetricExporterShim(exporter!)
        const reader = new PeriodicExportingMetricReader({
            exporter: this.parentExporter!,
            exportIntervalMillis: this.metricsExportIntervalMs
        });
        return reader
    }
 
    private readCredentials(scheme: string, certFile?: string): ChannelCredentials | undefined {
        var creds: ChannelCredentials | undefined = undefined
        if (certFile && scheme === ("grpcs:")) {
            const certContent = this.readCertFile(certFile)
            if (certContent) {
                creds = ChannelCredentials.createSsl(Buffer.from(certContent))
            } else {
                this._warn(`Failed to read certificate file: ${certFile}`)
            }
        }
        return creds
    }
 
    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 creds: ChannelCredentials | undefined = this.readCredentials(scheme, certFile)
        var headers = this.makeHeaders(scheme, authToken)
        const reader: PeriodicExportingMetricReader | undefined = this.makeReader(scheme, ep, headers, creds)
        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
    }
}
 
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();
    }
}