razonyang/psr-rate-limiter

PSR-15 Rate Limiter Middleware

1.0.0 2019-08-21 04:39 UTC

This package is auto-updated.

Last update: 2024-11-13 10:00:25 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version Total Downloads LICENSE

It was built on top of Token Bucket.

Installation

composer require razonyang/psr-rate-limiter

Usage

Let's take 5000 requests every hours as example:

// creates a token bucket manager, redis or memcached(built-in)
$capacity = 5000; // each bucket capacity, in other words, maximum number of tokens.
$rate = 0.72; // 3600/5200, how offen the token will be added to bucket
$logger = new \Psr\Log\NullLogger(); // PSR logger
$ttl = 3600; // time to live.
$prefix = 'rateLimiter:'; // prefix.
$manager = new \RazonYang\TokenBucket\Manager\RedisManager($capacity, $rate, $logger, $redis, $ttl, $prefix);

// PSR HTTP response factory
$responseFactory = new \Nyholm\Psr7\Factory\Psr17Factory();

// bucket name callback, let's we treat ip:path as bucket name here
$nameCallback = function (\Psr\Http\Message\ServerRequestInterface $request): string {
    $parameters = $request->getServerParams();
    $path = '';
    $ipKeys = ['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
    foreach ($ipKeys as $key) {
        if (!empty($parameters[$key])) {
            return $parameters[$key] . ':' . $request->getUri()->getPath();
        }
    }

    // rate limiting will be skipped when an empty bucket name returned
    return '';
};

$rateLimiter = new \RazonYang\Psr\RateLimiter\Middleware($manager, $responseFactory, $nameCallback);