Code coverage report for node/operations.js

Statements: 89.94% (143 / 159)      Branches: 62.5% (35 / 56)      Functions: 95% (19 / 20)      Lines: 89.94% (143 / 159)      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 340 341 342                                            1   1   1   1 1016   1016 1016 1016 1016 1016 1016 1016   1016 1016 1016 1016   1016     1016       1016       1016     1 2501   2501 2501 2501     1   6158   6158       1 5143       1 1003   1003     1 7528   7528     1 3829   3829     1           1 2524   2524 2524   2524     1 2507   2507 2507   2507     1 2514   2514 2514 13 13     2501   2501 2501     2501     2501   2501     1   13   13 13   13 92 13 13         13 13                                                       1 2534   2534 2534   33     2501 2501   2501     1 27   27 6 21 21       1 1003   1003 1003 1003     1 1949   1949   1949 1016 1016           1   6158   6158     1   8659   8659 8659 30     8629         1   5143 5143       5143 5143 3 3 1           1       5142 5142   5142 5142 5142 12466 12466 11173     5142   5142     1   10284 10284 10284 163 163 163         163                     163 41 20 20               20 19           41 21 20 20          
// 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(id, time, timeout) {
    var self = this;
 
    self.id = id;
    self.time = time;
    self.timeout = timeout;
}
 
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;
 
    self.requests.out[req.id] = req;
    self.pending.out++;
 
    return req;
};
 
Operations.prototype.addInReq = function addInReq(req) {
    var self = this;
 
    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) {
        self.logMissingOutRequest(id, context);
        return null;
    }
 
    delete self.requests.out[id];
 
    var now = self.timers.now();
    var timeout = now + TOMBSTONE_TTL_OFFSET + req.timeout +
        self._getTimeoutFuzz();
 
    self.tombstones.out.push(new OperationTombstone(
        req.id, self.timers.now(), timeout
    ));
    self.pending.out--;
 
    return req;
};
 
Operations.prototype.logMissingOutRequest =
function logMissingOutRequest(id, context) {
    var self = this;
 
    var tombstones = self.tombstones.out;
    var isStale = false;
 
    for (var i = 0; i < tombstones.length; i++) {
        if (tombstones[i].id === id) {
            isStale = true;
            break;
        }
    }
 
    // If this id has been timed out then just return
    Eif (isStale) {
        return null;
    }
 
    // 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, 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.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 req = ops[id];
        Iif (req === undefined) {
            self.logger.warn('unexpected undefined request', {
                direction: direction,
                id: id
            });
        } else Iif (req.timedOut) {
            self.logger.warn('lingering timed-out request', {
                direction: direction,
                id: id
            });
 
            if (direction === 'in') {
                self.popInReq(id);
            } else if (direction === 'out') {
                self.popOutReq(id);
            }
        } else if (req.checkTimeout()) {
            if (direction === 'out') {
                var now = self.timers.now();
                Iif (self.lastTimeoutTime &&
                    now > self.lastTimeoutTime + self.connectionStalePeriod
                ) {
                    var err = errors.ConnectionStaleTimeoutError({
                        lastTimeoutTime: self.lastTimeoutTime
                    });
                    self.connection.timedOutEvent
                        .emit(self, err);
                } else if (!self.lastTimeoutTime) {
                    self.lastTimeoutTime = self.timers.now();
                }
                
            }
            // else
            //     req.res.sendError // XXX may need to build
            if (direction === 'in') {
                self.popInReq(id);
            } else Eif (direction === 'out') {
                self.popOutReq(id);
            }
        }
    }
};