npmtest-pomelo (v0.0.1)

Code coverage report for node-npmtest-pomelo/node_modules/pomelo-rpc/lib/rpc-client/mailboxes/mqtt-mailbox.js

Statements: 14.81% (24 / 162)      Branches: 0% (0 / 60)      Functions: 0% (0 / 23)      Lines: 14.81% (24 / 162)      Ignored: none     

All files » node-npmtest-pomelo/node_modules/pomelo-rpc/lib/rpc-client/mailboxes/ » mqtt-mailbox.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 2821 1 1 1 1 1 1 1   1   1                                           1   1                                                                                                                                                 1                                       1                                                                                 1             1                                                   1       1               1             1           1                                       1                           1                                 1      
var logger = require('pomelo-logger').getLogger('pomelo-rpc', 'mqtt-mailbox');
var EventEmitter = require('events').EventEmitter;
var constants = require('../../util/constants');
var Tracer = require('../../util/tracer');
var MqttCon = require('mqtt-connection');
var utils = require('../../util/utils');
var util = require('util');
var net = require('net');
 
var CONNECT_TIMEOUT = 2000;
 
var MailBox = function(server, opts) {
  EventEmitter.call(this);
  this.curId = 0;
  this.id = server.id;
  this.host = server.host;
  this.port = server.port;
  this.requests = {};
  this.timeout = {};
  this.queue = [];
  this.bufferMsg = opts.bufferMsg;
  this.keepalive = opts.keepalive || constants.DEFAULT_PARAM.KEEPALIVE;
  this.interval = opts.interval || constants.DEFAULT_PARAM.INTERVAL;
  this.timeoutValue = opts.timeout || constants.DEFAULT_PARAM.CALLBACK_TIMEOUT;
  this.keepaliveTimer = null;
  this.lastPing = -1;
  this.lastPong = -1;
  this.connected = false;
  this.closed = false;
  this.opts = opts;
  this.serverId = opts.context.serverId;
};
 
util.inherits(MailBox, EventEmitter);
 
MailBox.prototype.connect = function(tracer, cb) {
  tracer && tracer.info('client', __filename, 'connect', 'mqtt-mailbox try to connect');
  if (this.connected) {
    tracer && tracer.error('client', __filename, 'connect', 'mailbox has already connected');
    return cb(new Error('mailbox has already connected.'));
  }
 
  var self = this;
 
  var stream = net.createConnection(this.port, this.host);
  this.socket = MqttCon(stream);
 
  var connectTimeout = setTimeout(function() {
    logger.error('rpc client %s connect to remote server %s timeout', self.serverId, self.id);
    self.emit('close', self.id);
  }, CONNECT_TIMEOUT);
 
  this.socket.connect({
    clientId: 'MQTT_RPC_' + Date.now()
  }, function() {
    if (self.connected) {
      return;
    }
 
    clearTimeout(connectTimeout);
    self.connected = true;
    if (self.bufferMsg) {
      self._interval = setInterval(function() {
        flush(self);
      }, self.interval);
    }
 
    self.setupKeepAlive();
    cb();
  });
 
  this.socket.on('publish', function(pkg) {
    pkg = pkg.payload.toString();
    try {
      pkg = JSON.parse(pkg);
      if (pkg instanceof Array) {
        processMsgs(self, pkg);
      } else {
        processMsg(self, pkg);
      }
    } catch (err) {
      logger.error('rpc client %s process remote server %s message with error: %s', self.serverId, self.id, err.stack);
    }
  });
 
  this.socket.on('error', function(err) {
    logger.error('rpc socket %s is error, remote server %s host: %s, port: %s', self.serverId, self.id, self.host, self.port);
    self.emit('close', self.id);
  });
 
  this.socket.on('pingresp', function() {
    self.lastPong = Date.now();
  });
 
  this.socket.on('disconnect', function(reason) {
    logger.error('rpc socket %s is disconnect from remote server %s, reason: %s', self.serverId, self.id, reason);
    var reqs = self.requests;
    for (var id in reqs) {
      var ReqCb = reqs[id];
      ReqCb(tracer, new Error(self.serverId + ' disconnect with remote server ' + self.id));
    }
    self.emit('close', self.id);
  });
};
 
/**
 * close mailbox
 */
MailBox.prototype.close = function() {
  if (this.closed) {
    return;
  }
  this.closed = true;
  this.connected = false;
  if (this._interval) {
    clearInterval(this._interval);
    this._interval = null;
  }
  this.socket.destroy();
};
 
/**
 * send message to remote server
 *
 * @param msg {service:"", method:"", args:[]}
 * @param opts {} attach info to send method
 * @param cb declaration decided by remote interface
 */
MailBox.prototype.send = function(tracer, msg, opts, cb) {
  tracer && tracer.info('client', __filename, 'send', 'mqtt-mailbox try to send');
  if (!this.connected) {
    tracer && tracer.error('client', __filename, 'send', 'mqtt-mailbox not init');
    cb(tracer, new Error(this.serverId + ' mqtt-mailbox is not init ' + this.id));
    return;
  }
 
  if (this.closed) {
    tracer && tracer.error('client', __filename, 'send', 'mailbox has already closed');
    cb(tracer, new Error(this.serverId + ' mqtt-mailbox has already closed ' + this.id));
    return;
  }
 
  var id = this.curId++;
  this.requests[id] = cb;
  setCbTimeout(this, id, tracer, cb);
 
  var pkg;
  if (tracer && tracer.isEnabled) {
    pkg = {
      traceId: tracer.id,
      seqId: tracer.seq,
      source: tracer.source,
      remote: tracer.remote,
      id: id,
      msg: msg
    };
  } else {
    pkg = {
      id: id,
      msg: msg
    };
  }
  if (this.bufferMsg) {
    enqueue(this, pkg);
  } else {
    doSend(this.socket, pkg);
  }
};
 
MailBox.prototype.setupKeepAlive = function() {
  var self = this;
  this.keepaliveTimer = setInterval(function() {
    self.checkKeepAlive();
  }, this.keepalive);
}
 
MailBox.prototype.checkKeepAlive = function() {
  if (this.closed) {
    return;
  }
 
  // console.log('checkKeepAlive lastPing %d lastPong %d ~~~', this.lastPing, this.lastPong);
  var now = Date.now();
  var KEEP_ALIVE_TIMEOUT = this.keepalive * 2;
  if (this.lastPing > 0) {
    if (this.lastPong < this.lastPing) {
      if (now - this.lastPing > KEEP_ALIVE_TIMEOUT) {
        logger.error('mqtt rpc client %s checkKeepAlive timeout from remote server %s for %d lastPing: %s lastPong: %s', this.serverId, this.id, KEEP_ALIVE_TIMEOUT, this.lastPing, this.lastPong);
        this.emit('close', this.id);
        this.lastPing = -1;
        // this.close();
      }
    } else {
      this.socket.pingreq();
      this.lastPing = Date.now();
    }
  } else {
    this.socket.pingreq();
    this.lastPing = Date.now();
  }
}
 
var enqueue = function(mailbox, msg) {
  mailbox.queue.push(msg);
};
 
var flush = function(mailbox) {
  if (mailbox.closed || !mailbox.queue.length) {
    return;
  }
  doSend(mailbox.socket, mailbox.queue);
  mailbox.queue = [];
};
 
var doSend = function(socket, msg) {
  socket.publish({
    topic: 'rpc',
    payload: JSON.stringify(msg)
  });
}
 
var processMsgs = function(mailbox, pkgs) {
  for (var i = 0, l = pkgs.length; i < l; i++) {
    processMsg(mailbox, pkgs[i]);
  }
};
 
var processMsg = function(mailbox, pkg) {
  var pkgId = pkg.id;
  clearCbTimeout(mailbox, pkgId);
  var cb = mailbox.requests[pkgId];
  if (!cb) {
    return;
  }
 
  delete mailbox.requests[pkgId];
  var rpcDebugLog = mailbox.opts.rpcDebugLog;
  var tracer = null;
  var sendErr = null;
  if (rpcDebugLog) {
    tracer = new Tracer(mailbox.opts.rpcLogger, mailbox.opts.rpcDebugLog, mailbox.opts.clientId, pkg.source, pkg.resp, pkg.traceId, pkg.seqId);
  }
  var pkgResp = pkg.resp;
 
  cb(tracer, sendErr, pkgResp);
};
 
var setCbTimeout = function(mailbox, id, tracer, cb) {
  var timer = setTimeout(function() {
    // logger.warn('rpc request is timeout, id: %s, host: %s, port: %s', id, mailbox.host, mailbox.port);
    clearCbTimeout(mailbox, id);
    if (mailbox.requests[id]) {
      delete mailbox.requests[id];
    }
    var eMsg = util.format('rpc %s callback timeout %d, remote server %s host: %s, port: %s', mailbox.serverId, mailbox.timeoutValue, id, mailbox.host, mailbox.port);
    logger.error(eMsg);
    cb(tracer, new Error(eMsg));
  }, mailbox.timeoutValue);
  mailbox.timeout[id] = timer;
};
 
var clearCbTimeout = function(mailbox, id) {
  if (!mailbox.timeout[id]) {
    logger.warn('timer is not exsits, serverId: %s remote: %s, host: %s, port: %s', mailbox.serverId, id, mailbox.host, mailbox.port);
    return;
  }
  clearTimeout(mailbox.timeout[id]);
  delete mailbox.timeout[id];
};
 
/**
 * Factory method to create mailbox
 *
 * @param {Object} server remote server info {id:"", host:"", port:""}
 * @param {Object} opts construct parameters
 *                      opts.bufferMsg {Boolean} msg should be buffered or send immediately.
 *                      opts.interval {Boolean} msg queue flush interval if bufferMsg is true. default is 50 ms
 */
module.exports.create = function(server, opts) {
  return new MailBox(server, opts || {});
};