-
Notifications
You must be signed in to change notification settings - Fork 47
/
PredisRateLimiter.php
81 lines (62 loc) · 1.92 KB
/
PredisRateLimiter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
declare(strict_types=1);
namespace RateLimit;
use Predis\ClientInterface;
use RateLimit\Exception\LimitExceeded;
use function ceil;
use function max;
use function time;
final class PredisRateLimiter extends ConfigurableRateLimiter implements RateLimiter, SilentRateLimiter
{
private ClientInterface $predis;
private string $keyPrefix;
public function __construct(Rate $rate, ClientInterface $predis, string $keyPrefix = '')
{
parent::__construct($rate);
$this->predis = $predis;
$this->keyPrefix = $keyPrefix;
}
public function limit(string $identifier): void
{
$key = $this->key($identifier);
$current = $this->getCurrent($key);
if ($current >= $this->rate->getOperations()) {
throw LimitExceeded::for($identifier, $this->rate);
}
$this->updateCounter($key);
}
public function limitSilently(string $identifier): Status
{
$key = $this->key($identifier);
$current = $this->getCurrent($key);
if ($current <= $this->rate->getOperations()) {
$current = $this->updateCounter($key);
}
return Status::from(
$identifier,
$current,
$this->rate->getOperations(),
time() + $this->ttl($key)
);
}
private function key(string $identifier): string
{
return "{$this->keyPrefix}{$identifier}:{$this->rate->getInterval()}";
}
private function getCurrent(string $key): int
{
return (int) $this->predis->get($key);
}
private function updateCounter(string $key): int
{
$current = $this->predis->incr($key);
if ($current === 1) {
$this->predis->expire($key, $this->rate->getInterval());
}
return $current;
}
private function ttl(string $key): int
{
return max((int) ceil($this->predis->pttl($key) / 1000), 0);
}
}