Skip to content

Commit b7e4f8e

Browse files
authored
test: destroy active connections when stopping fake agent (#5853)
The fake agent is used in tests and is stopped after the test is done. When calling its `stop` function, it will wait for active connections (sockets) to close before considering itself stopped. This can add an unnecessary waiting period after each test, as the timeout on the socket by default is two seconds in our code-base: https://github.com/DataDog/dd-trace-js/blob/90fe64b9845d04d6273ec2b7a36ba6a7844b8253/packages/dd-trace/src/exporters/common/request.js#L56 For integration tests making heavy use of fake agents, this can add several minutes of overhead that can be avoided by destroying the sockets when calling the `stop` function on the fake agent. This mainly affects tests running on Node.js 18, as sockets there for some reason takes a little longer to clear out.
1 parent ffcef30 commit b7e4f8e

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

integration-tests/helpers/fake-agent.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ module.exports = class FakeAgent extends EventEmitter {
1414
super({ captureRejections: true })
1515
this.port = port
1616
this.resetRemoteConfig()
17+
this._sockets = new Set()
1718
}
1819

1920
async start () {
@@ -23,6 +24,15 @@ module.exports = class FakeAgent extends EventEmitter {
2324
}, 10000)
2425
this.server = http.createServer(buildExpressServer(this))
2526
this.server.on('error', reject)
27+
28+
// Track connections to force close them later
29+
this.server.on('connection', (socket) => {
30+
this._sockets.add(socket)
31+
socket.on('close', () => {
32+
this._sockets.delete(socket)
33+
})
34+
})
35+
2636
this.server.listen(this.port, () => {
2737
this.port = this.server.address().port
2838
clearTimeout(timeoutObj)
@@ -32,7 +42,14 @@ module.exports = class FakeAgent extends EventEmitter {
3242
}
3343

3444
stop () {
45+
if (!this.server) return Promise.resolve()
46+
3547
return new Promise((resolve) => {
48+
if (!this.server?.listening) return resolve()
49+
for (const socket of this._sockets) {
50+
socket.destroy()
51+
}
52+
this._sockets.clear()
3653
this.server.on('close', resolve)
3754
this.server.close()
3855
})

0 commit comments

Comments
 (0)