All files traces.ts

90.29% Statements 93/103
85.45% Branches 47/55
100% Functions 16/16
90.29% Lines 93/103

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                              3x       3x     3x     3x                                             11x 11x 11x       5x 5x       5x 5x 5x       9x         32x           11x 8x   11x       32x 32x 4x 4x   28x         6x 2x 2x   4x 4x 1x   4x 2x   4x 1x   4x 4x 1x   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       32x 32x 32x 32x     32x 8x       24x 16x 8x 8x       32x         28x 28x     28x 28x             28x     28x 28x       28x 28x 28x 28x 28x 28x 28x 28x       28x                   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 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;
 
 
// ----- 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';
// ----- local type aliases (reuse runtime names) -----
type SpanExporter = _SpanExporter;
type ReadableSpan = _ReadableSpan;
type BatchSpanProcessor = _BatchSpanProcessor;
type NodeTracerProvider = _NodeTracerProvider;
 
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 headers = this.makeHeaders(scheme, authToken)
        var exporter = this.makeExporter(scheme, ep, headers)
        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>): SpanExporter | undefined {
        var exporter: SpanExporter | undefined = undefined
        var urlStr = url.href
        this._debug(`Creating traces 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 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>,
): BatchSpanProcessor | undefined {
        var exporter = this.makeExporter(scheme, url, httpHeaders)
        Iif (exporter === undefined) {
            return undefined
        }
        this.parentExporter = new SpanExporterShim(exporter!)
        return new BatchSpanProcessor(this.parentExporter!, {
            scheduledDelayMillis: this.config.getTracesExportIntervalMs()
        })
    }
 
 
    private setup(): void {
        Iif (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}'.`)
        const headers: Record<string,string> = authToken ? { 'Authorization': `Bearer ${authToken}` } : {}
        const processor: BatchSpanProcessor | undefined = this.makeBatchProcessor(scheme, ep, headers)
        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();
    }
}