redis.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. from __future__ import annotations
  2. import time
  3. from typing import TYPE_CHECKING, cast
  4. from deprecated.sphinx import versionchanged
  5. from packaging.version import Version
  6. from limits.typing import Literal, RedisClient
  7. from ..util import get_package_data
  8. from .base import MovingWindowSupport, SlidingWindowCounterSupport, Storage
  9. if TYPE_CHECKING:
  10. import redis
  11. @versionchanged(
  12. version="4.3",
  13. reason=(
  14. "Added support for using the redis client from :pypi:`valkey`"
  15. " if :paramref:`uri` has the ``valkey://`` schema"
  16. ),
  17. )
  18. class RedisStorage(Storage, MovingWindowSupport, SlidingWindowCounterSupport):
  19. """
  20. Rate limit storage with redis as backend.
  21. Depends on :pypi:`redis` (or :pypi:`valkey` if :paramref:`uri` starts with
  22. ``valkey://``)
  23. """
  24. STORAGE_SCHEME = [
  25. "redis",
  26. "rediss",
  27. "redis+unix",
  28. "valkey",
  29. "valkeys",
  30. "valkey+unix",
  31. ]
  32. """The storage scheme for redis"""
  33. DEPENDENCIES = {"redis": Version("3.0"), "valkey": Version("6.0")}
  34. RES_DIR = "resources/redis/lua_scripts"
  35. SCRIPT_MOVING_WINDOW = get_package_data(f"{RES_DIR}/moving_window.lua")
  36. SCRIPT_ACQUIRE_MOVING_WINDOW = get_package_data(
  37. f"{RES_DIR}/acquire_moving_window.lua"
  38. )
  39. SCRIPT_CLEAR_KEYS = get_package_data(f"{RES_DIR}/clear_keys.lua")
  40. SCRIPT_INCR_EXPIRE = get_package_data(f"{RES_DIR}/incr_expire.lua")
  41. SCRIPT_SLIDING_WINDOW = get_package_data(f"{RES_DIR}/sliding_window.lua")
  42. SCRIPT_ACQUIRE_SLIDING_WINDOW = get_package_data(
  43. f"{RES_DIR}/acquire_sliding_window.lua"
  44. )
  45. lua_moving_window: redis.commands.core.Script
  46. lua_acquire_moving_window: redis.commands.core.Script
  47. lua_sliding_window: redis.commands.core.Script
  48. lua_acquire_sliding_window: redis.commands.core.Script
  49. PREFIX = "LIMITS"
  50. target_server: Literal["redis", "valkey"]
  51. def __init__(
  52. self,
  53. uri: str,
  54. connection_pool: redis.connection.ConnectionPool | None = None,
  55. wrap_exceptions: bool = False,
  56. **options: float | str | bool,
  57. ) -> None:
  58. """
  59. :param uri: uri of the form ``redis://[:password]@host:port``,
  60. ``redis://[:password]@host:port/db``,
  61. ``rediss://[:password]@host:port``, ``redis+unix:///path/to/sock`` etc.
  62. This uri is passed directly to :func:`redis.from_url` except for the
  63. case of ``redis+unix://`` where it is replaced with ``unix://``.
  64. If the uri scheme is ``valkey`` the implementation used will be from
  65. :pypi:`valkey`.
  66. :param connection_pool: if provided, the redis client is initialized with
  67. the connection pool and any other params passed as :paramref:`options`
  68. :param wrap_exceptions: Whether to wrap storage exceptions in
  69. :exc:`limits.errors.StorageError` before raising it.
  70. :param options: all remaining keyword arguments are passed
  71. directly to the constructor of :class:`redis.Redis`
  72. :raise ConfigurationError: when the :pypi:`redis` library is not available
  73. """
  74. super().__init__(uri, wrap_exceptions=wrap_exceptions, **options)
  75. self.target_server = "valkey" if uri.startswith("valkey") else "redis"
  76. self.dependency = self.dependencies[self.target_server].module
  77. uri = uri.replace(f"{self.target_server}+unix", "unix")
  78. if not connection_pool:
  79. self.storage = self.dependency.from_url(uri, **options)
  80. else:
  81. if self.target_server == "redis":
  82. self.storage = self.dependency.Redis(
  83. connection_pool=connection_pool, **options
  84. )
  85. else:
  86. self.storage = self.dependency.Valkey(
  87. connection_pool=connection_pool, **options
  88. )
  89. self.initialize_storage(uri)
  90. @property
  91. def base_exceptions(
  92. self,
  93. ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover
  94. return ( # type: ignore[no-any-return]
  95. self.dependency.RedisError
  96. if self.target_server == "redis"
  97. else self.dependency.ValkeyError
  98. )
  99. def initialize_storage(self, _uri: str) -> None:
  100. self.lua_moving_window = self.get_connection().register_script(
  101. self.SCRIPT_MOVING_WINDOW
  102. )
  103. self.lua_acquire_moving_window = self.get_connection().register_script(
  104. self.SCRIPT_ACQUIRE_MOVING_WINDOW
  105. )
  106. self.lua_clear_keys = self.get_connection().register_script(
  107. self.SCRIPT_CLEAR_KEYS
  108. )
  109. self.lua_incr_expire = self.get_connection().register_script(
  110. self.SCRIPT_INCR_EXPIRE
  111. )
  112. self.lua_sliding_window = self.get_connection().register_script(
  113. self.SCRIPT_SLIDING_WINDOW
  114. )
  115. self.lua_acquire_sliding_window = self.get_connection().register_script(
  116. self.SCRIPT_ACQUIRE_SLIDING_WINDOW
  117. )
  118. def get_connection(self, readonly: bool = False) -> RedisClient:
  119. return cast(RedisClient, self.storage)
  120. def _current_window_key(self, key: str) -> str:
  121. """
  122. Return the current window's storage key (Sliding window strategy)
  123. Contrary to other strategies that have one key per rate limit item,
  124. this strategy has two keys per rate limit item than must be on the same machine.
  125. To keep the current key and the previous key on the same Redis cluster node,
  126. curly braces are added.
  127. Eg: "{constructed_key}"
  128. """
  129. return f"{{{key}}}"
  130. def _previous_window_key(self, key: str) -> str:
  131. """
  132. Return the previous window's storage key (Sliding window strategy).
  133. Curvy braces are added on the common pattern with the current window's key,
  134. so the current and the previous key are stored on the same Redis cluster node.
  135. Eg: "{constructed_key}/-1"
  136. """
  137. return f"{self._current_window_key(key)}/-1"
  138. def prefixed_key(self, key: str) -> str:
  139. return f"{self.PREFIX}:{key}"
  140. def get_moving_window(self, key: str, limit: int, expiry: int) -> tuple[float, int]:
  141. """
  142. returns the starting point and the number of entries in the moving
  143. window
  144. :param key: rate limit key
  145. :param expiry: expiry of entry
  146. :return: (start of window, number of acquired entries)
  147. """
  148. key = self.prefixed_key(key)
  149. timestamp = time.time()
  150. if window := self.lua_moving_window([key], [timestamp - expiry, limit]):
  151. return float(window[0]), window[1]
  152. return timestamp, 0
  153. def get_sliding_window(
  154. self, key: str, expiry: int
  155. ) -> tuple[int, float, int, float]:
  156. previous_key = self.prefixed_key(self._previous_window_key(key))
  157. current_key = self.prefixed_key(self._current_window_key(key))
  158. if window := self.lua_sliding_window([previous_key, current_key], [expiry]):
  159. return (
  160. int(window[0] or 0),
  161. max(0, float(window[1] or 0)) / 1000,
  162. int(window[2] or 0),
  163. max(0, float(window[3] or 0)) / 1000,
  164. )
  165. return 0, 0.0, 0, 0.0
  166. def incr(
  167. self,
  168. key: str,
  169. expiry: int,
  170. elastic_expiry: bool = False,
  171. amount: int = 1,
  172. ) -> int:
  173. """
  174. increments the counter for a given rate limit key
  175. :param key: the key to increment
  176. :param expiry: amount in seconds for the key to expire in
  177. :param amount: the number to increment by
  178. """
  179. key = self.prefixed_key(key)
  180. if elastic_expiry:
  181. value = self.get_connection().incrby(key, amount)
  182. self.get_connection().expire(key, expiry)
  183. return value
  184. else:
  185. return int(self.lua_incr_expire([key], [expiry, amount]))
  186. def get(self, key: str) -> int:
  187. """
  188. :param key: the key to get the counter value for
  189. """
  190. key = self.prefixed_key(key)
  191. return int(self.get_connection(True).get(key) or 0)
  192. def clear(self, key: str) -> None:
  193. """
  194. :param key: the key to clear rate limits for
  195. """
  196. key = self.prefixed_key(key)
  197. self.get_connection().delete(key)
  198. def acquire_entry(
  199. self,
  200. key: str,
  201. limit: int,
  202. expiry: int,
  203. amount: int = 1,
  204. ) -> bool:
  205. """
  206. :param key: rate limit key to acquire an entry in
  207. :param limit: amount of entries allowed
  208. :param expiry: expiry of the entry
  209. :param amount: the number of entries to acquire
  210. """
  211. key = self.prefixed_key(key)
  212. timestamp = time.time()
  213. acquired = self.lua_acquire_moving_window(
  214. [key], [timestamp, limit, expiry, amount]
  215. )
  216. return bool(acquired)
  217. def acquire_sliding_window_entry(
  218. self,
  219. key: str,
  220. limit: int,
  221. expiry: int,
  222. amount: int = 1,
  223. ) -> bool:
  224. """
  225. Acquire an entry. Shift the current window to the previous window if it expired.
  226. :param key: rate limit key to acquire an entry in
  227. :param limit: amount of entries allowed
  228. :param expiry: expiry of the entry
  229. :param amount: the number of entries to acquire
  230. """
  231. previous_key = self.prefixed_key(self._previous_window_key(key))
  232. current_key = self.prefixed_key(self._current_window_key(key))
  233. acquired = self.lua_acquire_sliding_window(
  234. [previous_key, current_key], [limit, expiry, amount]
  235. )
  236. return bool(acquired)
  237. def get_expiry(self, key: str) -> float:
  238. """
  239. :param key: the key to get the expiry for
  240. """
  241. key = self.prefixed_key(key)
  242. return max(self.get_connection(True).ttl(key), 0) + time.time()
  243. def check(self) -> bool:
  244. """
  245. check if storage is healthy
  246. """
  247. try:
  248. return self.get_connection().ping()
  249. except: # noqa
  250. return False
  251. def reset(self) -> int | None:
  252. """
  253. This function calls a Lua Script to delete keys prefixed with
  254. ``self.PREFIX`` in blocks of 5000.
  255. .. warning::
  256. This operation was designed to be fast, but was not tested
  257. on a large production based system. Be careful with its usage as it
  258. could be slow on very large data sets.
  259. """
  260. prefix = self.prefixed_key("*")
  261. return int(self.lua_clear_keys([prefix]))