File size: 6,673 Bytes
5be081e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
"""
FastAPI Application Entry Point for Todo API

Owner: Backend API Engineer
Purpose: Main FastAPI application with CORS, authentication, and database lifecycle
Architecture: Async FastAPI with SQLModel, JWT auth, and Neon PostgreSQL

Constitutional Constraints:
- REQUIRED: CORS configured for Next.js frontend (http://localhost:3000)
- REQUIRED: Database initialization on startup
- REQUIRED: Database cleanup on shutdown
- REQUIRED: Health check endpoint for monitoring
- REQUIRED: All routes protected with JWT authentication

Application Lifecycle:
1. Startup: Initialize database connection and create tables
2. Runtime: Handle API requests with JWT authentication
3. Shutdown: Close database connections gracefully

All endpoints enforce strict user isolation per constitution Principle IV.
"""

import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from src.db import init_database, cleanup_database, check_database_health
from src.api.routes import todos, chat

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("api.main")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Application lifespan manager for startup and shutdown events.

    Startup:
    - Initialize database connection
    - Create tables if they don't exist
    - Verify database health

    Shutdown:
    - Close database connections
    - Release connection pool resources

    Args:
        app: FastAPI application instance

    Yields:
        None (context manager for lifespan)
    """
    # Startup
    logger.info("Starting Todo API application...")
    try:
        await init_database()
        logger.info("✓ Database initialized successfully")
    except Exception as e:
        logger.error(f"Failed to initialize database: {e}")
        raise

    yield

    # Shutdown
    logger.info("Shutting down Todo API application...")
    try:
        await cleanup_database()
        logger.info("✓ Database connections closed")
    except Exception as e:
        logger.error(f"Error during shutdown: {e}")


# Create FastAPI application
app = FastAPI(
    title="Todo API",
    description="Secure Todo API with JWT authentication and user isolation",
    version="1.0.0",
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json"
)


# Configure CORS - Allow all origins
# NOTE: allow_credentials=False when using wildcard origin
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins
    allow_credentials=False,  # Required to be False when using "*"
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allow_headers=[
        "Authorization",  # JWT Bearer token
        "Content-Type",
        "Accept",
        "Origin",
        "X-Requested-With"
    ],
    expose_headers=["Content-Length", "Content-Type"],
    max_age=3600  # Cache preflight requests for 1 hour
)


# Include routers
app.include_router(todos.router)
app.include_router(chat.router)

# Note: MCP tools are called directly from chat endpoint
# FastMCP server mounting removed - tools work without external MCP server


# Health check endpoint (no authentication required)
@app.get(
    "/health",
    status_code=status.HTTP_200_OK,
    tags=["health"],
    summary="Health check endpoint",
    description="Check if the API and database are healthy. No authentication required.",
    responses={
        200: {"description": "Service is healthy"},
        503: {"description": "Service is unhealthy"}
    }
)
async def health_check():
    """
    Health check endpoint for monitoring and load balancers.

    Checks:
    - API is running
    - Database connection is healthy

    Returns:
        dict: Health status with database connectivity

    Status Codes:
        200: Service is healthy
        503: Service is unhealthy (database connection failed)
    """
    try:
        # Check database connectivity
        db_healthy = await check_database_health()

        if not db_healthy:
            logger.error("Health check failed: Database connection unhealthy")
            return JSONResponse(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                content={
                    "status": "unhealthy",
                    "database": "disconnected",
                    "message": "Database connection failed"
                }
            )

        return {
            "status": "healthy",
            "database": "connected",
            "message": "Todo API is running"
        }

    except Exception as e:
        logger.error(f"Health check failed: {e}")
        return JSONResponse(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            content={
                "status": "unhealthy",
                "database": "error",
                "message": str(e)
            }
        )


# Root endpoint (no authentication required)
@app.get(
    "/",
    tags=["root"],
    summary="API root endpoint",
    description="Returns basic API information. No authentication required."
)
async def root():
    """
    Root endpoint with API information.

    Returns:
        dict: API name, version, and documentation links
    """
    return {
        "name": "Todo API",
        "version": "1.0.0",
        "description": "Secure Todo API with JWT authentication and user isolation",
        "documentation": "/docs",
        "health": "/health"
    }


# Global exception handler for unhandled errors
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    """
    Global exception handler for unhandled errors.

    Logs the error and returns a generic 500 response.
    Prevents leaking sensitive information in error messages.

    Args:
        request: FastAPI request object
        exc: Exception that was raised

    Returns:
        JSONResponse: Generic error response
    """
    logger.error(f"Unhandled exception: {exc}", exc_info=True)
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "detail": "Internal server error"
        }
    )


if __name__ == "__main__":
    import uvicorn

    # Run with uvicorn for development
    # Production: Use gunicorn with uvicorn workers
    uvicorn.run(
        "backend.src.api.main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,  # Auto-reload on code changes (development only)
        log_level="info"
    )