Skip to content

Commit

Permalink
hive-common: Add hive.common.socketserver.serving
Browse files Browse the repository at this point in the history
  • Loading branch information
gbenson committed Nov 9, 2024
1 parent 3ac6541 commit bc5912d
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions libs/common/hive/common/socketserver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import logging

from contextlib import contextmanager
from socketserver import BaseServer
from threading import Thread

from .units import SECONDS

logger = logging.getLogger(__name__)


@contextmanager
def serving(
server: BaseServer,
*,
shutdown_timeout: float = 30 * SECONDS,
daemon: bool = True,
) -> Thread:
"""Run a :class:`socketserver.BaseServer` in another thread.
"""
thread = Thread(target=server.serve_forever, daemon=daemon)
logger.info("%s:%s: Starting server", thread, server)
thread.start()
try:
logger.info("%s:%s: Server started", thread, server)
yield thread
finally:
logger.info("%s: %s: Stopping server", thread, server)
server.shutdown()
logger.debug("%s: Waiting for thread exit", thread)
thread.join(timeout=30 * SECONDS)
logger.info("%s: %s: Server stopped", thread, server)

0 comments on commit bc5912d

Please sign in to comment.