routes.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from core_domain import CodeExecutionRequestContract, CodeExecutionResponseContract, ServiceHealth
  2. from core_shared import error_detail
  3. from fastapi import APIRouter, Depends, HTTPException
  4. from app.application.services import CodeRunnerApplicationService
  5. from app.bootstrap.settings import CodeRunnerServiceSettings
  6. from app.infrastructure.runner import CodeRunnerError, PythonCodeRunner
  7. router = APIRouter()
  8. def get_code_runner_settings() -> CodeRunnerServiceSettings:
  9. return CodeRunnerServiceSettings()
  10. def get_code_runner_application_service(
  11. settings: CodeRunnerServiceSettings = Depends(get_code_runner_settings)) -> CodeRunnerApplicationService:
  12. return CodeRunnerApplicationService(
  13. runner=PythonCodeRunner(settings=settings),
  14. settings=settings)
  15. @router.get("/health", response_model=ServiceHealth)
  16. def health_check(
  17. settings: CodeRunnerServiceSettings = Depends(get_code_runner_settings)) -> ServiceHealth:
  18. return ServiceHealth(service="code-runner-service", status="ok", database=settings.python_bin)
  19. @router.post("/execute", response_model=CodeExecutionResponseContract)
  20. def execute_code(
  21. payload: CodeExecutionRequestContract,
  22. service: CodeRunnerApplicationService = Depends(get_code_runner_application_service)) -> CodeExecutionResponseContract:
  23. try:
  24. return service.execute_code(payload)
  25. except CodeRunnerError as exc:
  26. raise HTTPException(status_code=422, detail=error_detail("error.code_runner.execution_failed", message=str(exc))) from exc