You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import functools
  2. import logging
  3. from collections.abc import Callable
  4. from typing import Any, Union
  5. import redis
  6. from redis import RedisError
  7. from redis.cache import CacheConfig
  8. from redis.cluster import ClusterNode, RedisCluster
  9. from redis.connection import Connection, SSLConnection
  10. from redis.sentinel import Sentinel
  11. from configs import dify_config
  12. from dify_app import DifyApp
  13. logger = logging.getLogger(__name__)
  14. class RedisClientWrapper:
  15. """
  16. A wrapper class for the Redis client that addresses the issue where the global
  17. `redis_client` variable cannot be updated when a new Redis instance is returned
  18. by Sentinel.
  19. This class allows for deferred initialization of the Redis client, enabling the
  20. client to be re-initialized with a new instance when necessary. This is particularly
  21. useful in scenarios where the Redis instance may change dynamically, such as during
  22. a failover in a Sentinel-managed Redis setup.
  23. Attributes:
  24. _client (redis.Redis): The actual Redis client instance. It remains None until
  25. initialized with the `initialize` method.
  26. Methods:
  27. initialize(client): Initializes the Redis client if it hasn't been initialized already.
  28. __getattr__(item): Delegates attribute access to the Redis client, raising an error
  29. if the client is not initialized.
  30. """
  31. def __init__(self):
  32. self._client = None
  33. def initialize(self, client):
  34. if self._client is None:
  35. self._client = client
  36. def __getattr__(self, item):
  37. if self._client is None:
  38. raise RuntimeError("Redis client is not initialized. Call init_app first.")
  39. return getattr(self._client, item)
  40. redis_client = RedisClientWrapper()
  41. def init_app(app: DifyApp):
  42. global redis_client
  43. connection_class: type[Union[Connection, SSLConnection]] = Connection
  44. if dify_config.REDIS_USE_SSL:
  45. connection_class = SSLConnection
  46. resp_protocol = dify_config.REDIS_SERIALIZATION_PROTOCOL
  47. if dify_config.REDIS_ENABLE_CLIENT_SIDE_CACHE:
  48. if resp_protocol >= 3:
  49. clientside_cache_config = CacheConfig()
  50. else:
  51. raise ValueError("Client side cache is only supported in RESP3")
  52. else:
  53. clientside_cache_config = None
  54. redis_params: dict[str, Any] = {
  55. "username": dify_config.REDIS_USERNAME,
  56. "password": dify_config.REDIS_PASSWORD or None, # Temporary fix for empty password
  57. "db": dify_config.REDIS_DB,
  58. "encoding": "utf-8",
  59. "encoding_errors": "strict",
  60. "decode_responses": False,
  61. "protocol": resp_protocol,
  62. "cache_config": clientside_cache_config,
  63. }
  64. if dify_config.REDIS_USE_SENTINEL:
  65. assert dify_config.REDIS_SENTINELS is not None, "REDIS_SENTINELS must be set when REDIS_USE_SENTINEL is True"
  66. sentinel_hosts = [
  67. (node.split(":")[0], int(node.split(":")[1])) for node in dify_config.REDIS_SENTINELS.split(",")
  68. ]
  69. sentinel = Sentinel(
  70. sentinel_hosts,
  71. sentinel_kwargs={
  72. "socket_timeout": dify_config.REDIS_SENTINEL_SOCKET_TIMEOUT,
  73. "username": dify_config.REDIS_SENTINEL_USERNAME,
  74. "password": dify_config.REDIS_SENTINEL_PASSWORD,
  75. },
  76. )
  77. master = sentinel.master_for(dify_config.REDIS_SENTINEL_SERVICE_NAME, **redis_params)
  78. redis_client.initialize(master)
  79. elif dify_config.REDIS_USE_CLUSTERS:
  80. assert dify_config.REDIS_CLUSTERS is not None, "REDIS_CLUSTERS must be set when REDIS_USE_CLUSTERS is True"
  81. nodes = [
  82. ClusterNode(host=node.split(":")[0], port=int(node.split(":")[1]))
  83. for node in dify_config.REDIS_CLUSTERS.split(",")
  84. ]
  85. redis_client.initialize(
  86. RedisCluster(
  87. startup_nodes=nodes,
  88. password=dify_config.REDIS_CLUSTERS_PASSWORD,
  89. protocol=resp_protocol,
  90. cache_config=clientside_cache_config,
  91. )
  92. )
  93. else:
  94. redis_params.update(
  95. {
  96. "host": dify_config.REDIS_HOST,
  97. "port": dify_config.REDIS_PORT,
  98. "connection_class": connection_class,
  99. "protocol": resp_protocol,
  100. "cache_config": clientside_cache_config,
  101. }
  102. )
  103. pool = redis.ConnectionPool(**redis_params)
  104. redis_client.initialize(redis.Redis(connection_pool=pool))
  105. app.extensions["redis"] = redis_client
  106. def redis_fallback(default_return: Any = None):
  107. """
  108. decorator to handle Redis operation exceptions and return a default value when Redis is unavailable.
  109. Args:
  110. default_return: The value to return when a Redis operation fails. Defaults to None.
  111. """
  112. def decorator(func: Callable):
  113. @functools.wraps(func)
  114. def wrapper(*args, **kwargs):
  115. try:
  116. return func(*args, **kwargs)
  117. except RedisError as e:
  118. logger.warning(f"Redis operation failed in {func.__name__}: {str(e)}", exc_info=True)
  119. return default_return
  120. return wrapper
  121. return decorator