Source code for smarter.lib.cache.client

"""
The django-redis client of Smarter's caches, which stops waiting for a Redis that can't be reached.

When Redis can't be reached, the callers on a request's path already do without the cache (issues #941, #1052,
#1091). But each cache call first waits out a socket timeout, two seconds to connect or five for a command, and a
request makes about 25 of them, one after another. While Redis drops packets, e.g. while its pod moves to another
node, each request then takes minutes (issue #1096).

:class:`CircuitBreakerClient` is django-redis's ``DefaultClient`` with a circuit breaker for each Redis server, shared
by every thread of the process:

1. **Closed.** Every command goes to Redis. When one fails because Redis can't be reached (a connection error or a
   timeout, see :func:`is_unreachable`), the breaker opens, and logs one warning line.
2. **Open.** For ``CIRCUIT_BREAKER_SECONDS``, every command fails at once, with no network round trip, raising
   the same ``ConnectionInterrupted`` as an outage does, so its callers degrade as they already do.
3. **Half open.** After that, one command is let through to try Redis. If it succeeds, the breaker closes, and logs
   one line. If it fails, the breaker stays open for another interval. The other commands still fail at once
   while the trial is in flight.

An error that Redis answers with, e.g. a ``ResponseError`` for a wrong type, means that Redis can be reached, so it
doesn't open the breaker.

``CACHE_OPTIONS`` in :mod:`smarter.settings.base` names this class as each cache's ``CLIENT_CLASS``, so every user of
the ``default`` and ``sessions`` caches gets it: ``@cache_results``, ``lazy_cache``, waffle's cache, the rate limits
and the session store. Celery's broker is usually the same server, and
:func:`smarter.lib.celery_conf.publish.delay_through_breaker` queues a task through the same breaker, with
:meth:`CircuitBreaker.call`.
"""

# The standard library's logging, not smarter.lib.logging: Django can open its cache while smarter.lib.logging is
# still initializing (e.g. to read a waffle switch), so this module can't take a logger from it.
import contextvars
import functools
import logging
import os
import threading
import time
from collections.abc import Callable
from typing import Any, Optional, TypeVar, cast
from urllib.parse import urlsplit

from django_redis.client import DefaultClient
from django_redis.exceptions import ConnectionInterrupted
from kombu.exceptions import OperationalError as KombuOperationalError
from redis.exceptions import ConnectionError as RedisConnectionError
from redis.exceptions import RedisError
from redis.exceptions import TimeoutError as RedisTimeoutError

from smarter.lib.logging.waffle_switched_logger import WaffleSwitchedLoggerWrapper

logger = WaffleSwitchedLoggerWrapper(logging.getLogger(__name__))

DEFAULT_CIRCUIT_BREAKER_SECONDS = 5.0
"""Seconds that a breaker stays open, when the cache's OPTIONS have no ``CIRCUIT_BREAKER_SECONDS``."""

UNREACHABLE_EXCEPTIONS: tuple[type[BaseException], ...] = (
    RedisConnectionError,
    RedisTimeoutError,
    TimeoutError,
    KombuOperationalError,
)
"""
The errors that mean Redis can't be reached: a refused or dropped connection, or a timeout.

Kombu raises ``OperationalError`` when it can't publish a Celery task to the broker for want of a connection.
"""

REDIS_ANSWERED_EXCEPTIONS: tuple[type[BaseException], ...] = (ConnectionInterrupted, RedisError)
"""The other errors of a command, which Redis answered with, e.g. a ``ResponseError``: Redis can be reached."""

GUARDED_COMMANDS: tuple[str, ...] = (
    "set",
    "incr_version",
    "add",
    "get",
    "persist",
    "expire",
    "pexpire",
    "pexpire_at",
    "expire_at",
    "delete",
    "delete_pattern",
    "delete_many",
    "clear",
    "get_many",
    "set_many",
    "incr",
    "decr",
    "ttl",
    "pttl",
    "has_key",
    "keys",
    "sadd",
    "scard",
    "sdiff",
    "sdiffstore",
    "sinter",
    "sinterstore",
    "smismember",
    "sismember",
    "smembers",
    "smove",
    "spop",
    "srandmember",
    "srem",
    "sscan",
    "sunion",
    "sunionstore",
    "touch",
    "hset",
    "hdel",
    "hlen",
    "hkeys",
    "hexists",
    "zadd",
    "zcard",
    "zcount",
    "zincrby",
    "zpopmax",
    "zpopmin",
    "zrange",
    "zrangebyscore",
    "zrank",
    "zrem",
    "zremrangebyscore",
    "zrevrange",
    "zrevrangebyscore",
    "zscore",
)
"""The ``DefaultClient`` methods that send a command to Redis, each of which goes through the breaker."""

UNGUARDED_COMMANDS: tuple[str, ...] = ("lock", "iter_keys", "sscan_iter")
"""
The ``DefaultClient`` methods that reach Redis only later, and so bypass the breaker.

``lock()`` returns a lock that talks to Redis when it is acquired, and the two ``*_iter()`` methods are generators that
talk to Redis as they are iterated. Nothing on a request's path uses them.
"""

_inside_guarded_call: contextvars.ContextVar[bool] = contextvars.ContextVar("_inside_guarded_call", default=False)
"""
Whether this thread or task is already inside a guarded command.

Some commands call others, e.g. ``add()`` calls ``set()``. The inner call belongs to the outer one, so it passes
through, rather than counting twice or being refused as a second trial while the breaker is half open.
"""

CallableType = TypeVar("CallableType", bound=Callable[..., Any])
ResultType = TypeVar("ResultType")


MAX_CAUSE_DEPTH = 5
"""How many ``__cause__`` links :func:`is_unreachable` follows, e.g. kombu's error, then redis-py's."""


[docs] def is_unreachable(error: BaseException) -> bool: """ Tell whether an error of a command means that Redis can't be reached. Libraries wrap redis-py's errors: django-redis in ``ConnectionInterrupted``, kombu, which publishes Celery's tasks, in its ``OperationalError``, each with the original error as its ``__cause__``. So the error and its causes decide. :param error: The error that a command raised. :returns: True for a connection error or a timeout, False for anything else, e.g. an error that Redis answered. """ current: Optional[BaseException] = error depth = 0 while current is not None and depth <= MAX_CAUSE_DEPTH: if isinstance(current, UNREACHABLE_EXCEPTIONS): return True current = current.__cause__ depth += 1 return False
[docs] def circuit_open_error() -> ConnectionInterrupted: """ Return the error that a command raises at once while its breaker is open. It is the error that django-redis raises during an outage, a ``ConnectionInterrupted`` caused by a redis-py ``ConnectionError``. Django-redis's cache re-raises the cause, so the callers that catch :data:`smarter.lib.cache.exceptions.CACHE_EXCEPTIONS` catch it either way. :returns: The error. """ cause = RedisConnectionError("Redis can't be reached: the cache's circuit breaker is open") error = ConnectionInterrupted(connection=None) error.__cause__ = cause return error
[docs] class CircuitBreaker: """ The state of one Redis server, as seen by every thread of this process. :param name: What the log lines call the server, e.g. ``smarter-redis:6379``. Never a url, which may hold a password. :param open_seconds: Seconds to fail fast after a failure, before one command may try Redis again. """
[docs] def __init__(self, name: str, open_seconds: float) -> None: self.name = name self.open_seconds = open_seconds self.opened_at: Optional[float] = None """When the breaker last opened, by ``time.monotonic()``, or None while it is closed.""" self.first_opened_at: Optional[float] = None """When the outage began, for the line that closes the breaker.""" self.trial_in_flight = False """Whether a command is trying Redis while the breaker is half open.""" self._lock = threading.Lock()
@property def is_open(self) -> bool: """ Tell whether the breaker is open or half open. :returns: True if a command failed because Redis couldn't be reached, and none has succeeded since. """ return self.opened_at is not None
[docs] def allow(self) -> bool: """ Decide whether a command may go to Redis now. :returns: True while the breaker is closed, and for the one command that tries Redis once it has been open for ``open_seconds``. False for every other command while it is open. """ with self._lock: if self.opened_at is None: return True if self.trial_in_flight: return False open_for = time.monotonic() - self.opened_at if open_for < self.open_seconds: return False self.trial_in_flight = True return True
[docs] def record_success(self) -> None: """Close the breaker, if it was open, after a command reached Redis.""" with self._lock: self.trial_in_flight = False if self.opened_at is None: return outage_began = self.first_opened_at if outage_began is None: outage_began = self.opened_at outage_seconds = time.monotonic() - outage_began self.opened_at = None self.first_opened_at = None logger.info("Redis at %s answers again after %.1f seconds", self.name, outage_seconds)
[docs] def record_failure(self, error: BaseException) -> None: """ Open the breaker, or keep it open for another interval, after a command couldn't reach Redis. :param error: The error of the command, for the line that opens the breaker. """ now = time.monotonic() with self._lock: self.trial_in_flight = False was_open = self.opened_at is not None self.opened_at = now if not was_open: self.first_opened_at = now if was_open: logger.debug("Redis at %s still can't be reached: %s", self.name, error) return # one line, no traceback: Redis being away is an outage to report, not a bug to debug. logger.warning( "Redis at %s can't be reached, so its commands fail fast and it is retried every %s seconds: %s", self.name, self.open_seconds, error, )
[docs] def record_no_verdict(self) -> None: """Let another command try Redis, after the trial failed before it could tell, e.g. while pickling a value.""" with self._lock: self.trial_in_flight = False
[docs] def record_error(self, error: BaseException) -> None: """ Record what a command's error says about Redis. :param error: The error that the command raised. """ if is_unreachable(error): self.record_failure(error) return if isinstance(error, REDIS_ANSWERED_EXCEPTIONS): # Redis answered, e.g. with a ResponseError for a wrong type, so it can be reached. self.record_success() return # e.g. a value that can't be pickled, before anything was sent: no news about Redis. self.record_no_verdict()
[docs] def call(self, command: Callable[[], ResultType], open_error: Callable[[], BaseException]) -> ResultType: """ Run a command that talks to this Redis server, unless the breaker is open. :param command: The command, without arguments, e.g. ``functools.partial(task.delay, payload)``. :param open_error: Returns the error to raise at once while the breaker is open, e.g. :func:`circuit_open_error`. :returns: The command's result. :raises BaseException: ``open_error()`` while the breaker is open, or whatever the command raised. """ if not self.allow(): raise open_error() try: result = command() except BaseException as error: self.record_error(error) raise self.record_success() return result
_breakers: dict[str, CircuitBreaker] = {} """The breaker of each Redis server that this process has used, by :func:`server_name`.""" _breakers_lock = threading.Lock()
[docs] def server_name(location: str) -> str: """ Return the name of a Redis server, from a cache's ``LOCATION``, without its credentials or database. The ``default`` and ``sessions`` caches are two databases of one server, so they share one breaker. :param location: A Redis url, e.g. ``redis://user:password@smarter-redis:6379/1``. :returns: Its host and port, e.g. ``smarter-redis:6379``, or a socket's path. """ parts = urlsplit(location) if parts.hostname is None: return parts.path if parts.port is None: return parts.hostname name = f"{parts.hostname}:{parts.port}" return name
[docs] def get_breaker(location: str, open_seconds: float) -> CircuitBreaker: """ Return the breaker of a Redis server, creating it on first use. :param location: The cache's ``LOCATION``, a Redis url. :param open_seconds: Seconds that a new breaker stays open after a failure. :returns: The breaker that every thread of this process shares for that server. """ name = server_name(location) with _breakers_lock: breaker = _breakers.get(name) if breaker is None: breaker = CircuitBreaker(name, open_seconds) _breakers[name] = breaker return breaker
[docs] def reset_breakers() -> None: """ Forget every breaker, e.g. in a process that was just forked, or between tests. A forked process, such as a Celery worker's child, starts with a copy of its parent's breakers, whose locks may have been held at the moment of the fork. """ global _breakers_lock # pylint: disable=global-statement _breakers_lock = threading.Lock() _breakers.clear()
os.register_at_fork(after_in_child=reset_breakers)
[docs] def guarded(method: CallableType) -> CallableType: """ Wrap a ``DefaultClient`` command so that it goes through the client's breaker. :param method: The command, e.g. ``DefaultClient.get``. :returns: The command, which raises :func:`circuit_open_error` at once while the breaker is open. """ @functools.wraps(method) def wrapper(self: "CircuitBreakerClient", *args: Any, **kwargs: Any) -> Any: if _inside_guarded_call.get(): return method(self, *args, **kwargs) command = functools.partial(method, self, *args, **kwargs) token = _inside_guarded_call.set(True) try: result = self.breaker.call(command, circuit_open_error) finally: _inside_guarded_call.reset(token) return result return cast(CallableType, wrapper)
[docs] class CircuitBreakerClient(DefaultClient): """ Django-redis's ``DefaultClient``, whose commands fail at once while Redis can't be reached. The breaker's interval is the cache's ``OPTIONS["CIRCUIT_BREAKER_SECONDS"]``, see :data:`smarter.settings.base.CACHE_CIRCUIT_BREAKER_SECONDS`. See the module's docstring for how the breaker works. """
[docs] def __init__(self, server, params: dict[str, Any], backend) -> None: super().__init__(server, params, backend) self.breaker_seconds = float(self._options.get("CIRCUIT_BREAKER_SECONDS", DEFAULT_CIRCUIT_BREAKER_SECONDS)) self.breaker_location = self._server[0]
@property def breaker(self) -> CircuitBreaker: """ Return the breaker of this cache's Redis server, shared with every other client of the same server. It is looked up on each command, rather than kept, so that :func:`reset_breakers`, after a fork or between tests, reaches the clients that already exist: Django keeps a cache client for each thread for as long as the thread lives. :returns: The breaker. """ breaker = get_breaker(self.breaker_location, self.breaker_seconds) return breaker
for _command_name in GUARDED_COMMANDS: _command = getattr(DefaultClient, _command_name) setattr(CircuitBreakerClient, _command_name, guarded(_command)) __all__ = [ "CircuitBreaker", "CircuitBreakerClient", "DEFAULT_CIRCUIT_BREAKER_SECONDS", "GUARDED_COMMANDS", "UNGUARDED_COMMANDS", "REDIS_ANSWERED_EXCEPTIONS", "UNREACHABLE_EXCEPTIONS", "circuit_open_error", "get_breaker", "guarded", "is_unreachable", "reset_breakers", "server_name", ]