-
Notifications
You must be signed in to change notification settings - Fork 602
feat(integrations): instrument pyreqwest tracing #5682
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
+693
−39
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
4639c12
feat(integrations): instrument pyreqwest tracing
servusdei2018 5e3f606
Test setup
sentrivana 64f7284
Merge branch 'master' into servusdei2018/master
sentrivana 2d5bf72
Merge branch 'master' into servusdei2018/master
sentrivana 5d2ee24
nit: address PR comments
servusdei2018 5e89884
fix: prevent duplicate spans
servusdei2018 72d6b3e
Merge remote-tracking branch 'origin/master' into servusdei2018/master
sentrivana e37329e
more tests
sentrivana d6b1942
revert pydantic ai update
sentrivana 8cf12aa
reformat
sentrivana 74e0566
Merge branch 'master' into master
sentrivana 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
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
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 |
|---|---|---|
|
|
@@ -124,6 +124,7 @@ | |
| "Network": [ | ||
| "grpc", | ||
| "httpx", | ||
| "pyreqwest", | ||
| "requests", | ||
| ], | ||
| "Tasks": [ | ||
|
|
||
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,136 @@ | ||
| import sentry_sdk | ||
| from sentry_sdk import start_span | ||
| from sentry_sdk.consts import OP, SPANDATA | ||
| from sentry_sdk.integrations import Integration, DidNotEnable | ||
| from sentry_sdk.tracing import BAGGAGE_HEADER_NAME | ||
| from sentry_sdk.tracing_utils import ( | ||
| should_propagate_trace, | ||
| add_http_request_source, | ||
| add_sentry_baggage_to_headers, | ||
| ) | ||
| from sentry_sdk.utils import ( | ||
| SENSITIVE_DATA_SUBSTITUTE, | ||
| capture_internal_exceptions, | ||
| logger, | ||
| parse_url, | ||
| ) | ||
|
|
||
| from contextlib import contextmanager | ||
| from typing import Any, Generator | ||
|
|
||
| try: | ||
| from pyreqwest.client import ClientBuilder, SyncClientBuilder # type: ignore[import-not-found] | ||
| from pyreqwest.request import ( # type: ignore[import-not-found] | ||
| Request, | ||
| OneOffRequestBuilder, | ||
| SyncOneOffRequestBuilder, | ||
| ) | ||
| from pyreqwest.middleware import Next, SyncNext # type: ignore[import-not-found] | ||
| from pyreqwest.response import Response, SyncResponse # type: ignore[import-not-found] | ||
| except ImportError: | ||
| raise DidNotEnable("pyreqwest not installed or incompatible version installed") | ||
|
|
||
|
|
||
| class PyreqwestIntegration(Integration): | ||
| identifier = "pyreqwest" | ||
| origin = f"auto.http.{identifier}" | ||
|
|
||
| @staticmethod | ||
| def setup_once() -> None: | ||
| _patch_pyreqwest() | ||
|
|
||
|
|
||
| def _patch_pyreqwest() -> None: | ||
| # Patch Client Builders | ||
| _patch_builder_method(ClientBuilder, "build", sentry_async_middleware) | ||
| _patch_builder_method(SyncClientBuilder, "build", sentry_sync_middleware) | ||
|
|
||
| # Patch Request Builders | ||
| _patch_builder_method(OneOffRequestBuilder, "send", sentry_async_middleware) | ||
| _patch_builder_method(SyncOneOffRequestBuilder, "send", sentry_sync_middleware) | ||
|
|
||
|
|
||
| def _patch_builder_method(cls: type, method_name: str, middleware: "Any") -> None: | ||
| if not hasattr(cls, method_name): | ||
| return | ||
|
|
||
| original_method = getattr(cls, method_name) | ||
|
|
||
| def sentry_patched_method(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": | ||
servusdei2018 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if not getattr(self, "_sentry_instrumented", False): | ||
| integration = sentry_sdk.get_client().get_integration(PyreqwestIntegration) | ||
| if integration is not None: | ||
| self.with_middleware(middleware) | ||
| try: | ||
| self._sentry_instrumented = True | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Did we have some test to check if this works and doesn't always give the exception? (as these are native classes) |
||
| except (TypeError, AttributeError): | ||
| # In case the instance itself is immutable or doesn't allow extra attributes | ||
| pass | ||
servusdei2018 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return original_method(self, *args, **kwargs) | ||
|
|
||
| setattr(cls, method_name, sentry_patched_method) | ||
|
|
||
|
|
||
| @contextmanager | ||
| def _sentry_pyreqwest_span(request: "Request") -> "Generator[Any, None, None]": | ||
| parsed_url = None | ||
| with capture_internal_exceptions(): | ||
| parsed_url = parse_url(str(request.url), sanitize=False) | ||
|
|
||
| with start_span( | ||
| op=OP.HTTP_CLIENT, | ||
| name=f"{request.method} {parsed_url.url if parsed_url else SENSITIVE_DATA_SUBSTITUTE}", | ||
| origin=PyreqwestIntegration.origin, | ||
| ) as span: | ||
| span.set_data(SPANDATA.HTTP_METHOD, request.method) | ||
| if parsed_url is not None: | ||
| span.set_data("url", parsed_url.url) | ||
| span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query) | ||
| span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment) | ||
|
|
||
| if should_propagate_trace(sentry_sdk.get_client(), str(request.url)): | ||
| for ( | ||
| key, | ||
| value, | ||
| ) in sentry_sdk.get_current_scope().iter_trace_propagation_headers(): | ||
| logger.debug( | ||
| "[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format( | ||
| key=key, value=value, url=request.url | ||
| ) | ||
| ) | ||
|
|
||
| if key == BAGGAGE_HEADER_NAME: | ||
| add_sentry_baggage_to_headers(request.headers, value) | ||
| else: | ||
| request.headers[key] = value | ||
|
|
||
| yield span | ||
|
|
||
| with capture_internal_exceptions(): | ||
| add_http_request_source(span) | ||
|
|
||
|
|
||
| async def sentry_async_middleware( | ||
| request: "Request", next_handler: "Next" | ||
| ) -> "Response": | ||
| if sentry_sdk.get_client().get_integration(PyreqwestIntegration) is None: | ||
| return await next_handler.run(request) | ||
|
|
||
| with _sentry_pyreqwest_span(request) as span: | ||
| response = await next_handler.run(request) | ||
| span.set_http_status(response.status) | ||
|
|
||
| return response | ||
|
|
||
|
|
||
| def sentry_sync_middleware( | ||
| request: "Request", next_handler: "SyncNext" | ||
| ) -> "SyncResponse": | ||
| if sentry_sdk.get_client().get_integration(PyreqwestIntegration) is None: | ||
| return next_handler.run(request) | ||
|
|
||
| with _sentry_pyreqwest_span(request) as span: | ||
| response = next_handler.run(request) | ||
| span.set_http_status(response.status) | ||
|
|
||
| return response | ||
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,9 @@ | ||
| import os | ||
| import sys | ||
| import pytest | ||
|
|
||
| pytest.importorskip("pyreqwest") | ||
|
|
||
| # Load `pyreqwest_helpers` into the module search path to test request source path names relative to module. See | ||
| # `test_request_source_with_module_in_search_path` | ||
| sys.path.insert(0, os.path.join(os.path.dirname(__file__))) |
Empty file.
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,2 @@ | ||
| def get_request_with_client(client, url): | ||
| client.get(url).build().send() |
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.