Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions src/labthings_fastapi/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

# `_thing_servers` is used as a global from `ThingServer.__init__`
from labthings_fastapi.outputs import blob
from labthings_fastapi.server._catch_uvicorn_shutdown import ServerWithShutdownHandler
from labthings_fastapi.server.config_model import (
ThingsConfig,
ThingServerConfig,
Expand Down Expand Up @@ -518,19 +519,35 @@ def thing_paths(request: Request) -> Mapping[str, str]:

return router

def serve(self, host: str = "localhost", port: int = 5000) -> None:
def serve(self, host: str = "localhost", port: int = 5000, **kwargs: Any) -> None:
r"""Run the server in `uvicorn`\ .

This method will run the server from Python, using `uvicorn.run`\ .
This is the most convenient way to run a LabThings server from Python, and
is identical to what happens when it is run from the command line.

Note that this function uses a subclass of `uvicorn.Server` in order to catch
shutdown events. This allows us to terminate active connections on the server
side, in order to shut down cleanly even if websockets or MJPEG streams are
active.

:param host: The IP address or hostname on which to serve. By default, this
is ``localhost`` which is only accessible from your computer. To serve
over a network on all available IPv4 addresses, use ``"0.0.0.0"``.
:param port: The port on which to serve. This defaults to 5000.
:param \**kwargs: Additional keyword arguments are handled as if passed
to `uvicorn.run`.
"""
uvicorn.run(self.app, host=host, port=port, ws="websockets-sansio")
config = uvicorn.Config(
self.app, host=host, port=port, ws="websockets-sansio", **kwargs
)
server = ServerWithShutdownHandler(config)
server.shutdown_callback = self.message_broker.close_streams
try:
server.run()
except KeyboardInterrupt:
# KeyboardInterrupt is used to close the server, and shouldn't propagate
pass

@contextmanager
def test_client(self) -> Iterator[TestClient]:
Expand Down
28 changes: 28 additions & 0 deletions src/labthings_fastapi/server/_catch_uvicorn_shutdown.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Subclass `uvicorn.Server` so we can hook into the shutdown event."""

import socket
from collections.abc import Awaitable, Callable
from logging import getLogger

from uvicorn import Server

logger = getLogger(__name__)


class ServerWithShutdownHandler(Server):
"""A subclass of `uvicorn.Server` that provides a shutdown hook."""

shutdown_callback: Callable[[], Awaitable[None]] | None = None

async def shutdown(self, sockets: list[socket.socket] | None = None) -> None:
"""Call the callback function before this method is called on the superclass.

:param sockets: a list of sockets that are open.
"""
try:
if self.shutdown_callback is not None:
logger.info("Awaiting shutdown callback.")
await self.shutdown_callback()
finally:
# Make sure we shut down, even if there's an error.
await super().shutdown(sockets=sockets)
5 changes: 3 additions & 2 deletions tests/test_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ def test_cli_debug_flag(mocker):
Test that using the --debug flag sets the logger level to DEBUG,
and that not using it leaves the logger level at INFO.
"""
mocker.patch("uvicorn.run")
# We don't actually want to run the server, so mock uvicorn.Server.run.
mocker.patch("uvicorn.Server.run")
# Reset logger level to INFO
reset_thing_logger()

Expand Down Expand Up @@ -211,7 +212,7 @@ def test_cli_debug_flag_with_thing(caplog, mocker):
"""
Test that using the --debug flag allows capturing debug logs during __init__.
"""
mocker.patch("uvicorn.run")
mocker.patch("uvicorn.Server.run")

# Reset logger level to INFO
reset_thing_logger()
Expand Down
99 changes: 92 additions & 7 deletions tests/test_mjpeg_stream.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import io
import logging
import os
import re
import sys
import threading
import time
from datetime import datetime
from subprocess import PIPE # noqa: S404 All subprocess commands are static strings
from unittest import mock

import anyio
import httpx2
import pytest
from anyio import from_thread, to_thread
from PIL import Image
Expand All @@ -30,12 +36,17 @@ class Telly(lt.Thing):
_stream_thread: threading.Thread
_streaming: bool = False
framerate: float = 1000
frame_limit: int = 999
frame_limit: int = 9999
frame_event: threading.Event | None = None
initial_delay: float = 0

stream = lt.outputs.MJPEGStreamDescriptor()

def __init__(self, break_shutdown: bool = False, **kwargs):
super().__init__(**kwargs)
if break_shutdown:
MessageBroker.close_streams = mock.AsyncMock()

def __enter__(self):
self._streaming = True
self._stream_thread = threading.Thread(target=self._make_images)
Expand Down Expand Up @@ -358,15 +369,89 @@ def test_mjpeg_stream_http(server: lt.ThingServer, telly: Telly):
assert telly.stream.last_frame_i == 2


@pytest.mark.slow
@pytest.mark.parametrize("broken", [False, True])
async def test_clean_shutdown_with_connected_stream(broken):
"""Check that the server closes the connection when it's shut down."""
# Because we're using a Thing defined in this module, we need to make it
# importable (in the subprocess).
# This is done by setting `PYTHONPATH` in the subprocess.
tests_folder = os.path.dirname(__file__)
path_with_tests_appended = os.pathsep.join(sys.path + [tests_folder])
env = os.environ.copy() | {"PYTHONPATH": path_with_tests_appended}
logging.info("Starting server in a subprocess...")
process = await anyio.open_process(
[
"labthings-server",
"--port",
"0",
"--json",
lt.ThingServerConfig(
things={
"telly": {
"cls": "tests.test_mjpeg_stream:Telly",
"kwargs": {"break_shutdown": broken},
}
}
).model_dump_json(),
],
env=env,
stdout=PIPE,
stderr=PIPE,
) # noqa: S607
assert process.stderr is not None
port: int | None = None
for _ in range(10):
with anyio.fail_after(2):
msg = await process.stderr.receive()
pattern = r"Uvicorn running on http://127.0.0.1:(\d+) "
match = re.search(pattern, msg.decode())
if match:
port = int(match.group(1))
break
logging.info(f"Started up successfully on port {port}")
# Connect to the MJPEG stream
client = httpx2.AsyncClient(base_url=f"http://127.0.0.1:{port}/")
async with client.stream("GET", "/telly/stream") as response:
response.raise_for_status()
# Receive 3 frames to verify it's streaming images
aiter = response.aiter_bytes()
for _ in range(3):
# Each JPEG results in 3 parts - separator, frame, and newline.
# the first one should be a separator (we'll error if it's not)
assert (await anext(aiter)).startswith(SEPARATOR)
assert_magic_bytes((await anext(aiter)))
assert (await anext(aiter)) == b"\r\n"
# Tell the server to stop while the stream is still open
process.terminate()
terminate_called = time.time()
async for _data in aiter:
# keep receiving until the stream stops or we time out
if time.time() - terminate_called > 0.1:
if broken:
# Without the graceful shutdown code, this loop will
# go on forever. Terminate it after it's run for 100ms
# to avoid a horribly long test.
break
else:
# If the stream hasn't closed within 100ms, fail the test.
raise TimeoutError("Stream is still going :(")

# Stop the server, and check it shuts down within 1s.
with anyio.fail_after(1):
await process.wait()


if __name__ == "__main__":
"""This block allows you to connect manually with a web browser.

That's helpful, because the tests above don't actually stream anything
as noted in `test_mjpeg_stream_http`.
This is intended to allow manual testing with a web browser.
The newer tests now do actually start a real server, so this isn't
as crucial as it once was.
"""
thing_server = lt.ThingServer.from_things({"telly": Telly})
telly = thing_server.things["telly"]
assert isinstance(telly, Telly)
telly.framerate = 6
telly.frame_limit = -1
tv = thing_server.things["telly"]
assert isinstance(tv, Telly)
tv.framerate = 6
tv.frame_limit = -1
thing_server.serve()
23 changes: 23 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,26 @@ def check_server(server: lt.ThingServer, debug: bool = False):
# Invalid configuration raises a TypeError, with upgrade message
with pytest.raises(TypeError, match="from_things"):
lt.ThingServer(config_dict["things"])


def test_server_serve_keyboardinterrupt(mocker):
"""Check the server closes cleanly from the command line.

When run from the command line, `KeyboardInterrupt` is raised when the
server is shut down interactively with `Ctrl` + `C`.

This test checks the exception does not propagate.
"""
server = lt.ThingServer.from_things({})
raised = False

def raise_keyboardinterrupt(*args):
nonlocal raised
raised = True
raise KeyboardInterrupt()

mocker.patch("uvicorn.Server.run", raise_keyboardinterrupt)

server.serve()

assert raised
85 changes: 85 additions & 0 deletions tests/test_server_catch_uvicorn_shutdown.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""Test the subclass that hooks in to `uvicorn.Server.shutdown`."""

from unittest.mock import call

import pytest
from fastapi import FastAPI
from uvicorn import Config

from labthings_fastapi.server._catch_uvicorn_shutdown import ServerWithShutdownHandler


async def test_serverwithshutdownhandler_shutdown_nocallback(mocker):
"""Check that shutdown is not broken if there's no callback."""
superclass_shutdown = mocker.AsyncMock()
mocker.patch("uvicorn.Server.shutdown", superclass_shutdown)
app = FastAPI()
server = ServerWithShutdownHandler(Config(app))

# By default there's no handler present: we should see no error,
# and Server.shutdown() should be called.
await server.shutdown([])
superclass_shutdown.assert_called_once_with(sockets=[])


async def test_serverwithshutdownhandler_shutdown_withcallback(mocker, caplog):
"""Check that we call the callback before the superclass function."""
mocks = mocker.AsyncMock()
mocker.patch("uvicorn.Server.shutdown", mocks.superclass_shutdown)
app = FastAPI()
server = ServerWithShutdownHandler(Config(app))

# If a handler is present, it should be called as well.
server.shutdown_callback = mocks.callback
with caplog.at_level("INFO"):
await server.shutdown([])
# Check the calls are in the correct order (callback first)
mocks.assert_has_calls([call.callback(), call.superclass_shutdown(sockets=[])])
assert caplog.record_tuples == [
(
"labthings_fastapi.server._catch_uvicorn_shutdown",
20,
"Awaiting shutdown callback.",
)
]


async def test_serverwithshutdownhandler_shutdown_withcallback_err(mocker, caplog):
"""Check that an exception in the callback still runs the superclass function."""
mocks = mocker.AsyncMock()
mocker.patch("uvicorn.Server.shutdown", mocks.superclass_shutdown)
app = FastAPI()
server = ServerWithShutdownHandler(Config(app))

async def fail():
raise RuntimeError("Callback failed.")

# If a handler is present, it should be called as well.
server.shutdown_callback = mocks.callback
mocks.callback.side_effect = fail
with pytest.raises(RuntimeError, match="Callback failed."):
await server.shutdown([])
# Check the calls are in the correct order (callback first)
# This makes sure the server shutdown routine ran as intended.
mocks.assert_has_calls([call.callback(), call.superclass_shutdown(sockets=[])])


if __name__ == "__main__":
# This block lets us test a real server with a broken callback.
# It's a pain to do this in unit tests, and I think
# `test_serverwithshutdownhandler_shutdown_withcallback_err` is
# the right thing to run. However, it was important to check it
# in situ at least once, and we may as well preserve that test.
from fastapi import FastAPI
from uvicorn import Config

async def bad_shutdown():
raise RuntimeError("Oh Dear :(")

try:
app = FastAPI()
server = ServerWithShutdownHandler(Config(app, port=0))
server.shutdown_callback = bad_shutdown
server.run()
except KeyboardInterrupt:
pass
Loading