routes.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import asyncio
  2. from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
  3. from sqlalchemy import text
  4. from sqlalchemy.orm import Session
  5. from core_domain import ServiceDescriptor, ServiceHealth
  6. from app.bootstrap.settings import ApiGatewaySettings
  7. from app.db.session import get_db
  8. from app.domain.repositories import ApiKeyRepository, GatewayRequestAuditRepository
  9. from app.infrastructure.api_keys import generate_api_key, get_api_key_prefix, hash_api_key
  10. from app.infrastructure.proxy import ProxyServiceName, ProxyTarget, ServiceProxy
  11. from app.schemas.gateway import (
  12. ApiKeyCreateRequest,
  13. ApiKeyCreateResponse,
  14. ApiKeyResponse,
  15. ApiKeyStatusUpdateRequest,
  16. GatewayRequestAuditResponse,
  17. GatewayServicesHealthResponse,
  18. )
  19. router = APIRouter()
  20. @router.get("/health", response_model=ServiceDescriptor)
  21. def health_check(db: Session = Depends(get_db)) -> ServiceDescriptor:
  22. db.execute(text("SELECT 1"))
  23. return ServiceDescriptor(name="api-gateway")
  24. @router.get("/ready", response_model=ServiceHealth)
  25. def readiness_check(db: Session = Depends(get_db)) -> ServiceHealth:
  26. db.execute(text("SELECT 1"))
  27. return ServiceHealth(service="api-gateway", status="ok", database="ok")
  28. @router.post("/gateway/api-keys", response_model=ApiKeyCreateResponse)
  29. def create_api_key(
  30. payload: ApiKeyCreateRequest,
  31. db: Session = Depends(get_db),
  32. ) -> ApiKeyCreateResponse:
  33. api_key = generate_api_key()
  34. entity = ApiKeyRepository(db).create(
  35. tenant_id=payload.tenant_id,
  36. name=payload.name,
  37. key_prefix=get_api_key_prefix(api_key),
  38. key_hash=hash_api_key(api_key),
  39. scopes=payload.scopes,
  40. expires_time=payload.expires_time,
  41. )
  42. return ApiKeyCreateResponse(
  43. id=entity.id,
  44. tenant_id=entity.tenant_id,
  45. name=entity.name,
  46. key_prefix=entity.key_prefix,
  47. api_key=api_key,
  48. status=entity.status,
  49. scopes=entity.scopes,
  50. expires_time=entity.expires_time,
  51. created_time=entity.created_time,
  52. )
  53. @router.get("/gateway/api-keys", response_model=list[ApiKeyResponse])
  54. def list_api_keys(
  55. tenant_id: str = Query(...),
  56. db: Session = Depends(get_db),
  57. ) -> list[ApiKeyResponse]:
  58. return [
  59. ApiKeyResponse.from_entity(item)
  60. for item in ApiKeyRepository(db).list_by_tenant(tenant_id=tenant_id)
  61. ]
  62. @router.patch("/gateway/api-keys/{api_key_id}/status", response_model=ApiKeyResponse)
  63. def update_api_key_status(
  64. api_key_id: str,
  65. payload: ApiKeyStatusUpdateRequest,
  66. db: Session = Depends(get_db),
  67. ) -> ApiKeyResponse:
  68. entity = ApiKeyRepository(db).update_status(
  69. tenant_id=payload.tenant_id,
  70. api_key_id=api_key_id,
  71. status=payload.status,
  72. )
  73. if entity is None:
  74. raise HTTPException(status_code=404, detail=f"api key not found: {api_key_id}")
  75. return ApiKeyResponse.from_entity(entity)
  76. @router.get("/gateway/audits", response_model=list[GatewayRequestAuditResponse])
  77. def list_gateway_audits(
  78. tenant_id: str = Query(...),
  79. request_id: str | None = Query(default=None),
  80. target_service: str | None = Query(default=None),
  81. limit: int = Query(default=100, ge=1, le=500),
  82. db: Session = Depends(get_db),
  83. ) -> list[GatewayRequestAuditResponse]:
  84. items = GatewayRequestAuditRepository(db).list_by_scope(
  85. tenant_id=tenant_id,
  86. request_id=request_id,
  87. target_service=target_service,
  88. limit=limit,
  89. )
  90. return [GatewayRequestAuditResponse.from_entity(item) for item in items]
  91. def get_gateway_settings() -> ApiGatewaySettings:
  92. return ApiGatewaySettings()
  93. def get_service_proxy(settings: ApiGatewaySettings = Depends(get_gateway_settings)) -> ServiceProxy:
  94. return ServiceProxy(timeout_seconds=settings.proxy_timeout_seconds)
  95. def build_proxy_targets(settings: ApiGatewaySettings) -> dict[ProxyServiceName, ProxyTarget]:
  96. return {
  97. "workflow-service": ProxyTarget(
  98. service_name="workflow-service",
  99. base_url=settings.workflow_service_url,
  100. path_prefix="/workflows",
  101. health_path="/workflows/health",
  102. ),
  103. "session-service": ProxyTarget(
  104. service_name="session-service",
  105. base_url=settings.session_service_url,
  106. path_prefix="/sessions",
  107. health_path="/sessions/health",
  108. ),
  109. "runtime-service": ProxyTarget(
  110. service_name="runtime-service",
  111. base_url=settings.runtime_service_url,
  112. path_prefix="/runtime",
  113. health_path="/runtime/health",
  114. ),
  115. "tool-service": ProxyTarget(
  116. service_name="tool-service",
  117. base_url=settings.tool_service_url,
  118. path_prefix="/tools",
  119. health_path="/tools/health",
  120. ),
  121. "model-gateway-service": ProxyTarget(
  122. service_name="model-gateway-service",
  123. base_url=settings.model_gateway_service_url,
  124. path_prefix="/models",
  125. health_path="/models/health",
  126. ),
  127. "code-runner-service": ProxyTarget(
  128. service_name="code-runner-service",
  129. base_url=settings.code_runner_service_url,
  130. path_prefix="/code",
  131. health_path="/code/health",
  132. ),
  133. "agent-service": ProxyTarget(
  134. service_name="agent-service",
  135. base_url=settings.agent_service_url,
  136. path_prefix="/agents",
  137. health_path="/agents/health",
  138. ),
  139. }
  140. @router.get("/gateway/services/health", response_model=GatewayServicesHealthResponse)
  141. async def downstream_health_check(
  142. settings: ApiGatewaySettings = Depends(get_gateway_settings),
  143. ) -> GatewayServicesHealthResponse:
  144. targets = build_proxy_targets(settings)
  145. health_proxy = ServiceProxy(timeout_seconds=settings.downstream_health_timeout_seconds)
  146. downstream_services = await asyncio.gather(
  147. *[health_proxy.check_health(target) for target in targets.values()]
  148. )
  149. status = "ok" if all(item.status == "ok" for item in downstream_services) else "degraded"
  150. return GatewayServicesHealthResponse(
  151. status=status,
  152. downstream_services=downstream_services,
  153. )
  154. @router.api_route(
  155. "/gateway/workflows",
  156. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  157. )
  158. @router.api_route(
  159. "/gateway/workflows/{path:path}",
  160. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  161. )
  162. async def proxy_workflow_service(
  163. request: Request,
  164. path: str = "",
  165. settings: ApiGatewaySettings = Depends(get_gateway_settings),
  166. proxy: ServiceProxy = Depends(get_service_proxy),
  167. ) -> Response:
  168. return await proxy.forward(
  169. request=request,
  170. target=build_proxy_targets(settings)["workflow-service"],
  171. path=path,
  172. )
  173. @router.api_route(
  174. "/gateway/sessions",
  175. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  176. )
  177. @router.api_route(
  178. "/gateway/sessions/{path:path}",
  179. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  180. )
  181. async def proxy_session_service(
  182. request: Request,
  183. path: str = "",
  184. settings: ApiGatewaySettings = Depends(get_gateway_settings),
  185. proxy: ServiceProxy = Depends(get_service_proxy),
  186. ) -> Response:
  187. return await proxy.forward(
  188. request=request,
  189. target=build_proxy_targets(settings)["session-service"],
  190. path=path,
  191. )
  192. @router.api_route(
  193. "/gateway/runtime",
  194. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  195. )
  196. @router.api_route(
  197. "/gateway/runtime/{path:path}",
  198. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  199. )
  200. async def proxy_runtime_service(
  201. request: Request,
  202. path: str = "",
  203. settings: ApiGatewaySettings = Depends(get_gateway_settings),
  204. proxy: ServiceProxy = Depends(get_service_proxy),
  205. ) -> Response:
  206. return await proxy.forward(
  207. request=request,
  208. target=build_proxy_targets(settings)["runtime-service"],
  209. path=path,
  210. )
  211. @router.api_route(
  212. "/gateway/agents",
  213. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  214. )
  215. @router.api_route(
  216. "/gateway/agents/{path:path}",
  217. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  218. )
  219. async def proxy_agent_service(
  220. request: Request,
  221. path: str = "",
  222. settings: ApiGatewaySettings = Depends(get_gateway_settings),
  223. proxy: ServiceProxy = Depends(get_service_proxy),
  224. ) -> Response:
  225. return await proxy.forward(
  226. request=request,
  227. target=build_proxy_targets(settings)["agent-service"],
  228. path=path,
  229. )
  230. @router.api_route(
  231. "/gateway/tools",
  232. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  233. )
  234. @router.api_route(
  235. "/gateway/tools/{path:path}",
  236. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  237. )
  238. async def proxy_tool_service(
  239. request: Request,
  240. path: str = "",
  241. settings: ApiGatewaySettings = Depends(get_gateway_settings),
  242. proxy: ServiceProxy = Depends(get_service_proxy),
  243. ) -> Response:
  244. return await proxy.forward(
  245. request=request,
  246. target=build_proxy_targets(settings)["tool-service"],
  247. path=path,
  248. )
  249. @router.api_route(
  250. "/gateway/models",
  251. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  252. )
  253. @router.api_route(
  254. "/gateway/models/{path:path}",
  255. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  256. )
  257. async def proxy_model_gateway_service(
  258. request: Request,
  259. path: str = "",
  260. settings: ApiGatewaySettings = Depends(get_gateway_settings),
  261. proxy: ServiceProxy = Depends(get_service_proxy),
  262. ) -> Response:
  263. return await proxy.forward(
  264. request=request,
  265. target=build_proxy_targets(settings)["model-gateway-service"],
  266. path=path,
  267. )
  268. @router.api_route(
  269. "/gateway/code",
  270. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  271. )
  272. @router.api_route(
  273. "/gateway/code/{path:path}",
  274. methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
  275. )
  276. async def proxy_code_runner_service(
  277. request: Request,
  278. path: str = "",
  279. settings: ApiGatewaySettings = Depends(get_gateway_settings),
  280. proxy: ServiceProxy = Depends(get_service_proxy),
  281. ) -> Response:
  282. return await proxy.forward(
  283. request=request,
  284. target=build_proxy_targets(settings)["code-runner-service"],
  285. path=path,
  286. )