-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathtraces.spec.js
More file actions
938 lines (772 loc) · 36.4 KB
/
Copy pathtraces.spec.js
File metadata and controls
938 lines (772 loc) · 36.4 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
'use strict'
const assert = require('assert')
const http = require('node:http')
const https = require('node:https')
const { describe, it, beforeEach, afterEach } = require('mocha')
const sinon = require('sinon')
const proxyquire = require('proxyquire')
require('../setup/core')
const { getConfigFresh } = require('../helpers/config')
const id = require('../../src/id')
const OtlpHttpTraceExporter = require('../../src/opentelemetry/trace/otlp_http_trace_exporter')
const { createOtlpTraceExporter } = require('../../src/opentelemetry/trace')
const OTEL_ENV_KEYS = [
'OTEL_TRACES_EXPORTER',
'OTEL_EXPORTER_OTLP_ENDPOINT',
'OTEL_EXPORTER_OTLP_TRACES_ENDPOINT',
'OTEL_EXPORTER_OTLP_PROTOCOL',
'OTEL_EXPORTER_OTLP_TRACES_PROTOCOL',
'OTEL_EXPORTER_OTLP_HEADERS',
'OTEL_EXPORTER_OTLP_TRACES_HEADERS',
'OTEL_EXPORTER_OTLP_TIMEOUT',
'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',
]
describe('OpenTelemetry Traces', () => {
let originalEnv
/**
* Creates a mock DD-formatted span (as produced by span_format.js).
*
* @param {object} [overrides] - Optional field overrides
* @returns {object} A mock DD-formatted span
*/
function createMockSpan (overrides = {}) {
return {
trace_id: id('1234567890abcdef1234567890abcdef'),
span_id: id('abcdef1234567890'),
parent_id: id('1111111111111111'),
name: 'test.operation',
resource: '/api/test',
service: 'test-service',
type: 'web',
error: 0,
meta: {
'span.kind': 'server',
'http.method': 'GET',
'http.url': 'http://localhost/api/test',
},
metrics: {
'http.status_code': 200,
},
start: 1700000000000000000, // nanoseconds
duration: 50000000, // 50ms in nanoseconds
...overrides,
}
}
function mockOtlpExport (validator) {
let capturedPayload, capturedHeaders
let validatorCalled = false
sinon.stub(http, 'request').callsFake((options, onResponse) => {
if (options.path && options.path.includes('/v1/traces')) {
capturedHeaders = options.headers
const mockReq = {
write: (data) => { capturedPayload = data },
end: () => {
const decoded = JSON.parse(capturedPayload.toString())
validator(decoded, capturedHeaders)
validatorCalled = true
},
on: () => {},
once: () => {},
setTimeout: () => {},
}
onResponse({ statusCode: 200, on: () => {}, once: () => {}, setTimeout: () => {} })
return mockReq
}
const mockReq = {
write: () => {},
end: () => {},
on: () => {},
once: () => {},
setTimeout: () => {},
}
onResponse({ statusCode: 200, on: () => {}, once: () => {}, setTimeout: () => {} })
return mockReq
})
return () => {
if (!validatorCalled) {
throw new Error('OTLP export validator was never called')
}
}
}
/**
* Builds an OtlpHttpTraceExporter from a fresh config derived from the current
* process.env. Does NOT initialize the full tracer — this avoids leaking
* process-level listeners across tests.
*
* @param {object} [extraEnv] - Extra environment variables for this one build
* @returns {OtlpHttpTraceExporter}
*/
function buildExporter (extraEnv) {
if (extraEnv) Object.assign(process.env, extraEnv)
return createOtlpTraceExporter(getConfigFresh())
}
beforeEach(() => {
originalEnv = { ...process.env }
// Clear OTEL env vars that may be set by the host environment to prevent test pollution.
for (const key of OTEL_ENV_KEYS) delete process.env[key]
})
afterEach(() => {
process.env = originalEnv
sinon.restore()
})
describe('Transformer', () => {
const OtlpTraceTransformer = require('../../src/opentelemetry/trace/otlp_transformer')
const { getProtobufTypes } = require('../../src/opentelemetry/otlp/protobuf_loader')
const { protoSpanKind } = getProtobufTypes()
const {
SPAN_KIND_UNSPECIFIED,
SPAN_KIND_INTERNAL,
SPAN_KIND_SERVER,
SPAN_KIND_CLIENT,
SPAN_KIND_PRODUCER,
SPAN_KIND_CONSUMER,
} = protoSpanKind.values
/**
* Helper to decode the JSON payload from the transformer.
*
* @param {Buffer} payload - The JSON-encoded payload
* @returns {object} Decoded JSON object
*/
function decodePayload (payload) {
return JSON.parse(payload.toString())
}
/**
* Helper to extract attribute values from an OTLP attributes array.
*
* @param {object[]} attributes - Array of OTLP KeyValue objects
* @returns {Record<string, string|number>} Flat key-value map
*/
function extractAttrs (attributes) {
const attrs = {}
for (const attr of attributes) {
if (attr.value.stringValue !== undefined) {
attrs[attr.key] = attr.value.stringValue
} else if (attr.value.intValue !== undefined) {
attrs[attr.key] = attr.value.intValue
} else if (attr.value.doubleValue !== undefined) {
attrs[attr.key] = attr.value.doubleValue
}
}
return attrs
}
it('transforms a basic span to OTLP JSON format', () => {
const transformer = new OtlpTraceTransformer({ 'service.name': 'test-service' })
const span = createMockSpan()
const decoded = decodePayload(transformer.transformSpans([span]))
assert.strictEqual(decoded.resourceSpans.length, 1)
const { resource, scopeSpans } = decoded.resourceSpans[0]
const resourceAttrs = extractAttrs(resource.attributes)
assert.strictEqual(resourceAttrs['service.name'], 'test-service')
assert.strictEqual(scopeSpans.length, 1)
assert.strictEqual(scopeSpans[0].scope.name, 'dd-trace-js')
const otlpSpan = scopeSpans[0].spans[0]
assert.deepStrictEqual({
name: otlpSpan.name,
kind: otlpSpan.kind,
startTimeUnixNano: otlpSpan.startTimeUnixNano,
endTimeUnixNano: otlpSpan.endTimeUnixNano,
}, {
name: '/api/test',
kind: 2,
startTimeUnixNano: 1700000000000000000,
endTimeUnixNano: 1700000000050000000,
})
// trace-id and span-id must be hex-encoded strings per the OTLP http/json spec
assert.strictEqual(typeof otlpSpan.traceId, 'string', 'traceId must be a string')
assert.strictEqual(otlpSpan.traceId.length, 32, 'traceId must be 32 hex chars (16 bytes)')
assert.match(otlpSpan.traceId, /^[0-9a-f]+$/, 'traceId must be lowercase hex')
assert.strictEqual(typeof otlpSpan.spanId, 'string', 'spanId must be a string')
assert.strictEqual(otlpSpan.spanId.length, 16, 'spanId must be 16 hex chars (8 bytes)')
assert.match(otlpSpan.spanId, /^[0-9a-f]+$/, 'spanId must be lowercase hex')
assert.strictEqual(typeof otlpSpan.parentSpanId, 'string', 'parentSpanId must be a string')
assert.strictEqual(otlpSpan.parentSpanId.length, 16, 'parentSpanId must be 16 hex chars (8 bytes)')
})
it('maps span kind correctly', () => {
const transformer = new OtlpTraceTransformer({})
const kinds = ['internal', 'server', 'client', 'producer', 'consumer']
const expected = [SPAN_KIND_INTERNAL, SPAN_KIND_SERVER, SPAN_KIND_CLIENT, SPAN_KIND_PRODUCER, SPAN_KIND_CONSUMER]
for (let i = 0; i < kinds.length; i++) {
const span = createMockSpan({ meta: { 'span.kind': kinds[i] } })
const decoded = decodePayload(transformer.transformSpans([span]))
assert.strictEqual(decoded.resourceSpans[0].scopeSpans[0].spans[0].kind, expected[i])
}
})
it('defaults to SPAN_KIND_UNSPECIFIED when no span.kind', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({ meta: {} })
const decoded = decodePayload(transformer.transformSpans([span]))
assert.strictEqual(decoded.resourceSpans[0].scopeSpans[0].spans[0].kind, SPAN_KIND_UNSPECIFIED)
})
it('maps error status correctly', () => {
const transformer = new OtlpTraceTransformer({})
const okSpan = createMockSpan({ error: 0 })
const okDecoded = decodePayload(transformer.transformSpans([okSpan]))
assert.strictEqual(okDecoded.resourceSpans[0].scopeSpans[0].spans[0].status.code, 0)
const errSpan = createMockSpan({ error: 1, meta: { 'error.message': 'something broke' } })
const errDecoded = decodePayload(transformer.transformSpans([errSpan]))
assert.deepStrictEqual(errDecoded.resourceSpans[0].scopeSpans[0].spans[0].status, {
code: 2,
message: 'something broke',
})
})
it('combines error.type and error.message in status message', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({
error: 1,
meta: { 'error.type': 'TypeError', 'error.message': 'cannot read properties' },
})
const decoded = decodePayload(transformer.transformSpans([span]))
assert.deepStrictEqual(decoded.resourceSpans[0].scopeSpans[0].spans[0].status, {
code: 2,
message: 'TypeError: cannot read properties',
})
})
it('falls back to error.type when no error.message is present', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({ error: 1, meta: { 'error.type': 'TypeError' } })
const decoded = decodePayload(transformer.transformSpans([span]))
assert.deepStrictEqual(decoded.resourceSpans[0].scopeSpans[0].spans[0].status, {
code: 2,
message: 'TypeError',
})
})
it('omits parentSpanId for root spans (zero parent ID)', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({ parent_id: id('0') })
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
assert(!otlpSpan.parentSpanId, 'parentSpanId should not be set for root span')
})
it('includes meta and metrics as attributes', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({
meta: {
'http.method': 'POST',
'http.url': 'http://example.com',
},
metrics: {
'http.status_code': 404,
},
})
const decoded = decodePayload(transformer.transformSpans([span]))
const attrs = extractAttrs(decoded.resourceSpans[0].scopeSpans[0].spans[0].attributes)
assert.deepStrictEqual({
'http.method': attrs['http.method'],
'http.url': attrs['http.url'],
'http.status_code': attrs['http.status_code'],
}, {
'http.method': 'POST',
'http.url': 'http://example.com',
'http.status_code': 404,
})
})
it('encodes meta_struct values as base64 bytesValue attributes', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({
meta_struct: {
'_dd.stack': { nodejs: [{ id: 1, text: 'fn', file: 'a.js', line: 10 }] },
'http.request.body': { key: 'value' },
},
})
const decoded = decodePayload(transformer.transformSpans([span]))
const attrs = decoded.resourceSpans[0].scopeSpans[0].spans[0].attributes
const stackAttr = attrs.find(a => a.key === '_dd.stack')
assert.ok(stackAttr, '_dd.stack attribute should be present')
assert.notStrictEqual(stackAttr.value.bytesValue, undefined, '_dd.stack should have bytesValue')
const stackDecoded = JSON.parse(Buffer.from(stackAttr.value.bytesValue, 'base64').toString())
assert.deepStrictEqual(stackDecoded, { nodejs: [{ id: 1, text: 'fn', file: 'a.js', line: 10 }] })
const bodyAttr = attrs.find(a => a.key === 'http.request.body')
assert.ok(bodyAttr, 'http.request.body attribute should be present')
assert.notStrictEqual(bodyAttr.value.bytesValue, undefined, 'http.request.body should have bytesValue')
const bodyDecoded = JSON.parse(Buffer.from(bodyAttr.value.bytesValue, 'base64').toString())
assert.deepStrictEqual(bodyDecoded, { key: 'value' })
})
it('excludes _dd.span_links and span.kind from attributes', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({
meta: {
'span.kind': 'client',
'_dd.span_links': '[]',
'keep.this': 'value',
},
})
const decoded = decodePayload(transformer.transformSpans([span]))
const keys = decoded.resourceSpans[0].scopeSpans[0].spans[0].attributes.map(a => a.key)
assert(!keys.includes('span.kind'), 'span.kind should be excluded from attributes')
assert(!keys.includes('_dd.span_links'), '_dd.span_links should be excluded from attributes')
assert(keys.includes('keep.this'), 'Other meta keys should be present')
})
it('includes resource, service, type, and operation name as attributes', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan()
const decoded = decodePayload(transformer.transformSpans([span]))
const attrs = extractAttrs(decoded.resourceSpans[0].scopeSpans[0].spans[0].attributes)
assert.deepStrictEqual(
{
'resource.name': attrs['resource.name'],
'service.name': attrs['service.name'],
'span.type': attrs['span.type'],
'operation.name': attrs['operation.name'],
},
{
'resource.name': '/api/test',
'service.name': 'test-service',
'span.type': 'web',
'operation.name': 'test.operation',
}
)
})
it('transforms span events', () => {
const transformer = new OtlpTraceTransformer({})
// Raw events carry startTime; the transformer derives timeUnixNano = round(startTime * 1e6).
const span = createMockSpan({
span_events: [{
name: 'exception',
startTime: 1700000000010,
attributes: {
'exception.message': 'test error',
'exception.type': 'Error',
},
}],
})
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
assert.strictEqual(otlpSpan.events.length, 1)
assert.strictEqual(otlpSpan.events[0].name, 'exception')
assert.strictEqual(Number(otlpSpan.events[0].timeUnixNano), 1700000000010000000)
const eventAttrs = extractAttrs(otlpSpan.events[0].attributes)
assert.deepStrictEqual(
{ 'exception.message': eventAttrs['exception.message'], 'exception.type': eventAttrs['exception.type'] },
{ 'exception.message': 'test error', 'exception.type': 'Error' }
)
})
it('transforms span links from _dd.span_links JSON', () => {
const transformer = new OtlpTraceTransformer({})
const links = JSON.stringify([{
trace_id: 'aabbccddaabbccddaabbccddaabbccdd',
span_id: '1122334455667788',
attributes: { 'link.reason': 'follows-from' },
tracestate: 'dd=s:1',
}])
const span = createMockSpan({
meta: {
'_dd.span_links': links,
},
})
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
assert.strictEqual(otlpSpan.links.length, 1)
const link = otlpSpan.links[0]
assert.deepStrictEqual(
{ traceId: link.traceId, spanId: link.spanId, traceState: link.traceState },
{ traceId: 'aabbccddaabbccddaabbccddaabbccdd', spanId: '1122334455667788', traceState: 'dd=s:1' }
)
assert.strictEqual(extractAttrs(link.attributes)['link.reason'], 'follows-from')
})
it('maps timestamps correctly', () => {
const transformer = new OtlpTraceTransformer({})
const beforeNs = Date.now() * 1e6
const durationNs = 50000000 // 50ms
const span = createMockSpan({
start: beforeNs,
duration: durationNs,
})
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
assert.ok(otlpSpan.startTimeUnixNano >= beforeNs,
`startTimeUnixNano (${otlpSpan.startTimeUnixNano}) should be >= recorded time (${beforeNs})`)
assert.ok(otlpSpan.endTimeUnixNano >= otlpSpan.startTimeUnixNano,
`endTimeUnixNano (${otlpSpan.endTimeUnixNano}) should be >= startTimeUnixNano (${otlpSpan.startTimeUnixNano})`)
})
it('handles empty span array', () => {
const transformer = new OtlpTraceTransformer({})
const decoded = decodePayload(transformer.transformSpans([]))
assert.strictEqual(decoded.resourceSpans.length, 1)
assert.strictEqual(decoded.resourceSpans[0].scopeSpans[0].spans.length, 0)
})
it('handles multiple spans', () => {
const transformer = new OtlpTraceTransformer({})
const spans = [
createMockSpan({ resource: '/api/first' }),
createMockSpan({ resource: '/api/second', span_id: id('bbbbbbbbbbbbbbbb') }),
]
const decoded = decodePayload(transformer.transformSpans(spans))
const otlpSpans = decoded.resourceSpans[0].scopeSpans[0].spans
assert.strictEqual(otlpSpans.length, 2)
assert.deepStrictEqual(
[otlpSpans[0].name, otlpSpans[1].name],
['/api/first', '/api/second']
)
})
describe('128-bit trace ID handling', () => {
// DD splits 128-bit trace IDs: low 64 bits live on the span Identifier,
// upper 64 bits live in trace-level tags as `_dd.p.tid` (16 hex chars).
// span_format.js#extractChunkTags only copies trace-level tags onto the
// first-in-chunk span, so the transformer has to look across the batch
// to find `_dd.p.tid` and then apply it to every span.
it('reconstructs the full 128-bit traceId for every span in a batch from _dd.p.tid', () => {
const transformer = new OtlpTraceTransformer({})
const lowHex = 'abcdef0123456789'
const tidHigh = '1234567890abcdef'
const traceIdLow = id(lowHex)
const firstSpan = createMockSpan({
trace_id: traceIdLow,
meta: { 'span.kind': 'internal', '_dd.p.tid': tidHigh },
})
const secondSpan = createMockSpan({
trace_id: traceIdLow,
span_id: id('bbbbbbbbbbbbbbbb'),
meta: { 'span.kind': 'internal' },
})
const thirdSpan = createMockSpan({
trace_id: traceIdLow,
span_id: id('cccccccccccccccc'),
meta: { 'span.kind': 'internal' },
})
const decoded = decodePayload(transformer.transformSpans([firstSpan, secondSpan, thirdSpan]))
const otlpSpans = decoded.resourceSpans[0].scopeSpans[0].spans
const expectedTraceId = tidHigh + lowHex
for (const otlpSpan of otlpSpans) {
assert.strictEqual(otlpSpan.traceId, expectedTraceId)
}
})
it('drops _dd.p.tid from OTLP attributes once consumed into traceId', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({
trace_id: id('abcdef0123456789'),
meta: { 'span.kind': 'internal', '_dd.p.tid': '1234567890abcdef' },
})
const decoded = decodePayload(transformer.transformSpans([span]))
const attrs = extractAttrs(decoded.resourceSpans[0].scopeSpans[0].spans[0].attributes)
assert.strictEqual(attrs['_dd.p.tid'], undefined)
})
it('zero-pads traceId to 32 hex chars when no _dd.p.tid is present', () => {
const transformer = new OtlpTraceTransformer({})
const span = createMockSpan({
trace_id: id('abcdef0123456789'),
meta: { 'span.kind': 'internal' },
})
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
assert.strictEqual(otlpSpan.traceId, '0000000000000000abcdef0123456789')
})
it('lowercases an uppercase _dd.p.tid so the OTLP traceId is canonical lowercase hex', () => {
const transformer = new OtlpTraceTransformer({})
const lowHex = 'abcdef0123456789'
const span = createMockSpan({
trace_id: id(lowHex),
meta: { 'span.kind': 'internal', '_dd.p.tid': '1234567890ABCDEF' },
})
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
assert.strictEqual(otlpSpan.traceId, '1234567890abcdef' + lowHex)
})
it('uses a full 16-byte trace_id buffer directly without consulting _dd.p.tid', () => {
const transformer = new OtlpTraceTransformer({})
const unusedTidHigh = '1000000000000000'
const span = createMockSpan({
trace_id: id('1234567890abcdef1234567890abcdef'),
meta: { 'span.kind': 'internal', '_dd.p.tid': unusedTidHigh },
})
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
assert.strictEqual(otlpSpan.traceId, '1234567890abcdef1234567890abcdef')
})
})
describe('otelTraceSemanticsEnabled', () => {
it('omits service.name, operation.name, resource.name, span.type, and span.kind from attributes', () => {
const transformer = new OtlpTraceTransformer({}, true)
const span = createMockSpan({ type: 'web', meta: { 'span.kind': 'server' } })
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
const attrs = extractAttrs(otlpSpan.attributes)
assert.strictEqual(attrs['service.name'], undefined)
assert.strictEqual(attrs['operation.name'], undefined)
assert.strictEqual(attrs['resource.name'], undefined)
assert.strictEqual(attrs['span.type'], undefined)
assert.strictEqual(attrs['span.kind'], undefined)
assert.strictEqual(otlpSpan.kind, 2) // SPAN_KIND_SERVER — kind field still set
})
it('still emits non-DD meta tags and metrics as attributes', () => {
const transformer = new OtlpTraceTransformer({}, true)
const span = createMockSpan({
meta: { 'span.kind': 'server', 'http.method': 'GET', 'http.url': 'http://localhost/api' },
metrics: { 'http.status_code': 200 },
})
const decoded = decodePayload(transformer.transformSpans([span]))
const attrs = extractAttrs(decoded.resourceSpans[0].scopeSpans[0].spans[0].attributes)
assert.strictEqual(attrs['http.method'], 'GET')
assert.strictEqual(attrs['http.url'], 'http://localhost/api')
assert.strictEqual(attrs['http.status_code'], 200)
})
it('excludes error.message from attributes but still populates OTLP status', () => {
const transformer = new OtlpTraceTransformer({}, true)
const span = createMockSpan({
error: 1,
meta: {
'error.message': 'cannot read properties',
'http.method': 'GET',
},
})
const decoded = decodePayload(transformer.transformSpans([span]))
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
const attrs = extractAttrs(otlpSpan.attributes)
assert.strictEqual(attrs['error.message'], undefined, 'error.message must not appear as an attribute')
assert.strictEqual(attrs['http.method'], 'GET', 'non-error meta should still be present')
assert.deepStrictEqual(otlpSpan.status, {
code: 2,
message: 'cannot read properties',
}, 'OTLP status must still be populated from error.message')
})
})
})
describe('Exporter', () => {
it('exports spans via OTLP HTTP with JSON encoding', () => {
mockOtlpExport((decoded) => {
const otlpSpan = decoded.resourceSpans[0].scopeSpans[0].spans[0]
assert.strictEqual(otlpSpan.name, '/api/test')
})
const exporter = buildExporter({ OTEL_TRACES_EXPORTER: 'otlp' })
const span = createMockSpan({ name: 'http.request' })
exporter.export([span])
})
it('sends JSON content-type header', () => {
mockOtlpExport((decoded, headers) => {
assert.strictEqual(headers['Content-Type'], 'application/json')
})
const exporter = buildExporter({ OTEL_TRACES_EXPORTER: 'otlp' })
exporter.export([createMockSpan()])
})
it('includes custom headers from OTEL_EXPORTER_OTLP_TRACES_HEADERS', () => {
mockOtlpExport((decoded, headers) => {
assert.strictEqual(headers['x-api-key'], 'secret123')
})
const exporter = buildExporter({
OTEL_TRACES_EXPORTER: 'otlp',
OTEL_EXPORTER_OTLP_TRACES_HEADERS: 'x-api-key=secret123',
})
exporter.export([createMockSpan()])
})
it('includes multiple comma-separated custom headers from OTEL_EXPORTER_OTLP_TRACES_HEADERS', () => {
mockOtlpExport((decoded, headers) => {
assert.strictEqual(headers['x-api-key'], 'secret123')
assert.strictEqual(headers['other-config-value'], 'value')
})
const exporter = buildExporter({
OTEL_TRACES_EXPORTER: 'otlp',
OTEL_EXPORTER_OTLP_TRACES_HEADERS: 'x-api-key=secret123,other-config-value=value',
})
exporter.export([createMockSpan()])
})
it('includes custom headers from OTEL_EXPORTER_OTLP_HEADERS when traces-specific header is not set', () => {
mockOtlpExport((decoded, headers) => {
assert.strictEqual(headers['x-generic-key'], 'generic-value')
})
const exporter = buildExporter({
OTEL_TRACES_EXPORTER: 'otlp',
OTEL_EXPORTER_OTLP_HEADERS: 'x-generic-key=generic-value',
})
exporter.export([createMockSpan()])
})
it('uses OTEL_EXPORTER_OTLP_TRACES_HEADERS over OTEL_EXPORTER_OTLP_HEADERS when both are set', () => {
mockOtlpExport((decoded, headers) => {
assert.strictEqual(headers['x-traces-key'], 'traces-value')
assert.strictEqual(headers['x-generic-key'], undefined)
})
const exporter = buildExporter({
OTEL_TRACES_EXPORTER: 'otlp',
OTEL_EXPORTER_OTLP_HEADERS: 'x-generic-key=generic-value',
OTEL_EXPORTER_OTLP_TRACES_HEADERS: 'x-traces-key=traces-value',
})
exporter.export([createMockSpan()])
})
it('does not export empty span arrays', () => {
let exportCalled = false
sinon.stub(http, 'request').callsFake(() => {
exportCalled = true
return { write: () => {}, end: () => {}, on: () => {}, once: () => {}, setTimeout: () => {} }
})
const exporter = new OtlpHttpTraceExporter('http://localhost:4318/v1/traces', {}, 1000, {})
exporter.export([])
assert(!exportCalled, 'No HTTP request should be made for empty span arrays')
})
it('does not export spans with rejected sampling priority (0)', () => {
let exportCalled = false
sinon.stub(http, 'request').callsFake(() => {
exportCalled = true
return { write: () => {}, end: () => {}, on: () => {}, once: () => {}, setTimeout: () => {} }
})
const exporter = new OtlpHttpTraceExporter('http://localhost:4318/v1/traces', {}, 1000, {})
exporter.export([createMockSpan({ metrics: { _sampling_priority_v1: 0 } })])
assert(!exportCalled, 'No HTTP request should be made for rejected traces')
})
it('does not export spans with user-rejected sampling priority (-1)', () => {
let exportCalled = false
sinon.stub(http, 'request').callsFake(() => {
exportCalled = true
return { write: () => {}, end: () => {}, on: () => {}, once: () => {}, setTimeout: () => {} }
})
const exporter = new OtlpHttpTraceExporter('http://localhost:4318/v1/traces', {}, 1000, {})
exporter.export([createMockSpan({ metrics: { _sampling_priority_v1: -1 } })])
assert(!exportCalled, 'No HTTP request should be made for user-rejected traces')
})
it('DatadogTracer uses the OTLP exporter when OTEL_TRACES_EXPORTER=otlp', () => {
process.env.OTEL_TRACES_EXPORTER = 'otlp'
const DatadogTracer = proxyquire.noPreserveCache()('../../src/opentracing/tracer', {})
const tracer = new DatadogTracer(getConfigFresh())
assert(tracer._exporter instanceof OtlpHttpTraceExporter,
'Exporter should be the OTLP exporter when OTEL_TRACES_EXPORTER=otlp')
})
it('DatadogTracer does not use the OTLP exporter when OTEL_TRACES_EXPORTER is not otlp', () => {
delete process.env.OTEL_TRACES_EXPORTER
const DatadogTracer = proxyquire.noPreserveCache()('../../src/opentracing/tracer', {})
const tracer = new DatadogTracer(getConfigFresh())
assert(!(tracer._exporter instanceof OtlpHttpTraceExporter),
'Exporter should not be the OTLP exporter when OTEL_TRACES_EXPORTER is not otlp')
})
})
describe('Configurations', () => {
// Only http/json is currently supported. Other protocols (grpc, http/protobuf)
// are not yet implemented and will be added in a future release.
it('uses default http/json protocol', () => {
const config = getConfigFresh()
assert.strictEqual(config.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL, 'http/json')
})
it('uses port 4318 for default OTLP HTTP endpoint', () => {
const config = getConfigFresh()
const endpoint = config.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
assert(endpoint.includes(':4318'), `expected port 4318 in URL, got: ${endpoint}`)
})
it('respects explicit traces-specific endpoint as-is', () => {
process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT = 'http://custom-collector:9999'
const config = getConfigFresh()
assert.strictEqual(config.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, 'http://custom-collector:9999')
})
it('appends /v1/traces to the generic OTEL_EXPORTER_OTLP_ENDPOINT base URL', () => {
process.env.OTEL_EXPORTER_OTLP_ENDPOINT = 'http://collector:4318/custom'
const config = getConfigFresh()
assert.strictEqual(config.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, 'http://collector:4318/custom/v1/traces')
})
it('traces-specific endpoint takes precedence over generic endpoint', () => {
process.env.OTEL_EXPORTER_OTLP_ENDPOINT = 'http://generic:4318'
process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT = 'http://traces-specific:9999'
const config = getConfigFresh()
assert.strictEqual(config.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, 'http://traces-specific:9999')
})
it('exporter setUrl preserves a bare URL as-is without adding a signal path', () => {
const exporter = new OtlpHttpTraceExporter('http://collector:4318', {}, 1000, {})
assert.strictEqual(exporter.options.path, '/')
})
it('exporter setUrl preserves an explicit signal-specific path as-is', () => {
const exporter = new OtlpHttpTraceExporter('http://collector:4318/custom', {}, 1000, {})
assert.strictEqual(exporter.options.path, '/custom')
})
it('exporter setUrl preserves a trailing-slash signal-specific path', () => {
const exporter = new OtlpHttpTraceExporter('http://collector:4318/v1/traces/', {}, 1000, {})
assert.strictEqual(exporter.options.path, '/v1/traces/')
})
it('exporter setUrl keeps /v1/traces when already present', () => {
const exporter = new OtlpHttpTraceExporter('http://collector:4318/v1/traces', {}, 1000, {})
assert.strictEqual(exporter.options.path, '/v1/traces')
})
it('exports resource with service, version, env, and hostname', () => {
process.env.DD_SERVICE = 'my-trace-service'
process.env.DD_VERSION = 'v2.0.0'
process.env.DD_ENV = 'staging'
process.env.DD_TRACE_REPORT_HOSTNAME = 'true'
mockOtlpExport((decoded) => {
const resource = decoded.resourceSpans[0].resource
const resourceAttrs = {}
resource.attributes.forEach(attr => {
resourceAttrs[attr.key] = attr.value.stringValue
})
assert.deepStrictEqual(
{
'service.name': resourceAttrs['service.name'],
'service.version': resourceAttrs['service.version'],
'deployment.environment.name': resourceAttrs['deployment.environment.name'],
'telemetry.sdk.name': resourceAttrs['telemetry.sdk.name'],
'telemetry.sdk.language': resourceAttrs['telemetry.sdk.language'],
},
{
'service.name': 'my-trace-service',
'service.version': 'v2.0.0',
'deployment.environment.name': 'staging',
'telemetry.sdk.name': 'datadog',
'telemetry.sdk.language': 'nodejs',
}
)
assert.ok(resourceAttrs['telemetry.sdk.version'], 'telemetry.sdk.version should be set')
})
const exporter = buildExporter({ OTEL_TRACES_EXPORTER: 'otlp' })
exporter.export([createMockSpan()])
})
})
describe('Telemetry Metrics', () => {
it('sets protocol:http tag for http:// endpoint', () => {
const exporter = new OtlpHttpTraceExporter('http://collector.example/v1/traces', {}, 1000, {})
assert.ok(exporter.telemetryTags.includes('protocol:http'))
})
it('sets protocol:https tag for https:// endpoint', () => {
const exporter = new OtlpHttpTraceExporter('https://collector.example/v1/traces', {}, 1000, {})
assert.ok(exporter.telemetryTags.includes('protocol:https'))
})
it('tracks telemetry metrics for exported traces', () => {
const telemetryMetrics = {
manager: { namespace: sinon.stub().returns({ count: sinon.stub().returns({ inc: sinon.spy() }) }) },
}
const MockedExporter = proxyquire('../../src/opentelemetry/trace/otlp_http_trace_exporter', {
'../otlp/otlp_http_exporter_base': proxyquire('../../src/opentelemetry/otlp/otlp_http_exporter_base', {
'../../telemetry/metrics': telemetryMetrics,
}),
})
const exporter = new MockedExporter('http://localhost:4318/v1/traces', {}, 1000, {})
exporter.export([createMockSpan()])
assert(telemetryMetrics.manager.namespace().count().inc.calledWith(1))
})
})
describe('setUrl', () => {
it('retargets hostname and port and preserves an explicit custom path as-is', () => {
const exporter = new OtlpHttpTraceExporter('http://localhost:4318/v1/traces', {}, 1000, {})
exporter.setUrl('http://otel-collector:9999/custom/path')
assert.strictEqual(exporter.options.hostname, 'otel-collector')
assert.strictEqual(exporter.options.port, '9999')
assert.strictEqual(exporter.options.path, '/custom/path')
})
it('uses a bare URL as-is without adding a signal path', () => {
const exporter = new OtlpHttpTraceExporter('http://localhost:4318/v1/traces', {}, 1000, {})
exporter.setUrl('http://otel-collector:9999')
assert.strictEqual(exporter.options.path, '/')
})
it('keeps /v1/traces when already present and preserves the query string', () => {
const exporter = new OtlpHttpTraceExporter('http://localhost:4318/v1/traces', {}, 1000, {})
exporter.setUrl('http://otel-collector:9999/v1/traces?token=abc')
assert.strictEqual(exporter.options.path, '/v1/traces?token=abc')
})
it('selects http transport for http:// URLs', () => {
const exporter = new OtlpHttpTraceExporter('http://collector.example/v1/traces', {}, 1000, {})
const mockReq = { write: () => {}, end: () => {}, on: () => mockReq, once: () => mockReq }
const httpStub = sinon.stub(http, 'request').returns(mockReq)
sinon.stub(https, 'request').returns(mockReq)
exporter.sendPayload(Buffer.from('{}'), () => {})
assert.ok(httpStub.calledOnce, 'http.request should have been called')
})
it('selects https transport for https:// URLs', () => {
const exporter = new OtlpHttpTraceExporter('https://collector.example/v1/traces', {}, 1000, {})
const mockReq = { write: () => {}, end: () => {}, on: () => mockReq, once: () => mockReq }
sinon.stub(http, 'request').returns(mockReq)
const httpsStub = sinon.stub(https, 'request').returns(mockReq)
exporter.sendPayload(Buffer.from('{}'), () => {})
assert.ok(httpsStub.calledOnce, 'https.request should have been called')
})
it('switches transport when setUrl is called with a different scheme', () => {
const exporter = new OtlpHttpTraceExporter('http://collector.example/v1/traces', {}, 1000, {})
const mockReq = { write: () => {}, end: () => {}, on: () => mockReq, once: () => mockReq }
sinon.stub(http, 'request').returns(mockReq)
const httpsStub = sinon.stub(https, 'request').returns(mockReq)
exporter.setUrl('https://secure-collector.example/v1/traces')
exporter.sendPayload(Buffer.from('{}'), () => {})
assert.ok(httpsStub.calledOnce, 'https.request should have been called after switching to https')
})
})
})