-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimit.js
executable file
·492 lines (431 loc) · 18.8 KB
/
ratelimit.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
ISC License
Copyright (c) 2023 cameo69
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
module.exports = function (RED) {
"use strict";
var _maxKeptMsgsCount;
const _statusUpdateMinTime = 100;
const _statusUpdateHoldTime = 1000;
function maxKeptMsgsCount(node) { //copied from delay node
if (_maxKeptMsgsCount === undefined) {
const name = "nodeMessageBufferMaxLength";
if (RED.settings.hasOwnProperty(name)) {
_maxKeptMsgsCount = RED.settings[name];
}
else {
_maxKeptMsgsCount = 0;
}
}
return _maxKeptMsgsCount;
}
function QueueLinked() { //based on code by Blindman67 https://codereview.stackexchange.com/questions/255698/queue-with-o1-enqueue-and-dequeue-with-js-arrays
var head, tail;
var l = 0;
return Object.freeze({
push(value) {
const link = {value, next: undefined, previous: undefined};
if (tail) link.previous = tail;
tail = head ? tail.next = link : head = link;
l++;
},
shift() {
if (head) {
const value = head.value;
head = head.next;
if (head) {
head.previous = undefined;
} else {
tail = undefined;
}
l--;
return value;
}
},
pop() {
if (tail) {
const value = tail.value;
tail = tail.previous;
if (tail) {
tail.next = undefined;
} else {
head = undefined;
}
l--;
return value;
}
},
peek() { return head?.value },
len() { return l },
isEmpty() { return (l === 0) },
removeFirstOccurrence(v) {
//let idx = 1;
if (head) {
if (head.value === v) {
head = head.next;
l--;
return true;
//return idx;
}
let lastHead = head;
let currentPos = head.next;
while (currentPos) {
//idx++;
if (currentPos.value === v) {
lastHead.next = currentPos.next;
if (currentPos === tail) {
tail = lastHead;
}
l--;
return true;
//return idx;
}
lastHead = currentPos;
currentPos = currentPos.next;
}
}
return false;
//return -1;
}
});
}
function RateLimitNode(config) {
const node = this;
RED.nodes.createNode(node, config);
// backward compatibility to v0.0.9 and earlier
if (typeof config.delay_action == "undefined") //idea repeat.js
{
config.delay_action = "ratelimit";
}
if (typeof config.drop_select == "undefined") {
config.drop_select = "emit";
}
// backward compatibility to v0.0.12 and earlier
if (typeof config.buffer_size == "undefined") //idea repeat.js
{
config.buffer_size = 0;
}
if (typeof config.emit_msg_2nd == "undefined")
{
config.emit_msg_2nd = false;
}
if (config.drop_select === "emit") {
config.drop_select = "drop";
config.emit_msg_2nd = true;
}
// backward compatibility to v0.0.13 and earlier
if (typeof config.control_topic == "undefined")
{
config.control_topic = "";
}
node.rateUnits = config.rateUnits;
if (config.rateUnits === "millisecond") {
node.nbRateUnits = config.nbRateUnits;
} else if (config.rateUnits === "minute") {
node.nbRateUnits = config.nbRateUnits * 60 * 1000;
} else if (config.rateUnits === "hour") {
node.nbRateUnits = config.nbRateUnits * 60 * 60 * 1000;
} else if (config.rateUnits === "day") {
node.nbRateUnits = config.nbRateUnits * 24 * 60 * 60 * 1000;
} else {
// Default to second
node.nbRateUnits = config.nbRateUnits * 1000;
}
node.rate = config.rate;
node.delay_action = config.delay_action;
node.drop_select = config.drop_select;
node.buffer_size = config.buffer_size;
node.buffer_drop_old = (config.buffer_drop === "buffer_drop_old");
node.outputs = config.outputs;
node.name = config.name;
node.emit_msg_2nd = config.emit_msg_2nd;
node.addcurrentcount = config.addcurrentcount;
node.msgcounter = 0;
node.buffer = QueueLinked();
node.timeoutLinkedIDs = QueueLinked();
node.org_rate = Object.freeze({"rate": node.rate, "nbRateUnits": node.nbRateUnits, "buffer_size": node.buffer_size});
node.useControlTopic = (typeof config.control_topic === "string" && config.control_topic !== "");
node.control_topic = config.control_topic;
node.isOpen = true;
node.canReportStatus = true;
node.canWarn = true;
if (node.delay_action === "ratelimit") {
node.on("input", function (msg, send, done) {
function addTimeout() {
function addTimeoutID(id) {
node.timeoutLinkedIDs.push(id);
}
(function() {
let tID = setTimeout(function () {
if ((node.msgcounter) > 0) {
node.msgcounter--;
updateStatus();
} else {
if (canWarn) {
canWarn = false;
setTimeout(() => {canWarn = true;},1000);
node.warn(`(node.msgcounter = ${node.msgcounter} <= 0) within callback of setTimeout. Check!`);
}
}
sendFromQueue();
node.timeoutLinkedIDs.removeFirstOccurrence(tID);
}, node.nbRateUnits);
addTimeoutID(tID);
})();
}
function sendFromQueue() {
while (node.isOpen && node.msgcounter < node.rate && !node.buffer.isEmpty()) {
const currentCounter = ++node.msgcounter;
const msgInfo = node.buffer.shift();
addCurrentCountToMsg(msgInfo.msg, currentCounter);
msgInfo.send(msgInfo.msg);
addTimeout();
msgInfo.done();
}
updateStatus();
}
function flushQueue() {
while (node.isOpen && !node.buffer.isEmpty()) {
const currentCounter = ++node.msgcounter;
const msgInfo = node.buffer.shift();
addCurrentCountToMsg(msgInfo.msg, currentCounter);
msgInfo.send(msgInfo.msg);
addTimeout();
msgInfo.done();
}
updateStatus();
}
function flushResetQueue() {
node.isOpen = false;
while (!node.buffer.isEmpty()) {
const currentCounter = ++node.msgcounter;
const msgInfo = node.buffer.shift();
addCurrentCountToMsg(msgInfo.msg, currentCounter);
msgInfo.send(msgInfo.msg);
//addTimeout();
//updateStatus();
msgInfo.done();
}
resetQueue();
}
function resetQueue() {
node.isOpen = false;
while(!node.timeoutLinkedIDs.isEmpty()) {
let id = node.timeoutLinkedIDs.shift();
clearTimeout(id);
}
while(!node.buffer.isEmpty()) {
node.buffer.shift().done();
}
node.msgcounter = 0;
node.rate = node.org_rate.rate;
node.nbRateUnits = node.org_rate.nbRateUnits;
node.buffer_size = node.org_rate.buffer_size;
//node.status({});
updateStatus();
node.isOpen = true;
}
function send_emit_msg_2nd(msg, send) {
addCurrentCountToMsg(msg, node.msgcounter);
send([null, msg]);
}
if (!node.isOpen) {
done();
return;
}
if (node.useControlTopic && typeof msg.topic === 'string' && msg.topic === node.control_topic) {
if (typeof msg.payload === 'string') {
if (msg.payload === "status") {
msg.payload = {
"buffer_len": node.buffer.len(),
"timeoutLinkedIDs_len": node.timeoutLinkedIDs.len()
};
if (node.outputs == 1) {
send(msg);
} else {
send([msg, null]);
}
} else if (msg.payload === "flush") {
flushQueue();
} else if (msg.payload === "flushreset") {
flushResetQueue();
} else if (msg.payload === "reset") {
resetQueue();
}
}
if (typeof msg.payload === "object") {
function isPositiveInteger(n) {
return 0 === n % (!isNaN(parseFloat(n)) && 0 <= ~~n);
}
if ((typeof msg.payload.rate === "number") && isPositiveInteger(msg.payload.rate) && (msg.payload.rate > 0)) {
node.rate = msg.payload.rate;
}
if ((typeof msg.payload.time === "number") && isPositiveInteger(msg.payload.time) && (msg.payload.time > 0)) {
node.nbRateUnits = msg.payload.time;
}
if ((typeof msg.payload.queue === "number") && isPositiveInteger(msg.payload.queue)) {
node.buffer_size = msg.payload.queue;
if (true || node.drop_select === "queue") {
while (node.buffer_size > 0 && node.buffer.len() > node.buffer_size) {
if (node.emit_msg_2nd) {
let oldmsg;
if (node.buffer_drop_old) {
oldmsg = node.buffer.shift();
} else {
oldmsg = node.buffer.pop();
}
send_emit_msg_2nd(oldmsg.msg, oldmsg.send);
oldmsg.done();
} else {
if (node.buffer_drop_old) {
node.buffer.shift().done();
} else {
node.buffer.pop().done();
}
}
}
}
}
}
done();
return;
}
if (node.msgcounter < node.rate) {
const currentCounter = ++node.msgcounter;
addCurrentCountToMsg(msg, currentCounter);
if (node.outputs == 1) {
send(msg);
} else {
send([msg, null]);
}
addTimeout();
updateStatus();
done();
//} else if (node.drop_select === "drop") {
// done();
} else if (node.drop_select === "queue") {
if (node.buffer_size > 0 && node.buffer.len() >= node.buffer_size) {
if (node.buffer_drop_old) {
let oldmsg = node.buffer.shift();
if (node.emit_msg_2nd) {
send_emit_msg_2nd(oldmsg.msg, oldmsg.send);
}
oldmsg.done();
const m = RED.util.cloneMessage(msg);
node.buffer.push({ msg: m, send: send, done: done });
} else {
if (node.emit_msg_2nd) {
send_emit_msg_2nd(msg, send);
}
//updateStatus();
done();
}
} else {
const m = RED.util.cloneMessage(msg);
node.buffer.push({ msg: m, send: send, done: done });
}
updateStatus();
} else {
//default case before v0.0.10 if (node.drop_select === "emit") {
//and as of v0.0.13 "emit" will be "drop" + emit_msg_2nd
if (node.emit_msg_2nd) {
send_emit_msg_2nd(msg, send);
}
//updateStatus();
done();
}
});
node.on('close', function(removed, done) {
node.isOpen = false;
while(!node.timeoutLinkedIDs.isEmpty()) {
let id = node.timeoutLinkedIDs.shift();
clearTimeout(id);
//node.timeoutLinkedIDs.shift()
}
while(!node.buffer.isEmpty()) {
node.buffer.shift().done();
}
node.msgcounter = 0;
node.status({});
done();
});
} else {
//not defined, you should not get here, never!
done(Error("node.delay_action is not defined"));
}
function updateStatus(str) {
function setStatusTimeOut(exec) {
node.canReportStatus = false;
clearTimeout(node.finalStatusID);
exec(false);
setTimeout(() => {
if (node.statusNeedsUpdate) {
setStatusTimeOut(exec);
} else {
node.canReportStatus = true;
}
}, _statusUpdateMinTime);
node.finalStatusID = setTimeout(() => {
exec(true);
}, _statusUpdateHoldTime);
}
const doStatusUpdate = function (isFinal) {
node.statusNeedsUpdate = false;
let color = "green";
let currentCount = node.msgcounter;
const bufLength = node.buffer.len();
if (bufLength > 0 || currentCount > 0 || !isFinal) {
if (bufLength === 0) {
if (currentCount >= node.rate) {
color = "blue";
}
} else {
color = "red";
if (!isFinal && currentCount === node.rate - 1) {
currentCount = node.rate;
}
}
let txt = currentCount + " sent in timeframe";
if (bufLength) txt += ", " + bufLength + " queued";
//if (str) txt += ", " + str;
node.status({ fill: color, shape: "ring", text: txt });
//node.status({ fill: color, shape: "ring", text: `${txt} - ${node.timeoutLinkedIDs.len()}` });
} else {
//node.status({ fill: color, shape: "dot", text: "" });
node.status({});
}
}
if (!node.canReportStatus) {
node.statusNeedsUpdate = true;
return;
}
setStatusTimeOut(doStatusUpdate);
}
function addCurrentCountToMsg(msg, currentMsgCounter) {
if (node.addcurrentcount) {
msg.CurrentCount = currentMsgCounter;
}
}
}
RED.nodes.registerType("rate-limiter", RateLimitNode);
};
/*
- possibility to control via command 'control'? --> reset, flush, trigger, status...)
- persistence after restart node red?
- blocking gate (stores all/parts (for given time period?) and only releases after certain time -> flush or rate)
- threshold gate (like blocking gate, but releases when certain amount per time (rate) is reached, else drop/2nd)
- burst generation mode
done
- better implementation of queue (suited for high speeds)
- possibility to control via command 'control'? --> reset, flush, trigger, status...)
*/