Files

72 lines
2.3 KiB
PHP
Raw Permalink Normal View History

2026-01-06 02:05:38 +02:00
<?php
2026-10-05 18:10:18 -04:00
declare(strict_types=1);
2026-01-06 02:05:38 +02:00
namespace Pterodactyl\Enum;
use Illuminate\Cache\RateLimiting\Limit;
2026-10-05 18:10:18 -04:00
use Illuminate\Http\Request;
2026-01-06 02:05:38 +02:00
use Illuminate\Routing\Middleware\ThrottleRequests;
2026-10-05 18:10:18 -04:00
use Illuminate\Support\Facades\RateLimiter;
use InvalidArgumentException;
use Pterodactyl\Models\Server;
2026-01-06 02:05:38 +02:00
/**
* A basic resource throttler for individual servers. This is applied in addition
* to existing rate limits and allows the code to slow down speedy users that might
* be creating resources a little too quickly for comfort. This throttle generally
* only applies to creation flows, and not general view/edit/delete flows.
*/
enum ResourceLimit
{
case Allocation;
case Backup;
case Database;
case Schedule;
case Subuser;
case Websocket;
case FilePull;
2026-10-05 18:10:18 -04:00
public static function boot(): void
{
foreach (self::cases() as $case) {
RateLimiter::for($case->throttleKey(), function (Request $request) use ($case) {
$route = $request->route();
throw_if($route === null, InvalidArgumentException::class, 'Expected an active route when applying a server resource limit.');
$server = $route->parameter('server');
throw_unless($server instanceof Server, InvalidArgumentException::class, 'Expected route parameter [server] to be a server.');
return $case->limit()->by($server->uuid);
});
}
}
2026-01-06 02:05:38 +02:00
public function throttleKey(): string
{
return mb_strtolower("api.client:server-resource:{$this->name}");
}
/**
* Returns a middleware that will throttle the specific resource by server. This
* throttle applies to any user making changes to that resource on the specific
* server, it is NOT per-user.
*/
public function middleware(): string
{
return ThrottleRequests::using($this->throttleKey());
}
public function limit(): Limit
{
2026-10-05 18:10:18 -04:00
return match ($this) {
2026-01-06 02:05:38 +02:00
self::Backup => Limit::perMinutes(15, 3),
self::Database => Limit::perMinute(2),
self::FilePull => Limit::perMinutes(10, 5),
self::Subuser => Limit::perMinutes(15, 10),
self::Websocket => Limit::perMinute(5),
default => Limit::perMinute(2),
};
}
}