Code coverage report for node/out_request.js

Statements: 92.88% (261 / 281)      Branches: 78.13% (75 / 96)      Functions: 94.12% (32 / 34)      Lines: 94.18% (259 / 275)      Ignored: none     

All files » node/ » out_request.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 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591                                            1   1 1 1 1   1 1   1   2579   2579 2579 2579 2579   2579 2579   2579 2579 2579 2579 2579 2579   2579 2579 2579 2579 2579 2579 2579 2579     2579 2579 2579 2579 2579 2579 2579 2579 2579 2579 2579 2579 2579 2579 2579   2579   2028     2578     1   1   1 2028   2028                         2027     1               1               1   1354   1354 1313                 41                     1   988   988 944               44                   1   298   298 287   11                           1 1211                       1 11   11 11 11 11   11 11 11 11     1 1211   1211 1211 1211 1211   1211 1211 1211     1   1224   1224 13                         1211 924       1     13   13 13 13 13   13 13 13 13 13     1   2578   2578   2578                           1     2578   2578 2578 2578 2578   2578 2578 2578 2578 2578     1 1286   1286   1286                       1 1286   1286 1286 1286 1286   1286 1286 1286     1 1354   1354 1329     1354 1354 1354 1354   1354     1 16 16 16 16 16     1 1224   1224 1224 1224     1224 1224   1224 1224   1224     1 689 689   665 665   24 24                             1 2578 2578   2578 2578 2027   2578 2576 3 2576                             1 24 24               24 24 24                 1 1913   1913   1913 1362   1362 1362     1913 630     1913 79     1913 1913 1913   1913 1911 1911     1   1916   1916                       1 1916   1916 1916 1916 1916   1916 1916 1916     1   661 661   661 661   1 1 1 1     1 660 660 660     661     1 82 82     82   82 82   1 6 6 6     1 76 76 76 74 74   2       1 2       82     1 25   25 25 25 25 25 25   25     1 25 25                  
// 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';
 
module.exports = TChannelOutRequest;
 
var assert = require('assert');
var EventEmitter = require('./lib/event_emitter');
var inherits = require('util').inherits;
var parallel = require('run-parallel');
 
var errors = require('./errors');
var States = require('./reqres_states');
 
function TChannelOutRequest(id, options) {
    /*max-statements: [2, 50]*/
    var self = this;
 
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.responseEvent = self.defineEvent('response');
    self.finishEvent = self.defineEvent('finish');
 
    assert(options.channel, 'channel required');
    assert(id, 'id is required');
 
    self.peerState = options.peerState || null;
    self.retryCount = options.retryCount || 0;
    self.channel = options.channel || null;
    self.logical = options.logical || false;
    self.parent = options.parent || null;
    self.hasNoParent = options.hasNoParent || false;
 
    self.remoteAddr = options.remoteAddr || '';
    self.timeout = options.timeout || 0;
    self.tracing = options.tracing || null;
    self.serviceName = options.serviceName || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.forwardTrace = options.forwardTrace || false;
 
    // All self requests have id 0
    self.operations = null;
    self.timeHeapHandle = null;
    self.id = id;
    self.state = States.Initial;
    self.start = 0;
    self.end = 0;
    self.streamed = false;
    self.arg1 = null;
    self.endpoint = '';
    self.arg2 = null;
    self.arg3 = null;
    self.span = null;
    self.err = null;
    self.res = null;
    self.timedOut = false;
 
    if (options.channel.tracer && !self.forwardTrace) {
        // new span with new ids
        self.setupTracing(options);
    }
 
    self.peerState.onRequest(self);
}
 
inherits(TChannelOutRequest, EventEmitter);
 
TChannelOutRequest.prototype.type = 'tchannel.outgoing-request';
 
TChannelOutRequest.prototype.setupTracing = function setupTracing(options) {
    var self = this;
 
    self.span = options.channel.tracer.setupNewSpan({
        outgoing: true,
        parentSpan: options.parent && options.parent.span,
        hasNoParent: options.hasNoParent,
        spanid: null,
        traceid: null,
        parentid: null,
        flags: options.trace ? 1 : 0,
        remoteName: self.remoteAddr,
        serviceName: self.serviceName,
        name: '' // fill this in later
    });
 
    self.tracing = self.span.getTracing();
};
 
TChannelOutRequest.prototype._sendCallRequest = function _sendCallRequest(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallRequest'
    });
};
 
TChannelOutRequest.prototype._sendCallRequestCont = function _sendCallRequestCont(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallRequestCont'
    });
};
 
TChannelOutRequest.prototype.emitPerAttemptErrorStat =
function emitPerAttemptErrorStat(err) {
    var self = this;
 
    if (err.isErrorFrame) {
        self.channel.outboundCallsPerAttemptSystemErrorsStat.increment(1, {
            'target-service': self.serviceName,
            'service': self.headers.cn,
            // TODO should always be buffer
            'target-endpoint': self.endpoint,
            'type': err.codeName,
            'retry-count': self.retryCount
        });
    } else {
        self.channel.outboundCallsPerAttemptOperationalErrorsStat.increment(1, {
            'target-service': self.serviceName,
            'service': self.headers.cn,
            // TODO should always be buffer
            'target-endpoint': self.endpoint,
            'type': err.type || 'unknown',
            'retry-count': self.retryCounts
        });
    }
};
 
TChannelOutRequest.prototype.emitErrorStat =
function emitErrorStat(err) {
    var self = this;
 
    if (err.isErrorFrame) {
        self.channel.outboundCallsSystemErrorsStat.increment(1, {
            'target-service': self.serviceName,
            'service': self.headers.cn,
            // TODO should always be buffer
            'target-endpoint': self.endpoint,
            'type': err.codeName
        });
    } else {
        self.channel.outboundCallsOperationalErrorsStat.increment(1, {
            'target-service': self.serviceName,
            'service': self.headers.cn,
            // TODO should always be buffer
            'target-endpoint': self.endpoint,
            'type': err.type || 'unknown'
        });
    }
};
 
TChannelOutRequest.prototype.emitResponseStat =
function emitResponseStat(res) {
    var self = this;
 
    if (res.ok) {
        emitOutboundCallsSuccess(self);
    } else {
        self.channel.emitFastStat(self.channel.buildStat(
            'outbound.calls.app-errors',
            'counter',
            1,
            new OutboundCallsAppErrorsTags(
                self.serviceName,
                self.headers.cn,
                self.endpoint,
                'unknown'
            )
        ));
    }
};
 
function emitOutboundCallsSuccess(request) {
    request.channel.emitFastStat(request.channel.buildStat(
        'outbound.calls.success',
        'counter',
        1,
        new OutboundCallsSuccessTags(
            request.serviceName,
            request.headers.cn,
            request.endpoint
        )
    ));
}
 
function OutboundCallsAppErrorsTags(serviceName, cn, endpoint, type) {
    var self = this;
 
    self.app = '';
    self.host = '';
    self.cluster = '';
    self.version = '';
 
    self.targetService = serviceName;
    self.service = cn;
    self.targetEndpoint = endpoint;
    self.type = type;
}
 
function OutboundCallsSuccessTags(serviceName, cn, endpoint) {
    var self = this;
 
    self.app = '';
    self.host = '';
    self.cluster = '';
    self.version = '';
 
    self.targetService = serviceName;
    self.service = cn;
    self.targetEndpoint = endpoint;
}
 
TChannelOutRequest.prototype.emitPerAttemptResponseStat =
function emitPerAttemptResponseStat(res) {
    var self = this;
 
    if (!res.ok) {
        self.channel.emitFastStat(self.channel.buildStat(
            'outbound.calls.per-attempt.app-errors',
            'counter',
            1,
            new OutboundCallsPerAttemptAppErrorsTags(
                self.serviceName,
                self.headers.cn,
                self.endpoint,
                'unknown',
                self.retryCount
            )
        ));
    // Only emit success if peer-to-peer request or relay
    } else if (self.logical === false) {
        emitOutboundCallsSuccess(self);
    }
};
 
function OutboundCallsPerAttemptAppErrorsTags(
    serviceName, cn, endpoint, type, retryCount
) {
    var self = this;
 
    self.app = '';
    self.host = '';
    self.cluster = '';
    self.version = '';
 
    self.targetService = serviceName;
    self.service = cn;
    self.targetEndpoint = endpoint;
    self.type = type;
    self.retryCount = retryCount;
}
 
TChannelOutRequest.prototype.emitPerAttemptLatency =
function emitPerAttemptLatency() {
    var self = this;
 
    var latency = self.end - self.start;
 
    self.channel.emitFastStat(self.channel.buildStat(
        'outbound.calls.per-attempt-latency',
        'timing',
        latency,
        new OutboundCallsPerAttemptLatencyTags(
            self.serviceName,
            self.headers.cn,
            self.endpoint,
            self.remoteAddr,
            self.retryCount
        )
    ));
};
 
function OutboundCallsPerAttemptLatencyTags(
    serviceName, cn, endpoint, remoteAddr, retryCount
) {
    var self = this;
 
    self.app = '';
    self.host = '';
    self.cluster = '';
    self.version = '';
 
    self.targetService = serviceName;
    self.service = cn;
    self.targetEndpoint = endpoint;
    self.peer = remoteAddr;
    self.retryCount = retryCount;
}
 
TChannelOutRequest.prototype.emitLatency = function emitLatency() {
    var self = this;
 
    var latency = self.end - self.start;
 
    self.channel.emitFastStat(self.channel.buildStat(
        'outbound.calls.latency',
        'timing',
        latency,
        new OutboundCallsLatencyTags(
            self.serviceName,
            self.headers.cn,
            self.endpoint
        )
    ));
};
 
function OutboundCallsLatencyTags(serviceName, cn, endpoint) {
    var self = this;
 
    self.app = '';
    self.host = '';
    self.cluster = '';
    self.version = '';
 
    self.targetService = serviceName;
    self.service = cn;
    self.targetEndpoint = endpoint;
}
 
TChannelOutRequest.prototype.emitError = function emitError(err) {
    var self = this;
 
    if (!self.end) {
        self.end = self.channel.timers.now();
    }
 
    self.err = err;
    self.emitPerAttemptLatency();
    self.emitPerAttemptErrorStat(err);
    self.peerState.onRequestError(err);
 
    self.errorEvent.emit(self, err);
};
 
TChannelOutRequest.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;
    info.reqRemoteAddr = self.remoteAddr;
    info.serviceName = self.serviceName;
    info.outArg1 = String(self.arg1);
    return info;
};
 
TChannelOutRequest.prototype.emitResponse = function emitResponse(res) {
    var self = this;
 
    self.peerState.onRequestHealthy(self);
    Eif (!self.end) {
        self.end = self.channel.timers.now();
    }
 
    self.res = res;
    self.res.span = self.span;
 
    self.emitPerAttemptLatency();
    self.emitPerAttemptResponseStat(res);
 
    self.responseEvent.emit(self, res);
};
 
TChannelOutRequest.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallRequestFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallRequestContFrame(parts, isLast);
            break;
        case States.Done:
            // TODO: could probably happen normally, like say if a
            // streaming request is cancelled
            self.emitError(errors.RequestFrameState({
                attempted: 'arg parts',
                state: 'Done'
            }));
            break;
        case States.Error:
            // TODO: log warn
            break;
    }
};
 
TChannelOutRequest.prototype.sendCallRequestFrame = function sendCallRequestFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.start = self.channel.timers.now();
            if (self.span) {
                self.span.annotate('cs');
            }
            self._sendCallRequest(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            self.emitError(errors.RequestFrameState({
                attempted: 'call request',
                state: 'Streaming'
            }));
            break;
        case States.Done:
            self.emitError(errors.RequestAlreadyDone({
                attempted: 'call request'
            }));
            break;
    }
};
 
TChannelOutRequest.prototype.sendCallRequestContFrame = function sendCallRequestContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.emitError(errors.RequestFrameState({
                attempted: 'call request continuation',
                state: 'Initial'
            }));
            break;
        case States.Streaming:
            self._sendCallRequestCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
            self.emitError(errors.RequestAlreadyDone({
                attempted: 'call request continuation'
            }));
            break;
    }
};
 
TChannelOutRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
 
    self.endpoint = String(arg1);
 
    if (self.span) {
        self.span.name = self.endpoint;
 
        self.span.annotateBinary('as', self.headers.as);
        self.span.annotateBinary('cn', self.headers.cn);
    }
 
    if (self.logical === false && self.retryCount === 0) {
        self.emitOutboundCallsSent();
    }
 
    if (callback) {
        self.hookupCallback(callback);
    }
 
    self.arg1 = arg1;
    self.arg2 = arg2;
    self.arg3 = arg3;
 
    self.sendCallRequestFrame([arg1, arg2, arg3], true);
    self.finishEvent.emit(self);
    return self;
};
 
TChannelOutRequest.prototype.emitOutboundCallsSent =
function emitOutboundCallsSent() {
    var self = this;
 
    self.channel.emitFastStat(self.channel.buildStat(
        'outbound.calls.sent',
        'counter',
        1,
        new OutboundCallsSentTags(
            self.serviceName,
            self.headers.cn,
            self.endpoint
        )
    ));
};
 
function OutboundCallsSentTags(serviceName, cn, endpoint) {
    var self = this;
 
    self.app = '';
    self.host = '';
    self.cluster = '';
    self.version = '';
 
    self.targetService = serviceName;
    self.service = cn;
    self.targetEndpoint = endpoint;
}
 
TChannelOutRequest.prototype.hookupStreamCallback =
function hookupCallback(callback) {
    var self = this;
    var called = false;
 
    self.errorEvent.on(onError);
    self.responseEvent.on(onResponse);
 
    function onError(err) {
        Iif (called) return;
        called = true;
        callback(err, null, null);
    }
 
    function onResponse(res) {
        Iif (called) return;
        called = true;
        callback(null, self, res);
    }
 
    return self;
};
 
TChannelOutRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    Iif (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;
 
    self.errorEvent.on(onError);
    self.responseEvent.on(onResponse);
 
    function onError(err) {
        Iif (called) return;
        called = true;
        callback(err, null, null);
    }
 
    function onResponse(res) {
        Iif (called) return;
        called = true;
        if (!res.streamed) {
            callback(null, res, res.arg2, res.arg3);
            return;
        }
        parallel({
            arg2: res.arg2.onValueReady,
            arg3: res.arg3.onValueReady
        }, compatCall);
        function compatCall(err, args) {
            callback(err, res, args.arg2, args.arg3);
        }
    }
 
    return self;
};
 
TChannelOutRequest.prototype.onTimeout = function onTimeout(now) {
    var self = this;
 
    Eif (!self.res || self.res.state === States.Initial) {
        self.end = now;
        self.timedOut = true;
        Eif (self.operations) {
            self.operations.checkLastTimeoutTime(now);
            self.operations.popOutReq(self.id);
        }
        process.nextTick(deferOutReqTimeoutErrorEmit);
    }
 
    function deferOutReqTimeoutErrorEmit() {
        var elapsed = now - self.start;
        self.emitError(errors.RequestTimeoutError({
            id: self.id,
            start: self.start,
            elapsed: elapsed,
            logical: self.logical,
            timeout: self.timeout
        }));
    }
};