Download backend/src/main.py from new-arc/vector: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/new-arc/vector/resolve/main/backend/src/main.py
- Command line
-
hf download hf://spaces/new-arc/vector/backend/src/main.py
-
curl -L -o main.py https://huggingface.co/spaces/new-arc/vector/resolve/main/backend/src/main.py
10.5 kB
| """ | |
| SupoClip FastAPI application. | |
| This is the new main entry point with: | |
| - Separated concerns (routes, services, repositories, workers) | |
| - Async job queue with arq | |
| - Real-time progress updates via SSE | |
| - Thread pool for blocking operations | |
| """ | |
| from contextlib import asynccontextmanager | |
| import logging | |
| import time | |
| from fastapi import FastAPI, Depends, HTTPException, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| from fastapi.exceptions import RequestValidationError | |
| from fastapi.encoders import jsonable_encoder | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from .config import Config, get_config, set_config_override | |
| from .database import AsyncSessionLocal, close_db, configure_database, get_db, init_db | |
| from .runtime_settings import load_runtime_settings_cache | |
| from .workers.job_queue import JobQueue | |
| from .api.routes import tasks | |
| from .api.routes.admin import router as admin_router | |
| from .observability import ( | |
| TRACE_HEADER, | |
| clear_trace_id, | |
| configure_logging, | |
| generate_trace_id, | |
| get_trace_id, | |
| set_trace_id, | |
| set_user_id, | |
| ) | |
| from .source_submission import is_task_create_request, log_task_create_validation_error | |
| configure_logging() | |
| logger = logging.getLogger(__name__) | |
| def create_app( | |
| *, | |
| config: Config | None = None, | |
| session_maker=None, | |
| queue_adapter=JobQueue, | |
| ): | |
| if config is None: | |
| set_config_override(None) | |
| runtime_config = get_config() | |
| else: | |
| runtime_config = config | |
| set_config_override(runtime_config) | |
| if session_maker is not None: | |
| configure_database( | |
| session_maker=session_maker, | |
| engine=session_maker.kw.get("bind"), | |
| ) | |
| async def lifespan(app: FastAPI): | |
| """Application lifespan: startup and shutdown events.""" | |
| logger.info("π Starting SupoClip API...") | |
| try: | |
| await init_db() | |
| logger.info("β Database initialized") | |
| async with AsyncSessionLocal() as db: | |
| await load_runtime_settings_cache(db) | |
| logger.info("β Runtime settings loaded") | |
| await queue_adapter.get_pool() | |
| logger.info("β Job queue initialized") | |
| yield | |
| finally: | |
| logger.info("π Shutting down SupoClip API...") | |
| await close_db() | |
| await queue_adapter.close_pool() | |
| logger.info("β Cleanup complete") | |
| app = FastAPI( | |
| title="SupoClip API", | |
| description="SupoClip backend with async job processing", | |
| version="0.2.0", | |
| lifespan=lifespan, | |
| ) | |
| app.state.queue_adapter = queue_adapter | |
| app.state.config = runtime_config | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=runtime_config.cors_origins, | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=[ | |
| "Content-Type", | |
| "Authorization", | |
| "x-supoclip-user-id", | |
| "x-supoclip-ts", | |
| "x-supoclip-signature", | |
| "x-trace-id", | |
| "user_id", | |
| "Idempotency-Key", | |
| ], | |
| expose_headers=["x-trace-id"], | |
| ) | |
| async def trace_and_request_logging_middleware(request: Request, call_next): | |
| trace_id = request.headers.get(TRACE_HEADER) or generate_trace_id() | |
| set_trace_id(trace_id) | |
| started_at = time.perf_counter() | |
| logger.info("Incoming request %s %s", request.method, request.url.path) | |
| try: | |
| response = await call_next(request) | |
| except Exception: | |
| set_user_id(getattr(request.state, "user_id", None)) | |
| logger.exception("Unhandled exception while processing request") | |
| clear_trace_id() | |
| set_user_id(None) | |
| raise | |
| # The endpoint ran in its own context; bring the user it authenticated | |
| # back into this one so the completion log line carries it. | |
| set_user_id(getattr(request.state, "user_id", None)) | |
| elapsed_ms = round((time.perf_counter() - started_at) * 1000, 2) | |
| response.headers[TRACE_HEADER] = trace_id | |
| logger.info( | |
| "Completed request %s %s with status %s in %sms", | |
| request.method, | |
| request.url.path, | |
| response.status_code, | |
| elapsed_ms, | |
| ) | |
| clear_trace_id() | |
| set_user_id(None) | |
| return response | |
| async def http_exception_handler(_: Request, exc: HTTPException): | |
| trace_id = get_trace_id() | |
| logger.warning( | |
| "HTTP exception: status=%s detail=%s", exc.status_code, exc.detail | |
| ) | |
| return JSONResponse( | |
| status_code=exc.status_code, | |
| content=jsonable_encoder({"detail": exc.detail, "trace_id": trace_id}), | |
| headers={TRACE_HEADER: trace_id}, | |
| ) | |
| async def validation_exception_handler(request: Request, exc: RequestValidationError): | |
| trace_id = get_trace_id() | |
| # Task creation logs a sanitized source line instead of exc.errors(), | |
| # which includes the submitted input (query tokens and all). | |
| if is_task_create_request(request.method, request.url.path): | |
| await log_task_create_validation_error(request, exc) | |
| else: | |
| logger.warning("Validation error: %s", exc.errors()) | |
| return JSONResponse( | |
| status_code=422, | |
| content={"detail": exc.errors(), "trace_id": trace_id}, | |
| headers={TRACE_HEADER: trace_id}, | |
| ) | |
| async def unhandled_exception_handler(request: Request, exc: Exception): | |
| trace_id = get_trace_id() | |
| set_user_id(getattr(request.state, "user_id", None)) | |
| logger.error("Unhandled server error: %s", exc, exc_info=True) | |
| return JSONResponse( | |
| status_code=500, | |
| content={ | |
| "detail": "An internal server error occurred. Contact support with the trace ID.", | |
| "trace_id": trace_id, | |
| }, | |
| headers={TRACE_HEADER: trace_id}, | |
| ) | |
| app.include_router(tasks.router) | |
| from .api.routes.clip_exports import router as clip_export_router | |
| from .api.routes.editor import router as editor_router | |
| app.include_router(clip_export_router) | |
| app.include_router(editor_router) | |
| app.include_router(admin_router) | |
| from .api.routes.media import router as media_router | |
| from .api.routes.feedback import router as feedback_router | |
| from .api.routes.billing import router as billing_router | |
| from .api.routes.api_keys import router as api_keys_router | |
| from .api.routes.account import router as account_router | |
| from .api.routes.social import router as social_router | |
| from .api.routes.email_preferences import router as email_preferences_router | |
| from .api.routes.feature_flags import router as feature_flags_router | |
| app.include_router(media_router) | |
| app.include_router(feedback_router) | |
| app.include_router(billing_router) | |
| app.include_router(api_keys_router) | |
| app.include_router(account_router) | |
| app.include_router(social_router) | |
| app.include_router(email_preferences_router) | |
| app.include_router(feature_flags_router) | |
| def read_root(): | |
| """Root endpoint.""" | |
| return { | |
| "name": "SupoClip API", | |
| "version": "0.2.0", | |
| "status": "running", | |
| "docs": "/docs", | |
| "architecture": "job queue", | |
| } | |
| async def health_check(): | |
| """Basic health check.""" | |
| return {"status": "healthy"} | |
| async def check_database_health(db: AsyncSession = Depends(get_db)): | |
| """Check database connectivity.""" | |
| from sqlalchemy import text | |
| try: | |
| await db.execute(text("SELECT 1")) | |
| return {"status": "healthy", "database": "connected"} | |
| except Exception as e: | |
| logger.error("Database health check failed: %s", e) | |
| return JSONResponse( | |
| status_code=503, | |
| content={"status": "unhealthy", "database": "disconnected"}, | |
| ) | |
| async def check_redis_health(): | |
| """Check Redis connectivity.""" | |
| try: | |
| pool = await app.state.queue_adapter.get_pool() | |
| await pool.ping() | |
| return {"status": "healthy", "redis": "connected"} | |
| except Exception as e: | |
| return { | |
| "status": "unhealthy", | |
| "redis": "disconnected", | |
| "error": str(e), | |
| } | |
| async def check_worker_health(): | |
| """Check ARQ's expiring heartbeat, not just Redis connectivity.""" | |
| from arq.constants import health_check_key_suffix | |
| from .workers.job_queue import DEFAULT_QUEUE_NAME | |
| try: | |
| pool = await app.state.queue_adapter.get_pool() | |
| heartbeat = await pool.get(DEFAULT_QUEUE_NAME + health_check_key_suffix) | |
| if heartbeat: | |
| return {"status": "healthy", "worker": "connected"} | |
| except Exception: | |
| logger.exception("Worker heartbeat check failed") | |
| return JSONResponse( | |
| status_code=503, | |
| content={"status": "unhealthy", "worker": "unavailable"}, | |
| ) | |
| async def check_storage_health(): | |
| """Read cached worker probes; public requests never perform writes.""" | |
| import json | |
| from pathlib import Path | |
| config = get_config() | |
| if not getattr(config, "media_fallback_enabled", False): | |
| return {"status": "unmonitored", "replication": "disabled"} | |
| try: | |
| report = json.loads((Path(config.temp_dir) / "media-replication" / "health.json").read_text()) | |
| if time.time() - report["checked_at"] > 180: | |
| report = {"status": "unhealthy", "reason": "stale_probe"} | |
| except (OSError, ValueError, KeyError): | |
| report = {"status": "unhealthy", "reason": "probe_unavailable"} | |
| return JSONResponse(status_code=200 if report["status"] == "healthy" else 503, content=report, | |
| headers={"Cache-Control": "no-store"}) | |
| return app | |
| app = create_app() | |