|
| 1 | +""" |
| 2 | +Project management API endpoints. |
| 3 | +""" |
| 4 | +from fastapi import APIRouter, Request, BackgroundTasks |
| 5 | +from fastapi.responses import JSONResponse |
| 6 | +import os |
| 7 | +from datetime import datetime |
| 8 | + |
| 9 | +from db import ( |
| 10 | + get_project_by_id, list_projects, |
| 11 | + update_project_status, delete_project, get_or_create_project, |
| 12 | + CreateProjectRequest, IndexProjectRequest |
| 13 | +) |
| 14 | +from ai.analyzer import analyze_local_path_background |
| 15 | +from utils.logger import get_logger |
| 16 | +from utils.config import CFG |
| 17 | +from .rate_limiter import indexing_limiter |
| 18 | + |
| 19 | +logger = get_logger(__name__) |
| 20 | +router = APIRouter(prefix="/api", tags=["projects"]) |
| 21 | + |
| 22 | +MAX_FILE_SIZE = int(CFG.get("max_file_size", 200000)) |
| 23 | + |
| 24 | + |
| 25 | +def _get_client_ip(request: Request) -> str: |
| 26 | + """Get client IP address from request.""" |
| 27 | + forwarded = request.headers.get("X-Forwarded-For") |
| 28 | + if forwarded: |
| 29 | + return forwarded.split(",")[0].strip() |
| 30 | + return request.client.host if request.client else "unknown" |
| 31 | + |
| 32 | + |
| 33 | +@router.post("/projects", summary="Create or get a project") |
| 34 | +def api_create_project(request: CreateProjectRequest): |
| 35 | + """ |
| 36 | + Create or get a project with per-project database. |
| 37 | + |
| 38 | + - **path**: Absolute path to project directory (required) |
| 39 | + - **name**: Optional project name (defaults to directory name) |
| 40 | + |
| 41 | + Returns project metadata including: |
| 42 | + - **id**: Unique project identifier |
| 43 | + - **database_path**: Path to project's SQLite database |
| 44 | + - **status**: Current project status |
| 45 | + """ |
| 46 | + try: |
| 47 | + project = get_or_create_project(request.path, request.name) |
| 48 | + return JSONResponse(project) |
| 49 | + except ValueError as e: |
| 50 | + # ValueError is expected for invalid inputs, safe to show message |
| 51 | + logger.warning(f"Validation error creating project: {e}") |
| 52 | + return JSONResponse({"error": "Invalid project path"}, status_code=400) |
| 53 | + except RuntimeError as e: |
| 54 | + # RuntimeError may contain sensitive details, use generic message |
| 55 | + logger.error(f"Runtime error creating project: {e}") |
| 56 | + return JSONResponse({"error": "Database operation failed"}, status_code=500) |
| 57 | + except Exception as e: |
| 58 | + logger.exception(f"Unexpected error creating project: {e}") |
| 59 | + return JSONResponse({"error": "Internal server error"}, status_code=500) |
| 60 | + |
| 61 | + |
| 62 | +@router.get("/projects", summary="List all projects") |
| 63 | +def api_list_projects(): |
| 64 | + """ |
| 65 | + List all registered projects. |
| 66 | + |
| 67 | + Returns array of project objects with metadata: |
| 68 | + - **id**: Unique project identifier |
| 69 | + - **name**: Project name |
| 70 | + - **path**: Project directory path |
| 71 | + - **status**: Current status (created, indexing, ready, error) |
| 72 | + - **last_indexed_at**: Last indexing timestamp |
| 73 | + """ |
| 74 | + try: |
| 75 | + projects = list_projects() |
| 76 | + return JSONResponse(projects) |
| 77 | + except Exception as e: |
| 78 | + logger.exception(f"Error listing projects: {e}") |
| 79 | + return JSONResponse({"error": "Failed to list projects"}, status_code=500) |
| 80 | + |
| 81 | + |
| 82 | +@router.get("/projects/{project_id}", summary="Get project by ID") |
| 83 | +def api_get_project(project_id: str): |
| 84 | + """ |
| 85 | + Get project details by ID. |
| 86 | + |
| 87 | + - **project_id**: Unique project identifier |
| 88 | + |
| 89 | + Returns project metadata or 404 if not found. |
| 90 | + """ |
| 91 | + try: |
| 92 | + project = get_project_by_id(project_id) |
| 93 | + if not project: |
| 94 | + return JSONResponse({"error": "Project not found"}, status_code=404) |
| 95 | + return JSONResponse(project) |
| 96 | + except Exception as e: |
| 97 | + logger.exception(f"Error getting project: {e}") |
| 98 | + return JSONResponse({"error": "Failed to retrieve project"}, status_code=500) |
| 99 | + |
| 100 | + |
| 101 | +@router.delete("/projects/{project_id}", summary="Delete a project") |
| 102 | +def api_delete_project(project_id: str): |
| 103 | + """ |
| 104 | + Delete a project and its database. |
| 105 | + |
| 106 | + - **project_id**: Unique project identifier |
| 107 | + |
| 108 | + Permanently removes the project and all indexed data. |
| 109 | + Returns 404 if project not found. |
| 110 | + """ |
| 111 | + try: |
| 112 | + delete_project(project_id) |
| 113 | + return JSONResponse({"success": True}) |
| 114 | + except ValueError as e: |
| 115 | + logger.warning(f"Project not found for deletion: {e}") |
| 116 | + return JSONResponse({"error": "Project not found"}, status_code=404) |
| 117 | + except Exception as e: |
| 118 | + logger.exception(f"Error deleting project: {e}") |
| 119 | + return JSONResponse({"error": "Failed to delete project"}, status_code=500) |
| 120 | + |
| 121 | + |
| 122 | +@router.post("/projects/index", tags=["indexing"], summary="Index a project") |
| 123 | +def api_index_project(http_request: Request, request: IndexProjectRequest, background_tasks: BackgroundTasks): |
| 124 | + """ |
| 125 | + Index or re-index a project in the background. |
| 126 | + |
| 127 | + - **project_id**: Unique project identifier |
| 128 | + |
| 129 | + Starts background indexing process: |
| 130 | + - Scans project directory for code files |
| 131 | + - Generates embeddings for semantic search |
| 132 | + - Uses incremental indexing (skips unchanged files) |
| 133 | + |
| 134 | + Rate limit: 10 requests per minute per IP. |
| 135 | + |
| 136 | + Returns immediately with status "indexing". |
| 137 | + Poll project status to check completion. |
| 138 | + """ |
| 139 | + # Rate limiting for indexing operations (more strict) |
| 140 | + client_ip = _get_client_ip(http_request) |
| 141 | + allowed, retry_after = indexing_limiter.is_allowed(client_ip) |
| 142 | + if not allowed: |
| 143 | + return JSONResponse( |
| 144 | + {"error": "Rate limit exceeded for indexing", "retry_after": retry_after}, |
| 145 | + status_code=429, |
| 146 | + headers={"Retry-After": str(retry_after)} |
| 147 | + ) |
| 148 | + |
| 149 | + try: |
| 150 | + project = get_project_by_id(request.project_id) |
| 151 | + if not project: |
| 152 | + return JSONResponse({"error": "Project not found"}, status_code=404) |
| 153 | + |
| 154 | + project_path = project["path"] |
| 155 | + db_path = project["database_path"] |
| 156 | + |
| 157 | + if not os.path.exists(project_path): |
| 158 | + return JSONResponse({"error": "Project path does not exist"}, status_code=400) |
| 159 | + |
| 160 | + # Update status to indexing |
| 161 | + update_project_status(request.project_id, "indexing") |
| 162 | + |
| 163 | + # Start background indexing |
| 164 | + venv_path = CFG.get("venv_path") |
| 165 | + |
| 166 | + def index_callback(): |
| 167 | + try: |
| 168 | + analyze_local_path_background(project_path, db_path, venv_path, MAX_FILE_SIZE, CFG) |
| 169 | + update_project_status(request.project_id, "ready", datetime.utcnow().isoformat()) |
| 170 | + except Exception as e: |
| 171 | + update_project_status(request.project_id, "error") |
| 172 | + raise |
| 173 | + |
| 174 | + background_tasks.add_task(index_callback) |
| 175 | + |
| 176 | + return JSONResponse({"status": "indexing", "project_id": request.project_id}) |
| 177 | + except Exception as e: |
| 178 | + logger.exception(f"Error starting project indexing: {e}") |
| 179 | + return JSONResponse({"error": "Failed to start indexing"}, status_code=500) |
0 commit comments