Skip to content

Commit

Permalink
set a default and max ttl for redis keys
Browse files Browse the repository at this point in the history
having infinite TTL can lead to leaked keys as the prefix changes with version upgrades

Signed-off-by: Robin Appelman <robin@icewind.nl>
  • Loading branch information
icewind1991 committed Jun 15, 2023
1 parent aedb4be commit b27b5ed
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions lib/private/Memcache/Redis.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ class Redis extends Cache implements IMemcacheTTL {
],
];

private const DEFAULT_TTL = 24 * 60 * 60; // 1 day
private const MAX_TTL = 30 * 24 * 60 * 60; // 1 month

/**
* @var \Redis|\RedisCluster $cache
*/
Expand Down Expand Up @@ -79,11 +82,12 @@ public function get($key) {

public function set($key, $value, $ttl = 0) {
$value = self::encodeValue($value);
if ($ttl > 0) {
return $this->getCache()->setex($this->getPrefix() . $key, $ttl, $value);
} else {
return $this->getCache()->set($this->getPrefix() . $key, $value);
if ($ttl === 0) {
// having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
$ttl = self::DEFAULT_TTL;
}
$ttl = min($ttl, self::MAX_TTL);
return $this->getCache()->setex($this->getPrefix() . $key, $ttl, $value);
}

public function hasKey($key) {
Expand Down Expand Up @@ -117,11 +121,14 @@ public function clear($prefix = '') {
*/
public function add($key, $value, $ttl = 0) {
$value = self::encodeValue($value);
if ($ttl === 0) {
// having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
$ttl = self::DEFAULT_TTL;
}
$ttl = min($ttl, self::MAX_TTL);

$args = ['nx'];
if ($ttl !== 0 && is_int($ttl)) {
$args['ex'] = $ttl;
}
$args['ex'] = $ttl;

return $this->getCache()->set($this->getPrefix() . $key, $value, $args);
}
Expand Down Expand Up @@ -178,6 +185,11 @@ public function cad($key, $old) {
}

public function setTTL($key, $ttl) {
if ($ttl === 0) {
// having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
$ttl = self::DEFAULT_TTL;
}
$ttl = min($ttl, self::MAX_TTL);
$this->getCache()->expire($this->getPrefix() . $key, $ttl);
}

Expand Down

0 comments on commit b27b5ed

Please sign in to comment.