From eb8218b5fc602fa8d89a3fc4317eb9482f42b71d Mon Sep 17 00:00:00 2001 From: Alexander Schepanovski Date: Tue, 4 Apr 2023 17:56:02 +0700 Subject: [PATCH] Make it work with Redis 6.x and older again Fixes #449 --- cacheops/lua/cache_thing.lua | 10 ++++++++++ cacheops/lua/cache_thing_insideout.lua | 10 ++++++++++ cacheops/redis.py | 11 +++++++++++ 3 files changed, 31 insertions(+) diff --git a/cacheops/lua/cache_thing.lua b/cacheops/lua/cache_thing.lua index 8bf6995d..f4468f41 100644 --- a/cacheops/lua/cache_thing.lua +++ b/cacheops/lua/cache_thing.lua @@ -47,6 +47,16 @@ for db_table, disj in pairs(dnfs) do redis.call('sadd', conj_key, key) -- NOTE: an invalidator should live longer than any key it references. -- So we update its ttl on every key if needed. + -- REDIS_7 redis.call('expire', conj_key, timeout, 'gt') + -- /REDIS_7 + -- REDIS_6 + local conj_ttl = redis.call('ttl', conj_key) + if conj_ttl < timeout then + -- We set conj_key life with a margin over key life to call expire rarer + -- And add few extra seconds to be extra safe + redis.call('expire', conj_key, timeout * 2 + 10) + end + -- /REDIS_6 end end diff --git a/cacheops/lua/cache_thing_insideout.lua b/cacheops/lua/cache_thing_insideout.lua index d66f05a8..21f40820 100644 --- a/cacheops/lua/cache_thing_insideout.lua +++ b/cacheops/lua/cache_thing_insideout.lua @@ -19,7 +19,17 @@ for _, conj_key in ipairs(conj_keys) do table.insert(stamps, stamp) -- NOTE: an invalidator should live longer than any key it references. -- So we update its ttl on every key if needed. + -- REDIS_7 redis.call('expire', conj_key, timeout, 'gt') + -- /REDIS_7 + -- REDIS_6 + local conj_ttl = redis.call('ttl', conj_key) + if conj_ttl < timeout then + -- We set conj_key life with a margin over key life to call expire rarer + -- And add few extra seconds to be extra safe + redis.call('expire', conj_key, timeout * 2 + 10) + end + -- /REDIS_6 end -- Write data to cache along with a checksum of the stamps to see if any of them changed diff --git a/cacheops/redis.py b/cacheops/redis.py index d4ee32c0..e9bc78ae 100644 --- a/cacheops/redis.py +++ b/cacheops/redis.py @@ -54,6 +54,7 @@ def redis_client(): ### Lua script loader import os.path +import re @memoize @@ -61,4 +62,14 @@ def load_script(name): filename = os.path.join(os.path.dirname(__file__), 'lua/%s.lua' % name) with open(filename) as f: code = f.read() + if is_redis_7(): + code = re.sub(r'REDIS_6.*?/REDIS_6', '', code, flags=re.S) + else: + code = re.sub(r'REDIS_7.*?/REDIS_7', '', code, flags=re.S) return redis_client.register_script(code) + + +@memoize +def is_redis_7(): + redis_version = redis_client.info('server')['redis_version'] + return int(redis_version.split('.')[0]) >= 7