routes.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. from fastapi import APIRouter, Depends, HTTPException, Query
  2. from sqlalchemy import text
  3. from sqlalchemy.orm import Session
  4. from core_domain import ServiceHealth
  5. from app.application.services import RuntimeApplicationService, build_runtime_application_service
  6. from app.bootstrap.settings import RuntimeServiceSettings
  7. from app.db.session import get_db
  8. from app.infrastructure.code_runner_client import CodeRunnerClientError
  9. from app.infrastructure.human_client import HumanServiceClientError
  10. from app.infrastructure.model_gateway_client import ModelGatewayClientError
  11. from app.infrastructure.tool_client import ToolServiceClientError
  12. from app.infrastructure.workflow_client import WorkflowServiceClientError
  13. from app.schemas.run import (
  14. ExecutionLogResponse,
  15. HumanNodeResumeRequest,
  16. NodeArtifactResponse,
  17. NodeRunExecuteRequest,
  18. NodeRunExecuteResponse,
  19. NodeRunResponse,
  20. NodeRunStatusUpdateRequest,
  21. RunBootstrapResponse,
  22. RunCreateRequest,
  23. RunExecuteRequest,
  24. RunExecuteResponse,
  25. TraceSpanResponse,
  26. WorkerExecuteNextRequest,
  27. WorkerExecuteNextResponse,
  28. WorkflowRunResponse,
  29. WorkflowRunStatusUpdateRequest,
  30. )
  31. router = APIRouter()
  32. def get_runtime_settings() -> RuntimeServiceSettings:
  33. return RuntimeServiceSettings()
  34. def get_runtime_application_service(
  35. db: Session = Depends(get_db),
  36. settings: RuntimeServiceSettings = Depends(get_runtime_settings),
  37. ) -> RuntimeApplicationService:
  38. return build_runtime_application_service(db=db, settings=settings)
  39. @router.get("/health", response_model=ServiceHealth)
  40. def health_check(db: Session = Depends(get_db)) -> ServiceHealth:
  41. db.execute(text("SELECT 1"))
  42. return ServiceHealth(service="runtime-service", status="ok", database="ok")
  43. @router.post("/runs", response_model=RunBootstrapResponse)
  44. def create_run(
  45. payload: RunCreateRequest,
  46. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  47. ) -> RunBootstrapResponse:
  48. try:
  49. workflow_run, initial_node = service.create_run(payload)
  50. except (
  51. CodeRunnerClientError,
  52. ModelGatewayClientError,
  53. HumanServiceClientError,
  54. ToolServiceClientError,
  55. WorkflowServiceClientError,
  56. ) as exc:
  57. raise HTTPException(status_code=502, detail=str(exc)) from exc
  58. return RunBootstrapResponse(
  59. run=WorkflowRunResponse.from_entity(workflow_run),
  60. initial_node=NodeRunResponse.from_entity(initial_node) if initial_node else None,
  61. )
  62. @router.get("/runs", response_model=list[WorkflowRunResponse])
  63. def list_runs(
  64. tenant_id: str = Query(...),
  65. session_id: str | None = Query(default=None),
  66. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  67. ) -> list[WorkflowRunResponse]:
  68. return [
  69. WorkflowRunResponse.from_entity(item)
  70. for item in service.list_runs(tenant_id=tenant_id, session_id=session_id)
  71. ]
  72. @router.get("/node-runs", response_model=list[NodeRunResponse])
  73. def list_node_runs(
  74. tenant_id: str = Query(...),
  75. run_id: str = Query(...),
  76. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  77. ) -> list[NodeRunResponse]:
  78. return [
  79. NodeRunResponse.from_entity(item)
  80. for item in service.list_node_runs(tenant_id=tenant_id, run_id=run_id)
  81. ]
  82. @router.get("/execution-logs", response_model=list[ExecutionLogResponse])
  83. def list_execution_logs(
  84. tenant_id: str = Query(...),
  85. run_id: str | None = Query(default=None),
  86. node_run_id: str | None = Query(default=None),
  87. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  88. ) -> list[ExecutionLogResponse]:
  89. return [
  90. ExecutionLogResponse.from_entity(item)
  91. for item in service.list_execution_logs(
  92. tenant_id=tenant_id,
  93. run_id=run_id,
  94. node_run_id=node_run_id,
  95. )
  96. ]
  97. @router.get("/node-artifacts", response_model=list[NodeArtifactResponse])
  98. def list_node_artifacts(
  99. tenant_id: str = Query(...),
  100. run_id: str | None = Query(default=None),
  101. node_run_id: str | None = Query(default=None),
  102. artifact_type: str | None = Query(default=None),
  103. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  104. ) -> list[NodeArtifactResponse]:
  105. return [
  106. NodeArtifactResponse.from_entity(item)
  107. for item in service.list_node_artifacts(
  108. tenant_id=tenant_id,
  109. run_id=run_id,
  110. node_run_id=node_run_id,
  111. artifact_type=artifact_type,
  112. )
  113. ]
  114. @router.get("/trace-spans", response_model=list[TraceSpanResponse])
  115. def list_trace_spans(
  116. tenant_id: str = Query(...),
  117. run_id: str | None = Query(default=None),
  118. node_run_id: str | None = Query(default=None),
  119. span_type: str | None = Query(default=None),
  120. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  121. ) -> list[TraceSpanResponse]:
  122. return [
  123. TraceSpanResponse.from_entity(item)
  124. for item in service.list_trace_spans(
  125. tenant_id=tenant_id,
  126. run_id=run_id,
  127. node_run_id=node_run_id,
  128. span_type=span_type,
  129. )
  130. ]
  131. @router.post("/runs/{run_id}/status", response_model=WorkflowRunResponse)
  132. def update_run_status(
  133. run_id: str,
  134. payload: WorkflowRunStatusUpdateRequest,
  135. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  136. ) -> WorkflowRunResponse:
  137. entity = service.update_run_status(run_id=run_id, payload=payload)
  138. if entity is None:
  139. raise HTTPException(status_code=404, detail=f"workflow_run not found: {run_id}")
  140. return WorkflowRunResponse.from_entity(entity)
  141. @router.post("/node-runs/{node_run_id}/status", response_model=NodeRunResponse)
  142. def update_node_run_status(
  143. node_run_id: str,
  144. payload: NodeRunStatusUpdateRequest,
  145. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  146. ) -> NodeRunResponse:
  147. entity = service.update_node_run_status(node_run_id=node_run_id, payload=payload)
  148. if entity is None:
  149. raise HTTPException(status_code=404, detail=f"node_run not found: {node_run_id}")
  150. return NodeRunResponse.from_entity(entity)
  151. @router.post("/node-runs/{node_run_id}/execute", response_model=NodeRunExecuteResponse)
  152. def execute_node_run(
  153. node_run_id: str,
  154. payload: NodeRunExecuteRequest,
  155. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  156. ) -> NodeRunExecuteResponse:
  157. try:
  158. result = service.execute_node_run(node_run_id=node_run_id, payload=payload)
  159. except (
  160. CodeRunnerClientError,
  161. ModelGatewayClientError,
  162. HumanServiceClientError,
  163. ToolServiceClientError,
  164. WorkflowServiceClientError,
  165. ) as exc:
  166. raise HTTPException(status_code=502, detail=str(exc)) from exc
  167. if result is None:
  168. raise HTTPException(status_code=404, detail=f"node_run not found: {node_run_id}")
  169. workflow_run, node_run, executor_name = result
  170. return NodeRunExecuteResponse(
  171. run=WorkflowRunResponse.from_entity(workflow_run),
  172. node_run=NodeRunResponse.from_entity(node_run),
  173. executor_name=executor_name,
  174. )
  175. @router.post("/runs/{run_id}/execute-next", response_model=NodeRunExecuteResponse)
  176. def execute_next_node_run(
  177. run_id: str,
  178. payload: NodeRunExecuteRequest,
  179. tenant_id: str = Query(...),
  180. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  181. ) -> NodeRunExecuteResponse:
  182. try:
  183. result = service.execute_next_node_run(
  184. tenant_id=tenant_id,
  185. run_id=run_id,
  186. payload=payload,
  187. )
  188. except (
  189. CodeRunnerClientError,
  190. ModelGatewayClientError,
  191. HumanServiceClientError,
  192. ToolServiceClientError,
  193. WorkflowServiceClientError,
  194. ) as exc:
  195. raise HTTPException(status_code=502, detail=str(exc)) from exc
  196. if result is None:
  197. raise HTTPException(status_code=404, detail=f"queued node_run not found for run: {run_id}")
  198. workflow_run, node_run, executor_name = result
  199. return NodeRunExecuteResponse(
  200. run=WorkflowRunResponse.from_entity(workflow_run),
  201. node_run=NodeRunResponse.from_entity(node_run),
  202. executor_name=executor_name,
  203. )
  204. @router.post("/runs/{run_id}/execute", response_model=RunExecuteResponse)
  205. def execute_run(
  206. run_id: str,
  207. payload: RunExecuteRequest,
  208. tenant_id: str = Query(...),
  209. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  210. ) -> RunExecuteResponse:
  211. try:
  212. result = service.execute_run(
  213. tenant_id=tenant_id,
  214. run_id=run_id,
  215. payload=payload,
  216. )
  217. except (
  218. CodeRunnerClientError,
  219. ModelGatewayClientError,
  220. HumanServiceClientError,
  221. ToolServiceClientError,
  222. WorkflowServiceClientError,
  223. ) as exc:
  224. raise HTTPException(status_code=502, detail=str(exc)) from exc
  225. if result is None:
  226. raise HTTPException(status_code=404, detail=f"workflow_run not found: {run_id}")
  227. workflow_run, node_runs, executor_names = result
  228. return RunExecuteResponse(
  229. run=WorkflowRunResponse.from_entity(workflow_run),
  230. node_runs=[NodeRunResponse.from_entity(item) for item in node_runs],
  231. executor_names=executor_names,
  232. )
  233. @router.post("/node-runs/{node_run_id}/resume-human", response_model=NodeRunExecuteResponse)
  234. def resume_human_node_run(
  235. node_run_id: str,
  236. payload: HumanNodeResumeRequest,
  237. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  238. ) -> NodeRunExecuteResponse:
  239. try:
  240. result = service.resume_human_node_run(
  241. node_run_id=node_run_id,
  242. payload=payload,
  243. )
  244. except (
  245. CodeRunnerClientError,
  246. ModelGatewayClientError,
  247. HumanServiceClientError,
  248. ToolServiceClientError,
  249. WorkflowServiceClientError,
  250. ) as exc:
  251. raise HTTPException(status_code=502, detail=str(exc)) from exc
  252. if result is None:
  253. raise HTTPException(
  254. status_code=404,
  255. detail=f"human node_run not found or task mismatch: {node_run_id}",
  256. )
  257. workflow_run, node_run, executor_name = result
  258. return NodeRunExecuteResponse(
  259. run=WorkflowRunResponse.from_entity(workflow_run),
  260. node_run=NodeRunResponse.from_entity(node_run),
  261. executor_name=executor_name,
  262. )
  263. @router.post("/workers/execute-next", response_model=WorkerExecuteNextResponse)
  264. def execute_next_worker_task(
  265. payload: WorkerExecuteNextRequest,
  266. settings: RuntimeServiceSettings = Depends(get_runtime_settings),
  267. service: RuntimeApplicationService = Depends(get_runtime_application_service),
  268. ) -> WorkerExecuteNextResponse:
  269. try:
  270. result = service.execute_next_claimed_node_run(
  271. worker_key=payload.worker_key,
  272. lease_seconds=payload.lease_seconds or settings.worker_lease_seconds,
  273. )
  274. except (
  275. CodeRunnerClientError,
  276. ModelGatewayClientError,
  277. HumanServiceClientError,
  278. ToolServiceClientError,
  279. WorkflowServiceClientError,
  280. ) as exc:
  281. raise HTTPException(status_code=502, detail=str(exc)) from exc
  282. if result is None:
  283. raise HTTPException(status_code=404, detail="queued worker task not found")
  284. workflow_run, node_run, executor_name, released_lease_count = result
  285. return WorkerExecuteNextResponse(
  286. run=WorkflowRunResponse.from_entity(workflow_run),
  287. node_run=NodeRunResponse.from_entity(node_run),
  288. executor_name=executor_name,
  289. released_lease_count=released_lease_count,
  290. )