Blame view

api/routes/admin.py 4.51 KB
be52af70   tangwang   first commit
1
2
3
4
  """
  Admin API routes for configuration and management.
  """
  
26b910bd   tangwang   refactor service ...
5
  from fastapi import APIRouter, HTTPException, Request
be52af70   tangwang   first commit
6
7
8
  from typing import Dict
  
  from ..models import HealthResponse, ErrorResponse
26b910bd   tangwang   refactor service ...
9
  from indexer.mapping_generator import get_tenant_index_name
be52af70   tangwang   first commit
10
11
12
13
14
15
16
17
18
19
20
21
  
  router = APIRouter(prefix="/admin", tags=["admin"])
  
  
  @router.get("/health", response_model=HealthResponse)
  async def health_check():
      """
      Health check endpoint.
  
      Returns service status and Elasticsearch connectivity.
      """
      try:
a406638e   tangwang   up
22
          from ..app import get_es_client, get_config
be52af70   tangwang   first commit
23
24
25
26
27
28
29
30
31
  
          es_client = get_es_client()
          config = get_config()
  
          # Check ES connectivity
          es_status = "connected" if es_client.ping() else "disconnected"
  
          return HealthResponse(
              status="healthy" if es_status == "connected" else "unhealthy",
4d824a77   tangwang   所有租户共用一套统一配置.tena...
32
              elasticsearch=es_status
be52af70   tangwang   first commit
33
34
35
36
37
          )
  
      except Exception as e:
          return HealthResponse(
              status="unhealthy",
4d824a77   tangwang   所有租户共用一套统一配置.tena...
38
              elasticsearch="error"
be52af70   tangwang   first commit
39
40
41
42
43
44
          )
  
  
  @router.get("/config")
  async def get_configuration():
      """
37e994bb   tangwang   命名修改、代码清理
45
      Get current search configuration (sanitized).
be52af70   tangwang   first commit
46
47
      """
      try:
a406638e   tangwang   up
48
          from ..app import get_config
be52af70   tangwang   first commit
49
50
51
52
  
          config = get_config()
  
          return {
be52af70   tangwang   first commit
53
              "es_index_name": config.es_index_name,
33839b37   tangwang   属性值参与搜索:
54
              "num_field_boosts": len(config.field_boosts),
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
55
56
57
              "multilingual_fields": config.query_config.multilingual_fields,
              "shared_fields": config.query_config.shared_fields,
              "core_multilingual_fields": config.query_config.core_multilingual_fields,
be52af70   tangwang   first commit
58
59
60
61
62
              "supported_languages": config.query_config.supported_languages,
              "ranking_expression": config.ranking.expression,
              "spu_enabled": config.spu_config.enabled
          }
  
26b910bd   tangwang   refactor service ...
63
64
      except HTTPException:
          raise
be52af70   tangwang   first commit
65
66
67
68
69
70
71
72
73
74
75
76
77
      except Exception as e:
          raise HTTPException(status_code=500, detail=str(e))
  
  
  @router.post("/rewrite-rules")
  async def update_rewrite_rules(rules: Dict[str, str]):
      """
      Update query rewrite rules.
  
      Args:
          rules: Dictionary of pattern -> replacement mappings
      """
      try:
a406638e   tangwang   up
78
          from ..app import get_query_parser
be52af70   tangwang   first commit
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
  
          query_parser = get_query_parser()
          query_parser.update_rewrite_rules(rules)
  
          return {
              "status": "success",
              "message": f"Updated {len(rules)} rewrite rules"
          }
  
      except Exception as e:
          raise HTTPException(status_code=500, detail=str(e))
  
  
  @router.get("/rewrite-rules")
  async def get_rewrite_rules():
      """
      Get current query rewrite rules.
      """
      try:
a406638e   tangwang   up
98
          from ..app import get_query_parser
be52af70   tangwang   first commit
99
100
101
102
103
104
105
106
107
108
109
110
111
112
  
          query_parser = get_query_parser()
          rules = query_parser.get_rewrite_rules()
  
          return {
              "rules": rules,
              "count": len(rules)
          }
  
      except Exception as e:
          raise HTTPException(status_code=500, detail=str(e))
  
  
  @router.get("/stats")
26b910bd   tangwang   refactor service ...
113
  async def get_index_stats(http_request: Request):
be52af70   tangwang   first commit
114
115
116
117
      """
      Get index statistics.
      """
      try:
26b910bd   tangwang   refactor service ...
118
119
          from urllib.parse import parse_qs
          from ..app import get_es_client
be52af70   tangwang   first commit
120
121
  
          es_client = get_es_client()
26b910bd   tangwang   refactor service ...
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  
          tenant_id = http_request.headers.get("X-Tenant-ID")
          if not tenant_id:
              query_string = http_request.url.query
              if query_string:
                  params = parse_qs(query_string)
                  tenant_id = params.get("tenant_id", [None])[0]
  
          if not tenant_id:
              raise HTTPException(
                  status_code=400,
                  detail="tenant_id is required. Provide it via header 'X-Tenant-ID' or query parameter 'tenant_id'",
              )
  
          index_name = get_tenant_index_name(tenant_id)
          if not es_client.client.indices.exists(index=index_name):
              raise HTTPException(
                  status_code=404,
                  detail=f"Tenant index not found: {index_name}",
              )
be52af70   tangwang   first commit
142
143
  
          # Get document count
26b910bd   tangwang   refactor service ...
144
          doc_count = es_client.client.count(index=index_name).get("count", 0)
be52af70   tangwang   first commit
145
146
147
  
          # Get index size (if available)
          try:
26b910bd   tangwang   refactor service ...
148
149
              stats = es_client.client.indices.stats(index=index_name)
              size_in_bytes = stats["indices"][index_name]["total"]["store"]["size_in_bytes"]
be52af70   tangwang   first commit
150
              size_mb = size_in_bytes / (1024 * 1024)
26b910bd   tangwang   refactor service ...
151
          except Exception:
be52af70   tangwang   first commit
152
153
154
              size_mb = None
  
          return {
26b910bd   tangwang   refactor service ...
155
156
              "tenant_id": str(tenant_id),
              "index_name": index_name,
be52af70   tangwang   first commit
157
158
159
160
161
162
              "document_count": doc_count,
              "size_mb": round(size_mb, 2) if size_mb else None
          }
  
      except Exception as e:
          raise HTTPException(status_code=500, detail=str(e))