dashboard-nanobot/backend/bootstrap/app_runtime.py

53 lines
2.3 KiB
Python
Raw Normal View History

2026-03-31 04:31:47 +00:00
import asyncio
from fastapi import FastAPI
from sqlmodel import Session, select
2026-04-04 16:29:37 +00:00
from core.cache import cache
2026-03-31 04:31:47 +00:00
from core.database import engine, init_database
from core.docker_instance import docker_manager
2026-04-13 08:36:58 +00:00
from core.speech_service import inspect_speech_model_status
2026-03-31 04:31:47 +00:00
from core.settings import DATABASE_URL_DISPLAY, REDIS_ENABLED
from models.bot import BotInstance
2026-04-13 10:10:25 +00:00
from services.default_assets_service import validate_runtime_data_assets
2026-04-13 08:36:58 +00:00
from services.platform_service import get_speech_runtime_settings, prune_expired_activity_events
2026-03-31 04:31:47 +00:00
from services.runtime_service import docker_callback, set_main_loop
2026-04-04 16:29:37 +00:00
def reload_platform_runtime(app: FastAPI) -> None:
cache.delete_prefix("")
speech_service = getattr(app.state, "speech_service", None)
if speech_service is not None and hasattr(speech_service, "reset_runtime"):
speech_service.reset_runtime()
2026-03-31 04:31:47 +00:00
def register_app_runtime(app: FastAPI) -> None:
@app.on_event("startup")
async def _on_startup() -> None:
2026-04-13 12:07:07 +00:00
redis_state = "Disabled"
if REDIS_ENABLED:
redis_state = "Connected" if cache.enabled else f"Unavailable ({cache.status})"
2026-03-31 04:31:47 +00:00
print(
2026-04-13 12:07:07 +00:00
f"🚀 Dashboard Backend 启动中... (DB: {DATABASE_URL_DISPLAY}, REDIS: {redis_state})"
2026-03-31 04:31:47 +00:00
)
current_loop = asyncio.get_running_loop()
app.state.main_loop = current_loop
set_main_loop(current_loop)
2026-04-13 10:10:25 +00:00
validate_runtime_data_assets()
print("[init] data 目录校验通过")
2026-03-31 04:31:47 +00:00
init_database()
with Session(engine) as session:
prune_expired_activity_events(session, force=True)
bots = session.exec(select(BotInstance)).all()
for bot in bots:
docker_manager.ensure_monitor(bot.id, docker_callback)
2026-04-13 08:36:58 +00:00
speech_settings = get_speech_runtime_settings()
model_status = inspect_speech_model_status()
if speech_settings["enabled"]:
if model_status["ready"]:
print(f"🎙️ 语音识别模型就绪: {model_status['resolved_path']}")
else:
hint = f",请将模型文件放到 {model_status['expected_path']}" if model_status["expected_path"] else ""
print(f"⚠️ 语音识别模型未就绪: {model_status['message']}{hint}")
2026-03-31 04:31:47 +00:00
print("✅ 启动自检完成")