Skip to content

Commit

Permalink
Use fastapi routes for metrics (#467)
Browse files Browse the repository at this point in the history
  • Loading branch information
evroon authored Feb 11, 2024
1 parent 9479c92 commit 549243b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
3 changes: 2 additions & 1 deletion backend/bracket/models/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pydantic import BaseModel

from bracket.utils.http import HTTPMethod
from bracket.utils.starlette import get_route_path
from bracket.utils.types import EnumAutoStr

if TYPE_CHECKING:
Expand All @@ -28,7 +29,7 @@ class RequestDefinition(BaseModel):
@staticmethod
def from_request(request: Request) -> RequestDefinition:
return RequestDefinition(
url=str(request.url.path),
url=get_route_path(request),
method=HTTPMethod(request.method),
)

Expand Down
31 changes: 31 additions & 0 deletions backend/bracket/utils/starlette.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from starlette.requests import Request
from starlette.routing import Match, Route


def _get_route_for_request(request: Request) -> Route | None:
"""
Determine FastAPI route for a starlette Request
Based on: https://stackoverflow.com/a/76203889
"""

route: Route | None = getattr(request.state, "__route_cached__", None)
if route is not None:
return route

for route in request.app.routes:
match, _ = route.matches(request.scope)
if match is Match.FULL:
request.state.__route_cached__ = route
return route

return None


def get_route_path(request: Request) -> str:
if (route := _get_route_for_request(request)) is not None:
msg = f"Expected `str` for `route.path`, got: {type(route.path).__name__}"
assert isinstance(route.path, str), msg
return route.path

return f"unhandled:{request.url.path}"

0 comments on commit 549243b

Please sign in to comment.