proxy.py 3.8 KB

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