Skip to content

Commit

Permalink
[Update] server: added server state with exception logging
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastien committed Oct 2, 2024
1 parent a5a0873 commit 59e15be
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/py/extra/server.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from typing import Callable, NamedTuple, Any, Coroutine, Literal
from pathlib import Path
from signal import SIGINT, SIGTERM
from dataclasses import dataclass
import socket
import asyncio
from .utils.logging import exception, info, warning, event
Expand All @@ -17,6 +19,21 @@
from .config import HOST, PORT


@dataclass(slots=True)
class ServerState:
isRunning: bool = True

def stop(self) -> None:
self.isRunning = False

def onException(
self, loop: asyncio.AbstractEventLoop, context: dict[str, Any]
) -> None:
e = context.get("exception")
if e:
exception(e)


class ServerOptions(NamedTuple):
host: str = "0.0.0.0" # nosec: B104
port: int = 8000
Expand Down Expand Up @@ -336,6 +353,13 @@ async def Serve(
except RuntimeError:
loop = asyncio.new_event_loop()

# 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())
loop.set_exception_handler(state.onException)

info(
"Extra AIO Server listening",
icon="🚀",
Expand All @@ -344,7 +368,7 @@ async def Serve(
)

try:
while True:
while state.isRunning:
if options.condition and not options.condition():
break
try:
Expand Down

0 comments on commit 59e15be

Please sign in to comment.