Code coverage report for node/hyperbahn/index.js

Statements: 88.08% (133 / 151)      Branches: 74.29% (52 / 70)      Functions: 93.75% (15 / 16)      Lines: 88.08% (133 / 151)      Ignored: none     

All files » node/hyperbahn/ » index.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                                            1 1 1 1 1 1   1 1   1           1             1       1 1                         1                             1   34 12     22   22   22   19 19 18     17 17 17 17 17   17 17 17 17   17 17   17               17 12 12       17           17         17   17 17 17 17 17   17   17 2   15       1   1             1   22   22   20             20 1     19                   19 17   19     19       19           1   2   2 2   2       2         2         1   2   2 2   2             1   26   26                   26                             1     26       26     26             26   2   2         24         26 26 26   1   26 9             9   9 9     17                                           17             17 17 17 17   17     17 17       1   1 1 1 1 1     1 9   9       1 17   17 17   17     1   26   26 3     23   13             1 14 14 1     13 13 13    
// 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 TypedError = require('error/typed');
var WrappedError = require('error/wrapped');
var timers = require('timers');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
 
var Reporter = require('../tcollector/reporter.js');
var TChannelJSON = require('../as/json.js');
 
var AdvertisementTimeoutError = WrappedError({
    type: 'hyperbahn-client.advertisement-timeout',
    message: 'Hyperbahn advertisement timed out after {time} ms!.\n' +
        '{origMessage}.\n'
});
 
var AlreadyDestroyed = TypedError({
    type: 'hyperbahn-client.already-destroyed',
    message: 'HyperbahnClient was already destroyed.\n' +
        'Cannot invoke {method}.',
    method: null
});
 
var States = {
    UNADVERTISED: 'UNADVERTISED',
    ADVERTISED: 'ADVERTISED'
};
var DEFAULT_TTL = 60 * 1000;
var DEFAULT_ERROR_RETRY_TIMES = [
    200, // One fast retry
 
    1000, // Fibonacci backoff
    1000,
    2000,
    3000,
    5000,
    8000,
 
    10000 // Max out at 10 seconds
];
 
module.exports = HyperbahnClient;
 
// # HyperbahnClient
// options.
//   * (required) tchannel: tchannel instance
//   * (required) serviceName: string service name
//   * (required) hostPortList: array of initial hyperbahn nodes
//   * callerName: the caller name
//   * logger: logtron instance
//   * reportTracing: Whether to report tracing
//   * hardFail: boolean; default false; whether or not to fail hard when we
//     can't advertise or on unexpected hyperbahn errors
//   * registrationTimeout: deprecated
//   * advertisementTimeout: integer. In hardFail mode we default to 5000. If
//     not in hardFail mode we don't time out advertisements.
function HyperbahnClient(options) {
    /*eslint max-statements: [2, 25] complexity: [2, 20] */
    if (!(this instanceof HyperbahnClient)) {
        return new HyperbahnClient(options);
    }
 
    var self = this;
 
    EventEmitter.call(this);
 
    assert(options && options.tchannel && !options.tchannel.topChannel,
        'Must pass in top level tchannel');
    assert(options.tchannel.tracer, 'Top channel must have trace enabled');
    assert(options.serviceName, 'must pass in serviceName');
    assert(Array.isArray(options.hostPortList),
        'Must pass in hostPortList');
 
    self.hostPortList = options.hostPortList;
    self.serviceName = options.serviceName;
    self.callerName = options.callerName || options.serviceName;
    self.tchannel = options.tchannel;
    self.reportTracing = 'reportTracing' in options ?
        options.reportTracing : true;
    self.hardFail = !!options.hardFail;
    self.advertiseInterval = options.advertiseInterval || DEFAULT_TTL;
    self.timeoutFuzz = self.advertiseInterval;
    self.errorRetryTimes = options.errorRetryTimes || DEFAULT_ERROR_RETRY_TIMES;
 
    self.logger = options.logger || self.tchannel.logger;
    self.statsd = options.statsd;
 
    self.reporter = Reporter({
        channel: self.getClientChannel({
            serviceName: 'tcollector',
            trace: false
        }),
        logger: self.logger,
        callerName: self.callerName
    });
    self.tchannel.tracer.reporter = function report(span) {
        Eif (self.reportTracing) {
            self.reporter.report(span);
        }
    };
 
    Iif (!self.reportTracing) {
        self.logger.warn('HyperbahnClient tcollector tracing is OFF', {
            service: self.serviceName
        });
    }
 
    self.hyperbahnChannel = self.tchannel.subChannels.hyperbahn ||
        self.tchannel.makeSubChannel({
            serviceName: 'hyperbahn',
            peers: self.hostPortList
        });
    self.tchannelJSON = TChannelJSON();
 
    self.lastError = null;
    self.latestAdvertisementResult = null;
    self.attemptCounter = 0;
    self.state = States.UNADVERTISED;
    self._destroyed = false;
 
    var advertisementTimeout = options.advertisementTimeout ||
        options.registrationTimeout;
    if (self.hardFail) {
        self.advertisementTimeoutTime = advertisementTimeout || 5000;
    } else {
        self.advertisementTimeoutTime = advertisementTimeout;
    }
}
 
util.inherits(HyperbahnClient, EventEmitter);
 
HyperbahnClient.prototype.setReportTracing = function setReportTracing(bool) {
    var self = this;
 
    self.reportTracing = bool;
};
 
// Gets the subchannel for hitting a particular service.
HyperbahnClient.prototype.getClientChannel =
function getClientChannel(options) {
    var self = this;
 
    assert(options && options.serviceName, 'must pass serviceName');
 
    Iif (self._destroyed) {
        self.emit('error', AlreadyDestroyed({
            method: 'getClientChannel'
        }));
        return null;
    }
 
    if (self.tchannel.subChannels[options.serviceName]) {
        return self.tchannel.subChannels[options.serviceName];
    }
 
    var channelOptions = {
        peers: self.hostPortList,
        serviceName: options.serviceName,
        requestDefaults: {
            serviceName: options.serviceName,
            headers: {
                cn: self.callerName
            }
        }
    };
    if ('trace' in options) {
        channelOptions.trace = options.trace;
    }
    Iif ('timeout' in options) {
        channelOptions.requestDefaults.timeout = options.timeout;
    }
    Iif ('retryLimit' in options) {
        channelOptions.requestDefaults.retryLimit = options.retryLimit;
    }
 
    return self.tchannel.makeSubChannel(channelOptions);
};
 
// ## advertisementTimeout
// Called after a certain amount of time to have a fatal error when reg fails.
// Will not be called if options.advertisementTimeout isn't passed in
HyperbahnClient.prototype.advertisementTimeout =
function advertisementTimeout() {
    var self = this;
 
    Eif (self.state === States.UNADVERTISED) {
        var lastError = self.lastError ||
            new Error('advertisement timeout!');
        var err = AdvertisementTimeoutError(lastError, {
            time: self.advertisementTimeoutTime
        });
 
        self.logger.fatal('HyperbahnClient: advertisement timed out', {
            timeout: self.advertisementTimeout,
            error: err
        });
 
        self.advertisementFailure(err);
    }
    // TODO else warn
};
 
HyperbahnClient.prototype.advertisementFailure =
function advertisementFailure(err) {
    var self = this;
 
    self.destroy();
    self.emit('error', err);
 
    Iif (self.statsd) {
        self.statsd.increment(
            'hyperbahn-client.' + self.serviceName + '.advertisement.failure'
        );
    }
};
 
HyperbahnClient.prototype.sendAdvertiseRequest =
function sendAdvertiseRequest(opts, cb) {
    var self = this;
 
    var req = self.hyperbahnChannel.request({
        serviceName: 'hyperbahn',
        timeout: (opts && opts.timeout) || 50,
        hasNoParent: true,
        trace: false,
        retryLimit: 1,
        headers: {
            cn: self.callerName
        }
    });
    self.tchannelJSON.send(req, 'ad', null, {
        services: [{
            cost: 0,
            serviceName: self.serviceName
        }]
    }, cb);
};
 
// ## advertise
// Advertise with Hyperbahn. If called with a callback, the callback will not be
// called until there has been a successful advertisement. This function
// attempts a advertise and retries until there are no healthy servers left; it
// will then repeatedly choose random servers to try until it finds one that
// works.
// register is **deprecated**
HyperbahnClient.prototype.register =
HyperbahnClient.prototype.advertise =
function advertise(opts) {
    var self = this;
    // Attempt a advertisement. If it succeeds, setTimeout to re-advertise with
    // the same server after the TTL.
 
    assert(self.tchannel.hostPort,
        'must call tchannel.listen() before advertise()');
 
    Iif (self._destroyed) {
        self.emit('error', AlreadyDestroyed({
            method: 'advertise'
        }));
        return;
    }
 
    if (self.advertisementTimeoutTime) {
        // Start the timeout timer
        self.advertisementTimeoutTimer = timers.setTimeout(
            function advertisementTimeoutTimer() {
                self.advertisementTimeout();
            },
            self.advertisementTimeoutTime
        );
    } else {
        self.logger.info('HyperbahnClient advertisement timeout disabled', {
            service: self.serviceName
        });
    }
 
    self.attemptCounter++;
    self.sendAdvertiseRequest(opts, advertiseInternalCb);
    self.emit('advertise-attempt');
 
    function advertiseInternalCb(err, result) {
        /*eslint max-statements: [2, 40] */
        if (err) {
            self.logger[self.hardFail ? 'error' : 'warn'](
                'HyperbahnClient: advertisement failure, ' +
                'marking server as sick', {
                error: err,
                serviceName: self.serviceName,
                hostPort: self.hostPort
            });
            self.lastError = err;
 
            self.advertiseAgain(self.getErrorRetryTime());
            return;
        }
 
        Iif (result.ok === false) {
            err = result.body;
            var errInfo2 = {
                error: err,
                serviceName: self.serviceName,
                hostPort: self.hostPort
            };
 
            self.logger[self.hardFail ? 'fatal' : 'warn'](
                'HyperbahnClient: unexpected failure (from Hyperbahn)',
                errInfo2
            );
 
            if (self.hardFail) {
                self.advertisementFailure(err);
            } else {
                self.advertiseAgain(self.getErrorRetryTime());
            }
 
            return;
        }
 
        Iif (self.statsd) {
            self.statsd.increment(
                'hyperbahn-client.' + self.serviceName +
                    '.advertisement.success'
            );
        }
 
        self.latestAdvertisementResult = result;
        self.attemptCounter = 0;
        self.state = States.ADVERTISED;
        timers.clearTimeout(self.advertisementTimeoutTimer);
 
        self.advertiseAgain(self.getHealthyRetryTime());
 
        // registered event is deprecated
        self.emit('registered');
        self.emit('advertised');
    }
};
 
HyperbahnClient.prototype.unadvertise =
function unadvertise() {
    var self = this;
    self.destroy();
    self.latestAdvertisementResult = null;
    self.state = States.UNADVERTISED;
    self.emit('unadvertised');
};
 
HyperbahnClient.prototype.getErrorRetryTime = function getErrorRetryTime() {
    var self = this;
 
    return self.errorRetryTimes[self.attemptCounter - 1] ||
        self.errorRetryTimes[self.errorRetryTimes.length - 1];
};
 
HyperbahnClient.prototype.getHealthyRetryTime = function getHealthyRetryTime() {
    var self = this;
 
    var fuzz = self.timeoutFuzz;
    var delay = Math.round(Math.floor(Math.random() * fuzz)) - (fuzz / 2);
 
    return self.advertiseInterval + delay;
};
 
HyperbahnClient.prototype.advertiseAgain =
function advertiseAgain(delay) {
    var self = this;
 
    if (self._destroyed) {
        return;
    }
 
    self._advertisementTimer = timers.setTimeout(
        function advertiseTimeout() {
            self.advertise();
        },
        delay
    );
};
 
// ## destroy
HyperbahnClient.prototype.destroy = function destroy() {
    var self = this;
    if (self._destroyed) {
        return;
    }
 
    self._destroyed = true;
    timers.clearTimeout(this._advertisementTimer);
    timers.clearTimeout(this.advertisementTimeoutTimer);
};