Name: spife-ratelimit
Owner: npm
Description: :alarm_clock: :no_entry_sign: ratelimit spife apps with token buckets!
Created: 2017-08-25 23:15:49.0
Updated: 2018-04-24 01:21:50.0
Pushed: 2018-03-12 16:41:05.0
Size: 59
Language: JavaScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
Middleware that adds Token Bucket-style ratelimiting to Spife.
ettings.js:
le.exports.MIDDLEWARE = {
@npm/spife-ratelimiting', {
redisUrl: 'redis://localhost:6379', // let it connect to redis
redisClient, // (or give it a client)
costHeader: 'npm-cost', // the "cost" header to use
// for determining how many
// tokens a request took
clock: Date.now, // if you would like time to
// move to the beat of a
// different drum
getBucket (spifeRequest) { // given a request, return
// an object describing its
// token bucket
return {
capacity: 100, // how many tokens does
// the bucket hold?
interval: 60, // in minutes, how long
// does the bucket take to
// fill up?
key: String // what should the bucket be
// named?
}
}
iews.js:
t reply = require('@npm/spife/reply')
t cost = require('@npm/spife-ratelimiter/decorator')
le.exports = {
a view can declare how much it costs up-front:
dex: cost(index, 5),
her
tion index (req, context) {
turn 'I cost five tokens!'
tion other (req, context) {
turn reply.header(
'I cost a hundred tokens sometimes',
'npm-cost',
Math.random() > 0.5 ? 100 : 0
This is implemented in redis by keeping two keys per bucket: one that
tracks the current number of tokens, and one that tracks the last update
time. Both keys are expired at interval
, and updated atomically using a
Lua script.