diff --git a/src/py/extra/server.py b/src/py/extra/server.py index 57f1fa8..81e46dd 100644 --- a/src/py/extra/server.py +++ b/src/py/extra/server.py @@ -4,6 +4,7 @@ from dataclasses import dataclass import socket import asyncio +import threading from .utils.logging import exception, info, warning, event from .utils.codec import BytesTransform from .utils.limits import LimitType, unlimit @@ -53,6 +54,7 @@ class ServerOptions(NamedTuple): keepalive: float = 3_600 logRequests: bool = True condition: Callable[[], bool] | None = None + stopSignals: bool = True OPTIONS: ServerOptions = ServerOptions() @@ -371,9 +373,15 @@ async def Serve( # Manage server state state = ServerState() - # Registers handlers for signals and exception (so that we log them) - loop.add_signal_handler(SIGINT, lambda: state.stop()) - loop.add_signal_handler(SIGTERM, lambda: state.stop()) + # Registers handlers for signals and exception (so that we log them). Note + # that we'll get a `set_wakeup_fd only works in main thread of the main interpreter` + # when this is not run out of the main thread. + if ( + options.stopSignals + and threading.current_thread() is threading.main_thread() + ): + loop.add_signal_handler(SIGINT, lambda: state.stop()) + loop.add_signal_handler(SIGTERM, lambda: state.stop()) loop.set_exception_handler(state.onException) info(