Passed
Pull Request — master (#19)
by Alexander
02:00
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
    private const MILLISECONDS_PER_SECOND = 1000;
25
26
    /**
27
     * @var int Period to apply limit to.
28
     */
29
    private int $periodInMilliseconds;
30
31
    private int $limit;
32
33
    /**
34
     * @var float Maximum interval before next increment.
35
     * In GCRA it is known as emission interval.
36
     */
37
    private float $incrementIntervalInMilliseconds;
38
39
    private StorageInterface $storage;
40
41
    private int $ttlInSeconds;
42
    private string $cachePrefix;
43
44
    private TimerInterface $timer;
45
46
    /**
47
     * @param StorageInterface $storage
48
     * @param int $limit Maximum number of increments that could be performed before increments are limited.
49
     * @param int $periodInSeconds Period to apply limit to.
50
     * @param int $ttlInSeconds
51
     * @param TimerInterface|null $timer
52
     * @param string $cachePrefix
53
     */
54 9
    public function __construct(
55
        StorageInterface $storage,
56
        int $limit,
57
        int $periodInSeconds,
58
        int $ttlInSeconds = self::DEFAULT_TTL,
59
        ?TimerInterface $timer = null,
60
        string $cachePrefix = self::ID_PREFIX
61
    ) {
62 9
        if ($limit < 1) {
63 1
            throw new InvalidArgumentException('The limit must be a positive value.');
64
        }
65
66 8
        if ($periodInSeconds < 1) {
67 1
            throw new InvalidArgumentException('The period must be a positive value.');
68
        }
69
70 7
        $this->limit = $limit;
71 7
        $this->periodInMilliseconds = $periodInSeconds * self::MILLISECONDS_PER_SECOND;
72 7
        $this->storage = $storage;
73 7
        $this->ttlInSeconds = $ttlInSeconds;
74 7
        $this->cachePrefix = $cachePrefix;
75 7
        $this->timer = $timer ?: new MicrotimeTimer();
76
77 7
        $this->incrementIntervalInMilliseconds = (float)($this->periodInMilliseconds / $this->limit);
78 7
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 7
    public function hit(string $id): CounterState
84
    {
85
        // Last increment time.
86
        // In GCRA it's known as arrival time.
87 7
        $lastIncrementTimeInMilliseconds = $this->timer->nowInMilliseconds();
88
89 7
        $theoreticalNextIncrementTime = $this->calculateTheoreticalNextIncrementTime(
90 7
            $lastIncrementTimeInMilliseconds,
91 7
            $this->getLastStoredTheoreticalNextIncrementTime($id, $lastIncrementTimeInMilliseconds)
92
        );
93
94 7
        $remaining = $this->calculateRemaining($lastIncrementTimeInMilliseconds, $theoreticalNextIncrementTime);
95 7
        $resetAfter = $this->calculateResetAfter($theoreticalNextIncrementTime);
96
97 7
        if ($remaining >= 1) {
98 6
            $this->storeTheoreticalNextIncrementTime($id, $theoreticalNextIncrementTime);
99
        }
100
101 7
        return new CounterState($this->limit, $remaining, $resetAfter);
102
    }
103
104
    /**
105
     * @param int $lastIncrementTimeInMilliseconds
106
     * @param float $storedTheoreticalNextIncrementTime
107
     *
108
     * @return float Theoretical increment time that would be expected from equally spaced increments at exactly rate
109
     * limit. In GCRA it is known as TAT, theoretical arrival time.
110
     */
111 7
    private function calculateTheoreticalNextIncrementTime(
112
        int $lastIncrementTimeInMilliseconds,
113
        float $storedTheoreticalNextIncrementTime
114
    ): float {
115 7
        return max($lastIncrementTimeInMilliseconds, $storedTheoreticalNextIncrementTime) +
116 7
            $this->incrementIntervalInMilliseconds;
117
    }
118
119
    /**
120
     * @param int $lastIncrementTimeInMilliseconds
121
     * @param float $theoreticalNextIncrementTime
122
     *
123
     * @return int The number of remaining requests in the current time period.
124
     */
125 7
    private function calculateRemaining(int $lastIncrementTimeInMilliseconds, float $theoreticalNextIncrementTime): int
126
    {
127 7
        $incrementAllowedAt = $theoreticalNextIncrementTime - $this->periodInMilliseconds;
128
129
        return (int)(
130 7
            round($lastIncrementTimeInMilliseconds - $incrementAllowedAt) /
131 7
            $this->incrementIntervalInMilliseconds
132
        );
133
    }
134
135 7
    private function getLastStoredTheoreticalNextIncrementTime(string $id, int $lastIncrementTimeInMilliseconds): float
136
    {
137 7
        return (float)$this->storage->get($this->getCacheKey($id), $lastIncrementTimeInMilliseconds);
138
    }
139
140 6
    private function storeTheoreticalNextIncrementTime(string $id, float $theoreticalNextIncrementTime): void
141
    {
142 6
        $this->storage->save($this->getCacheKey($id), $theoreticalNextIncrementTime, $this->ttlInSeconds);
143 6
    }
144
145
    /**
146
     * @param float $theoreticalNextIncrementTime
147
     *
148
     * @return int Timestamp to wait until the rate limit resets.
149
     */
150 7
    private function calculateResetAfter(float $theoreticalNextIncrementTime): int
151
    {
152 7
        return (int)($theoreticalNextIncrementTime / self::MILLISECONDS_PER_SECOND);
153
    }
154
155
    /**
156
     * @param string $id
157
     *
158
     * @return string Cache key used to store the next increment time.
159
     */
160 7
    private function getCacheKey(string $id): string
161
    {
162 7
        return $this->cachePrefix . $id;
163
    }
164
}
165