|
| 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 | + ) |
0 commit comments