|
| 1 | +from aws_xray_sdk.core import AWSXRayRecorder, xray_recorder |
| 2 | +from aws_xray_sdk.core.lambda_launcher import check_in_lambda |
| 3 | +from aws_xray_sdk.core.models import http |
| 4 | +from aws_xray_sdk.core.models.segment import Segment |
| 5 | +from aws_xray_sdk.core.utils import stacktrace |
| 6 | +from aws_xray_sdk.ext.util import construct_xray_header, prepare_response_header |
| 7 | +from chocs import HttpRequest, HttpResponse, HttpStatus |
| 8 | +from chocs.errors import HttpError |
| 9 | +from chocs.middleware import Middleware, MiddlewareHandler |
| 10 | +from typing import Callable |
| 11 | + |
| 12 | +__all__ = ["AwsXRayMiddleware"] |
| 13 | + |
| 14 | + |
| 15 | +ErrorHandler = Callable[[HttpRequest, Exception, Segment], HttpResponse] |
| 16 | +SegmentHandler = Callable[[HttpRequest, Segment], None] |
| 17 | + |
| 18 | + |
| 19 | +def default_error_handler( |
| 20 | + request: HttpRequest, error: Exception, segment: Segment |
| 21 | +) -> HttpResponse: |
| 22 | + |
| 23 | + stack = stacktrace.get_stacktrace(limit=10) |
| 24 | + segment.add_exception(error, stack) |
| 25 | + |
| 26 | + if isinstance(error, HttpError): |
| 27 | + response = HttpResponse(error.http_message, error.status_code) |
| 28 | + else: |
| 29 | + response = HttpResponse("Server Error", HttpStatus.INTERNAL_SERVER_ERROR) |
| 30 | + |
| 31 | + return response |
| 32 | + |
| 33 | + |
| 34 | +class AwsXRayMiddleware(Middleware): |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + recorder: AWSXRayRecorder = None, |
| 38 | + error_handler: ErrorHandler = default_error_handler, |
| 39 | + segment_handler: SegmentHandler = None, |
| 40 | + ): |
| 41 | + """ |
| 42 | +
|
| 43 | + :param recorder: |
| 44 | + :param error_handler: A callable that will be used if any error occurs during application execution |
| 45 | + :param segment_handler: A callable that will be used to provide extra information for x-ray segment |
| 46 | + """ |
| 47 | + |
| 48 | + self._recorder = recorder if recorder is not None else xray_recorder |
| 49 | + self._error_handler = error_handler |
| 50 | + self._segment_handler = segment_handler |
| 51 | + |
| 52 | + def __deepcopy__(self, memo): |
| 53 | + # Handle issue with deepcopying middleware when generating the MiddlewarePipeline for the application. |
| 54 | + # Since `xray_recorder` is globally instanciated, we can handle it separately to other attributes when |
| 55 | + # handling the deepcopy. This fix will work for cases where no custom recorder is used, however if one |
| 56 | + # does want to use a custom recorder, they may need to handle their own deepcopy pickling. |
| 57 | + |
| 58 | + return AwsXRayMiddleware( |
| 59 | + self._recorder, self._error_handler, self._segment_handler |
| 60 | + ) |
| 61 | + |
| 62 | + def handle(self, request: HttpRequest, next: MiddlewareHandler) -> HttpResponse: |
| 63 | + # If we are not in lambda environment just ignore the middleware |
| 64 | + if not check_in_lambda(): |
| 65 | + return next(request) |
| 66 | + |
| 67 | + # There is some malfunction, so lets ignore it. |
| 68 | + if "__handler__" not in request.attributes: |
| 69 | + return next(request) |
| 70 | + |
| 71 | + lambda_handler = request.attributes["__handler__"] |
| 72 | + |
| 73 | + # Get the name of the handler function to use as the segment name. |
| 74 | + segment_name = lambda_handler.__name__ |
| 75 | + |
| 76 | + # Extract x-ray trace header from inbound request headers. Used by AWS internally to track |
| 77 | + # request/response cycle. When locally testing, the `aws_event` flag is not set on the request |
| 78 | + # attributes. In this case we fallback to the requests headers. |
| 79 | + xray_header = construct_xray_header( |
| 80 | + request.attributes.get("aws_event", {}).get("headers", request.headers) |
| 81 | + ) |
| 82 | + |
| 83 | + # Start subsegment for x-ray recording. We are in a lambda so we will always have a parent segment. |
| 84 | + segment = self._recorder.begin_subsegment(segment_name) |
| 85 | + |
| 86 | + request.attributes["aws_xray_recorder"] = self._recorder |
| 87 | + |
| 88 | + # Save x-ray trace header information to the current subsegment. |
| 89 | + segment.save_origin_trace_header(xray_header) |
| 90 | + |
| 91 | + # Add request metadata to x-ray segment. |
| 92 | + segment.put_http_meta(http.METHOD, str(request.method)) |
| 93 | + segment.put_http_meta( |
| 94 | + http.URL, |
| 95 | + str(request.path) |
| 96 | + + ("?" + str(request.query_string) if request.query_string else ""), |
| 97 | + ) |
| 98 | + |
| 99 | + # Allow to append extra metadata to x-ray segment. |
| 100 | + if self._segment_handler: |
| 101 | + self._segment_handler(request, segment) |
| 102 | + |
| 103 | + try: |
| 104 | + response = next(request) |
| 105 | + except Exception as error: |
| 106 | + response = self._error_handler(request, error, segment) |
| 107 | + |
| 108 | + # Add the xray header from the inbound request to the response. Needed for AWS to keep track of the |
| 109 | + # request/response cycle internally in x-ray. |
| 110 | + response.headers[http.XRAY_HEADER] = prepare_response_header( |
| 111 | + xray_header, segment |
| 112 | + ) |
| 113 | + segment.put_http_meta(http.STATUS, int(response.status_code)) |
| 114 | + |
| 115 | + self._recorder.end_subsegment() |
| 116 | + |
| 117 | + return response |
0 commit comments