Repository navigation
[#290] Add first-class route rate limiting with global backend #507
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
4d6c396
[#290] Add first-class route rate limiting with global backend
armanist 4b839c4
[#290] Return dynamic Retry-After for rate limit windows
armanist 0213c7d
[#290] Replace rate-limit file storage cache dependency with fs
armanist ed52784
[#290] Validate positive rate limit values at route definition
armanist 592bb9d
[#290] Cover in-group route rateLimit builder branch
armanist f441f46
[#290] Add targeted tests for rate limit edge branches
armanist 10ad363
[#290] Decouple rate limiter config and align adapter behavior
armanist 8c5f88d
[#290] Harden file adapter tests against filename coupling
armanist File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * Quantum PHP Framework | ||
| * | ||
| * An open source software development framework for PHP | ||
| * | ||
| * @package Quantum | ||
| * @author Arman Ag. <arman.ag@softberg.org> | ||
| * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org) | ||
| * @link http://quantum.softberg.org/ | ||
| * @since 3.0.0 | ||
| */ | ||
|
|
||
| namespace Quantum\RateLimit\Adapters; | ||
|
|
||
| use Quantum\RateLimit\Contracts\RateLimitAdapterInterface; | ||
| use Quantum\Config\Exceptions\ConfigException; | ||
| use Quantum\App\Exceptions\BaseException; | ||
| use Quantum\Di\Exceptions\DiException; | ||
| use Quantum\Storage\FileSystem; | ||
| use ReflectionException; | ||
|
|
||
| /** | ||
| * Class FileRateLimitAdapter | ||
| * @package Quantum\RateLimit | ||
| */ | ||
| class FileRateLimitAdapter implements RateLimitAdapterInterface | ||
| { | ||
| private FileSystem $fs; | ||
|
|
||
| private int $resetInterval; | ||
|
|
||
| private string $path; | ||
|
|
||
| private string $prefix; | ||
|
|
||
| /** | ||
| * @param array<string, mixed> $params | ||
| * @throws ConfigException|DiException|BaseException|ReflectionException | ||
| */ | ||
| public function __construct(array $params) | ||
| { | ||
| $this->resetInterval = $params['ttl']; | ||
| $this->path = $params['path']; | ||
| $this->prefix = (string) ($params['prefix'] ?? ''); | ||
| $this->fs = fs(); | ||
|
|
||
| if (!$this->fs->isDirectory($this->path)) { | ||
| $this->fs->makeDirectory($this->path); | ||
| } | ||
| } | ||
|
|
||
| public function hit(string $key, int $limit, int $interval): bool | ||
| { | ||
| $now = time(); | ||
| $statePath = $this->getStatePath($key); | ||
| $lockPath = $this->getLockPath($key); | ||
| $lockHandle = fopen($lockPath, 'c+'); | ||
|
|
||
| if ($lockHandle === false) { | ||
| return false; | ||
| } | ||
|
|
||
| if (!flock($lockHandle, LOCK_EX)) { | ||
| fclose($lockHandle); | ||
| return false; | ||
| } | ||
|
|
||
| try { | ||
| $data = $this->readState($statePath); | ||
|
|
||
| if (!is_array($data) || !isset($data['count'], $data['reset_at']) || $now >= (int) $data['reset_at']) { | ||
| $count = 0; | ||
| $resetAt = $now + $interval; | ||
| } else { | ||
| $count = $data['count']; | ||
| $resetAt = $data['reset_at']; | ||
| } | ||
|
|
||
| $count++; | ||
|
|
||
| $this->writeState($statePath, [ | ||
| 'count' => $count, | ||
| 'reset_at' => $resetAt, | ||
| ]); | ||
| } finally { | ||
| flock($lockHandle, LOCK_UN); | ||
| fclose($lockHandle); | ||
| } | ||
|
|
||
| return $count <= $limit; | ||
| } | ||
|
|
||
| public function reset(string $key, int $count = 0): void | ||
| { | ||
| $statePath = $this->getStatePath($key); | ||
|
|
||
| if ($count <= 0) { | ||
| if ($this->fs->exists($statePath)) { | ||
| $this->fs->remove($statePath); | ||
| } | ||
| return; | ||
| } | ||
|
|
||
| $this->writeState($statePath, [ | ||
| 'count' => $count, | ||
| 'reset_at' => time() + $this->resetInterval, | ||
| ]); | ||
| } | ||
|
|
||
| public function retryAfter(string $key): int | ||
| { | ||
| $data = $this->readState($this->getStatePath($key)); | ||
|
|
||
| if (!is_array($data) || !isset($data['reset_at'])) { | ||
| return 0; | ||
| } | ||
|
|
||
| return max(0, (int) $data['reset_at'] - time()); | ||
| } | ||
|
|
||
| private function getStatePath(string $key): string | ||
| { | ||
| return $this->path . DS . md5($this->prefix . $key) . '.rate'; | ||
| } | ||
|
|
||
| private function getLockPath(string $key): string | ||
| { | ||
| return $this->path . DS . md5($this->prefix . $key) . '.lock'; | ||
| } | ||
|
|
||
| /** | ||
| * @return array<string, int>|null | ||
| */ | ||
| private function readState(string $statePath): ?array | ||
| { | ||
| if (!$this->fs->exists($statePath)) { | ||
| return null; | ||
| } | ||
|
|
||
| $raw = $this->fs->get($statePath); | ||
|
|
||
| if (!is_string($raw) || $raw === '') { | ||
| return null; | ||
| } | ||
|
|
||
| $data = json_decode($raw, true); | ||
|
|
||
| return is_array($data) ? $data : null; | ||
| } | ||
|
|
||
| /** | ||
| * @param array<string, int> $state | ||
| */ | ||
| private function writeState(string $statePath, array $state): void | ||
| { | ||
| $this->fs->put($statePath, (string) json_encode($state)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * Quantum PHP Framework | ||
| * | ||
| * An open source software development framework for PHP | ||
| * | ||
| * @package Quantum | ||
| * @author Arman Ag. <arman.ag@softberg.org> | ||
| * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org) | ||
| * @link http://quantum.softberg.org/ | ||
| * @since 3.0.0 | ||
| */ | ||
|
|
||
| namespace Quantum\RateLimit\Adapters; | ||
|
|
||
| use Quantum\RateLimit\Contracts\RateLimitAdapterInterface; | ||
| use RedisException; | ||
| use Redis; | ||
|
|
||
| /** | ||
| * Class RedisRateLimitAdapter | ||
| * @package Quantum\RateLimit | ||
| */ | ||
| class RedisRateLimitAdapter implements RateLimitAdapterInterface | ||
| { | ||
| private Redis $redis; | ||
|
|
||
| private int $resetInterval; | ||
|
|
||
| private string $prefix; | ||
|
|
||
| /** | ||
| * @param array<string, mixed> $params | ||
| * @throws RedisException | ||
| */ | ||
| public function __construct(array $params) | ||
| { | ||
| $this->resetInterval = $params['ttl']; | ||
| $this->prefix = (string) ($params['prefix'] ?? ''); | ||
|
|
||
| $this->redis = new Redis(); | ||
| $this->redis->connect($params['host'], $params['port']); | ||
| } | ||
|
|
||
| public function hit(string $key, int $limit, int $interval): bool | ||
| { | ||
| $namespacedKey = $this->prefix . $key; | ||
| $count = (int) $this->redis->incr($namespacedKey); | ||
|
|
||
| if ($count === 1) { | ||
| $this->redis->expire($namespacedKey, $interval); | ||
| } | ||
|
|
||
| return $count <= $limit; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| public function reset(string $key, int $count = 0): void | ||
| { | ||
| $namespacedKey = $this->prefix . $key; | ||
|
|
||
| if ($count <= 0) { | ||
| $this->redis->del($namespacedKey); | ||
| return; | ||
| } | ||
|
|
||
| $this->redis->setex($namespacedKey, $this->resetInterval, (string) $count); | ||
| } | ||
|
|
||
| public function retryAfter(string $key): int | ||
| { | ||
| $ttl = (int) $this->redis->ttl($this->prefix . $key); | ||
| return $ttl > 0 ? $ttl : 0; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * Quantum PHP Framework | ||
| * | ||
| * An open source software development framework for PHP | ||
| * | ||
| * @package Quantum | ||
| * @author Arman Ag. <arman.ag@softberg.org> | ||
| * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org) | ||
| * @link http://quantum.softberg.org/ | ||
| * @since 3.0.0 | ||
| */ | ||
|
|
||
| namespace Quantum\RateLimit\Contracts; | ||
|
|
||
| /** | ||
| * Interface RateLimitAdapterInterface | ||
| * @package Quantum\RateLimit | ||
| */ | ||
| interface RateLimitAdapterInterface | ||
| { | ||
| public function hit(string $key, int $limit, int $interval): bool; | ||
|
|
||
| public function reset(string $key, int $count = 0): void; | ||
|
|
||
| public function retryAfter(string $key): int; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.