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
|
"""
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__))))
|
86d8358b
tangwang
config optimize
|
41
|
from config import get_app_config # noqa: E402
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
42
43
44
45
|
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
|
5b8f58c0
tangwang
sugg
|
46
|
from suggestion import SuggestionIndexBuilder # noqa: E402
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
47
|
from .routes import indexer as indexer_routes # noqa: E402
|
5b8f58c0
tangwang
sugg
|
48
49
50
51
52
53
|
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
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
54
55
56
|
_es_client: Optional[ESClient] = None
|
86d8358b
tangwang
config optimize
|
57
|
_app_config = None
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
58
59
|
_incremental_service: Optional[IncrementalIndexerService] = None
_bulk_indexing_service: Optional[BulkIndexingService] = None
|
5b8f58c0
tangwang
sugg
|
60
|
_suggestion_builder: Optional[SuggestionIndexBuilder] = None
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
61
62
63
64
65
66
67
68
69
|
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.
"""
|
86d8358b
tangwang
config optimize
|
70
|
global _es_client, _app_config, _incremental_service, _bulk_indexing_service, _suggestion_builder
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
71
72
73
74
75
76
|
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...")
|
86d8358b
tangwang
config optimize
|
77
|
_app_config = get_app_config()
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
78
79
80
|
logger.info("Configuration loaded")
# Get ES credentials
|
86d8358b
tangwang
config optimize
|
81
82
|
es_username = _app_config.infrastructure.elasticsearch.username
es_password = _app_config.infrastructure.elasticsearch.password
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
# 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)
|
86d8358b
tangwang
config optimize
|
98
99
100
101
102
103
|
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
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
104
105
106
107
108
109
110
111
112
113
114
115
116
|
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)
|
5b8f58c0
tangwang
sugg
|
117
|
_suggestion_builder = SuggestionIndexBuilder(es_client=_es_client, db_engine=db_engine)
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
118
119
120
121
|
set_indexer_services(
incremental_service=_incremental_service,
bulk_indexing_service=_bulk_indexing_service,
)
|
5b8f58c0
tangwang
sugg
|
122
|
set_suggestion_builder(_suggestion_builder)
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
123
124
125
126
127
128
129
130
131
132
133
134
|
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
|
135
136
|
raise RuntimeError(
"Database config incomplete for indexer. "
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
137
138
|
f"Missing: {', '.join(missing)}"
)
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
139
140
141
142
143
144
145
146
147
148
|
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
项目名称和部署路径修改
|
149
|
description="Dedicated indexing service for saas-search",
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
150
151
152
153
154
155
156
157
158
|
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 的默认线程池调...
|
159
160
161
162
163
164
165
166
167
|
# 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")
|
86d8358b
tangwang
config optimize
|
168
|
es_host = get_app_config().infrastructure.elasticsearch.host
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
169
170
171
172
173
|
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
|
174
175
176
177
|
# Eager warmup: build per-tenant transformer bundles at startup to avoid
# first-request latency (config/provider/encoder + transformer wiring).
try:
|
86d8358b
tangwang
config optimize
|
178
|
if _incremental_service is not None and _app_config is not None:
|
cc11ae04
tangwang
cnclip
|
179
|
tenants = []
|
86d8358b
tangwang
config optimize
|
180
181
182
|
tmap = _app_config.tenants.tenants
if isinstance(tmap, dict):
tenants = [str(k) for k in tmap.keys()]
|
cc11ae04
tangwang
cnclip
|
183
184
185
|
# If no explicit tenants configured, skip warmup.
if tenants:
warm = _incremental_service.warmup_transformers(tenants)
|
ed948666
tangwang
tidy
|
186
187
|
if warm.get("failed"):
raise RuntimeError(f"Indexer warmup failed: {warm['failed']}")
|
cc11ae04
tangwang
cnclip
|
188
189
190
191
|
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
|
192
193
|
logger.error("Indexer warmup failed: %s", e, exc_info=True)
raise
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
194
195
|
except Exception as e:
logger.error(f"Failed to initialize indexer service: {e}", exc_info=True)
|
ed948666
tangwang
tidy
|
196
|
raise
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
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
|
@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
|
224
|
# ensure ES is reachable
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
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
|
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)
|
5b8f58c0
tangwang
sugg
|
250
251
|
# Mount suggestion indexing routes (full + incremental)
app.include_router(suggestion_indexer_routes.router)
|
bb9c626c
tangwang
搜索服务(6002)不再初始化/挂...
|
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
|
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,
)
|