Code coverage report for node/operations.js

Statements: 84.77% (128 / 151)      Branches: 60.87% (28 / 46)      Functions: 100% (19 / 19)      Lines: 84.77% (128 / 151)      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                                            1   1   1   1 723   723 723 723 723 723 723 723   723 723 723 723   723     723       723       723     1 825   825 825 825     1   1446   1446       1 723       1 716   716     1 5552   5552     1 1768   1768     1 791   791     1 842   842 842   842     1 830   830 830   830     1 825   825 825                                                 825   825 825     825     825   825     1 833   833 833   8     825 825   825     1 20   20 5 15 15       1 716   716 716 716     1 1378   1378   1378 723 723           1   1446   1446     1   2271   2271 2271 30     2241         1   723 723       723 723                         723 723   723 723 3211 3211 239 239       723     1   1446 1446 1446 83 83 83         83                     83 14 7 7               7 6           14 7 7 7          
// 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: {},
        out: {}
    };
    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];
    Iif (!req) {
        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
        if (isStale) {
            return null;
        }
 
        // 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
        });
        return null;
    }
 
    delete self.requests.out[id];
 
    var now = self.timers.now();
    var timeout = now + TOMBSTONE_TTL_OFFSET + req.ttl +
        self._getTimeoutFuzz();
 
    self.tombstones.out.push(new OperationTombstone(
        req.id, self.timers.now(), timeout
    ));
    self.pending.out--;
 
    return req;
};
 
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;
    Iif (!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();
    for (var i = 0; i < self.tombstones.out.length; i++) {
        var tombstone = self.tombstones.out[i];
        if (now >= tombstone.timeout) {
            self.tombstones.out.splice(i, 1);
            i--;
        }
    }
 
    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);
            }
        }
    }
};