Completed
Pull Request — master (#10)
by Krishnaprasad
08:08 queued 03:56
created

LeakyBucketThrottler::getRetryTimeout()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 8
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 8
loc 8
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
crap 6
1
<?php
2
/**
3
 * The MIT License (MIT)
4
 *
5
 * Copyright (c) 2015 Krishnaprasad MG <[email protected]>
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in all
15
 * copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
 * SOFTWARE.
24
 */
25
26
namespace Sunspikes\Ratelimit\Throttle\Throttler;
27
28
use Sunspikes\Ratelimit\Cache\Exception\ItemNotFoundException;
29
use Sunspikes\Ratelimit\Cache\ThrottlerCacheInterface;
30
use Sunspikes\Ratelimit\Throttle\Entity\CacheCount;
31
use Sunspikes\Ratelimit\Throttle\Entity\CacheTime;
32
use Sunspikes\Ratelimit\Time\TimeAdapterInterface;
33
34
final class LeakyBucketThrottler implements RetriableThrottlerInterface
35
{
36
    const CACHE_KEY_TIME = '-time';
37
    const CACHE_KEY_TOKEN = '-tokens';
38
39
    /**
40
     * @var ThrottlerCacheInterface
41
     */
42
    private $cache;
43
44
    /**
45
     * @var int|null
46
     */
47
    private $cacheTtl;
48
49
    /**
50
     * @var string
51
     */
52
    private $key;
53
54
    /**
55
     * @var int
56
     */
57
    private $threshold;
58
59
    /**
60
     * @var TimeAdapterInterface
61
     */
62
    private $timeProvider;
63
64
    /**
65
     * @var int
66
     */
67
    private $timeLimit;
68
69
    /**
70
     * @var int
71
     */
72
    private $tokenlimit;
73
74
    /**
75
     * @param ThrottlerCacheInterface $cache
76
     * @param TimeAdapterInterface    $timeAdapter
77
     * @param string                  $key        Cache key prefix
78
     * @param int                     $tokenLimit Bucket capacity
79
     * @param int                     $timeLimit  Refill time in milliseconds
80
     * @param int|null                $threshold  Capacity threshold on which to start throttling (default: 0)
81
     * @param int|null                $cacheTtl   Cache ttl time (default: null => CacheAdapter ttl)
82
     */
83 6
    public function __construct(
84
        ThrottlerCacheInterface $cache,
85
        TimeAdapterInterface $timeAdapter,
86
        $key,
87
        $tokenLimit,
88
        $timeLimit,
89
        $threshold = null,
90
        $cacheTtl = null
91
    ) {
92 6
        $this->cache = $cache;
93 6
        $this->timeProvider = $timeAdapter;
94 6
        $this->key = $key;
95 6
        $this->tokenlimit = $tokenLimit;
96 6
        $this->timeLimit = $timeLimit;
97 6
        $this->cacheTtl = $cacheTtl;
98 6
        $this->threshold = null !== $threshold ? $threshold : 0;
99 6
    }
100
101
    /**
102
     * @inheritdoc
103
     */
104 2
    public function access()
105
    {
106 2
        return 0 === $this->hit();
107
    }
108
109
    /**
110
     * @inheritdoc
111
     */
112 5
    public function hit()
113
    {
114 5
        $tokenCount = $this->count();
115
116 5
        $this->setUsedCapacity($tokenCount + 1);
117
118 5
        if (0 < $wait = $this->getWaitTime($tokenCount)) {
119 1
            $this->timeProvider->usleep(self::MILLISECOND_TO_MICROSECOND_MULTIPLIER * $wait);
120
        }
121
122 5
        return $wait;
123
    }
124
125
    /**
126
     * @inheritdoc
127
     */
128 5
    public function clear()
129
    {
130 5
        $this->setUsedCapacity(0);
131 5
    }
132
133
    /**
134
     * @inheritdoc
135
     */
136 5
    public function count()
137
    {
138
        try {
139
            /** @var CacheTime $timeItem */
140 5
            $timeItem = $this->cache->getItem($this->getTimeCacheKey());
141 5
            $timeSinceLastRequest = self::SECOND_TO_MILLISECOND_MULTIPLIER * ($this->timeProvider->now() - $timeItem->getTime());
142
143 5
            if ($timeSinceLastRequest > $this->timeLimit) {
144
                return 0;
145
            }
146
147
            /** @var CacheCount $countItem */
148 5
            $countItem = $this->cache->getItem($this->getTokenCacheKey());
149 5
        } catch (ItemNotFoundException $exception) {
150 5
            $this->clear(); //Clear the bucket
151
152 5
            return 0;
153
        }
154
155
        // Return the `used` token count, minus the amount of tokens which have been `refilled` since the previous request
156 5
        return  (int) max(0, ceil($countItem->getCount() - ($this->tokenlimit * $timeSinceLastRequest / ($this->timeLimit))));
157
    }
158
159
    /**
160
     * @inheritdoc
161
     */
162 2
    public function check()
163
    {
164 2
        return 0 === $this->getWaitTime($this->count());
165
    }
166
167
    /**
168
     * @inheritdoc
169
     */
170
    public function getTime()
171
    {
172
        return $this->timeLimit;
173
    }
174
175
    /**
176
     * @inheritdoc
177
     */
178
    public function getLimit()
179
    {
180
        return $this->tokenlimit;
181
    }
182
183
    /**
184
     * @inheritdoc
185
     */
186 View Code Duplication
    public function getRetryTimeout()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
187
    {
188
        if ($this->threshold > $this->count() + 1) {
189
            return 0;
190
        }
191
192
        return (int) ceil($this->timeLimit / $this->tokenlimit);
193
    }
194
195
    /**
196
     * @param int $tokenCount
197
     *
198
     * @return int
199
     */
200 5 View Code Duplication
    private function getWaitTime($tokenCount)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
201
    {
202 5
        if ($this->threshold > $tokenCount) {
203 5
            return 0;
204
        }
205
206 2
        return (int) ceil($this->timeLimit / max(1, ($this->tokenlimit - $this->threshold)));
207
    }
208
209
    /**
210
     * @param int $tokens
211
     */
212 5
    private function setUsedCapacity($tokens)
213
    {
214 5
        $countItem = new CacheCount($tokens, $this->cacheTtl);
215 5
        $this->cache->setItem($this->getTokenCacheKey(), $countItem);
216
217 5
        $timeItem = new CacheTime($this->timeProvider->now(), $this->cacheTtl);
218 5
        $this->cache->setItem($this->getTimeCacheKey(), $timeItem);
219 5
    }
220
221
    /**
222
     * @return string
223
     */
224 5
    private function getTokenCacheKey()
225
    {
226 5
        return $this->key.self::CACHE_KEY_TOKEN;
227
    }
228
229
    /**
230
     * @return string
231
     */
232 5
    private function getTimeCacheKey()
233
    {
234 5
        return $this->key.self::CACHE_KEY_TIME;
235
    }
236
}
237