fastapi-sql-limiter 0.3.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.
- fastapi_sql_limiter/__init__.py +35 -0
- fastapi_sql_limiter/_init_.py +5 -0
- fastapi_sql_limiter/exception.py +20 -0
- fastapi_sql_limiter/exceptions.py +51 -0
- fastapi_sql_limiter/limiter.py +456 -0
- fastapi_sql_limiter/py.typed +1 -0
- fastapi_sql_limiter/storage.py +312 -0
- fastapi_sql_limiter-0.3.0.dist-info/METADATA +300 -0
- fastapi_sql_limiter-0.3.0.dist-info/RECORD +12 -0
- fastapi_sql_limiter-0.3.0.dist-info/WHEEL +5 -0
- fastapi_sql_limiter-0.3.0.dist-info/licenses/LICENSE +21 -0
- fastapi_sql_limiter-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""PostgreSQL-backed rate limiting for FastAPI applications."""
|
|
2
|
+
|
|
3
|
+
from .exceptions import (
|
|
4
|
+
RateLimiterError,
|
|
5
|
+
RateLimiterNotConfiguredError,
|
|
6
|
+
RateLimiterUnavailable,
|
|
7
|
+
RateLimitExceeded,
|
|
8
|
+
StorageNotInitializedError,
|
|
9
|
+
)
|
|
10
|
+
from .limiter import (
|
|
11
|
+
RateLimiter,
|
|
12
|
+
RateLimitEvent,
|
|
13
|
+
RateLimitInfo,
|
|
14
|
+
get_default_limiter,
|
|
15
|
+
rate_limit,
|
|
16
|
+
set_default_limiter,
|
|
17
|
+
)
|
|
18
|
+
from .storage import PostgresStorage
|
|
19
|
+
|
|
20
|
+
__version__ = "0.3.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"PostgresStorage",
|
|
24
|
+
"RateLimitExceeded",
|
|
25
|
+
"RateLimitEvent",
|
|
26
|
+
"RateLimitInfo",
|
|
27
|
+
"RateLimiter",
|
|
28
|
+
"RateLimiterError",
|
|
29
|
+
"RateLimiterNotConfiguredError",
|
|
30
|
+
"RateLimiterUnavailable",
|
|
31
|
+
"StorageNotInitializedError",
|
|
32
|
+
"get_default_limiter",
|
|
33
|
+
"rate_limit",
|
|
34
|
+
"set_default_limiter",
|
|
35
|
+
]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Backward-compatible exception imports.
|
|
2
|
+
|
|
3
|
+
Use :mod:`fastapi_sql_limiter.exceptions` for new code.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from .exceptions import (
|
|
7
|
+
RateLimiterError,
|
|
8
|
+
RateLimiterNotConfiguredError,
|
|
9
|
+
RateLimiterUnavailable,
|
|
10
|
+
RateLimitExceeded,
|
|
11
|
+
StorageNotInitializedError,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"RateLimitExceeded",
|
|
16
|
+
"RateLimiterError",
|
|
17
|
+
"RateLimiterNotConfiguredError",
|
|
18
|
+
"RateLimiterUnavailable",
|
|
19
|
+
"StorageNotInitializedError",
|
|
20
|
+
]
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Exceptions raised by :mod:`fastapi_sql_limiter`."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
from fastapi import HTTPException, status
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class RateLimiterError(RuntimeError):
|
|
9
|
+
"""Base class for package-specific runtime errors."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class RateLimiterNotConfiguredError(RateLimiterError):
|
|
13
|
+
"""Raised when a decorator has no limiter instance to use."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class StorageNotInitializedError(RateLimiterError):
|
|
17
|
+
"""Raised when rate-limit storage is used before initialization."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RateLimiterUnavailable(HTTPException):
|
|
21
|
+
"""HTTP 503 raised when quota storage cannot enforce a limit safely."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, detail: str = "Rate limiting service unavailable") -> None:
|
|
24
|
+
super().__init__(
|
|
25
|
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
26
|
+
detail=detail,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RateLimitExceeded(HTTPException):
|
|
31
|
+
"""HTTP 429 response with standard retry and rate-limit metadata."""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
*,
|
|
36
|
+
limit: int,
|
|
37
|
+
reset_at: int,
|
|
38
|
+
retry_after: float,
|
|
39
|
+
detail: str = "Rate limit exceeded",
|
|
40
|
+
) -> None:
|
|
41
|
+
retry_after_seconds = max(1, math.ceil(retry_after))
|
|
42
|
+
super().__init__(
|
|
43
|
+
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
44
|
+
detail=detail,
|
|
45
|
+
headers={
|
|
46
|
+
"Retry-After": str(retry_after_seconds),
|
|
47
|
+
"X-RateLimit-Limit": str(limit),
|
|
48
|
+
"X-RateLimit-Remaining": "0",
|
|
49
|
+
"X-RateLimit-Reset": str(reset_at),
|
|
50
|
+
},
|
|
51
|
+
)
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
"""FastAPI-facing rate limiter and endpoint decorator."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import inspect
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from functools import wraps
|
|
10
|
+
from typing import Any, Awaitable, Callable, Literal, Mapping, Optional, Protocol, Union
|
|
11
|
+
|
|
12
|
+
from fastapi import Request, Response
|
|
13
|
+
from starlette.concurrency import run_in_threadpool
|
|
14
|
+
|
|
15
|
+
from .exceptions import (
|
|
16
|
+
RateLimiterNotConfiguredError,
|
|
17
|
+
RateLimiterUnavailable,
|
|
18
|
+
RateLimitExceeded,
|
|
19
|
+
)
|
|
20
|
+
from .storage import PostgresStorage, StorageWindow
|
|
21
|
+
|
|
22
|
+
_MAX_IDENTITY_BYTES = 4_096
|
|
23
|
+
_POSTGRES_BIGINT_MAX = 9_223_372_036_854_775_807
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RateLimitStorage(Protocol):
|
|
27
|
+
"""Storage behavior required by :class:`RateLimiter`."""
|
|
28
|
+
|
|
29
|
+
async def initialize(self) -> None: ...
|
|
30
|
+
|
|
31
|
+
async def increment_window(self, key: str, window: int) -> StorageWindow: ...
|
|
32
|
+
|
|
33
|
+
async def increment(
|
|
34
|
+
self, key: str, window_start: int, expires_at: int
|
|
35
|
+
) -> int: ...
|
|
36
|
+
|
|
37
|
+
async def cleanup(
|
|
38
|
+
self,
|
|
39
|
+
expired_before: Optional[int] = None,
|
|
40
|
+
*,
|
|
41
|
+
batch_size: int = 1_000,
|
|
42
|
+
) -> int: ...
|
|
43
|
+
|
|
44
|
+
async def close(self) -> None: ...
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class RateLimitInfo:
|
|
49
|
+
"""Result of a single rate-limit check."""
|
|
50
|
+
|
|
51
|
+
allowed: bool
|
|
52
|
+
limit: int
|
|
53
|
+
remaining: int
|
|
54
|
+
reset_at: int
|
|
55
|
+
retry_after: float
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True, slots=True)
|
|
59
|
+
class RateLimitEvent:
|
|
60
|
+
"""Privacy-preserving operational event emitted after a limit check."""
|
|
61
|
+
|
|
62
|
+
outcome: Literal["allowed", "rejected", "error"]
|
|
63
|
+
limit: int
|
|
64
|
+
window: int
|
|
65
|
+
remaining: int | None
|
|
66
|
+
elapsed_seconds: float
|
|
67
|
+
error_type: str | None = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
KeyFunction = Callable[[Request], Union[str, Awaitable[str]]]
|
|
71
|
+
Endpoint = Callable[..., Any]
|
|
72
|
+
Observer = Callable[[RateLimitEvent], Union[None, Awaitable[None]]]
|
|
73
|
+
|
|
74
|
+
_default_limiter: Optional["RateLimiter"] = None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def set_default_limiter(limiter: Optional["RateLimiter"]) -> None:
|
|
78
|
+
"""Set the process-wide limiter used by decorators without an explicit one."""
|
|
79
|
+
|
|
80
|
+
global _default_limiter
|
|
81
|
+
_default_limiter = limiter
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def get_default_limiter() -> "RateLimiter":
|
|
85
|
+
"""Return the configured process-wide limiter."""
|
|
86
|
+
|
|
87
|
+
if _default_limiter is None:
|
|
88
|
+
raise RateLimiterNotConfiguredError(
|
|
89
|
+
"no default limiter is configured; create RateLimiter or pass "
|
|
90
|
+
"limiter= to @rate_limit"
|
|
91
|
+
)
|
|
92
|
+
return _default_limiter
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class RateLimiter:
|
|
96
|
+
"""Coordinate rate-limit checks against a shared storage backend."""
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
dsn: Optional[str] = None,
|
|
101
|
+
*,
|
|
102
|
+
storage: Optional[RateLimitStorage] = None,
|
|
103
|
+
table_name: str = "fastapi_sql_limiter",
|
|
104
|
+
min_pool_size: int = 1,
|
|
105
|
+
max_pool_size: int = 10,
|
|
106
|
+
connect_timeout: float = 10.0,
|
|
107
|
+
acquire_timeout: float = 5.0,
|
|
108
|
+
command_timeout: float = 5.0,
|
|
109
|
+
create_schema: bool = True,
|
|
110
|
+
set_as_default: bool = True,
|
|
111
|
+
clock: Callable[[], float] = time.time,
|
|
112
|
+
observer: Observer | None = None,
|
|
113
|
+
) -> None:
|
|
114
|
+
if storage is not None and dsn is not None:
|
|
115
|
+
raise ValueError("provide either dsn or storage, not both")
|
|
116
|
+
self.storage: RateLimitStorage = (
|
|
117
|
+
storage
|
|
118
|
+
if storage is not None
|
|
119
|
+
else PostgresStorage(
|
|
120
|
+
dsn,
|
|
121
|
+
table_name=table_name,
|
|
122
|
+
min_pool_size=min_pool_size,
|
|
123
|
+
max_pool_size=max_pool_size,
|
|
124
|
+
connect_timeout=connect_timeout,
|
|
125
|
+
acquire_timeout=acquire_timeout,
|
|
126
|
+
command_timeout=command_timeout,
|
|
127
|
+
create_schema=create_schema,
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
self._clock = clock
|
|
131
|
+
self._observer = observer
|
|
132
|
+
if set_as_default:
|
|
133
|
+
set_default_limiter(self)
|
|
134
|
+
|
|
135
|
+
async def init_db(self) -> None:
|
|
136
|
+
"""Initialize storage and, when configured, create its schema."""
|
|
137
|
+
|
|
138
|
+
await self.storage.initialize()
|
|
139
|
+
|
|
140
|
+
async def check(self, key: str, *, limit: int, window: int) -> RateLimitInfo:
|
|
141
|
+
"""Increment a key's bucket and return the resulting limit state."""
|
|
142
|
+
|
|
143
|
+
_validate_rule(limit, window)
|
|
144
|
+
if not isinstance(key, str) or not key.strip():
|
|
145
|
+
raise ValueError("key must be a non-empty string")
|
|
146
|
+
if len(key) > 512:
|
|
147
|
+
raise ValueError("key must not exceed 512 characters")
|
|
148
|
+
|
|
149
|
+
# Different fixed-window durations can have the same aligned start
|
|
150
|
+
# epoch. Scope every storage key by policy so their counters cannot
|
|
151
|
+
# collide, including for direct callers and legacy storage adapters.
|
|
152
|
+
storage_key = f"{window}:{key}"
|
|
153
|
+
|
|
154
|
+
started = time.perf_counter()
|
|
155
|
+
try:
|
|
156
|
+
increment_window = getattr(self.storage, "increment_window", None)
|
|
157
|
+
if callable(increment_window):
|
|
158
|
+
state = await increment_window(storage_key, window)
|
|
159
|
+
count = state.count
|
|
160
|
+
reset_at = state.reset_at
|
|
161
|
+
retry_after = state.retry_after
|
|
162
|
+
else:
|
|
163
|
+
# Compatibility path for storage adapters written for 0.2.x.
|
|
164
|
+
now = self._clock()
|
|
165
|
+
window_start = int(now // window) * window
|
|
166
|
+
reset_at = window_start + window
|
|
167
|
+
count = await self.storage.increment(
|
|
168
|
+
storage_key,
|
|
169
|
+
window_start,
|
|
170
|
+
reset_at,
|
|
171
|
+
)
|
|
172
|
+
retry_after = max(reset_at - now, 0.0)
|
|
173
|
+
except Exception as exc:
|
|
174
|
+
await self._observe(
|
|
175
|
+
RateLimitEvent(
|
|
176
|
+
outcome="error",
|
|
177
|
+
limit=limit,
|
|
178
|
+
window=window,
|
|
179
|
+
remaining=None,
|
|
180
|
+
elapsed_seconds=time.perf_counter() - started,
|
|
181
|
+
error_type=type(exc).__name__,
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
raise
|
|
185
|
+
|
|
186
|
+
remaining = max(limit - count, 0)
|
|
187
|
+
result = RateLimitInfo(
|
|
188
|
+
allowed=count <= limit,
|
|
189
|
+
limit=limit,
|
|
190
|
+
remaining=remaining,
|
|
191
|
+
reset_at=reset_at,
|
|
192
|
+
retry_after=max(retry_after, 0.0),
|
|
193
|
+
)
|
|
194
|
+
await self._observe(
|
|
195
|
+
RateLimitEvent(
|
|
196
|
+
outcome="allowed" if result.allowed else "rejected",
|
|
197
|
+
limit=limit,
|
|
198
|
+
window=window,
|
|
199
|
+
remaining=remaining,
|
|
200
|
+
elapsed_seconds=time.perf_counter() - started,
|
|
201
|
+
)
|
|
202
|
+
)
|
|
203
|
+
return result
|
|
204
|
+
|
|
205
|
+
async def cleanup(
|
|
206
|
+
self,
|
|
207
|
+
expired_before: Optional[int] = None,
|
|
208
|
+
*,
|
|
209
|
+
batch_size: int = 1_000,
|
|
210
|
+
) -> int:
|
|
211
|
+
"""Remove one bounded batch of expired rate-limit buckets."""
|
|
212
|
+
|
|
213
|
+
try:
|
|
214
|
+
parameters: Mapping[str, inspect.Parameter] = inspect.signature(
|
|
215
|
+
self.storage.cleanup
|
|
216
|
+
).parameters
|
|
217
|
+
except (TypeError, ValueError):
|
|
218
|
+
parameters = {}
|
|
219
|
+
if "batch_size" in parameters:
|
|
220
|
+
return await self.storage.cleanup(
|
|
221
|
+
expired_before,
|
|
222
|
+
batch_size=batch_size,
|
|
223
|
+
)
|
|
224
|
+
return await self.storage.cleanup(expired_before)
|
|
225
|
+
|
|
226
|
+
async def close(self) -> None:
|
|
227
|
+
"""Release resources owned by the storage backend."""
|
|
228
|
+
|
|
229
|
+
await self.storage.close()
|
|
230
|
+
|
|
231
|
+
async def __aenter__(self) -> "RateLimiter":
|
|
232
|
+
await self.init_db()
|
|
233
|
+
return self
|
|
234
|
+
|
|
235
|
+
async def __aexit__(self, *_: object) -> None:
|
|
236
|
+
await self.close()
|
|
237
|
+
|
|
238
|
+
async def _observe(self, event: RateLimitEvent) -> None:
|
|
239
|
+
if self._observer is None:
|
|
240
|
+
return
|
|
241
|
+
try:
|
|
242
|
+
result = self._observer(event)
|
|
243
|
+
if inspect.isawaitable(result):
|
|
244
|
+
await result
|
|
245
|
+
except Exception:
|
|
246
|
+
# Observability must never alter quota enforcement.
|
|
247
|
+
return
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def rate_limit(
|
|
251
|
+
*,
|
|
252
|
+
limit: int,
|
|
253
|
+
window: int,
|
|
254
|
+
limiter: Optional[RateLimiter] = None,
|
|
255
|
+
key_func: Optional[KeyFunction] = None,
|
|
256
|
+
namespace: Optional[str] = None,
|
|
257
|
+
) -> Callable[[Endpoint], Endpoint]:
|
|
258
|
+
"""Limit calls to a FastAPI endpoint.
|
|
259
|
+
|
|
260
|
+
``limit`` requests are allowed per fixed ``window`` in seconds. The
|
|
261
|
+
default identity is the direct peer IP. Applications behind a trusted
|
|
262
|
+
proxy should provide a key function that validates their forwarding
|
|
263
|
+
headers or, preferably, returns an authenticated user or API-key ID.
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
_validate_rule(limit, window)
|
|
267
|
+
if namespace is not None and not namespace.strip():
|
|
268
|
+
raise ValueError("namespace must be a non-empty string")
|
|
269
|
+
if namespace is not None and len(namespace) > 400:
|
|
270
|
+
raise ValueError("namespace must not exceed 400 characters")
|
|
271
|
+
|
|
272
|
+
def decorator(endpoint: Endpoint) -> Endpoint:
|
|
273
|
+
endpoint_signature = inspect.signature(endpoint)
|
|
274
|
+
request_parameter = _find_request_parameter(endpoint_signature)
|
|
275
|
+
response_parameter = _find_response_parameter(endpoint_signature)
|
|
276
|
+
injected_parameter: Optional[str] = None
|
|
277
|
+
injected_response_parameter: Optional[str] = None
|
|
278
|
+
exposed_signature = endpoint_signature
|
|
279
|
+
|
|
280
|
+
if request_parameter is None:
|
|
281
|
+
injected_parameter = _unique_parameter_name(
|
|
282
|
+
endpoint_signature,
|
|
283
|
+
"__rate_limit_request",
|
|
284
|
+
)
|
|
285
|
+
exposed_signature = _inject_parameter(
|
|
286
|
+
exposed_signature,
|
|
287
|
+
injected_parameter,
|
|
288
|
+
Request,
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
if response_parameter is None:
|
|
292
|
+
injected_response_parameter = _unique_parameter_name(
|
|
293
|
+
exposed_signature,
|
|
294
|
+
"__rate_limit_response",
|
|
295
|
+
)
|
|
296
|
+
exposed_signature = _inject_parameter(
|
|
297
|
+
exposed_signature,
|
|
298
|
+
injected_response_parameter,
|
|
299
|
+
Response,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
@wraps(endpoint)
|
|
303
|
+
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
304
|
+
if injected_parameter is not None:
|
|
305
|
+
request = kwargs.pop(injected_parameter)
|
|
306
|
+
if injected_response_parameter is not None:
|
|
307
|
+
response = kwargs.pop(injected_response_parameter)
|
|
308
|
+
|
|
309
|
+
if request_parameter is not None or response_parameter is not None:
|
|
310
|
+
bound = endpoint_signature.bind_partial(*args, **kwargs)
|
|
311
|
+
if request_parameter is not None:
|
|
312
|
+
request = bound.arguments[request_parameter]
|
|
313
|
+
if response_parameter is not None:
|
|
314
|
+
response = bound.arguments[response_parameter]
|
|
315
|
+
|
|
316
|
+
active_limiter = limiter if limiter is not None else get_default_limiter()
|
|
317
|
+
identity = await _resolve_identity(request, key_func)
|
|
318
|
+
identity_bytes = identity.encode("utf-8")
|
|
319
|
+
if len(identity_bytes) > _MAX_IDENTITY_BYTES:
|
|
320
|
+
raise ValueError("rate-limit identity must not exceed 4096 UTF-8 bytes")
|
|
321
|
+
digest = hashlib.sha256(identity_bytes).hexdigest()
|
|
322
|
+
bucket_namespace = namespace or _default_namespace(request, endpoint)
|
|
323
|
+
if len(bucket_namespace) > 400:
|
|
324
|
+
namespace_hash = hashlib.sha256(
|
|
325
|
+
bucket_namespace.encode("utf-8")
|
|
326
|
+
).hexdigest()
|
|
327
|
+
bucket_namespace = f"endpoint:{namespace_hash}"
|
|
328
|
+
try:
|
|
329
|
+
result = await active_limiter.check(
|
|
330
|
+
f"{bucket_namespace}:{digest}",
|
|
331
|
+
limit=limit,
|
|
332
|
+
window=window,
|
|
333
|
+
)
|
|
334
|
+
except Exception as exc:
|
|
335
|
+
raise RateLimiterUnavailable() from exc
|
|
336
|
+
request.state.rate_limit = result
|
|
337
|
+
_apply_rate_limit_headers(response, result)
|
|
338
|
+
if not result.allowed:
|
|
339
|
+
raise RateLimitExceeded(
|
|
340
|
+
limit=result.limit,
|
|
341
|
+
reset_at=result.reset_at,
|
|
342
|
+
retry_after=result.retry_after,
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
if inspect.iscoroutinefunction(endpoint):
|
|
346
|
+
endpoint_result = await endpoint(*args, **kwargs)
|
|
347
|
+
else:
|
|
348
|
+
endpoint_result = await run_in_threadpool(endpoint, *args, **kwargs)
|
|
349
|
+
if isinstance(endpoint_result, Response):
|
|
350
|
+
_apply_rate_limit_headers(endpoint_result, result)
|
|
351
|
+
return endpoint_result
|
|
352
|
+
|
|
353
|
+
wrapper.__signature__ = exposed_signature # type: ignore[attr-defined]
|
|
354
|
+
return wrapper
|
|
355
|
+
|
|
356
|
+
return decorator
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _validate_rule(limit: int, window: int) -> None:
|
|
360
|
+
if (
|
|
361
|
+
isinstance(limit, bool)
|
|
362
|
+
or not isinstance(limit, int)
|
|
363
|
+
or not 1 <= limit <= _POSTGRES_BIGINT_MAX
|
|
364
|
+
):
|
|
365
|
+
raise ValueError("limit must be a positive PostgreSQL BIGINT")
|
|
366
|
+
if (
|
|
367
|
+
isinstance(window, bool)
|
|
368
|
+
or not isinstance(window, int)
|
|
369
|
+
or not 1 <= window <= _POSTGRES_BIGINT_MAX
|
|
370
|
+
):
|
|
371
|
+
raise ValueError(
|
|
372
|
+
"window must be a positive PostgreSQL BIGINT number of seconds"
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _find_request_parameter(signature: inspect.Signature) -> Optional[str]:
|
|
377
|
+
for name, parameter in signature.parameters.items():
|
|
378
|
+
annotation = parameter.annotation
|
|
379
|
+
if annotation is Request or (
|
|
380
|
+
isinstance(annotation, str) and annotation.rsplit(".", 1)[-1] == "Request"
|
|
381
|
+
):
|
|
382
|
+
return name
|
|
383
|
+
return None
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _find_response_parameter(signature: inspect.Signature) -> Optional[str]:
|
|
387
|
+
for name, parameter in signature.parameters.items():
|
|
388
|
+
annotation = parameter.annotation
|
|
389
|
+
if annotation is Response or (
|
|
390
|
+
isinstance(annotation, str) and annotation.rsplit(".", 1)[-1] == "Response"
|
|
391
|
+
):
|
|
392
|
+
return name
|
|
393
|
+
return None
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _inject_parameter(
|
|
397
|
+
signature: inspect.Signature,
|
|
398
|
+
name: str,
|
|
399
|
+
annotation: type[Any],
|
|
400
|
+
) -> inspect.Signature:
|
|
401
|
+
parameters = list(signature.parameters.values())
|
|
402
|
+
insertion_index = next(
|
|
403
|
+
(
|
|
404
|
+
index
|
|
405
|
+
for index, parameter in enumerate(parameters)
|
|
406
|
+
if parameter.kind is inspect.Parameter.VAR_KEYWORD
|
|
407
|
+
),
|
|
408
|
+
len(parameters),
|
|
409
|
+
)
|
|
410
|
+
parameters.insert(
|
|
411
|
+
insertion_index,
|
|
412
|
+
inspect.Parameter(
|
|
413
|
+
name,
|
|
414
|
+
kind=inspect.Parameter.KEYWORD_ONLY,
|
|
415
|
+
annotation=annotation,
|
|
416
|
+
),
|
|
417
|
+
)
|
|
418
|
+
return signature.replace(parameters=parameters)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _unique_parameter_name(signature: inspect.Signature, base_name: str) -> str:
|
|
422
|
+
name = base_name
|
|
423
|
+
while name in signature.parameters:
|
|
424
|
+
name = f"_{name}"
|
|
425
|
+
return name
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _default_namespace(request: Request, endpoint: Endpoint) -> str:
|
|
429
|
+
route = request.scope.get("route")
|
|
430
|
+
route_path = getattr(route, "path", request.url.path)
|
|
431
|
+
return (
|
|
432
|
+
f"{endpoint.__module__}.{endpoint.__qualname__}:"
|
|
433
|
+
f"{request.method}:{route_path}"
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _apply_rate_limit_headers(response: Response, result: RateLimitInfo) -> None:
|
|
438
|
+
response.headers["X-RateLimit-Limit"] = str(result.limit)
|
|
439
|
+
response.headers["X-RateLimit-Remaining"] = str(result.remaining)
|
|
440
|
+
response.headers["X-RateLimit-Reset"] = str(result.reset_at)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
async def _resolve_identity(
|
|
444
|
+
request: Request,
|
|
445
|
+
key_func: Optional[KeyFunction],
|
|
446
|
+
) -> str:
|
|
447
|
+
value: object
|
|
448
|
+
if key_func is None:
|
|
449
|
+
value = request.client.host if request.client is not None else "unknown-client"
|
|
450
|
+
else:
|
|
451
|
+
value = key_func(request)
|
|
452
|
+
if inspect.isawaitable(value):
|
|
453
|
+
value = await value
|
|
454
|
+
if not isinstance(value, str) or not value.strip():
|
|
455
|
+
raise ValueError("key_func must return a non-empty string")
|
|
456
|
+
return value
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""Atomic PostgreSQL storage for fixed-window rate limits."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .exceptions import StorageNotInitializedError
|
|
11
|
+
|
|
12
|
+
_VALID_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,47}$")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class StorageWindow:
|
|
17
|
+
"""Database-derived state for one fixed-window increment."""
|
|
18
|
+
|
|
19
|
+
count: int
|
|
20
|
+
window_start: int
|
|
21
|
+
reset_at: int
|
|
22
|
+
retry_after: float
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PostgresStorage:
|
|
26
|
+
"""Persist rate-limit counters in PostgreSQL using atomic upserts.
|
|
27
|
+
|
|
28
|
+
A pre-existing asyncpg-compatible pool may be supplied for applications
|
|
29
|
+
that centrally manage database connections. Pools passed by the caller are
|
|
30
|
+
never closed by this class.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
dsn: str | None = None,
|
|
36
|
+
*,
|
|
37
|
+
pool: Any | None = None,
|
|
38
|
+
table_name: str = "fastapi_sql_limiter",
|
|
39
|
+
min_pool_size: int = 1,
|
|
40
|
+
max_pool_size: int = 10,
|
|
41
|
+
connect_timeout: float = 10.0,
|
|
42
|
+
acquire_timeout: float = 5.0,
|
|
43
|
+
command_timeout: float = 5.0,
|
|
44
|
+
create_schema: bool = True,
|
|
45
|
+
) -> None:
|
|
46
|
+
if pool is None and (not isinstance(dsn, str) or not dsn.strip()):
|
|
47
|
+
raise ValueError("dsn is required when pool is not provided")
|
|
48
|
+
if dsn is not None and pool is not None:
|
|
49
|
+
raise ValueError("provide either dsn or pool, not both")
|
|
50
|
+
if not _VALID_IDENTIFIER.fullmatch(table_name):
|
|
51
|
+
raise ValueError(
|
|
52
|
+
"table_name must be a PostgreSQL identifier of at most 48 characters"
|
|
53
|
+
)
|
|
54
|
+
if isinstance(min_pool_size, bool) or min_pool_size < 1:
|
|
55
|
+
raise ValueError("min_pool_size must be at least 1")
|
|
56
|
+
if isinstance(max_pool_size, bool) or max_pool_size < min_pool_size:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
"max_pool_size must be greater than or equal to min_pool_size"
|
|
59
|
+
)
|
|
60
|
+
self._validate_timeout("connect_timeout", connect_timeout)
|
|
61
|
+
self._validate_timeout("acquire_timeout", acquire_timeout)
|
|
62
|
+
self._validate_timeout("command_timeout", command_timeout)
|
|
63
|
+
if not isinstance(create_schema, bool):
|
|
64
|
+
raise ValueError("create_schema must be a boolean")
|
|
65
|
+
|
|
66
|
+
self._dsn = dsn
|
|
67
|
+
self._pool = pool
|
|
68
|
+
self._initialized = False
|
|
69
|
+
self._owns_pool = pool is None
|
|
70
|
+
self._table_name = table_name
|
|
71
|
+
self._min_pool_size = min_pool_size
|
|
72
|
+
self._max_pool_size = max_pool_size
|
|
73
|
+
self._connect_timeout = connect_timeout
|
|
74
|
+
self._acquire_timeout = acquire_timeout
|
|
75
|
+
self._command_timeout = command_timeout
|
|
76
|
+
self._create_schema = create_schema
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def initialized(self) -> bool:
|
|
80
|
+
"""Whether the storage connection lifecycle has been initialized."""
|
|
81
|
+
|
|
82
|
+
return self._initialized
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def schema_statements(self) -> tuple[str, str]:
|
|
86
|
+
"""Return idempotent DDL for administrator-managed schema setup."""
|
|
87
|
+
|
|
88
|
+
return self._create_table_sql, self._create_expiry_index_sql
|
|
89
|
+
|
|
90
|
+
async def initialize(self) -> None:
|
|
91
|
+
"""Create the pool and optionally ensure the schema exists."""
|
|
92
|
+
|
|
93
|
+
if self._pool is None:
|
|
94
|
+
try:
|
|
95
|
+
import asyncpg # type: ignore[import-untyped]
|
|
96
|
+
except ImportError as exc: # pragma: no cover
|
|
97
|
+
raise RuntimeError(
|
|
98
|
+
"asyncpg is required to use PostgreSQL storage; install "
|
|
99
|
+
"the package with its runtime dependencies"
|
|
100
|
+
) from exc
|
|
101
|
+
|
|
102
|
+
self._pool = await asyncpg.create_pool(
|
|
103
|
+
dsn=self._dsn,
|
|
104
|
+
min_size=self._min_pool_size,
|
|
105
|
+
max_size=self._max_pool_size,
|
|
106
|
+
timeout=self._connect_timeout,
|
|
107
|
+
command_timeout=self._command_timeout,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
if self._create_schema:
|
|
112
|
+
await self.initialize_schema()
|
|
113
|
+
self._initialized = True
|
|
114
|
+
except BaseException:
|
|
115
|
+
if self._owns_pool and self._pool is not None:
|
|
116
|
+
await self._pool.close()
|
|
117
|
+
self._pool = None
|
|
118
|
+
raise
|
|
119
|
+
|
|
120
|
+
async def initialize_schema(self) -> None:
|
|
121
|
+
"""Execute idempotent schema DDL using the configured pool."""
|
|
122
|
+
|
|
123
|
+
pool = self._pool
|
|
124
|
+
if pool is None:
|
|
125
|
+
raise StorageNotInitializedError(
|
|
126
|
+
"no database pool is available; call initialize() first"
|
|
127
|
+
)
|
|
128
|
+
async with pool.acquire(timeout=self._acquire_timeout) as connection:
|
|
129
|
+
for statement in self.schema_statements:
|
|
130
|
+
await connection.execute(statement, timeout=self._command_timeout)
|
|
131
|
+
|
|
132
|
+
async def increment_window(self, key: str, window: int) -> StorageWindow:
|
|
133
|
+
"""Atomically increment a database-clock-derived fixed window."""
|
|
134
|
+
|
|
135
|
+
pool = self._require_pool()
|
|
136
|
+
async with pool.acquire(timeout=self._acquire_timeout) as connection:
|
|
137
|
+
record = await connection.fetchrow(
|
|
138
|
+
self._increment_window_sql,
|
|
139
|
+
key,
|
|
140
|
+
window,
|
|
141
|
+
timeout=self._command_timeout,
|
|
142
|
+
)
|
|
143
|
+
if record is None: # pragma: no cover - PostgreSQL always returns one row
|
|
144
|
+
raise RuntimeError("PostgreSQL increment returned no row")
|
|
145
|
+
return StorageWindow(
|
|
146
|
+
count=int(record["request_count"]),
|
|
147
|
+
window_start=int(record["window_start"]),
|
|
148
|
+
reset_at=int(record["expires_at"]),
|
|
149
|
+
retry_after=float(record["retry_after"]),
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
async def increment(
|
|
153
|
+
self,
|
|
154
|
+
key: str,
|
|
155
|
+
window_start: int,
|
|
156
|
+
expires_at: int,
|
|
157
|
+
) -> int:
|
|
158
|
+
"""Atomically increment an explicit bucket.
|
|
159
|
+
|
|
160
|
+
Retained for compatibility. New enforcement should use
|
|
161
|
+
:meth:`increment_window` so all workers use database time.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
pool = self._require_pool()
|
|
165
|
+
async with pool.acquire(timeout=self._acquire_timeout) as connection:
|
|
166
|
+
count = await connection.fetchval(
|
|
167
|
+
self._increment_sql,
|
|
168
|
+
key,
|
|
169
|
+
window_start,
|
|
170
|
+
expires_at,
|
|
171
|
+
timeout=self._command_timeout,
|
|
172
|
+
)
|
|
173
|
+
return int(count)
|
|
174
|
+
|
|
175
|
+
async def cleanup(
|
|
176
|
+
self,
|
|
177
|
+
expired_before: int | None = None,
|
|
178
|
+
*,
|
|
179
|
+
batch_size: int = 1_000,
|
|
180
|
+
) -> int:
|
|
181
|
+
"""Delete one bounded batch of expired buckets.
|
|
182
|
+
|
|
183
|
+
PostgreSQL time is used when ``expired_before`` is omitted. Concurrent
|
|
184
|
+
cleanup workers skip locked rows rather than blocking one another.
|
|
185
|
+
"""
|
|
186
|
+
|
|
187
|
+
if isinstance(batch_size, bool) or not isinstance(batch_size, int):
|
|
188
|
+
raise ValueError("batch_size must be a positive integer")
|
|
189
|
+
if batch_size < 1 or batch_size > 100_000:
|
|
190
|
+
raise ValueError("batch_size must be between 1 and 100000")
|
|
191
|
+
if expired_before is not None and (
|
|
192
|
+
isinstance(expired_before, bool) or not isinstance(expired_before, int)
|
|
193
|
+
):
|
|
194
|
+
raise ValueError("expired_before must be an integer timestamp or None")
|
|
195
|
+
|
|
196
|
+
pool = self._require_pool()
|
|
197
|
+
async with pool.acquire(timeout=self._acquire_timeout) as connection:
|
|
198
|
+
result = await connection.execute(
|
|
199
|
+
self._cleanup_sql,
|
|
200
|
+
expired_before,
|
|
201
|
+
batch_size,
|
|
202
|
+
math.ceil(self._command_timeout),
|
|
203
|
+
timeout=self._command_timeout,
|
|
204
|
+
)
|
|
205
|
+
try:
|
|
206
|
+
return int(result.rsplit(" ", 1)[-1])
|
|
207
|
+
except (AttributeError, ValueError) as exc:
|
|
208
|
+
message = f"unexpected PostgreSQL DELETE result: {result!r}"
|
|
209
|
+
raise RuntimeError(message) from exc
|
|
210
|
+
|
|
211
|
+
async def close(self) -> None:
|
|
212
|
+
"""Close an internally owned pool; caller-owned pools remain open."""
|
|
213
|
+
|
|
214
|
+
self._initialized = False
|
|
215
|
+
if self._pool is not None and self._owns_pool:
|
|
216
|
+
pool = self._pool
|
|
217
|
+
self._pool = None
|
|
218
|
+
await pool.close()
|
|
219
|
+
|
|
220
|
+
def _require_pool(self) -> Any:
|
|
221
|
+
if self._pool is None or not self._initialized:
|
|
222
|
+
raise StorageNotInitializedError(
|
|
223
|
+
"storage is not initialized; call await limiter.init_db() first"
|
|
224
|
+
)
|
|
225
|
+
return self._pool
|
|
226
|
+
|
|
227
|
+
@staticmethod
|
|
228
|
+
def _validate_timeout(name: str, value: float) -> None:
|
|
229
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
|
|
230
|
+
raise ValueError(f"{name} must be a positive number")
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def _create_table_sql(self) -> str:
|
|
234
|
+
return f"""
|
|
235
|
+
CREATE TABLE IF NOT EXISTS {self._table_name} (
|
|
236
|
+
bucket_key TEXT NOT NULL,
|
|
237
|
+
window_start BIGINT NOT NULL,
|
|
238
|
+
request_count BIGINT NOT NULL,
|
|
239
|
+
expires_at BIGINT NOT NULL,
|
|
240
|
+
PRIMARY KEY (bucket_key, window_start)
|
|
241
|
+
)
|
|
242
|
+
"""
|
|
243
|
+
|
|
244
|
+
@property
|
|
245
|
+
def _create_expiry_index_sql(self) -> str:
|
|
246
|
+
return (
|
|
247
|
+
f"CREATE INDEX IF NOT EXISTS {self._table_name}_expires_idx "
|
|
248
|
+
f"ON {self._table_name} (expires_at)"
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
def _increment_sql(self) -> str:
|
|
253
|
+
return f"""
|
|
254
|
+
INSERT INTO {self._table_name} AS buckets
|
|
255
|
+
(bucket_key, window_start, request_count, expires_at)
|
|
256
|
+
VALUES ($1, $2, 1, $3)
|
|
257
|
+
ON CONFLICT (bucket_key, window_start)
|
|
258
|
+
DO UPDATE SET
|
|
259
|
+
request_count = buckets.request_count + 1,
|
|
260
|
+
expires_at = EXCLUDED.expires_at
|
|
261
|
+
RETURNING request_count
|
|
262
|
+
"""
|
|
263
|
+
|
|
264
|
+
@property
|
|
265
|
+
def _increment_window_sql(self) -> str:
|
|
266
|
+
return f"""
|
|
267
|
+
WITH timing AS (
|
|
268
|
+
SELECT
|
|
269
|
+
floor(
|
|
270
|
+
extract(epoch FROM statement_timestamp())
|
|
271
|
+
/ $2::double precision
|
|
272
|
+
)::bigint * $2::bigint AS window_start,
|
|
273
|
+
extract(epoch FROM statement_timestamp()) AS now_epoch
|
|
274
|
+
), incremented AS (
|
|
275
|
+
INSERT INTO {self._table_name} AS buckets
|
|
276
|
+
(bucket_key, window_start, request_count, expires_at)
|
|
277
|
+
SELECT $1, window_start, 1, window_start + $2::bigint
|
|
278
|
+
FROM timing
|
|
279
|
+
ON CONFLICT (bucket_key, window_start)
|
|
280
|
+
DO UPDATE SET
|
|
281
|
+
request_count = buckets.request_count + 1
|
|
282
|
+
RETURNING request_count, window_start, expires_at
|
|
283
|
+
)
|
|
284
|
+
SELECT
|
|
285
|
+
incremented.request_count,
|
|
286
|
+
incremented.window_start,
|
|
287
|
+
incremented.expires_at,
|
|
288
|
+
greatest(incremented.expires_at - timing.now_epoch, 0)::float8
|
|
289
|
+
AS retry_after
|
|
290
|
+
FROM incremented CROSS JOIN timing
|
|
291
|
+
"""
|
|
292
|
+
|
|
293
|
+
@property
|
|
294
|
+
def _cleanup_sql(self) -> str:
|
|
295
|
+
return f"""
|
|
296
|
+
WITH expired AS (
|
|
297
|
+
SELECT ctid
|
|
298
|
+
FROM {self._table_name}
|
|
299
|
+
WHERE expires_at <= coalesce(
|
|
300
|
+
$1::bigint,
|
|
301
|
+
floor(
|
|
302
|
+
extract(epoch FROM statement_timestamp()) - $3::bigint
|
|
303
|
+
)::bigint
|
|
304
|
+
)
|
|
305
|
+
ORDER BY expires_at
|
|
306
|
+
LIMIT $2
|
|
307
|
+
FOR UPDATE SKIP LOCKED
|
|
308
|
+
)
|
|
309
|
+
DELETE FROM {self._table_name} AS buckets
|
|
310
|
+
USING expired
|
|
311
|
+
WHERE buckets.ctid = expired.ctid
|
|
312
|
+
"""
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-sql-limiter
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Distributed PostgreSQL-backed rate limiting for FastAPI. Atomic counters, simple integration and no Redis required.
|
|
5
|
+
Author: Ragavan
|
|
6
|
+
Maintainer: Ragavan
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/ragavanasde/fastapi-sql-limiter
|
|
9
|
+
Project-URL: Documentation, https://github.com/ragavanasde/fastapi-sql-limiter/tree/main/docs
|
|
10
|
+
Project-URL: Repository, https://github.com/ragavanasde/fastapi-sql-limiter
|
|
11
|
+
Project-URL: Issues, https://github.com/ragavanasde/fastapi-sql-limiter/issues
|
|
12
|
+
Project-URL: Changelog, https://github.com/ragavanasde/fastapi-sql-limiter/blob/main/CHANGELOG.md
|
|
13
|
+
Project-URL: Security, https://github.com/ragavanasde/fastapi-sql-limiter/security/policy
|
|
14
|
+
Keywords: asyncpg,distributed,fastapi,postgresql,rate-limit,throttle
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Framework :: FastAPI
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
26
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.11
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Requires-Dist: asyncpg>=0.28.0
|
|
32
|
+
Requires-Dist: fastapi>=0.100.0
|
|
33
|
+
Provides-Extra: dev
|
|
34
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
35
|
+
Requires-Dist: coverage[toml]>=7.6; extra == "dev"
|
|
36
|
+
Requires-Dist: httpx>=0.24; extra == "dev"
|
|
37
|
+
Requires-Dist: mypy>=1.11; extra == "dev"
|
|
38
|
+
Requires-Dist: pip-audit>=2.7; extra == "dev"
|
|
39
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
40
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
41
|
+
Requires-Dist: twine>=5.1; extra == "dev"
|
|
42
|
+
Dynamic: license-file
|
|
43
|
+
|
|
44
|
+
# fastapi-sql-limiter
|
|
45
|
+
|
|
46
|
+
`fastapi-sql-limiter` is a lightweight, PostgreSQL-backed fixed-window rate
|
|
47
|
+
limiter for FastAPI. It gives every application process the same atomic request
|
|
48
|
+
counter, so limits remain consistent across workers and hosts without adding
|
|
49
|
+
Redis to a PostgreSQL-based stack.
|
|
50
|
+
|
|
51
|
+
**Distributed FastAPI rate limiting using PostgreSQL. No Redis required.**
|
|
52
|
+
|
|
53
|
+
The package is intended for FastAPI services that already operate PostgreSQL
|
|
54
|
+
and need straightforward endpoint throttling rather than a full API gateway.
|
|
55
|
+
|
|
56
|
+
Project links: [source](https://github.com/ragavanasde/fastapi-sql-limiter),
|
|
57
|
+
[documentation](https://github.com/ragavanasde/fastapi-sql-limiter/tree/main/docs),
|
|
58
|
+
[issues](https://github.com/ragavanasde/fastapi-sql-limiter/issues), and
|
|
59
|
+
[changelog](CHANGELOG.md).
|
|
60
|
+
|
|
61
|
+
## Features
|
|
62
|
+
|
|
63
|
+
- Atomic distributed counters using one PostgreSQL UPSERT and database-clock
|
|
64
|
+
window calculation per request.
|
|
65
|
+
- Async `asyncpg` connection pooling or integration with a caller-owned pool.
|
|
66
|
+
- Per-client, per-user, per-tenant, or per-API-key limits.
|
|
67
|
+
- HTTP 429 responses with standard `Retry-After`; successful and rejected
|
|
68
|
+
responses include conventional `X-RateLimit-*` metadata.
|
|
69
|
+
- Explicit startup, shutdown, and expired-bucket cleanup APIs.
|
|
70
|
+
- Hashed identities in storage and no implicit trust of proxy headers.
|
|
71
|
+
- Sanitized HTTP 503 fail-closed behavior for storage failures.
|
|
72
|
+
- Bounded concurrent cleanup, configurable timeouts, and optional observers.
|
|
73
|
+
- Typed public API with no Redis dependency.
|
|
74
|
+
|
|
75
|
+
## Requirements
|
|
76
|
+
|
|
77
|
+
- Python 3.11 or newer (CI covers 3.11–3.15).
|
|
78
|
+
- FastAPI 0.100 or newer and asyncpg 0.28 or newer.
|
|
79
|
+
- A supported PostgreSQL release (CI covers PostgreSQL 15 and 19).
|
|
80
|
+
|
|
81
|
+
## Installation
|
|
82
|
+
|
|
83
|
+
Install the current source checkout with:
|
|
84
|
+
|
|
85
|
+
```console
|
|
86
|
+
python -m pip install .
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
After a release is published to PyPI, the package can be installed with:
|
|
90
|
+
|
|
91
|
+
```console
|
|
92
|
+
python -m pip install fastapi-sql-limiter
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
For development tools, use `python -m pip install -e ".[dev]"` in a fresh
|
|
96
|
+
virtual environment.
|
|
97
|
+
|
|
98
|
+
## Quick start
|
|
99
|
+
|
|
100
|
+
Store the connection string in an environment variable rather than source
|
|
101
|
+
control:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
import os
|
|
105
|
+
from contextlib import asynccontextmanager
|
|
106
|
+
|
|
107
|
+
from fastapi import FastAPI
|
|
108
|
+
from fastapi_sql_limiter import RateLimiter, rate_limit
|
|
109
|
+
|
|
110
|
+
limiter = RateLimiter(
|
|
111
|
+
dsn=os.environ["DATABASE_URL"],
|
|
112
|
+
set_as_default=False,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@asynccontextmanager
|
|
117
|
+
async def lifespan(app: FastAPI):
|
|
118
|
+
await limiter.init_db()
|
|
119
|
+
yield
|
|
120
|
+
await limiter.close()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
app = FastAPI(lifespan=lifespan)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@app.get("/items")
|
|
127
|
+
@rate_limit(limit=5, window=60, limiter=limiter)
|
|
128
|
+
async def read_items():
|
|
129
|
+
return {"items": ["one", "two"]}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The sixth request from the same direct client within a fixed 60-second window
|
|
133
|
+
returns `429 Too Many Requests`. The decorator must remain below the FastAPI
|
|
134
|
+
route decorator, as shown above.
|
|
135
|
+
|
|
136
|
+
For compatibility with the original `0.1.0` example, constructing a limiter
|
|
137
|
+
sets it as the process default, so `@rate_limit(limit=5, window=60)` also works.
|
|
138
|
+
Passing `limiter=` explicitly is recommended when a process can host more than
|
|
139
|
+
one FastAPI application or storage configuration.
|
|
140
|
+
|
|
141
|
+
## Choosing a request identity
|
|
142
|
+
|
|
143
|
+
The default key is the direct network peer IP (`request.client.host`). It does
|
|
144
|
+
not use `X-Forwarded-For`, because trusting that header without a correctly
|
|
145
|
+
configured proxy lets clients evade limits.
|
|
146
|
+
|
|
147
|
+
Authenticated services should normally limit a stable internal identity:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
from fastapi import HTTPException, Request
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def authenticated_account(request: Request) -> str:
|
|
154
|
+
account_id = getattr(request.state, "account_id", None)
|
|
155
|
+
if account_id is None:
|
|
156
|
+
raise HTTPException(status_code=401, detail="Authentication required")
|
|
157
|
+
return str(account_id)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@app.get("/reports")
|
|
161
|
+
@rate_limit(
|
|
162
|
+
limit=20,
|
|
163
|
+
window=60,
|
|
164
|
+
limiter=limiter,
|
|
165
|
+
key_func=authenticated_account,
|
|
166
|
+
namespace="reports",
|
|
167
|
+
)
|
|
168
|
+
async def reports():
|
|
169
|
+
return {"status": "ready"}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Key functions may be synchronous or asynchronous and must return a non-empty
|
|
173
|
+
string of at most 4096 UTF-8 bytes. Identities are SHA-256 hashed before they
|
|
174
|
+
enter PostgreSQL. Hashing a low-entropy value such as an IP address is
|
|
175
|
+
pseudonymization, not anonymization: it may remain guessable. Never return a
|
|
176
|
+
raw API key; use its internal record ID or an application-side keyed digest.
|
|
177
|
+
A namespace separates independent policies; by default it includes the
|
|
178
|
+
endpoint, HTTP method, and FastAPI route template.
|
|
179
|
+
Separate applications that reuse the same database should use different table
|
|
180
|
+
names or explicit application-prefixed namespaces; identical code, methods,
|
|
181
|
+
and route templates intentionally produce identical automatic namespaces.
|
|
182
|
+
|
|
183
|
+
## Existing asyncpg pool
|
|
184
|
+
|
|
185
|
+
Applications that already manage a pool can share it:
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
from fastapi_sql_limiter import PostgresStorage, RateLimiter
|
|
189
|
+
|
|
190
|
+
storage = PostgresStorage(pool=application_pool)
|
|
191
|
+
limiter = RateLimiter(storage=storage, set_as_default=False)
|
|
192
|
+
await limiter.init_db()
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`limiter.close()` never closes a caller-owned pool, but it does mark the
|
|
196
|
+
limiter storage closed. Call `init_db()` again before reuse.
|
|
197
|
+
|
|
198
|
+
## Direct checks and cleanup
|
|
199
|
+
|
|
200
|
+
The lower-level API can enforce limits outside a route decorator:
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
result = await limiter.check("jobs:tenant-42", limit=100, window=60)
|
|
204
|
+
if not result.allowed:
|
|
205
|
+
print(result.retry_after)
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Expired buckets do not affect correctness, but they consume table space.
|
|
209
|
+
Schedule cleanup at an interval appropriate for the service:
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
deleted_rows = await limiter.cleanup()
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Cleanup deletes at most 1,000 rows by default. Use `batch_size=`, loop until it
|
|
216
|
+
returns zero, and keep PostgreSQL autovacuum enabled. Concurrent cleaners use
|
|
217
|
+
`FOR UPDATE SKIP LOCKED` rather than waiting on the same rows.
|
|
218
|
+
|
|
219
|
+
## Production schema and failures
|
|
220
|
+
|
|
221
|
+
Production applications should install `PostgresStorage.schema_statements`
|
|
222
|
+
with an administrative role, then construct the limiter with
|
|
223
|
+
`create_schema=False`. The runtime role needs `SELECT`, `INSERT`, and `UPDATE`;
|
|
224
|
+
only the cleanup role needs `DELETE`. Connection creation, pool acquisition,
|
|
225
|
+
and commands have configurable timeouts.
|
|
226
|
+
|
|
227
|
+
Database failures do not silently disable protection. Decorated requests get
|
|
228
|
+
a sanitized `503 Rate limiting service unavailable`; quota violations alone
|
|
229
|
+
use 429. Checks are not automatically retried because a lost database response
|
|
230
|
+
can leave an already-committed increment.
|
|
231
|
+
|
|
232
|
+
Pass a sync or async `observer(event)` to `RateLimiter` for allowed, rejected,
|
|
233
|
+
and database-error counts and latency. Events omit identities and error text,
|
|
234
|
+
and observer failures cannot change enforcement.
|
|
235
|
+
|
|
236
|
+
## API reference
|
|
237
|
+
|
|
238
|
+
- `RateLimiter(dsn, ...)`: owns PostgreSQL storage and optionally registers as
|
|
239
|
+
the default limiter.
|
|
240
|
+
- `RateLimiter.init_db()`: creates the pool, table, and expiry index.
|
|
241
|
+
- `RateLimiter.check(key, limit=, window=)`: returns `RateLimitInfo`.
|
|
242
|
+
- `RateLimiter.cleanup(expired_before=None, batch_size=1000)`: deletes one
|
|
243
|
+
bounded batch.
|
|
244
|
+
- `RateLimiter.close()`: releases owned database resources.
|
|
245
|
+
- `rate_limit(limit=, window=, limiter=, key_func=, namespace=)`: decorates a
|
|
246
|
+
FastAPI endpoint.
|
|
247
|
+
- `PostgresStorage(pool=...)`: adapts an existing asyncpg-compatible pool.
|
|
248
|
+
- `RateLimitExceeded`: the HTTP 429 exception raised by the decorator.
|
|
249
|
+
- `RateLimiterUnavailable`: the sanitized HTTP 503 exception.
|
|
250
|
+
- `RateLimitEvent`: the optional observer payload.
|
|
251
|
+
|
|
252
|
+
## How it works
|
|
253
|
+
|
|
254
|
+
Each request maps to `(namespace, hashed identity, fixed window)`. The window,
|
|
255
|
+
reset time, and retry delay use PostgreSQL `statement_timestamp()` in the same
|
|
256
|
+
statement as `INSERT ... ON CONFLICT DO UPDATE ... RETURNING`. The request is
|
|
257
|
+
accepted while the returned count is at most the configured limit. This avoids
|
|
258
|
+
lost updates, process-local races, application clock drift, and extra queries.
|
|
259
|
+
|
|
260
|
+
## Troubleshooting
|
|
261
|
+
|
|
262
|
+
- **`storage is not initialized`**: call `await limiter.init_db()` in FastAPI's
|
|
263
|
+
lifespan before serving requests.
|
|
264
|
+
- **Database permission error at startup**: create the table once with a role
|
|
265
|
+
allowed to run DDL or grant the application role the required schema access.
|
|
266
|
+
- **Every request has the proxy IP**: use an authenticated identity or a custom
|
|
267
|
+
key function that reads forwarding headers only from a trusted proxy setup.
|
|
268
|
+
- **Unexpectedly shared limits**: pass distinct `namespace=` values or explicit
|
|
269
|
+
limiter instances.
|
|
270
|
+
- **Database outage**: decorated checks return sanitized 503 responses. The
|
|
271
|
+
package intentionally does not fail open and silently remove protection.
|
|
272
|
+
|
|
273
|
+
## Known limitations
|
|
274
|
+
|
|
275
|
+
- Fixed windows can permit a burst around a window boundary.
|
|
276
|
+
- Every check performs a database round trip; extremely high-volume public APIs
|
|
277
|
+
may be better served by a gateway or an in-memory distributed store.
|
|
278
|
+
- Cleanup must be scheduled by the application or database operator.
|
|
279
|
+
- Every protected request performs a PostgreSQL write; a hot identity is
|
|
280
|
+
serialized at one row.
|
|
281
|
+
- Multiple simultaneous policies are deferred because partial counter updates
|
|
282
|
+
and atomic rejection semantics require additional design work.
|
|
283
|
+
- Real PostgreSQL tests exist and run in CI, but require `TEST_DATABASE_URL`
|
|
284
|
+
locally.
|
|
285
|
+
|
|
286
|
+
## Development and security
|
|
287
|
+
|
|
288
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for local checks and
|
|
289
|
+
[SECURITY.md](SECURITY.md) for vulnerability reporting and operational advice.
|
|
290
|
+
Release changes are recorded in [CHANGELOG.md](CHANGELOG.md).
|
|
291
|
+
|
|
292
|
+
Operational details are in [deployment](docs/deployment.md), architecture and
|
|
293
|
+
API semantics in [architecture](docs/architecture.md), reproducible performance
|
|
294
|
+
work in [benchmarks](docs/benchmarks.md), and release steps in
|
|
295
|
+
[releasing](docs/releasing.md).
|
|
296
|
+
|
|
297
|
+
## License
|
|
298
|
+
|
|
299
|
+
Copyright (c) 2026 Ragavan. This project is distributed under the
|
|
300
|
+
[MIT License](LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
fastapi_sql_limiter/__init__.py,sha256=ZzGNhvgUNLu605S_uwvIzax9ybNu1ifRoCX5opg2Au4,762
|
|
2
|
+
fastapi_sql_limiter/_init_.py,sha256=kmQyEq4gs8-MnWryUJdq4reoXAjkhbnO5zmQQx5UkZI,227
|
|
3
|
+
fastapi_sql_limiter/exception.py,sha256=-dZZrfzFXVI8L3nJ9ZOr99wrL6pW8_oslhd7Mw536M0,437
|
|
4
|
+
fastapi_sql_limiter/exceptions.py,sha256=IKomaDMAC9lPhmgCxM7PZOzgM1B2yDewcHoO0EGnvKc,1503
|
|
5
|
+
fastapi_sql_limiter/limiter.py,sha256=pynrpz6Vw0RPV9eheYCHVqc4wE0TvZdGQ6XFnA3AVZc,15407
|
|
6
|
+
fastapi_sql_limiter/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
7
|
+
fastapi_sql_limiter/storage.py,sha256=qYHwunhKuOxe571Q3c08T90x2g-x4Ao49nrStv3ucXw,11435
|
|
8
|
+
fastapi_sql_limiter-0.3.0.dist-info/licenses/LICENSE,sha256=QAO-pEvYWb3M6jbmi0-0zv3d9fsLu9IYQsLrxOczKB0,1064
|
|
9
|
+
fastapi_sql_limiter-0.3.0.dist-info/METADATA,sha256=gTSCAbHu56uB-inPo3NphKGWR7gvcO1s7U_PmbI2VHw,11656
|
|
10
|
+
fastapi_sql_limiter-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
fastapi_sql_limiter-0.3.0.dist-info/top_level.txt,sha256=zLhMGxs7fBQBAstuKzmGzlucg2coHxvpDOX2iL__BVc,20
|
|
12
|
+
fastapi_sql_limiter-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ragavan
|
|
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
|
+
fastapi_sql_limiter
|