pacegate 0.1.0__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.
pacegate/__init__.py 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
+ ]
pacegate/asgi.py ADDED
@@ -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""})
pacegate/limiter.py ADDED
@@ -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
pacegate/py.typed ADDED
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,9 @@
1
+ pacegate/__init__.py,sha256=AbatnwZ39WxmQ-Z17H1drFvPGmvELOrT9szxaTMY9k8,333
2
+ pacegate/asgi.py,sha256=_ENBljIdkJea3MoWjrhCo36vDgplGA6ac_IqGMiNtcs,1343
3
+ pacegate/limiter.py,sha256=C2GpZet15cBeOoVIwsEfvxdkUmL014ebpn7zPvv5408,6405
4
+ pacegate/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pacegate-0.1.0.dist-info/licenses/LICENSE,sha256=vdR7UFG2CVYOTQIBV7KZTV6hrzq1I885Ws4JVwa6FUg,1078
6
+ pacegate-0.1.0.dist-info/METADATA,sha256=5OvkIzXr_Cs2BNJt_cw7nzEzKp9kZs2r3haHCurEqCs,2155
7
+ pacegate-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ pacegate-0.1.0.dist-info/top_level.txt,sha256=Qk1D6TmySbveT0fT_dHRaZ1B1ssfPV7Z4TgMsFl3p10,9
9
+ pacegate-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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.
@@ -0,0 +1 @@
1
+ pacegate