proxy.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. from dataclasses import dataclass
  2. from typing import Literal
  3. import httpx
  4. from core_shared.observability import PARENT_SPAN_ID_HEADER, SPAN_ID_HEADER, TRACE_ID_HEADER
  5. from core_shared.security import build_internal_service_headers
  6. from fastapi import Request, Response
  7. from app.bootstrap.settings import ApiGatewaySettings
  8. from app.infrastructure.audit import mark_gateway_target
  9. from app.infrastructure.request_context import REQUEST_ID_HEADER, get_gateway_request_context
  10. from app.schemas.gateway import DownstreamServiceHealth
  11. ProxyServiceName = Literal[
  12. "workflow-service",
  13. "session-service",
  14. "runtime-service",
  15. "tool-service",
  16. "model-gateway-service",
  17. "code-runner-service",
  18. "agent-service",
  19. "memory-service",
  20. "team-service",
  21. "skill-service",
  22. "human-service",
  23. "knowledge-service",
  24. "event-service",
  25. "auth-service",
  26. "scheduler-service",
  27. ]
  28. @dataclass(frozen=True)
  29. class ProxyTarget:
  30. service_name: ProxyServiceName
  31. base_url: str
  32. path_prefix: str
  33. health_path: str
  34. class ServiceProxy:
  35. def __init__(self, *, settings: ApiGatewaySettings, timeout_seconds: float) -> None:
  36. self.settings = settings
  37. self.timeout_seconds = timeout_seconds
  38. async def forward(
  39. self,
  40. *,
  41. request: Request,
  42. target: ProxyTarget,
  43. path: str) -> Response:
  44. target_url = build_target_url(target=target, path=path)
  45. mark_gateway_target(
  46. request,
  47. target_service=target.service_name,
  48. target_url=target_url)
  49. headers = build_forward_headers(request)
  50. request_context = get_gateway_request_context(request)
  51. headers[REQUEST_ID_HEADER] = request_context.request_id
  52. trace_id = getattr(request.state, "trace_id", None)
  53. span_id = getattr(request.state, "span_id", None)
  54. if isinstance(trace_id, str):
  55. headers[TRACE_ID_HEADER] = trace_id
  56. if isinstance(span_id, str):
  57. headers[PARENT_SPAN_ID_HEADER] = span_id
  58. headers.update(build_internal_service_headers(self.settings))
  59. body = await request.body()
  60. async with httpx.AsyncClient(timeout=self.timeout_seconds) as client:
  61. upstream_response = await client.request(
  62. method=request.method,
  63. url=target_url,
  64. params=request.query_params,
  65. headers=headers,
  66. content=body)
  67. return Response(
  68. content=upstream_response.content,
  69. status_code=upstream_response.status_code,
  70. headers=build_response_headers(upstream_response),
  71. media_type=upstream_response.headers.get("content-type"))
  72. async def check_health(self, target: ProxyTarget) -> DownstreamServiceHealth:
  73. health_url = f"{target.base_url.rstrip('/')}{target.health_path}"
  74. try:
  75. async with httpx.AsyncClient(timeout=self.timeout_seconds) as client:
  76. response = await client.get(
  77. health_url,
  78. headers=build_internal_service_headers(self.settings))
  79. except httpx.HTTPError as exc:
  80. return DownstreamServiceHealth(
  81. service=target.service_name,
  82. status="error",
  83. url=health_url,
  84. error_message=str(exc))
  85. return DownstreamServiceHealth(
  86. service=target.service_name,
  87. status="ok" if response.is_success else "error",
  88. url=health_url,
  89. status_code=response.status_code,
  90. error_message=None if response.is_success else response.text)
  91. def build_target_url(*, target: ProxyTarget, path: str) -> str:
  92. normalized_path = path.strip("/")
  93. if normalized_path:
  94. return f"{target.base_url.rstrip('/')}{target.path_prefix}/{normalized_path}"
  95. return f"{target.base_url.rstrip('/')}{target.path_prefix}"
  96. def build_forward_headers(request: Request) -> dict[str, str]:
  97. skipped_headers = {
  98. "host",
  99. "content-length",
  100. "connection",
  101. REQUEST_ID_HEADER,
  102. "x-internal-service-token",
  103. "x-internal-service-name",
  104. TRACE_ID_HEADER,
  105. SPAN_ID_HEADER,
  106. PARENT_SPAN_ID_HEADER,
  107. }
  108. return {
  109. key: value
  110. for key, value in request.headers.items()
  111. if key.lower() not in skipped_headers
  112. }
  113. def build_response_headers(response: httpx.Response) -> dict[str, str]:
  114. skipped_headers = {"content-length", "transfer-encoding", "connection"}
  115. return {
  116. key: value
  117. for key, value in response.headers.items()
  118. if key.lower() not in skipped_headers
  119. }