proxy.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. from dataclasses import dataclass
  2. from typing import Literal
  3. import httpx
  4. from fastapi import Request, Response
  5. from app.infrastructure.audit import mark_gateway_target
  6. from app.infrastructure.request_context import REQUEST_ID_HEADER, TENANT_ID_HEADER, get_gateway_request_context
  7. from app.schemas.gateway import DownstreamServiceHealth
  8. ProxyServiceName = Literal[
  9. "workflow-service",
  10. "session-service",
  11. "runtime-service",
  12. "tool-service",
  13. "model-gateway-service",
  14. "code-runner-service",
  15. "agent-service",
  16. ]
  17. @dataclass(frozen=True)
  18. class ProxyTarget:
  19. service_name: ProxyServiceName
  20. base_url: str
  21. path_prefix: str
  22. health_path: str
  23. class ServiceProxy:
  24. def __init__(self, *, timeout_seconds: float) -> None:
  25. self.timeout_seconds = timeout_seconds
  26. async def forward(
  27. self,
  28. *,
  29. request: Request,
  30. target: ProxyTarget,
  31. path: str,
  32. ) -> Response:
  33. target_url = build_target_url(target=target, path=path)
  34. mark_gateway_target(
  35. request,
  36. target_service=target.service_name,
  37. target_url=target_url,
  38. )
  39. headers = build_forward_headers(request)
  40. request_context = get_gateway_request_context(request)
  41. headers[REQUEST_ID_HEADER] = request_context.request_id
  42. headers[TENANT_ID_HEADER] = request_context.tenant_id
  43. body = await request.body()
  44. async with httpx.AsyncClient(timeout=self.timeout_seconds) as client:
  45. upstream_response = await client.request(
  46. method=request.method,
  47. url=target_url,
  48. params=request.query_params,
  49. headers=headers,
  50. content=body,
  51. )
  52. return Response(
  53. content=upstream_response.content,
  54. status_code=upstream_response.status_code,
  55. headers=build_response_headers(upstream_response),
  56. media_type=upstream_response.headers.get("content-type"),
  57. )
  58. async def check_health(self, target: ProxyTarget) -> DownstreamServiceHealth:
  59. health_url = f"{target.base_url.rstrip('/')}{target.health_path}"
  60. try:
  61. async with httpx.AsyncClient(timeout=self.timeout_seconds) as client:
  62. response = await client.get(health_url)
  63. except httpx.HTTPError as exc:
  64. return DownstreamServiceHealth(
  65. service=target.service_name,
  66. status="error",
  67. url=health_url,
  68. error_message=str(exc),
  69. )
  70. return DownstreamServiceHealth(
  71. service=target.service_name,
  72. status="ok" if response.is_success else "error",
  73. url=health_url,
  74. status_code=response.status_code,
  75. error_message=None if response.is_success else response.text,
  76. )
  77. def build_target_url(*, target: ProxyTarget, path: str) -> str:
  78. normalized_path = path.strip("/")
  79. if normalized_path:
  80. return f"{target.base_url.rstrip('/')}{target.path_prefix}/{normalized_path}"
  81. return f"{target.base_url.rstrip('/')}{target.path_prefix}"
  82. def build_forward_headers(request: Request) -> dict[str, str]:
  83. skipped_headers = {"host", "content-length", "connection", REQUEST_ID_HEADER, TENANT_ID_HEADER}
  84. return {
  85. key: value
  86. for key, value in request.headers.items()
  87. if key.lower() not in skipped_headers
  88. }
  89. def build_response_headers(response: httpx.Response) -> dict[str, str]:
  90. skipped_headers = {"content-length", "transfer-encoding", "connection"}
  91. return {
  92. key: value
  93. for key, value in response.headers.items()
  94. if key.lower() not in skipped_headers
  95. }