proxy.py 3.7 KB

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