Code coverage report for node/operations.js

Statements: 88.2% (142 / 161)      Branches: 62.96% (34 / 54)      Functions: 90.48% (19 / 21)      Lines: 88.2% (142 / 161)      Ignored: none     

All files » node/ » operations.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                                            1   1   1   1 1097   1097 1097 1097 1097 1097 1097 1097   1097 1097 1097 1097   1097     1097       1097       1097     1 2541   2541 2541 2541 2541     1 29   29               29 27       1   6604   6604       1 5508       1 1082   1082     1 7637   7637     1 3885   3885     1           1 2565   2565 2565 2565   2565     1 2549   2549 2549 2549   2549     1 2563   2563 2563 22 22 85   22             2541   2541 2541 2541 2541   2541   2541     1                                                         1 2577   2577 2577   35     2542 2542   2542     1 29   29 7 22 22       1 1082   1082 1082 1082     1 2108   2108   2108 1097 1097           1   6604   6604     1   6604   6604 6604 12     6592         1   5508 5508       5508 5508 3 3 1           1       5507 5507   5507 5507 5507 12742 12742 11445     5507   5507     1   11014 11014 11014 216 216 216         216                     216 53 29       53 24 29 29          
// 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 errors = require('./errors.js');
 
var TOMBSTONE_TTL_OFFSET = 500;
 
module.exports = Operations;
 
function Operations(opts) {
    var self = this;
 
    self.timers = opts.timers;
    self.logger = opts.logger;
    self.random = opts.random;
    self.timeoutCheckInterval = opts.timeoutCheckInterval;
    self.timeoutFuzz = opts.timeoutFuzz;
    self.initTimeout = opts.initTimeout;
    self.connectionStalePeriod = opts.connectionStalePeriod;
 
    self.connection = opts.connection;
    self.startTime = self.timers.now();
    self.timer = null;
    self.destroyed = false;
 
    self.tombstones = {
        out: []
    };
    self.requests = {
        in: Object.create(null),
        out: Object.create(null)
    };
    self.pending = {
        in: 0,
        out: 0
    };
    self.lastTimeoutTime = 0;
}
 
function OperationTombstone(operations, id, time, timeout) {
    var self = this;
 
    self.operations = operations;
    self.id = id;
    self.time = time;
    self.timeout = timeout;
}
 
Operations.prototype.checkLastTimeoutTime = function checkLastTimeoutTime(now) {
    var self = this;
 
    Iif (self.lastTimeoutTime &&
        now > self.lastTimeoutTime + self.connectionStalePeriod) {
        var err = errors.ConnectionStaleTimeoutError({
            lastTimeoutTime: self.lastTimeoutTime
        });
        self.connection.timedOutEvent.emit(self.connection, err);
        // TODO: y u no:
        // self.lastTimeoutTime = now;
    } else if (!self.lastTimeoutTime) {
        self.lastTimeoutTime = now;
    }
};
 
Operations.prototype.startTimeoutTimer =
function startTimeoutTimer() {
    var self = this;
 
    self.timer = self.timers.setTimeout(
        onChannelTimeout, self._getTimeoutDelay()
    );
 
    function onChannelTimeout() {
        self._onTimeoutCheck();
    }
};
 
Operations.prototype.getRequests = function getRequests() {
    var self = this;
 
    return self.requests;
};
 
Operations.prototype.getPending = function getPending() {
    var self = this;
 
    return self.pending;
};
 
Operations.prototype.getOutReq = function getOutReq(id) {
    var self = this;
 
    return self.requests.out[id];
};
 
Operations.prototype.getInReq = function getInReq(id) {
    var self = this;
 
    return self.requests.in[id];
};
 
Operations.prototype.addOutReq = function addOutReq(req) {
    var self = this;
 
    req.operations = self;
    self.requests.out[req.id] = req;
    self.pending.out++;
 
    return req;
};
 
Operations.prototype.addInReq = function addInReq(req) {
    var self = this;
 
    req.operations = self;
    self.requests.in[req.id] = req;
    self.pending.in++;
 
    return req;
};
 
Operations.prototype.popOutReq = function popOutReq(id, context) {
    var self = this;
 
    var req = self.requests.out[id];
    if (!req) {
        var tombstones = self.tombstones.out;
        for (var i = 0; i < tombstones.length; i++) {
            if (tombstones[i].id === id) {
                // If this id has been timed out then just return
                return null;
            }
        }
        self.logMissingOutRequest(id, context);
        return null;
    }
 
    delete self.requests.out[id];
 
    var now = self.timers.now();
    var timeout = TOMBSTONE_TTL_OFFSET + req.timeout;
    var tombstone = new OperationTombstone(self, req.id, now, timeout);
    self.pending.out--;
 
    self.tombstones.out.push(tombstone);
 
    return req;
};
 
Operations.prototype.logMissingOutRequest =
function logMissingOutRequest(id, context) {
    var self = this;
 
    // context is err or res
    if (context && context.originalId) {
        context = {
            error: context,
            id: context.originalId,
            info: 'got error frame for unknown id'
        };
    } else if (context && context.id) {
        context = {
            responseId: context.id,
            code: context.code,
            arg1: Buffer.isBuffer(context.arg1) ?
                String(context.arg1) : 'streamed-arg1',
            info: 'got call response for unknown id'
        };
    }
 
    // This could be because of a confused / corrupted server.
    self.logger.info('popOutReq received for unknown or lost id', {
        context: context,
        socketRemoteAddr: self.connection.socketRemoteAddr,
        direction: self.connection.direction
    });
};
 
Operations.prototype.popInReq = function popInReq(id) {
    var self = this;
 
    var req = self.requests.in[id];
    if (!req) {
        // TODO warn ?
        return null;
    }
 
    delete self.requests.in[id];
    self.pending.in--;
 
    return req;
};
 
Operations.prototype.removeReq = function removeReq(id) {
    var self = this;
 
    if (id in self.requests.in) {
        delete self.requests.in[id];
    } else Eif (id in self.requests.out) {
        delete self.requests.out[id];
    }
};
 
Operations.prototype.clear = function clear() {
    var self = this;
 
    self.pending.in = 0;
    self.pending.out = 0;
    self.tombstones.out = [];
};
 
Operations.prototype.destroy = function destroy() {
    var self = this;
 
    self.destroyed = true;
 
    if (self.timer) {
        self.timers.clearTimeout(self.timer);
        self.timer = null;
    }
};
 
// timeout check runs every timeoutCheckInterval +/- some random fuzz. Range is from
//   base - fuzz/2 to base + fuzz/2
Operations.prototype._getTimeoutDelay =
function _getTimeoutDelay() {
    var self = this;
 
    return self.timeoutCheckInterval + self._getTimeoutFuzz();
};
 
Operations.prototype._getTimeoutFuzz =
function _getTimeoutFuzz() {
    var self = this;
 
    var fuzz = self.timeoutFuzz;
    if (!fuzz) {
        return 0;
    }
 
    return Math.round(Math.floor(self.random() * fuzz)) - (fuzz / 2);
};
 
// 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.
Operations.prototype._onTimeoutCheck =
function _onTimeoutCheck() {
    var self = this;
    Iif (self.destroyed) {
        return;
    }
 
    var isInitialized = self.connection.remoteName;
    if (!isInitialized) {
        var elapsed = self.timers.now() - self.startTime;
        if (elapsed >= self.initTimeout) {
            self.connection.timedOutEvent
                .emit(self.connection, errors.ConnectionTimeoutError({
                    start: self.startTime,
                    elapsed: elapsed,
                    timeout: self.initTimeout
                }));
            return;
        }
    }
 
    self._checkTimeout(self.requests.out, 'out');
    self._checkTimeout(self.requests.in, 'in');
 
    var now = self.timers.now();
    var tombstones = [];
    for (var i = 0; i < self.tombstones.out.length; i++) {
        var tombstone = self.tombstones.out[i];
        if (now < (tombstone.time + tombstone.timeout)) {
            tombstones.push(tombstone);
        }
    }
    self.tombstones.out = tombstones;
 
    self.startTimeoutTimer();
};
 
Operations.prototype._checkTimeout =
function _checkTimeout(ops, direction) {
    var self = this;
    var opKeys = Object.keys(ops);
    for (var i = 0; i < opKeys.length; i++) {
        var id = opKeys[i];
        var op = ops[id];
        Iif (op === undefined) {
            self.logger.warn('unexpected undefined operation', {
                direction: direction,
                id: id
            });
        } else Iif (op.timedOut) {
            self.logger.warn('lingering timed-out operation', {
                direction: direction,
                id: id
            });
 
            if (direction === 'in') {
                self.popInReq(id);
            } else if (direction === 'out') {
                self.popOutReq(id);
            }
        } else if (op.checkTimeout()) {
            if (direction === 'out') {
                self.checkLastTimeoutTime(self.timers.now());
            }
            // else
            //     op.res.sendError // XXX may need to build
            if (direction === 'in') {
                self.popInReq(id);
            } else Eif (direction === 'out') {
                self.popOutReq(id);
            }
        }
    }
};