File size: 10,450 Bytes
851e5ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""
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"),
        )

    @asynccontextmanager
    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"],
    )

    @app.middleware("http")
    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

    @app.exception_handler(HTTPException)
    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},
        )

    @app.exception_handler(RequestValidationError)
    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},
        )

    @app.exception_handler(Exception)
    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)

    @app.get("/")
    def read_root():
        """Root endpoint."""
        return {
            "name": "SupoClip API",
            "version": "0.2.0",
            "status": "running",
            "docs": "/docs",
            "architecture": "job queue",
        }

    @app.get("/health")
    async def health_check():
        """Basic health check."""
        return {"status": "healthy"}

    @app.get("/health/db")
    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"},
            )

    @app.get("/health/redis")
    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),
            }

    @app.get("/health/worker")
    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"},
        )

    @app.get("/health/storage")
    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()