From 0d208b737a1848839d94e713f887db97bdfd3cb0 Mon Sep 17 00:00:00 2001 From: KEERTHI M Date: Thu, 1 Oct 2026 10:52:08 +0530 Subject: [PATCH] Refactor FastAPI app initialization and update comments Refactor FastAPI application initialization to use create_app() for improved configuration flexibility. Update comments and docstrings for clarity. --- api/app.py | 302 +++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 214 insertions(+), 88 deletions(-) diff --git a/api/app.py b/api/app.py index a948313..f0eccc3 100644 --- a/api/app.py +++ b/api/app.py @@ -1,34 +1,36 @@ """ FastAPI application assembly. -This module now builds the application through `create_app()` rather than -configuring a module-level singleton at import time. Import-time -construction meant there was no point at which the app could be built with -different settings, no shutdown hook, and no way to stand up a second -isolated instance in a test. +This module builds the application through `create_app()` rather than +configuring a module-level singleton at import time. -`app = create_app()` is still exported at module level, because +`app = create_app()` is still exported at module level because `api.app:app` is the documented uvicorn target, the deployment entry point, -and what `tests/test_api.py` and `tests/test_voice_layer.py` import. That -contract is unchanged. +and what `tests/test_api.py` and `tests/test_voice_layer.py` import. Runnable in mock mode with no API key: python -m uvicorn api.app:app --reload -Starting the server calls no LLM, speech or vector provider. Configuration -is read (config/settings.py for provider/domain values, core/config.py for -service values) and validated, and providers are resolved lazily at first -use, exactly as before. - -Wiring seams preserved verbatim -------------------------------- -`app.state.registry`, `app.state.interviewer_factory` and -`app.state.voice_service_factory` remain exactly what they were: pure wiring -hooks, None/default in a real deployment, read on every request. The -dependency container (core/container.py) reads through to them rather than -shadowing them, so assigning them still works. +Starting the server calls no LLM, speech, or vector provider. +Configuration is read from: + +- config/settings.py for provider/domain values +- core/config.py for service values + +Providers are resolved lazily at first use. + +Wiring seams preserved: + +- `app.state.registry` +- `app.state.interviewer_factory` +- `app.state.voice_service_factory` + +These remain pure wiring hooks and are read on every request. +The dependency container (`core/container.py`) reads through to them +rather than shadowing them. """ + from pathlib import Path from fastapi import Depends, FastAPI @@ -40,14 +42,14 @@ from api.routes.applications import router as applications_router from api.routes.auth import router as auth_router from api.routes.bugs import router as bugs_router -from api.routes.llm_credentials import router as llm_credentials_router from api.routes.candidates import router as candidates_router from api.routes.evaluations import router as evaluations_router from api.routes.interview import router as interview_router from api.routes.interview_mediator import router as interview_mediator_router from api.routes.jobs import router as jobs_router -from api.routes.rubrics import router as rubrics_router +from api.routes.llm_credentials import router as llm_credentials_router from api.routes.reports import router as reports_router +from api.routes.rubrics import router as rubrics_router from api.routes.scoring import router as scoring_router from api.routes.voice import router as voice_router from core.config import AppSettings, get_settings @@ -56,32 +58,40 @@ from core.lifespan import build_lifespan from core.middleware import install_middleware -# P9: the voice client is served from the API's OWN origin. + +# P9: The voice client is served from the API's own origin. +# +# `pages/voice-interview.html` builds its WebSocket URL from +# `location.host`. Opening the page directly as a `file://` URL would +# result in an empty host, preventing the WebSocket connection. +# +# Serving the page from the API also keeps browser fetch/WebSocket +# requests same-origin, so this vertical slice does not require CORS. +# +# CORS is available through `CORS_ALLOW_ORIGINS` in `core/config.py` +# for deployments using a separately hosted frontend. # -# Necessary, not cosmetic: pages/voice-interview.html builds its WebSocket -# URL from `location.host`, so opening it as a file:// URL yields an empty -# host and the socket can never connect. Serving it here also keeps the -# browser's fetch/WebSocket same-origin, which is why the vertical slice -# needs no CORS configuration (CORS is now available via CORS_ALLOW_ORIGINS -# for a separately-hosted frontend - see core/config.py - but is off unless -# an operator opts in). Read-only static hosting of one directory: no upload -# path and no user-supplied path is ever joined here, so it introduces no -# traversal surface of its own (StaticFiles normalizes and confines paths -# beneath the mounted directory). +# StaticFiles provides read-only static hosting and confines access +# beneath the mounted directory. _PAGES_DIR = Path(__file__).resolve().parent.parent / "pages" def create_app(settings: AppSettings | None = None) -> FastAPI: - """Build a fully wired application. + """ + Build and return a fully wired FastAPI application. + + If `settings` is not supplied, the process-wide cached settings + are used. - `settings` defaults to the process-wide cached settings; passing an - explicit object is what lets a test exercise a differently-configured - app (production mode, CORS enabled, auth enabled) without mutating the - environment for every other test in the session. + Passing an explicit settings object allows tests to create an + independently configured application without modifying environment + variables for the rest of the test session. """ + from api.registry import SessionRegistry - settings = settings or get_settings() + if settings is None: + settings = get_settings() app = FastAPI( title=settings.app_name, @@ -97,44 +107,121 @@ def create_app(settings: AppSettings | None = None) -> FastAPI: openapi_url=settings.openapi_url, ) - # The three pre-existing wiring seams. See the module docstring; the - # container reads these on every request rather than copying them. + # ------------------------------------------------------------------ + # Pre-existing wiring seams + # ------------------------------------------------------------------ + app.state.registry = SessionRegistry() app.state.interviewer_factory = None app.state.voice_service_factory = None - # Chunk 2: the same kind of pure wiring seam, for the three agents the - # job/candidate/matching services wrap (JDAnalyzerAgent, - # ResumeParserAgent, ResumeMatcherAgent). None means "let the agent - # resolve its own default LLM provider" - see core/container.py's - # `*_factory_for` methods. + + # Chunk 2: + # Wiring seams for the job/candidate/matching agents: + # + # - JDAnalyzerAgent + # - ResumeParserAgent + # - ResumeMatcherAgent + # + # None means the agent resolves its own default LLM provider. app.state.jd_analyzer_factory = None app.state.resume_parser_factory = None app.state.resume_matcher_factory = None - # Chunk 4: one bundled seam for the seven evaluation agents - see - # core/container.py:evaluation_agent_factories_for and - # services/evaluation_service.py:EvaluationAgentFactories. + + # Chunk 4: + # Bundled wiring seam for the seven evaluation agents. app.state.evaluation_agent_factories = None - # Chunk 5: same pattern, for LeaderboardAgent (RecruiterService). + + # Chunk 5: + # Wiring seam for LeaderboardAgent used by RecruiterService. app.state.leaderboard_factory = None + + # Make the application settings available through app.state. app.state.settings = settings + # ------------------------------------------------------------------ + # Middleware and exception handling + # ------------------------------------------------------------------ + install_middleware(app, settings) register_exception_handlers(app) - app.include_router(auth_router, prefix=settings.api_prefix) - app.include_router(admin_router, prefix=settings.api_prefix) - app.include_router(interview_router, prefix=settings.api_prefix) - app.include_router(voice_router, prefix=settings.api_prefix) - app.include_router(interview_mediator_router, prefix=settings.api_prefix) - app.include_router(scoring_router, prefix=settings.api_prefix) - app.include_router(reports_router, prefix=settings.api_prefix) - app.include_router(jobs_router, prefix=settings.api_prefix) - app.include_router(rubrics_router, prefix=settings.api_prefix) - app.include_router(candidates_router, prefix=settings.api_prefix) - app.include_router(applications_router, prefix=settings.api_prefix) - app.include_router(evaluations_router, prefix=settings.api_prefix) - app.include_router(bugs_router, prefix=settings.api_prefix) - app.include_router(llm_credentials_router, prefix=settings.api_prefix) + # ------------------------------------------------------------------ + # API routes + # ------------------------------------------------------------------ + + app.include_router( + auth_router, + prefix=settings.api_prefix, + ) + + app.include_router( + admin_router, + prefix=settings.api_prefix, + ) + + app.include_router( + interview_router, + prefix=settings.api_prefix, + ) + + app.include_router( + voice_router, + prefix=settings.api_prefix, + ) + + app.include_router( + interview_mediator_router, + prefix=settings.api_prefix, + ) + + app.include_router( + scoring_router, + prefix=settings.api_prefix, + ) + + app.include_router( + reports_router, + prefix=settings.api_prefix, + ) + + app.include_router( + jobs_router, + prefix=settings.api_prefix, + ) + + app.include_router( + rubrics_router, + prefix=settings.api_prefix, + ) + + app.include_router( + candidates_router, + prefix=settings.api_prefix, + ) + + app.include_router( + applications_router, + prefix=settings.api_prefix, + ) + + app.include_router( + evaluations_router, + prefix=settings.api_prefix, + ) + + app.include_router( + bugs_router, + prefix=settings.api_prefix, + ) + + app.include_router( + llm_credentials_router, + prefix=settings.api_prefix, + ) + + # ------------------------------------------------------------------ + # Health endpoint + # ------------------------------------------------------------------ @app.api_route( f"{settings.api_prefix}/health", @@ -143,43 +230,82 @@ def create_app(settings: AppSettings | None = None) -> FastAPI: tags=["health"], ) async def health() -> HealthResponse: - """Liveness. No LLM call, no provider call, no database call, no API - key required (P5 Phase 13). - - The body is exactly `{"status": "ok"}` and stays that way. A liveness - probe is polled continuously by a load balancer, so it must be the - cheapest endpoint in the service and must not describe the service's - internals to whoever can reach it. Operational detail lives on `/` - instead (below). - - It deliberately does not probe upstreams either: a health check that - fails because a third-party model is briefly unavailable takes the - whole service out of rotation for something it can still partly - serve, and burns paid quota on every probe. """ + Liveness endpoint. + + This endpoint intentionally performs: + + - no LLM call + - no provider call + - no database call + - no API-key validation + + The response remains exactly: + + {"status": "ok"} + + This keeps the endpoint inexpensive enough for continuous + load-balancer health checks. + """ + return HealthResponse(status="ok") - @app.api_route(f"{settings.api_prefix}/", methods=["GET", "HEAD"], include_in_schema=False) - async def root(container: ServiceContainer = Depends(get_container)) -> dict: - """How this process is configured. + # ------------------------------------------------------------------ + # Root endpoint + # ------------------------------------------------------------------ - Credential-free by construction: `AppSettings.public_summary()` - returns provider *names* only - never a key, a connection string or a - path. `persistence` is here specifically so a deployment still running - on the temporary in-memory repositories announces it, rather than - looking healthy while losing every transcript on restart. + @app.api_route( + f"{settings.api_prefix}/", + methods=["GET", "HEAD"], + include_in_schema=False, + ) + async def root( + container: ServiceContainer = Depends(get_container), + ) -> dict: """ + Return a credential-free summary of the running service. + + Provider names may be exposed, but credentials, connection + strings, and filesystem paths must never be returned. + + Persistence information is included so deployments using + temporary in-memory repositories are clearly identified. + """ + return { "service": "openhire-live-interview-api", **container.settings.public_summary(), - "persistence": "ephemeral" if container.persistence_is_ephemeral else "durable", + "persistence": ( + "ephemeral" + if container.persistence_is_ephemeral + else "durable" + ), } + # ------------------------------------------------------------------ + # Static pages + # ------------------------------------------------------------------ + if settings.serve_static_pages and _PAGES_DIR.is_dir(): - app.mount("/app", StaticFiles(directory=str(_PAGES_DIR), html=True), name="pages") + app.mount( + "/app", + StaticFiles( + directory=str(_PAGES_DIR), + html=True, + ), + name="pages", + ) return app -# The uvicorn/deployment/test entry point. Unchanged contract. +# ---------------------------------------------------------------------- +# Uvicorn / deployment / test entry point +# ---------------------------------------------------------------------- + +# Keep this module-level application object because: +# +# uvicorn api.app:app --reload +# +# and existing tests depend on it. app = create_app()