LifeVta commited on
Commit
a01eff8
·
verified ·
1 Parent(s): bfd375a

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +65 -70
app/main.py CHANGED
@@ -1,20 +1,21 @@
1
  """Grok2API application entry point.
2
 
3
  Start with:
4
- uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app
5
 
6
  Multi-worker notes:
7
- - All workers run a lightweight account-directory sync loop (ACCOUNT_SYNC_INTERVAL env, default 30 s).
8
- - Only the worker that wins the advisory file lock runs the heavy AccountRefreshScheduler.
9
- On Linux/macOS this uses fcntl.flock; on Windows it falls back to "always be leader"
10
- (i.e. every worker runs the scheduler — acceptable because Windows deployments are
11
- almost always single-worker anyway).
12
  """
13
 
14
  import asyncio
15
  import os
16
  import platform
17
  import sys
 
18
  from contextlib import asynccontextmanager
19
  from pathlib import Path
20
 
@@ -99,6 +100,18 @@ setup_logging(
99
 
100
  @asynccontextmanager
101
  async def lifespan(app: FastAPI):
 
 
 
 
 
 
 
 
 
 
 
 
102
  # 1. Load configuration.
103
  await _config.load()
104
  reload_logging(
@@ -154,14 +167,6 @@ async def lifespan(app: FastAPI):
154
  app.state.directory = directory
155
 
156
  # 3. Account directory sync loop — all workers, lightweight incremental pull.
157
- # Keeps each worker's in-memory table eventually consistent with the repo.
158
- #
159
- # Adaptive interval strategy:
160
- # - After detecting changes → re-check in ACCOUNT_SYNC_ACTIVE_INTERVAL (default 3 s)
161
- # so rapid back-to-back writes (bulk import, refresh cycle) are picked up quickly.
162
- # - After N idle polls → back off toward ACCOUNT_SYNC_INTERVAL (default 30 s).
163
- # scan_changes() is an indexed DB query that costs < 1 ms when nothing changed,
164
- # so polling aggressively after a change is essentially free.
165
  _SYNC_IDLE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_INTERVAL", "30"))
166
  _SYNC_ACTIVE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_ACTIVE_INTERVAL", "3"))
167
  _SYNC_IDLE_AFTER = 5 # consecutive empty polls before returning to idle pace
@@ -187,13 +192,6 @@ async def lifespan(app: FastAPI):
187
  sync_task = asyncio.create_task(_sync_loop(), name="account-dir-sync")
188
 
189
  # 4. Account refresh scheduler — only the leader worker.
190
- # Uses an advisory file lock so exactly one process runs the heavy
191
- # upstream quota-fetch loop regardless of worker count.
192
- #
193
- # ``account.refresh.enabled`` selects between two independent runtime
194
- # strategies:
195
- # - true → "quota" selector + scheduler running (default).
196
- # - false → "random" selector + scheduler idle (no upstream probing).
197
  from app.control.account.refresh import AccountRefreshService
198
 
199
  refresh_enabled = _config.get_bool("account.refresh.enabled", False)
@@ -243,7 +241,7 @@ async def lifespan(app: FastAPI):
243
  if is_leader:
244
  proxy_scheduler.start()
245
 
246
- # 6. Console 配额窗口自动重置任务(轻量巡检,每30秒扫描一次过期窗口)
247
  _CONSOLE_RESET_INTERVAL = 30 # 秒
248
 
249
  async def _console_reset_loop() -> None:
@@ -260,9 +258,7 @@ async def lifespan(app: FastAPI):
260
  _console_reset_loop(), name="console-quota-reset"
261
  ) if is_leader else None
262
 
263
- # 7. Console 429 EXPIRED 账号自动恢复任务(每10分钟巡检一次)
264
- # 恢复条件:状态 EXPIRED + 原因 console_429_threshold_exceeded
265
- # + usage_use_count > 5 + expired_at <= now - 1小时
266
  _CONSOLE_RECOVERY_INTERVAL = 600 # 10 分钟
267
 
268
  async def _console_recovery_loop() -> None:
@@ -279,6 +275,30 @@ async def lifespan(app: FastAPI):
279
  _console_recovery_loop(), name="console-expired-recovery"
280
  ) if is_leader else None
281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  logger.info("application startup completed")
283
  yield
284
 
@@ -286,6 +306,14 @@ async def lifespan(app: FastAPI):
286
  # Shutdown
287
  # -----------
288
  logger.info("application shutdown started")
 
 
 
 
 
 
 
 
289
  if console_reset_task is not None:
290
  console_reset_task.cancel()
291
  try:
@@ -324,51 +352,18 @@ async def lifespan(app: FastAPI):
324
  def create_app() -> FastAPI:
325
  openapi_tags = [
326
  {"name": "OpenAI - Models", "description": "Model discovery endpoints."},
327
- {
328
- "name": "OpenAI - Chat",
329
- "description": "Chat Completions compatible endpoints.",
330
- },
331
- {
332
- "name": "OpenAI - Responses",
333
- "description": "Responses API compatible endpoints.",
334
- },
335
- {
336
- "name": "OpenAI - Images",
337
- "description": "Image generation and image edit endpoints.",
338
- },
339
- {
340
- "name": "OpenAI - Videos",
341
- "description": "Video job creation and retrieval endpoints.",
342
- },
343
- {
344
- "name": "OpenAI - Files",
345
- "description": "Locally cached media file endpoints.",
346
- },
347
- {
348
- "name": "Anthropic - Messages",
349
- "description": "Anthropic Messages API compatible endpoints.",
350
- },
351
- {
352
- "name": "Admin - System",
353
- "description": "Admin system status and runtime configuration endpoints.",
354
- },
355
- {
356
- "name": "Admin - Tokens",
357
- "description": "Admin account token management endpoints.",
358
- },
359
  {"name": "Admin - Batch", "description": "Admin batch operation endpoints."},
360
- {
361
- "name": "Admin - Assets",
362
- "description": "Admin online asset management endpoints.",
363
- },
364
- {
365
- "name": "Admin - Cache",
366
- "description": "Admin local cache management endpoints.",
367
- },
368
- {
369
- "name": "WebUI - System",
370
- "description": "WebUI authentication and system endpoints.",
371
- },
372
  {"name": "WebUI - Chat", "description": "WebUI chat API endpoints."},
373
  {"name": "WebUI - Voice", "description": "WebUI voice API endpoints."},
374
  ]
@@ -481,4 +476,4 @@ if __name__ == "__main__":
481
  "direct startup is disabled: use "
482
  "uv run granian --interface asgi --host 0.0.0.0 --port 8000 app.main:app"
483
  )
484
- raise SystemExit(1)
 
1
  """Grok2API application entry point.
2
 
3
  Start with:
4
+ uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app
5
 
6
  Multi-worker notes:
7
+ - All workers run a lightweight account-directory sync loop (ACCOUNT_SYNC_INTERVAL env, default 30 s).
8
+ - Only the worker that wins the advisory file lock runs the heavy AccountRefreshScheduler.
9
+ On Linux/macOS this uses fcntl.flock; on Windows it falls back to "always be leader"
10
+ (i.e. every worker runs the scheduler — acceptable because Windows deployments are
11
+ almost always single-worker anyway).
12
  """
13
 
14
  import asyncio
15
  import os
16
  import platform
17
  import sys
18
+ import base64
19
  from contextlib import asynccontextmanager
20
  from pathlib import Path
21
 
 
100
 
101
  @asynccontextmanager
102
  async def lifespan(app: FastAPI):
103
+ # 🌟 核心新增逻辑[1/3]:开机冷启动自愈,检查并从 Secrets 中恢复整个账号数据库
104
+ target_db = data_path("accounts.db")
105
+ stored_db_b64 = os.getenv("STORED_DB_B64")
106
+
107
+ if stored_db_b64 and (not target_db.exists() or target_db.stat().st_size == 0):
108
+ try:
109
+ target_db.parent.mkdir(parents=True, exist_ok=True)
110
+ target_db.write_bytes(base64.b64decode(stored_db_b64.strip()))
111
+ logger.info("[🎉 自动化自愈] 已成功从隐藏加密环境变量还原 287 个账号数据库卷!")
112
+ except Exception as e:
113
+ logger.error("[❌ 自动化自愈失败] 解析或写入账号数据库故障: {}", e)
114
+
115
  # 1. Load configuration.
116
  await _config.load()
117
  reload_logging(
 
167
  app.state.directory = directory
168
 
169
  # 3. Account directory sync loop — all workers, lightweight incremental pull.
 
 
 
 
 
 
 
 
170
  _SYNC_IDLE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_INTERVAL", "30"))
171
  _SYNC_ACTIVE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_ACTIVE_INTERVAL", "3"))
172
  _SYNC_IDLE_AFTER = 5 # consecutive empty polls before returning to idle pace
 
192
  sync_task = asyncio.create_task(_sync_loop(), name="account-dir-sync")
193
 
194
  # 4. Account refresh scheduler — only the leader worker.
 
 
 
 
 
 
 
195
  from app.control.account.refresh import AccountRefreshService
196
 
197
  refresh_enabled = _config.get_bool("account.refresh.enabled", False)
 
241
  if is_leader:
242
  proxy_scheduler.start()
243
 
244
+ # 6. Console 配额窗口自动重置任务
245
  _CONSOLE_RESET_INTERVAL = 30 # 秒
246
 
247
  async def _console_reset_loop() -> None:
 
258
  _console_reset_loop(), name="console-quota-reset"
259
  ) if is_leader else None
260
 
261
+ # 7. Console 429 EXPIRED 账号自动恢复任务
 
 
262
  _CONSOLE_RECOVERY_INTERVAL = 600 # 10 分钟
263
 
264
  async def _console_recovery_loop() -> None:
 
275
  _console_recovery_loop(), name="console-expired-recovery"
276
  ) if is_leader else None
277
 
278
+ # 🌟 核心新增逻辑[2/3]:轻量级后台实时监控任务(检测账号导入并序列化打印)
279
+ async def _db_backup_monitor_loop():
280
+ last_captured_size = 0
281
+ if target_db.exists():
282
+ last_captured_size = target_db.stat().st_size
283
+
284
+ while True:
285
+ await asyncio.sleep(15) # 每 15 秒轻量检测一次文件变动
286
+ try:
287
+ if target_db.exists():
288
+ current_size = target_db.stat().st_size
289
+ if current_size > 0 and current_size != last_captured_size:
290
+ last_captured_size = current_size
291
+ b64_data = base64.b64encode(target_db.read_bytes()).decode("utf-8")
292
+ print(f"\n\n============== 📢 [Grok2API 账号池发生更新] ==============\n"
293
+ f"检测到你导入或更新了账号,请复制下方整串密文到系统 Space 的 Settings -> Variables and secrets 里,\n"
294
+ f"新建一个隐藏秘密(Secret),命名为: STORED_DB_B64\n\n"
295
+ f"{b64_data}\n"
296
+ f"===========================================================\n\n", flush=True)
297
+ except Exception:
298
+ pass
299
+
300
+ backup_monitor_task = asyncio.create_task(_db_backup_monitor_loop(), name="db-backup-monitor")
301
+
302
  logger.info("application startup completed")
303
  yield
304
 
 
306
  # Shutdown
307
  # -----------
308
  logger.info("application shutdown started")
309
+
310
+ # 🌟 核心新增逻辑[3/3]:注销备份任务
311
+ backup_monitor_task.cancel()
312
+ try:
313
+ await backup_monitor_task
314
+ except asyncio.CancelledError:
315
+ pass
316
+
317
  if console_reset_task is not None:
318
  console_reset_task.cancel()
319
  try:
 
352
  def create_app() -> FastAPI:
353
  openapi_tags = [
354
  {"name": "OpenAI - Models", "description": "Model discovery endpoints."},
355
+ {"name": "OpenAI - Chat", "description": "Chat Completions compatible endpoints."},
356
+ {"name": "OpenAI - Responses", "description": "Responses API compatible endpoints."},
357
+ {"name": "OpenAI - Images", "description": "Image generation and image edit endpoints."},
358
+ {"name": "OpenAI - Videos", "description": "Video job creation and retrieval endpoints."},
359
+ {"name": "OpenAI - Files", "description": "Locally cached media file endpoints."},
360
+ {"name": "Anthropic - Messages", "description": "Anthropic Messages API compatible endpoints."},
361
+ {"name": "Admin - System", "description": "Admin system status and runtime configuration endpoints."},
362
+ {"name": "Admin - Tokens", "description": "Admin account token management endpoints."},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  {"name": "Admin - Batch", "description": "Admin batch operation endpoints."},
364
+ {"name": "Admin - Assets", "description": "Admin online asset management endpoints."},
365
+ {"name": "Admin - Cache", "description": "Admin local cache management endpoints."},
366
+ {"name": "WebUI - System", "description": "WebUI authentication and system endpoints."},
 
 
 
 
 
 
 
 
 
367
  {"name": "WebUI - Chat", "description": "WebUI chat API endpoints."},
368
  {"name": "WebUI - Voice", "description": "WebUI voice API endpoints."},
369
  ]
 
476
  "direct startup is disabled: use "
477
  "uv run granian --interface asgi --host 0.0.0.0 --port 8000 app.main:app"
478
  )
479
+ raise SystemExit(1)