diff --git a/src/custom-otlp-trace-exporter.ts b/src/custom-otlp-trace-exporter.ts new file mode 100644 index 0000000..5c096fd --- /dev/null +++ b/src/custom-otlp-trace-exporter.ts @@ -0,0 +1,36 @@ +import { + addHrTimes, + millisToHrTime, + OTLPTraceExporter, + ReadableSpan, +} from '../deps.ts'; + +const LIMIT = new Date('2000-01-01').getTime() / 1000; +const isMonotonicHrTime = (hrTime: [number, number]): boolean => + hrTime[0] < LIMIT; +// @ts-ignore +const variableTimeOrigin = () => new Date() - performance.now(); + +export class CustomOTLPTraceExporter extends OTLPTraceExporter { + export(spans: ReadableSpan[], resultCallback: (result: any) => void): void { + // Current timeOrigin + const hrTime = millisToHrTime(variableTimeOrigin()); + // Just before exporting + for (const span of spans) { + // Only if the spans were created with the monotonic clock + if (!isMonotonicHrTime(span.startTime)) { + return; + } + // Convert the times to wall-clock + // @ts-ignore + span.startTime = addHrTimes(span.startTime, hrTime); + // @ts-ignore + span.endTime = addHrTimes(span.endTime, hrTime); + for (const event of span.events) { + event.time = addHrTimes(event.time, hrTime); + } + } + // And proceed to the regular export + return super.export(spans, resultCallback); + } +} diff --git a/src/main.ts b/src/main.ts index 909104b..5372ae7 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,7 +4,7 @@ import { BatchTracedSpanProcessor, // ConsoleSpanExporter, dotenvLoad, - OTLPTraceExporter, + // OTLPTraceExporter, redis, Resource, SemanticResourceAttributes, @@ -16,6 +16,7 @@ import { DenoKvCache } from './cache/deno-kv-cache.ts'; import { RedisCache } from './cache/redis-cache.ts'; import { createRequestHandler } from './create-request-handler.ts'; import { CustomTracerProvider } from './custom-tracer-provider.ts'; +import { CustomOTLPTraceExporter } from './custom-otlp-trace-exporter.ts'; import { instrumentRequestHandler } from './instrument-request-handler.ts'; import { TimeSpanProcessor } from './time-span-processor.ts'; import { sanitizeBasePath, sanitizeUpstreamOrigin } from './utils.ts'; @@ -51,7 +52,7 @@ const provider = new CustomTracerProvider({ [SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]: 'javascript', }), }); -provider.addSpanProcessor(new TimeSpanProcessor()); +//provider.addSpanProcessor(new TimeSpanProcessor()); provider.addSpanProcessor( new SimpleSpanProcessor(new ServerTimingSpanExporter()), ); @@ -73,7 +74,7 @@ if (config.DD_TRACE_ENABLED) { // an optional limit on pending requests concurrencyLimit: 10, }; - const otlpExporter = new OTLPTraceExporter(collectorOptions); + const otlpExporter = new CustomOTLPTraceExporter(collectorOptions); const otelProcessor = new BatchTracedSpanProcessor(otlpExporter); provider.addSpanProcessor(otelProcessor); console.log('OTLP options:', collectorOptions);