Completed
Push — master ( d6870c...9a821e )
by Krishnaprasad
05:41 queued 02:32
created

LeakyBucketThrottler::getTimeCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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\Adapter\CacheAdapterInterface;
30
use Sunspikes\Ratelimit\Time\TimeAdapterInterface;
31
32
final class LeakyBucketThrottler implements RetriableThrottlerInterface
33
{
34
    const CACHE_KEY_TIME = ':time';
35
    const CACHE_KEY_TOKEN = ':tokens';
36
37
    /**
38
     * @var CacheAdapterInterface
39
     */
40
    private $cache;
41
42
    /**
43
     * @var int|null
44
     */
45
    private $cacheTtl;
46
47
    /**
48
     * @var string
49
     */
50
    private $key;
51
52
    /**
53
     * @var int
54
     */
55
    private $threshold;
56
57
    /**
58
     * @var TimeAdapterInterface
59
     */
60
    private $timeProvider;
61
62
    /**
63
     * @var int
64
     */
65
    private $timeLimit;
66
67
    /**
68
     * @var int
69
     */
70
    private $tokenlimit;
71
72
    /**
73
     * @param CacheAdapterInterface $cache
74
     * @param TimeAdapterInterface  $timeAdapter
75
     * @param string                $key          Cache key prefix
76
     * @param int                   $tokenLimit   Bucket capacity
77
     * @param int                   $timeLimit    Refill time in milliseconds
78
     * @param int|null              $threshold    Capacity threshold on which to start throttling (default: 0)
79
     * @param int|null              $cacheTtl     Cache ttl time (default: null => CacheAdapter ttl)
80
     */
81 16
    public function __construct(
82
        CacheAdapterInterface $cache,
83
        TimeAdapterInterface $timeAdapter,
84
        $key,
85
        $tokenLimit,
86
        $timeLimit,
87
        $threshold = null,
88
        $cacheTtl = null
89
    ) {
90 16
        $this->cache = $cache;
91 16
        $this->timeProvider = $timeAdapter;
92 16
        $this->key = $key;
93 16
        $this->tokenlimit = $tokenLimit;
94 16
        $this->timeLimit = $timeLimit;
95 16
        $this->cacheTtl = $cacheTtl;
96 16
        $this->threshold = null !== $threshold ? $threshold : 0;
97 16
    }
98
99
    /**
100
     * @inheritdoc
101
     */
102 3
    public function access()
103
    {
104 3
        return 0 === $this->hit();
105
    }
106
107
    /**
108
     * @inheritdoc
109
     */
110 8
    public function hit()
111
    {
112 8
        $tokenCount = $this->count();
113
114 8
        $this->setUsedCapacity($tokenCount + 1);
115
116 8
        if (0 < $wait = $this->getWaitTime($tokenCount)) {
117 2
            $this->timeProvider->usleep(self::MILLISECOND_TO_MICROSECOND_MULTIPLIER * $wait);
118 2
        }
119
120 8
        return $wait;
121
    }
122
123
    /**
124
     * @inheritdoc
125
     */
126 7
    public function clear()
127
    {
128 7
        $this->setUsedCapacity(0);
129 7
    }
130
131
    /**
132
     * @inheritdoc
133
     */
134 14
    public function count()
135
    {
136
        try {
137 14
            $cachedTime = $this->cache->get($this->getTimeCacheKey());
138 13
            $timeSinceLastRequest = self::SECOND_TO_MILLISECOND_MULTIPLIER * ($this->timeProvider->now() - $cachedTime);
139
140 13
            if ($timeSinceLastRequest > $this->timeLimit) {
141 4
                return 0;
142
            }
143
144 9
            $lastTokenCount = $this->cache->get($this->getTokenCacheKey());
145 10
        } catch (ItemNotFoundException $exception) {
146 6
            $this->clear(); //Clear the bucket
147
148 6
            return 0;
149
        }
150
151
        // Return the `used` token count, minus the amount of tokens which have been `refilled` since the previous request
152 9
        return  (int) max(0, ceil($lastTokenCount - ($this->tokenlimit * $timeSinceLastRequest / ($this->timeLimit))));
153
    }
154
155
    /**
156
     * @inheritdoc
157
     */
158 3
    public function check()
159
    {
160 3
        return 0 === $this->getWaitTime($this->count());
161
    }
162
163
    /**
164
     * @inheritdoc
165
     */
166
    public function getTime()
167
    {
168
        return $this->timeLimit;
169
    }
170
171
    /**
172
     * @inheritdoc
173
     */
174
    public function getLimit()
175
    {
176
        return $this->tokenlimit;
177
    }
178
179
    /**
180
     * @inheritdoc
181
     */
182 2 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...
183
    {
184 2
        if ($this->threshold > $this->count() + 1) {
185 1
            return 0;
186
        }
187
188 1
        return (int) ceil($this->timeLimit / $this->tokenlimit);
189
    }
190
191
    /**
192
     * @param int $tokenCount
193
     *
194
     * @return int
195
     */
196 9 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...
197
    {
198 9
        if ($this->threshold > $tokenCount) {
199 8
            return 0;
200
        }
201
202 3
        return (int) ceil($this->timeLimit / max(1, ($this->tokenlimit - $this->threshold)));
203
    }
204
205
    /**
206
     * @param int $tokens
207
     */
208 10
    private function setUsedCapacity($tokens)
209
    {
210 10
        $this->cache->set($this->getTokenCacheKey(), $tokens, $this->cacheTtl);
211 10
        $this->cache->set($this->getTimeCacheKey(), $this->timeProvider->now(), $this->cacheTtl);
212 10
    }
213
214
    /**
215
     * @return string
216
     */
217 12
    private function getTokenCacheKey()
218
    {
219 12
        return $this->key.self::CACHE_KEY_TOKEN;
220
    }
221
222
    /**
223
     * @return string
224
     */
225 15
    private function getTimeCacheKey()
226
    {
227 15
        return $this->key.self::CACHE_KEY_TIME;
228
    }
229
}
230