Code coverage report for node/states.js

Statements: 92.46% (184 / 199)      Branches: 86.11% (31 / 36)      Functions: 75% (30 / 40)      Lines: 92.46% (184 / 199)      Ignored: none     

All files » node/ » states.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                                            1 1   1   1 1 1 1 1   1 887   887   887   887 887 887     887     887     887       887                             1 898   898 898 898 898 898     1     1     1     1     1     1 1543     1 146   146 13       1 3772   3772 3772 3250   522       1 836 836   836 836 836 836   836   1   1 1128   1128 1128 1128     1 24   24 24 24       1 1137   1137 301 301     1137 1137     1 279   279 279     1 6871   6871 6871 6871 292 6579 9       1           1 818 818   818 818 818 818 818       1   1 1 1   1         1 5555   5555     5555     1 964   964           964   964       18           946 946       1 1204 1204 1204     1 113 113 113 113     1 88   88 88 88 82   6   88     1 18 18   18 18 18     1   1 1 1   1 164   164 164   164     146       1         1 690   690     690         690     1 146   146 146     1 57   57 57 6       1 89   89     1 3   3 3         3     1 62   62     1   1 1 1   1       1 263     1 1978   1978     1           1   1 1 1   1       1       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 format = require('util').format;
var inherits = require('util').inherits;
 
var errors = require('./errors');
 
module.exports.StateOptions = StateOptions;
module.exports.HealthyState = HealthyState;
module.exports.UnhealthyState = UnhealthyState;
module.exports.LockedHealthyState = LockedHealthyState;
module.exports.LockedUnhealthyState = LockedUnhealthyState;
 
function StateOptions(stateMachine, options) {
    options = options || {};
    // for setState changes
    this.stateMachine = stateMachine;
    // for downstream shouldRequest, used differently in Peer and Circuit.
    this.nextHandler = options.nextHandler;
    // for mocking tests
    this.timers = options.timers;
    this.timeHeap = options.timeHeap;
    this.random = options.random;
    // the number of miliseconds that healthy and unhealthy requests are
    // tracked between state reevaluation.
    this.period = options.period;
    // when healthy, the minimum number of requests during a period to trigger
    // state reevaluation.
    this.minimumRequests = options.minimumRequests;
    // when healthy, the failure rate for a period that will trigger a
    // transition to unhealthy.
    this.maxErrorRate = options.maxErrorRate;
    // when unhealthy, allow one request per period. this is the number of
    // consecutive periods that must have 100% healthy responses to trigger a
    // switch back to healthy.
    this.probation = options.probation;
}
 
/*
 * Collectively, the health states receive additional options through the peer
 * options:
 * - maxErrorRate (error rate to go from healthy to unhealthy)
 * - minResponseCount (response count to go from unhealthy to healthy)
 * - TODO
 *
 * They also inherit:
 * - channel.timers
 * - channel.random
 */
 
function State(options) {
    var self = this;
 
    self.stateMachine = options.stateMachine;
    self.nextHandler = options.nextHandler;
    self.timers = options.timers;
    self.timeHeap = options.timeHeap;
    self.random = options.random;
}
 
State.prototype.onDeactivate = function onDeactivate() {
};
 
State.prototype.onRequest = function onRequest(/* req */) {
};
 
State.prototype.onRequestHealthy = function onRequestHealthy() {
};
 
State.prototype.onRequestUnhealthy = function onRequestUnhealthy() {
};
 
State.prototype.onRequestError = function onRequestError(err) {
};
 
State.prototype.close = function close(callback) {
    callback(null);
};
 
State.prototype.invalidate = function invalidate() {
    var self = this;
 
    if (self.stateMachine.invalidateScore) {
        self.stateMachine.invalidateScore();
    }
};
 
State.prototype.shouldRequest = function shouldRequest(req, options) {
    var self = this;
 
    var now = self.timers.now();
    if (self.willCallNextHandler(now)) {
        return self.nextHandler.shouldRequest(req, options);
    } else {
        return 0;
    }
};
 
function PeriodicState(options) {
    var self = this;
    State.call(self, options);
 
    self.period = options.period || 1000; // ms
    self.start = 0;
    self.timeout = 0;
    self.periodTimer = null;
 
    self.startNewPeriod(self.timers.now());
}
inherits(PeriodicState, State);
 
PeriodicState.prototype.startNewPeriod = function startNewPeriod(now) {
    var self = this;
 
    self.start = now;
    self.setPeriodTimer(self.period, now);
    self.onNewPeriod();
};
 
PeriodicState.prototype.onDeactivate = function onDeactivate() {
    var self = this;
 
    Eif (self.periodTimer) {
        self.periodTimer.cancel();
        self.periodTimer = null;
    }
};
 
PeriodicState.prototype.setPeriodTimer = function setPeriodTimer(timeout, now) {
    var self = this;
 
    if (self.periodTimer) {
        self.periodTimer.cancel();
        self.periodTimer = null;
    }
 
    self.timeout = timeout;
    self.periodTimer = self.timeHeap.update(self, now);
};
 
PeriodicState.prototype.onTimeout = function onTimeout() {
    var self = this;
 
    var now = self.timers.now();
    self.checkPeriod(true, now);
};
 
PeriodicState.prototype.checkPeriod = function checkPeriod(inTimeout, now) {
    var self = this;
 
    var elapsed = now - self.start;
    var remain = self.period - elapsed;
    if (remain <= 0) {
        self.startNewPeriod(now);
    } else if (inTimeout) {
        self.setPeriodTimer(remain, now);
    }
};
 
PeriodicState.prototype.willCallNextHandler = function willCallNextHandler(now) {
    var self = this;
 
    self.checkPeriod(false, now);
};
 
function HealthyState(options) {
    var self = this;
    PeriodicState.call(self, options);
 
    self.maxErrorRate = options.maxErrorRate || 0.5;
    self.healthyCount = 0;
    self.unhealthyCount = 0;
    self.totalRequests = 0;
    self.minRequests = typeof options.minRequests === 'number' ?
        options.minRequests : 5;
}
 
inherits(HealthyState, PeriodicState);
 
HealthyState.prototype.type = 'tchannel.healthy';
HealthyState.prototype.healthy = true;
HealthyState.prototype.locked = false;
 
HealthyState.prototype.toString = function healthyToString() {
    var self = this;
    return format('[Healthy %s healthy %s unhealthy]', self.healthyCount, self.unhealthyCount);
};
 
HealthyState.prototype.willCallNextHandler = function willCallNextHandler(now) {
    var self = this;
 
    self.checkPeriod(false, now);
 
    // active unless .onNewPeriod transitioned
    return self.stateMachine.state === self;
};
 
HealthyState.prototype.onNewPeriod = function onNewPeriod(now) {
    var self = this;
 
    var totalCount = self.healthyCount + self.unhealthyCount;
 
    // TODO: could store on self for introspection, maybe call it
    // "lastPeriodErrorRate"?; we could even keep a fixed size sample of error
    // rates from periods and choose based on their differences (discrete
    // derivative)...
    var errorRate = self.unhealthyCount / totalCount;
 
    if (errorRate > self.maxErrorRate &&
        self.totalRequests > self.minRequests) {
        // Transition to unhealthy state if the healthy request rate dips below
        // the acceptable threshold.
        self.stateMachine.setState(UnhealthyState);
        // TODO: useful to mark self dead somehow? for now we're just using "am
        // I still the current state" logic coupled to the consuming
        // stateMachine in .willCallNextHandler
    } else {
        // okay last period, reset counts for the new period
        self.healthyCount = 0;
        self.unhealthyCount = 0;
    }
};
 
HealthyState.prototype.onRequestHealthy = function onRequestHealthy() {
    var self = this;
    self.healthyCount++;
    self.totalRequests++;
};
 
HealthyState.prototype.onRequestUnhealthy = function onRequestUnhealthy() {
    var self = this;
    self.totalRequests++;
    self.unhealthyCount++;
    self.checkPeriod(false, self.timers.now());
};
 
HealthyState.prototype.onRequestError = function onRequestError(err) {
    var self = this;
 
    self.totalRequests++;
    var codeString = errors.classify(err);
    if (errors.isUnhealthy(codeString)) {
        self.unhealthyCount++;
    } else {
        self.healthyCount++;
    }
    self.checkPeriod(false, self.timers.now());
};
 
function UnhealthyState(options) {
    var self = this;
    PeriodicState.call(self, options);
 
    self.minResponseCount = options.probation || 5;
    self.healthyCount = 0;
    self.triedThisPeriod = true;
}
 
inherits(UnhealthyState, PeriodicState);
 
UnhealthyState.prototype.type = 'tchannel.unhealthy';
UnhealthyState.prototype.healthy = false;
UnhealthyState.prototype.locked = false;
 
UnhealthyState.prototype.onNewPeriod = function onNewPeriod(now) {
    var self = this;
 
    var triedLastPeriod = self.triedThisPeriod;
    self.triedThisPeriod = false;
 
    if (triedLastPeriod) {
        // score only changes if we had gone back to "closed" state, otherwise
        // we simply are remaining "open" for a single probe
        self.invalidate();
    }
};
 
UnhealthyState.prototype.toString = function healthyToString() {
    var self = this;
    return format('[Unhealthy %s consecutive healthy requests]', self.healthyCount);
};
 
UnhealthyState.prototype.willCallNextHandler = function willCallNextHandler(now) {
    var self = this;
 
    self.checkPeriod(false, now);
 
    // if .checkPeriod transitioned us back to healthy, we're done
    Iif (self.stateMachine.state !== self) {
        return false;
    }
 
    // Allow one trial per period
    return !self.triedThisPeriod;
};
 
UnhealthyState.prototype.onRequest = function onRequest(/* req */) {
    var self = this;
 
    self.triedThisPeriod = true;
    self.checkPeriod(false, self.timers.now());
};
 
UnhealthyState.prototype.onRequestHealthy = function onRequestHealthy() {
    var self = this;
 
    self.healthyCount++;
    if (self.healthyCount > self.minResponseCount) {
        self.stateMachine.setState(HealthyState);
    }
};
 
UnhealthyState.prototype.onRequestUnhealthy = function onRequestUnhealthy() {
    var self = this;
 
    self.healthyCount = 0;
};
 
UnhealthyState.prototype.onRequestError = function onRequestError(err) {
    var self = this;
 
    var codeString = errors.classify(err);
    Iif (!errors.isUnhealthy(codeString)) {
        self.onRequestHealthy();
        return;
    }
 
    self.healthyCount = 0;
};
 
function LockedHealthyState(options) {
    var self = this;
 
    State.call(self, options);
}
 
inherits(LockedHealthyState, State);
 
LockedHealthyState.prototype.type = 'tchannel.healthy-locked';
LockedHealthyState.prototype.healthy = true;
LockedHealthyState.prototype.locked = true;
 
LockedHealthyState.prototype.toString = function lockedHealthyToString() {
    return '[Healthy state (locked)]';
};
 
LockedHealthyState.prototype.willCallNextHandler = function willCallNextHandler() {
    return true;
};
 
LockedHealthyState.prototype.shouldRequest = function shouldRequest(req, options) {
    var self = this;
 
    return self.nextHandler.shouldRequest(req, options);
};
 
function LockedUnhealthyState(options) {
    var self = this;
 
    State.call(self, options);
}
 
inherits(LockedUnhealthyState, State);
 
LockedUnhealthyState.prototype.type = 'tchannel.unhealthy-locked';
LockedUnhealthyState.prototype.healthy = false;
LockedUnhealthyState.prototype.locked = true;
 
LockedUnhealthyState.prototype.toString = function lockedUnhealthyToString() {
    return '[Unhealthy state (locked)]';
};
 
LockedUnhealthyState.prototype.willCallNextHandler = function willCallNextHandler() {
    return false;
};
 
LockedUnhealthyState.prototype.shouldRequest = function shouldRequest(req, options) {
    return 0;
};