pacegate 0.1.0__tar.gz → 0.2.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/src/pacegate.egg-info → pacegate-0.2.0}/PKG-INFO +33 -2
- pacegate-0.2.0/README.md +69 -0
- {pacegate-0.1.0 → pacegate-0.2.0}/pyproject.toml +1 -1
- pacegate-0.2.0/src/pacegate/__init__.py +16 -0
- pacegate-0.2.0/src/pacegate/submission.py +176 -0
- {pacegate-0.1.0 → pacegate-0.2.0/src/pacegate.egg-info}/PKG-INFO +33 -2
- {pacegate-0.1.0 → pacegate-0.2.0}/src/pacegate.egg-info/SOURCES.txt +3 -1
- pacegate-0.2.0/tests/test_submission.py +68 -0
- pacegate-0.1.0/README.md +0 -38
- pacegate-0.1.0/src/pacegate/__init__.py +0 -9
- {pacegate-0.1.0 → pacegate-0.2.0}/LICENSE +0 -0
- {pacegate-0.1.0 → pacegate-0.2.0}/setup.cfg +0 -0
- {pacegate-0.1.0 → pacegate-0.2.0}/src/pacegate/asgi.py +0 -0
- {pacegate-0.1.0 → pacegate-0.2.0}/src/pacegate/limiter.py +0 -0
- {pacegate-0.1.0 → pacegate-0.2.0}/src/pacegate/py.typed +0 -0
- {pacegate-0.1.0 → pacegate-0.2.0}/src/pacegate.egg-info/dependency_links.txt +0 -0
- {pacegate-0.1.0 → pacegate-0.2.0}/src/pacegate.egg-info/top_level.txt +0 -0
- {pacegate-0.1.0 → pacegate-0.2.0}/tests/test_rate_limit.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pacegate
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Request rate limits and temporary blocks for Python web applications
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
Requires-Python: >=3.10
|
|
@@ -10,7 +10,7 @@ Dynamic: license-file
|
|
|
10
10
|
|
|
11
11
|
# pacegate
|
|
12
12
|
|
|
13
|
-
Apply fixed-window rate limits
|
|
13
|
+
Apply fixed-window rate limits and detect duplicate submissions in Python applications. The package supports Python 3.10 or later and has zero runtime dependencies.
|
|
14
14
|
|
|
15
15
|
```sh
|
|
16
16
|
python -m pip install pacegate
|
|
@@ -39,6 +39,37 @@ Window and block durations range from one millisecond to one year. An optional t
|
|
|
39
39
|
|
|
40
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
41
|
|
|
42
|
+
## Duplicate submissions
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import json
|
|
46
|
+
|
|
47
|
+
from pacegate import DuplicateSubmission, DuplicateSubmissionGuard
|
|
48
|
+
|
|
49
|
+
guard = DuplicateSubmissionGuard(lease_seconds=60, retention_seconds=300)
|
|
50
|
+
|
|
51
|
+
async def submit_order(user_id, operation_id, save):
|
|
52
|
+
key = json.dumps([user_id, "submit-order", operation_id])
|
|
53
|
+
claim = await guard.begin(key)
|
|
54
|
+
if isinstance(claim, DuplicateSubmission):
|
|
55
|
+
return {"state": claim.state, "retry_after": claim.retry_after}
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
await save()
|
|
59
|
+
except Exception:
|
|
60
|
+
await claim.fail()
|
|
61
|
+
raise
|
|
62
|
+
if not await claim.complete():
|
|
63
|
+
raise RuntimeError("Submission claim expired.")
|
|
64
|
+
return {"state": "completed"}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Call the guard before processing the form. Scope the key to the authenticated user and operation. In a web view, a duplicate can return HTTP 409 with a `Retry-After` header. Claims first report `in_progress`. Successful completion retains the `completed` state for the retention period. Calling `fail()` releases the key by default. Set `on_failure="retain"` when the application should keep a `failed` state for that period.
|
|
68
|
+
|
|
69
|
+
After expiration, a new attempt can claim the key and an older owner can no longer mutate its state. Choose a lease longer than the operation. For idempotent business writes, enforce uniqueness in the persistence layer. Applications handle response replay and decide how to respond to failed settlement.
|
|
70
|
+
|
|
71
|
+
The in-memory submission store is bounded, thread-safe, and process-local. A shared `SubmissionStore` must atomically claim keys and verify ownership before settlement. It can return results synchronously or asynchronously.
|
|
72
|
+
|
|
42
73
|
## Development
|
|
43
74
|
|
|
44
75
|
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.
|
pacegate-0.2.0/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# pacegate
|
|
2
|
+
|
|
3
|
+
Apply fixed-window rate limits and detect duplicate submissions in 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
|
+
## Duplicate submissions
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import json
|
|
36
|
+
|
|
37
|
+
from pacegate import DuplicateSubmission, DuplicateSubmissionGuard
|
|
38
|
+
|
|
39
|
+
guard = DuplicateSubmissionGuard(lease_seconds=60, retention_seconds=300)
|
|
40
|
+
|
|
41
|
+
async def submit_order(user_id, operation_id, save):
|
|
42
|
+
key = json.dumps([user_id, "submit-order", operation_id])
|
|
43
|
+
claim = await guard.begin(key)
|
|
44
|
+
if isinstance(claim, DuplicateSubmission):
|
|
45
|
+
return {"state": claim.state, "retry_after": claim.retry_after}
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
await save()
|
|
49
|
+
except Exception:
|
|
50
|
+
await claim.fail()
|
|
51
|
+
raise
|
|
52
|
+
if not await claim.complete():
|
|
53
|
+
raise RuntimeError("Submission claim expired.")
|
|
54
|
+
return {"state": "completed"}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Call the guard before processing the form. Scope the key to the authenticated user and operation. In a web view, a duplicate can return HTTP 409 with a `Retry-After` header. Claims first report `in_progress`. Successful completion retains the `completed` state for the retention period. Calling `fail()` releases the key by default. Set `on_failure="retain"` when the application should keep a `failed` state for that period.
|
|
58
|
+
|
|
59
|
+
After expiration, a new attempt can claim the key and an older owner can no longer mutate its state. Choose a lease longer than the operation. For idempotent business writes, enforce uniqueness in the persistence layer. Applications handle response replay and decide how to respond to failed settlement.
|
|
60
|
+
|
|
61
|
+
The in-memory submission store is bounded, thread-safe, and process-local. A shared `SubmissionStore` must atomically claim keys and verify ownership before settlement. It can return results synchronously or asynchronously.
|
|
62
|
+
|
|
63
|
+
## Development
|
|
64
|
+
|
|
65
|
+
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.
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
MIT
|
|
@@ -0,0 +1,16 @@
|
|
|
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
|
+
from .submission import (
|
|
7
|
+
ClaimResult, DuplicateSubmission, DuplicateSubmissionGuard, MemorySubmissionStore,
|
|
8
|
+
OwnedSubmission, SubmissionClaim, SubmissionSettlement, SubmissionStore,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"ClaimResult", "DuplicateSubmission", "DuplicateSubmissionGuard", "MemorySubmissionStore",
|
|
13
|
+
"OwnedSubmission", "SubmissionClaim", "SubmissionSettlement", "SubmissionStore",
|
|
14
|
+
"Decision", "MemoryStore", "Operation", "RateLimiter", "RateLimitMiddleware",
|
|
15
|
+
"Rule", "Store", "StoreDecision",
|
|
16
|
+
]
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Duplicate submission protection with atomic, expiring claims."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from inspect import isawaitable
|
|
8
|
+
from math import ceil, isfinite
|
|
9
|
+
import re
|
|
10
|
+
from threading import Lock
|
|
11
|
+
from time import monotonic
|
|
12
|
+
from typing import Literal, Protocol
|
|
13
|
+
from uuid import uuid4
|
|
14
|
+
|
|
15
|
+
State = Literal["in_progress", "completed", "failed"]
|
|
16
|
+
SettlementState = Literal["completed", "failed", "released"]
|
|
17
|
+
Key = tuple[str, str]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class SubmissionClaim:
|
|
22
|
+
key: Key
|
|
23
|
+
owner: str
|
|
24
|
+
lease_seconds: float
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class SubmissionSettlement:
|
|
29
|
+
key: Key
|
|
30
|
+
owner: str
|
|
31
|
+
state: SettlementState
|
|
32
|
+
retention_seconds: float
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class DuplicateSubmission:
|
|
37
|
+
state: State
|
|
38
|
+
retry_after: int
|
|
39
|
+
allowed = False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class ClaimResult:
|
|
44
|
+
acquired: bool
|
|
45
|
+
state: State = "in_progress"
|
|
46
|
+
retry_seconds: float = 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class SubmissionStore(Protocol):
|
|
50
|
+
def claim(self, operation: SubmissionClaim) -> ClaimResult | Awaitable[ClaimResult]:
|
|
51
|
+
"""Atomically claim a key with no live entry."""
|
|
52
|
+
|
|
53
|
+
def settle(self, operation: SubmissionSettlement) -> bool | Awaitable[bool]:
|
|
54
|
+
"""Atomically settle a live claim only if its owner matches."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class _Entry:
|
|
59
|
+
owner: str
|
|
60
|
+
state: State
|
|
61
|
+
expires: float
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class MemorySubmissionStore:
|
|
65
|
+
"""Bounded, thread-safe submission tracking for one process."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, max_entries: int = 10_000, *, clock: Callable[[], float] = monotonic):
|
|
68
|
+
if type(max_entries) is not int or max_entries < 1:
|
|
69
|
+
raise ValueError("max_entries must be a positive integer.")
|
|
70
|
+
self._entries: dict[Key, _Entry] = {}
|
|
71
|
+
self._lock = Lock()
|
|
72
|
+
self._max_entries = max_entries
|
|
73
|
+
self._clock = clock
|
|
74
|
+
self._next_expiry = float("inf")
|
|
75
|
+
|
|
76
|
+
def _now(self) -> float:
|
|
77
|
+
now = self._clock()
|
|
78
|
+
if not isfinite(now):
|
|
79
|
+
raise ValueError("The submission clock must return finite time.")
|
|
80
|
+
return now
|
|
81
|
+
|
|
82
|
+
def claim(self, operation: SubmissionClaim) -> ClaimResult:
|
|
83
|
+
with self._lock:
|
|
84
|
+
now = self._now()
|
|
85
|
+
entry = self._entries.get(operation.key)
|
|
86
|
+
if entry is not None and entry.expires > now:
|
|
87
|
+
return ClaimResult(False, entry.state, entry.expires - now)
|
|
88
|
+
if entry is None and len(self._entries) >= self._max_entries:
|
|
89
|
+
if now >= self._next_expiry:
|
|
90
|
+
self._entries = {key: entry for key, entry in self._entries.items() if entry.expires > now}
|
|
91
|
+
self._next_expiry = min((e.expires for e in self._entries.values()), default=float("inf"))
|
|
92
|
+
if len(self._entries) >= self._max_entries:
|
|
93
|
+
raise RuntimeError("Submission store capacity exceeded.")
|
|
94
|
+
expires = now + operation.lease_seconds
|
|
95
|
+
self._entries[operation.key] = _Entry(operation.owner, "in_progress", expires)
|
|
96
|
+
self._next_expiry = min(self._next_expiry, expires)
|
|
97
|
+
return ClaimResult(True)
|
|
98
|
+
|
|
99
|
+
def settle(self, operation: SubmissionSettlement) -> bool:
|
|
100
|
+
with self._lock:
|
|
101
|
+
now = self._now()
|
|
102
|
+
entry = self._entries.get(operation.key)
|
|
103
|
+
if entry is None or entry.owner != operation.owner or entry.state != "in_progress" or entry.expires <= now:
|
|
104
|
+
return False
|
|
105
|
+
if operation.state == "released":
|
|
106
|
+
del self._entries[operation.key]
|
|
107
|
+
else:
|
|
108
|
+
expires = now + operation.retention_seconds
|
|
109
|
+
self._entries[operation.key] = _Entry(operation.owner, operation.state, expires)
|
|
110
|
+
self._next_expiry = min(self._next_expiry, expires)
|
|
111
|
+
return True
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass(frozen=True)
|
|
115
|
+
class OwnedSubmission:
|
|
116
|
+
_settle: Callable[[SettlementState], Awaitable[bool]]
|
|
117
|
+
_failure_state: Literal["released", "failed"]
|
|
118
|
+
allowed = True
|
|
119
|
+
|
|
120
|
+
async def complete(self) -> bool:
|
|
121
|
+
return await self._settle("completed")
|
|
122
|
+
|
|
123
|
+
async def fail(self) -> bool:
|
|
124
|
+
return await self._settle(self._failure_state)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class DuplicateSubmissionGuard:
|
|
128
|
+
"""Claim a submission before running application code."""
|
|
129
|
+
|
|
130
|
+
def __init__(
|
|
131
|
+
self, *, lease_seconds: float = 60, retention_seconds: float = 300,
|
|
132
|
+
on_failure: Literal["release", "retain"] = "release", namespace: str = "pacegate",
|
|
133
|
+
store: SubmissionStore | None = None,
|
|
134
|
+
) -> None:
|
|
135
|
+
for duration in (lease_seconds, retention_seconds):
|
|
136
|
+
if type(duration) not in {int, float} or not 0.001 <= duration <= 31_536_000:
|
|
137
|
+
raise ValueError("Submission durations must be between one millisecond and one year.")
|
|
138
|
+
if on_failure not in {"release", "retain"}:
|
|
139
|
+
raise ValueError("Invalid submission failure policy.")
|
|
140
|
+
if not isinstance(namespace, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", namespace):
|
|
141
|
+
raise ValueError("Invalid submission namespace.")
|
|
142
|
+
self._lease = lease_seconds
|
|
143
|
+
self._retention = retention_seconds
|
|
144
|
+
self._failure_state: Literal["released", "failed"] = "released" if on_failure == "release" else "failed"
|
|
145
|
+
self._namespace = namespace
|
|
146
|
+
self._store = store if store is not None else MemorySubmissionStore()
|
|
147
|
+
|
|
148
|
+
async def begin(self, key: str) -> OwnedSubmission | DuplicateSubmission:
|
|
149
|
+
if not isinstance(key, str) or not 1 <= len(key) <= 512:
|
|
150
|
+
raise ValueError("Submission keys must be strings of 1 through 512 characters.")
|
|
151
|
+
scoped_key = (self._namespace, key)
|
|
152
|
+
owner = uuid4().hex
|
|
153
|
+
result = self._store.claim(SubmissionClaim(scoped_key, owner, self._lease))
|
|
154
|
+
if isawaitable(result):
|
|
155
|
+
result = await result
|
|
156
|
+
if not isinstance(result, ClaimResult) or type(result.acquired) is not bool:
|
|
157
|
+
raise TypeError("Invalid submission store decision.")
|
|
158
|
+
if not result.acquired:
|
|
159
|
+
if result.state not in ("in_progress", "completed", "failed") or (
|
|
160
|
+
type(result.retry_seconds) not in {int, float}
|
|
161
|
+
or not isfinite(result.retry_seconds) or result.retry_seconds <= 0
|
|
162
|
+
):
|
|
163
|
+
raise ValueError("Invalid duplicate submission state or retry interval.")
|
|
164
|
+
return DuplicateSubmission(result.state, ceil(result.retry_seconds))
|
|
165
|
+
|
|
166
|
+
async def settle(state: SettlementState) -> bool:
|
|
167
|
+
outcome = self._store.settle(SubmissionSettlement(
|
|
168
|
+
scoped_key, owner, state, 0 if state == "released" else self._retention,
|
|
169
|
+
))
|
|
170
|
+
if isawaitable(outcome):
|
|
171
|
+
outcome = await outcome
|
|
172
|
+
if type(outcome) is not bool:
|
|
173
|
+
raise TypeError("Invalid submission settlement result.")
|
|
174
|
+
return outcome
|
|
175
|
+
|
|
176
|
+
return OwnedSubmission(settle, self._failure_state)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pacegate
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Request rate limits and temporary blocks for Python web applications
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
Requires-Python: >=3.10
|
|
@@ -10,7 +10,7 @@ Dynamic: license-file
|
|
|
10
10
|
|
|
11
11
|
# pacegate
|
|
12
12
|
|
|
13
|
-
Apply fixed-window rate limits
|
|
13
|
+
Apply fixed-window rate limits and detect duplicate submissions in Python applications. The package supports Python 3.10 or later and has zero runtime dependencies.
|
|
14
14
|
|
|
15
15
|
```sh
|
|
16
16
|
python -m pip install pacegate
|
|
@@ -39,6 +39,37 @@ Window and block durations range from one millisecond to one year. An optional t
|
|
|
39
39
|
|
|
40
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
41
|
|
|
42
|
+
## Duplicate submissions
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import json
|
|
46
|
+
|
|
47
|
+
from pacegate import DuplicateSubmission, DuplicateSubmissionGuard
|
|
48
|
+
|
|
49
|
+
guard = DuplicateSubmissionGuard(lease_seconds=60, retention_seconds=300)
|
|
50
|
+
|
|
51
|
+
async def submit_order(user_id, operation_id, save):
|
|
52
|
+
key = json.dumps([user_id, "submit-order", operation_id])
|
|
53
|
+
claim = await guard.begin(key)
|
|
54
|
+
if isinstance(claim, DuplicateSubmission):
|
|
55
|
+
return {"state": claim.state, "retry_after": claim.retry_after}
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
await save()
|
|
59
|
+
except Exception:
|
|
60
|
+
await claim.fail()
|
|
61
|
+
raise
|
|
62
|
+
if not await claim.complete():
|
|
63
|
+
raise RuntimeError("Submission claim expired.")
|
|
64
|
+
return {"state": "completed"}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Call the guard before processing the form. Scope the key to the authenticated user and operation. In a web view, a duplicate can return HTTP 409 with a `Retry-After` header. Claims first report `in_progress`. Successful completion retains the `completed` state for the retention period. Calling `fail()` releases the key by default. Set `on_failure="retain"` when the application should keep a `failed` state for that period.
|
|
68
|
+
|
|
69
|
+
After expiration, a new attempt can claim the key and an older owner can no longer mutate its state. Choose a lease longer than the operation. For idempotent business writes, enforce uniqueness in the persistence layer. Applications handle response replay and decide how to respond to failed settlement.
|
|
70
|
+
|
|
71
|
+
The in-memory submission store is bounded, thread-safe, and process-local. A shared `SubmissionStore` must atomically claim keys and verify ownership before settlement. It can return results synchronously or asynchronously.
|
|
72
|
+
|
|
42
73
|
## Development
|
|
43
74
|
|
|
44
75
|
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.
|
|
@@ -5,8 +5,10 @@ src/pacegate/__init__.py
|
|
|
5
5
|
src/pacegate/asgi.py
|
|
6
6
|
src/pacegate/limiter.py
|
|
7
7
|
src/pacegate/py.typed
|
|
8
|
+
src/pacegate/submission.py
|
|
8
9
|
src/pacegate.egg-info/PKG-INFO
|
|
9
10
|
src/pacegate.egg-info/SOURCES.txt
|
|
10
11
|
src/pacegate.egg-info/dependency_links.txt
|
|
11
12
|
src/pacegate.egg-info/top_level.txt
|
|
12
|
-
tests/test_rate_limit.py
|
|
13
|
+
tests/test_rate_limit.py
|
|
14
|
+
tests/test_submission.py
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
from pacegate import DuplicateSubmission, DuplicateSubmissionGuard, MemorySubmissionStore, OwnedSubmission
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class SubmissionTests(unittest.IsolatedAsyncioTestCase):
|
|
8
|
+
async def test_concurrent_claim_and_completion_retention(self):
|
|
9
|
+
time = 0
|
|
10
|
+
guard = DuplicateSubmissionGuard(lease_seconds=2, retention_seconds=5,
|
|
11
|
+
store=MemorySubmissionStore(clock=lambda: time))
|
|
12
|
+
outcomes = await asyncio.gather(*(guard.begin("user-1:form") for _ in range(12)))
|
|
13
|
+
wins = [outcome for outcome in outcomes if isinstance(outcome, OwnedSubmission)]
|
|
14
|
+
self.assertEqual(len(wins), 1)
|
|
15
|
+
self.assertEqual(outcomes.count(DuplicateSubmission("in_progress", 2)), 11)
|
|
16
|
+
time = 1
|
|
17
|
+
self.assertTrue(await wins[0].complete())
|
|
18
|
+
self.assertEqual(await guard.begin("user-1:form"), DuplicateSubmission("completed", 5))
|
|
19
|
+
time = 6
|
|
20
|
+
self.assertIsInstance(await guard.begin("user-1:form"), OwnedSubmission)
|
|
21
|
+
|
|
22
|
+
async def test_failure_policy(self):
|
|
23
|
+
for policy in ("release", "retain"):
|
|
24
|
+
guard = DuplicateSubmissionGuard(on_failure=policy)
|
|
25
|
+
first = await guard.begin("form")
|
|
26
|
+
self.assertIsInstance(first, OwnedSubmission)
|
|
27
|
+
self.assertTrue(await first.fail())
|
|
28
|
+
second = await guard.begin("form")
|
|
29
|
+
if policy == "release":
|
|
30
|
+
self.assertIsInstance(second, OwnedSubmission)
|
|
31
|
+
else:
|
|
32
|
+
self.assertIsInstance(second, DuplicateSubmission)
|
|
33
|
+
self.assertEqual(second.state, "failed")
|
|
34
|
+
|
|
35
|
+
async def test_lease_expiry_only_current_owner_can_settle(self):
|
|
36
|
+
time = 0
|
|
37
|
+
guard = DuplicateSubmissionGuard(lease_seconds=1, store=MemorySubmissionStore(clock=lambda: time))
|
|
38
|
+
first = await guard.begin("form")
|
|
39
|
+
self.assertIsInstance(first, OwnedSubmission)
|
|
40
|
+
time = 1
|
|
41
|
+
retry = await guard.begin("form")
|
|
42
|
+
self.assertIsInstance(retry, OwnedSubmission)
|
|
43
|
+
self.assertFalse(await first.fail())
|
|
44
|
+
self.assertFalse(await first.complete())
|
|
45
|
+
self.assertTrue(await retry.complete())
|
|
46
|
+
self.assertFalse(await retry.complete())
|
|
47
|
+
|
|
48
|
+
async def test_shared_async_store_and_bounded_capacity(self):
|
|
49
|
+
class AsyncStore:
|
|
50
|
+
def __init__(self):
|
|
51
|
+
self.memory = MemorySubmissionStore(max_entries=2)
|
|
52
|
+
|
|
53
|
+
async def claim(self, operation):
|
|
54
|
+
return self.memory.claim(operation)
|
|
55
|
+
|
|
56
|
+
async def settle(self, operation):
|
|
57
|
+
return self.memory.settle(operation)
|
|
58
|
+
|
|
59
|
+
store = AsyncStore()
|
|
60
|
+
first = DuplicateSubmissionGuard(store=store, namespace="first")
|
|
61
|
+
second = DuplicateSubmissionGuard(store=store, namespace="second")
|
|
62
|
+
winner = await first.begin("form")
|
|
63
|
+
self.assertIsInstance(winner, OwnedSubmission)
|
|
64
|
+
self.assertIsInstance(await second.begin("form"), OwnedSubmission)
|
|
65
|
+
with self.assertRaises(RuntimeError):
|
|
66
|
+
await second.begin("other")
|
|
67
|
+
self.assertTrue(await winner.fail())
|
|
68
|
+
self.assertIsInstance(await second.begin("other"), OwnedSubmission)
|
pacegate-0.1.0/README.md
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
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
|
|
@@ -1,9 +0,0 @@
|
|
|
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
|
-
]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|