tasks.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # Copyright (C) 2025 AIDC-AI
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. """
  13. Task management endpoints
  14. Endpoints for managing async tasks (checking status, canceling, etc.)
  15. """
  16. from typing import List, Optional
  17. from fastapi import APIRouter, HTTPException, Query
  18. from loguru import logger
  19. from api.tasks import task_manager, Task, TaskStatus
  20. router = APIRouter(prefix="/tasks", tags=["Tasks"])
  21. @router.get("", response_model=List[Task])
  22. async def list_tasks(
  23. status: Optional[TaskStatus] = Query(None, description="Filter by status"),
  24. limit: int = Query(100, ge=1, le=1000, description="Maximum number of tasks")
  25. ):
  26. """
  27. List tasks
  28. Retrieve list of tasks with optional filtering.
  29. - **status**: Optional filter by status (pending/running/completed/failed/cancelled)
  30. - **limit**: Maximum number of tasks to return (default 100)
  31. Returns list of tasks sorted by creation time (newest first).
  32. """
  33. try:
  34. tasks = task_manager.list_tasks(status=status, limit=limit)
  35. return tasks
  36. except Exception as e:
  37. logger.error(f"List tasks error: {e}")
  38. raise HTTPException(status_code=500, detail=str(e))
  39. @router.get("/{task_id}", response_model=Task)
  40. async def get_task(task_id: str):
  41. """
  42. Get task details
  43. Retrieve detailed information about a specific task.
  44. - **task_id**: Task ID
  45. Returns task details including status, progress, and result (if completed).
  46. """
  47. try:
  48. task = task_manager.get_task(task_id)
  49. if not task:
  50. raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
  51. return task
  52. except HTTPException:
  53. raise
  54. except Exception as e:
  55. logger.error(f"Get task error: {e}")
  56. raise HTTPException(status_code=500, detail=str(e))
  57. @router.delete("/{task_id}")
  58. async def cancel_task(task_id: str):
  59. """
  60. Cancel task
  61. Cancel a running or pending task.
  62. - **task_id**: Task ID
  63. Returns success status.
  64. """
  65. try:
  66. success = task_manager.cancel_task(task_id)
  67. if not success:
  68. raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
  69. return {
  70. "success": True,
  71. "message": f"Task {task_id} cancelled successfully"
  72. }
  73. except HTTPException:
  74. raise
  75. except Exception as e:
  76. logger.error(f"Cancel task error: {e}")
  77. raise HTTPException(status_code=500, detail=str(e))