Skip to content

Commit 8ba1edc

Browse files
authored
An example for Rate limit (#566)
* add rate limit example * better comment * add newline at end of file
1 parent 973db44 commit 8ba1edc

1 file changed

Lines changed: 69 additions & 0 deletions

File tree

‎examples/RateLimit.js‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/* RateLimit example */
2+
3+
const uWS = require('../dist/uws.js');
4+
const port = 9001;
5+
6+
const RateLimit = (limit, interval) => { let now = 0; const last = Symbol(), count = Symbol(); setInterval(() => ++now, interval); return ws => { if (ws[last] != now) { ws[last] = now; ws[count] = 1 } else { return ++ws[count] > limit } } }
7+
const rateLimit = RateLimit(1, 10000) // limit is: 1 message per 10 seconds.
8+
const rateLimit2 = RateLimit(10, 2000) // limit per interval (milliseconds)
9+
10+
11+
const app = uWS./*SSL*/App({
12+
key_file_name: 'misc/key.pem',
13+
cert_file_name: 'misc/cert.pem',
14+
passphrase: '1234'
15+
}).ws('/*', {
16+
/* Options */
17+
compression: uWS.SHARED_COMPRESSOR,
18+
maxPayloadLength: 16 * 1024 * 1024,
19+
idleTimeout: 10,
20+
/* Handlers */
21+
open: (ws) => {
22+
console.log('A WebSocket connected!');
23+
},
24+
message: async (ws, message, isBinary) => {
25+
26+
// rateLimit(ws) returns true if over limit
27+
if (rateLimit(ws)) {
28+
/*
29+
Do as you wish, personally, I prefer to inform the client, do Log,
30+
and close the connection if over limit happened.
31+
or you can just ignore its message and just return.
32+
*/
33+
const dataToSendToClient = {
34+
action: 'info',
35+
data: {
36+
message: {
37+
english: 'over limit! please slow down.',
38+
farsi: 'یواش‌تر'
39+
}
40+
}
41+
}
42+
await ws.send(JSON.stringify(dataToSendToClient));
43+
console.warn('rate limit hit!');
44+
return ws.end();
45+
}
46+
47+
//or maybe different type of message or /endpoint needs different limit
48+
if (ws.type2 && rateLimit2(ws)) {
49+
console.warn('type2 is over limit');
50+
return ws.end();
51+
}
52+
53+
// rest of message code goes here ...
54+
},
55+
drain: (ws) => {
56+
console.log('WebSocket backpressure: ' + ws.getBufferedAmount());
57+
},
58+
close: (ws, code, message) => {
59+
console.log('WebSocket closed');
60+
}
61+
}).any('/*', (res, req) => {
62+
res.end('Nothing to see here!');
63+
}).listen(port, (token) => {
64+
if (token) {
65+
console.log('Listening to port ' + port);
66+
} else {
67+
console.log('Failed to listen to port ' + port);
68+
}
69+
});

0 commit comments

Comments
 (0)