Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Limit.php
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ public function save(RateLimitStore $store, int $resetHits = 1): static
$successful = $store->set(
key: $this->getName(),
value: json_encode($data, JSON_THROW_ON_ERROR),
ttl: $this->getRemainingSeconds(),
ttl: max($this->getRemainingSeconds(), 1),
);

if ($successful === false) {
Expand Down
33 changes: 33 additions & 0 deletions tests/Unit/LimitStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Saloon\RateLimitPlugin\Limit;
use Saloon\RateLimitPlugin\Stores\MemoryStore;
use Saloon\RateLimitPlugin\Contracts\RateLimitStore;
use Saloon\RateLimitPlugin\Exceptions\LimitException;
use Saloon\RateLimitPlugin\Tests\Fixtures\Connectors\TestConnector;

Expand Down Expand Up @@ -90,3 +91,35 @@
'hits' => 1,
]);
});

test('the limit is not saved with a non-positive ttl when the clock ticks over mid-save', function () {
$store = new class implements RateLimitStore {
public ?int $ttl = null;

public function get(string $key): ?string
{
return null;
}

public function set(string $key, string $value, int $ttl): bool
{
$this->ttl = $ttl;

return true;
}
};

$limit = (new class(15) extends Limit {
protected int $clockReads = 0;

// The tick lands between the two reads of the remaining time inside save().
protected function getCurrentTimestamp(): int
{
return parent::getCurrentTimestamp() + ($this->clockReads++ > 0 ? 1 : 0);
}
})->everySeconds(1)->setPrefix('custom')->name('limit');

$limit->hit()->save($store);

expect($store->ttl)->toBe(1);
});