Add io.throttle-in-rate-limit for socket event rate

This commit is contained in:
Calvin Montgomery 2018-07-25 21:07:07 -07:00
parent db2361aee9
commit 67b1c97d89
4 changed files with 44 additions and 4 deletions

View file

@ -223,6 +223,8 @@ class IOServer {
return;
}
this.setRateLimiter(socket);
emitMetrics(socket);
LOGGER.info('Accepted socket from %s', socket.context.ipAddress);
@ -240,6 +242,25 @@ class IOServer {
}
}
setRateLimiter(socket) {
const thunk = () => Config.get('io.throttle.in-rate-limit');
socket._inRateLimit = new TokenBucket(thunk, thunk);
socket.on('cytube:count-event', () => {
if (socket._inRateLimit.throttle()) {
LOGGER.warn(
'Kicking client %s: exceeded in-rate-limit of %d',
socket.context.ipAddress,
thunk()
);
socket.emit('kick', { reason: 'Rate limit exceeded' });
socket.disconnect();
}
});
}
initSocketIO() {
patchSocketMetrics();
patchTypecheckedFunctions();
@ -277,10 +298,12 @@ const outgoingPacketCount = new Counter({
function patchSocketMetrics() {
const onevent = Socket.prototype.onevent;
const packet = Socket.prototype.packet;
const emit = require('events').EventEmitter.prototype.emit;
Socket.prototype.onevent = function patchedOnevent() {
onevent.apply(this, arguments);
incomingEventCount.inc(1);
emit.call(this, 'cytube:count-event');
};
Socket.prototype.packet = function patchedPacket() {