Skip to content

Commit 59e15be

Browse files
committed
[Update] server: added server state with exception logging
1 parent a5a0873 commit 59e15be

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/py/extra/server.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from typing import Callable, NamedTuple, Any, Coroutine, Literal
22
from pathlib import Path
3+
from signal import SIGINT, SIGTERM
4+
from dataclasses import dataclass
35
import socket
46
import asyncio
57
from .utils.logging import exception, info, warning, event
@@ -17,6 +19,21 @@
1719
from .config import HOST, PORT
1820

1921

22+
@dataclass(slots=True)
23+
class ServerState:
24+
isRunning: bool = True
25+
26+
def stop(self) -> None:
27+
self.isRunning = False
28+
29+
def onException(
30+
self, loop: asyncio.AbstractEventLoop, context: dict[str, Any]
31+
) -> None:
32+
e = context.get("exception")
33+
if e:
34+
exception(e)
35+
36+
2037
class ServerOptions(NamedTuple):
2138
host: str = "0.0.0.0" # nosec: B104
2239
port: int = 8000
@@ -336,6 +353,13 @@ async def Serve(
336353
except RuntimeError:
337354
loop = asyncio.new_event_loop()
338355

356+
# Manage server state
357+
state = ServerState()
358+
# Registers handlers for signals and exception (so that we log them)
359+
loop.add_signal_handler(SIGINT, lambda: state.stop())
360+
loop.add_signal_handler(SIGTERM, lambda: state.stop())
361+
loop.set_exception_handler(state.onException)
362+
339363
info(
340364
"Extra AIO Server listening",
341365
icon="🚀",
@@ -344,7 +368,7 @@ async def Serve(
344368
)
345369

346370
try:
347-
while True:
371+
while state.isRunning:
348372
if options.condition and not options.condition():
349373
break
350374
try:

0 commit comments

Comments
 (0)