From b25713d6fe6258cd181eb996a2b87e41d57baad1 Mon Sep 17 00:00:00 2001 From: meirzamoodle Date: Wed, 19 Jun 2024 13:30:37 +0700 Subject: [PATCH] MDL-75864 cache: Change key prefix in cache_cron_task Currently, the cache_cron_task is set to look for 'sess_' as a key prefix, which is not used in any code. As a result, sessions that have exceeded the timeout are never deleted. The proposed patch involves changing the prefix to the LASTACCESS key prefix and fixing the return value of get_many in the Redis cache so that it can return the required keys. Co-authored-by: Renaud Lemaire --- cache/classes/helper.php | 25 +++++++++++++++++-------- cache/stores/redis/lib.php | 2 +- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/cache/classes/helper.php b/cache/classes/helper.php index b3a5d083d21..7eed4ceedb6 100644 --- a/cache/classes/helper.php +++ b/cache/classes/helper.php @@ -759,18 +759,27 @@ class cache_helper { debugging('Cache stores used for session definitions should ideally be searchable.', DEBUG_DEVELOPER); continue; } - // Get all of the keys. - $keys = $store->find_by_prefix(cache_session::KEY_PREFIX); - $todelete = array(); + // Get all of the last access keys. + $keys = $store->find_by_prefix(cache_session::LASTACCESS); + $todelete = []; foreach ($store->get_many($keys) as $key => $value) { - if (strpos($key, cache_session::KEY_PREFIX) !== 0 || !is_array($value) || !isset($value['lastaccess'])) { - continue; + $expiresvalue = 0; + if ($value instanceof cache_ttl_wrapper) { + $expiresvalue = $value->data; + } else if ($value instanceof cache_cached_object) { + $expiresvalue = $value->restore_object(); + } else { + $expiresvalue = $value; } - if ((int)$value['lastaccess'] < $purgetime || true) { - $todelete[] = $key; + $expires = (int) $expiresvalue; + + if ($expires > 0 && $expires < $purgetime) { + $prefix = substr($key, strlen(cache_session::LASTACCESS)); + $foundbyprefix = $store->find_by_prefix($prefix); + $todelete = array_merge($todelete, [$key], $foundbyprefix); } } - if (count($todelete)) { + if ($todelete) { $outcome = (int)$store->delete_many($todelete); if ($output) { $strdef = s($definition->get_id()); diff --git a/cache/stores/redis/lib.php b/cache/stores/redis/lib.php index a3aea960d96..a084155bf81 100644 --- a/cache/stores/redis/lib.php +++ b/cache/stores/redis/lib.php @@ -355,7 +355,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_ * @return array An array of the values of the given keys. */ public function get_many($keys) { - $values = $this->redis->hMGet($this->hash, $keys); + $values = $this->redis->hMGet($this->hash, $keys) ?: []; if ($this->compressor == self::COMPRESSOR_NONE) { return $values;