Class TokenBucket
Token Bucket algorithm.
The token bucket algorithm can be used for controlling the usage rate
of a resource. The scope of that rate is determined by the underlying
storage.
Example:
use bandwidthThrottle\tokenBucket\Rate;
use bandwidthThrottle\tokenBucket\TokenBucket;
use bandwidthThrottle\tokenBucket\storage\FileStorage;
$storage = new FileStorage(__DIR__ . "/api.bucket");
$rate = new Rate(10, Rate::SECOND);
$bucket = new TokenBucket(10, $rate, $storage);
$bucket->bootstrap(10);
if (!$bucket->consume(1, $seconds)) {
http_response_code(429);
header(sprintf("Retry-After: %d", floor($seconds)));
exit();
}
Methods summary
public
|
|
public
|
#
bootstrap( integer $tokens = 0 )
Bootstraps the storage with an initial amount of tokens.
Bootstraps the storage with an initial amount of tokens.
If the storage was already bootstrapped this method returns silently.
While you could call bootstrap() on each request, you should not do that!
This method will do unnecessary storage communications just to see that
bootstrapping was performed already. You therefore should call that
method in your application's bootstrap or deploy process.
This method is threadsafe.
Parameters
- $tokens
- Initial amount of tokens, default is 0.
Throws
|
public
boolean
|
#
consume( integer $tokens, float & $seconds = 0 )
Consumes tokens from the bucket.
Consumes tokens from the bucket.
This method consumes only tokens if there are sufficient tokens available.
If there aren't sufficient tokens, no tokens will be removed and the
remaining seconds to wait are written to $seconds.
This method is threadsafe.
Parameters
- $tokens
- The token amount.
- $seconds
- $seconds The seconds to wait.
Returns
boolean If tokens were consumed.
Throws
Suppresswarnings(phpmd)
|
public
bandwidthThrottle\tokenBucket\Rate
|
#
getRate( )
Returns the token add rate.
Returns the token add rate.
Returns
|
public
integer
|
#
getCapacity( )
The token capacity of this bucket.
The token capacity of this bucket.
Returns
integer The capacity.
|
public
integer
|
#
getTokens( )
Returns the currently available tokens of this bucket.
Returns the currently available tokens of this bucket.
This is a purely informative method. Use this method if you are
interested in the amount of remaining tokens. Those tokens
could be consumed instantly. This method will not consume any token.
Use bandwidthThrottle\tokenBucket\TokenBucket::consume() to do so.
This method will never return more than the capacity of the bucket.
Returns
integer amount of currently available tokens
Throws
|