fix(runtime): distinguish event loop owners (#6425)

Co-authored-by: jxxghp <jxxghp@gmail.com>
This commit is contained in:
InfinityPacer
2026-08-23 21:40:23 +08:00
committed by GitHub
co-authored by jxxghp
parent f64030a074
commit eb36e6be91
4 changed files with 76 additions and 17 deletions
+6 -3
View File
@@ -513,6 +513,7 @@ async def lifespan(app: FastAPI):
health = get_application_health(app)
health.begin_startup()
main_loop = asyncio.get_running_loop()
main_loop_owner: object | None = None
enabled_components: tuple[LifecycleComponent, ...] = ()
started_component_names: set[str] = set()
active_start_component: LifecycleComponent | None = None
@@ -522,7 +523,7 @@ async def lifespan(app: FastAPI):
safe_mode=settings.MOVIEPILOT_SAFE_MODE,
)
print("Starting up...")
global_vars.set_loop(main_loop)
main_loop_owner = global_vars.set_loop(main_loop)
components = build_lifecycle_components(app)
enabled_components = tuple(
component
@@ -567,7 +568,8 @@ async def lifespan(app: FastAPI):
except Exception as cleanup_error:
logger.error(f"启动失败后的生命周期清理失败:{cleanup_error}")
finally:
global_vars.clear_loop(main_loop)
if main_loop_owner is not None:
global_vars.clear_loop(main_loop_owner)
raise
try:
# 在此处 yield,表示应用已经启动,控制权交回 FastAPI 主事件循环
@@ -585,4 +587,5 @@ async def lifespan(app: FastAPI):
# 日志最后关闭,确保其他组件的收尾信息已写入文件
LoggerManager.shutdown()
finally:
global_vars.clear_loop(main_loop)
if main_loop_owner is not None:
global_vars.clear_loop(main_loop_owner)