Passed
Pull Request — master (#19)
by Vadim
02:42
created

Counter::incrementAndGetState()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 22
ccs 12
cts 12
cp 1
crap 3
rs 9.9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\RateLimiter;
6
7
use InvalidArgumentException;
8
use Yiisoft\Yii\RateLimiter\Storage\StorageInterface;
9
use Yiisoft\Yii\RateLimiter\Time\MicrotimeTimer;
10
use Yiisoft\Yii\RateLimiter\Time\TimerInterface;
11
12
/**
13
 * Counter implements generic cell rate limit algorithm (GCRA) that ensures that after reaching the limit further
14
 * increments are distributed equally.
15
 *
16
 * @link https://en.wikipedia.org/wiki/Generic_cell_rate_algorithm
17
 */
18
final class Counter implements CounterInterface
19
{
20
    private const DEFAULT_TTL = 86400;
21
22
    private const ID_PREFIX = 'rate-limiter-';
23
24
    /**
25
     * @var int Period to apply limit to.
26
     */
27
    private int $periodInMilliseconds;
28
29
    private int $limit;
30
31
    /**
32
     * @var float Maximum interval before next increment.
33
     * In GCRA it is known as emission interval.
34
     */
35
    private float $incrementIntervalInMilliseconds;
36
37
    private StorageInterface $storage;
38
39
    private int $ttlInSeconds;
40
    private string $cachePrefix;
41
42
    private TimerInterface $timer;
43
44
    /**
45
     * @param StorageInterface $storage
46
     * @param int $limit Maximum number of increments that could be performed before increments are limited.
47
     * @param int $periodInSeconds Period to apply limit to.
48
     * @param int $ttlInSeconds
49
     * @param TimerInterface|null $timer
50
     * @param string $cachePrefix
51
     */
52 9
    public function __construct(
53
        StorageInterface $storage,
54
        int $limit,
55
        int $periodInSeconds,
56
        int $ttlInSeconds = self::DEFAULT_TTL,
57
        ?TimerInterface $timer = null,
58
        string $cachePrefix = self::ID_PREFIX
59
    ) {
60 9
        if ($limit < 1) {
61 1
            throw new InvalidArgumentException('The limit must be a positive value.');
62
        }
63
64 8
        if ($periodInSeconds < 1) {
65 1
            throw new InvalidArgumentException('The period must be a positive value.');
66
        }
67
68 7
        $this->limit = $limit;
69 7
        $this->periodInMilliseconds = $periodInSeconds * MILLISECONDS_PER_SECOND;
70 7
        $this->storage = $storage;
71 7
        $this->ttlInSeconds = $ttlInSeconds;
72 7
        $this->cachePrefix = $cachePrefix;
73 7
        $this->timer = $timer ?: new MicrotimeTimer();
74
75 7
        $this->incrementIntervalInMilliseconds = (float)($this->periodInMilliseconds / $this->limit);
76 7
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81 7
    public function hit(string $id): CounterState
82
    {
83
        // Last increment time.
84
        // In GCRA it's known as arrival time.
85 7
        $lastIncrementTimeInMilliseconds = $this->timer->nowInMilliseconds();
86
87 7
        $theoreticalNextIncrementTime = $this->calculateTheoreticalNextIncrementTime(
88 7
            $lastIncrementTimeInMilliseconds,
89 7
            $this->getLastStoredTheoreticalNextIncrementTime($id, $lastIncrementTimeInMilliseconds)
90
        );
91
92 7
        $remaining = $this->calculateRemaining($lastIncrementTimeInMilliseconds, $theoreticalNextIncrementTime);
93 7
        $resetAfter = $this->calculateResetAfter($theoreticalNextIncrementTime);
94
95 7
        if ($remaining >= 1) {
96 6
            $this->storeTheoreticalNextIncrementTime($id, $theoreticalNextIncrementTime);
97
        }
98
99 7
        return new CounterState($this->limit, $remaining, $resetAfter);
100
    }
101
102
    /**
103
     * @param int $lastIncrementTimeInMilliseconds
104
     * @param float $storedTheoreticalNextIncrementTime
105
     *
106
     * @return float Theoretical increment time that would be expected from equally spaced increments at exactly rate
107
     * limit. In GCRA it is known as TAT, theoretical arrival time.
108
     */
109 7
    private function calculateTheoreticalNextIncrementTime(
110
        int $lastIncrementTimeInMilliseconds,
111
        float $storedTheoreticalNextIncrementTime
112
    ): float {
113 7
        return max($lastIncrementTimeInMilliseconds, $storedTheoreticalNextIncrementTime) +
114 7
            $this->incrementIntervalInMilliseconds;
115
    }
116
117
    /**
118
     * @param int $lastIncrementTimeInMilliseconds
119
     * @param float $theoreticalNextIncrementTime
120
     *
121
     * @return int The number of remaining requests in the current time period.
122
     */
123 7
    private function calculateRemaining(int $lastIncrementTimeInMilliseconds, float $theoreticalNextIncrementTime): int
124
    {
125 7
        $incrementAllowedAt = $theoreticalNextIncrementTime - $this->periodInMilliseconds;
126
127
        return (int)(
128 7
            round($lastIncrementTimeInMilliseconds - $incrementAllowedAt) /
129 7
            $this->incrementIntervalInMilliseconds
130
        );
131
    }
132
133 7
    private function getLastStoredTheoreticalNextIncrementTime(string $id, int $lastIncrementTimeInMilliseconds): float
134
    {
135 7
        return (float)$this->storage->get($this->getCacheKey($id), $lastIncrementTimeInMilliseconds);
136
    }
137
138 6
    private function storeTheoreticalNextIncrementTime(string $id, float $theoreticalNextIncrementTime): void
139
    {
140 6
        $this->storage->save($this->getCacheKey($id), $theoreticalNextIncrementTime, $this->ttlInSeconds);
141 6
    }
142
143
    /**
144
     * @param float $theoreticalNextIncrementTime
145
     *
146
     * @return int Timestamp to wait until the rate limit resets.
147
     */
148 7
    private function calculateResetAfter(float $theoreticalNextIncrementTime): int
149
    {
150 7
        return (int)($theoreticalNextIncrementTime / MILLISECONDS_PER_SECOND);
151
    }
152
153
    /**
154
     * @param string $id
155
     *
156
     * @return string Cache key used to store the next increment time.
157
     */
158 7
    private function getCacheKey(string $id): string
159
    {
160 7
        return $this->cachePrefix . $id;
161
    }
162
}
163