|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace RateLimit; |
|
6
|
|
|
|
|
7
|
|
|
use RateLimit\Exception\LimitExceeded; |
|
8
|
|
|
|
|
9
|
|
|
abstract class AbstractElapsedTimeRateLimiter implements RateLimiter, SilentRateLimiter |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var string |
|
13
|
|
|
*/ |
|
14
|
|
|
private $keyPrefix; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct(string $keyPrefix = '') |
|
17
|
|
|
{ |
|
18
|
|
|
$this->keyPrefix = $keyPrefix; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
final public function limit(string $identifier, Rate $rate): void |
|
22
|
|
|
{ |
|
23
|
|
|
$interval = $rate->getInterval(); |
|
24
|
|
|
$valueKey = $this->valueKey($identifier, $interval); |
|
25
|
|
|
$timeKey = $this->timeKey($identifier, $interval); |
|
26
|
|
|
|
|
27
|
|
|
$current = $this->getCurrent($valueKey); |
|
28
|
|
|
if ($current >= $rate->getOperations()) { |
|
29
|
|
|
throw LimitExceeded::for($identifier, $rate); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
$this->updateCounter($valueKey, $timeKey, $rate->getInterval()); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
final public function limitSilently(string $identifier, Rate $rate): Status |
|
36
|
|
|
{ |
|
37
|
|
|
$interval = $rate->getInterval(); |
|
38
|
|
|
$valueKey = $this->valueKey($identifier, $interval); |
|
39
|
|
|
$timeKey = $this->timeKey($identifier, $interval); |
|
40
|
|
|
|
|
41
|
|
|
$current = $this->getCurrent($valueKey); |
|
42
|
|
|
if ($current <= $rate->getOperations()) { |
|
43
|
|
|
$current = $this->updateCounter($valueKey, $timeKey, $interval); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
return Status::from( |
|
47
|
|
|
\sprintf('%s%s', $this->keyPrefix, $identifier), |
|
48
|
|
|
$current, |
|
49
|
|
|
$rate->getOperations(), |
|
50
|
|
|
\time() + \max(0, $interval - $this->getElapsedTime($timeKey)) |
|
51
|
|
|
); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
private function valueKey(string $identifier, int $interval): string |
|
55
|
|
|
{ |
|
56
|
|
|
return \sprintf('%s%s:value:%d', $this->keyPrefix, $identifier, $interval); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
private function timeKey(string $identifier, int $interval): string |
|
60
|
|
|
{ |
|
61
|
|
|
return \sprintf('%s%s:time:%d', $this->keyPrefix, $identifier, $interval); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
abstract protected function getCurrent(string $valueKey): int; |
|
65
|
|
|
|
|
66
|
|
|
abstract protected function updateCounter(string $valueKey, string $timeKey, int $interval): int; |
|
67
|
|
|
|
|
68
|
|
|
abstract protected function getElapsedTime(string $timeKey): int; |
|
69
|
|
|
} |
|
70
|
|
|
|