pacegate 0.1.0__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.
- pacegate-0.1.0/LICENSE +21 -0
- pacegate-0.1.0/PKG-INFO +48 -0
- pacegate-0.1.0/README.md +38 -0
- pacegate-0.1.0/pyproject.toml +19 -0
- pacegate-0.1.0/setup.cfg +4 -0
- pacegate-0.1.0/src/pacegate/__init__.py +9 -0
- pacegate-0.1.0/src/pacegate/asgi.py +37 -0
- pacegate-0.1.0/src/pacegate/limiter.py +163 -0
- pacegate-0.1.0/src/pacegate/py.typed +0 -0
- pacegate-0.1.0/src/pacegate.egg-info/PKG-INFO +48 -0
- pacegate-0.1.0/src/pacegate.egg-info/SOURCES.txt +12 -0
- pacegate-0.1.0/src/pacegate.egg-info/dependency_links.txt +1 -0
- pacegate-0.1.0/src/pacegate.egg-info/top_level.txt +1 -0
- pacegate-0.1.0/tests/test_rate_limit.py +65 -0
pacegate-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pacegate contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pacegate-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pacegate
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Request rate limits and temporary blocks for Python web applications
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# pacegate
|
|
12
|
+
|
|
13
|
+
Apply fixed-window rate limits to Python applications. The package supports Python 3.10 or later and has zero runtime dependencies.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
python -m pip install pacegate
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## ASGI
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from pacegate import RateLimitMiddleware, RateLimiter, Rule
|
|
23
|
+
|
|
24
|
+
limiter = RateLimiter([
|
|
25
|
+
Rule("client", ("ip",), 20, window_seconds=60, block_seconds=120),
|
|
26
|
+
Rule("endpoint", ("endpoint",), 100, window_seconds=60),
|
|
27
|
+
])
|
|
28
|
+
|
|
29
|
+
def identify(scope):
|
|
30
|
+
client = scope.get("client")
|
|
31
|
+
return {"ip": client[0] if client else None, "endpoint": "public-api"}
|
|
32
|
+
|
|
33
|
+
app = RateLimitMiddleware(app, limiter, identify)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Wrap the application after it has been created. An applicable rule may combine `ip`, `user_id`, and `endpoint`. Rules skip identities with missing dimensions. Supply trusted client identity and stable endpoint keys from the application. The wrapper returns HTTP 429 with `Retry-After` and `Cache-Control: no-store` when a rule rejects a request.
|
|
37
|
+
|
|
38
|
+
Window and block durations range from one millisecond to one year. An optional temporary block starts at first rejection and lasts at least until the window ends. Later rejections do not extend it. Requests near adjacent windows can consume both windows of quota in a short period. Call `await limiter.check(identity)` to integrate without ASGI.
|
|
39
|
+
|
|
40
|
+
The default `MemoryStore` is thread-safe and process-local. It raises when all of its bounded entries are in use. Shared quotas across processes require a custom `Store` that atomically consumes per key. A store can return its decision synchronously or asynchronously. Use distinct namespaces for unrelated rules that share the same store.
|
|
41
|
+
|
|
42
|
+
## Development
|
|
43
|
+
|
|
44
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
45
|
+
|
|
46
|
+
## License
|
|
47
|
+
|
|
48
|
+
MIT
|
pacegate-0.1.0/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# pacegate
|
|
2
|
+
|
|
3
|
+
Apply fixed-window rate limits to Python applications. The package supports Python 3.10 or later and has zero runtime dependencies.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
python -m pip install pacegate
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## ASGI
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from pacegate import RateLimitMiddleware, RateLimiter, Rule
|
|
13
|
+
|
|
14
|
+
limiter = RateLimiter([
|
|
15
|
+
Rule("client", ("ip",), 20, window_seconds=60, block_seconds=120),
|
|
16
|
+
Rule("endpoint", ("endpoint",), 100, window_seconds=60),
|
|
17
|
+
])
|
|
18
|
+
|
|
19
|
+
def identify(scope):
|
|
20
|
+
client = scope.get("client")
|
|
21
|
+
return {"ip": client[0] if client else None, "endpoint": "public-api"}
|
|
22
|
+
|
|
23
|
+
app = RateLimitMiddleware(app, limiter, identify)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Wrap the application after it has been created. An applicable rule may combine `ip`, `user_id`, and `endpoint`. Rules skip identities with missing dimensions. Supply trusted client identity and stable endpoint keys from the application. The wrapper returns HTTP 429 with `Retry-After` and `Cache-Control: no-store` when a rule rejects a request.
|
|
27
|
+
|
|
28
|
+
Window and block durations range from one millisecond to one year. An optional temporary block starts at first rejection and lasts at least until the window ends. Later rejections do not extend it. Requests near adjacent windows can consume both windows of quota in a short period. Call `await limiter.check(identity)` to integrate without ASGI.
|
|
29
|
+
|
|
30
|
+
The default `MemoryStore` is thread-safe and process-local. It raises when all of its bounded entries are in use. Shared quotas across processes require a custom `Store` that atomically consumes per key. A store can return its decision synchronously or asynchronously. Use distinct namespaces for unrelated rules that share the same store.
|
|
31
|
+
|
|
32
|
+
## Development
|
|
33
|
+
|
|
34
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
35
|
+
|
|
36
|
+
## License
|
|
37
|
+
|
|
38
|
+
MIT
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pacegate"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Request rate limits and temporary blocks for Python web applications"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
|
|
15
|
+
[tool.setuptools.packages.find]
|
|
16
|
+
where = ["src"]
|
|
17
|
+
|
|
18
|
+
[tool.setuptools.package-data]
|
|
19
|
+
pacegate = ["py.typed"]
|
pacegate-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Framework-independent rate limiting and temporary blocks."""
|
|
2
|
+
|
|
3
|
+
from .asgi import RateLimitMiddleware
|
|
4
|
+
from .limiter import Decision, MemoryStore, Operation, RateLimiter, Rule, Store, StoreDecision
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"Decision", "MemoryStore", "Operation", "RateLimiter", "RateLimitMiddleware",
|
|
8
|
+
"Rule", "Store", "StoreDecision",
|
|
9
|
+
]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""ASGI adapter for rate limiting."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
4
|
+
from inspect import isawaitable
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .limiter import RateLimiter
|
|
8
|
+
|
|
9
|
+
Identity = Mapping[str, str | None]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class RateLimitMiddleware:
|
|
13
|
+
"""Return HTTP 429 on rejection before calling the application."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, app: Any, limiter: RateLimiter,
|
|
16
|
+
identify: Callable[[dict[str, Any]], Identity | Awaitable[Identity]]) -> None:
|
|
17
|
+
self.app = app
|
|
18
|
+
self.limiter = limiter
|
|
19
|
+
self.identify = identify
|
|
20
|
+
|
|
21
|
+
async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
|
|
22
|
+
if scope.get("type") != "http":
|
|
23
|
+
await self.app(scope, receive, send)
|
|
24
|
+
return
|
|
25
|
+
identity = self.identify(scope)
|
|
26
|
+
if isawaitable(identity):
|
|
27
|
+
identity = await identity
|
|
28
|
+
decision = await self.limiter.check(identity)
|
|
29
|
+
if decision.allowed:
|
|
30
|
+
await self.app(scope, receive, send)
|
|
31
|
+
return
|
|
32
|
+
await send({
|
|
33
|
+
"type": "http.response.start", "status": 429,
|
|
34
|
+
"headers": [(b"retry-after", str(decision.retry_after).encode("ascii")),
|
|
35
|
+
(b"cache-control", b"no-store"), (b"content-length", b"0")],
|
|
36
|
+
})
|
|
37
|
+
await send({"type": "http.response.body", "body": b""})
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Fixed-window rate limits with atomic per-key storage."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from inspect import isawaitable
|
|
6
|
+
from math import ceil, isfinite
|
|
7
|
+
import re
|
|
8
|
+
from threading import Lock
|
|
9
|
+
from time import monotonic
|
|
10
|
+
from typing import Protocol
|
|
11
|
+
|
|
12
|
+
_DIMENSIONS = ("ip", "user_id", "endpoint")
|
|
13
|
+
Key = tuple[str, ...]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _duration(value: float) -> bool:
|
|
17
|
+
return type(value) in {int, float} and 0.001 <= value <= 31_536_000
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _label(value: str) -> bool:
|
|
21
|
+
return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", value) is not None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Rule:
|
|
26
|
+
id: str
|
|
27
|
+
by: tuple[str, ...]
|
|
28
|
+
limit: int
|
|
29
|
+
window_seconds: float
|
|
30
|
+
block_seconds: float | None = None
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
if not _label(self.id):
|
|
34
|
+
raise ValueError("Invalid rate limit rule ID.")
|
|
35
|
+
if not isinstance(self.by, tuple) or not self.by or len(set(self.by)) != len(self.by) or any(
|
|
36
|
+
item not in _DIMENSIONS for item in self.by
|
|
37
|
+
):
|
|
38
|
+
raise ValueError("Rules require distinct rate limit dimensions.")
|
|
39
|
+
if type(self.limit) is not int or self.limit < 1:
|
|
40
|
+
raise ValueError("The limit must be a positive integer.")
|
|
41
|
+
if not _duration(self.window_seconds) or (
|
|
42
|
+
self.block_seconds is not None and not _duration(self.block_seconds)
|
|
43
|
+
):
|
|
44
|
+
raise ValueError("Rate limit durations must be between one millisecond and one year.")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class Operation:
|
|
49
|
+
key: Key
|
|
50
|
+
limit: int
|
|
51
|
+
window_seconds: float
|
|
52
|
+
block_seconds: float | None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class StoreDecision:
|
|
57
|
+
allowed: bool
|
|
58
|
+
retry_seconds: float = 0
|
|
59
|
+
blocked: bool = False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Store(Protocol):
|
|
63
|
+
def consume(self, operation: Operation) -> StoreDecision | Awaitable[StoreDecision]:
|
|
64
|
+
"""Atomically check and consume an attempt for a single key."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class _Bucket:
|
|
69
|
+
count: int
|
|
70
|
+
expires: float
|
|
71
|
+
blocked: bool = False
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class MemoryStore:
|
|
75
|
+
"""Thread-safe process-local storage."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, max_entries: int = 10_000, *, clock: Callable[[], float] = monotonic):
|
|
78
|
+
if type(max_entries) is not int or max_entries < 1:
|
|
79
|
+
raise ValueError("max_entries must be a positive integer.")
|
|
80
|
+
self._buckets: dict[Key, _Bucket] = {}
|
|
81
|
+
self._max_entries = max_entries
|
|
82
|
+
self._clock = clock
|
|
83
|
+
self._lock = Lock()
|
|
84
|
+
self._next_expiry = float("inf")
|
|
85
|
+
|
|
86
|
+
def consume(self, operation: Operation) -> StoreDecision:
|
|
87
|
+
with self._lock:
|
|
88
|
+
now = self._clock()
|
|
89
|
+
if not isfinite(now):
|
|
90
|
+
raise ValueError("The rate limit clock must return finite time.")
|
|
91
|
+
bucket = self._buckets.get(operation.key)
|
|
92
|
+
if bucket is None or bucket.expires <= now:
|
|
93
|
+
if bucket is None and len(self._buckets) >= self._max_entries:
|
|
94
|
+
if now >= self._next_expiry:
|
|
95
|
+
self._buckets = {key: value for key, value in self._buckets.items()
|
|
96
|
+
if value.expires > now}
|
|
97
|
+
self._next_expiry = min(
|
|
98
|
+
(value.expires for value in self._buckets.values()), default=float("inf"),
|
|
99
|
+
)
|
|
100
|
+
if len(self._buckets) >= self._max_entries:
|
|
101
|
+
raise RuntimeError("Rate limit store capacity exceeded.")
|
|
102
|
+
expires = now + operation.window_seconds
|
|
103
|
+
self._buckets[operation.key] = _Bucket(1, expires)
|
|
104
|
+
self._next_expiry = min(self._next_expiry, expires)
|
|
105
|
+
return StoreDecision(True)
|
|
106
|
+
if not bucket.blocked and bucket.count < operation.limit:
|
|
107
|
+
bucket.count += 1
|
|
108
|
+
return StoreDecision(True)
|
|
109
|
+
if not bucket.blocked and operation.block_seconds is not None:
|
|
110
|
+
bucket.blocked = True
|
|
111
|
+
bucket.expires = max(bucket.expires, now + operation.block_seconds)
|
|
112
|
+
return StoreDecision(False, bucket.expires - now, bucket.blocked)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True)
|
|
116
|
+
class Decision:
|
|
117
|
+
allowed: bool
|
|
118
|
+
rule_id: str | None = None
|
|
119
|
+
retry_after: int = 0
|
|
120
|
+
blocked: bool = False
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class RateLimiter:
|
|
124
|
+
"""Evaluate every applicable rule and report the longest rejection."""
|
|
125
|
+
|
|
126
|
+
def __init__(self, rules: Sequence[Rule], *, store: Store | None = None,
|
|
127
|
+
namespace: str = "pacegate") -> None:
|
|
128
|
+
self.rules = tuple(rules)
|
|
129
|
+
if not self.rules or len({rule.id for rule in self.rules}) != len(self.rules):
|
|
130
|
+
raise ValueError("At least one rule with a unique ID is required.")
|
|
131
|
+
if not _label(namespace):
|
|
132
|
+
raise ValueError("Invalid rate limiter namespace.")
|
|
133
|
+
self.namespace = namespace
|
|
134
|
+
self.store = store if store is not None else MemoryStore()
|
|
135
|
+
|
|
136
|
+
async def check(self, identity: Mapping[str, str | None]) -> Decision:
|
|
137
|
+
values = {}
|
|
138
|
+
for dimension in _DIMENSIONS:
|
|
139
|
+
value = identity.get(dimension)
|
|
140
|
+
if value is None or value == "":
|
|
141
|
+
continue
|
|
142
|
+
if not isinstance(value, str) or len(value) > 512:
|
|
143
|
+
raise ValueError("Rate limit dimensions must be strings of at most 512 characters.")
|
|
144
|
+
values[dimension] = value
|
|
145
|
+
longest = 0.0
|
|
146
|
+
result = Decision(True)
|
|
147
|
+
for rule in self.rules:
|
|
148
|
+
if any(dimension not in values for dimension in rule.by):
|
|
149
|
+
continue
|
|
150
|
+
key = (self.namespace, rule.id, *(values[dimension] for dimension in rule.by))
|
|
151
|
+
outcome = self.store.consume(Operation(key, rule.limit, rule.window_seconds, rule.block_seconds))
|
|
152
|
+
if isawaitable(outcome):
|
|
153
|
+
outcome = await outcome
|
|
154
|
+
if not isinstance(outcome, StoreDecision) or type(outcome.allowed) is not bool:
|
|
155
|
+
raise TypeError("Invalid rate limit store decision.")
|
|
156
|
+
if not outcome.allowed:
|
|
157
|
+
retry = outcome.retry_seconds
|
|
158
|
+
if type(retry) not in {int, float} or not isfinite(retry) or retry <= 0:
|
|
159
|
+
raise ValueError("Invalid rate limit retry interval.")
|
|
160
|
+
if retry > longest:
|
|
161
|
+
longest = retry
|
|
162
|
+
result = Decision(False, rule.id, ceil(retry), outcome.blocked)
|
|
163
|
+
return result
|
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pacegate
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Request rate limits and temporary blocks for Python web applications
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# pacegate
|
|
12
|
+
|
|
13
|
+
Apply fixed-window rate limits to Python applications. The package supports Python 3.10 or later and has zero runtime dependencies.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
python -m pip install pacegate
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## ASGI
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from pacegate import RateLimitMiddleware, RateLimiter, Rule
|
|
23
|
+
|
|
24
|
+
limiter = RateLimiter([
|
|
25
|
+
Rule("client", ("ip",), 20, window_seconds=60, block_seconds=120),
|
|
26
|
+
Rule("endpoint", ("endpoint",), 100, window_seconds=60),
|
|
27
|
+
])
|
|
28
|
+
|
|
29
|
+
def identify(scope):
|
|
30
|
+
client = scope.get("client")
|
|
31
|
+
return {"ip": client[0] if client else None, "endpoint": "public-api"}
|
|
32
|
+
|
|
33
|
+
app = RateLimitMiddleware(app, limiter, identify)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Wrap the application after it has been created. An applicable rule may combine `ip`, `user_id`, and `endpoint`. Rules skip identities with missing dimensions. Supply trusted client identity and stable endpoint keys from the application. The wrapper returns HTTP 429 with `Retry-After` and `Cache-Control: no-store` when a rule rejects a request.
|
|
37
|
+
|
|
38
|
+
Window and block durations range from one millisecond to one year. An optional temporary block starts at first rejection and lasts at least until the window ends. Later rejections do not extend it. Requests near adjacent windows can consume both windows of quota in a short period. Call `await limiter.check(identity)` to integrate without ASGI.
|
|
39
|
+
|
|
40
|
+
The default `MemoryStore` is thread-safe and process-local. It raises when all of its bounded entries are in use. Shared quotas across processes require a custom `Store` that atomically consumes per key. A store can return its decision synchronously or asynchronously. Use distinct namespaces for unrelated rules that share the same store.
|
|
41
|
+
|
|
42
|
+
## Development
|
|
43
|
+
|
|
44
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
45
|
+
|
|
46
|
+
## License
|
|
47
|
+
|
|
48
|
+
MIT
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/pacegate/__init__.py
|
|
5
|
+
src/pacegate/asgi.py
|
|
6
|
+
src/pacegate/limiter.py
|
|
7
|
+
src/pacegate/py.typed
|
|
8
|
+
src/pacegate.egg-info/PKG-INFO
|
|
9
|
+
src/pacegate.egg-info/SOURCES.txt
|
|
10
|
+
src/pacegate.egg-info/dependency_links.txt
|
|
11
|
+
src/pacegate.egg-info/top_level.txt
|
|
12
|
+
tests/test_rate_limit.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pacegate
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
from pacegate import MemoryStore, RateLimiter, RateLimitMiddleware, Rule, StoreDecision
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class LimiterTests(unittest.IsolatedAsyncioTestCase):
|
|
8
|
+
def test_rejects_durations_below_clock_resolution_contract(self):
|
|
9
|
+
with self.assertRaises(ValueError):
|
|
10
|
+
Rule("client", ("ip",), 1, 1e-20)
|
|
11
|
+
|
|
12
|
+
async def test_compound_rules_and_block_expiration(self):
|
|
13
|
+
time = 0.0
|
|
14
|
+
limiter = RateLimiter([Rule("user-route", ("user_id", "endpoint"), 1, 1, 4)],
|
|
15
|
+
store=MemoryStore(clock=lambda: time))
|
|
16
|
+
identity = {"user_id": "u", "endpoint": "a"}
|
|
17
|
+
self.assertTrue((await limiter.check({"endpoint": "a"})).allowed)
|
|
18
|
+
self.assertTrue((await limiter.check(identity)).allowed)
|
|
19
|
+
self.assertTrue((await limiter.check({"user_id": "u", "endpoint": "b"})).allowed)
|
|
20
|
+
time = 0.5
|
|
21
|
+
denied = await limiter.check(identity)
|
|
22
|
+
self.assertTrue(denied.blocked)
|
|
23
|
+
self.assertEqual(denied.retry_after, 4)
|
|
24
|
+
time = 3.5
|
|
25
|
+
self.assertEqual((await limiter.check(identity)).retry_after, 1)
|
|
26
|
+
time = 4.5
|
|
27
|
+
self.assertTrue((await limiter.check(identity)).allowed)
|
|
28
|
+
|
|
29
|
+
async def test_memory_capacity_and_concurrent_attempts(self):
|
|
30
|
+
time = 0.0
|
|
31
|
+
limiter = RateLimiter([Rule("client", ("ip",), 2, 1)],
|
|
32
|
+
store=MemoryStore(max_entries=1, clock=lambda: time))
|
|
33
|
+
result = await asyncio.gather(*(limiter.check({"ip": "a"}) for _ in range(10)))
|
|
34
|
+
self.assertEqual(sum(result_item.allowed for result_item in result), 2)
|
|
35
|
+
with self.assertRaises(RuntimeError):
|
|
36
|
+
await limiter.check({"ip": "b"})
|
|
37
|
+
time = 1
|
|
38
|
+
self.assertTrue((await limiter.check({"ip": "b"})).allowed)
|
|
39
|
+
|
|
40
|
+
async def test_longest_precise_retry_for_async_store(self):
|
|
41
|
+
class SharedStore:
|
|
42
|
+
async def consume(self, operation):
|
|
43
|
+
return StoreDecision(False, operation.window_seconds)
|
|
44
|
+
|
|
45
|
+
limiter = RateLimiter([Rule("short", ("ip",), 1, 0.2), Rule("long", ("ip",), 1, 0.8)],
|
|
46
|
+
store=SharedStore())
|
|
47
|
+
decision = await limiter.check({"ip": "a"})
|
|
48
|
+
self.assertEqual((decision.rule_id, decision.retry_after), ("long", 1))
|
|
49
|
+
|
|
50
|
+
async def test_middleware_stops_rejected_requests(self):
|
|
51
|
+
async def app(scope, receive, send):
|
|
52
|
+
await send({"type": "http.response.start", "status": 200, "headers": []})
|
|
53
|
+
|
|
54
|
+
output = []
|
|
55
|
+
|
|
56
|
+
async def send(message):
|
|
57
|
+
output.append(message)
|
|
58
|
+
|
|
59
|
+
limiter = RateLimiter([Rule("endpoint", ("endpoint",), 1, 60)])
|
|
60
|
+
middleware = RateLimitMiddleware(app, limiter, lambda scope: {"endpoint": scope["path"]})
|
|
61
|
+
await middleware({"type": "http", "path": "/api"}, None, send)
|
|
62
|
+
await middleware({"type": "http", "path": "/api"}, None, send)
|
|
63
|
+
self.assertEqual([output[0]["status"], output[1]["status"]], [200, 429])
|
|
64
|
+
self.assertGreater(int(dict(output[1]["headers"])[b"retry-after"]), 0)
|
|
65
|
+
self.assertEqual(output[2]["body"], b"")
|