Skip to content
This repository has been archived by the owner on Nov 10, 2022. It is now read-only.

Commit

Permalink
fix: add a rate limiter (2 updates per second)
Browse files Browse the repository at this point in the history
  • Loading branch information
severo committed Jan 17, 2020
1 parent 95bef62 commit db39e75
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 7 deletions.
32 changes: 25 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@ const http = require('http').Server(app)
const io = require('socket.io')(http)
const port = process.env.PORT || 3000
const rnd = require('randomcolor')
const { RateLimiterMemory } = require('rate-limiter-flexible')

// TODO: add a public page that redirects to the GitHub repository
// app.use(express.static(__dirname + '/public'))

const rateLimiter = new RateLimiterMemory({
points: 2, // 5 points
duration: 1, // per second
})

const chat = io.on('connection', socket => {
socket.on('chat', data => {
// console.log(`Message received: ${data}`)
Expand Down Expand Up @@ -40,14 +46,26 @@ const onUpdateGuest = socket => (guest, ack) => {
// For now, there is no difference with onNewGuest
onNewGuest(socket)(guest, ack)
}
const onUpdateUrlQuerySpec = socket => (newUrlQuerySpec, ack) => {
const onUpdateUrlQuerySpec = socket => async (newUrlQuerySpec, ack) => {
console.log('new urlQuerySpec')
const guest = guests.get(socket.id)
if (guest !== undefined) {
touch(guest)
urlQuerySpec = newUrlQuerySpec
socket.broadcast.emit('urlqueryspec', urlQuerySpec)
ack(urlQuerySpec)
try {
await rateLimiter.consume(socket.id) // consume 1 point per event from IP
const guest = guests.get(socket.id)
if (guest !== undefined) {
touch(guest)
if (urlQuerySpec !== newUrlQuerySpec) {
// ?
urlQuerySpec = newUrlQuerySpec
socket.broadcast.emit('urlqueryspec', urlQuerySpec)
}
ack(urlQuerySpec)
}
console.log('OK')
} catch (rejRes) {
// no available points to consume
// emit error or warning message
socket.emit('blocked', { 'retry-ms': rejRes.msBeforeNext })
console.log('Blocked')
}
}
const onByeBye = socket => _ => {
Expand Down
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"dependencies": {
"express": "^4.17.1",
"randomcolor": "^0.5.4",
"rate-limiter-flexible": "^1.3.0",
"socket.io": "^2.3.0"
},
"engines": {
Expand Down

0 comments on commit db39e75

Please sign in to comment.