limits 4.1__tar.gz → 4.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {limits-4.1 → limits-4.2}/HISTORY.rst +10 -0
- {limits-4.1 → limits-4.2}/PKG-INFO +1 -1
- {limits-4.1 → limits-4.2}/doc/source/async.rst +4 -1
- {limits-4.1 → limits-4.2}/doc/source/installation.rst +6 -0
- {limits-4.1 → limits-4.2}/doc/source/storage.rst +10 -0
- {limits-4.1 → limits-4.2}/limits/__init__.py +3 -1
- {limits-4.1 → limits-4.2}/limits/_version.py +4 -4
- {limits-4.1 → limits-4.2}/limits/aio/__init__.py +2 -0
- {limits-4.1 → limits-4.2}/limits/aio/storage/__init__.py +2 -0
- {limits-4.1 → limits-4.2}/limits/aio/storage/etcd.py +2 -0
- {limits-4.1 → limits-4.2}/limits/aio/storage/memcached.py +2 -0
- {limits-4.1 → limits-4.2}/limits/aio/storage/memory.py +2 -0
- limits-4.2/limits/aio/storage/redis/__init__.py +341 -0
- limits-4.2/limits/aio/storage/redis/bridge.py +121 -0
- limits-4.2/limits/aio/storage/redis/coredis.py +209 -0
- limits-4.2/limits/aio/storage/redis/redispy.py +257 -0
- {limits-4.1 → limits-4.2}/limits/aio/strategies.py +2 -0
- {limits-4.1 → limits-4.2}/limits/errors.py +2 -0
- {limits-4.1 → limits-4.2}/limits/storage/__init__.py +2 -0
- {limits-4.1 → limits-4.2}/limits/storage/etcd.py +2 -0
- {limits-4.1 → limits-4.2}/limits/storage/memcached.py +2 -0
- {limits-4.1 → limits-4.2}/limits/storage/memory.py +2 -0
- {limits-4.1 → limits-4.2}/limits/storage/redis_cluster.py +2 -0
- {limits-4.1 → limits-4.2}/limits/storage/redis_sentinel.py +2 -0
- {limits-4.1 → limits-4.2}/limits/strategies.py +2 -0
- {limits-4.1 → limits-4.2}/limits/typing.py +15 -7
- {limits-4.1 → limits-4.2}/limits/util.py +2 -0
- {limits-4.1 → limits-4.2}/limits.egg-info/PKG-INFO +1 -1
- {limits-4.1 → limits-4.2}/limits.egg-info/SOURCES.txt +4 -1
- limits-4.2/pyproject.toml +25 -0
- {limits-4.1 → limits-4.2}/setup.cfg +0 -8
- {limits-4.1 → limits-4.2}/tests/test_limit_granularities.py +2 -0
- {limits-4.1 → limits-4.2}/tests/test_limits.py +2 -0
- {limits-4.1 → limits-4.2}/tests/test_ratelimit_parser.py +2 -0
- {limits-4.1 → limits-4.2}/tests/test_storage.py +2 -0
- {limits-4.1 → limits-4.2}/tests/test_strategy.py +2 -0
- {limits-4.1 → limits-4.2}/tests/test_utils.py +2 -0
- {limits-4.1 → limits-4.2}/versioneer.py +430 -342
- limits-4.1/limits/aio/storage/redis.py +0 -555
- limits-4.1/pyproject.toml +0 -10
- {limits-4.1 → limits-4.2}/CLASSIFIERS +0 -0
- {limits-4.1 → limits-4.2}/CONTRIBUTIONS.rst +0 -0
- {limits-4.1 → limits-4.2}/LICENSE.txt +0 -0
- {limits-4.1 → limits-4.2}/MANIFEST.in +0 -0
- {limits-4.1 → limits-4.2}/README.rst +0 -0
- {limits-4.1 → limits-4.2}/doc/Makefile +0 -0
- {limits-4.1 → limits-4.2}/doc/source/_static/custom.css +0 -0
- {limits-4.1 → limits-4.2}/doc/source/api.rst +0 -0
- {limits-4.1 → limits-4.2}/doc/source/changelog.rst +0 -0
- {limits-4.1 → limits-4.2}/doc/source/conf.py +0 -0
- {limits-4.1 → limits-4.2}/doc/source/custom-storage.rst +0 -0
- {limits-4.1 → limits-4.2}/doc/source/index.rst +0 -0
- {limits-4.1 → limits-4.2}/doc/source/quickstart.rst +0 -0
- {limits-4.1 → limits-4.2}/doc/source/strategies.rst +0 -0
- {limits-4.1 → limits-4.2}/doc/source/theme_config.py +0 -0
- {limits-4.1 → limits-4.2}/limits/aio/storage/base.py +0 -0
- {limits-4.1 → limits-4.2}/limits/aio/storage/mongodb.py +0 -0
- {limits-4.1 → limits-4.2}/limits/limits.py +0 -0
- {limits-4.1 → limits-4.2}/limits/py.typed +0 -0
- {limits-4.1 → limits-4.2}/limits/resources/redis/lua_scripts/acquire_moving_window.lua +0 -0
- {limits-4.1 → limits-4.2}/limits/resources/redis/lua_scripts/acquire_sliding_window.lua +0 -0
- {limits-4.1 → limits-4.2}/limits/resources/redis/lua_scripts/clear_keys.lua +0 -0
- {limits-4.1 → limits-4.2}/limits/resources/redis/lua_scripts/incr_expire.lua +0 -0
- {limits-4.1 → limits-4.2}/limits/resources/redis/lua_scripts/moving_window.lua +0 -0
- {limits-4.1 → limits-4.2}/limits/resources/redis/lua_scripts/sliding_window.lua +0 -0
- {limits-4.1 → limits-4.2}/limits/storage/base.py +0 -0
- {limits-4.1 → limits-4.2}/limits/storage/mongodb.py +0 -0
- {limits-4.1 → limits-4.2}/limits/storage/redis.py +0 -0
- {limits-4.1 → limits-4.2}/limits/storage/registry.py +0 -0
- {limits-4.1 → limits-4.2}/limits/version.py +0 -0
- {limits-4.1 → limits-4.2}/limits.egg-info/dependency_links.txt +0 -0
- {limits-4.1 → limits-4.2}/limits.egg-info/not-zip-safe +0 -0
- {limits-4.1 → limits-4.2}/limits.egg-info/requires.txt +0 -0
- {limits-4.1 → limits-4.2}/limits.egg-info/top_level.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/ci.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/dev.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/docs.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/main.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/async-etcd.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/async-memcached.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/async-mongodb.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/async-redis.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/etcd.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/memcached.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/mongodb.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/redis.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/storage/rediscluster.txt +0 -0
- {limits-4.1 → limits-4.2}/requirements/test.txt +0 -0
- {limits-4.1 → limits-4.2}/setup.py +0 -0
|
@@ -3,6 +3,15 @@
|
|
|
3
3
|
Changelog
|
|
4
4
|
=========
|
|
5
5
|
|
|
6
|
+
v4.2
|
|
7
|
+
----
|
|
8
|
+
Release Date: 2025-03-11
|
|
9
|
+
|
|
10
|
+
* Feature
|
|
11
|
+
|
|
12
|
+
* Add support for using ``redis-py`` instead of ``coredis``
|
|
13
|
+
which asyncio + redis storages
|
|
14
|
+
|
|
6
15
|
v4.1
|
|
7
16
|
----
|
|
8
17
|
Release Date: 2025-03-07
|
|
@@ -782,5 +791,6 @@ Release Date: 2015-01-08
|
|
|
782
791
|
|
|
783
792
|
|
|
784
793
|
|
|
794
|
+
|
|
785
795
|
|
|
786
796
|
|
|
@@ -10,7 +10,10 @@ A new namespace ``limits.aio`` is available which mirrors the original
|
|
|
10
10
|
The following async storage backends are implemented:
|
|
11
11
|
|
|
12
12
|
- In-Memory
|
|
13
|
-
- Redis (via `coredis <https://coredis.readthedocs.org>`_
|
|
13
|
+
- Redis (via `coredis <https://coredis.readthedocs.org>`_
|
|
14
|
+
or `redis-py <https://redis-py.readthedocs.io>`_. Refer to
|
|
15
|
+
:paramref:`limits.aio.storage.RedisStorage.implementation` for
|
|
16
|
+
details on selecting the dependency)
|
|
14
17
|
- Memcached (via `emcache <https://emcache.readthedocs.org>`_)
|
|
15
18
|
- MongoDB (via `motor <https://motor.readthedocs.org>`_)
|
|
16
19
|
- Etcd (via `aetcd <https://aetcd.readthedocs.org>`_)
|
|
@@ -79,6 +79,12 @@ along with the package using the following extras:
|
|
|
79
79
|
|
|
80
80
|
.. literalinclude:: ../../requirements/storage/async-redis.txt
|
|
81
81
|
|
|
82
|
+
.. versionadded:: 4.2
|
|
83
|
+
:pypi:`redis` if installed can be used instead of :pypi:`coredis` by setting
|
|
84
|
+
:paramref:`~limits.aio.storage.Redis.implementation` to ``redispy``.
|
|
85
|
+
See :class:`limits.aio.storage.RedisStorage` for more details.
|
|
86
|
+
|
|
87
|
+
|
|
82
88
|
.. tab:: Memcached
|
|
83
89
|
|
|
84
90
|
.. code:: console
|
|
@@ -31,6 +31,11 @@ the results in `github <https://github.com/alisaifee/limits/actions/workflows/co
|
|
|
31
31
|
|
|
32
32
|
.. literalinclude:: ../../requirements/storage/async-redis.txt
|
|
33
33
|
|
|
34
|
+
.. note::
|
|
35
|
+
.. versionadded:: 4.2
|
|
36
|
+
:pypi:`redis` can be used instead of :pypi:`coredis` by setting
|
|
37
|
+
:paramref:`limits.aio.storage.RedisStorage.implementation` to ``redispy``
|
|
38
|
+
|
|
34
39
|
`Redis <https://redis.io>`_
|
|
35
40
|
|
|
36
41
|
.. program-output:: bash -c "cat ../../.github/workflows/compatibility.yml | grep -o -P 'LIMITS_REDIS_SERVER_VERSION=[\d\.]+' | cut -d = -f 2"
|
|
@@ -53,6 +58,11 @@ the results in `github <https://github.com/alisaifee/limits/actions/workflows/co
|
|
|
53
58
|
|
|
54
59
|
.. literalinclude:: ../../requirements/storage/async-redis.txt
|
|
55
60
|
|
|
61
|
+
.. note::
|
|
62
|
+
.. versionadded:: 4.2
|
|
63
|
+
:pypi:`redis` can be used instead of :pypi:`coredis` by setting
|
|
64
|
+
:paramref:`limits.aio.storage.RedisClusterStorage.implementation` to ``redispy``
|
|
65
|
+
|
|
56
66
|
`Redis cluster <https://redis.io/topics/cluster-tutorial>`_
|
|
57
67
|
|
|
58
68
|
.. program-output:: bash -c "cat ../../.github/workflows/compatibility.yml | grep -o -P 'LIMITS_REDIS_SERVER_VERSION=[\d\.]+' | cut -d = -f 2"
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
Rate limiting with commonly used storage backends
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
5
7
|
from . import _version, aio, storage, strategies
|
|
6
8
|
from .limits import (
|
|
7
9
|
RateLimitItem,
|
|
@@ -30,4 +32,4 @@ __all__ = [
|
|
|
30
32
|
"WindowStats",
|
|
31
33
|
]
|
|
32
34
|
|
|
33
|
-
__version__ = _version.get_versions()["version"]
|
|
35
|
+
__version__ = _version.get_versions()["version"]
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
# This file was generated by 'versioneer.py' (0.
|
|
2
|
+
# This file was generated by 'versioneer.py' (0.29) from
|
|
3
3
|
# revision-control system data, or from the parent directory name of an
|
|
4
4
|
# unpacked source archive. Distribution tarballs contain a pre-generated copy
|
|
5
5
|
# of this file.
|
|
@@ -8,11 +8,11 @@ import json
|
|
|
8
8
|
|
|
9
9
|
version_json = '''
|
|
10
10
|
{
|
|
11
|
-
"date": "2025-03-
|
|
11
|
+
"date": "2025-03-11T11:27:52-0700",
|
|
12
12
|
"dirty": false,
|
|
13
13
|
"error": null,
|
|
14
|
-
"full-revisionid": "
|
|
15
|
-
"version": "4.
|
|
14
|
+
"full-revisionid": "ef5c0911dd6e0c1a412b3f467d0d1503a2fa24ce",
|
|
15
|
+
"version": "4.2"
|
|
16
16
|
}
|
|
17
17
|
''' # END VERSION_JSON
|
|
18
18
|
|
|
@@ -3,6 +3,8 @@ Implementations of storage backends to be used with
|
|
|
3
3
|
:class:`limits.aio.strategies.RateLimiter` strategies
|
|
4
4
|
"""
|
|
5
5
|
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
6
8
|
from .base import MovingWindowSupport, SlidingWindowCounterSupport, Storage
|
|
7
9
|
from .etcd import EtcdStorage
|
|
8
10
|
from .memcached import MemcachedStorage
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Optional, Type, Union
|
|
4
|
+
|
|
5
|
+
from deprecated.sphinx import versionadded, versionchanged
|
|
6
|
+
from packaging.version import Version
|
|
7
|
+
|
|
8
|
+
from limits.aio.storage import MovingWindowSupport, SlidingWindowCounterSupport, Storage
|
|
9
|
+
from limits.aio.storage.redis.bridge import RedisBridge
|
|
10
|
+
from limits.aio.storage.redis.coredis import CoredisBridge
|
|
11
|
+
from limits.aio.storage.redis.redispy import RedispyBridge
|
|
12
|
+
from limits.typing import Literal
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@versionadded(version="2.1")
|
|
16
|
+
@versionchanged(
|
|
17
|
+
version="4.2",
|
|
18
|
+
reason=(
|
|
19
|
+
"Added support for using the asyncio redis client from :pypi:`redis`"
|
|
20
|
+
" through :paramref:`implementation`"
|
|
21
|
+
),
|
|
22
|
+
)
|
|
23
|
+
class RedisStorage(Storage, MovingWindowSupport, SlidingWindowCounterSupport):
|
|
24
|
+
"""
|
|
25
|
+
Rate limit storage with redis as backend.
|
|
26
|
+
|
|
27
|
+
Depends on :pypi:`coredis` or :pypi:`redis`
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
STORAGE_SCHEME = ["async+redis", "async+rediss", "async+redis+unix"]
|
|
31
|
+
"""
|
|
32
|
+
The storage schemes for redis to be used in an async context
|
|
33
|
+
"""
|
|
34
|
+
DEPENDENCIES = {"redis": Version("5.2.0"), "coredis": Version("3.4.0")}
|
|
35
|
+
MODE: Literal["BASIC", "CLUSTER", "SENTINEL"] = "BASIC"
|
|
36
|
+
bridge: RedisBridge
|
|
37
|
+
storage_exceptions: tuple[Exception, ...]
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
uri: str,
|
|
42
|
+
wrap_exceptions: bool = False,
|
|
43
|
+
implementation: Literal["redispy", "coredis"] = "coredis",
|
|
44
|
+
**options: Union[float, str, bool],
|
|
45
|
+
) -> None:
|
|
46
|
+
"""
|
|
47
|
+
:param uri: uri of the form:
|
|
48
|
+
|
|
49
|
+
- ``async+redis://[:password]@host:port``
|
|
50
|
+
- ``async+redis://[:password]@host:port/db``
|
|
51
|
+
- ``async+rediss://[:password]@host:port``
|
|
52
|
+
- ``async+redis+unix:///path/to/sock?db=0`` etc...
|
|
53
|
+
|
|
54
|
+
This uri is passed directly to :meth:`coredis.Redis.from_url` or
|
|
55
|
+
:meth:`redis.asyncio.client.Redis.from_url` with the initial ``async`` removed,
|
|
56
|
+
except for the case of ``async+redis+unix`` where it is replaced with ``unix``.
|
|
57
|
+
:param connection_pool: if provided, the redis client is initialized with
|
|
58
|
+
the connection pool and any other params passed as :paramref:`options`
|
|
59
|
+
:param wrap_exceptions: Whether to wrap storage exceptions in
|
|
60
|
+
:exc:`limits.errors.StorageError` before raising it.
|
|
61
|
+
:param implementation: Whether to use the client implementation from
|
|
62
|
+
:class:`coredis.Redis` (``coredis``) or :class:`redis.asyncio.client.Redis` (``redispy``).
|
|
63
|
+
:param options: all remaining keyword arguments are passed
|
|
64
|
+
directly to the constructor of :class:`coredis.Redis` or :class:`redis.asyncio.client.Redis`
|
|
65
|
+
:raise ConfigurationError: when the redis library is not available
|
|
66
|
+
"""
|
|
67
|
+
uri = uri.replace("async+redis", "redis", 1)
|
|
68
|
+
uri = uri.replace("redis+unix", "unix")
|
|
69
|
+
|
|
70
|
+
super().__init__(uri, wrap_exceptions=wrap_exceptions)
|
|
71
|
+
self.options = options
|
|
72
|
+
if implementation == "redispy":
|
|
73
|
+
self.bridge = RedispyBridge(uri, self.dependencies["redis"].module)
|
|
74
|
+
else:
|
|
75
|
+
self.bridge = CoredisBridge(uri, self.dependencies["coredis"].module)
|
|
76
|
+
self.configure_bridge()
|
|
77
|
+
self.bridge.register_scripts()
|
|
78
|
+
|
|
79
|
+
def _current_window_key(self, key: str) -> str:
|
|
80
|
+
"""
|
|
81
|
+
Return the current window's storage key (Sliding window strategy)
|
|
82
|
+
|
|
83
|
+
Contrary to other strategies that have one key per rate limit item,
|
|
84
|
+
this strategy has two keys per rate limit item than must be on the same machine.
|
|
85
|
+
To keep the current key and the previous key on the same Redis cluster node,
|
|
86
|
+
curly braces are added.
|
|
87
|
+
|
|
88
|
+
Eg: "{constructed_key}"
|
|
89
|
+
"""
|
|
90
|
+
return f"{{{key}}}"
|
|
91
|
+
|
|
92
|
+
def _previous_window_key(self, key: str) -> str:
|
|
93
|
+
"""
|
|
94
|
+
Return the previous window's storage key (Sliding window strategy).
|
|
95
|
+
|
|
96
|
+
Curvy braces are added on the common pattern with the current window's key,
|
|
97
|
+
so the current and the previous key are stored on the same Redis cluster node.
|
|
98
|
+
|
|
99
|
+
Eg: "{constructed_key}/-1"
|
|
100
|
+
"""
|
|
101
|
+
return f"{self._current_window_key(key)}/-1"
|
|
102
|
+
|
|
103
|
+
def configure_bridge(self) -> None:
|
|
104
|
+
self.bridge.use_basic(**self.options)
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def base_exceptions(
|
|
108
|
+
self,
|
|
109
|
+
) -> Union[Type[Exception], tuple[Type[Exception], ...]]: # pragma: no cover
|
|
110
|
+
return self.bridge.base_exceptions
|
|
111
|
+
|
|
112
|
+
async def incr(
|
|
113
|
+
self, key: str, expiry: int, elastic_expiry: bool = False, amount: int = 1
|
|
114
|
+
) -> int:
|
|
115
|
+
"""
|
|
116
|
+
increments the counter for a given rate limit key
|
|
117
|
+
|
|
118
|
+
:param key: the key to increment
|
|
119
|
+
:param expiry: amount in seconds for the key to expire in
|
|
120
|
+
:param amount: the number to increment by
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
return await self.bridge.incr(key, expiry, elastic_expiry, amount)
|
|
124
|
+
|
|
125
|
+
async def get(self, key: str) -> int:
|
|
126
|
+
"""
|
|
127
|
+
:param key: the key to get the counter value for
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
return await self.bridge.get(key)
|
|
131
|
+
|
|
132
|
+
async def clear(self, key: str) -> None:
|
|
133
|
+
"""
|
|
134
|
+
:param key: the key to clear rate limits for
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
return await self.bridge.clear(key)
|
|
138
|
+
|
|
139
|
+
async def acquire_entry(
|
|
140
|
+
self, key: str, limit: int, expiry: int, amount: int = 1
|
|
141
|
+
) -> bool:
|
|
142
|
+
"""
|
|
143
|
+
:param key: rate limit key to acquire an entry in
|
|
144
|
+
:param limit: amount of entries allowed
|
|
145
|
+
:param expiry: expiry of the entry
|
|
146
|
+
:param amount: the number of entries to acquire
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
return await self.bridge.acquire_entry(key, limit, expiry, amount)
|
|
150
|
+
|
|
151
|
+
async def get_moving_window(
|
|
152
|
+
self, key: str, limit: int, expiry: int
|
|
153
|
+
) -> tuple[float, int]:
|
|
154
|
+
"""
|
|
155
|
+
returns the starting point and the number of entries in the moving
|
|
156
|
+
window
|
|
157
|
+
|
|
158
|
+
:param key: rate limit key
|
|
159
|
+
:param expiry: expiry of entry
|
|
160
|
+
:return: (previous count, previous TTL, current count, current TTL)
|
|
161
|
+
"""
|
|
162
|
+
return await self.bridge.get_moving_window(key, limit, expiry)
|
|
163
|
+
|
|
164
|
+
async def acquire_sliding_window_entry(
|
|
165
|
+
self,
|
|
166
|
+
key: str,
|
|
167
|
+
limit: int,
|
|
168
|
+
expiry: int,
|
|
169
|
+
amount: int = 1,
|
|
170
|
+
) -> bool:
|
|
171
|
+
current_key = self._current_window_key(key)
|
|
172
|
+
previous_key = self._previous_window_key(key)
|
|
173
|
+
return await self.bridge.acquire_sliding_window_entry(
|
|
174
|
+
previous_key, current_key, limit, expiry, amount
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
async def get_sliding_window(
|
|
178
|
+
self, key: str, expiry: int
|
|
179
|
+
) -> tuple[int, float, int, float]:
|
|
180
|
+
previous_key = self._previous_window_key(key)
|
|
181
|
+
current_key = self._current_window_key(key)
|
|
182
|
+
return await self.bridge.get_sliding_window(previous_key, current_key, expiry)
|
|
183
|
+
|
|
184
|
+
async def get_expiry(self, key: str) -> float:
|
|
185
|
+
"""
|
|
186
|
+
:param key: the key to get the expiry for
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
return await self.bridge.get_expiry(key)
|
|
190
|
+
|
|
191
|
+
async def check(self) -> bool:
|
|
192
|
+
"""
|
|
193
|
+
Check if storage is healthy by calling ``PING``
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
return await self.bridge.check()
|
|
197
|
+
|
|
198
|
+
async def reset(self) -> Optional[int]:
|
|
199
|
+
"""
|
|
200
|
+
This function calls a Lua Script to delete keys prefixed with
|
|
201
|
+
``self.PREFIX`` in blocks of 5000.
|
|
202
|
+
|
|
203
|
+
.. warning:: This operation was designed to be fast, but was not tested
|
|
204
|
+
on a large production based system. Be careful with its usage as it
|
|
205
|
+
could be slow on very large data sets.
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
return await self.bridge.lua_reset()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@versionadded(version="2.1")
|
|
212
|
+
@versionchanged(
|
|
213
|
+
version="4.2",
|
|
214
|
+
reason="Added support for using the asyncio redis client from :pypi:`redis` ",
|
|
215
|
+
)
|
|
216
|
+
class RedisClusterStorage(RedisStorage):
|
|
217
|
+
"""
|
|
218
|
+
Rate limit storage with redis cluster as backend
|
|
219
|
+
|
|
220
|
+
Depends on :pypi:`coredis` or :pypi:`redis`
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
STORAGE_SCHEME = ["async+redis+cluster"]
|
|
224
|
+
"""
|
|
225
|
+
The storage schemes for redis cluster to be used in an async context
|
|
226
|
+
"""
|
|
227
|
+
|
|
228
|
+
MODE = "CLUSTER"
|
|
229
|
+
|
|
230
|
+
def __init__(
|
|
231
|
+
self,
|
|
232
|
+
uri: str,
|
|
233
|
+
wrap_exceptions: bool = False,
|
|
234
|
+
implementation: Literal["redispy", "coredis"] = "coredis",
|
|
235
|
+
**options: Union[float, str, bool],
|
|
236
|
+
) -> None:
|
|
237
|
+
"""
|
|
238
|
+
:param uri: url of the form
|
|
239
|
+
``async+redis+cluster://[:password]@host:port,host:port``
|
|
240
|
+
:param wrap_exceptions: Whether to wrap storage exceptions in
|
|
241
|
+
:exc:`limits.errors.StorageError` before raising it.
|
|
242
|
+
:param implementation: Whether to use the client implementation from
|
|
243
|
+
:class:`coredis.RedisCluster` (``coredis``) or :class:`redis.asyncio.cluster.RedisCluster` (``redispy``).
|
|
244
|
+
:param options: all remaining keyword arguments are passed
|
|
245
|
+
directly to the constructor of :class:`coredis.RedisCluster` or
|
|
246
|
+
:class:`redis.asyncio.RedisCluster`
|
|
247
|
+
:raise ConfigurationError: when the redis library is not
|
|
248
|
+
available or if the redis host cannot be pinged.
|
|
249
|
+
"""
|
|
250
|
+
super().__init__(
|
|
251
|
+
uri,
|
|
252
|
+
wrap_exceptions=wrap_exceptions,
|
|
253
|
+
implementation=implementation,
|
|
254
|
+
**options,
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
def configure_bridge(self) -> None:
|
|
258
|
+
self.bridge.use_cluster(**self.options)
|
|
259
|
+
|
|
260
|
+
async def reset(self) -> Optional[int]:
|
|
261
|
+
"""
|
|
262
|
+
Redis Clusters are sharded and deleting across shards
|
|
263
|
+
can't be done atomically. Because of this, this reset loops over all
|
|
264
|
+
keys that are prefixed with ``self.PREFIX`` and calls delete on them,
|
|
265
|
+
one at a time.
|
|
266
|
+
|
|
267
|
+
.. warning:: This operation was not tested with extremely large data sets.
|
|
268
|
+
On a large production based system, care should be taken with its
|
|
269
|
+
usage as it could be slow on very large data sets
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
return await self.bridge.reset()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@versionadded(version="2.1")
|
|
276
|
+
@versionchanged(
|
|
277
|
+
version="4.2",
|
|
278
|
+
reason="Added support for using the asyncio redis client from :pypi:`redis` ",
|
|
279
|
+
)
|
|
280
|
+
class RedisSentinelStorage(RedisStorage):
|
|
281
|
+
"""
|
|
282
|
+
Rate limit storage with redis sentinel as backend
|
|
283
|
+
|
|
284
|
+
Depends on :pypi:`coredis` or :pypi:`redis`
|
|
285
|
+
"""
|
|
286
|
+
|
|
287
|
+
STORAGE_SCHEME = ["async+redis+sentinel"]
|
|
288
|
+
"""The storage scheme for redis accessed via a redis sentinel installation"""
|
|
289
|
+
|
|
290
|
+
MODE = "SENTINEL"
|
|
291
|
+
|
|
292
|
+
DEPENDENCIES = {
|
|
293
|
+
"redis": Version("5.2.0"),
|
|
294
|
+
"coredis": Version("3.4.0"),
|
|
295
|
+
"coredis.sentinel": Version("3.4.0"),
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
def __init__(
|
|
299
|
+
self,
|
|
300
|
+
uri: str,
|
|
301
|
+
wrap_exceptions: bool = False,
|
|
302
|
+
implementation: Literal["redispy", "coredis"] = "coredis",
|
|
303
|
+
service_name: Optional[str] = None,
|
|
304
|
+
use_replicas: bool = True,
|
|
305
|
+
sentinel_kwargs: Optional[dict[str, Union[float, str, bool]]] = None,
|
|
306
|
+
**options: Union[float, str, bool],
|
|
307
|
+
):
|
|
308
|
+
"""
|
|
309
|
+
:param uri: url of the form
|
|
310
|
+
``async+redis+sentinel://host:port,host:port/service_name``
|
|
311
|
+
:param wrap_exceptions: Whether to wrap storage exceptions in
|
|
312
|
+
:exc:`limits.errors.StorageError` before raising it.
|
|
313
|
+
:param implementation: Whether to use the client implementation from
|
|
314
|
+
:class:`coredis.sentinel.Sentinel` (``coredis``) or
|
|
315
|
+
:class:`redis.asyncio.sentinel.Sentinel` (``redispy``)
|
|
316
|
+
:param service_name: sentinel service name (if not provided in `uri`)
|
|
317
|
+
:param use_replicas: Whether to use replicas for read only operations
|
|
318
|
+
:param sentinel_kwargs: optional arguments to pass as
|
|
319
|
+
`sentinel_kwargs`` to :class:`coredis.sentinel.Sentinel` or
|
|
320
|
+
:class:`redis.asyncio.Sentinel`
|
|
321
|
+
:param options: all remaining keyword arguments are passed
|
|
322
|
+
directly to the constructor of :class:`coredis.sentinel.Sentinel` or
|
|
323
|
+
:class:`redis.asyncio.sentinel.Sentinel`
|
|
324
|
+
:raise ConfigurationError: when the redis library is not available
|
|
325
|
+
or if the redis primary host cannot be pinged.
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
self.service_name = service_name
|
|
329
|
+
self.use_replicas = use_replicas
|
|
330
|
+
self.sentinel_kwargs = sentinel_kwargs
|
|
331
|
+
super().__init__(
|
|
332
|
+
uri,
|
|
333
|
+
wrap_exceptions=wrap_exceptions,
|
|
334
|
+
implementation=implementation,
|
|
335
|
+
**options,
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
def configure_bridge(self) -> None:
|
|
339
|
+
self.bridge.use_sentinel(
|
|
340
|
+
self.service_name, self.use_replicas, self.sentinel_kwargs, **self.options
|
|
341
|
+
)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import urllib
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from types import ModuleType
|
|
6
|
+
|
|
7
|
+
from limits.typing import Optional, Type, Union
|
|
8
|
+
from limits.util import get_package_data
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RedisBridge(ABC):
|
|
12
|
+
PREFIX = "LIMITS"
|
|
13
|
+
RES_DIR = "resources/redis/lua_scripts"
|
|
14
|
+
|
|
15
|
+
SCRIPT_MOVING_WINDOW = get_package_data(f"{RES_DIR}/moving_window.lua")
|
|
16
|
+
SCRIPT_ACQUIRE_MOVING_WINDOW = get_package_data(
|
|
17
|
+
f"{RES_DIR}/acquire_moving_window.lua"
|
|
18
|
+
)
|
|
19
|
+
SCRIPT_CLEAR_KEYS = get_package_data(f"{RES_DIR}/clear_keys.lua")
|
|
20
|
+
SCRIPT_INCR_EXPIRE = get_package_data(f"{RES_DIR}/incr_expire.lua")
|
|
21
|
+
SCRIPT_SLIDING_WINDOW = get_package_data(f"{RES_DIR}/sliding_window.lua")
|
|
22
|
+
SCRIPT_ACQUIRE_SLIDING_WINDOW = get_package_data(
|
|
23
|
+
f"{RES_DIR}/acquire_sliding_window.lua"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
uri: str,
|
|
29
|
+
dependency: ModuleType,
|
|
30
|
+
) -> None:
|
|
31
|
+
self.uri = uri
|
|
32
|
+
self.parsed_uri = urllib.parse.urlparse(self.uri)
|
|
33
|
+
self.dependency = dependency
|
|
34
|
+
self.parsed_auth = {}
|
|
35
|
+
if self.parsed_uri.username:
|
|
36
|
+
self.parsed_auth["username"] = self.parsed_uri.username
|
|
37
|
+
if self.parsed_uri.password:
|
|
38
|
+
self.parsed_auth["password"] = self.parsed_uri.password
|
|
39
|
+
|
|
40
|
+
def prefixed_key(self, key: str) -> str:
|
|
41
|
+
return f"{self.PREFIX}:{key}"
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def register_scripts(self) -> None: ...
|
|
45
|
+
|
|
46
|
+
@abstractmethod
|
|
47
|
+
def use_sentinel(
|
|
48
|
+
self,
|
|
49
|
+
service_name: Optional[str],
|
|
50
|
+
use_replicas: bool,
|
|
51
|
+
sentinel_kwargs: Optional[dict[str, Union[str, float, bool]]],
|
|
52
|
+
**options: Union[str, float, bool],
|
|
53
|
+
) -> None: ...
|
|
54
|
+
|
|
55
|
+
@abstractmethod
|
|
56
|
+
def use_basic(self, **options: Union[str, float, bool]) -> None: ...
|
|
57
|
+
|
|
58
|
+
@abstractmethod
|
|
59
|
+
def use_cluster(self, **options: Union[str, float, bool]) -> None: ...
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
@abstractmethod
|
|
63
|
+
def base_exceptions(
|
|
64
|
+
self,
|
|
65
|
+
) -> Union[Type[Exception], tuple[Type[Exception], ...]]: ...
|
|
66
|
+
|
|
67
|
+
@abstractmethod
|
|
68
|
+
async def incr(
|
|
69
|
+
self,
|
|
70
|
+
key: str,
|
|
71
|
+
expiry: int,
|
|
72
|
+
elastic_expiry: bool = False,
|
|
73
|
+
amount: int = 1,
|
|
74
|
+
) -> int: ...
|
|
75
|
+
|
|
76
|
+
@abstractmethod
|
|
77
|
+
async def get(self, key: str) -> int: ...
|
|
78
|
+
|
|
79
|
+
@abstractmethod
|
|
80
|
+
async def clear(self, key: str) -> None: ...
|
|
81
|
+
|
|
82
|
+
@abstractmethod
|
|
83
|
+
async def get_moving_window(
|
|
84
|
+
self, key: str, limit: int, expiry: int
|
|
85
|
+
) -> tuple[float, int]: ...
|
|
86
|
+
|
|
87
|
+
@abstractmethod
|
|
88
|
+
async def get_sliding_window(
|
|
89
|
+
self, previous_key: str, current_key: str, expiry: int
|
|
90
|
+
) -> tuple[int, float, int, float]: ...
|
|
91
|
+
|
|
92
|
+
@abstractmethod
|
|
93
|
+
async def acquire_entry(
|
|
94
|
+
self,
|
|
95
|
+
key: str,
|
|
96
|
+
limit: int,
|
|
97
|
+
expiry: int,
|
|
98
|
+
amount: int = 1,
|
|
99
|
+
) -> bool: ...
|
|
100
|
+
|
|
101
|
+
@abstractmethod
|
|
102
|
+
async def acquire_sliding_window_entry(
|
|
103
|
+
self,
|
|
104
|
+
previous_key: str,
|
|
105
|
+
current_key: str,
|
|
106
|
+
limit: int,
|
|
107
|
+
expiry: int,
|
|
108
|
+
amount: int = 1,
|
|
109
|
+
) -> bool: ...
|
|
110
|
+
|
|
111
|
+
@abstractmethod
|
|
112
|
+
async def get_expiry(self, key: str) -> float: ...
|
|
113
|
+
|
|
114
|
+
@abstractmethod
|
|
115
|
+
async def check(self) -> bool: ...
|
|
116
|
+
|
|
117
|
+
@abstractmethod
|
|
118
|
+
async def reset(self) -> Optional[int]: ...
|
|
119
|
+
|
|
120
|
+
@abstractmethod
|
|
121
|
+
async def lua_reset(self) -> Optional[int]: ...
|