proxy.py 3.7 KB

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