-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathbasic.spec.js
More file actions
917 lines (789 loc) · 34.7 KB
/
Copy pathbasic.spec.js
File metadata and controls
917 lines (789 loc) · 34.7 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
'use strict'
const { writeFileSync } = require('fs')
const os = require('os')
const { join } = require('path')
const assert = require('assert')
const { pollInterval, setup } = require('./utils')
const { assertObjectContains, assertUUID } = require('../helpers')
const { UNACKNOWLEDGED, ACKNOWLEDGED, ERROR } = require('../../packages/dd-trace/src/remote_config/apply_states')
const { version } = require('../../package.json')
describe('Dynamic Instrumentation', function () {
describe('Default env', function () {
const t = setup({ dependencies: ['fastify'] })
it('base case: target app should work as expected if no test probe has been added', async function () {
const response = await t.axios.get(t.breakpoint.url)
assert.strictEqual(response.status, 200)
assert.deepStrictEqual(response.data, { hello: 'bar' })
})
describe('diagnostics messages', function () {
it('should send expected diagnostics messages if probe is received and triggered', function (done) {
let receivedAckUpdate = false
const probeId = t.rcConfig.config.id
const expectedPayloads = [{
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 0, status: 'RECEIVED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 0, status: 'INSTALLED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 0, status: 'EMITTING' } }
}]
t.agent.on('remote-config-ack-update', (id, version, state, error) => {
// Due to the very short DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS, there's a race condition in which we might
// get an UNACKNOWLEDGED state first before the ACKNOWLEDGED state.
if (state === UNACKNOWLEDGED) return
assert.strictEqual(id, t.rcConfig.id)
assert.strictEqual(version, 1)
assert.strictEqual(state, ACKNOWLEDGED)
assert.ok(!error) // falsy check since error will be an empty string, but that's an implementation detail
receivedAckUpdate = true
endIfDone()
})
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const expected = expectedPayloads.shift()
assertObjectContains(event, expected)
assertUUID(event.debugger.diagnostics.runtimeId)
if (event.debugger.diagnostics.status === 'INSTALLED') {
t.axios.get(t.breakpoint.url)
.then((response) => {
assert.strictEqual(response.status, 200)
assert.deepStrictEqual(response.data, { hello: 'bar' })
})
.catch(done)
} else {
endIfDone()
}
})
})
t.agent.addRemoteConfig(t.rcConfig)
function endIfDone () {
if (receivedAckUpdate && expectedPayloads.length === 0) done()
}
})
it('should send expected diagnostics messages if probe is first received and then updated', function (done) {
let receivedAckUpdates = 0
const probeId = t.rcConfig.config.id
const expectedPayloads = [{
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 0, status: 'RECEIVED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 0, status: 'INSTALLED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 1, status: 'RECEIVED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 1, status: 'INSTALLED' } }
}]
const triggers = [
() => {
t.rcConfig.config.version++
t.agent.updateRemoteConfig(t.rcConfig.id, t.rcConfig.config)
},
() => {}
]
t.agent.on('remote-config-ack-update', (id, version, state, error) => {
// Due to the very short DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS, there's a race condition in which we might
// get an UNACKNOWLEDGED state first before the ACKNOWLEDGED state.
if (state === UNACKNOWLEDGED) return
assert.strictEqual(id, t.rcConfig.id)
assert.strictEqual(version, ++receivedAckUpdates)
assert.strictEqual(state, ACKNOWLEDGED)
assert.ok(!error) // falsy check since error will be an empty string, but that's an implementation detail
endIfDone()
})
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const expected = expectedPayloads.shift()
assertObjectContains(event, expected)
assertUUID(event.debugger.diagnostics.runtimeId)
if (event.debugger.diagnostics.status === 'INSTALLED') {
const trigger = triggers.shift()
assert.ok(trigger, 'expecting a trigger function to be defined')
trigger()
}
endIfDone()
})
})
t.agent.addRemoteConfig(t.rcConfig)
function endIfDone () {
if (receivedAckUpdates === 2 && expectedPayloads.length === 0) done()
}
})
it('should send expected diagnostics messages if probe is first received and then deleted', function (done) {
let receivedAckUpdate = false
let payloadsProcessed = false
const probeId = t.rcConfig.config.id
const expectedPayloads = [{
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 0, status: 'RECEIVED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId, probeVersion: 0, status: 'INSTALLED' } }
}]
t.agent.on('remote-config-ack-update', (id, version, state, error) => {
// Due to the very short DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS, there's a race condition in which we might
// get an UNACKNOWLEDGED state first before the ACKNOWLEDGED state.
if (state === UNACKNOWLEDGED) return
assert.strictEqual(id, t.rcConfig.id)
assert.strictEqual(version, 1)
assert.strictEqual(state, ACKNOWLEDGED)
assert.ok(!error) // falsy check since error will be an empty string, but that's an implementation detail
receivedAckUpdate = true
endIfDone()
})
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const expected = expectedPayloads.shift()
assertObjectContains(event, expected)
assertUUID(event.debugger.diagnostics.runtimeId)
if (event.debugger.diagnostics.status === 'INSTALLED') {
t.agent.removeRemoteConfig(t.rcConfig.id)
// Wait a little to see if we get any follow-up `debugger-diagnostics` messages
setTimeout(() => {
payloadsProcessed = true
endIfDone()
}, pollInterval * 2 * 1000) // wait twice as long as the RC poll interval
}
})
})
t.agent.addRemoteConfig(t.rcConfig)
function endIfDone () {
if (receivedAckUpdate && payloadsProcessed) done()
}
})
it(
'should send expected error diagnostics messages if probe doesn\'t conform to expected schema',
unsupportedOrInvalidProbesTest({ invalid: 'config' }, { status: 'ERROR' })
)
it(
'should send expected error diagnostics messages if probe type isn\'t supported',
// @ts-expect-error Expecting this probe type to be invalid
unsupportedOrInvalidProbesTest(t.generateProbeConfig({ type: 'INVALID_PROBE' }))
)
it(
'should send expected error diagnostics messages if it isn\'t a line-probe',
unsupportedOrInvalidProbesTest(
// @ts-expect-error Expecting this probe type to be invalid
t.generateProbeConfig({ where: { typeName: 'index.js', methodName: 'handlerA' } })
)
)
function unsupportedOrInvalidProbesTest (config, customErrorDiagnosticsObj) {
return function (done) {
let receivedAckUpdate = false
t.agent.on('remote-config-ack-update', (id, version, state, error) => {
assert.strictEqual(id, `logProbe_${config.id}`)
assert.strictEqual(version, 1)
assert.strictEqual(state, ERROR)
assert.strictEqual(error.slice(0, 6), 'Error:')
receivedAckUpdate = true
endIfDone()
})
const probeId = config.id
const expectedPayloads = [{
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { status: 'RECEIVED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: customErrorDiagnosticsObj ?? { probeId, probeVersion: 0, status: 'ERROR' } }
}]
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const expected = expectedPayloads.shift()
assertObjectContains(event, expected)
const { diagnostics } = event.debugger
assertUUID(diagnostics.runtimeId)
if (diagnostics.status === 'ERROR') {
assert.ok(Object.hasOwn(diagnostics, 'exception'))
assert.deepStrictEqual(['message', 'stacktrace'], Object.keys(diagnostics.exception).sort())
assert.strictEqual(typeof diagnostics.exception.message, 'string')
assert.strictEqual(typeof diagnostics.exception.stacktrace, 'string')
}
endIfDone()
})
})
t.agent.addRemoteConfig({
product: 'LIVE_DEBUGGING',
id: `logProbe_${config.id}`,
config
})
function endIfDone () {
if (receivedAckUpdate && expectedPayloads.length === 0) done()
}
}
}
describe('multiple probes at the same location', function () {
it('should support adding multiple probes at the same location', function (done) {
const rcConfig1 = t.generateRemoteConfig()
const rcConfig2 = t.generateRemoteConfig()
const expectedPayloads = [{
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig1.config.id, probeVersion: 0, status: 'RECEIVED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig2.config.id, probeVersion: 0, status: 'RECEIVED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig1.config.id, probeVersion: 0, status: 'INSTALLED' } }
}, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig2.config.id, probeVersion: 0, status: 'INSTALLED' } }
}]
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const expected = expectedPayloads.shift()
assertObjectContains(event, expected)
})
endIfDone()
})
t.agent.addRemoteConfig(rcConfig1)
t.agent.addRemoteConfig(rcConfig2)
function endIfDone () {
if (expectedPayloads.length === 0) done()
}
})
it('should support triggering multiple probes added at the same location', function (done) {
let installed = 0
const rcConfig1 = t.generateRemoteConfig()
const rcConfig2 = t.generateRemoteConfig()
const expectedPayloads = new Map([
[rcConfig1.config.id, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig1.config.id, probeVersion: 0, status: 'EMITTING' } }
}],
[rcConfig2.config.id, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig2.config.id, probeVersion: 0, status: 'EMITTING' } }
}]
])
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const { diagnostics } = event.debugger
if (diagnostics.status === 'INSTALLED') {
if (++installed === 2) {
t.axios.get(t.breakpoint.url).catch(done)
}
} else if (diagnostics.status === 'EMITTING') {
const expected = expectedPayloads.get(diagnostics.probeId)
assert.ok(expected, `expected payload not found for probe ${diagnostics.probeId}`)
expectedPayloads.delete(diagnostics.probeId)
assertObjectContains(event, expected)
}
})
endIfDone()
})
t.agent.addRemoteConfig(rcConfig1)
t.agent.addRemoteConfig(rcConfig2)
function endIfDone () {
if (expectedPayloads.size === 0) done()
}
})
it('should support not triggering any probes when all conditions are not met', function (done) {
let installed = 0
const rcConfig1 = t.generateRemoteConfig({ when: { json: { eq: [{ ref: 'foo' }, 'bar'] } } })
const rcConfig2 = t.generateRemoteConfig({ when: { json: { eq: [{ ref: 'foo' }, 'baz'] } } })
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const { diagnostics } = event.debugger
if (diagnostics.status === 'INSTALLED') {
if (++installed === 2) {
t.axios.get(t.breakpoint.url).catch(done)
setTimeout(done, 2000)
}
} else if (diagnostics.status === 'EMITTING') {
assert.fail('should not trigger any probes when all conditions are not met')
}
})
})
t.agent.addRemoteConfig(rcConfig1)
t.agent.addRemoteConfig(rcConfig2)
})
it('should only trigger the probes whose conditions are met (all have conditions)', function (done) {
let installed = 0
const rcConfig1 = t.generateRemoteConfig({
when: { json: { eq: [{ getmember: [{ getmember: [{ ref: 'request' }, 'params'] }, 'name'] }, 'invalid'] } }
})
const rcConfig2 = t.generateRemoteConfig({
when: { json: { eq: [{ getmember: [{ getmember: [{ ref: 'request' }, 'params'] }, 'name'] }, 'bar'] } }
})
const expectedPayloads = new Map([
[rcConfig2.config.id, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig2.config.id, probeVersion: 0, status: 'EMITTING' } }
}]
])
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const { diagnostics } = event.debugger
if (diagnostics.status === 'INSTALLED') {
if (++installed === 2) {
t.axios.get(t.breakpoint.url).catch(done)
}
} else if (diagnostics.status === 'EMITTING') {
const expected = expectedPayloads.get(diagnostics.probeId)
assert.ok(expected, `expected payload not found for probe ${diagnostics.probeId}`)
expectedPayloads.delete(diagnostics.probeId)
assertObjectContains(event, expected)
}
})
endIfDone()
})
t.agent.addRemoteConfig(rcConfig1)
t.agent.addRemoteConfig(rcConfig2)
function endIfDone () {
if (expectedPayloads.size === 0) done()
}
})
it('trigger on met condition, even if other condition throws (all have conditions)', function (done) {
let installed = 0
// this condition will throw because `foo` is not defined
const rcConfig1 = t.generateRemoteConfig({ when: { json: { eq: [{ ref: 'foo' }, 'bar'] } } })
const rcConfig2 = t.generateRemoteConfig({
when: { json: { eq: [{ getmember: [{ getmember: [{ ref: 'request' }, 'params'] }, 'name'] }, 'bar'] } }
})
const expectedPayloads = new Map([
[rcConfig2.config.id, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig2.config.id, probeVersion: 0, status: 'EMITTING' } }
}]
])
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const { diagnostics } = event.debugger
if (diagnostics.status === 'INSTALLED') {
if (++installed === 2) {
t.axios.get(t.breakpoint.url).catch(done)
}
} else if (diagnostics.status === 'EMITTING') {
const expected = expectedPayloads.get(diagnostics.probeId)
assert.ok(expected, `expected payload not found for probe ${diagnostics.probeId}`)
expectedPayloads.delete(diagnostics.probeId)
assertObjectContains(event, expected)
}
})
endIfDone()
})
t.agent.addRemoteConfig(rcConfig1)
t.agent.addRemoteConfig(rcConfig2)
function endIfDone () {
if (expectedPayloads.size === 0) done()
}
})
it('should only trigger the probes whose conditions are met (not all have conditions)', function (done) {
let installed = 0
const rcConfig1 = t.generateRemoteConfig({
when: { json: { eq: [{ getmember: [{ getmember: [{ ref: 'request' }, 'params'] }, 'name'] }, 'invalid'] } }
})
const rcConfig2 = t.generateRemoteConfig({
when: { json: { eq: [{ getmember: [{ getmember: [{ ref: 'request' }, 'params'] }, 'name'] }, 'bar'] } }
})
const rcConfig3 = t.generateRemoteConfig()
const expectedPayloads = new Map([
[rcConfig2.config.id, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig2.config.id, probeVersion: 0, status: 'EMITTING' } }
}],
[rcConfig3.config.id, {
ddsource: 'dd_debugger',
service: 'node',
debugger: { diagnostics: { probeId: rcConfig3.config.id, probeVersion: 0, status: 'EMITTING' } }
}]
])
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const { diagnostics } = event.debugger
if (diagnostics.status === 'INSTALLED') {
if (++installed === 3) {
t.axios.get(t.breakpoint.url).catch(done)
}
} else if (diagnostics.status === 'EMITTING') {
const expected = expectedPayloads.get(diagnostics.probeId)
assert.ok(expected, `expected payload not found for probe ${diagnostics.probeId}`)
expectedPayloads.delete(diagnostics.probeId)
assertObjectContains(event, expected)
}
})
endIfDone()
})
t.agent.addRemoteConfig(rcConfig1)
t.agent.addRemoteConfig(rcConfig2)
t.agent.addRemoteConfig(rcConfig3)
function endIfDone () {
if (expectedPayloads.size === 0) done()
}
})
})
})
describe('input messages', function () {
it('should capture and send expected payload when a log line probe is triggered', testBasicInput.bind(null, t))
it('should respond with updated message if probe message is updated', function (done) {
const expectedMessages = ['Hello World!', 'Hello Updated World!']
const triggers = [
async () => {
await t.axios.get(t.breakpoint.url)
t.rcConfig.config.version++
t.rcConfig.config.template = 'Hello Updated World!'
t.agent.updateRemoteConfig(t.rcConfig.id, t.rcConfig.config)
},
async () => {
await t.axios.get(t.breakpoint.url)
}
]
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
if (event.debugger.diagnostics.status === 'INSTALLED') {
const trigger = triggers.shift()
assert.ok(trigger, 'expecting a trigger function to be defined')
trigger().catch(done)
}
})
})
t.agent.on('debugger-input', ({ payload: [payload] }) => {
assert.strictEqual(payload.message, expectedMessages.shift())
if (expectedMessages.length === 0) done()
})
t.agent.addRemoteConfig(t.rcConfig)
})
it('should not trigger if probe is deleted', function (done) {
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
if (event.debugger.diagnostics.status === 'INSTALLED') {
t.agent.once('remote-config-responded', async () => {
await t.axios.get(t.breakpoint.url)
// We want to wait enough time to see if the client triggers on the breakpoint so that the test can fail
// if it does, but not so long that the test times out.
// TODO: Is there some signal we can use instead of a timer?
setTimeout(done, pollInterval * 2 * 1000) // wait twice as long as the RC poll interval
})
t.agent.removeRemoteConfig(t.rcConfig.id)
}
})
})
t.agent.on('debugger-input', () => {
assert.fail('should not capture anything when the probe is deleted')
})
t.agent.addRemoteConfig(t.rcConfig)
})
})
describe('sampling', function () {
it('should respect sampling rate for single probe', function (done) {
let prev, timer
const rcConfig = t.generateRemoteConfig({ sampling: { snapshotsPerSecond: 1 } })
function triggerBreakpointContinuously () {
t.axios.get(t.breakpoint.url).catch(done)
timer = setTimeout(triggerBreakpointContinuously, 10)
}
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
if (event.debugger.diagnostics.status === 'INSTALLED') triggerBreakpointContinuously()
})
})
t.agent.on('debugger-input', ({ payload }) => {
payload.forEach(({ debugger: { snapshot: { timestamp } } }) => {
if (prev !== undefined) {
const duration = timestamp - prev
clearTimeout(timer)
// Allow for a variance of +50ms (time will tell if this is enough)
assert.ok(duration >= 1000)
assert.ok(duration < 1050)
// Wait at least a full sampling period, to see if we get any more payloads
timer = setTimeout(done, 1250)
}
prev = timestamp
})
})
t.agent.addRemoteConfig(rcConfig)
})
it('should adhere to individual probes sample rate', function (done) {
/** @type {(() => void) & { calledOnce?: boolean }} */
const doneWhenCalledTwice = () => {
if (doneWhenCalledTwice.calledOnce) return done()
doneWhenCalledTwice.calledOnce = true
}
const rcConfig1 = t.breakpoints[0].generateRemoteConfig({ sampling: { snapshotsPerSecond: 1 } })
const rcConfig2 = t.breakpoints[1].generateRemoteConfig({ sampling: { snapshotsPerSecond: 1 } })
const state = {
[rcConfig1.config.id]: {
triggerBreakpointContinuously () {
t.axios.get(t.breakpoints[0].url).catch(done)
this.timer = setTimeout(this.triggerBreakpointContinuously.bind(this), 10)
}
},
[rcConfig2.config.id]: {
triggerBreakpointContinuously () {
t.axios.get(t.breakpoints[1].url).catch(done)
this.timer = setTimeout(this.triggerBreakpointContinuously.bind(this), 10)
}
}
}
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const { probeId, status } = event.debugger.diagnostics
if (status === 'INSTALLED') state[probeId].triggerBreakpointContinuously()
})
})
t.agent.on('debugger-input', ({ payload }) => {
payload.forEach((result) => {
const _state = state[result.debugger.snapshot.probe.id]
const { timestamp } = result.debugger.snapshot
if (_state.prev !== undefined) {
const duration = timestamp - _state.prev
clearTimeout(_state.timer)
// Allow for a variance of +50ms (time will tell if this is enough)
assert.ok(duration >= 1000)
assert.ok(duration < 1050)
// Wait at least a full sampling period, to see if we get any more payloads
_state.timer = setTimeout(doneWhenCalledTwice, 1250)
}
_state.prev = timestamp
})
})
t.agent.addRemoteConfig(rcConfig1)
t.agent.addRemoteConfig(rcConfig2)
})
})
describe('condition', function () {
beforeEach(() => { t.triggerBreakpoint() })
it('should trigger when condition is met', function (done) {
t.agent.on('debugger-input', () => {
done()
})
t.agent.addRemoteConfig(t.generateRemoteConfig({
when: { json: { eq: [{ getmember: [{ getmember: [{ ref: 'request' }, 'params'] }, 'name'] }, 'bar'] } }
}))
})
it('should not trigger when condition is not met', function (done) {
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
if (event.debugger.diagnostics.status === 'INSTALLED') {
// Can't know if the probe didn't trigger, so just wait a bit and see if the test fails in the mean time
setTimeout(done, 2000)
}
})
})
t.agent.on('debugger-input', () => {
assert.fail('Should not trigger when condition is not met')
})
t.agent.addRemoteConfig(t.generateRemoteConfig({
when: { json: { eq: [{ getmember: [{ getmember: [{ ref: 'request' }, 'params'] }, 'name'] }, 'invalid'] } }
}))
})
it('should report error if condition cannot be compiled', function (done) {
const rcConfig = t.generateRemoteConfig({
when: { dsl: 'original dsl', json: { ref: 'this is not a valid ref' } }
})
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach(({ debugger: { diagnostics } }) => {
if (diagnostics.status === 'ERROR') {
assert.strictEqual(
diagnostics.exception.message,
`Cannot compile expression: original dsl (probe: ${rcConfig.config.id}, version: 0)`
)
done()
} else if (diagnostics.status === 'INSTALLED') {
assert.fail('Should not install when condition cannot be compiled')
}
})
})
t.agent.addRemoteConfig(rcConfig)
})
})
describe('race conditions', function () {
it('should remove the last breakpoint completely before trying to add a new one', function (done) {
const rcConfig2 = t.generateRemoteConfig()
t.agent.on('debugger-diagnostics', ({ payload }) => {
payload.forEach((event) => {
const { probeId, status } = event.debugger.diagnostics
if (status !== 'INSTALLED') return
if (probeId === t.rcConfig.config.id) {
// First INSTALLED payload: Try to trigger the race condition.
t.agent.removeRemoteConfig(t.rcConfig.id)
t.agent.addRemoteConfig(rcConfig2)
} else {
// Second INSTALLED payload: Perform an HTTP request to see if we successfully handled the race condition.
let finished = false
// If the race condition occurred, the debugger will have been detached from the main thread and the new
// probe will never trigger. If that's the case, the following timer will fire:
const timer = setTimeout(() => {
done(new Error('Race condition occurred!'))
}, 2000)
// If we successfully handled the race condition, the probe will trigger, we'll get a probe result and the
// following event listener will be called:
t.agent.once('debugger-input', () => {
clearTimeout(timer)
finished = true
done()
})
// Perform HTTP request to try and trigger the probe
t.axios.get(t.breakpoint.url).catch((err) => {
// If the request hasn't fully completed by the time the tests ends and the target app is destroyed,
// Axios will complain with a "socket hang up" error. Hence this sanity check before calling
// `done(err)`. If we later add more tests below this one, this shouldn't be an issue.
if (!finished) done(err)
})
}
})
})
t.agent.addRemoteConfig(t.rcConfig)
})
})
})
describe('probe file', function () {
const probeFile = join(os.tmpdir(), 'probes.json')
const t = setup({
env: { DD_DYNAMIC_INSTRUMENTATION_PROBE_FILE: probeFile },
dependencies: ['fastify']
})
const probe = t.generateProbeConfig()
writeFileSync(probeFile, JSON.stringify([probe]))
it('should install probes from a probe file', testBasicInputWithoutRC.bind(null, t, probe))
})
describe('DD_TRACING_ENABLED=true, DD_TRACE_128_BIT_TRACEID_GENERATION_ENABLED=true', function () {
const t = setup({
env: { DD_TRACING_ENABLED: 'true', DD_TRACE_128_BIT_TRACEID_GENERATION_ENABLED: true },
dependencies: ['fastify']
})
describe('input messages', function () {
it('should capture and send expected payload when a log line probe is triggered', testBasicInput.bind(null, t))
})
})
describe('DD_TRACING_ENABLED=true, DD_TRACE_128_BIT_TRACEID_GENERATION_ENABLED=false', function () {
const t = setup({
env: { DD_TRACING_ENABLED: 'true', DD_TRACE_128_BIT_TRACEID_GENERATION_ENABLED: false },
dependencies: ['fastify']
})
describe('input messages', function () {
it('should capture and send expected payload when a log line probe is triggered', testBasicInput.bind(null, t))
})
})
describe('DD_TRACING_ENABLED=false', function () {
const t = setup({
env: { DD_TRACING_ENABLED: 'false' },
dependencies: ['fastify']
})
describe('input messages', function () {
it(
'should capture and send expected payload when a log line probe is triggered',
testBasicInputWithoutDD.bind(null, t)
)
})
})
})
function testBasicInput (t, done) {
t.triggerBreakpoint()
setupAssertionListeners(t, done)
t.agent.addRemoteConfig(t.rcConfig)
}
function testBasicInputWithoutRC (t, probe, done) {
t.triggerBreakpoint(false)
setupAssertionListeners(t, done, probe)
}
function setupAssertionListeners (t, done, probe) {
let traceId, spanId, dd
t.agent.on('message', ({ payload }) => {
const span = payload.find((arr) => arr[0].name === 'fastify.request')?.[0]
if (!span) return
traceId = span.trace_id.toString()
spanId = span.span_id.toString()
assertDD()
})
t.agent.on('debugger-input', ({ payload }) => {
assertBasicInputPayload(t, payload, probe)
payload = payload[0]
assert.ok(typeof payload.dd === 'object' && payload.dd !== null)
assert.deepStrictEqual(['span_id', 'trace_id'], Object.keys(payload.dd).sort())
assert.strictEqual(typeof payload.dd.trace_id, 'string')
assert.strictEqual(typeof payload.dd.span_id, 'string')
assert.ok(payload.dd.trace_id.length > 0)
assert.ok(payload.dd.span_id.length > 0)
dd = payload.dd
assertDD()
})
function assertDD () {
if (!traceId || !spanId || !dd) return
assert.strictEqual(dd.trace_id, traceId)
assert.strictEqual(dd.span_id, spanId)
done()
}
}
function testBasicInputWithoutDD (t, done) {
t.triggerBreakpoint()
t.agent.on('debugger-input', ({ payload }) => {
assertBasicInputPayload(t, payload)
assert.ok(!('dd' in payload[0]))
done()
})
t.agent.addRemoteConfig(t.rcConfig)
}
function assertBasicInputPayload (t, payload, probe = t.rcConfig.config) {
assert.ok(Array.isArray(payload))
assert.strictEqual(payload.length, 1)
payload = payload[0]
const expected = {
ddsource: 'dd_debugger',
hostname: os.hostname(),
service: 'node',
message: 'Hello World!',
logger: {
name: t.breakpoint.deployedFile,
method: 'fooHandler',
version,
thread_name: 'MainThread'
},
debugger: {
snapshot: {
probe: {
id: probe.id,
version: 0,
location: { file: t.breakpoint.deployedFile, lines: [String(t.breakpoint.line)] }
},
language: 'javascript'
}
}
}
assertObjectContains(payload, expected)
assert.match(payload.logger.thread_id, /^pid:\d+$/)
assertUUID(payload.debugger.snapshot.id)
assert.strictEqual(typeof payload.debugger.snapshot.timestamp, 'number')
assert.ok(payload.debugger.snapshot.timestamp > Date.now() - 1000 * 60)
assert.ok(payload.debugger.snapshot.timestamp <= Date.now())
assert.ok(Array.isArray(payload.debugger.snapshot.stack))
assert.ok(payload.debugger.snapshot.stack.length > 0)
for (const frame of payload.debugger.snapshot.stack) {
assert.ok(typeof frame === 'object' && frame !== null)
assert.deepStrictEqual(['columnNumber', 'fileName', 'function', 'lineNumber'], Object.keys(frame).sort())
assert.strictEqual(typeof frame.fileName, 'string')
assert.strictEqual(typeof frame.function, 'string')
assert.ok(frame.lineNumber > 0)
assert.ok(frame.columnNumber > 0)
}
const topFrame = payload.debugger.snapshot.stack[0]
// path seems to be prefixed with `/private` on Mac
assert.match(topFrame.fileName, new RegExp(`${t.appFile}$`))
assert.strictEqual(topFrame.function, 'fooHandler')
assert.strictEqual(topFrame.lineNumber, t.breakpoint.line)
assert.strictEqual(topFrame.columnNumber, 3)
}