All files traces.ts

93.96% Statements 109/116
90.16% Branches 55/61
100% Functions 17/17
93.96% Lines 109/116

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                              3x     3x     3x     3x     3x     3x                                                 11x 11x 11x       5x 5x       5x 5x 5x       9x         41x           11x 8x   11x       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 4x         11x 2x 9x 1x   8x   11x 11x     11x   11x       6x 6x       3x         11x 11x 2x   9x 8x     1x     1x   1x         41x 41x 41x 41x 9x 9x         32x 8x       24x 16x 8x 8x       41x         37x 37x     37x 37x           46x 46x 4x 4x 3x   1x     46x       37x 1x   37x 37x       37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x       37x                   1x       3x       1x      
// SPDX-FileCopyrightText: 2025-2026 Anaconda, Inc
// SPDX-License-Identifier: Apache-2.0
 
import * as fs from 'fs';
 
import { type AttrMap, type CarrierMap, TraceArgs, type ASpan } from './types.js'
import { Configuration } from './config.js'
import { ResourceAttributes } from './attributes.js'
import { AnacondaCommon } from "./common.js"
import { SpanExporterShim } from './exporter_shims.js';
 
// ----- values -----
import { diag, DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api';
 
import * as otlpTraceHttpNS from '@opentelemetry/exporter-trace-otlp-http';
const { OTLPTraceExporter: OTLPTraceExporterHTTP } = otlpTraceHttpNS;
 
import * as otlpTraceGrpcNS from '@opentelemetry/exporter-trace-otlp-grpc';
const { OTLPTraceExporter: OTLPTraceExporterGRPC } = otlpTraceGrpcNS;
 
import * as sdkTraceBaseNS from '@opentelemetry/sdk-trace-base';
const { ConsoleSpanExporter, BatchSpanProcessor } = sdkTraceBaseNS;
 
import * as sdkTraceNodeNS from '@opentelemetry/sdk-trace-node';
const { NodeTracerProvider } = sdkTraceNodeNS;
 
import * as api from '@opentelemetry/api';
const { trace, propagation } = api;
 
import grpc from '@grpc/grpc-js';
const { ChannelCredentials } = grpc;
 
// ----- types -----
import type { Span, Context } from '@opentelemetry/api';
import type {
  SpanExporter as _SpanExporter,
  ReadableSpan as _ReadableSpan,
  BatchSpanProcessor as _BatchSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import type { NodeTracerProvider as _NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import type { ChannelCredentials as _ChannelCredentials } from '@grpc/grpc-js';
 
// ----- local type aliases (reuse runtime names) -----
type SpanExporter = _SpanExporter;
type ReadableSpan = _ReadableSpan;
type BatchSpanProcessor = _BatchSpanProcessor;
type NodeTracerProvider = _NodeTracerProvider;
type ChannelCredentials = _ChannelCredentials;
 
export class ASpanImpl implements ASpan {
    readonly tracer: AnacondaTrace
    readonly ctx: Context;
    readonly span: Span;
 
    constructor(tracer: AnacondaTrace, ctx: Context, span: Span) {
        this.tracer = tracer
        this.ctx = ctx
        this.span = span
    }
 
    addEvent(name: string, attributes: AttrMap = {}): this {
        this.span.addEvent(name, attributes)
        return this
    }
 
    getCurrentCarrier(): CarrierMap {
        let carrier: CarrierMap = {}
        propagation.inject(this.ctx, carrier)
        return carrier
    }
 
    end(): void {
        this.span.end();
    }
}
 
export class AnacondaTrace extends AnacondaCommon {
    provider: NodeTracerProvider | null = null
    private processor: BatchSpanProcessor | undefined
    private _tracer: api.Tracer | undefined
    parentExporter: SpanExporterShim | undefined
 
    get tracer(): api.Tracer {
        if (this._tracer === undefined) {
            this._tracer = trace.getTracer(this.serviceName, this.serviceVersion)
        }
        return this._tracer!
    }
 
    constructor(config: Configuration, attributes: ResourceAttributes) {
        super(config, attributes)
        if (this.isValidOtelUrl(this.config.getTraceEndpointTuple()[0].href) === false) {
            console.error(`The traces endpoint URL is not valid: ${this.config.getTraceEndpointTuple()[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 traces endpoint URL is not valid: ${endpoint!.href}`)
            return false
        }
        let [url, token, cert] = this.config.getTraceEndpointTuple()
        if (endpoint !== url && endpoint !== undefined) {
            this.config.traceEndpoint![0] = endpoint
        }
        if (authToken !== token) {
            this.config.traceEndpoint![1] = authToken
        }
        if (certFile !== cert) {
            this.config.traceEndpoint![2] = certFile
        }
        let id = userId?.trim()
        if (typeof id === 'string' && id.length > 0) {
            this.attributes.userId = id
        }
        var [scheme, ep] = this.transformURL(this.config.traceEndpoint![0])
        var creds: ChannelCredentials | undefined = this.readCredentials(scheme, this.config.traceEndpoint![2])
        var headers = this.makeHeaders(scheme, authToken)
        var exporter = this.makeExporter(scheme, ep, headers, creds)
        Iif (exporter === undefined) {
            return false
        }
        await this.processor?.forceFlush()
        var oldExporter = await this.parentExporter?.swapExporter(exporter!)
        await oldExporter?.shutdown()
        return true
    }
 
    getTrace(name: string, attributes?: AttrMap, carrier?: CarrierMap, parentObject?: ASpan): ASpan {
        let ctx
        if (parentObject) { // Highest precidence if both this and carrier are passed
            ctx = propagation.extract(api.context.active(), parentObject!.getCurrentCarrier())
        } else if (carrier) { // Lowest precidence if both this and parentObject are passed.
            ctx = propagation.extract(api.context.active(), carrier!)
        } else {
            ctx = api.context.active()
        }
        ctx = this.embedUserIdIfMissing(ctx)
        const rootSpan = this.tracer.startSpan(name, {
                attributes: this.makeEventAttributes(attributes)
            }, ctx)
        const ctxWithSpan = trace.setSpan(ctx, rootSpan)
 
        return new ASpanImpl(this, ctxWithSpan, rootSpan)
    }
 
    async flush(): Promise<void> {
        try {
            await this.processor?.forceFlush()
        } catch (error) {
            // Log export failures instead of crashing the application
            // This matches Python SDK behavior where export failures are logged
            this._warn(`Trace export failed: ${this.errorMessage(error)}`)
        }
    }
 
    private embedUserIdIfMissing(ctx: Context): Context {
        const currentBaggage = propagation.getBaggage(ctx)
        if (currentBaggage?.getEntry("user.id")?.value) {
            return ctx
        }
        if (this.attributes.userId === "") {
            return ctx
        }
        let newBaggage: api.Baggage
        Iif (currentBaggage) {
            newBaggage = currentBaggage.setEntry("user.id", { value: this.attributes.userId })
        } else {
            newBaggage = propagation.createBaggage({ "user.id": { value: this.attributes.userId }})
        }
        return propagation.setBaggage(ctx, newBaggage)
    }
 
    private makeExporter(scheme: string, url: URL, httpHeaders: Record<string,string>,
                         creds?: ChannelCredentials): SpanExporter | undefined {
        var exporter: SpanExporter | undefined = undefined
        var urlStr = url.href
        this._debug(`Creating traces exporter at endpoint ${urlStr}`)
        if (scheme === 'grpc:' || scheme === 'grpcs:') {
            urlStr = `${url.hostname}:${url.port}`
            exporter = new OTLPTraceExporterGRPC({
                url: urlStr,
                headers: httpHeaders,
                credentials: creds
            });
        } else if (scheme === 'http:' || scheme === 'https:') {
            exporter = new OTLPTraceExporterHTTP({
                url: urlStr,
                headers: httpHeaders
            });
        } else if (scheme === 'console:') {
            exporter = new ConsoleSpanExporter()
        } else if (scheme === 'devnull:') {
            exporter = new NoopSpanExporter()
        } else E{
            this._warn(`Received bad scheme for tracing: ${scheme}!`)
        }
        return exporter
    }
 
    makeBatchProcessor(scheme: string, url: URL, httpHeaders: Record<string,string>,
                       creds?: ChannelCredentials): BatchSpanProcessor | undefined {
        var exporter = this.makeExporter(scheme, url, httpHeaders, creds)
        Iif (exporter === undefined) {
            return undefined
        }
        this.parentExporter = new SpanExporterShim(exporter!)
        return new BatchSpanProcessor(this.parentExporter!, {
            scheduledDelayMillis: this.config.getTracesExportIntervalMs()
        })
    }
 
    readCredentials(scheme: string, certFile?: string): ChannelCredentials | undefined {
        var creds: ChannelCredentials | undefined = undefined
        if (certFile !== undefined && 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.getTraceEndpointTuple()
        Iif (!this.isValidOtelUrl(endpoint.href)) {
            console.error(`The traces endpoint URL is not valid: ${endpoint.href}`)
            return
        }
        const scheme = endpoint.protocol
        const ep = new URL(endpoint.href)
        this._debug(`Connecting to traces endpoint '${ep.href}'.`)
        ep.protocol = ep.protocol.replace("grpcs:", "https:")
        ep.protocol = ep.protocol.replace("grpc:", "http:")
        var creds: ChannelCredentials | undefined = this.readCredentials(scheme, certFile)
        const headers: Record<string,string> = authToken ? { 'Authorization': `Bearer ${authToken}` } : {}
        const processor: BatchSpanProcessor | undefined = this.makeBatchProcessor(scheme, ep, headers, creds)
        if (processor) {
            this.processor = processor
            this.provider = new NodeTracerProvider({
                spanProcessors: [this.processor],
                resource: this.resources
            })
            this.provider!.register()
        } else E{
            console.warn('Failed to create a batch processor for tracing!')
        }
    }
}
 
export class NoopSpanExporter implements SpanExporter {
    export(_spans: ReadableSpan[], resultCallback: (result: { code: number }) => void): void {
        // Immediately report success without doing anything
        resultCallback({ code: 0 });
    }
 
    shutdown(): Promise<void> {
        return Promise.resolve();
    }
 
    forceFlush(): Promise<void> {
        return Promise.resolve();
    }
}