limits 4.1__py3-none-any.whl → 4.3__py3-none-any.whl
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/__init__.py +8 -6
- limits/_version.py +4 -4
- limits/aio/__init__.py +2 -0
- limits/aio/storage/__init__.py +6 -4
- limits/aio/storage/base.py +5 -8
- limits/aio/storage/etcd.py +6 -4
- limits/aio/storage/memcached.py +6 -4
- limits/aio/storage/memory.py +42 -26
- limits/aio/storage/mongodb.py +4 -7
- limits/aio/storage/redis/__init__.py +402 -0
- limits/aio/storage/redis/bridge.py +120 -0
- limits/aio/storage/redis/coredis.py +209 -0
- limits/aio/storage/redis/redispy.py +257 -0
- limits/aio/storage/redis/valkey.py +9 -0
- limits/aio/strategies.py +4 -2
- limits/errors.py +2 -0
- limits/storage/__init__.py +14 -11
- limits/storage/base.py +5 -10
- limits/storage/etcd.py +6 -4
- limits/storage/memcached.py +6 -7
- limits/storage/memory.py +42 -31
- limits/storage/mongodb.py +7 -10
- limits/storage/redis.py +48 -18
- limits/storage/redis_cluster.py +31 -11
- limits/storage/redis_sentinel.py +35 -11
- limits/storage/registry.py +1 -3
- limits/strategies.py +11 -9
- limits/typing.py +45 -42
- limits/util.py +12 -12
- {limits-4.1.dist-info → limits-4.3.dist-info}/METADATA +52 -36
- limits-4.3.dist-info/RECORD +43 -0
- {limits-4.1.dist-info → limits-4.3.dist-info}/WHEEL +1 -1
- limits/aio/storage/redis.py +0 -555
- limits-4.1.dist-info/RECORD +0 -39
- {limits-4.1.dist-info → limits-4.3.dist-info}/LICENSE.txt +0 -0
- {limits-4.1.dist-info → limits-4.3.dist-info}/top_level.txt +0 -0
limits/aio/storage/redis.py
DELETED
|
@@ -1,555 +0,0 @@
|
|
|
1
|
-
import time
|
|
2
|
-
import urllib
|
|
3
|
-
from typing import TYPE_CHECKING, cast
|
|
4
|
-
|
|
5
|
-
from deprecated.sphinx import versionadded
|
|
6
|
-
from packaging.version import Version
|
|
7
|
-
|
|
8
|
-
from limits.aio.storage.base import (
|
|
9
|
-
MovingWindowSupport,
|
|
10
|
-
SlidingWindowCounterSupport,
|
|
11
|
-
Storage,
|
|
12
|
-
)
|
|
13
|
-
from limits.errors import ConfigurationError
|
|
14
|
-
from limits.typing import AsyncRedisClient, Optional, Type, Union
|
|
15
|
-
from limits.util import get_package_data
|
|
16
|
-
|
|
17
|
-
if TYPE_CHECKING:
|
|
18
|
-
import coredis
|
|
19
|
-
import coredis.commands
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
class RedisInteractor:
|
|
23
|
-
RES_DIR = "resources/redis/lua_scripts"
|
|
24
|
-
|
|
25
|
-
SCRIPT_MOVING_WINDOW = get_package_data(f"{RES_DIR}/moving_window.lua")
|
|
26
|
-
SCRIPT_ACQUIRE_MOVING_WINDOW = get_package_data(
|
|
27
|
-
f"{RES_DIR}/acquire_moving_window.lua"
|
|
28
|
-
)
|
|
29
|
-
SCRIPT_CLEAR_KEYS = get_package_data(f"{RES_DIR}/clear_keys.lua")
|
|
30
|
-
SCRIPT_INCR_EXPIRE = get_package_data(f"{RES_DIR}/incr_expire.lua")
|
|
31
|
-
SCRIPT_SLIDING_WINDOW = get_package_data(f"{RES_DIR}/sliding_window.lua")
|
|
32
|
-
SCRIPT_ACQUIRE_SLIDING_WINDOW = get_package_data(
|
|
33
|
-
f"{RES_DIR}/acquire_sliding_window.lua"
|
|
34
|
-
)
|
|
35
|
-
|
|
36
|
-
lua_moving_window: "coredis.commands.Script[bytes]"
|
|
37
|
-
lua_acquire_moving_window: "coredis.commands.Script[bytes]"
|
|
38
|
-
lua_sliding_window: "coredis.commands.Script[bytes]"
|
|
39
|
-
lua_acquire_sliding_window: "coredis.commands.Script[bytes]"
|
|
40
|
-
lua_clear_keys: "coredis.commands.Script[bytes]"
|
|
41
|
-
lua_incr_expire: "coredis.commands.Script[bytes]"
|
|
42
|
-
|
|
43
|
-
PREFIX = "LIMITS"
|
|
44
|
-
|
|
45
|
-
def prefixed_key(self, key: str) -> str:
|
|
46
|
-
return f"{self.PREFIX}:{key}"
|
|
47
|
-
|
|
48
|
-
async def _incr(
|
|
49
|
-
self,
|
|
50
|
-
key: str,
|
|
51
|
-
expiry: int,
|
|
52
|
-
connection: AsyncRedisClient,
|
|
53
|
-
elastic_expiry: bool = False,
|
|
54
|
-
amount: int = 1,
|
|
55
|
-
) -> int:
|
|
56
|
-
"""
|
|
57
|
-
increments the counter for a given rate limit key
|
|
58
|
-
|
|
59
|
-
:param connection: Redis connection
|
|
60
|
-
:param key: the key to increment
|
|
61
|
-
:param expiry: amount in seconds for the key to expire in
|
|
62
|
-
:param amount: the number to increment by
|
|
63
|
-
"""
|
|
64
|
-
key = self.prefixed_key(key)
|
|
65
|
-
value = await connection.incrby(key, amount)
|
|
66
|
-
|
|
67
|
-
if elastic_expiry or value == amount:
|
|
68
|
-
await connection.expire(key, expiry)
|
|
69
|
-
|
|
70
|
-
return value
|
|
71
|
-
|
|
72
|
-
async def _get(self, key: str, connection: AsyncRedisClient) -> int:
|
|
73
|
-
"""
|
|
74
|
-
:param connection: Redis connection
|
|
75
|
-
:param key: the key to get the counter value for
|
|
76
|
-
"""
|
|
77
|
-
|
|
78
|
-
key = self.prefixed_key(key)
|
|
79
|
-
return int(await connection.get(key) or 0)
|
|
80
|
-
|
|
81
|
-
async def _clear(self, key: str, connection: AsyncRedisClient) -> None:
|
|
82
|
-
"""
|
|
83
|
-
:param key: the key to clear rate limits for
|
|
84
|
-
:param connection: Redis connection
|
|
85
|
-
"""
|
|
86
|
-
key = self.prefixed_key(key)
|
|
87
|
-
await connection.delete([key])
|
|
88
|
-
|
|
89
|
-
async def get_moving_window(
|
|
90
|
-
self, key: str, limit: int, expiry: int
|
|
91
|
-
) -> tuple[float, int]:
|
|
92
|
-
"""
|
|
93
|
-
returns the starting point and the number of entries in the moving
|
|
94
|
-
window
|
|
95
|
-
|
|
96
|
-
:param key: rate limit key
|
|
97
|
-
:param expiry: expiry of entry
|
|
98
|
-
:return: (previous count, previous TTL, current count, current TTL)
|
|
99
|
-
"""
|
|
100
|
-
key = self.prefixed_key(key)
|
|
101
|
-
timestamp = time.time()
|
|
102
|
-
window = await self.lua_moving_window.execute(
|
|
103
|
-
[key], [timestamp - expiry, limit]
|
|
104
|
-
)
|
|
105
|
-
if window:
|
|
106
|
-
return float(window[0]), window[1] # type: ignore
|
|
107
|
-
return timestamp, 0
|
|
108
|
-
|
|
109
|
-
async def get_sliding_window(
|
|
110
|
-
self, key: str, expiry: int
|
|
111
|
-
) -> tuple[int, float, int, float]:
|
|
112
|
-
previous_key = self.prefixed_key(self._previous_window_key(key))
|
|
113
|
-
current_key = self.prefixed_key(self._current_window_key(key))
|
|
114
|
-
|
|
115
|
-
if window := await self.lua_sliding_window.execute(
|
|
116
|
-
[previous_key, current_key], [expiry]
|
|
117
|
-
):
|
|
118
|
-
return (
|
|
119
|
-
int(window[0] or 0), # type: ignore
|
|
120
|
-
max(0, float(window[1] or 0)) / 1000, # type: ignore
|
|
121
|
-
int(window[2] or 0), # type: ignore
|
|
122
|
-
max(0, float(window[3] or 0)) / 1000, # type: ignore
|
|
123
|
-
)
|
|
124
|
-
return 0, 0.0, 0, 0.0
|
|
125
|
-
|
|
126
|
-
async def _acquire_entry(
|
|
127
|
-
self,
|
|
128
|
-
key: str,
|
|
129
|
-
limit: int,
|
|
130
|
-
expiry: int,
|
|
131
|
-
connection: AsyncRedisClient,
|
|
132
|
-
amount: int = 1,
|
|
133
|
-
) -> bool:
|
|
134
|
-
"""
|
|
135
|
-
:param key: rate limit key to acquire an entry in
|
|
136
|
-
:param limit: amount of entries allowed
|
|
137
|
-
:param expiry: expiry of the entry
|
|
138
|
-
:param connection: Redis connection
|
|
139
|
-
"""
|
|
140
|
-
key = self.prefixed_key(key)
|
|
141
|
-
timestamp = time.time()
|
|
142
|
-
acquired = await self.lua_acquire_moving_window.execute(
|
|
143
|
-
[key], [timestamp, limit, expiry, amount]
|
|
144
|
-
)
|
|
145
|
-
|
|
146
|
-
return bool(acquired)
|
|
147
|
-
|
|
148
|
-
async def _acquire_sliding_window_entry(
|
|
149
|
-
self,
|
|
150
|
-
previous_key: str,
|
|
151
|
-
current_key: str,
|
|
152
|
-
limit: int,
|
|
153
|
-
expiry: int,
|
|
154
|
-
amount: int = 1,
|
|
155
|
-
) -> bool:
|
|
156
|
-
previous_key = self.prefixed_key(previous_key)
|
|
157
|
-
current_key = self.prefixed_key(current_key)
|
|
158
|
-
acquired = await self.lua_acquire_sliding_window.execute(
|
|
159
|
-
[previous_key, current_key], [limit, expiry, amount]
|
|
160
|
-
)
|
|
161
|
-
return bool(acquired)
|
|
162
|
-
|
|
163
|
-
async def _get_expiry(self, key: str, connection: AsyncRedisClient) -> float:
|
|
164
|
-
"""
|
|
165
|
-
:param key: the key to get the expiry for
|
|
166
|
-
:param connection: Redis connection
|
|
167
|
-
"""
|
|
168
|
-
|
|
169
|
-
key = self.prefixed_key(key)
|
|
170
|
-
return max(await connection.ttl(key), 0) + time.time()
|
|
171
|
-
|
|
172
|
-
async def _check(self, connection: AsyncRedisClient) -> bool:
|
|
173
|
-
"""
|
|
174
|
-
check if storage is healthy
|
|
175
|
-
|
|
176
|
-
:param connection: Redis connection
|
|
177
|
-
"""
|
|
178
|
-
try:
|
|
179
|
-
await connection.ping()
|
|
180
|
-
|
|
181
|
-
return True
|
|
182
|
-
except: # noqa
|
|
183
|
-
return False
|
|
184
|
-
|
|
185
|
-
def _current_window_key(self, key: str) -> str:
|
|
186
|
-
"""
|
|
187
|
-
Return the current window's storage key (Sliding window strategy)
|
|
188
|
-
|
|
189
|
-
Contrary to other strategies that have one key per rate limit item,
|
|
190
|
-
this strategy has two keys per rate limit item than must be on the same machine.
|
|
191
|
-
To keep the current key and the previous key on the same Redis cluster node,
|
|
192
|
-
curly braces are added.
|
|
193
|
-
|
|
194
|
-
Eg: "{constructed_key}"
|
|
195
|
-
"""
|
|
196
|
-
return f"{{{key}}}"
|
|
197
|
-
|
|
198
|
-
def _previous_window_key(self, key: str) -> str:
|
|
199
|
-
"""
|
|
200
|
-
Return the previous window's storage key (Sliding window strategy).
|
|
201
|
-
|
|
202
|
-
Curvy braces are added on the common pattern with the current window's key,
|
|
203
|
-
so the current and the previous key are stored on the same Redis cluster node.
|
|
204
|
-
|
|
205
|
-
Eg: "{constructed_key}/-1"
|
|
206
|
-
"""
|
|
207
|
-
return f"{self._current_window_key(key)}/-1"
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
@versionadded(version="2.1")
|
|
211
|
-
class RedisStorage(
|
|
212
|
-
RedisInteractor, Storage, MovingWindowSupport, SlidingWindowCounterSupport
|
|
213
|
-
):
|
|
214
|
-
"""
|
|
215
|
-
Rate limit storage with redis as backend.
|
|
216
|
-
|
|
217
|
-
Depends on :pypi:`coredis`
|
|
218
|
-
"""
|
|
219
|
-
|
|
220
|
-
STORAGE_SCHEME = ["async+redis", "async+rediss", "async+redis+unix"]
|
|
221
|
-
"""
|
|
222
|
-
The storage schemes for redis to be used in an async context
|
|
223
|
-
"""
|
|
224
|
-
DEPENDENCIES = {"coredis": Version("3.4.0")}
|
|
225
|
-
|
|
226
|
-
def __init__(
|
|
227
|
-
self,
|
|
228
|
-
uri: str,
|
|
229
|
-
connection_pool: Optional["coredis.ConnectionPool"] = None,
|
|
230
|
-
wrap_exceptions: bool = False,
|
|
231
|
-
**options: Union[float, str, bool],
|
|
232
|
-
) -> None:
|
|
233
|
-
"""
|
|
234
|
-
:param uri: uri of the form:
|
|
235
|
-
|
|
236
|
-
- ``async+redis://[:password]@host:port``
|
|
237
|
-
- ``async+redis://[:password]@host:port/db``
|
|
238
|
-
- ``async+rediss://[:password]@host:port``
|
|
239
|
-
- ``async+redis+unix:///path/to/sock?db=0`` etc...
|
|
240
|
-
|
|
241
|
-
This uri is passed directly to :meth:`coredis.Redis.from_url` with
|
|
242
|
-
the initial ``async`` removed, except for the case of ``async+redis+unix``
|
|
243
|
-
where it is replaced with ``unix``.
|
|
244
|
-
:param connection_pool: if provided, the redis client is initialized with
|
|
245
|
-
the connection pool and any other params passed as :paramref:`options`
|
|
246
|
-
:param wrap_exceptions: Whether to wrap storage exceptions in
|
|
247
|
-
:exc:`limits.errors.StorageError` before raising it.
|
|
248
|
-
:param options: all remaining keyword arguments are passed
|
|
249
|
-
directly to the constructor of :class:`coredis.Redis`
|
|
250
|
-
:raise ConfigurationError: when the redis library is not available
|
|
251
|
-
"""
|
|
252
|
-
uri = uri.replace("async+redis", "redis", 1)
|
|
253
|
-
uri = uri.replace("redis+unix", "unix")
|
|
254
|
-
|
|
255
|
-
super().__init__(uri, wrap_exceptions=wrap_exceptions, **options)
|
|
256
|
-
|
|
257
|
-
self.dependency = self.dependencies["coredis"].module
|
|
258
|
-
|
|
259
|
-
if connection_pool:
|
|
260
|
-
self.storage = self.dependency.Redis(
|
|
261
|
-
connection_pool=connection_pool, **options
|
|
262
|
-
)
|
|
263
|
-
else:
|
|
264
|
-
self.storage = self.dependency.Redis.from_url(uri, **options)
|
|
265
|
-
|
|
266
|
-
self.initialize_storage(uri)
|
|
267
|
-
|
|
268
|
-
@property
|
|
269
|
-
def base_exceptions(
|
|
270
|
-
self,
|
|
271
|
-
) -> Union[Type[Exception], tuple[Type[Exception], ...]]: # pragma: no cover
|
|
272
|
-
return self.dependency.exceptions.RedisError # type: ignore[no-any-return]
|
|
273
|
-
|
|
274
|
-
def initialize_storage(self, _uri: str) -> None:
|
|
275
|
-
# all these methods are coroutines, so must be called with await
|
|
276
|
-
self.lua_moving_window = self.storage.register_script(self.SCRIPT_MOVING_WINDOW)
|
|
277
|
-
self.lua_acquire_moving_window = self.storage.register_script(
|
|
278
|
-
self.SCRIPT_ACQUIRE_MOVING_WINDOW
|
|
279
|
-
)
|
|
280
|
-
self.lua_clear_keys = self.storage.register_script(self.SCRIPT_CLEAR_KEYS)
|
|
281
|
-
self.lua_incr_expire = self.storage.register_script(self.SCRIPT_INCR_EXPIRE)
|
|
282
|
-
self.lua_sliding_window = self.storage.register_script(
|
|
283
|
-
self.SCRIPT_SLIDING_WINDOW
|
|
284
|
-
)
|
|
285
|
-
self.lua_acquire_sliding_window = self.storage.register_script(
|
|
286
|
-
self.SCRIPT_ACQUIRE_SLIDING_WINDOW
|
|
287
|
-
)
|
|
288
|
-
|
|
289
|
-
async def incr(
|
|
290
|
-
self, key: str, expiry: int, elastic_expiry: bool = False, amount: int = 1
|
|
291
|
-
) -> int:
|
|
292
|
-
"""
|
|
293
|
-
increments the counter for a given rate limit key
|
|
294
|
-
|
|
295
|
-
:param key: the key to increment
|
|
296
|
-
:param expiry: amount in seconds for the key to expire in
|
|
297
|
-
:param amount: the number to increment by
|
|
298
|
-
"""
|
|
299
|
-
|
|
300
|
-
if elastic_expiry:
|
|
301
|
-
return await super()._incr(
|
|
302
|
-
key, expiry, self.storage, elastic_expiry, amount
|
|
303
|
-
)
|
|
304
|
-
else:
|
|
305
|
-
key = self.prefixed_key(key)
|
|
306
|
-
return cast(
|
|
307
|
-
int, await self.lua_incr_expire.execute([key], [expiry, amount])
|
|
308
|
-
)
|
|
309
|
-
|
|
310
|
-
async def get(self, key: str) -> int:
|
|
311
|
-
"""
|
|
312
|
-
:param key: the key to get the counter value for
|
|
313
|
-
"""
|
|
314
|
-
|
|
315
|
-
return await super()._get(key, self.storage)
|
|
316
|
-
|
|
317
|
-
async def clear(self, key: str) -> None:
|
|
318
|
-
"""
|
|
319
|
-
:param key: the key to clear rate limits for
|
|
320
|
-
"""
|
|
321
|
-
|
|
322
|
-
return await super()._clear(key, self.storage)
|
|
323
|
-
|
|
324
|
-
async def acquire_entry(
|
|
325
|
-
self, key: str, limit: int, expiry: int, amount: int = 1
|
|
326
|
-
) -> bool:
|
|
327
|
-
"""
|
|
328
|
-
:param key: rate limit key to acquire an entry in
|
|
329
|
-
:param limit: amount of entries allowed
|
|
330
|
-
:param expiry: expiry of the entry
|
|
331
|
-
:param amount: the number of entries to acquire
|
|
332
|
-
"""
|
|
333
|
-
|
|
334
|
-
return await super()._acquire_entry(key, limit, expiry, self.storage, amount)
|
|
335
|
-
|
|
336
|
-
async def acquire_sliding_window_entry(
|
|
337
|
-
self,
|
|
338
|
-
key: str,
|
|
339
|
-
limit: int,
|
|
340
|
-
expiry: int,
|
|
341
|
-
amount: int = 1,
|
|
342
|
-
) -> bool:
|
|
343
|
-
current_key = self._current_window_key(key)
|
|
344
|
-
previous_key = self._previous_window_key(key)
|
|
345
|
-
return await super()._acquire_sliding_window_entry(
|
|
346
|
-
previous_key, current_key, limit, expiry, amount
|
|
347
|
-
)
|
|
348
|
-
|
|
349
|
-
async def get_expiry(self, key: str) -> float:
|
|
350
|
-
"""
|
|
351
|
-
:param key: the key to get the expiry for
|
|
352
|
-
"""
|
|
353
|
-
|
|
354
|
-
return await super()._get_expiry(key, self.storage)
|
|
355
|
-
|
|
356
|
-
async def check(self) -> bool:
|
|
357
|
-
"""
|
|
358
|
-
Check if storage is healthy by calling :meth:`coredis.Redis.ping`
|
|
359
|
-
"""
|
|
360
|
-
|
|
361
|
-
return await super()._check(self.storage)
|
|
362
|
-
|
|
363
|
-
async def reset(self) -> Optional[int]:
|
|
364
|
-
"""
|
|
365
|
-
This function calls a Lua Script to delete keys prefixed with
|
|
366
|
-
``self.PREFIX`` in blocks of 5000.
|
|
367
|
-
|
|
368
|
-
.. warning:: This operation was designed to be fast, but was not tested
|
|
369
|
-
on a large production based system. Be careful with its usage as it
|
|
370
|
-
could be slow on very large data sets.
|
|
371
|
-
"""
|
|
372
|
-
|
|
373
|
-
prefix = self.prefixed_key("*")
|
|
374
|
-
return cast(int, await self.lua_clear_keys.execute([prefix]))
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
@versionadded(version="2.1")
|
|
378
|
-
class RedisClusterStorage(RedisStorage):
|
|
379
|
-
"""
|
|
380
|
-
Rate limit storage with redis cluster as backend
|
|
381
|
-
|
|
382
|
-
Depends on :pypi:`coredis`
|
|
383
|
-
"""
|
|
384
|
-
|
|
385
|
-
STORAGE_SCHEME = ["async+redis+cluster"]
|
|
386
|
-
"""
|
|
387
|
-
The storage schemes for redis cluster to be used in an async context
|
|
388
|
-
"""
|
|
389
|
-
|
|
390
|
-
DEFAULT_OPTIONS: dict[str, Union[float, str, bool]] = {
|
|
391
|
-
"max_connections": 1000,
|
|
392
|
-
}
|
|
393
|
-
"Default options passed to :class:`coredis.RedisCluster`"
|
|
394
|
-
|
|
395
|
-
def __init__(
|
|
396
|
-
self,
|
|
397
|
-
uri: str,
|
|
398
|
-
wrap_exceptions: bool = False,
|
|
399
|
-
**options: Union[float, str, bool],
|
|
400
|
-
) -> None:
|
|
401
|
-
"""
|
|
402
|
-
:param uri: url of the form
|
|
403
|
-
``async+redis+cluster://[:password]@host:port,host:port``
|
|
404
|
-
:param options: all remaining keyword arguments are passed
|
|
405
|
-
directly to the constructor of :class:`coredis.RedisCluster`
|
|
406
|
-
:raise ConfigurationError: when the coredis library is not
|
|
407
|
-
available or if the redis host cannot be pinged.
|
|
408
|
-
"""
|
|
409
|
-
parsed = urllib.parse.urlparse(uri)
|
|
410
|
-
parsed_auth: dict[str, Union[float, str, bool]] = {}
|
|
411
|
-
|
|
412
|
-
if parsed.username:
|
|
413
|
-
parsed_auth["username"] = parsed.username
|
|
414
|
-
if parsed.password:
|
|
415
|
-
parsed_auth["password"] = parsed.password
|
|
416
|
-
|
|
417
|
-
sep = parsed.netloc.find("@") + 1
|
|
418
|
-
cluster_hosts = []
|
|
419
|
-
|
|
420
|
-
for loc in parsed.netloc[sep:].split(","):
|
|
421
|
-
host, port = loc.split(":")
|
|
422
|
-
cluster_hosts.append({"host": host, "port": int(port)})
|
|
423
|
-
|
|
424
|
-
super(RedisStorage, self).__init__(
|
|
425
|
-
uri, wrap_exceptions=wrap_exceptions, **options
|
|
426
|
-
)
|
|
427
|
-
|
|
428
|
-
self.dependency = self.dependencies["coredis"].module
|
|
429
|
-
|
|
430
|
-
self.storage: "coredis.RedisCluster[str]" = self.dependency.RedisCluster(
|
|
431
|
-
startup_nodes=cluster_hosts,
|
|
432
|
-
**{**self.DEFAULT_OPTIONS, **parsed_auth, **options},
|
|
433
|
-
)
|
|
434
|
-
self.initialize_storage(uri)
|
|
435
|
-
|
|
436
|
-
async def reset(self) -> Optional[int]:
|
|
437
|
-
"""
|
|
438
|
-
Redis Clusters are sharded and deleting across shards
|
|
439
|
-
can't be done atomically. Because of this, this reset loops over all
|
|
440
|
-
keys that are prefixed with ``self.PREFIX`` and calls delete on them,
|
|
441
|
-
one at a time.
|
|
442
|
-
|
|
443
|
-
.. warning:: This operation was not tested with extremely large data sets.
|
|
444
|
-
On a large production based system, care should be taken with its
|
|
445
|
-
usage as it could be slow on very large data sets
|
|
446
|
-
"""
|
|
447
|
-
|
|
448
|
-
prefix = self.prefixed_key("*")
|
|
449
|
-
keys = await self.storage.keys(prefix)
|
|
450
|
-
count = 0
|
|
451
|
-
for key in keys:
|
|
452
|
-
count += await self.storage.delete([key])
|
|
453
|
-
return count
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
@versionadded(version="2.1")
|
|
457
|
-
class RedisSentinelStorage(RedisStorage):
|
|
458
|
-
"""
|
|
459
|
-
Rate limit storage with redis sentinel as backend
|
|
460
|
-
|
|
461
|
-
Depends on :pypi:`coredis`
|
|
462
|
-
"""
|
|
463
|
-
|
|
464
|
-
STORAGE_SCHEME = ["async+redis+sentinel"]
|
|
465
|
-
"""The storage scheme for redis accessed via a redis sentinel installation"""
|
|
466
|
-
|
|
467
|
-
DEPENDENCIES = {"coredis.sentinel": Version("3.4.0")}
|
|
468
|
-
|
|
469
|
-
def __init__(
|
|
470
|
-
self,
|
|
471
|
-
uri: str,
|
|
472
|
-
service_name: Optional[str] = None,
|
|
473
|
-
use_replicas: bool = True,
|
|
474
|
-
sentinel_kwargs: Optional[dict[str, Union[float, str, bool]]] = None,
|
|
475
|
-
**options: Union[float, str, bool],
|
|
476
|
-
):
|
|
477
|
-
"""
|
|
478
|
-
:param uri: url of the form
|
|
479
|
-
``async+redis+sentinel://host:port,host:port/service_name``
|
|
480
|
-
:param service_name, optional: sentinel service name
|
|
481
|
-
(if not provided in `uri`)
|
|
482
|
-
:param use_replicas: Whether to use replicas for read only operations
|
|
483
|
-
:param sentinel_kwargs, optional: kwargs to pass as
|
|
484
|
-
``sentinel_kwargs`` to :class:`coredis.sentinel.Sentinel`
|
|
485
|
-
:param options: all remaining keyword arguments are passed
|
|
486
|
-
directly to the constructor of :class:`coredis.sentinel.Sentinel`
|
|
487
|
-
:raise ConfigurationError: when the coredis library is not available
|
|
488
|
-
or if the redis primary host cannot be pinged.
|
|
489
|
-
"""
|
|
490
|
-
|
|
491
|
-
parsed = urllib.parse.urlparse(uri)
|
|
492
|
-
sentinel_configuration = []
|
|
493
|
-
connection_options = options.copy()
|
|
494
|
-
sentinel_options = sentinel_kwargs.copy() if sentinel_kwargs else {}
|
|
495
|
-
parsed_auth: dict[str, Union[float, str, bool]] = {}
|
|
496
|
-
|
|
497
|
-
if parsed.username:
|
|
498
|
-
parsed_auth["username"] = parsed.username
|
|
499
|
-
|
|
500
|
-
if parsed.password:
|
|
501
|
-
parsed_auth["password"] = parsed.password
|
|
502
|
-
|
|
503
|
-
sep = parsed.netloc.find("@") + 1
|
|
504
|
-
|
|
505
|
-
for loc in parsed.netloc[sep:].split(","):
|
|
506
|
-
host, port = loc.split(":")
|
|
507
|
-
sentinel_configuration.append((host, int(port)))
|
|
508
|
-
self.service_name = (
|
|
509
|
-
parsed.path.replace("/", "") if parsed.path else service_name
|
|
510
|
-
)
|
|
511
|
-
|
|
512
|
-
if self.service_name is None:
|
|
513
|
-
raise ConfigurationError("'service_name' not provided")
|
|
514
|
-
|
|
515
|
-
super(RedisStorage, self).__init__()
|
|
516
|
-
|
|
517
|
-
self.dependency = self.dependencies["coredis.sentinel"].module
|
|
518
|
-
|
|
519
|
-
self.sentinel = self.dependency.Sentinel(
|
|
520
|
-
sentinel_configuration,
|
|
521
|
-
sentinel_kwargs={**parsed_auth, **sentinel_options},
|
|
522
|
-
**{**parsed_auth, **connection_options},
|
|
523
|
-
)
|
|
524
|
-
self.storage = self.sentinel.primary_for(self.service_name)
|
|
525
|
-
self.storage_replica = self.sentinel.replica_for(self.service_name)
|
|
526
|
-
self.use_replicas = use_replicas
|
|
527
|
-
self.initialize_storage(uri)
|
|
528
|
-
|
|
529
|
-
async def get(self, key: str) -> int:
|
|
530
|
-
"""
|
|
531
|
-
:param key: the key to get the counter value for
|
|
532
|
-
"""
|
|
533
|
-
|
|
534
|
-
return await super()._get(
|
|
535
|
-
key, self.storage_replica if self.use_replicas else self.storage
|
|
536
|
-
)
|
|
537
|
-
|
|
538
|
-
async def get_expiry(self, key: str) -> float:
|
|
539
|
-
"""
|
|
540
|
-
:param key: the key to get the expiry for
|
|
541
|
-
"""
|
|
542
|
-
|
|
543
|
-
return await super()._get_expiry(
|
|
544
|
-
key, self.storage_replica if self.use_replicas else self.storage
|
|
545
|
-
)
|
|
546
|
-
|
|
547
|
-
async def check(self) -> bool:
|
|
548
|
-
"""
|
|
549
|
-
Check if storage is healthy by calling :meth:`coredis.Redis.ping`
|
|
550
|
-
on the replica.
|
|
551
|
-
"""
|
|
552
|
-
|
|
553
|
-
return await super()._check(
|
|
554
|
-
self.storage_replica if self.use_replicas else self.storage
|
|
555
|
-
)
|
limits-4.1.dist-info/RECORD
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
limits/__init__.py,sha256=j_yVhgN9pdz8o5rQjVwdJTBSq8F-CTzof9kkiYgjRbw,728
|
|
2
|
-
limits/_version.py,sha256=PIGOsmzILcAnImlW2gkexgfobAMt1PHUP-qZuYYI6Es,495
|
|
3
|
-
limits/errors.py,sha256=xCKGOVJiD-g8FlsQQb17AW2pTUvalYSuizPpvEVoYJE,626
|
|
4
|
-
limits/limits.py,sha256=YzzZP8_ay_zlMMnnY2xhAcFTTFvFe5HEk8NQlvUTru4,4907
|
|
5
|
-
limits/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
-
limits/strategies.py,sha256=18DpCMqDGaZDMYJYY9RuFCA20SINT3az8G-IWCG9bQE,10877
|
|
7
|
-
limits/typing.py,sha256=Me0f4A544qM73fgcr1PU3lrO9zj4EaNaQ6aQVAHfjuc,4193
|
|
8
|
-
limits/util.py,sha256=XAl7V8vZtxL4WSZ7nyFau0R6-gMUDeSV3QQ531T1tYI,6059
|
|
9
|
-
limits/version.py,sha256=YwkF3dtq1KGzvmL3iVGctA8NNtGlK_0arrzZkZGVjUs,47
|
|
10
|
-
limits/aio/__init__.py,sha256=IOetunwQy1c5GefzitK8lewbTzHGiE-kmE9NlqSdr3U,82
|
|
11
|
-
limits/aio/strategies.py,sha256=bY_F-fv0CgQjOHJJPA3iNFuomBvBiTC-3KQ-jSfV_0Y,10744
|
|
12
|
-
limits/aio/storage/__init__.py,sha256=QFoni6CYQMN-UPmja2UXiJmB_Fr6JiVWerDz3uS_HOQ,659
|
|
13
|
-
limits/aio/storage/base.py,sha256=HK6TjsJhar_6y22SBmrJJGMCmFdCmhe69LUOoWhkr3E,6494
|
|
14
|
-
limits/aio/storage/etcd.py,sha256=TEtuPP6l31e5zI7k6dGzNJVM6Vmt0wrm-QzkZvkPPvg,5004
|
|
15
|
-
limits/aio/storage/memcached.py,sha256=dQmSfBRQoUJn4Sj4kYTHd7vEQuMzY3tTp-bnSzfLsZw,10362
|
|
16
|
-
limits/aio/storage/memory.py,sha256=7qrI3cg7QnWmaLLryvqoxCLP1221ExD8UMkh7uCfuuE,9152
|
|
17
|
-
limits/aio/storage/mongodb.py,sha256=6SPdleRWhk0eqQoRZJPEgbRrrt9Pb5IOdrK0tvLxIo4,19371
|
|
18
|
-
limits/aio/storage/redis.py,sha256=sff6HZoEJXLR175lV9k14HjWgmf7Q4hK68N1ZL9BFtE,18746
|
|
19
|
-
limits/resources/redis/lua_scripts/acquire_moving_window.lua,sha256=5CFJX7D6T6RG5SFr6eVZ6zepmI1EkGWmKeVEO4QNrWo,483
|
|
20
|
-
limits/resources/redis/lua_scripts/acquire_sliding_window.lua,sha256=OhVI1MAN_gT92P6r-2CEmvy1yvQVjYCCZxWIxfXYceY,1329
|
|
21
|
-
limits/resources/redis/lua_scripts/clear_keys.lua,sha256=zU0cVfLGmapRQF9x9u0GclapM_IB2pJLszNzVQ1QRK4,184
|
|
22
|
-
limits/resources/redis/lua_scripts/incr_expire.lua,sha256=Uq9NcrrcDI-F87TDAJexoSJn2SDgeXIUEYozCp9S3oA,195
|
|
23
|
-
limits/resources/redis/lua_scripts/moving_window.lua,sha256=5hUZghISDh8Cbg8HJediM_OKjjNMF-0CBywWmsc93vA,430
|
|
24
|
-
limits/resources/redis/lua_scripts/sliding_window.lua,sha256=qG3Yg30Dq54QpRUcR9AOrKQ5bdJiaYpCacTm6Kxblvc,713
|
|
25
|
-
limits/storage/__init__.py,sha256=mGbsTP5P8beXXKqYxsicNW8leU9wfotCy-GIcN7pdKs,2662
|
|
26
|
-
limits/storage/base.py,sha256=pqH9ARhu35oTLew0K1WfT6QHPLMp4NzxHrHBWZ2mRDM,7113
|
|
27
|
-
limits/storage/etcd.py,sha256=F66CdOlZMapEvAF55D8fn3jktkx-yEqAfLza-n2T6NY,4668
|
|
28
|
-
limits/storage/memcached.py,sha256=wIegarAR6-19N6T-_YzV0zBd3-W3kf6osVSCQ5DMBRw,11233
|
|
29
|
-
limits/storage/memory.py,sha256=a6kbG2f5lg9aG3oRWXPyzYjwFBn_aD_n0ejbqoEj-b8,8734
|
|
30
|
-
limits/storage/mongodb.py,sha256=RRK9NXg2Sq-sLAfOQp9S1jVbbheL8yGGJLvwfgWsi-g,18304
|
|
31
|
-
limits/storage/redis.py,sha256=Pp5o3yLDiTHomHu1pUL6Ghz4TZOcoDirqSN-UnDZKv4,9652
|
|
32
|
-
limits/storage/redis_cluster.py,sha256=hAwBGsU1FkG4w2xjtzUJF8g3f_iP_qzCz1B4ZW63I9A,3733
|
|
33
|
-
limits/storage/redis_sentinel.py,sha256=h1wpBM3NYosBPSavTrhH16yFw17911YID04AB6WYSJM,3561
|
|
34
|
-
limits/storage/registry.py,sha256=Az-0CkVv9b5uZAvIVDYabilngIsChdFdtnTOur1JA94,689
|
|
35
|
-
limits-4.1.dist-info/LICENSE.txt,sha256=T6i7kq7F5gIPfcno9FCxU5Hcwm22Bjq0uHZV3ElcjsQ,1061
|
|
36
|
-
limits-4.1.dist-info/METADATA,sha256=u7wxlD0LDCr1uoi4e6nS9rKMtjzGmfHUvO4Tkz9-DI4,10992
|
|
37
|
-
limits-4.1.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
|
|
38
|
-
limits-4.1.dist-info/top_level.txt,sha256=C7g5ahldPoU2s6iWTaJayUrbGmPK1d6e9t5Nn0vQ2jM,7
|
|
39
|
-
limits-4.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|