Fix env save-and-restart by deferring PM2 restart until after HTTP response.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-07-13 10:54:48 +08:00
parent c4753ffb89
commit 1bda78ceb2
5 changed files with 69 additions and 27 deletions
+26 -1
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import os
import shlex
import subprocess
import sys
from typing import Any
@@ -23,10 +24,34 @@ def resolve_pm2_app_name(exchange_key: str) -> str:
return default_pm2_app_name(exchange_key)
def restart_instance_pm2(exchange_key: str) -> dict[str, Any]:
def schedule_pm2_restart(app_name: str, *, delay_seconds: float = 1.0) -> dict[str, Any]:
"""延迟触发 PM2 重启,便于 HTTP 响应先返回(避免重启当前进程导致请求中断)."""
if not sys.platform.startswith("linux"):
return {"ok": False, "msg": "仅 Linux 服务器支持 PM2 重启", "app": app_name}
if not (app_name or "").strip():
return {"ok": False, "msg": "未指定 PM2 应用名", "app": app_name}
app_name = app_name.strip()
try:
cmd = f"sleep {delay_seconds} && exec pm2 restart {shlex.quote(app_name)} --update-env"
subprocess.Popen(
["bash", "-c", cmd],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
return {"ok": True, "app": app_name, "msg": "重启已触发", "deferred": True}
except FileNotFoundError:
return {"ok": False, "msg": "未找到 bash 或 pm2 命令", "app": app_name}
except Exception as e:
return {"ok": False, "msg": str(e), "app": app_name}
def restart_instance_pm2(exchange_key: str, *, defer: bool = False) -> dict[str, Any]:
if not sys.platform.startswith("linux"):
return {"ok": False, "msg": "仅 Linux 服务器支持 PM2 重启", "app": None}
app_name = resolve_pm2_app_name(exchange_key)
if defer:
return schedule_pm2_restart(app_name)
try:
proc = subprocess.run(
["pm2", "restart", app_name, "--update-env"],