Coder Social home page Coder Social logo

ioredis-quota's Introduction

Build Status NPM Version Dependency Status

ioredis-quota

General-purpose quota management.

This NPM package is a simple quota manager with a simple, promisified API. It's open-source and it's written with TypeScript.

The source code is available on GitHub where you can also find our issue tracker.

Install

The package depends on ioredis but it should also work with any other Redis library that supports promises.

$ npm install --save ioredis ioredis-quota

Getting Started

To make the code clean, the examples are written in TypeScript.

You start by some initialization code.

import Redis from "ioredis";
import { Quota } from "ioredis-quota";

const quota = new Quota({
  redis: new Redis(),
  rates: [
    { key: "github-api", unit: "minute", limit: 10 }, // Allow up to 10 requests per minute.
    { key: "github-api", unit: "hour", limit: 100 },  // Allow up to 100 requests per hour.
  ]
});

Use the grant() method to verify that the request you are making does not exceed the rate limit.

try {
  await quota.grant(); // Grant 10 requests per minute and 100 requests per hour.
  // We have not exceeded the minutely nor daily quota so we can execute a request.
} catch (e) {
  // We reached the limits. Use `e.nextDate` to handle a retry.
}

Or use the schedule() method which uses the grant() method and returns the next appropriate date for execution (e.nextDate) instead of throwing an error.

const nextDate = await quota.schedule(); // => Sat Jun 17 14:58:57 CEST 2017

API

Quota({ redis, prefix, rates })

A core class which is used for checking quota.

Option Type Required Default Description
redis Object Yes - Redis class instance.
prefix String No quota A string which prefix all the keys.
rates Object[] No [] List of quota definitions.
rates.key String Yes - Quota unique name.
rates.unit String Yes - Quota unit (second, minute, hour, day, week, month, quarter or year).
rates.limit Integer Yes - The maximum value of the increment.

QuotaError(nextDate, message)

Quota error class which is thrown when the grant method does not succeed.

Option Type Required Default Description
nextDate Date Yes - A moment when quota is reset.
message String No Quota limit exceeded. Error message.

quota.buildIdentifier({ key, unit }): String

Builds and returns the final Redis key.

Option Type Required Default Description
key String Yes - Quota key name.
unit String Yes - Quota unit (second, minute, hour, day, week, month, quarter or year).

quota.flush([{ key, unit }]): Promise

Atomically removes quota. Note that if no attributes are specified then all identifiers are deleted.

Option Type Required Default Description
key String Yes - Quota key name.
unit String Yes - Quota unit (second, minute, hour, day, week, month, quarter or year).

quota.grant(rates): Promise

Atomically verifies quota for each rate and throws the QuotaError if the rate's value exceeds the specified limit attribute. Please note that this method will increment the counter for each defined rate by one per unit (if you specify two rate objects with the same unit this means that this unit will be incremented by 2).

Option Type Required Default Description
rates Object, Object[] No [] List of quota definitions (appends class rates).
rates.key String Yes - Quota unique name.
rates.unit String Yes - Quota unit (second, minute, hour, day, week, month, quarter or year).
rates.limit Integer Yes - The maximum value of the increment.

quota.parseIdentifier(identifier): String

Parses the identifier string and returns key's data (prefix, timestamp and key).

Option Type Required Default Description
identifier String Yes - Redis key.

quota.schedule(rates): Promise

Atomically verifies quota for each rate and returns the next available date.

Option Type Required Default Description
rates Object, Object[] No [] List of quota definitions (appends class rates).
rates.key String Yes - Quota unique name.
rates.unit String Yes - Quota unit (second, minute, hour, day, week, month, quarter or year).
rates.limit Integer Yes - The maximum value of the increment.

License (MIT)

Copyright (c) 2016 Kristijan Sedlak <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

ioredis-quota's People

Contributors

xpepermint avatar

Stargazers

mathieu duval avatar  avatar Federico Feroldi avatar Tadej Stanic avatar  avatar Mike Diarmid avatar Zihua Li avatar  avatar

Watchers

 avatar  avatar

ioredis-quota's Issues

Rate's value is 0 at the very first request

I try to use this package as an API rate limiter, which should prevent brute-force attacks on selected endpoints.

I made an express middleware function like this:

export default function (redisClient: Redis) {
  const quota = new Quota({
    redis: redisClient,
    prefix: 'quota:'
  })
  return async function (req, res, next) {
    try {
      await quota.grant([
        {
          key: req.ip,
          unit: 'second',
          limit: appConfig.requestRateLimitSecond
        },
        {
          key: req.ip,
          unit: 'minute',
          limit: appConfig.requestRateLimitMinute
        }
      ])
      next()
    } catch (e) {
      res.send(JSON.stringify({errors: e}))
    }
  }
}

When the very first request is made I can see that both keys are created with value 0, so the request is refused. But if I have just one rule (i.e. per minute), then the key's value is 1 and everything works as expected.

Is this a bug or it's something that I don't understand about the rules concept?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.