Skip to content

Commit ddba4b4

Browse files
authored
Merge pull request #905 from guru-bharadwaj20/feat/http-compression-handler
feat(http): add a compression handler for request bodies
2 parents 6bcfa8d + ca79728 commit ddba4b4

5 files changed

Lines changed: 436 additions & 0 deletions

File tree

‎packages/http/httpx/kiota_http/middleware/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from .async_kiota_transport import AsyncKiotaTransport
22
from .body_inspection_handler import BodyInspectionHandler
3+
from .compression_handler import CompressionHandler
34
from .headers_inspection_handler import HeadersInspectionHandler
45
from .middleware import PARENT_SPAN_KEY, REQUEST_OPTIONS_KEY, BaseMiddleware, MiddlewarePipeline
56
from .parameters_name_decoding_handler import ParametersNameDecodingHandler
@@ -11,6 +12,7 @@
1112
__all__ = [
1213
"AsyncKiotaTransport",
1314
"BodyInspectionHandler",
15+
"CompressionHandler",
1416
"HeadersInspectionHandler",
1517
"PARENT_SPAN_KEY",
1618
"REQUEST_OPTIONS_KEY",
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import asyncio
2+
import gzip
3+
from typing import Optional
4+
5+
from opentelemetry.semconv.attributes.http_attributes import HTTP_RESPONSE_STATUS_CODE
6+
7+
import httpx
8+
9+
from .middleware import REQUEST_OPTIONS_KEY, BaseMiddleware
10+
from .options import CompressionHandlerOption
11+
12+
COMPRESSION_ENABLE_KEY = "com.microsoft.kiota.handler.compression.enable"
13+
REQUEST_BODY_COMPRESSED_KEY = "http.request.body.compressed"
14+
REQUEST_BODY_SIZE_KEY = "http.request.body.size"
15+
16+
17+
class CompressionHandler(BaseMiddleware):
18+
"""Middleware that gzip compresses request bodies.
19+
20+
If the server answers a compressed request with 415 Unsupported Media Type, the
21+
request is sent once more with the original, uncompressed body.
22+
23+
The handler is not part of the default middleware. Add it before the RetryHandler
24+
so a retried request is not compressed again.
25+
"""
26+
27+
CONTENT_ENCODING_HEADER = "Content-Encoding"
28+
CONTENT_RANGE_HEADER = "Content-Range"
29+
CONTENT_LENGTH_HEADER = "Content-Length"
30+
TRANSFER_ENCODING_HEADER = "Transfer-Encoding"
31+
UNSUPPORTED_MEDIA_TYPE = 415
32+
33+
def __init__(self, options: Optional[CompressionHandlerOption] = None) -> None:
34+
"""Create an instance of CompressionHandler
35+
36+
Args:
37+
options (CompressionHandlerOption, optional): The compression options to
38+
use. A new CompressionHandlerOption is created when not provided.
39+
"""
40+
super().__init__()
41+
self.options = options if options is not None else CompressionHandlerOption()
42+
43+
async def send(
44+
self, request: httpx.Request, transport: httpx.AsyncBaseTransport
45+
) -> httpx.Response:
46+
"""To execute the current middleware
47+
48+
Args:
49+
request (httpx.Request): The prepared request object
50+
transport(httpx.AsyncBaseTransport): The HTTP transport to use
51+
52+
Returns:
53+
Response: The response object.
54+
"""
55+
if request is None:
56+
raise TypeError("request cannot be null")
57+
_enable_span = self._create_observability_span(request, "CompressionHandler_send")
58+
try:
59+
current_options = self._get_current_options(request)
60+
_enable_span.set_attribute(COMPRESSION_ENABLE_KEY, current_options.enable_compression)
61+
if not current_options.enable_compression or not self._can_compress(request):
62+
return await super().send(request, transport)
63+
64+
body = await request.aread()
65+
if not body:
66+
return await super().send(request, transport)
67+
68+
# gzip is CPU bound, compress in a worker thread so large bodies do not
69+
# block the event loop
70+
compressed_body = await asyncio.to_thread(gzip.compress, body)
71+
compressed_request = self._build_compressed_request(request, compressed_body)
72+
_enable_span.set_attribute(REQUEST_BODY_COMPRESSED_KEY, True)
73+
_enable_span.set_attribute(REQUEST_BODY_SIZE_KEY, len(compressed_request.content))
74+
response = await super().send(compressed_request, transport)
75+
if response.status_code != self.UNSUPPORTED_MEDIA_TYPE:
76+
return response
77+
78+
# The server does not accept compressed bodies, send the original request
79+
await response.aclose()
80+
_enable_span.set_attribute(HTTP_RESPONSE_STATUS_CODE, response.status_code)
81+
_enable_span.set_attribute(REQUEST_BODY_COMPRESSED_KEY, False)
82+
_enable_span.set_attribute(REQUEST_BODY_SIZE_KEY, len(body))
83+
return await super().send(request, transport)
84+
except Exception as exc:
85+
_enable_span.record_exception(exc)
86+
raise
87+
finally:
88+
_enable_span.end()
89+
90+
def _get_current_options(self, request: httpx.Request) -> CompressionHandlerOption:
91+
"""Returns the options to use for the request. The request options take
92+
precedence over the handler options.
93+
94+
Args:
95+
request (httpx.Request): The prepared request object
96+
97+
Returns:
98+
CompressionHandlerOption: The options to be used.
99+
"""
100+
request_options = request.extensions.get(REQUEST_OPTIONS_KEY)
101+
if request_options:
102+
current_options: CompressionHandlerOption = request_options.get(
103+
CompressionHandlerOption.get_key(), self.options
104+
)
105+
return current_options
106+
return self.options
107+
108+
def _can_compress(self, request: httpx.Request) -> bool:
109+
"""Checks the request headers to decide whether the body can be compressed.
110+
Bodies that are already encoded, and partial bodies sent with a bytes
111+
Content-Range, are sent as they are.
112+
"""
113+
if self.CONTENT_ENCODING_HEADER in request.headers:
114+
return False
115+
content_range = request.headers.get(self.CONTENT_RANGE_HEADER)
116+
if content_range is not None and "bytes" in content_range.lower():
117+
return False
118+
return True
119+
120+
def _build_compressed_request(self, request: httpx.Request, body: bytes) -> httpx.Request:
121+
"""Creates a copy of the request with a gzip compressed body.
122+
The original request is left untouched so it can be sent again uncompressed.
123+
"""
124+
headers = request.headers.copy()
125+
headers.pop(self.TRANSFER_ENCODING_HEADER, None)
126+
headers[self.CONTENT_ENCODING_HEADER] = "gzip"
127+
headers[self.CONTENT_LENGTH_HEADER] = str(len(body))
128+
return httpx.Request(
129+
method=request.method,
130+
url=request.url,
131+
headers=headers,
132+
content=body,
133+
extensions=request.extensions.copy(),
134+
)

‎packages/http/httpx/kiota_http/middleware/options/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from .body_inspection_handler_option import BodyInspectionHandlerOption
2+
from .compression_handler_option import CompressionHandlerOption
23
from .headers_inspection_handler_option import HeadersInspectionHandlerOption
34
from .parameters_name_decoding_handler_option import ParametersNameDecodingHandlerOption
45
from .redirect_handler_option import RedirectHandlerOption
@@ -10,6 +11,7 @@
1011

1112
__all__ = [
1213
"BodyInspectionHandlerOption",
14+
"CompressionHandlerOption",
1315
"HeadersInspectionHandlerOption",
1416
"ParametersNameDecodingHandlerOption",
1517
"RedirectHandlerOption",
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from kiota_abstractions.request_option import RequestOption
2+
3+
4+
class CompressionHandlerOption(RequestOption):
5+
"""Config options for the CompressionHandler
6+
"""
7+
8+
COMPRESSION_HANDLER_OPTION_KEY = "CompressionHandlerOption"
9+
10+
def __init__(self, enable_compression: bool = True) -> None:
11+
"""Creates an instance of the compression handler option.
12+
13+
Args:
14+
enable_compression (bool, optional): Whether to gzip request bodies.
15+
Defaults to True.
16+
"""
17+
self._enable_compression = enable_compression
18+
19+
@property
20+
def enable_compression(self) -> bool:
21+
"""Whether request bodies are gzip compressed"""
22+
return self._enable_compression
23+
24+
@enable_compression.setter
25+
def enable_compression(self, value: bool) -> None:
26+
self._enable_compression = value
27+
28+
@staticmethod
29+
def get_key() -> str:
30+
return CompressionHandlerOption.COMPRESSION_HANDLER_OPTION_KEY

0 commit comments

Comments
 (0)