Blame view

api/indexer_app.py 9.33 KB
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
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
  """
  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
          ]
ed948666   tangwang   tidy
127
128
          raise RuntimeError(
              "Database config incomplete for indexer. "
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
129
130
              f"Missing: {', '.join(missing)}"
          )
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
131
132
133
134
135
136
137
138
139
140
  
      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",
a7920e17   tangwang   项目名称和部署路径修改
141
      description="Dedicated indexing service for saas-search",
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
142
143
144
145
146
147
148
149
150
      version="1.0.0",
      docs_url="/docs",
      redoc_url="/redoc",
      openapi_url="/openapi.json",
  )
  
  
  @app.on_event("startup")
  async def startup_event():
f62a541c   tangwang   将 uvicorn 的默认线程池调...
151
152
153
154
155
156
157
158
159
      # 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")
      
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
160
161
162
163
164
165
      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")
cc11ae04   tangwang   cnclip
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
  
          # 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 _config is not None:
                  tenants = []
                  # config.tenant_config shape: {"default": {...}, "tenants": {"1": {...}, ...}}
                  tc = getattr(_config, "tenant_config", None) or {}
                  if isinstance(tc, dict):
                      tmap = tc.get("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)
ed948666   tangwang   tidy
181
182
                      if warm.get("failed"):
                          raise RuntimeError(f"Indexer warmup failed: {warm['failed']}")
cc11ae04   tangwang   cnclip
183
184
185
186
                      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:
ed948666   tangwang   tidy
187
188
              logger.error("Indexer warmup failed: %s", e, exc_info=True)
              raise
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
189
190
      except Exception as e:
          logger.error(f"Failed to initialize indexer service: {e}", exc_info=True)
ed948666   tangwang   tidy
191
          raise
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
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
  
  
  @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:
ed948666   tangwang   tidy
219
          # ensure ES is reachable
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
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
          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,
      )