indexer_app.py 9.55 KB
"""
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 import get_app_config  # 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 suggestion import SuggestionIndexBuilder  # noqa: E402
from .routes import indexer as indexer_routes  # noqa: E402
from .routes import suggestion_indexer as suggestion_indexer_routes  # noqa: E402
from .service_registry import (
    set_es_client,
    set_indexer_services,
    set_suggestion_builder,
)  # noqa: E402


_es_client: Optional[ESClient] = None
_app_config = None
_incremental_service: Optional[IncrementalIndexerService] = None
_bulk_indexing_service: Optional[BulkIndexingService] = None
_suggestion_builder: Optional[SuggestionIndexBuilder] = 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, _app_config, _incremental_service, _bulk_indexing_service, _suggestion_builder

    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...")
    _app_config = get_app_config()
    logger.info("Configuration loaded")

    # Get ES credentials
    es_username = _app_config.infrastructure.elasticsearch.username
    es_password = _app_config.infrastructure.elasticsearch.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_config = _app_config.infrastructure.database
    db_host = db_config.host
    db_port = db_config.port
    db_database = db_config.database
    db_username = db_config.username
    db_password = db_config.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)
        _suggestion_builder = SuggestionIndexBuilder(es_client=_es_client, db_engine=db_engine)
        set_indexer_services(
            incremental_service=_incremental_service,
            bulk_indexing_service=_bulk_indexing_service,
        )
        set_suggestion_builder(_suggestion_builder)
        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
        ]
        raise RuntimeError(
            "Database config incomplete for indexer. "
            f"Missing: {', '.join(missing)}"
        )

    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 saas-search",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json",
)


@app.on_event("startup")
async def startup_event():
    # Configure thread pool size for uvicorn (default is 40, set to 48)
    try:
        import anyio.to_thread
        limiter = anyio.to_thread.current_default_thread_limiter()
        limiter.total_tokens = 48
        logger.info(f"Thread pool size set to {limiter.total_tokens}")
    except Exception as e:
        logger.warning(f"Failed to set thread pool size: {e}, using default")
    
    es_host = get_app_config().infrastructure.elasticsearch.host
    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")

        # Eager warmup: build per-tenant transformer bundles at startup to avoid
        # first-request latency (config/provider/encoder + transformer wiring).
        try:
            if _incremental_service is not None and _app_config is not None:
                tenants = []
                tmap = _app_config.tenants.tenants
                if isinstance(tmap, dict):
                    tenants = [str(k) for k in tmap.keys()]
                # If no explicit tenants configured, skip warmup.
                if tenants:
                    warm = _incremental_service.warmup_transformers(tenants)
                    if warm.get("failed"):
                        raise RuntimeError(f"Indexer warmup failed: {warm['failed']}")
                    logger.info("Indexer warmup completed: %s", warm)
                else:
                    logger.info("Indexer warmup skipped (no tenant ids in config.tenant_config.tenants)")
        except Exception as e:
            logger.error("Indexer warmup failed: %s", e, exc_info=True)
            raise
    except Exception as e:
        logger.error(f"Failed to initialize indexer service: {e}", exc_info=True)
        raise


@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
        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)
# Mount suggestion indexing routes (full + incremental)
app.include_router(suggestion_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,
    )