Repository navigation
Expand file tree
/
Copy pathThrottleCommits.php
More file actions
67 lines (52 loc) · 1.86 KB
/
Copy pathThrottleCommits.php
File metadata and controls
67 lines (52 loc) · 1.86 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
<?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 Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final readonly class ThrottleCommits
{
private const int PER_MINUTE = 10;
/**
* One budget of commits a minute, however they are posted.
*
* @param Closure(Request): (Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$user = $request->user();
assert($user instanceof User);
$key = "commits:{$user->id}";
if (RateLimiter::tooManyAttempts($key, self::PER_MINUTE)) {
return $this->slowDown($request, RateLimiter::availableIn($key));
}
RateLimiter::increment($key, 60);
return $next($request);
}
private function slowDown(Request $request, int $retryAfter): Response
{
$message = 'Slow down: 10 commits a minute. Even CI takes breaks.';
// The `devnull commit` script prints plain text...
if ($request->routeIs('cli-commit.store')) {
return response($message."\n", 429, ['Retry-After' => $retryAfter])
->header('Content-Type', 'text/plain; charset=utf-8');
}
// The mobile app reads JSON with a code...
if ($request->routeIs('api-commit.store')) {
return new ApiException(ApiErrorCode::RateLimited, $message, ['Retry-After' => $retryAfter])->render();
}
if ($request->expectsJson()) {
return response()->json(['message' => $message], 429, ['Retry-After' => $retryAfter]);
}
Inertia::flash('toast', [
'type' => 'error',
'message' => $message,
]);
return back();
}
}