Code coverage report for node/peer.js

Statements: 97.28% (250 / 257)      Branches: 79.8% (79 / 99)      Functions: 100% (33 / 33)      Lines: 97.61% (245 / 251)      Ignored: none     

All files » node/ » peer.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 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475                                            1 1 1 1 1   1 1 1 1   1   1 1696 840   856 856 856   856 856   856   856 856 856 856 856 856 856 856 856   856                     856 74 74   782     856 856 856         1 354       354 354 354           354           1   1 3251   3251 1869     1382 1382 1555 1555       1 4   4 4 2 2   2   2 2       2     1 1544   1544 856 856     1544 1544 511 511     1033   1 511 510         510         1 862   862 862       1 8244 8244 5306 5306   2938     1 14708 14708 14708 11185 11185 11185 5877 32   3555     1 354 354       354 354 352 352 235       354     1 6460 6460 6460 587 586 586   6459     1   1989   1989   1989   1989 1800   189       1   189   189 189 189 189   1 1     1 62     1 126     1 189 189 189 189 189       1 2577   2577 2577 2577     1 1118     1118 588   530   1118 1118   1118 1118     588     1118   1 515 515     1 2     1 1101     1 1103 1103 1103 1103 2             2 2 1   1       1103       1 1103   1103   1103 1103 1103     1103   1103     1 589 589 589 588 588 588 588 588 588     1 588 588 588 588 588     1                           4654 4654 4654     1 4654 4654 4654 3494   3494   4654             1 2736   2736 2     2734 2734 358     2376     1 1 1 1   1 856   856 856     1 8244   8244 8244   8244 2938 5306 1744 3562 1193   2369         1 4654         4654 4654 4654 1400   4654   1436 1436           3022   1632       1  
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
 
'use strict';
 
var assert = require('assert');
var inherits = require('util').inherits;
var EventEmitter = require('./lib/event_emitter');
var StateMachine = require('./state_machine');
var net = require('net');
 
var TChannelConnection = require('./connection');
var errors = require('./errors');
var states = require('./states');
var Request = require('./request');
 
var DEFAULT_REPORT_INTERVAL = 1000;
 
function TChannelPeer(channel, hostPort, options) {
    if (!(this instanceof TChannelPeer)) {
        return new TChannelPeer(channel, hostPort, options);
    }
    var self = this;
    EventEmitter.call(self);
    StateMachine.call(self);
 
    self.stateChangedEvent = self.defineEvent('stateChanged');
    self.allocConnectionEvent = self.defineEvent('allocConnection');
 
    assert(hostPort !== '0.0.0.0:0', 'Cannot create ephemeral peer');
 
    self.channel = channel;
    self.logger = self.channel.logger;
    self.timers = self.channel.timers;
    self.random = self.channel.random;
    self.options = options || {};
    self.hostPort = hostPort;
    self.connections = [];
    self.pendingIdentified = 0;
    self.heapElements = [];
 
    self.stateOptions = new states.StateOptions(self, {
        timeHeap: self.channel.timeHeap,
        timers: self.timers,
        random: self.random,
        period: self.options.period,
        maxErrorRate: self.options.maxErrorRate,
        minimumRequests: self.options.minimumRequests,
        probation: self.options.probation,
        nextHandler: new PreferOutgoingHandler(self)
    });
 
    if (self.options.initialState) {
        self.setState(self.options.initialState);
        delete self.options.initialState;
    } else {
        self.setState(states.HealthyState);
    }
 
    self.reportInterval = self.options.reportInterval || DEFAULT_REPORT_INTERVAL;
    Eif (self.reportInterval > 0) {
        self.reportTimer = self.timers.setTimeout(
            onReport, self.reportInterval
        );
    }
 
    function onReport() {
        Iif (!self.hostPort) {
            return;
        }
 
        var count = self.countConnections('out');
        Eif (self.channel.emitConnectionMetrics) {
            self.channel.connectionsActiveStat.update(count, {
                'host-port': self.channel.hostPort,
                'peer-host-port': self.hostPort
            });
        }
 
        self.reportTimer = self.timers.setTimeout(
            onReport, self.reportInterval
        );
    }
}
 
inherits(TChannelPeer, EventEmitter);
 
TChannelPeer.prototype.invalidateScore = function invalidateScore() {
    var self = this;
 
    if (!self.heapElements.length) {
        return;
    }
 
    var score = self.state.shouldRequest();
    for (var i = 0; i < self.heapElements.length; i++) {
        var el = self.heapElements[i];
        el.rescore(score);
    }
};
 
TChannelPeer.prototype.isConnected = function isConnected(direction, identified) {
    var self = this;
 
    Eif (identified === undefined) identified = true;
    for (var i = 0; i < self.connections.length; i++) {
        var conn = self.connections[i];
        Iif (direction && conn.direction !== direction) {
            continue;
        } else Iif (conn.closing) {
            continue;
        } else Eif (conn.remoteName !== null || !identified) {
            return true;
        }
    }
 
    return false;
};
 
TChannelPeer.prototype.close = function close(callback) {
    var self = this;
 
    if (self.reportTimer) {
        self.timers.clearTimeout(self.reportTimer);
        self.reportTimer = null;
    }
 
    var counter = self.connections.length;
    if (counter) {
        self.connections.forEach(function eachConn(conn) {
            conn.close(onClose);
        });
    } else {
        self.state.close(callback);
    }
    function onClose() {
        if (--counter <= 0) {
            Iif (counter < 0) {
                self.logger.error('closed more peer sockets than expected', {
                    counter: counter
                });
            }
            self.state.close(callback);
        }
    }
};
 
TChannelPeer.prototype.setState = function setState(StateType) {
    var self = this;
 
    Eif (StateMachine.prototype.setState.call(self, StateType)) {
        self.invalidateScore();
    }
};
 
TChannelPeer.prototype.getInConnection = function getInConnection() {
    var self = this;
    for (var i = 0; i < self.connections.length; i++) {
        var conn = self.connections[i];
        Eif (!conn.closing) return conn;
    }
    return null;
};
 
TChannelPeer.prototype.getOutConnection = function getOutConnection(preferIdentified) {
    var self = this;
    var candidate = null;
    for (var i = self.connections.length - 1; i >= 0; i--) {
        var conn = self.connections[i];
        Iif (conn.closing) continue;
        if (!preferIdentified) return conn; // user doesn't care, take last outgoing
        if (conn.remoteName) return conn; // user wanted an identified channel, and we found one
        Eif (!candidate) candidate = conn; // we'll fallback to returning this if we can't find an identified one
    }
    return candidate;
};
 
TChannelPeer.prototype.countConnections = function countConnections(direction) {
    var self = this;
    Iif (!direction) {
        return self.connections.length;
    }
 
    var count = 0;
    for (var i = 0; i < self.connections.length; i++) {
        var conn = self.connections[i];
        if (conn.direction === direction) {
            count++;
        }
    }
 
    return count;
};
 
TChannelPeer.prototype.connect = function connect(outOnly) {
    var self = this;
    var conn = self.getOutConnection(true);
    if (!conn || (outOnly && conn.direction !== 'out')) {
        var socket = self.makeOutSocket();
        conn = self.makeOutConnection(socket);
        self.addConnection(conn);
    }
    return conn;
};
 
TChannelPeer.prototype.waitForIdentified =
function waitForIdentified(callback) {
    var self = this;
 
    var conn = self.connect();
 
    Iif (conn.closing) {
        callback(conn.closeError);
    } else if (conn.remoteName) {
        callback(null);
    } else {
        self._waitForIdentified(conn, callback);
    }
};
 
TChannelPeer.prototype._waitForIdentified =
function _waitForIdentified(conn, callback) {
    var self = this;
 
    self.pendingIdentified++;
    conn.errorEvent.on(onConnectionError);
    conn.closeEvent.on(onConnectionClose);
    conn.identifiedEvent.on(onIdentified);
 
    function onConnectionError(err) {
        finish(err);
    }
 
    function onConnectionClose(err) {
        finish(err);
    }
 
    function onIdentified() {
        finish(null);
    }
 
    function finish(err) {
        self.pendingIdentified = 0;
        conn.errorEvent.removeListener(onConnectionError);
        conn.closeEvent.removeListener(onConnectionClose);
        conn.identifiedEvent.removeListener(onIdentified);
        callback(err);
    }
};
 
TChannelPeer.prototype.request = function peerRequest(options) {
    var self = this;
 
    options.peerState = self.state;
    options.timeout = options.timeout || Request.defaultTimeout;
    return self.connect().request(options);
};
 
TChannelPeer.prototype.addConnection = function addConnection(conn) {
    var self = this;
    // TODO: first approx alert for self.connections.length > 2
    // TODO: second approx support pruning
    if (conn.direction === 'out') {
        self.connections.push(conn);
    } else {
        self.connections.unshift(conn);
    }
    conn.errorEvent.on(onConnectionError);
    conn.closeEvent.on(onConnectionClose);
 
    self._maybeInvalidateScore();
    if (!conn.remoteName) {
        // TODO: could optimize if nextHandler had a way of saying "would a new
        // identified connection change your QOS?"
        conn.identifiedEvent.on(onIdentified);
    }
 
    return conn;
 
    function onIdentified() {
        conn.identifiedEvent.removeListener(onIdentified);
        self._maybeInvalidateScore();
    }
 
    function onConnectionError(err) {
        removeConnection(err);
    }
 
    function onConnectionClose() {
        removeConnection(null);
    }
 
    function removeConnection(err) {
        conn.closeEvent.removeListener(onConnectionClose);
        conn.errorEvent.removeListener(onConnectionError);
        conn.identifiedEvent.removeListener(onIdentified);
        if (err) {
            var loggerInfo = {
                error: err,
                direction: conn.direction,
                remoteName: conn.remoteName,
                socketRemoteAddr: conn.socketRemoteAddr
            };
 
            var codeName = errors.classify(err);
            if (codeName === 'Timeout') {
                self.logger.warn('Got a connection error', loggerInfo);
            } else {
                self.logger.error('Got an unexpected connection error', loggerInfo);
            }
        }
 
        self.removeConnection(conn);
    }
};
 
TChannelPeer.prototype.removeConnection = function removeConnection(conn) {
    var self = this;
 
    var ret = null;
 
    var index = self.connections ? self.connections.indexOf(conn) : -1;
    Eif (index !== -1) {
        ret = self.connections.splice(index, 1)[0];
    }
 
    self._maybeInvalidateScore();
 
    return ret;
};
 
TChannelPeer.prototype.makeOutSocket = function makeOutSocket() {
    var self = this;
    var parts = self.hostPort.split(':');
    assert(parts.length === 2, 'invalid destination');
    var host = parts[0];
    var port = parts[1];
    assert(host !== '0.0.0.0', 'cannot connect to ephemeral peer');
    assert(port !== '0', 'cannot connect to dynamic port');
    var socket = net.createConnection({host: host, port: port});
    return socket;
};
 
TChannelPeer.prototype.makeOutConnection = function makeOutConnection(socket) {
    var self = this;
    var chan = self.channel.topChannel || self.channel;
    var conn = new TChannelConnection(chan, socket, 'out', self.hostPort);
    self.allocConnectionEvent.emit(self, conn);
    return conn;
};
 
TChannelPeer.prototype.outPendingWeightedRandom = function outPendingWeightedRandom() {
    // A weighted random variable:
    //   random() ** (1 / weight)
    // Such that the probability distribution is uniform for weights of 0, but
    // an increasing bias with increasing weight.
    // However, although weight should start at 0 and increase probability,
    // the number of pending requests starts at 0 and should decrease
    // probability as it increases.
    // For 0 pending requests, we produce a uniform probability distribution by
    // raising a uniform random variable to the power of 1 (pending + 1).
    // As the number of pending requests increase, the magnitude of the power
    // increases and the probability distribution develops a bias toward zero.
    // TODO review weighted reservoir sampling:
    // http://arxiv.org/pdf/1012.0256.pdf
    var self = this;
    var pending = self.pendingIdentified + self.countOutPending();
    return Math.pow(self.random(), 1 + pending);
};
 
TChannelPeer.prototype.countOutPending = function countOutPending() {
    var self = this;
    var pending = 0;
    for (var index = 0; index < self.connections.length; index++) {
        var connPending = self.connections[index].ops.getPending();
 
        pending += connPending.out;
    }
    return pending;
};
 
// TODO: on connection #shouldRequest impacting event
// - on identified
 
// Called on connection change event
TChannelPeer.prototype._maybeInvalidateScore = function _maybeInvalidateScore() {
    var self = this;
 
    if (!self.state.willCallNextHandler()) {
        return;
    }
 
    var nextHandler = self.state.nextHandler;
    if (nextHandler.getQOS() === nextHandler.lastQOS) {
        return;
    }
 
    self.invalidateScore();
};
 
var QOS_UNCONNECTED = 0;
var QOS_ONLY_INCOMING = 1;
var QOS_FRESH_OUTGOING = 2;
var QOS_READY_OUTGOING = 3;
 
function PreferOutgoingHandler(peer) {
    var self = this;
 
    self.peer = peer;
    self.lastQOS = self.getQOS();
}
 
PreferOutgoingHandler.prototype.getQOS = function getQOS() {
    var self = this;
 
    var inconn = self.peer.getInConnection();
    var outconn = self.peer.getOutConnection();
 
    if (!inconn && !outconn) {
        return QOS_UNCONNECTED;
    } else if (!outconn || outconn.direction !== 'out') {
        return QOS_ONLY_INCOMING;
    } else if (outconn.remoteName === null) {
        return QOS_FRESH_OUTGOING;
    } else {
        return QOS_READY_OUTGOING;
    }
};
 
// Consulted depending on the peer state
PreferOutgoingHandler.prototype.shouldRequest = function shouldRequest() {
    var self = this;
 
    // space:
    //   [0.1, 0.4)  peers with no identified outgoing connection
    //   [0.4, 1.0)  identified outgoing connections
    var random = self.peer.outPendingWeightedRandom();
    var qos = self.getQOS();
    if (self.lastQOS !== qos) {
        self.lastQOS = qos;
    }
    switch (qos) {
        case QOS_ONLY_INCOMING:
            Eif (!self.peer.channel.destroyed) {
                self.peer.connect();
            }
            /* falls through */
        case QOS_UNCONNECTED:
            /* falls through */
        case QOS_FRESH_OUTGOING:
            return 0.1 + random * 0.3;
        case QOS_READY_OUTGOING:
            return 0.4 + random * 0.6;
    }
};
 
module.exports = TChannelPeer;