106 lines
4.8 KiB
Python
106 lines
4.8 KiB
Python
"""统一 CyberGril 实例单进程双入口启动器(HEL-877 部署草案,本卡未执行).
|
||
|
||
HTTP 8360 与 HTTPS 8361(语音页需要 secure context 才能拿麦克风)必须共用
|
||
同一个 API 进程、同一份 app.state(epoch / chat_lock / store / 语音会话登记)。
|
||
|
||
HEL-879 收口(总管复核第 1 项):uvicorn 两个 Server 默认各自进入一次 FastAPI
|
||
lifespan,导致 epoch 1→2、Store/life/chat_lock 全部被第二次初始化替换——同一个
|
||
app 对象并不保证只初始化一次。本启动器改为:
|
||
|
||
- 应用生命周期由本启动器**独占管理且只进入一次**(`app.router.lifespan_context`);
|
||
- 两个 uvicorn Server 以 `lifespan="off"` 只负责监听,共享同一份状态;
|
||
- 任一监听退出(失败/取消/信号)先把另一个也停掉,**再**退出生命周期:
|
||
绝不出现一边还在接请求、一边已被另一个监听提前关库;循环与资源只关闭一次;
|
||
- `create_app` 的 lifespan 自带重入门卫:任何二次进入直接报错(fail-closed),
|
||
防止未来改回 auto 双 Server 时再次静默替换状态。
|
||
|
||
自签证书签发命令与回滚步骤见 docs/runbook-hel877-voice.md。
|
||
|
||
用法(部署卡执行,先 `cd` 到仓库根并激活 3.11 venv):
|
||
PYTHONPATH=src python deploy/voice/serve_dual_8360_8361.py \
|
||
--http-port 8360 --https-port 8361 \
|
||
--cert /opt/cybergril-voice-certs/cert.pem --key /opt/cybergril-voice-certs/key.pem
|
||
|
||
本地离线冒烟(不涉及任何现网/证书变更):
|
||
PYTHONPATH=src python deploy/voice/serve_dual_8360_8361.py \
|
||
--http-port 18360 --https-port 18361 --cert <本地测试证书> --key <本地测试密钥>
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import asyncio
|
||
import contextlib
|
||
import os
|
||
import sys
|
||
|
||
import uvicorn
|
||
|
||
from cybergril.api.app import create_app
|
||
|
||
|
||
async def serve(http_port: int, https_port: int, cert: str, key: str, app=None) -> None:
|
||
# ONE app object, ONE lifespan owner: both listeners share state, locks,
|
||
# epoch and the store. The uvicorn servers never run the app lifespan
|
||
# themselves (lifespan="off") — the context manager below is its only
|
||
# owner, so initialization and shutdown each happen exactly once.
|
||
if app is None:
|
||
app = create_app()
|
||
http_server = uvicorn.Server(
|
||
uvicorn.Config(app, host="0.0.0.0", port=http_port, log_level="info",
|
||
lifespan="off")
|
||
)
|
||
https_server = uvicorn.Server(
|
||
uvicorn.Config(app, host="0.0.0.0", port=https_port, ssl_certfile=cert,
|
||
ssl_keyfile=key, log_level="info", lifespan="off")
|
||
)
|
||
async with app.router.lifespan_context(app):
|
||
servers = [asyncio.create_task(http_server.serve()),
|
||
asyncio.create_task(https_server.serve())]
|
||
try:
|
||
done, pending = await asyncio.wait(servers,
|
||
return_when=asyncio.FIRST_COMPLETED)
|
||
except asyncio.CancelledError:
|
||
# The launcher itself was cancelled: stop both listeners first
|
||
# (graceful should_exit, hard cancel only as a last resort), await
|
||
# their full exit, only then let the lifespan close (and re-raise).
|
||
# No listener is ever left running without its state.
|
||
for server in (http_server, https_server):
|
||
server.should_exit = True
|
||
for task in servers:
|
||
with contextlib.suppress(asyncio.CancelledError, Exception):
|
||
await asyncio.wait_for(asyncio.shield(task), timeout=5.0)
|
||
for task in servers:
|
||
task.cancel()
|
||
with contextlib.suppress(asyncio.CancelledError, Exception):
|
||
await task
|
||
raise
|
||
# Any listener ending stops the other FIRST; only after both listeners
|
||
# have fully exited does the lifespan context above close the loop's
|
||
# resources and the store — never the other way around.
|
||
for server in (http_server, https_server):
|
||
server.should_exit = True
|
||
for task in pending:
|
||
with contextlib.suppress(asyncio.CancelledError, Exception):
|
||
await task
|
||
for task in done:
|
||
task.result() # surface the first listener's real error, after cleanup
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument("--http-port", type=int, default=8360)
|
||
parser.add_argument("--https-port", type=int, default=8361)
|
||
parser.add_argument("--cert", required=True)
|
||
parser.add_argument("--key", required=True)
|
||
parser.add_argument("--db", default=os.environ.get("CYBERGRIL_DB"))
|
||
args = parser.parse_args()
|
||
if args.db:
|
||
os.environ["CYBERGRIL_DB"] = args.db
|
||
asyncio.run(serve(args.http_port, args.https_port, args.cert, args.key))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|