""" FastAPI application dedicated to indexing (separate from search API). This service mounts ONLY ONE copy of indexer routes: api/routes/indexer.py and injects required services via api/service_registry.py. Usage: uvicorn api.indexer_app:app --host 0.0.0.0 --port 6004 --reload This service only exposes /indexer/* routes and can be run in a separate process so that heavy indexing work does not block online search traffic. """ import os import sys import logging import time from typing import Optional from fastapi import FastAPI, Request from fastapi.responses import JSONResponse # Configure logging import pathlib log_dir = pathlib.Path("logs") log_dir.mkdir(exist_ok=True) logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", handlers=[ logging.StreamHandler(), logging.FileHandler(log_dir / "indexer_api.log", mode="a", encoding="utf-8"), ], ) logger = logging.getLogger(__name__) # Add parent directory to path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from config.env_config import ES_CONFIG # noqa: E402 from config import ConfigLoader # noqa: E402 from utils import ESClient # noqa: E402 from utils.db_connector import create_db_connection # noqa: E402 from indexer.incremental_service import IncrementalIndexerService # noqa: E402 from indexer.bulk_indexing_service import BulkIndexingService # noqa: E402 from .routes import indexer as indexer_routes # noqa: E402 from .service_registry import set_es_client, set_indexer_services # noqa: E402 _es_client: Optional[ESClient] = None _config = None _incremental_service: Optional[IncrementalIndexerService] = None _bulk_indexing_service: Optional[BulkIndexingService] = None def init_indexer_service(es_host: str = "http://localhost:9200"): """ Initialize indexing services (ES client + DB + indexers). This mirrors the indexing-related initialization logic in api.app.init_service but without search-related components. """ global _es_client, _config, _incremental_service, _bulk_indexing_service start_time = time.time() logger.info("Initializing Indexer service") # Load configuration (kept for parity/logging; indexer routes don't depend on it) logger.info("Loading configuration...") config_loader = ConfigLoader("config/config.yaml") _config = config_loader.load_config() logger.info("Configuration loaded") # Get ES credentials es_username = os.getenv("ES_USERNAME") or ES_CONFIG.get("username") es_password = os.getenv("ES_PASSWORD") or ES_CONFIG.get("password") # Connect to Elasticsearch logger.info(f"Connecting to Elasticsearch at {es_host} for indexer...") if es_username and es_password: _es_client = ESClient(hosts=[es_host], username=es_username, password=es_password) else: _es_client = ESClient(hosts=[es_host]) if not _es_client.ping(): raise ConnectionError(f"Failed to connect to Elasticsearch at {es_host}") logger.info("Elasticsearch connected for indexer") # publish ES client for routes set_es_client(_es_client) # Initialize indexing services (DB is required here) db_host = os.getenv("DB_HOST") db_port = int(os.getenv("DB_PORT", 3306)) db_database = os.getenv("DB_DATABASE") db_username = os.getenv("DB_USERNAME") db_password = os.getenv("DB_PASSWORD") if all([db_host, db_database, db_username, db_password]): logger.info("Initializing database connection for indexing services...") db_engine = create_db_connection( host=db_host, port=db_port, database=db_database, username=db_username, password=db_password, ) _incremental_service = IncrementalIndexerService(db_engine) _bulk_indexing_service = BulkIndexingService(db_engine, _es_client) set_indexer_services( incremental_service=_incremental_service, bulk_indexing_service=_bulk_indexing_service, ) logger.info("Indexer services initialized (incremental + bulk)") else: missing = [ name for name, value in [ ("DB_HOST", db_host), ("DB_DATABASE", db_database), ("DB_USERNAME", db_username), ("DB_PASSWORD", db_password), ] if not value ] logger.warning( "Database config incomplete for indexer, services will not be available. " f"Missing: {', '.join(missing)}" ) _incremental_service = None _bulk_indexing_service = None elapsed = time.time() - start_time logger.info(f"Indexer service ready! (took {elapsed:.2f}s)") # NOTE: we intentionally do NOT synchronize anything into api.app # to avoid code/route duplication and accidental availability on port 6002. app = FastAPI( title="E-Commerce Indexer API", description="Dedicated indexing service for SearchEngine", version="1.0.0", docs_url="/docs", redoc_url="/redoc", openapi_url="/openapi.json", ) @app.on_event("startup") async def startup_event(): es_host = os.getenv("ES_HOST", "http://localhost:9200") logger.info("Starting Indexer API service") logger.info(f"Elasticsearch Host: {es_host}") try: init_indexer_service(es_host=es_host) logger.info("Indexer service initialized successfully") except Exception as e: logger.error(f"Failed to initialize indexer service: {e}", exc_info=True) logger.warning("Indexer service will start but may not function correctly") @app.on_event("shutdown") async def shutdown_event(): logger.info("Shutting down Indexer API service") @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): """Global exception handler with basic logging.""" client_ip = request.client.host if request.client else "unknown" logger.error(f"Unhandled exception from {client_ip}: {exc}", exc_info=True) return JSONResponse( status_code=500, content={ "error": "Internal server error", "detail": "An unexpected error occurred in indexer service.", "timestamp": int(time.time()), }, ) @app.get("/health") async def health_check(): """Simple health check for indexer service.""" try: # ensure ES is reachable (best-effort) if _es_client is None: raise RuntimeError("ES client is not initialized") return { "status": "healthy", "services": { "elasticsearch": "connected", "incremental_indexer": "initialized" if _incremental_service else "unavailable", "bulk_indexer": "initialized" if _bulk_indexing_service else "unavailable", }, "timestamp": int(time.time()), } except Exception as e: logger.error(f"Indexer health check failed: {e}") return JSONResponse( status_code=503, content={ "status": "unhealthy", "error": str(e), "timestamp": int(time.time()), }, ) # Mount the single source of truth indexer routes app.include_router(indexer_routes.router) if __name__ == "__main__": import argparse import uvicorn parser = argparse.ArgumentParser(description="Start Indexer API service") parser.add_argument("--host", default="0.0.0.0", help="Host to bind to") parser.add_argument("--port", type=int, default=6004, help="Port to bind to") parser.add_argument("--es-host", default="http://localhost:9200", help="Elasticsearch host") parser.add_argument("--reload", action="store_true", help="Enable auto-reload") args = parser.parse_args() os.environ["ES_HOST"] = args.es_host uvicorn.run( "api.indexer_app:app", host=args.host, port=args.port, reload=args.reload, )