-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathserver.spec.js
More file actions
909 lines (786 loc) · 30 KB
/
Copy pathserver.spec.js
File metadata and controls
909 lines (786 loc) · 30 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
'use strict'
const assert = require('node:assert/strict')
const { fork } = require('node:child_process')
const { once } = require('node:events')
const path = require('node:path')
const { text } = require('node:stream/consumers')
const { setImmediate } = require('node:timers/promises')
const { afterEach, beforeEach, describe, it } = require('mocha')
const sinon = require('sinon')
const { channel } = require('dc-polyfill')
const agent = require('../../dd-trace/test/plugins/agent')
const web = require('../../dd-trace/src/plugins/util/web')
const { FOREIGN_HTTP2_SERVER } = require('../../dd-trace/src/constants')
const { withNamingSchema } = require('../../dd-trace/test/setup/mocha')
const { assertObjectContains } = require('../../../integration-tests/helpers')
const { rawExpectedSchema } = require('./naming')
/**
* @param {typeof import('http2')} http2
* @param {string} url
* @param {{ signal?: import('node:events').EventEmitter }} [options]
*/
function request (http2, url, options = {}) {
const { signal } = options
const urlObj = new URL(url)
return new Promise((resolve, reject) => {
const client = http2
.connect(urlObj.origin)
.on('error', reject)
const req = client.request({
':path': urlObj.pathname + urlObj.search,
':method': 'GET',
})
req.on('error', reject)
if (signal) {
signal.on('abort', () => req.destroy())
}
const chunks = []
req.on('data', (chunk) => {
chunks.push(chunk)
})
req.on('end', () => {
resolve(Buffer.concat(chunks))
})
req.end()
})
}
/**
* @returns {Promise<{ code: number | null, stderr: string }>}
*/
async function runThrowingStreamHandler () {
const child = fork(path.join(__dirname, 'fixtures', 'throwing-stream-handler.js'), {
env: {
...process.env,
DD_TRACE_AGENT_PORT: '0',
DD_TRACE_STARTUP_LOGS: 'false',
},
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
})
const [[code], stderr] = await Promise.all([
once(child, 'exit'),
text(child.stderr),
])
return { code, stderr }
}
describe('Plugin', () => {
let http2
let listener
let appListener
let tracer
let port
let app
['http2', 'node:http2'].forEach(pluginToBeLoaded => {
describe(`${pluginToBeLoaded}/server`, () => {
beforeEach(() => {
tracer = require('../../dd-trace')
listener = (req, res) => {
app && app(req, res)
res.writeHead(200)
res.end()
}
})
afterEach(() => {
appListener && appListener.close()
app = null
return agent.close()
})
describe('cancelled request', () => {
/** @type {Promise<void>} */
let requestReceived
/** @type {() => void} */
let resolveRequestReceived
/** @type {Promise<void>} */
let allowHandler
/** @type {() => void} */
let resolveAllowHandler
let responseSent
beforeEach(() => {
requestReceived = new Promise(resolve => { resolveRequestReceived = resolve })
allowHandler = new Promise(resolve => { resolveAllowHandler = resolve })
responseSent = false
listener = (req, res) => {
resolveRequestReceived()
// Only invoke `app` after the test has explicitly allowed it.
// This keeps the test deterministic and removes reliance on wall-clock time.
let closed = false
req.once('close', () => { closed = true })
res.once('close', () => { closed = true })
// Server-side safeguard: if something tries to send a response, record it.
const writeHead = res.writeHead
res.writeHead = function (...args) {
responseSent = true
return writeHead.apply(this, args)
}
const end = res.end
res.end = function (...args) {
responseSent = true
return end.apply(this, args)
}
allowHandler.then(() => {
if (closed) return
app && app(req, res)
res.writeHead(200)
res.end()
})
}
})
beforeEach(() => {
return agent.load('http2')
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
beforeEach(done => {
const server = http2.createServer(listener)
appListener = server
.listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
})
it('should send traces to agent', async () => {
app = sinon.stub()
const tracesPromise = agent.assertSomeTraces(traces => {
// The batch may also contain the client-side http.request span; find the server span.
const serverTrace = traces.find(t => t[0]?.name === 'web.request')
if (!serverTrace) throw new Error('No web.request span found in batch yet')
sinon.assert.notCalled(app) // request should be cancelled before call to app
assertObjectContains(serverTrace[0], {
name: 'web.request',
service: 'test',
type: 'web',
resource: 'GET',
meta: {
'span.kind': 'server',
'http.url': `http://localhost:${port}/user`,
'http.method': 'GET',
'http.status_code': '200',
component: 'http2',
},
})
})
const noop = () => {}
const url = new URL(`http://localhost:${port}/user`)
const client = http2.connect(url.origin)
client.on('error', noop)
const req = client.request({
':path': url.pathname,
':method': 'GET',
})
req.on('error', noop)
let responseReceived = false
req.once('response', () => { responseReceived = true })
req.on('data', () => { responseReceived = true })
const reqClosed = new Promise(resolve => req.once('close', resolve))
req.end()
// Ensure the server has received the request before we cancel it.
await requestReceived
const cancelCode = http2.constants && http2.constants.NGHTTP2_CANCEL
if (typeof req.close === 'function' && cancelCode !== undefined) {
req.close(cancelCode)
} else {
req.destroy()
}
if (typeof client.close === 'function') {
client.close()
} else {
client.destroy()
}
// Give the event loop a chance to process the stream cancellation before allowing
// the server handler to proceed (no fixed sleep, just a few turns).
await setImmediate()
await setImmediate()
await setImmediate()
resolveAllowHandler()
await tracesPromise
// Safeguard: if the handler ran, we'd typically see a response event/data.
// Wait until the stream is fully closed, then assert we never observed a response.
await reqClosed
assert.strictEqual(responseReceived, false)
assert.strictEqual(responseSent, false)
})
})
describe('with OTel semantics enabled', () => {
beforeEach(() => {
process.env.DD_TRACE_OTEL_SEMANTICS_ENABLED = 'true'
return agent.load('http2', { client: false })
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
beforeEach(done => {
appListener = http2.createServer(listener).listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
})
afterEach(() => {
delete process.env.DD_TRACE_OTEL_SEMANTICS_ENABLED
})
it('emits OpenTelemetry server attributes and omits the Datadog ones', done => {
agent.assertSomeTraces(traces => {
const span = traces[0][0]
assertObjectContains(span, {
name: 'web.request',
meta: {
'span.kind': 'server',
'http.request.method': 'GET',
'url.path': '/user',
'url.scheme': 'http',
'server.address': 'localhost',
},
metrics: {
'http.response.status_code': 200,
},
})
assert.ok(!Object.hasOwn(span.meta, 'http.method'))
assert.ok(!Object.hasOwn(span.meta, 'http.url'))
assert.ok(!Object.hasOwn(span.meta, 'http.status_code'))
}).then(done).catch(done)
request(http2, `http://localhost:${port}/user`).catch(done)
})
})
describe('without configuration', () => {
beforeEach(() => {
return agent.load('http2')
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
beforeEach(done => {
const server = http2.createServer(listener)
appListener = server
.listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
})
const spanProducerFn = (done) => {
request(http2, `http://localhost:${port}/user`).catch(done)
}
withNamingSchema(
spanProducerFn,
rawExpectedSchema.server
)
it('publishes a close response event', async () => {
const emit = sinon.spy()
const emitChannel = channel('apm:http2:server:response:emit')
emitChannel.subscribe(emit)
try {
await request(http2, `http://localhost:${port}/user`)
sinon.assert.calledWithMatch(emit, { eventName: 'close' })
} finally {
emitChannel.unsubscribe(emit)
}
})
it('should do automatic instrumentation', done => {
agent
.assertFirstTraceSpan({
name: 'web.request',
service: 'test',
type: 'web',
resource: 'GET',
meta: {
'span.kind': 'server',
'http.url': `http://localhost:${port}/user`,
'http.method': 'GET',
'http.status_code': '200',
component: 'http2',
},
})
.then(done)
.catch(done)
request(http2, `http://localhost:${port}/user`).catch(done)
})
it('should run the request\'s close event in the correct context', done => {
app = (req, res) => {
req.on('close', () => {
assert.strictEqual(tracer.scope().active(), null)
done()
})
}
request(http2, `http://localhost:${port}/user`).catch(done)
})
it('should run the response\'s close event in the correct context', done => {
app = (req, res) => {
const span = tracer.scope().active()
res.on('close', () => {
assert.strictEqual(tracer.scope().active(), span)
done()
})
}
request(http2, `http://localhost:${port}/user`).catch(done)
})
it('should run the finish event in the correct context', done => {
app = (req, res) => {
const span = tracer.scope().active()
res.on('finish', () => {
assert.strictEqual(tracer.scope().active(), span)
done()
})
}
request(http2, `http://localhost:${port}/user`).catch(done)
})
it('should not cause `end` to be called multiple times', done => {
app = (req, res) => {
res.end = sinon.spy(res.end)
res.on('finish', () => {
sinon.assert.calledOnce(res.end)
done()
})
}
request(http2, `http://localhost:${port}/user`).catch(done)
})
})
describe('with a blocklist configuration', () => {
beforeEach(() => {
return agent.load('http2', { client: false, blocklist: '/health' })
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
beforeEach(done => {
const server = http2.createServer(listener)
appListener = server
.listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
})
it('should drop traces for blocklist route', done => {
agent
.assertNoTraces(() => {
throw new Error('Blocklisted routes should not be recorded.')
}, { timeoutMs: 100 })
.then(done, done)
request(http2, `http://localhost:${port}/health`).catch(done)
})
})
describe('with queryStringObfuscation', () => {
describe('set to a regex pattern', () => {
beforeEach(() => {
return agent.load('http2', { client: false, queryStringObfuscation: 'secret=.*?(&|$)' })
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
beforeEach(done => {
const server = http2.createServer(listener)
appListener = server
.listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
})
it('should obfuscate matching query string parameters', done => {
agent
.assertFirstTraceSpan({
name: 'web.request',
service: 'test',
type: 'web',
resource: 'GET',
meta: {
'span.kind': 'server',
'http.url': `http://localhost:${port}/user?<redacted>foo=bar`,
'http.method': 'GET',
'http.status_code': '200',
component: 'http2',
},
})
.then(done)
.catch(done)
request(http2, `http://localhost:${port}/user?secret=password&foo=bar`).catch(done)
})
})
describe('set to true', () => {
beforeEach(() => {
return agent.load('http2', { client: false, queryStringObfuscation: true })
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
beforeEach(done => {
const server = http2.createServer(listener)
appListener = server
.listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
})
it('should remove the entire query string', done => {
agent
.assertFirstTraceSpan({
name: 'web.request',
service: 'test',
type: 'web',
resource: 'GET',
meta: {
'span.kind': 'server',
'http.url': `http://localhost:${port}/user`,
'http.method': 'GET',
'http.status_code': '200',
component: 'http2',
},
})
.then(done)
.catch(done)
request(http2, `http://localhost:${port}/user?secret=password&foo=bar`).catch(done)
})
})
describe('set to false', () => {
beforeEach(() => {
return agent.load('http2', { client: false, queryStringObfuscation: false })
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
beforeEach(done => {
const server = http2.createServer(listener)
appListener = server
.listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
})
it('should not obfuscate the query string', done => {
agent
.assertFirstTraceSpan({
name: 'web.request',
service: 'test',
type: 'web',
resource: 'GET',
meta: {
'span.kind': 'server',
'http.url': `http://localhost:${port}/user?secret=password&foo=bar`,
'http.method': 'GET',
'http.status_code': '200',
component: 'http2',
},
})
.then(done)
.catch(done)
request(http2, `http://localhost:${port}/user?secret=password&foo=bar`).catch(done)
})
})
})
describe('core API', () => {
beforeEach(() => {
return agent.load('http2', { client: false })
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
function listen (server, done) {
appListener = server.listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
}
describe('server.on(\'stream\')', () => {
beforeEach(done => {
const server = http2.createServer()
server.on('stream', (stream) => {
stream.respond({ ':status': 200 })
stream.end()
})
listen(server, done)
})
it('should instrument the core stream API', done => {
agent
.assertFirstTraceSpan({
name: 'web.request',
service: 'test',
type: 'web',
resource: 'GET',
meta: {
'span.kind': 'server',
'http.url': `http://localhost:${port}/user`,
'http.method': 'GET',
'http.status_code': '200',
component: 'http2',
},
})
.then(done)
.catch(done)
request(http2, `http://localhost:${port}/user`).catch(done)
})
it('should produce exactly one server span per request', async () => {
await assertSingleServerSpan(http2, `http://localhost:${port}/user`)
})
it('should run the stream\'s close event in the correct context', done => {
const server = appListener
server.removeAllListeners('stream')
server.on('stream', (stream) => {
const span = tracer.scope().active()
stream.once('close', () => {
assert.strictEqual(tracer.scope().active(), span)
done()
})
stream.respond({ ':status': 200 })
stream.end()
})
request(http2, `http://localhost:${port}/user`).catch(done)
})
it('reports status 200 for a stream aborted before it responded', done => {
const server = appListener
server.removeAllListeners('stream')
server.on('stream', (stream) => {
stream.on('error', () => {})
// Close without responding: `stream.sentHeaders` stays empty, so the
// adapter falls back to the compatibility default of 200 instead of
// tagging the span as an error with no status.
stream.close(http2.constants.NGHTTP2_INTERNAL_ERROR)
})
agent
.assertFirstTraceSpan({
name: 'web.request',
resource: 'GET',
error: 0,
meta: {
'span.kind': 'server',
'http.method': 'GET',
'http.status_code': '200',
component: 'http2',
},
})
.then(done)
.catch(done)
request(http2, `http://localhost:${port}/user`).catch(() => {})
})
})
describe('a server owned by another instrumentation', () => {
// Mirrors what the @grpc/grpc-js instrumentation does at server
// creation. The mark must make the http2 instrumentation skip the
// server entirely so the owning integration keeps the only span.
it('produces no web.request span when the server is marked foreign', async () => {
const server = http2.createServer()
server[FOREIGN_HTTP2_SERVER] = true
server.on('stream', (stream) => {
stream.respond({ ':status': 200 })
stream.end()
})
await new Promise(resolve => listen(server, resolve))
let serverSpanCount = 0
const countHandler = traces => {
serverSpanCount += traces.flat().filter(span => span.name === 'web.request').length
}
agent.subscribe(countHandler)
try {
await request(http2, `http://localhost:${port}/user`)
for (let drain = 0; drain < 5; drain++) await setImmediate()
assert.strictEqual(serverSpanCount, 0)
} finally {
agent.unsubscribe(countHandler)
}
})
it('still traces an unmarked server on the same code path', async () => {
const server = http2.createServer()
server.on('stream', (stream) => {
stream.respond({ ':status': 200 })
stream.end()
})
await new Promise(resolve => listen(server, resolve))
await Promise.all([
agent.assertFirstTraceSpan({ name: 'web.request', meta: { component: 'http2' } }),
request(http2, `http://localhost:${port}/user`),
])
})
})
describe('with configured headers', () => {
// The parent `core API` `beforeEach` already started the mock agent;
// reconfigure the plugin in place instead of `agent.load`, which would
// start a second agent and leak the first server's handle.
beforeEach(() => {
agent.reload('http2', { client: false, headers: ['x-foo', 'x-resp:resp_tag'] })
})
beforeEach(done => {
const server = http2.createServer()
server.on('stream', (stream) => {
stream.respond({ ':status': 200, 'x-resp': 'sent' })
stream.end()
})
listen(server, done)
})
it('tags configured request and response headers from the stream', done => {
agent
.assertFirstTraceSpan({
name: 'web.request',
meta: {
component: 'http2',
'http.request.headers.x-foo': 'bar',
resp_tag: 'sent',
},
})
.then(done)
.catch(done)
const url = new URL(`http://localhost:${port}/user`)
const client = http2.connect(url.origin).on('error', done)
const req = client.request({ ':path': url.pathname, ':method': 'GET', 'x-foo': 'bar' })
req.on('error', done)
req.on('end', () => client.close())
req.resume()
req.end()
})
})
describe('compatibility servers do not double-span', () => {
/** @param {import('node:http2').Http2Server} server */
function listenAsync (server) {
return new Promise(resolve => listen(server, resolve))
}
it('createServer(handler) produces exactly one server span', async () => {
const server = http2.createServer((req, res) => {
res.writeHead(200)
res.end()
})
await listenAsync(server)
await assertSingleServerSpan(http2, `http://localhost:${port}/user`)
})
it('createServer().on(\'request\') produces exactly one server span', async () => {
const server = http2.createServer()
server.on('request', (req, res) => {
res.writeHead(200)
res.end()
})
await listenAsync(server)
await assertSingleServerSpan(http2, `http://localhost:${port}/user`)
})
it('a server with both request and stream listeners produces exactly one server span', async () => {
const server = http2.createServer((req, res) => {
res.writeHead(200)
res.end()
})
server.on('stream', () => {})
await listenAsync(server)
await assertSingleServerSpan(http2, `http://localhost:${port}/user`)
})
it('keeps the server span active inside a mixed setup\'s stream listener', async () => {
let streamActive
const server = http2.createServer((req, res) => {
res.writeHead(200)
res.end()
})
server.on('stream', () => {
streamActive = tracer.scope().active()
})
await listenAsync(server)
const traceAsserted = agent.assertFirstTraceSpan(span => {
assert.ok(streamActive, 'stream listener ran without an active span')
assert.strictEqual(streamActive.context().toSpanId(), span.span_id.toString())
})
await Promise.all([traceAsserted, request(http2, `http://localhost:${port}/user`)])
})
describe('exposing the real compatibility req/res', () => {
let hookRes
beforeEach(() => {
hookRes = undefined
agent.reload('http2', {
client: false,
hooks: {
request (span, req, res) {
hookRes = res
},
},
})
})
it('hands the real compatibility req/res to the finish hook and web helpers', async () => {
let activeInRequestListener
const server = http2.createServer((req, res) => {
activeInRequestListener = tracer.scope().active()
// Setting the route through the shared web lifecycle only reaches
// the span when the real `req` resolves to the stream's context.
web.setRoute(req, '/users/:id')
res.writeHead(200)
res.end()
})
server.on('stream', () => {})
await listenAsync(server)
const traceAsserted = agent.assertFirstTraceSpan(span => {
assert.ok(activeInRequestListener, 'request listener ran without an active span')
assert.strictEqual(
activeInRequestListener.context().toSpanId(),
span.span_id.toString(),
'the request listener saw a different span than the one that finished'
)
assertObjectContains(span, { resource: 'GET /users/:id' })
// The synthetic stream adapter has no `writeHead`; only the real
// `Http2ServerResponse` this path used to expose does.
assert.strictEqual(typeof hookRes?.writeHead, 'function')
})
await Promise.all([traceAsserted, request(http2, `http://localhost:${port}/users/42`)])
})
})
})
})
describe('core API distributed tracing', () => {
beforeEach(() => {
return agent.load('http2')
.then(() => {
http2 = require(pluginToBeLoaded)
})
})
beforeEach(done => {
const server = http2.createServer()
server.on('stream', (stream) => {
stream.respond({ ':status': 200 })
stream.end()
})
appListener = server.listen(0, 'localhost', () => {
port = appListener.address().port
done()
})
})
it('makes the core server span a child of the client span', async () => {
const spans = []
const collect = traces => spans.push(...traces.flat())
agent.subscribe(collect)
try {
await request(http2, `http://localhost:${port}/user`)
for (let drain = 0; drain < 5; drain++) await setImmediate()
const clientSpan = spans.find(span => span.meta?.['span.kind'] === 'client')
const serverSpan = spans.find(span => span.name === 'web.request')
assert.ok(clientSpan, 'expected an http2 client span')
assert.ok(serverSpan, 'expected a core-API server span')
assert.strictEqual(serverSpan.trace_id.toString(), clientSpan.trace_id.toString())
assert.strictEqual(serverSpan.parent_id.toString(), clientSpan.span_id.toString())
} finally {
agent.unsubscribe(collect)
}
})
})
})
})
describe('http2/server error propagation', () => {
it('rethrows synchronous stream handler errors', async () => {
const { code, stderr } = await runThrowingStreamHandler()
assert.strictEqual(code, 1)
assert.match(stderr, /Error: expected stream handler failure/)
})
})
})
/**
* Drive one request and assert the agent receives exactly one `web.request`
* span for it. A compatibility server emits both 'request' and 'stream'; a
* regression that drops the core-API request-listener gate produces a second
* `web.request` span that flushes in a later payload, so the count accumulates
* across every payload and is read only after the request has fully closed and
* the flush turns have drained (`flushInterval` is 0 under the test agent).
*
* @param {typeof import('http2')} http2
* @param {string} url
*/
async function assertSingleServerSpan (http2, url) {
let serverSpanCount = 0
const countHandler = traces => {
serverSpanCount += traces.flat().filter(span => span.name === 'web.request').length
}
agent.subscribe(countHandler)
try {
await request(http2, url)
// Let every flush for the request drain (flushInterval is 0, so each
// finished trace chunk is sent on the next turns) before reading the count.
for (let drain = 0; drain < 5; drain++) await setImmediate()
assert.strictEqual(serverSpanCount, 1)
} finally {
agent.unsubscribe(countHandler)
}
}