Code coverage report for node/hyperbahn/rate_limiting.js

Statements: 98.98% (97 / 98)      Branches: 97.37% (37 / 38)      Functions: 100% (10 / 10)      Lines: 98.98% (97 / 98)      Ignored: none     

All files » node/hyperbahn/ » rate_limiting.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                                            1   1 1 1 1   1 66     66   66 66 66 66   66 66 66 66 66 66 66 66   66     1   1   2257     2257 2257 3985 3985 3985 3985   1181   3985 3985 3985 3985   1983   2002 2002     2257   2191           1   2 2     1   1113   1113 1113 15     1098     1   64   64 64 64 64 64 64 64 32   32 32     64     1   2222   2222 2222 64 64     2222 2222     1   2222   2222 2222 2222     1   1183 1183   1183 69       1114 1114 1114 1 1       1113 5     1108 1108 1108 1 1     1107     1   66 66     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 assert = require('assert');
 
var DEFAULT_SERVICE_QPS_LIMIT = 500;
var DEFAULT_TOTAL_QPS_LIMIT = 1000;
var DEFAULT_BUCKETS = 20;
var TOTAL_QPS = '~~TotalQPS++';
 
function RateLimiting(options) {
    Iif (!(this instanceof RateLimiting)) {
        return new RateLimiting(options);
    }
    var self = this;
 
    assert(options.serviceDispatchHandler, 'serviceDispatchHandler is required for RateLimiting');
    self.serviceDispatchHandler = options.serviceDispatchHandler;
    self.egressNodes = options.serviceDispatchHandler.egressNodes;
    self.timers = self.serviceDispatchHandler.channel.timers;
 
    self.qpsLimits = options.qpsLimits || Object.create(null);
    self.counters = Object.create(null);
    self.buckets = options.buckets || DEFAULT_BUCKETS;
    assert(self.buckets > 0 && self.buckets <= 1000, 'counter buckets should between (0 1000]');
    self.refreshDelay = 1000 / self.buckets;
    self.defaultServiceQpsLimit = options.defaultServiceQpsLimit || DEFAULT_SERVICE_QPS_LIMIT;
    self.totalQpsLimit = options.totalQpsLimit || DEFAULT_TOTAL_QPS_LIMIT;
    self.buckets = options.buckets || DEFAULT_BUCKETS;
 
    self.refresh();
}
 
RateLimiting.prototype.type = 'tchannel.hyperbahn.rate-limiting';
 
RateLimiting.prototype.refresh =
function refresh() {
    var self = this;
 
    // update hte sliding window
    var services = Object.keys(self.counters);
    for (var i = 0; i < services.length; i++) {
        var serviceName = services[i];
        var counter = self.counters[serviceName];
        var next = (counter.index + 1) % self.buckets;
        if (counter.buckets[next]) {
            // offset the bucket being moved out
            counter.qps -= counter.buckets[next];
        }
        assert(counter.qps >= 0, 'qps shouls always be larger equal to 0');
        counter.index = next;
        counter.buckets[counter.index] = 0;
        if (serviceName === TOTAL_QPS) {
            // total QPS limit never change
            continue;
        }
        var limit = self.qpsLimits[serviceName] || self.defaultServiceQpsLimit;
        counter.qpsLimit = limit / self.egressNodes.kValueFor(serviceName);
    }
 
    self.refreshTimer = self.timers.setTimeout(
        function refresh() {
            self.refresh();
        },
        self.refreshDelay
    );
};
 
RateLimiting.prototype.removeCounter =
function removeCounter(serviceName) {
    var self = this;
    delete self.counters[serviceName];
};
 
RateLimiting.prototype.isExitFor =
function isExitFor(serviceName) {
    var self = this;
 
    var chan = self.serviceDispatchHandler.channel.subChannels[serviceName];
    if (!chan) {
        return self.egressNodes.isExitFor(serviceName);
    }
 
    return chan.serviceProxyMode === 'exit';
};
 
RateLimiting.prototype.createCounter =
function createCounter(serviceName) {
    var self = this;
 
    var counter = Object.create(null);
    counter.index = 0;
    counter.qps = 0;
    counter.buckets = [];
    counter.buckets.length = self.buckets;
    counter.buckets[0] = 0;
    if (serviceName === TOTAL_QPS) {
        counter.qpsLimit = self.totalQpsLimit;
    } else {
        var limit = self.qpsLimits[serviceName] || self.defaultServiceQpsLimit;
        counter.qpsLimit = limit / self.egressNodes.kValueFor(serviceName);
    }
 
    return counter;
};
 
RateLimiting.prototype.incrementCounter =
function incrementCounter(serviceName) {
    var self = this;
 
    var counter = self.counters[serviceName];
    if (!counter) {
        counter = self.createCounter(serviceName);
        self.counters[serviceName] = counter;
    }
 
    counter.buckets[counter.index] += 1;
    counter.qps += 1;
};
 
RateLimiting.prototype.shouldRateLimit =
function shouldRateLimit(serviceName) {
    var self = this;
 
    var counter = self.counters[serviceName];
    assert(counter, 'cannot find counter for ' + serviceName);
    return counter.qps <= counter.qpsLimit ? 0 : counter.qpsLimit;
};
 
RateLimiting.prototype.handleRequest =
function handleRequest(req, buildRes) {
    var self = this;
    assert(req.serviceName, 'serviceName should not be empty for rate limiting.');
 
    if (req.serviceName === 'hyperbahn') {
        return false;
    }
 
    // check total QPS
    self.incrementCounter(TOTAL_QPS);
    var limit = self.shouldRateLimit(TOTAL_QPS);
    if (limit) {
        buildRes().sendError('Busy', 'hyperbahn node is rate limited by the total rate ' + limit + ' qps');
        return true;
    }
 
    // check QPS for serviceName
    if (!self.isExitFor(req.serviceName)) {
        return false;
    }
 
    self.incrementCounter(req.serviceName);
    limit = self.shouldRateLimit(req.serviceName);
    if (limit) {
        buildRes().sendError('Busy', req.serviceName + ' is rate limited by ' + limit + ' qps');
        return true;
    }
 
    return false;
};
 
RateLimiting.prototype.destroy =
function destroy() {
    var self = this;
    self.timers.clearTimeout(self.refreshTimer);
};
 
module.exports = RateLimiting;