-
Notifications
You must be signed in to change notification settings - Fork 37
feat(http): implement body inspection handler #736
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
RKS (rksharma-owg)
wants to merge
13
commits into
microsoft:main
Choose a base branch
from
rksharma-owg:feat/body-inspection-handler
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.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
244d00a
feat(http): implement body inspection handler (closes #418)
rksharma-owg 036f295
chore: merge main into body inspection handler
rksharma-owg ee0ea54
fix(http): address body inspection review feedback
rksharma-owg 1dc4c07
fix(http): preserve inspection stream state
rksharma-owg 867f2e6
fix(http): align inspection guard and span lifecycle
rksharma-owg dc43895
test(http): isolate expected exception calls
rksharma-owg b80f4fc
fix(http): isolate captures and byte accounting
rksharma-owg ae25c49
fix(http): preserve restored response lifecycle
rksharma-owg 22d08e5
fix(http): guard body inspection fast paths
rksharma-owg bedfa19
Merge remote-tracking branch 'upstream/main' into feat/body-inspectio…
rksharma-owg eaa50db
fix(http): preserve options with request extensions
rksharma-owg 925196e
fix(http): read request extensions in body inspection and fallback to…
rksharma-owg d9180bb
fix(http): eliminate request options reflection across middleware han…
rksharma-owg 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
116 changes: 116 additions & 0 deletions
116
packages/http/httpx/kiota_http/middleware/body_inspection_handler.py
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,116 @@ | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. All Rights Reserved. | ||
| # Licensed under the MIT License. | ||
| # See License in the project root for license information. | ||
| # ------------------------------------ | ||
|
|
||
| from typing import Optional | ||
|
|
||
| import httpx | ||
|
|
||
| from .middleware import REQUEST_OPTIONS_KEY, BaseMiddleware | ||
| from .options import BodyInspectionHandlerOption | ||
|
|
||
| BODY_INSPECTION_KEY = "com.microsoft.kiota.handler.bodyInspection.enable" | ||
|
|
||
|
|
||
| class BodyInspectionHandler(BaseMiddleware): | ||
| """The Body Inspection Handler allows the developer to inspect the body of the | ||
| request and response. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| options: Optional[BodyInspectionHandlerOption] = None, | ||
| ): | ||
| """Create an instance of BodyInspectionHandler | ||
|
|
||
| Args: | ||
| options (BodyInspectionHandlerOption, optional): Default options to apply to the | ||
| handler. A new BodyInspectionHandlerOption per handler when not provided. | ||
| """ | ||
| super().__init__() | ||
| self.options = options if options is not None else BodyInspectionHandlerOption() | ||
|
|
||
| async def send( | ||
| self, request: httpx.Request, transport: httpx.AsyncBaseTransport | ||
| ) -> httpx.Response: | ||
| """To execute the current middleware | ||
|
|
||
| Args: | ||
| request (httpx.Request): The prepared request object | ||
| transport (httpx.AsyncBaseTransport): The HTTP transport to use | ||
|
|
||
| Returns: | ||
| httpx.Response: The response object. | ||
| """ | ||
| if request is None: | ||
| raise TypeError("request cannot be null") | ||
|
|
||
| current_options = self._get_current_options(request) | ||
|
baywet marked this conversation as resolved.
|
||
| span = self._create_observability_span(request, "BodyInspectionHandler_send") | ||
| try: | ||
| span.set_attribute(BODY_INSPECTION_KEY, True) | ||
|
|
||
| if current_options and current_options.inspect_request_body: | ||
| content = await request.aread() | ||
| if content: | ||
| current_options.request_body = content | ||
| else: | ||
| current_options.request_body = None | ||
|
|
||
| response = await super().send(request, transport) | ||
|
|
||
| if current_options and current_options.inspect_response_body: | ||
| response_content: Optional[bytes] = None | ||
| # A consumed stream is inspectable only when HTTPX cached its content. | ||
| if hasattr(response, "_content"): | ||
| response_content = response.content | ||
| elif not response.is_stream_consumed and not response.is_closed: | ||
| num_bytes_downloaded = response.num_bytes_downloaded | ||
| raw_content = b"".join([chunk async for chunk in response.aiter_raw()]) | ||
| self._restore_response_stream(response, raw_content, num_bytes_downloaded) | ||
| response_content = await response.aread() | ||
| self._restore_response_stream(response, raw_content, num_bytes_downloaded) | ||
| if response_content: | ||
| current_options.response_body = response_content | ||
| else: | ||
| current_options.response_body = None | ||
|
|
||
| return response | ||
| finally: | ||
| span.end() | ||
|
|
||
| def _get_current_options(self, request: httpx.Request) -> BodyInspectionHandlerOption: | ||
| """Returns the options to use for the request. Overrides default options if | ||
| request options are passed. | ||
|
|
||
| Args: | ||
| request (httpx.Request): The prepared request object | ||
|
|
||
| Returns: | ||
| BodyInspectionHandlerOption: The options to be used. | ||
| """ | ||
| current_options = None | ||
| request_options = request.extensions.get(REQUEST_OPTIONS_KEY) | ||
| if request_options: | ||
| current_options = request_options.get(BodyInspectionHandlerOption.get_key(), None) | ||
| if not current_options: | ||
| current_options = self.options | ||
|
|
||
| current_options._clear_captured_bodies() | ||
| return current_options | ||
|
|
||
| @staticmethod | ||
| def _restore_response_stream( | ||
| response: httpx.Response, content: bytes, num_bytes_downloaded: int | ||
| ) -> None: | ||
| # aread() caches decoded content and a stateful decoder; discard both when rewinding. | ||
| if hasattr(response, "_content"): | ||
| del response._content | ||
| if hasattr(response, "_decoder"): | ||
| del response._decoder | ||
| response.stream = httpx.ByteStream(content) | ||
| response.is_stream_consumed = False | ||
| response.is_closed = False | ||
| response._num_bytes_downloaded = num_bytes_downloaded | ||
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
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.