Code coverage report for node/hyperbahn/index.js

Statements: 86.78% (105 / 121)      Branches: 77.27% (51 / 66)      Functions: 91.67% (11 / 12)      Lines: 86.78% (105 / 121)      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                                            1 1 1 1 1 1   1 1   1           1           1             1       1 1   1                           1   28 12     16   16   16 3               13 1             12 1               11   11 11 11 11     11 11   11       11             11 4 4       11           11           11       11 11 11   11 11   11 2   9       1   1             1   16   16             16 2               14 1     13                                   1   2   2 2   2       2         2         1   2   2 2   2                         1 11       11             11   2   2         9         11       11               11             11 8             8   8 8     3                                           3             3 3 3   3   3 3     11     1   11   11 2     9   4             1 7 7 7    
// 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 HyperbahnClientInvalidOptionError = TypedError({
    type: 'hyperbahn-client.invalid-option',
    message: 'HyperbahnClient {method}: invalid option {name}' +
        ', expected {expected}, got {actual}'
});
 
var RegistrationTimeoutError = WrappedError({
    type: 'hyperbahn-client.registration-timeout',
    message: 'Hyperbahn registration 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 = {
    UNREGISTERED: 'UNREGISTERED',
    REGISTERED: 'REGISTERED'
};
var DEFAULT_TTL = 60 * 1000;
var REGISTER_ERROR_DELAY = 200;
 
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 register or on unexpected hyperbahn errors
//   * registrationTimeout: integer. In hardFail mode we default to 5000. If
//     not in hardFail mode we don't time out registrations.
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);
 
    if (!options || !options.tchannel || options.tchannel.topChannel) {
        throw HyperbahnClientInvalidOptionError({
            method: 'constructor',
            name: 'tchannel',
            expected: 'top level tchannel instance',
            actual: options ? typeof options.tchannel : 'undefined'
        });
    }
 
    if (!options.serviceName) {
        throw HyperbahnClientInvalidOptionError({
            method: 'constructor',
            name: 'serviceName',
            expected: 'string',
            actual: typeof options.serviceName
        });
    }
    if (!Array.isArray(options.hostPortList)) {
        throw HyperbahnClientInvalidOptionError({
            method: 'constructor',
            name: 'hostPortList',
            expected: 'array',
            actual: typeof options.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.logger = options.logger || self.tchannel.logger;
    self.statsd = options.statsd;
 
    assert(self.tchannel.tracer,
        'Top channel must have trace enabled'
    );
 
    var reporter = Reporter({
        channel: self.getClientChannel({
            serviceName: 'tcollector',
            trace: false
        }),
        logger: options.logger
    });
    self.tchannel.tracer.reporter = function report(span) {
        Eif (self.reportTracing) {
            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({
        logger: self.logger
    });
 
    self.hardFail = !!options.hardFail;
    self.lastError = null;
    self.latestRegistrationResult = null;
 
    self.state = States.UNREGISTERED;
    self._destroyed = false;
 
    if (self.hardFail) {
        self.registrationTimeoutTime = options.registrationTimeout || 5000;
    } else {
        self.registrationTimeoutTime = options.registrationTimeout;
    }
}
 
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;
 
    Iif (self._destroyed) {
        self.emit('error', AlreadyDestroyed({
            method: 'getClientChannel'
        }));
        return null;
    }
 
    if (!options || !options.serviceName) {
        throw HyperbahnClientInvalidOptionError({
            method: 'getClientChannel',
            name: 'serviceName',
            expected: 'string',
            actual: options ? typeof options.serviceName : 'undefined'
        });
    }
 
    if (self.tchannel.subChannels[options.serviceName]) {
        return self.tchannel.subChannels[options.serviceName];
    }
 
    return self.tchannel.makeSubChannel({
        serviceName: options.serviceName,
        trace: options.trace,
        requestDefaults: {
            serviceName: options.serviceName,
            timeout: options.timeout,
            retryLimit: options.retryLimit,
            headers: {
                cn: self.callerName
            }
        },
        peers: self.hostPortList
    });
};
 
// ## registrationTimeout
// Called after a certain amount of time to have a fatal error when reg fails.
// Will not be called if options.registrationTimeout isn't passed in
HyperbahnClient.prototype.registrationTimeout =
function registrationTimeout() {
    var self = this;
 
    Eif (self.state === States.UNREGISTERED) {
        var lastError = self.lastError ||
            new Error('registration timeout!');
        var err = RegistrationTimeoutError(lastError, {
            time: self.registrationTimeoutTime
        });
 
        self.logger.fatal('HyperbahnClient: registration timed out', {
            timeout: self.registrationTimeout,
            error: err
        });
 
        self.registrationFailure(err);
    }
    // TODO else warn
};
 
HyperbahnClient.prototype.registrationFailure =
function registrationFailure(err) {
    var self = this;
 
    self.destroy();
    self.emit('error', err);
 
    Iif (self.statsd) {
        self.statsd.increment(
            'hyperbahn-client.' + self.serviceName + '.registration.failure'
        );
    }
};
 
// ## register
// Register with Hyperbahn. If called with a callback, the callback will not be
// called until there has been a successful registration. This function
// attempts a register and retries until there are no healthy servers left; it
// will then repeatedly choose random servers to try until it finds one that
// works.
HyperbahnClient.prototype.register = function register(opts) {
    var self = this;
    // Attempt a registration. If it succeeds, setTimeout to re-register with
    // the same server after the TTL.
 
    Iif (self._destroyed) {
        self.emit('error', AlreadyDestroyed({
            method: 'register'
        }));
        return;
    }
 
    if (self.registrationTimeoutTime) {
        // Start the timeout timer
        self.registrationTimeoutTimer = timers.setTimeout(
            function registrationTimeoutTimer() {
                self.registrationTimeout();
            },
            self.registrationTimeoutTime
        );
    } else {
        self.logger.info('HyperbahnClient registration timeout disabled', {
            service: self.serviceName
        });
    }
 
    assert(self.tchannel.hostPort,
        'must call tchannel.listen() before register()'
    );
 
    var req = self.hyperbahnChannel.request({
        serviceName: 'hyperbahn',
        timeout: (opts && opts.timeout) || 50,
        hasNoParent: true,
        headers: {
            cn: self.callerName
        }
    });
    self.tchannelJSON.send(req, 'ad', null, {
        services: [{
            cost: 0,
            serviceName: self.serviceName
        }]
    }, function registerInternalCb(err, result) {
        /*eslint max-statements: [2, 40] */
        if (err) {
            self.logger[self.hardFail ? 'error' : 'warn'](
                'HyperbahnClient: registration failure, ' +
                'marking server as sick', {
                error: err,
                serviceName: self.serviceName,
                hostPort: self.hostPort
            });
            self.lastError = err;
 
            self.registerAgain(REGISTER_ERROR_DELAY);
            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.registrationFailure(err);
            } else {
                self.registerAgain(REGISTER_ERROR_DELAY);
            }
 
            return;
        }
 
        Iif (self.statsd) {
            self.statsd.increment(
                'hyperbahn-client.' + self.serviceName +
                    '.registration.success'
            );
        }
 
        self.latestRegistrationResult = result;
        self.state = States.REGISTERED;
        timers.clearTimeout(self.registrationTimeoutTimer);
 
        var ttl = DEFAULT_TTL;
 
        self.registerAgain(ttl);
        self.emit('registered');
    });
 
    self.emit('register-attempt');
};
 
HyperbahnClient.prototype.registerAgain =
function registerAgain(delay) {
    var self = this;
 
    if (self._destroyed) {
        return;
    }
 
    self._registrationTimer = timers.setTimeout(
        function registerTimeout() {
            self.register();
        },
        delay
    );
};
 
// ## destroy
HyperbahnClient.prototype.destroy = function destroy() {
    this._destroyed = true;
    timers.clearTimeout(this._registrationTimer);
    timers.clearTimeout(this.registrationTimeoutTimer);
};