-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathHasRateLimits.php
More file actions
248 lines (203 loc) · 7.16 KB
/
HasRateLimits.php
File metadata and controls
248 lines (203 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
<?php
declare(strict_types=1);
namespace Saloon\RateLimitPlugin\Traits;
use Exception;
use ReflectionClass;
use Saloon\Http\Response;
use Saloon\Enums\PipeOrder;
use Saloon\Http\PendingRequest;
use Saloon\RateLimitPlugin\Limit;
use Saloon\RateLimitPlugin\Helpers\LimitHelper;
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
use Saloon\RateLimitPlugin\Helpers\RetryAfterHelper;
use Saloon\RateLimitPlugin\Exceptions\LimitException;
use Saloon\RateLimitPlugin\Exceptions\RateLimitReachedException;
trait HasRateLimits
{
/**
* Is Rate limiting is enabled?
*/
protected bool $rateLimitingEnabled = true;
/**
* The rate limiter store
*/
protected ?RateLimitStore $rateLimitStore = null;
/**
* Attempt to automatically detect 429 errors
*/
protected bool $detectTooManyAttempts = true;
/**
* Boot the has rate limiting trait
*/
public function bootHasRateLimits(PendingRequest $pendingRequest): void
{
if (! $this->rateLimitingEnabled) {
return;
}
// Firstly, we'll register a request middleware that will check if we have
// exceeded any limits already. If we have, then this middleware will stop
// the request from being processed.
$pendingRequest->middleware()->onRequest(function (PendingRequest $pendingRequest): void {
$limit = $this->getExceededLimit();
if ($limit instanceof Limit) {
$this->handleExceededLimit($limit, $pendingRequest);
}
});
$pendingRequest->middleware()->onResponse(function (Response $response): Response {
$limitThatWasExceeded = null;
$store = $this->rateLimitStore();
// First we'll iterate over every limit class, and we'll check if the limit has
// been reached. We'll increment each of the limits and continue with the
// response.
foreach ($this->getLimits() as $limit) {
// We'll update our limit from the store which should populate it with the
// latest timestamp and hits.
$limit->update($store);
// Now we'll "hit" the limit which will increase the count
// We won't hit if it's a from response limiter.
$limit->usesResponse()
? $limit->handleResponse($response)
: $limit->hit();
// If our limit has been exceeded, we will assign the limit
// that was exceeded. This will throw an exception.
if ($limit->wasManuallyExceeded()) {
$limitThatWasExceeded = $limit;
}
// Finally, we'll commit the limit onto the store
$limit->save($store);
}
// If a limit was previously exceeded this means that the manual
// check to see if a response has hit the limit has come into
// place. We should make sure to throw the exception here.
if (isset($limitThatWasExceeded)) {
if (! $limit->getShouldSleep()) {
$this->throwLimitException($limitThatWasExceeded);
}
// When the limit has been instructed to sleep() we will make the request
// again, which will trigger the request middleware to sleep, and then
// hopefully get a successful response afterward.
return $this->send($response->getRequest());
}
return $response;
}, order: PipeOrder::FIRST);
}
/**
* Get the prefix added to every limit
*/
protected function getLimiterPrefix(): ?string
{
return (new ReflectionClass($this))->getShortName();
}
/**
* Define the "Too Many Attempts" (429) limiter
*
* This limiter will automatically attempt to detect 429 requests.
*/
protected function getTooManyAttemptsLimiter(): ?Limit
{
return Limit::custom($this->handleTooManyAttempts(...));
}
/**
* Handle too many attempts (429) statuses
*/
protected function handleTooManyAttempts(Response $response, Limit $limit): void
{
if ($response->status() !== 429) {
return;
}
$limit->exceeded(
releaseInSeconds: RetryAfterHelper::parse($response->header('Retry-After')),
);
}
/**
* Throw the limit exception
*
* @throws \Saloon\RateLimitPlugin\Exceptions\RateLimitReachedException
*/
protected function throwLimitException(Limit $limit): void
{
throw new RateLimitReachedException($limit);
}
/**
* Get the first limit that has exceeded
*
* @throws \JsonException
* @throws LimitException
* @throws Exception
*/
public function getExceededLimit(?float $threshold = null): ?Limit
{
$store = $this->rateLimitStore();
foreach ($this->getLimits() as $limit) {
$limit->update($store);
if ($limit->hasReachedLimit($threshold)) {
return $limit;
}
}
return null;
}
/**
* Check if we have reached the rate limit
*
* @throws \JsonException
* @throws LimitException
*/
public function hasReachedRateLimit(?float $threshold = null): bool
{
return $this->getExceededLimit($threshold) instanceof Limit;
}
/**
* Handle the exceeded limit
*
* If the limit should wait, we will increment a delay - otherwise we will continue
*
* @throws \Saloon\RateLimitPlugin\Exceptions\RateLimitReachedException
*/
protected function handleExceededLimit(Limit $limit, PendingRequest $pendingRequest): void
{
if (! $limit->getShouldSleep()) {
$this->throwLimitException($limit);
}
$existingDelay = $pendingRequest->delay()->get() ?? 0;
$remainingMilliseconds = $limit->getRemainingSeconds() * 1000;
$pendingRequest->delay()->set($existingDelay + $remainingMilliseconds);
}
/**
* Enable or disable the rate limiting functionality
*
* @return $this
*/
public function useRateLimitPlugin(bool $enabled = true): static
{
$this->rateLimitingEnabled = $enabled;
return $this;
}
/**
* Get the rate limiter store
*/
public function rateLimitStore(): RateLimitStore
{
return $this->rateLimitStore ??= $this->resolveRateLimitStore();
}
/**
* Get the limits for the rate limiter store
*
* @return array<Limit>
* @throws LimitException
*/
public function getLimits(): array
{
$tooManyAttemptsLimit = $this->detectTooManyAttempts === true ? $this->getTooManyAttemptsLimiter() : null;
return LimitHelper::configureLimits($this->resolveLimits(), $this->getLimiterPrefix(), $tooManyAttemptsLimit);
}
/**
* Resolve the limits for the rate limiter
*
* @return array<\Saloon\RateLimitPlugin\Limit>
*/
abstract protected function resolveLimits(): array;
/**
* Resolve the rate limit store
*/
abstract protected function resolveRateLimitStore(): RateLimitStore;
}