-
Notifications
You must be signed in to change notification settings - Fork 0
Chore/refactor and rate limit #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import redis.asyncio as aioredis | ||
| from fastapi import Request | ||
| from fastapi_limiter import FastAPILimiter | ||
|
|
||
| from app.settings import settings | ||
|
|
||
|
|
||
| async def rate_limit_identifier(request: Request) -> str: | ||
| """ | ||
| Prefer user id when available (set in get_current_user), otherwise fall | ||
| back to client IP. Keeps limits per-authenticated user across hosts. | ||
| """ | ||
| user_id = getattr(request.state, "user_id", None) | ||
| if user_id: | ||
| return f"user:{user_id}" | ||
| if request.client and request.client.host: | ||
| return f"ip:{request.client.host}" | ||
| return "anonymous" | ||
|
|
||
|
|
||
| async def init_rate_limiter(redis_client: aioredis.Redis | None = None) -> None: | ||
| """ | ||
| Initialize FastAPI-Limiter with a Redis client. Uses decode_responses to | ||
| keep counters as strings for portability. | ||
| """ | ||
| redis = redis_client or aioredis.from_url( | ||
| settings.redis_url, encoding="utf-8", decode_responses=True | ||
| ) | ||
| await FastAPILimiter.init(redis, identifier=rate_limit_identifier) | ||
|
|
||
|
|
||
| async def close_rate_limiter() -> None: | ||
| try: | ||
| await FastAPILimiter.close() | ||
| except Exception: | ||
| # best effort; don't crash shutdown | ||
| return |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Daily upload quota is bumped before any storage or database work and never rolled back.
_enforce_daily_upload_quotaruns as soon as the file is read, but ifwrite_bytes_async, the DB insert/commit, or downstream processing fails, the Redis counter remains incremented and the user loses daily quota even though no asset was stored. This can lock users out after transient upload errors; defer the increment until after successful persistence or wrap later steps in try/except to decrement on failure.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@codex can you backup this expected edge case with a test to prove your point? Or will the redis stubs make it hard to do so?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary
Testing
pytest tests/test_assets.py -q(fails: Postgres not running in container)View task →
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@codex That was a good call.
I had to copy the patch and propagate the failure with:
except Exception as exc:
if quota_charged and user_id is not None:
await self._rollback_daily_upload_quota(
user_id=user_id, bytes_removed=quota_bytes
)
if isinstance(exc, HTTPException):
raise
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Upload failed, please retry",
) from exc
Just as personal feedback. I am able to run tests in CI github environment by using simple commands that I have prepared like setting up the repo with poetry install --with dev and make db-up and make test-auto.
What is blocking you from doing that so that I can fix it?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary
Testing
pytest tests/test_assets.py::test_upload_rolls_back_quota_on_failure -q(fails: Postgres not running locally)View task →