Skip to content

Commit

Permalink
Destroy socket if when no timeout listener is found
Browse files Browse the repository at this point in the history
  • Loading branch information
yassernasc committed Jul 1, 2024
1 parent 63b13c2 commit c159111
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ module.exports = class HTTPServer extends TCPServer {
this._timeout = 0

this.on('connection', (socket) => {
new HTTPServerConnection(this, socket, opts)
const conn = new HTTPServerConnection(this, socket, opts)

if (this._timeout) {
socket.setTimeout(this._timeout)
socket.once('timeout', () => this.emit('timeout', socket))
socket.once('timeout', () => this._ontimeout(conn))
}
})

Expand All @@ -34,4 +34,12 @@ module.exports = class HTTPServer extends TCPServer {

return this
}

_ontimeout (conn) {
const reqTimeout = conn.req && conn.req.emit('timeout')
const resTimeout = conn.res && conn.res.emit('timeout')
const serverTimeout = this.emit('timeout', conn.socket)

if (!reqTimeout && !resTimeout && !serverTimeout) conn.socket.destroy()
}
}
34 changes: 34 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,40 @@ test('server timeout', async function (t) {
server.close()
})

test('close the server at timeout if do not have any handler', async function (t) {
t.plan(1)
const server = http.createServer().listen(0).setTimeout(100)

await waitForServer(server)

const client = http.request({ port: server.address().port })

client.on('error', () => {
t.pass()

server.close()
})
})

test('do not close the server at timeout if a handler is found', async function (t) {
t.plan(1)

const server = http.createServer((req, res) => {
res.on('timeout', () => {
t.pass('response timeout')

res.end()
server.close()
})
})

server.listen(0).setTimeout(100)

await waitForServer(server)

http.request({ port: server.address().port }).end()
})

test('server response timeout', async function (t) {
const sub = t.test()
sub.plan(2)
Expand Down

0 comments on commit c159111

Please sign in to comment.