proxy.py 4.6 KB

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