|
9 | 9 | Copyright (c) 2018 Sebastián Ramírez |
10 | 10 | """ |
11 | 11 |
|
12 | | -from fastapi import HTTPException # noqa: E402 |
| 12 | +from collections.abc import Coroutine, Callable # noqa: E402 |
| 13 | +from fastapi import HTTPException, Request, Response # noqa: E402 |
| 14 | +from typing import Any # noqa: E402 |
| 15 | +from fastapi.responses import JSONResponse # noqa: E402 |
13 | 16 | from fastapi.routing import APIRoute # noqa: E402 |
| 17 | +from karapace.api.content_type import negotiate_schema_content_type, SCHEMA_RESPONSE_DEFAULT_CONTENT_TYPE # noqa: E402 |
14 | 18 | from starlette.routing import Match # noqa: E402 |
15 | 19 | from starlette.types import Scope # noqa: E402 |
16 | 20 |
|
@@ -42,3 +46,39 @@ def matches(self, scope: Scope) -> tuple[Match, Scope]: |
42 | 46 | new_path = re.sub(r"\?.*", "", raw_path) |
43 | 47 | scope["path"] = new_path |
44 | 48 | return super().matches(scope) |
| 49 | + |
| 50 | + |
| 51 | +class SchemaRegistryRoute(RawPathRoute): |
| 52 | + """Route class for schema-registry endpoints that require content negotiation. |
| 53 | +
|
| 54 | + Validates Accept and Content-Type headers before any dependency injection or |
| 55 | + body parsing occurs. Returns 406/415 errors immediately for invalid headers, |
| 56 | + and sets the negotiated Content-Type on successful responses. |
| 57 | + """ |
| 58 | + |
| 59 | + def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: |
| 60 | + original_handler = super().get_route_handler() |
| 61 | + |
| 62 | + async def schema_content_handler(request: Request) -> Response: |
| 63 | + try: |
| 64 | + response_content_type = negotiate_schema_content_type(request) |
| 65 | + except HTTPException as exc: |
| 66 | + return JSONResponse( |
| 67 | + status_code=exc.status_code, |
| 68 | + content=exc.detail, |
| 69 | + headers={"Content-Type": SCHEMA_RESPONSE_DEFAULT_CONTENT_TYPE}, |
| 70 | + ) |
| 71 | + |
| 72 | + if request.headers.get("Content-Type") == "application/octet-stream": |
| 73 | + new_headers = request.headers.mutablecopy() |
| 74 | + new_headers["Content-Type"] = "application/json" |
| 75 | + request._headers = new_headers |
| 76 | + request.scope.update(headers=request.headers.raw) |
| 77 | + |
| 78 | + request.state.schema_response_content_type = response_content_type |
| 79 | + |
| 80 | + response = await original_handler(request) |
| 81 | + response.headers["Content-Type"] = response_content_type |
| 82 | + return response |
| 83 | + |
| 84 | + return schema_content_handler |
0 commit comments