Skip to content

Fixed Redis connectivity problems number one and two #338

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
41 changes: 31 additions & 10 deletions cashews/backends/redis/backend.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import logging
from typing import Any, AsyncIterator, Iterable, Mapping

from redis.asyncio import BlockingConnectionPool
Expand All @@ -10,7 +11,7 @@
from cashews.backends.interface import Backend
from cashews.serialize import DEFAULT_SERIALIZER, Serializer

from .client import Redis, SafePipeline, SafeRedis
from .client import NoScriptError, Redis, SafePipeline, SafeRedis

_UNLOCK = """
if redis.call("GET", KEYS[1]) == ARGV[1] then
Expand Down Expand Up @@ -42,6 +43,8 @@
# pylint: disable=arguments-differ
# pylint: disable=abstract-method

logger = logging.getLogger(__name__)


class _Redis(Backend):
_client: Redis | SafeRedis
Expand Down Expand Up @@ -151,9 +154,15 @@ async def is_locked(
return True

async def unlock(self, key: Key, value: Value) -> bool:
if "UNLOCK" not in self._sha:
self._sha["UNLOCK"] = await self._client.script_load(_UNLOCK.replace("\n", " "))
return await self._client.evalsha(self._sha["UNLOCK"], 1, key, value)
for _ in range(2):
if self._sha.get("UNLOCK") is None:
self._sha["UNLOCK"] = await self._client.script_load(_UNLOCK.replace("\n", " "))
try:
return await self._client.evalsha(self._sha["UNLOCK"], 1, key, value)
except NoScriptError as e:
save_e = e
self._sha["UNLOCK"] = None
logger.error("redis: can not execute command: EVALSHA", exc_info=save_e)

async def delete(self, key: Key) -> bool:
try:
Expand Down Expand Up @@ -237,11 +246,17 @@ async def _transform_value(self, key: Key, value: bytes | None, default: Value |
async def incr(self, key: Key, value: int = 1, expire: float | None = None) -> int:
if not expire:
return await self._client.incr(key, amount=value)
if "INCR_EXPIRE" not in self._sha:
self._sha["INCR_EXPIRE"] = await self._client.script_load(_INCR_EXPIRE.replace("\n", " "))
expire = expire or 0
expire = int(expire * 1000)
return await self._client.evalsha(self._sha["INCR_EXPIRE"], 1, key, value, expire)
for _ in range(2):
if self._sha.get("INCR_EXPIRE") is None:
self._sha["INCR_EXPIRE"] = await self._client.script_load(_INCR_EXPIRE.replace("\n", " "))
try:
return await self._client.evalsha(self._sha["INCR_EXPIRE"], 1, key, value, expire)
except NoScriptError as e:
save_e = e
self._sha["INCR_EXPIRE"] = None
logger.error("redis: can not execute command: EVALSHA", exc_info=save_e)

async def get_bits(self, key: Key, *indexes: int, size: int = 1) -> tuple[int, ...]:
"""
Expand Down Expand Up @@ -282,9 +297,15 @@ async def slice_incr(
) -> int:
expire = expire or 0
expire = int(expire * 1000)
if "INCR_SLICE" not in self._sha:
self._sha["INCR_SLICE"] = await self._client.script_load(_INCR_SLICE.replace("\n", " "))
return await self._client.evalsha(self._sha["INCR_SLICE"], 1, key, start, end, maxvalue, expire)
for _ in range(2):
if self._sha.get("INCR_SLICE") is None:
self._sha["INCR_SLICE"] = await self._client.script_load(_INCR_SLICE.replace("\n", " "))
try:
return await self._client.evalsha(self._sha["INCR_SLICE"], 1, key, start, end, maxvalue, expire)
except NoScriptError as e:
save_e = e
self._sha["INCR_SLICE"] = None
logger.error("redis: can not execute command: EVALSHA", exc_info=save_e)

async def set_add(self, key: Key, *values: str, expire: float | None = None):
if expire is None:
Expand Down
4 changes: 3 additions & 1 deletion cashews/backends/redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from redis.asyncio import Redis as _Redis
from redis.asyncio.client import Pipeline
from redis.exceptions import RedisError as RedisConnectionError
from redis.exceptions import NoScriptError, RedisError as RedisConnectionError

from cashews.exceptions import CacheBackendInteractionError

Expand All @@ -29,6 +29,8 @@ class SafeRedis(_Redis):
async def execute_command(self, command, *args: Any, **kwargs: Any):
try:
return await super().execute_command(command, *args, **kwargs)
except NoScriptError:
raise
except (
RedisConnectionError,
socket.gaierror,
Expand Down