Skip to content

Commit

Permalink
Fix conj keys TTL in Redis 7.x
Browse files Browse the repository at this point in the history
Closes #475
  • Loading branch information
Suor committed Jun 11, 2024
1 parent 0c8cdda commit 6e37725
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 10 deletions.
7 changes: 2 additions & 5 deletions cacheops/lua/cache_thing.lua
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,13 @@ 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_4
-- NOTE: we also can't use "EXPIRE conj_key timeout GT" because it will have no effect on
-- newly created and thus involatile conj keys.
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_4
end
end
7 changes: 2 additions & 5 deletions cacheops/lua/cache_thing_insideout.lua
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,14 @@ 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_4
-- NOTE: we also can't use "EXPIRE conj_key timeout GT" because it will have no effect on
-- newly created and thus involatile conj keys.
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_4
end

-- Write data to cache along with a checksum of the stamps to see if any of them changed
Expand Down
22 changes: 22 additions & 0 deletions tests/test_low_level.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import pytest

from cacheops.redis import redis_client

from .models import User
from .utils import BaseTestCase


@pytest.fixture()
def base(db):
case = BaseTestCase()
case.setUp()
yield
case.tearDown()


def test_ttl(base, django_assert_num_queries):
user = User.objects.create(username='Suor')
qs = User.objects.cache(timeout=100).filter(pk=user.pk)
list(qs)
assert 90 <= redis_client.ttl(qs._cache_key()) <= 100
assert redis_client.ttl(f'conj:auth_user:id={user.id}') > 100

0 comments on commit 6e37725

Please sign in to comment.