Repository navigation
Expand file tree
/
Copy pathThrottleIssues.php
More file actions
58 lines (44 loc) · 1.6 KB
/
Copy pathThrottleIssues.php
File metadata and controls
58 lines (44 loc) · 1.6 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
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Enums\ApiErrorCode;
use App\Exceptions\ApiException;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Symfony\Component\HttpFoundation\Response;
final readonly class ThrottleIssues
{
private const int PER_DAY = 10;
private const int DECAY_SECONDS = 86400;
/**
* One budget of issues a day, however they are opened. Only issues GitHub opened count, so a rejected draft or a
* GitHub outage costs nothing.
*
* @param Closure(Request): (Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$user = $request->user();
assert($user instanceof User);
$key = "issues:{$user->id}";
if (RateLimiter::tooManyAttempts($key, self::PER_DAY)) {
return $this->tooMany($request, RateLimiter::availableIn($key));
}
$response = $next($request);
if ($response->getStatusCode() === Response::HTTP_CREATED) {
RateLimiter::hit($key, self::DECAY_SECONDS);
}
return $response;
}
private function tooMany(Request $request, int $retryAfter): Response
{
$message = 'Issue limit reached: '.self::PER_DAY.' a day. Try again tomorrow.';
// The apps read JSON with a code...
if ($request->routeIs('api-issue.store')) {
return new ApiException(ApiErrorCode::RateLimited, $message, ['Retry-After' => $retryAfter])->render();
}
return response()->json(['message' => $message], 429);
}
}