Code coverage report for node/index.js

Statements: 86.04% (376 / 437)      Branches: 72.11% (106 / 147)      Functions: 82.26% (51 / 62)      Lines: 86.24% (376 / 436)      Ignored: none     

All files » node/ » 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 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 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882                                            1 1 1 1 1 1 1 1 1 1 1   1 1 1 1 1   1   1             1             1         1                 1             1 2683 1332     1351   1351 1351   1351 1351   1351 1351   1351   1351   1351   1351   1351     1351 1351 1351 1351   1351   1351     1351 1351 1351   1351 4     1351 667 667 667   667             1351 1350 1348 1348 1348   1348 1348     1351 1 1           1           1   1351 1350     1     1 1351 1351     1351     1351             1351     1351 1351 1351 1351 1351       1                                                   1     1                   1 1328 1328       1 1345 1345 1     1344 1344 1344     1344 677   667   1344     1 2045 2045 2045     1 1343 1343 1343   1343 1           1342 1342 1342       1 2677 2677   2677 2677 2673   2673 2673       2677     1 1343   1343 1     1342 675     1342 1342               1342           1342   1342   1342 1342   1342         1             1                           1 692 692       692 692       692 692     1 696 696 696 667   696     1 678 678 1   677 677 677 677     1 677 677 677   677       1 1343 1343     1 1350   1350       1350 1350 4   1350 1350   1350       1350 1343 1343   1343   1343           1343 1343     1350 1350 1348   2     1 1350 1350     1 2693 1350         1350 1341             1 1344 1344       1344 1344 1344 1344 1344 1344 1344   1344     1344 1344 1344 1344   1344 1344   1344 1344 1344         1344 691     1344 689 689                 689     1344 1 1     1344   1344 10   1344 1344 1344         1344 3164   1344       1344           1344 677 677 667 667           667 667 667 667             1344   1344   1344   1344           1344           1344           1344       1 1344     1   1                                 1 1352 1352 1352 1352     1 1352 1352   8       1 2687 2687 1344 1344           1 10 10 2     8           8 8   8     1 8 8 8   8 2 2   2       2 2 2 1 1         1 8 8 8 8 4 4 4           4                   4 4 4 2 2 2         1 2 2 2   2           1 1344 1344 1344   1344 1344   1344                   1344   1344         1344             1344             1344 1344   1344     1 1354 1354 1       1 3164 3164 3164       1 690 690 690           690 690 690       1 692                   692 692   692 692 692 692 692     1 691 691 691 691 691 691 691 691   1 691 5                 5   5     691     1 690             690 690       1 691 691 691 691 691 691 691     1 692 692 692 692     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 globalClearTimeout = require('timers').clearTimeout;
var globalSetTimeout = require('timers').setTimeout;
var globalNow = Date.now;
var globalRandom = Math.random;
var net = require('net');
var format = require('util').format;
var TypedError = require('error/typed');
var WrappedError = require('error/wrapped');
var bufrw = require('bufrw');
var ChunkReader = require('bufrw/stream/chunk_reader');
var ChunkWriter = require('bufrw/stream/chunk_writer');
 
var v2 = require('./v2');
var nullLogger = require('./null-logger.js');
var Spy = require('./v2/spy');
var EndpointHandler = require('./endpoint-handler.js');
var TracingAgent = require('./trace/agent');
 
var dumpEnabled = /\btchannel_dump\b/.test(process.env.NODE_DEBUG || '');
 
var TChannelListenError = WrappedError({
    type: 'tchannel.server.listen-failed',
    message: 'tchannel: {origMessage}',
    requestedPort: null,
    host: null
});
 
var TChannelReadProtocolError = WrappedError({
    type: 'tchannel.protocol.read-failed',
    message: 'tchannel read failure: {origMessage}',
    remoteName: null,
    localName: null
});
 
var NoHandlerError = TypedError({
    type: 'tchannel.no-handler',
    message: 'no handler defined'
});
 
var InvalidHandlerForRegister = TypedError({
    type: 'tchannel.invalid-handler.for-registration',
    message: 'Found unexpected handler when calling `.register()`.\n' +
        'You cannot set a custom handler when using `.register()`.\n' +
        '`.register()` is deprecated; use a proper handler.',
    handlerType: null,
    handler: null
});
 
var noHandlerHandler = {
    type: 'no-handler.handler',
    handleRequest: function noHandlerHandler(req, res) {
        res.sendNotOk(null, NoHandlerError().message);
    }
};
 
function TChannel(options) {
    if (!(this instanceof TChannel)) {
        return new TChannel(options);
    }
 
    var self = this;
 
    self.options = options || {};
    self.logger = self.options.logger || nullLogger;
    // Filled in by the listen call:
    self.host = null;
    self.requestedPort = null;
    // Filled in by listening event:
    self.port = null;
    self.hostPort = null;
    // TODO: maybe we should always add pid to user-supplied?
    self.processName = self.options.processName ||
        format('%s[%s]', process.title, process.pid);
    self.random = self.options.random ?
        self.options.random : globalRandom;
    self.setTimeout = self.options.timers ?
        self.options.timers.setTimeout : globalSetTimeout;
    self.clearTimeout = self.options.timers ?
        self.options.timers.clearTimeout : globalClearTimeout;
    self.now = self.options.timers ?
        self.options.timers.now : globalNow;
 
    self.reqTimeoutDefault = self.options.reqTimeoutDefault || 5000;
    self.serverTimeoutDefault = self.options.serverTimeoutDefault || 5000;
    self.timeoutCheckInterval = self.options.timeoutCheckInterval || 1000;
    self.timeoutFuzz = self.options.timeoutFuzz || 100;
 
    self.peers = Object.create(null);
 
    self.handler = self.options.handler || noHandlerHandler;
 
    // TChannel advances through the following states.
    self.listened = false;
    self.listening = false;
    self.destroyed = false;
 
    if (self.options.trace) {
        self.tracer = TracingAgent.getInstance();
    }
 
    self.serverSocket = net.createServer(function onServerSocketConnection(sock) {
        Eif (!self.destroyed) {
            var remoteAddr = sock.remoteAddress + ':' + sock.remotePort;
            var conn = new TChannelConnection(
                self, sock, 'in', remoteAddr, self.tracer);
            self.logger.debug('incoming server connection', {
                hostPort: self.hostPort,
                remoteAddr: conn.remoteAddr
            });
        }
    });
 
    self.serverSocket.on('listening', function onServerSocketListening() {
        if (!self.destroyed) {
            var address = self.serverSocket.address();
            self.hostPort = self.host + ':' + address.port;
            self.listening = true;
 
            self.logger.info(self.hostPort + ' listening');
            self.emit('listening');
        }
    });
    self.serverSocket.on('error', function onServerSocketError(err) {
        Eif (err.code === 'EADDRINUSE') {
            err = TChannelListenError(err, {
                requestedPort: self.requestedPort,
                host: self.host
            });
        }
 
        self.logger.error('server socket error', {
            err: err,
            requestedPort: self.requestedPort,
            host: self.host,
            hostPort: self.hostPort || null
        });
        self.emit('error', err);
    });
    self.serverSocket.on('close', function onServerSocketClose() {
        self.logger.warn('server socket close');
    });
}
require('util').inherits(TChannel, require('events').EventEmitter);
 
// Decoulping config and creation from the constructor.
TChannel.prototype.listen = function listen(port, host, callback) {
    var self = this;
    Iif (self.listened) {
        throw new Error('TChannel can only listen once'); // TODO typed error
    }
    Iif (typeof host !== 'string') {
        throw new Error('TChannel requires host argument'); // TODO typed error
    }
    Iif (typeof port !== 'number') {
        // Note that 0 is a valid port number, indicating that the system must
        // assign an available ephemeral port.
        throw new Error('TChannel must listen with numeric port'); // TODO typed error
    }
    // Does not expressly forbid 127.0.0.1 or localhost since these are valid
    // hosts for testing.
    Iif (host === '0.0.0.0') {
        throw new Error('TChannel must listen with externally visible host'); // TODO typed error
    }
    self.listened = true;
    self.requestedPort = port;
    self.host = host;
    var serverSocket = self.serverSocket;
    serverSocket.listen(port, host, callback);
};
 
// TODO: deprecated, callers should use .handler directly
TChannel.prototype.register = function register(name, handler) {
    var self = this;
 
    var handlerType = self.handler && self.handler.type;
 
    switch (handlerType) {
        case 'no-handler.handler':
            // lazyily set up the legacy handler
            self.handler = EndpointHandler();
            self.handler.type = 'legacy-handler.handler';
 
            break;
 
        case 'legacy-handler.handler':
            // If its still the legacy handler then we are good.
            break;
 
        default:
            throw InvalidHandlerForRegister({
                handlerType: handlerType,
                handler: self.handler
            });
    }
 
    self.handler.register(name, onReqRes);
 
    function onReqRes(req, res, arg2, arg3) {
        handler(arg2, arg3, req.remoteAddr, onResponse);
 
        function onResponse(err, res1, res2) {
            if (err) {
                res.sendNotOk(res1, err.message);
            } else {
                res.sendOk(res1, res2);
            }
        }
    }
};
 
TChannel.prototype.address = function address() {
    var self = this;
    return self.serverSocket.address();
};
 
// not public, used by addPeer
TChannel.prototype.setPeer = function setPeer(hostPort, conn) {
    var self = this;
    if (hostPort === self.hostPort) {
        throw new Error('refusing to set self peer'); // TODO typed error
    }
 
    var list = self.peers[hostPort];
    Eif (!list) {
        list = self.peers[hostPort] = [];
    }
 
    if (conn.direction === 'out') {
        list.unshift(conn);
    } else {
        list.push(conn);
    }
    return conn;
};
 
TChannel.prototype.getPeer = function getPeer(hostPort) {
    var self = this;
    var list = self.peers[hostPort];
    return list && list[0] ? list[0] : null;
};
 
TChannel.prototype.removePeer = function removePeer(hostPort, conn) {
    var self = this;
    var list = self.peers[hostPort];
    var index = list ? list.indexOf(conn) : -1;
 
    if (index === -1) {
        return;
    }
 
    // TODO: run (don't walk) away from "arrays" as peers, get to actual peer
    // objects... note how these current semantics can implicitly convert
    // an in socket to an out socket
    list.splice(index, 1);
    Eif (!list.length) {
        delete self.peers[hostPort];
    }
};
 
TChannel.prototype.getPeers = function getPeers() {
    var self = this;
    var keys = Object.keys(self.peers);
 
    var peers = [];
    for (var i = 0; i < keys.length; i++) {
        var list = self.peers[keys[i]];
 
        for (var j = 0; j < list.length; j++) {
            peers.push(list[j]);
        }
    }
 
    return peers;
};
 
TChannel.prototype.addPeer = function addPeer(hostPort, connection) {
    var self = this;
 
    if (hostPort === self.hostPort) {
        throw new Error('refusing to add self peer'); // TODO typed error
    }
 
    if (!connection) {
        connection = self.makeOutConnection(hostPort);
    }
 
    var existingPeer = self.getPeer(hostPort);
    Iif (existingPeer !== null && existingPeer !== connection) { // TODO: how about === undefined?
        self.logger.warn('allocated a connection twice', {
            hostPort: hostPort,
            direction: connection.direction
            // TODO: more log context
        });
    }
 
    self.logger.debug('alloc peer', {
        source: self.hostPort,
        destination: hostPort,
        direction: connection.direction
        // TODO: more log context
    });
    connection.once('reset', function onConnectionReset(/* err */) {
        // TODO: log?
        self.removePeer(hostPort, connection);
    });
    connection.once('socketClose', function onConnectionSocketClose(conn, err) {
        self.emit('socketClose', conn, err);
    });
    return self.setPeer(hostPort, connection);
};
 
/* jshint maxparams:5 */
// TODO: deprecated, callers should use .request directly
TChannel.prototype.send = function send(options, arg1, arg2, arg3, callback) {
    var self = this;
 
    return self
        .request(options)
        .send(arg1, arg2, arg3, onResponse);
 
    function onResponse(err, res, arg2, arg3) {
        if (err) {
            return callback(err);
        }
 
        if (!res.ok) {
            return callback(new Error(String(arg3)));
        }
 
        return callback(null, arg2, arg3);
    }
};
/* jshint maxparams:4 */
 
TChannel.prototype.request = function request(options) {
    var self = this;
    Iif (self.destroyed) {
        throw new Error('cannot request() to destroyed tchannel'); // TODO typed error
    }
 
    var dest = options.host;
    Iif (!dest) {
        throw new Error('cannot request() without options.host'); // TODO typed error
    }
 
    var peer = self.getOutConnection(dest);
    return peer.request(options);
};
 
TChannel.prototype.getOutConnection = function getOutConnection(dest) {
    var self = this;
    var peer = self.getPeer(dest);
    if (!peer) {
        peer = self.addPeer(dest);
    }
    return peer;
};
 
TChannel.prototype.makeSocket = function makeSocket(dest) {
    var parts = dest.split(':');
    if (parts.length !== 2) {
        throw new Error('invalid destination'); // TODO typed error
    }
    var host = parts[0];
    var port = parts[1];
    var socket = net.createConnection({host: host, port: port});
    return socket;
};
 
TChannel.prototype.makeOutConnection = function makeOutConnection(dest) {
    var self = this;
    var socket = self.makeSocket(dest);
    var connection =
        new TChannelConnection(self, socket, 'out', dest, self.tracer);
    return connection;
};
 
// to provide backward compatibility.
TChannel.prototype.quit = function close(callback) {
    var self = this;
    self.close(callback);
};
 
TChannel.prototype.close = function close(callback) {
    var self = this;
 
    Iif (self.destroyed) {
        throw new Error('double close'); // TODO typed error
    }
 
    self.destroyed = true;
    if (self.tracer) {
        self.tracer.destroy();
    }
    var peers = self.getPeers();
    var counter = peers.length + 1;
 
    self.logger.debug('quitting tchannel', {
        hostPort: self.hostPort
    });
 
    peers.forEach(function eachPeer(conn) {
        var sock = conn.socket;
        sock.once('close', onClose);
 
        conn.clearTimeoutTimer();
 
        self.logger.debug('destroy channel for', {
            direction: conn.direction,
            peerRemoteAddr: conn.remoteAddr,
            peerRemoteName: conn.remoteName,
            fromAddress: sock.address()
        });
        conn.resetAll(new Error('shutdown from quit')); // TODO typed error
        sock.destroy();
    });
 
    var serverSocket = self.serverSocket;
    if (serverSocket.address()) {
        closeServerSocket();
    } else {
        serverSocket.once('listening', closeServerSocket);
    }
 
    function closeServerSocket() {
        serverSocket.once('close', onClose);
        serverSocket.close();
    }
 
    function onClose() {
        if (--counter <= 0) {
            Iif (counter < 0) {
                self.logger.error('closed more sockets than expected', {
                    counter: counter
                });
            }
            if (typeof callback === 'function') {
                callback();
            }
        }
    }
};
 
/* jshint maxparams:6 */
function TChannelConnection(channel, socket, direction, remoteAddr, tracer) {
    var self = this;
    Iif (remoteAddr === channel.hostPort) {
        throw new Error('refusing to create self connection'); // TODO typed error
    }
 
    self.channel = channel;
    self.logger = self.channel.logger;
    self.socket = socket;
    self.direction = direction;
    self.remoteAddr = remoteAddr;
    self.timer = null;
    self.tracer = tracer;
 
    self.remoteName = null; // filled in by identify message
 
    // TODO: factor out an operation collection abstraction
    self.inOps = Object.create(null);
    self.inPending = 0;
    self.outOps = Object.create(null);
    self.outPending = 0;
 
    self.lastTimeoutTime = 0;
    self.closing = false;
 
    self.reader = ChunkReader(bufrw.UInt16BE, v2.Frame.RW);
    self.writer = ChunkWriter(v2.Frame.RW);
    self.handler = new v2.Handler(self.channel, {
        tracer: self.tracer
    });
 
    // TODO: refactor op boundary to pass full req/res around
    self.handler.on('call.incoming.request', function onCallRequest(req) {
        self.handleCallRequest(req);
    });
 
    self.handler.on('call.incoming.response', function onCallResponse(res) {
        var op = self.popOutOp(res.id);
        Iif (!op) {
            self.logger.warn('response received for unknown or lost operation', {
                responseId: res.id,
                remoteAddr: self.remoteAddr,
                direction: self.direction,
            });
            return;
        }
 
        op.req.emit('response', res);
    });
 
    self.handler.on('call.incoming.error', function onCallError(err) {
        var op = self.popOutOp(err.originalId);
        op.req.emit('error', err);
    });
 
    self.socket.setNoDelay(true);
 
    self.socket.on('error', function onSocketError(err) {
        self.onSocketErr(err);
    });
    self.socket.on('close', function onSocketClose() {
        self.onSocketErr(new Error('socket closed')); // TODO typed error
        Iif (self.remoteName === '0.0.0.0:0') {
            self.channel.removePeer(self.remoteAddr, self);
        }
    });
 
    self.reader.on('data', function onReaderFrame(frame) {
        self.onFrame(frame);
    });
    self.reader.on('error', function onReaderError(err) {
        self.onReaderError(err);
    });
 
    self.handler.on('error', function onHandlerError(err) {
        self.resetAll(err);
        // resetAll() does not close the socket
        self.socket.destroy();
    });
 
    if (direction === 'out') {
        self.handler.sendInitRequest();
        self.handler.once('init.response', function onOutIdentified(init) {
            self.remoteName = init.hostPort;
            self.channel.emit('identified', {
                hostPort: init.hostPort,
                processName: init.processName
            });
        });
    } else {
        self.handler.once('init.request', function onInIdentified(init) {
            self.remoteName = init.hostPort;
            self.channel.addPeer(init.hostPort, self);
            self.channel.emit('identified', {
                hostPort: init.hostPort,
                processName: init.processName
            });
        });
    }
 
    self.startTimeoutTimer();
 
    socket.once('close', clearTimer);
 
    var stream = self.socket;
 
    Iif (dumpEnabled) {
        stream = stream.pipe(Spy(process.stdout, {
            prefix: '>>> ' + self.remoteAddr + ' '
        }));
    }
 
    stream = stream
        .pipe(self.reader)
        .pipe(self.handler)
        .pipe(self.writer)
        ;
 
    Iif (dumpEnabled) {
        stream = stream.pipe(Spy(process.stdout, {
            prefix: '<<< ' + self.remoteAddr + ' '
        }));
    }
 
    stream = stream
        .pipe(self.socket)
        ;
 
    function clearTimer() {
        self.channel.clearTimeout(self.timer);
    }
}
require('util').inherits(TChannelConnection, require('events').EventEmitter);
 
TChannelConnection.prototype.onReaderError = function onReaderError(err) {
    var self = this;
 
    var readError = TChannelReadProtocolError(err, {
        remoteName: self.remoteName,
        localName: self.channel.hostPort
    });
 
    // TODO instead of resetting send an error frame first.
    // and reset the socket after sending an error frame
    self.resetAll(readError);
    // resetAll() does not close the socket
    self.socket.destroy();
};
 
// timeout check runs every timeoutCheckInterval +/- some random fuzz. Range is from
//   base - fuzz/2 to base + fuzz/2
TChannelConnection.prototype.getTimeoutDelay = function getTimeoutDelay() {
    var self = this;
    var base = self.channel.timeoutCheckInterval;
    var fuzz = self.channel.timeoutFuzz;
    return base + Math.round(Math.floor(self.channel.random() * fuzz) - (fuzz / 2));
};
 
TChannelConnection.prototype.startTimeoutTimer = function startTimeoutTimer() {
    var self = this;
    self.timer = self.channel.setTimeout(function onChannelTimeout() {
        // TODO: worth it to clear the fired self.timer objcet?
        self.onTimeoutCheck();
    }, self.getTimeoutDelay());
};
 
TChannelConnection.prototype.clearTimeoutTimer = function clearTimeoutTimer() {
    var self = this;
    if (self.timer) {
        self.channel.clearTimeout(self.timer);
        self.timer = null;
    }
};
 
// If the connection has some success and some timeouts, we should probably leave it up,
// but if everything is timing out, then we should kill the connection.
TChannelConnection.prototype.onTimeoutCheck = function onTimeoutCheck() {
    var self = this;
    if (self.closing) {
        return;
    }
 
    Iif (self.lastTimeoutTime) {
        self.logger.warn(self.channel.hostPort + ' destroying socket from timeouts');
        self.socket.destroy();
        return;
    }
 
    self.checkOutOpsForTimeout(self.outOps);
    self.checkInOpsForTimeout(self.inOps);
 
    self.startTimeoutTimer();
};
 
TChannelConnection.prototype.checkInOpsForTimeout = function checkInOpsForTimeout(ops) {
    var self = this;
    var opKeys = Object.keys(ops);
    var now = self.channel.now();
 
    for (var i = 0; i < opKeys.length; i++) {
        var opKey = opKeys[i];
        var op = ops[opKey];
 
        Iif (op === undefined) {
            continue;
        }
 
        var timeout = self.channel.serverTimeoutDefault;
        var duration = now - op.start;
        if (duration > timeout) {
            delete ops[opKey];
            self.inPending--;
        }
    }
};
 
TChannelConnection.prototype.checkOutOpsForTimeout = function checkOutOpsForTimeout(ops) {
    var self = this;
    var opKeys = Object.keys(ops);
    var now = self.channel.now();
    for (var i = 0; i < opKeys.length ; i++) {
        var opKey = opKeys[i];
        var op = ops[opKey];
        Iif (op.timedOut) {
            delete ops[opKey];
            self.outPending--;
            self.logger.warn('lingering timed-out outgoing operation');
            continue;
        }
        Iif (op === undefined) {
            // TODO: why not null and empty string too? I mean I guess false
            // and 0 might be a thing, but really why not just !op?
            self.channel.logger
                .warn('unexpected undefined operation', {
                    key: opKey,
                    op: op
                });
            continue;
        }
        var timeout = op.req.ttl || self.channel.reqTimeoutDefault;
        var duration = now - op.start;
        if (duration > timeout) {
            delete ops[opKey];
            self.outPending--;
            self.onReqTimeout(op);
        }
    }
};
 
TChannelConnection.prototype.onReqTimeout = function onReqTimeout(op) {
    var self = this;
    op.timedOut = true;
    op.req.emit('error', new Error('timed out')); // TODO typed error
    // TODO: why don't we pop the op?
    self.lastTimeoutTime = self.channel.now();
};
 
// this socket is completely broken, and is going away
// In addition to erroring out all of the pending work, we reset the state in case anybody
// stumbles across this object in a core dump.
TChannelConnection.prototype.resetAll = function resetAll(err) {
    var self = this;
    Iif (self.closing) return;
    self.closing = true;
 
    var inOpKeys = Object.keys(self.inOps);
    var outOpKeys = Object.keys(self.outOps);
 
    self.logger[err ? 'warn' : 'info']('resetting connection', {
        error: err,
        remoteName: self.remoteName,
        localName: self.channel.hostPort,
        numInOps: inOpKeys.length,
        numOutOps: outOpKeys.length,
        inPending: self.inPending,
        outPending: self.outPending
    });
 
    self.clearTimeoutTimer();
 
    self.emit('reset', err);
 
    // requests that we've received we can delete, but these reqs may have started their
    //   own outgoing work, which is hard to cancel. By setting this.closing, we make sure
    //   that once they do finish that their callback will swallow the response.
    inOpKeys.forEach(function eachInOp(id) {
        // TODO: we could support an op.cancel opt-in callback
        delete self.inOps[id];
        // TODO report or handle or log errors or something
    });
 
    // for all outgoing requests, forward the triggering error to the user callback
    outOpKeys.forEach(function eachOutOp(id) {
        var op = self.outOps[id];
        delete self.outOps[id];
        // TODO: shared mutable object... use Object.create(err)?
        op.req.emit('error', err);
    });
 
    self.inPending = 0;
    self.outPending = 0;
 
    self.emit('socketClose', self, err);
};
 
TChannelConnection.prototype.onSocketErr = function onSocketErr(err) {
    var self = this;
    if (!self.closing) {
        self.resetAll(err);
    }
};
 
TChannelConnection.prototype.onFrame = function onFrame(/* frame */) {
    var self = this;
    Eif (!self.closing) {
        self.lastTimeoutTime = 0;
    }
};
 
TChannelConnection.prototype.popOutOp = function popOutOp(id) {
    var self = this;
    var op = self.outOps[id];
    Iif (!op) {
        // TODO else case. We should warn about an incoming response for an
        // operation we did not send out.  This could be because of a timeout
        // or could be because of a confused / corrupted server.
        return;
    }
    delete self.outOps[id];
    self.outPending--;
    return op;
};
 
// create a request
TChannelConnection.prototype.request = function request(options) {
    var self = this;
    // TODO: use this to protect against >4Mi outstanding messages edge case
    // (e.g. zombie operation bug, incredible throughput, or simply very long
    // timeout
    // if (self.outOps[id]) {
    //  throw new Error('duplicate frame id in flight'); // TODO typed error
    // }
    // TODO: provide some sort of channel default for "service"
    // TODO: refactor callers
 
    options.checksumType = options.checksum;
    options.ttl = options.timeout || 1; // TODO: better default, support for dynamic
 
    var req = self.handler.buildOutgoingRequest(options);
    var id = req.id;
    self.outOps[id] = new TChannelClientOp(req, self.channel.now());
    self.pendingCount++;
    return req;
};
 
TChannelConnection.prototype.handleCallRequest = function handleCallRequest(req) {
    var self = this;
    req.remoteAddr = self.remoteName;
    var res = self.handler.buildOutgoingResponse(req);
    var id = req.id;
    self.inPending++;
    var op = self.inOps[id] = new TChannelServerOp(self, self.channel.now(), req, res);
    res.once('finish', opDone);
    process.nextTick(runHandler);
 
    function runHandler() {
        if (self.tracer) {
            res.span = self.tracer.setupNewSpan({
                spanid: req.tracing.spanid,
                traceid: req.tracing.traceid,
                parentid: req.tracing.parentid,
                hostPort: self.channel.hostPort,
                serviceName: self.channel.options.serviceName
            });
 
            // TODO: better annotations
            res.span.annotate('sr', Date.now());
 
            self.tracer.setCurrentSpan(res.span);
        }
 
        self.channel.handler.handleRequest(req, res);
    }
 
    function opDone() {
        Iif (self.inOps[id] !== op) {
            self.logger.warn('mismatched opDone callback', {
                hostPort: self.channel.hostPort,
                opId: id
            });
            return;
        }
        delete self.inOps[id];
        self.inPending--;
    }
};
 
function TChannelServerOp(connection, start, req, res) {
    var self = this;
    self.req = req;
    self.res = res;
    self.connection = connection;
    self.logger = connection.logger;
    self.timedOut = false;
    self.start = start;
}
 
function TChannelClientOp(req, start) {
    var self = this;
    self.req = req;
    self.start = start;
    self.timedOut = false;
}
 
module.exports = TChannel;