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

connection: use ping-pong instead of heartbeat #303

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
64 changes: 21 additions & 43 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

const { EventEmitter } = require('events');
const semver = require('semver');
const timers = require('timers');

const common = require('./common');
const serde = require('./serde');
Expand Down Expand Up @@ -53,18 +52,15 @@ class Connection extends EventEmitter {
this.application = null;
this.remoteProxies = {};

this._heartbeatCallbackInstance = null;
this._heartbeatInterval = null;
Copy link
Member

Choose a reason for hiding this comment

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

I think it will be more appropriate to call this field _heartbeatTimer or _heartbeatTimeout because it is somewhat confusing to use interval here, due to the same word being used as a parameter name in startHeartbeat method and having the meaning of the delay between heartbeats.

this._closed = false;

// Defined in constructor to be used as default callback in callMethod
// without binding it.
this._emitError = (error) => {
if (error) this.emit('error', error);
};

// Defined in constructor to be used as heartbeat message
// in debug mode events
this._heartbeatMessage = {};

transport.on('message', this._processMessage.bind(this));
transport.on('close', this._onSocketClose.bind(this));
transport.on('error', this._onSocketError.bind(this));
Expand Down Expand Up @@ -241,33 +237,36 @@ class Connection extends EventEmitter {
// Send a pong message
//
pong(messageId) {
if (this._closed) {
Copy link
Member

Choose a reason for hiding this comment

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

Given that it's a public method, I'd say that the caller shouldn't invoke pong() if the connection is closed. Otherwise, this check makes pong() inconsistent with other methods of a connection in a way that one may call it on a closed connection without any errors, which doesn't sound right.

Copy link
Member Author

Choose a reason for hiding this comment

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

@aqrln mark pong as a private method, there is no reason for it to be public.

Copy link
Member

@aqrln aqrln Nov 22, 2017

Choose a reason for hiding this comment

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

@nechaido sounds good to me, but the same goes for callback, then. (Though it's kinda out of scope of this PR.)

UPD: #306

return;
}
const message = { pong: [messageId] };
this._send(this._prepareMessage(message), message);
}

// Start sending heartbeat messages
// Start sending ping messages
// interval - heartbeat interval in milliseconds
//
startHeartbeat(interval) {
const callback = () => {
this.transport.send('{}');
this.setTimeout(interval, this._heartbeatCallbackInstance);

if (process.env.NODE_ENV !== 'production') {
this.emit('heartbeat', this._heartbeatMessage);
const heartbeat = () => {
if (this._closed) {
Copy link
Member

Choose a reason for hiding this comment

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

This can be simplified to

if (!this._closed) {
  this.ping();
}

return;
}
const pingId = this._nextMessageId;
this.ping(() => {
this.session.unbufferUpTo(pingId);
});
};

this._heartbeatCallbackInstance = callback;
callback();
this._heartbeatInterval = setInterval(heartbeat, interval);
}

// Stop sending heartbeat messages
// Stop sending ping messages
//
stopHeartbeat() {
if (this._heartbeatCallbackInstance) {
this.clearTimeout(this._heartbeatCallbackInstance);
this._heartbeatCallbackInstance = null;
if (this._heartbeatInterval) {
clearTimeout(this._heartbeatInterval);
this._heartbeatInterval = null;
}
}

Expand Down Expand Up @@ -320,40 +319,17 @@ class Connection extends EventEmitter {
// Close the connection
//
close() {
this._closed = true;
this.stopHeartbeat();
this.transport.end();
}

// Set a timeout using timers.enroll()
// milliseconds - amount of milliseconds
// callback - callback function
//
setTimeout(milliseconds, callback) {
timers.enroll(this, milliseconds);
timers._unrefActive(this);
this.once('_timeout', callback);
}

// Clear a timeout set with Connection#setTimeout
// handler - timer callback to remove
//
clearTimeout(handler) {
timers.unenroll(this);
this.removeListener('_timeout', handler);
}

// Returns underlying transport
//
getTransport() {
return this.transport.getRawTransport();
}

// timers.enroll() timeout handler
//
_onTimeout() {
this.emit('_timeout');
}

// Prepare a JSTP message to be sent over this connection
// message - a message to prepare
//
Expand Down Expand Up @@ -383,6 +359,7 @@ class Connection extends EventEmitter {
// message - a message to send (optional)
//
_end(message) {
this._closed = true;
this.stopHeartbeat();

if (message) {
Expand All @@ -400,6 +377,7 @@ class Connection extends EventEmitter {
// Closed socket event handler
//
_onSocketClose() {
this.closed = true;
Copy link
Member

Choose a reason for hiding this comment

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

Looks like there is a typo here, it should be this._closed instead of this.closed.

this.stopHeartbeat();
this.emit('close', this);
if (this.server) {
Expand Down
4 changes: 2 additions & 2 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,10 @@ class Server {
}
};

connection.setTimeout(HANDSHAKE_TIMEOUT, handleTimeout);
const handshakeTimeout = setTimeout(handleTimeout, HANDSHAKE_TIMEOUT);

connection.on('client', () => {
connection.clearTimeout(handleTimeout);
clearTimeout(handshakeTimeout);
if (this.heartbeatInterval) {
connection.startHeartbeat(this.heartbeatInterval);
}
Expand Down
10 changes: 7 additions & 3 deletions lib/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ class Session extends Map {
Object.preventExtensions(this);
}

unbufferUpTo(id) {
for (let i = this.guaranteedDeliveredCount + 1; i <= id; i++) {
this.buffer.delete(i);
}
}

_bufferMessage(id, message) {
this.buffer.set(Math.abs(id), message);
this.latestBufferedMessageId = id;
Expand All @@ -47,10 +53,8 @@ class Session extends Map {
if (this.connection) {
this.connection.close();
}
this.unbufferUpTo(recievedCount);
this.connection = newConnection;
for (let i = this.guaranteedDeliveredCount + 1; i <= recievedCount; i++) {
this.buffer.delete(i);
}
this.guaranteedDeliveredCount = recievedCount;
}

Expand Down
35 changes: 29 additions & 6 deletions test/node/connection-emit-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@ const jstp = require('../..');

const app = require('../fixtures/application');

const HEARTBEAT_INTERVAL = 100;

const application = new jstp.Application(app.name, app.interfaces);
const serverConfig = {
applications: [application],
authPolicy: app.authCallback,
heartbeatInterval: HEARTBEAT_INTERVAL,
};

let server;
Expand Down Expand Up @@ -191,14 +194,34 @@ test.test('must emit messages in development mode', (test) => {
});

test.test('must emit heartbeat messages in development mode', (test) => {
test.plan(2);
test.plan(4);
const received = {
serverPing: false,
serverPong: false,
clientPing: false,
clientPong: false,
};

server.getClientsArray()[0].on('heartbeat', (message) => {
test.strictSame(message, {}, 'heartbeat message must match on server side');
server.getClientsArray()[0].on('incomingMessage', (message) => {
if (message.ping !== undefined) {
received.serverPing = true;
} else if (message.pong !== undefined) {
received.serverPong = true;
}
});
connection.on('heartbeat', (message) => {
test.strictSame(message, {}, 'heartbeat message must match on client side');
connection.on('incomingMessage', (message) => {
if (message.ping !== undefined) {
received.clientPing = true;
} else if (message.pong !== undefined) {
received.clientPong = true;
}
});

connection.startHeartbeat(100);
connection.startHeartbeat(HEARTBEAT_INTERVAL);
setTimeout(() => {
test.assert(received.serverPing, 'server must receive ping message');
test.assert(received.serverPong, 'server must receive pong message');
test.assert(received.clientPing, 'client must receive ping message');
test.assert(received.clientPing, 'client must receive pong message');
}, 2 * HEARTBEAT_INTERVAL);
});
6 changes: 4 additions & 2 deletions test/node/regress-gh-283.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ server.listen(() => {

let heartbeatsCount = 0;

connection.on('heartbeat', () => {
heartbeatsCount++;
connection.on('incomingMessage', (message) => {
if (message.ping !== undefined) {
heartbeatsCount++;
}
});

setTimeout(() => {
Expand Down