Repository navigation
feat(Observability): Bind request context for API requests #9041
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
Open
khvn26
wants to merge
12
commits into
main
Choose a base branch
from
feat/eng-611-request-context
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+667
−95
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
1f30e8c
feat(Observability): Bind request context for API requests
khvn26 654a695
feat(Observability): Resolve request context from API routes
khvn26 8fd7e14
refactor(Observability): Resolve request context IDs in a service
khvn26 b349cff
refactor(Observability): Move the view kwargs mapper to `telemetry.ma…
khvn26 37bd642
refactor(Observability): Resolve request context IDs in one query at …
khvn26 c9f361b
fix(Observability): Skip non-decimal IDs in view kwargs
khvn26 f45f114
refactor(Observability): Drop request context comments
khvn26 950c741
refactor(Observability): Rename `ResolvedIds` to `ResolvedTelemetryAt…
khvn26 c063801
feat(Observability): Bind the environment key to request context
khvn26 c2382e2
feat(Observability): Bind the organisation of organisation routes
khvn26 1ec06a2
fix(Observability): Install the request context hook once
khvn26 75e5ccf
Merge remote-tracking branch 'origin/main' into feat/eng-611-request-…
khvn26 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,19 @@ | ||
| import typing | ||
|
|
||
| from telemetry.types import ResolvedTelemetryAttributes | ||
|
|
||
|
|
||
| def map_view_kwargs_to_telemetry_attributes( | ||
| view_kwargs: dict[str, typing.Any], | ||
| ) -> ResolvedTelemetryAttributes: | ||
| """Map the URL kwargs of a view to the IDs of the entities it acts on.""" | ||
| ids: ResolvedTelemetryAttributes = {} | ||
| if str(organisation_pk := view_kwargs.get("organisation_pk", "")).isdecimal(): | ||
| ids["organisation__id"] = int(organisation_pk) | ||
| if str(project_pk := view_kwargs.get("project_pk", "")).isdecimal(): | ||
| ids["project__id"] = int(project_pk) | ||
| if str(feature_pk := view_kwargs.get("feature_pk", "")).isdecimal(): | ||
| ids["feature__id"] = int(feature_pk) | ||
| if environment_api_key := view_kwargs.get("environment_api_key"): | ||
| ids["environment__key"] = environment_api_key | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| return ids | ||
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,68 @@ | ||
| """ | ||
| Describe API requests with Flagsmith-specific request context. | ||
|
|
||
| `common.core.request_context.RequestContextMiddleware` scopes request context | ||
| to the request, and binds its route. What the request acts on, and who makes | ||
| it, is only known once DRF has authenticated the request inside the view, so | ||
| it's bound from there. | ||
| """ | ||
|
|
||
| import functools | ||
| import typing | ||
|
|
||
| from common.core.request_context import bind_request_context | ||
| from rest_framework.request import Request | ||
| from rest_framework.views import APIView | ||
|
|
||
| from api_keys.user import APIKeyUser | ||
| from telemetry.mappers import map_view_kwargs_to_telemetry_attributes | ||
| from telemetry.services import get_resolved_telemetry_attributes | ||
| from users.models import FFAdminUser | ||
|
|
||
|
|
||
| def bind_api_request_context(request: Request, view: APIView) -> None: | ||
| """Bind what's known about `request` once DRF has authenticated it.""" | ||
| user = request.user | ||
| if isinstance(user, FFAdminUser): | ||
| bind_request_context(user__id=str(user.uuid)) | ||
| elif getattr(user, "is_master_api_key_user", False): | ||
| # NOTE: `isinstance` can't tell `APIKeyUser`s apart, see `UserABC`. | ||
| # Master API keys aren't users, so don't identify them as such; but | ||
| # they belong to exactly one organisation. | ||
| api_key_user = typing.cast(APIKeyUser, user) | ||
| bind_request_context(organisation__id=api_key_user.key.organisation_id) | ||
|
|
||
| resolved_ids = get_resolved_telemetry_attributes( | ||
| map_view_kwargs_to_telemetry_attributes(view.kwargs) | ||
| ) | ||
| bind_request_context(**resolved_ids) | ||
|
|
||
|
|
||
| _INSTALLED = "_binds_api_request_context" | ||
|
|
||
|
|
||
| def install() -> None: | ||
| """ | ||
| Bind API request context to every DRF view's request on authentication. | ||
|
|
||
| API requests, e.g. authenticated by token or master API key, are | ||
| authenticated by DRF inside the view, so a middleware can't tell who makes | ||
| them. DRF has no hook for authenticated requests, and views extend | ||
| `APIView` directly, so wrap `APIView.perform_authentication`, which every | ||
| view runs before checking permissions. | ||
| """ | ||
| perform_authentication = APIView.perform_authentication | ||
| if getattr(perform_authentication, _INSTALLED, False): | ||
| return # e.g. Django set up its apps again | ||
|
|
||
| @functools.wraps(perform_authentication) | ||
| def _perform_authentication(self: APIView, request: Request) -> None: | ||
| perform_authentication(self, request) | ||
| bind_api_request_context(request, self) | ||
|
|
||
| setattr(_perform_authentication, _INSTALLED, True) | ||
| setattr( | ||
| APIView, | ||
| "perform_authentication", | ||
| typing.cast(typing.Any, _perform_authentication), | ||
| ) |
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 was deleted.
Oops, something went wrong.
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,11 @@ | ||
| from typing import TypedDict | ||
|
|
||
|
|
||
| class ResolvedTelemetryAttributes(TypedDict, total=False): | ||
| """Telemetry-relevant attributes from objects an API request acts on""" | ||
|
|
||
| organisation__id: int | ||
| project__id: int | ||
| feature__id: int | ||
| environment__id: int | ||
| environment__key: str |
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.
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.
Uh oh!
There was an error while loading. Please reload this page.