Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for the TCP_USER_TIMEOUT option #103

Merged
merged 5 commits into from
Nov 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ The Missing (`TCP_KEEPINTVL` and `TCP_KEEPCNT`) `SO_KEEPALIVE` socket option set

Tested on 🐧 `linux` & 🍏 `osx` (both `amd64` and `arm64`), should work on 😈 `freebsd` and others. Does not work on 🐄 `win32` (pull requests welcome).

There's also support for getting & setting the `TCP_USER_TIMEOUT` (linux 🐧 only) option, which is closely related to keep-alive.

## Install

```bash
Expand Down
9 changes: 9 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,12 @@ export function setKeepAliveProbes(
export function getKeepAliveProbes(
socket: NodeJSSocketWithFileDescriptor
): number

export function setUserTimeout(
socket: NodeJSSocketWithFileDescriptor,
timeout: number
): boolean

export function getUserTimeout(
socket: NodeJSSocketWithFileDescriptor
): number
2 changes: 2 additions & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import { expectType } from 'tsd'
Net.createServer((incomingSocket) => {
expectType<boolean>(NetKeepAlive.setKeepAliveInterval(incomingSocket, 1000))
expectType<boolean>(NetKeepAlive.setKeepAliveProbes(incomingSocket, 1))
expectType<boolean>(NetKeepAlive.setUserTimeout(incomingSocket, 5000))
})

const clientSocket = Net.createConnection({port: -1})
expectType<boolean>(NetKeepAlive.setKeepAliveInterval(clientSocket, 1000))
expectType<boolean>(NetKeepAlive.setKeepAliveProbes(clientSocket, 1))
expectType<boolean>(NetKeepAlive.setUserTimeout(clientSocket, 5000))
2 changes: 2 additions & 0 deletions lib/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const Constants = {
SOL_TCP: 6,
TCP_KEEPINTVL: undefined,
TCP_KEEPCNT: undefined,
TCP_USER_TIMEOUT: undefined,
}

switch (OS.platform()) {
Expand All @@ -23,6 +24,7 @@ switch (OS.platform()) {
default:
Constants.TCP_KEEPINTVL = 5
Constants.TCP_KEEPCNT = 6
Constants.TCP_USER_TIMEOUT = 18
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like this feature is actually not supported on freebsd and darwin (not tested, assumption based, see review comment for details).

For those platforms the value would be undefiend which might cause segfault and I'm not sure what would happen in that case, most likely not what the user intended to do so I suggest throwing in set and get methods if this constant is null or undefiend (==null).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes a lot of sense, yes. I'll do that when I find some time.

break
}

Expand Down
93 changes: 93 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,96 @@ module.exports.getKeepAliveProbes = function getKeepAliveProbes(socket) {

return cntVal.deref()
}

/**
* Sets the TCP_USER_TIMEOUT value for specified socket.
*
* Note: The msec will be rounded towards the closest integer
*
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest lightly mentioning the interaction between TCP_USER_TIMEOUT and TCP_KEEPALIVE. And provide a link to man page for it. For developer experience purposes.

Suggested change
*
* Note: When used with the TCP keepalive option, TCP_USER_TIMEOUT will override
keepalive to determine when to close a connection due to keepalive failure.

Source: https://man7.org/linux/man-pages/man7/tcp.7.html

* @since v1.4.0
* @param {Net.Socket} socket to set the value for
* @param {number} msecs to wait for unacknowledged data before closing the connection
*
* @returns {boolean} <code>true</code> on success
*
* @example <caption>Set user timeout to 30 seconds (<code>30000</code> milliseconds) for socket <code>s</code></caption>
* NetKeepAlive.setUserTimeout(s, 30000)
*
* @throws {AssertionError} setUserTimeout requires two arguments
* @throws {AssertionError} setUserTimeout expects an instance of socket as its first argument
* @throws {AssertionError} setUserTimeout requires msec to be a Number
* @throws {ErrnoException|Error} Unexpected error
*/
module.exports.setUserTimeout = function setUserTimeout(
socket,
msecs
) {
Assert.strictEqual(
arguments.length,
2,
'setUserTimeout requires two arguments'
)
Assert(
_isSocket(socket),
'setUserTimeout expects an instance of socket as its first argument'
)
Assert.strictEqual(
msecs != null ? msecs.constructor : void 0,
Number,
'setUserTimeout requires msec to be a Number'
)

const fd = _getSocketFD(socket),
msecInt = ~~msecs,
msecVal = Ref.alloc('int', msecInt),
msecValLn = msecVal.type.size

return FFIBindings.setsockopt(
fd,
Constants.SOL_TCP,
Constants.TCP_USER_TIMEOUT,
msecVal,
msecValLn
)
}

/**
* Returns the TCP_USER_TIMEOUT value for specified socket.
*
* @since v1.4.0
* @param {Net.Socket} socket to check the value for
*
* @returns {number} msecs to wait for unacknowledged data before closing the connection
*
* @example <caption>Get the current user timeout for socket <code>s</code></caption>
* NetKeepAlive.getUserTimeout(s) // returns 30000 based on setter example
*
* @throws {AssertionError} getUserTimeout requires one arguments
* @throws {AssertionError} getUserTimeout expects an instance of socket as its first argument
* @throws {ErrnoException|Error} Unexpected error
*/
module.exports.getUserTimeout = function getUserTimeout(socket) {
Assert.strictEqual(
arguments.length,
1,
'getUserTimeout requires one arguments'
)
Assert(
_isSocket(socket),
'getUserTimeout expects an instance of socket as its first argument'
)

const fd = _getSocketFD(socket),
msecVal = Ref.alloc(Ref.types.uint32),
msecValLn = Ref.alloc(Ref.types.uint32, msecVal.type.size)

FFIBindings.getsockopt(
fd,
Constants.SOL_TCP,
Constants.TCP_USER_TIMEOUT,
msecVal,
msecValLn
)

return msecVal.deref()
}
2 changes: 2 additions & 0 deletions test/unit/test-constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ describe('constants', () => {
SOL_TCP: 6,
TCP_KEEPINTVL: 5,
TCP_KEEPCNT: 6,
TCP_USER_TIMEOUT: 18,
})
})

Expand All @@ -67,6 +68,7 @@ describe('constants', () => {
SOL_TCP: 6,
TCP_KEEPINTVL: 5,
TCP_KEEPCNT: 6,
TCP_USER_TIMEOUT: 18,
})
})
})
114 changes: 114 additions & 0 deletions test/unit/test-timeout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
const Stream = require('stream')
const Should = require('should')
const OS = require('os')
const Net = require('net')
const Lib = require('../../lib')

describe('TCP User Timeout', () => {
const itSkipOS = (skipOs, ...args) =>
(skipOs.includes(OS.platform()) ? it.skip : it)(...args)

it('should be a function', function () {
Lib.setUserTimeout.should.be.type('function')
})

it('should validate passed arguments', function () {
;(() => Lib.setUserTimeout()).should.throw(
'setUserTimeout requires two arguments'
)
;(() => Lib.setUserTimeout('')).should.throw(
'setUserTimeout requires two arguments'
)
;(() => Lib.setUserTimeout('', '', '')).should.throw(
'setUserTimeout requires two arguments'
)
;(() => Lib.setUserTimeout(null, 1)).should.throw(
'setUserTimeout expects an instance of socket as its first argument'
)
;(() => Lib.setUserTimeout({}, 1)).should.throw(
'setUserTimeout expects an instance of socket as its first argument'
)
;(() => Lib.setUserTimeout(new (class {})(), 1)).should.throw(
'setUserTimeout expects an instance of socket as its first argument'
)
;(() => Lib.setUserTimeout(new Stream.PassThrough(), 1)).should.throw(
'setUserTimeout expects an instance of socket as its first argument'
)

const socket = new Net.Socket()
;(() => Lib.setUserTimeout(socket, null)).should.throw(
'setUserTimeout requires msec to be a Number'
)
;(() => Lib.setUserTimeout(socket, '')).should.throw(
'setUserTimeout requires msec to be a Number'
)
;(() => Lib.setUserTimeout(socket, true)).should.throw(
'setUserTimeout requires msec to be a Number'
)
;(() => Lib.setUserTimeout(socket, {})).should.throw(
'setUserTimeout requires msec to be a Number'
)
})

itSkipOS(
['darwin', 'freebsd'],
'should throw when setsockopt returns -1',
(done) => {
const srv = Net.createServer()
srv.listen(0, () => {
const socket = Net.createConnection(srv.address(), () => {
;(() => Lib.setUserTimeout(socket, -1)).should.throw(
/^setsockopt /i
)
socket.destroy()
srv.close(done)
})
})
}
)

itSkipOS(['darwin', 'freebsd'], 'should be able to set and get 4 second value', (done) => {
const srv = Net.createServer()
srv.listen(0, () => {
const expected = 4000

const socket = Net.createConnection(srv.address(), () => {
;(() => {
Lib.setUserTimeout(socket, expected)
}).should.not.throw()

let actual
;(() => {
actual = Lib.getUserTimeout(socket)
}).should.not.throw()

expected.should.eql(actual)

socket.destroy()
srv.close(done)
})
})
})

itSkipOS(['darwin', 'freebsd'], 'should throw when trying to get using invalid fd', (done) => {
;(() => Lib.setUserTimeout(new Net.Socket(), 1)).should.throw(
'Unable to get socket fd'
)

const srv = Net.createServer()
srv.listen(0, function () {
const socket = Net.createConnection(this.address(), () => {
const oldHandle = socket._handle

socket._handle = { fd: -99999 }
;(() => Lib.getUserTimeout(socket)).should.throw(
'getsockopt EBADF'
)

socket._handle = oldHandle
socket.destroy()
srv.close(done)
})
})
})
})