Files
pulsewall/hub/app/runner.py
T
jmj c037b43f4a Initial commit: PulseWall hub, Android app, and protocol docs
- hub: FastAPI backend (MCP server, ADB LAN controller, bridge, storage)
- hub/web: Vue 3 admin console (device manager, screen mirror, chat workbench)
- android: Kotlin shell app with WebView stage, OTA, telemetry, keep-alive
- protocol: architecture, MCP schema, and WebSocket protocol specs
2026-11-30 07:37:34 +08:00

65 lines
1.9 KiB
Python

from __future__ import annotations
import asyncio
import contextlib
import os
import signal
from collections.abc import Generator
import uvicorn
from app.main import app
class GracefulHubServer(uvicorn.Server):
"""Triggers immediate cleanup of long-lived WS/MJPEG/SSE connections on first Ctrl+C without Python 3.13 tracebacks."""
def handle_exit(self, sig: int, frame) -> None: # type: ignore[override]
shutdown_ev = getattr(app.state, "shutdown_event", None)
adb_ctrl = getattr(app.state, "adb_controller", None)
bridge = getattr(app.state, "bridge", None)
if shutdown_ev is not None:
shutdown_ev.set()
if adb_ctrl is not None:
adb_ctrl.stop_all_streams()
try:
loop = asyncio.get_running_loop()
if bridge is not None:
loop.create_task(bridge.close_all())
except RuntimeError:
pass
super().handle_exit(sig, frame)
@contextlib.contextmanager
def capture_signals(self) -> Generator[None, None, None]:
# Override Uvicorn's capture_signals so it does NOT re-raise SIGINT after clean shutdown
# (which causes spurious CancelledError/KeyboardInterrupt tracebacks on Python 3.13 + uvloop).
original_handlers = {
sig: signal.signal(sig, self.handle_exit)
for sig in (signal.SIGINT, signal.SIGTERM)
}
try:
yield
finally:
for sig, handler in original_handlers.items():
signal.signal(sig, handler)
def main() -> None:
port = int(os.environ.get("PULSEWALL_PORT", "8765"))
config = uvicorn.Config(
app=app,
host="0.0.0.0",
port=port,
timeout_graceful_shutdown=2,
)
server = GracefulHubServer(config)
try:
server.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()