Skip to content

Commit

Permalink
Disconnect if no response to keepalive
Browse files Browse the repository at this point in the history
  • Loading branch information
Jean Aunis committed Jan 27, 2023
1 parent de316ab commit 4bf3d25
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions lib/AmiClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ class AmiClient extends EventEmitter{
_connector: null,
_kaTimer: null,
_kaActionId: null,
_lastKa: 0,
_lastKaResponse: 0,
_options: Object.assign({
reconnect: false,
maxAttemptsCount: 30,
Expand Down Expand Up @@ -115,7 +117,7 @@ class AmiClient extends EventEmitter{
.on('response', response => {
if(this._options.keepAlive && response.ActionID === this._kaActionId){
debugLog('keep-alive heart bit');
this._keepAliveBit();
this._lastKaResponse = this._now();
return;
}

Expand All @@ -138,7 +140,7 @@ class AmiClient extends EventEmitter{
.on('data', chunk => this.emit('data', chunk))
.on('error', error => this.emit('internalError', error))
.on('close', () => {
clearTimeout(this._kaTimer);
clearInterval(this._kaTimer);
this.emit('disconnect');
this._prEmitter.emit('disconnect');
setTimeout(() => {
Expand All @@ -156,6 +158,8 @@ class AmiClient extends EventEmitter{
});

if(this._options.keepAlive){
this._lastKa = 0;
this._lastKaResponse = 0;
this._keepAliveBit();
}
return this._connection;
Expand All @@ -167,7 +171,7 @@ class AmiClient extends EventEmitter{
*/
disconnect(){
this._userDisconnect = true;
clearTimeout(this._kaTimer);
clearInterval(this._kaTimer);
this.emit('disconnect');
if(this._connection){
this._connection.close();
Expand Down Expand Up @@ -261,18 +265,31 @@ class AmiClient extends EventEmitter{
return this._prepareOptions();
}


_now(){
return Math.floor(Date.now()/1000);
}
/**
* Keep-alive heart bit handler
* @private
*/
_keepAliveBit(){
this._kaTimer = setTimeout(() => {
this._kaTimer = setInterval(() => {
if(this._options.keepAlive && this._connection && this.isConnected){
if(this._lastKa > 0 && this._lastKaResponse < this._lastKa) {
/* Asterisk manager did not reply - let's disconnect */
debugLog("disconnect on KA timer");
this.disconnect();
/* reset the _userDisconnect flag so that we reconnect automatically */
this._userDisconnect = false;
return;
}
this._kaActionId = this._genActionId(this._specPrefix);
this._connection.write({
Action: 'Ping',
ActionID: this._kaActionId
});
this._lastKa = this._now();
}
}, this._options.keepAliveDelay);
this._kaTimer.unref();
Expand Down

1 comment on commit 4bf3d25

@pedrohmonico
Copy link

Choose a reason for hiding this comment

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

Does this fix help with the eventemitter leak error message?

Please sign in to comment.