Code coverage report for node/connection_base.js

Statements: 98.29% (115 / 117)      Branches: 80.49% (33 / 41)      Functions: 100% (18 / 18)      Lines: 98.28% (114 / 116)      Ignored: none     

All files » node/ » connection_base.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                                            1 1 1   1 1 1   1   1 1109   1109 1109 1109 1109 1109   1109 1109 1109   1109 1109 1109 1109 1109 1109 1109 1109 1109   1109                 1109   1109   1     1   2583   2583 2583                 2583   2582     1 2566   2566   2566 2566   2566   1 31     1 2566       1 31 31 31     31             1 2566   2566                     2566 1 2558       1 2566   2566 2566 2566 2566   2566 2566 2566     1   2567   2567 1               2567 2567     2567   2567 2567   2567 1947     2567   1 2577     1 22       1   1947   1947   1 1933       1 20     1   1933   1933     1   22   22                   22 10   10     10 10 10 10 12 12 12     22       7       15           1 2577   2577     2577 9               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 errors = require('./errors');
var States = require('./reqres_states');
var Operations = require('./operations');
 
var CONNECTION_BASE_IDENTIFIER = 0;
 
function TChannelConnectionBase(channel, direction, socketRemoteAddr) {
    assert(!channel.destroyed, 'refuse to create connection for destroyed channel');
 
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.timedOutEvent = self.defineEvent('timedOut');
    self.pingResponseEvent = self.defineEvent('pingResonse');
 
    self.closing = false;
    self.closeError = null;
    self.closeEvent = self.defineEvent('close');
 
    self.channel = channel;
    self.options = self.channel.options;
    self.logger = channel.logger;
    self.random = channel.random;
    self.timers = channel.timers;
    self.direction = direction;
    self.socketRemoteAddr = socketRemoteAddr;
    self.timer = null;
    self.remoteName = null; // filled in by identify message
 
    self.ops = new Operations({
        timers: self.timers,
        logger: self.logger,
        random: self.random,
        initTimeout: self.channel.initTimeout,
        connectionStalePeriod: self.options.connectionStalePeriod,
        connection: self
    });
 
    self.guid = ++CONNECTION_BASE_IDENTIFIER + '~';
 
    self.tracer = self.channel.tracer;
}
inherits(TChannelConnectionBase, EventEmitter);
 
// create a request
TChannelConnectionBase.prototype.request =
function connBaseRequest(options) {
    var self = this;
 
    assert(self.remoteName, 'cannot make request unless identified');
    options.remoteAddr = self.remoteName;
 
    // TODO: use this to protect against >4Mi outstanding messages edge case
    // (e.g. zombie operation bug, incredible throughput, or simply very long
    // timeout
    // assert(!self.requests.out[id], 'duplicate frame id in flight');
 
    // options.checksumType = options.checksum;
 
    var req = self.buildOutRequest(options);
 
    return self.ops.addOutReq(req);
};
 
TChannelConnectionBase.prototype.handleCallRequest = function handleCallRequest(req) {
    var self = this;
    
    self.ops.addInReq(req);
 
    req.remoteAddr = self.remoteName;
    req.errorEvent.on(onReqError);
 
    process.nextTick(runHandler);
 
    function onReqError(err) {
        self.onReqError(req, err);
    }
 
    function runHandler() {
        self.runHandler(req);
    }
};
 
TChannelConnectionBase.prototype.onReqError = function onReqError(req, err) {
    var self = this;
    if (!req.res) self.buildResponse(req, {});
    Eif (err.type === 'tchannel.timeout' ||
        err.type === 'tchannel.request.timeout'
    ) {
        req.res.sendError('Timeout', err.message);
    } else {
        var errName = err.name || err.constructor.name;
        req.res.sendError('UnexpectedError', errName + ': ' + err.message);
    }
};
 
TChannelConnectionBase.prototype.runHandler = function runHandler(req) {
    var self = this;
 
    self.channel.emitFastStat(self.channel.buildStat(
        'inbound.calls.recvd',
        'counter',
        1,
        new InboundCallsRecvdTags(
            req.headers.cn,
            req.serviceName,
            req.endpoint
        )
    ));
 
    self.channel.handler.handleRequest(req, buildResponse);
    function buildResponse(options) {
        return self.buildResponse(req, options || {});
    }
};
 
function InboundCallsRecvdTags(cn, serviceName, endpoint) {
    var self = this;
 
    self.app = null;
    self.host = null;
    self.cluster = null;
    self.version = null;
 
    self.callingService = cn || '';
    self.service = serviceName;
    self.endpoint = endpoint;
}
 
TChannelConnectionBase.prototype.buildResponse =
function buildResponse(req, options) {
    var self = this;
 
    if (req.res && req.res.state !== States.Initial) {
        self.errorEvent.emit(self, errors.ResponseAlreadyStarted({
            state: req.res.state,
            reason: 'buildResponse called twice',
            codeString: req.res.codeString,
            responseMessage: req.res.message
        }));
    }
 
    options.channel = self.channel;
    options.inreq = req;
 
    // TODO give this options a well defined type
    req.res = self.buildOutResponse(req, options);
 
    req.res.errorEvent.on(onError);
    req.res.finishEvent.on(opDone);
 
    if (!req.forwardTrace) {
        self.captureResponseSpans(req.res);
    }
 
    return req.res;
 
    function opDone() {
        self.onReqDone(req);
    }
 
    function onError(err) {
        self.onResponseError(err, req);
    }
};
 
TChannelConnectionBase.prototype.captureResponseSpans =
function captureResponseSpans(res) {
    var self = this;
 
    res.spanEvent.on(handleSpanFromRes);
 
    function handleSpanFromRes(span) {
        self.handleSpanFromRes(span);
    }
};
 
function isStringOrBuffer(x) {
    return typeof x === 'string' || Buffer.isBuffer(x);
}
 
TChannelConnectionBase.prototype.handleSpanFromRes =
function handleSpanFromRes(span) {
    var self = this;
 
    self.channel.tracer.report(span);
};
 
TChannelConnectionBase.prototype.onResponseError =
function onResponseError(err, req) {
    var self = this;
 
    var loggingOptions = {
        error: err,
        arg1: String(req.arg1),
        ok: req.res.ok,
        type: req.res.type,
        state: req.res.state === States.Done ? 'Done' :
            req.res.state === States.Error ? 'Error' :
            'Unknown'
    };
 
    if (req.res.state === States.Done) {
        var arg2 = isStringOrBuffer(req.res.arg2) ?
            req.res.arg2 : 'streaming';
        var arg3 = isStringOrBuffer(req.res.arg3) ?
            req.res.arg3 : 'streaming';
 
        loggingOptions.bufArg2 = arg2.slice(0, 50);
        loggingOptions.arg2 = String(arg2).slice(0, 50);
        loggingOptions.bufArg3 = arg3.slice(0, 50);
        loggingOptions.arg3 = String(arg3).slice(0, 50);
    } else Eif (req.res.state === States.Error) {
        loggingOptions.codeString = req.res.codeString;
        loggingOptions.errMessage = req.res.message;
    }
 
    if ((err.type === 'tchannel.response-already-started' ||
        err.type === 'tchannel.response-already-done') &&
        req.timedOut
    ) {
        self.logger.info(
            'error for timed out outgoing response', loggingOptions
        );
    } else {
        self.logger.error(
            'outgoing response has an error', loggingOptions
        );
    }
};
 
TChannelConnectionBase.prototype.onReqDone = function onReqDone(req) {
    var self = this;
 
    var inreq = self.ops.popInReq(req.id);
 
    // incoming req that timed out are already cleaned up
    if (inreq !== req && !req.timedOut) {
        self.logger.warn('mismatched onReqDone callback', {
            hostPort: self.channel.hostPort,
            hasInReq: inreq !== undefined,
            id: req.id
        });
    }
};
 
module.exports = TChannelConnectionBase;