Skip to content

Mjpeg graceful shutdown - #433

Open
rwb27 wants to merge 6 commits into
mjpeg-stream-refactorfrom
mjpeg-graceful-shutdown
Open

rwb27 wants to merge 6 commits into
mjpeg-stream-refactorfrom
mjpeg-graceful-shutdown

Conversation

@rwb27

@rwb27 rwb27 commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

This PR builds on #409 to shut down the MJPEG streams cleanly via the MessageBroker when the server is terminated.

Closes #313
OFM-Feature-Branch: v3-mjpeg-stream-refactor
Skip-OFM-v3-Test

This MR contains the following

  • Swaps uvicorn.run for uvicorn.Server.run and subclasses uvicorn.Server to customise shutdown behaviour.
  • Calls MessageBroker.close_streams() when the server is instructed to shut down. This closes all active MJPEG streams (and should do the same for websockets in due course).
  • Adds a test that runs a real server in a subprocess to check that it closes cleanly in test_mjpeg_stream.py.
  • Adds unit tests for the shutdown hook in its own module.

Writing the test for this prompted me to learn some new bits of anyio and has resulted in a test that is both realistic and performant (it costs about a second to start the server and I doubt we'll do better). I think it's important to have a few tests that actually start a real HTTP server, bound to a real port, and check it works correctly. Using anyio.open_process, I've achieved this with much less gnarly code than my previous versions using the (custom) MonitoredProcess helper, and it does not seem to waste any time. This test could be generalised and used for some other things in due course.

I have manually checked that, if I comment out the line setting the shutdown callback, the new test fails with a timeout after one second. I initially didn't want to include this in the tests for speed, but debugging this stuff is tricky enough that I think it's worth the extra second to make sure that the test does fail if we deliberately break the graceful shutdown so it's included in this PR.

Before merge:

  • Check that commenting out the shutdown callback results in the new test failing.
  • Create or update the OFM feature branch.
  • Add error handling in case close_streams raises an exception.
  • Check manually that the server still shuts down if there's an exception in the shutdown callback function.
  • Add and test error handling code to make sure the uvicorn shutdown function is always called.
  • Merge Mjpeg stream refactor #409, rebase, and retarget to main. This branch is based on Mjpeg stream refactor #409 and includes all its commits.

AI Contributions

AI was not used as part of this pull request.

Merge checklist:

  • All new/changed functions have up to date typehints and docstrings.
  • Any changes to the public API have been updated in docs/src/public_api.rst.
  • New or changed features have been added to (or updated in) the conceptual documentation.
  • Any new or updated dependencies have been added to the project configuration (e.g., pyproject.toml).
  • New functionality is fully tested.
  • Any decrease in test coverage has been justified.
  • Either the test-against-ofm-v3 job passes, or test-against-ofm-feature-branch passes.
  • New features have been used in a branch of the OpenFlexure Microscope, which is tested in test-against-ofm-feature-branch.
  • This code has been tested manually against simulated hardware (detail tests in "Before merge").
  • This code has been tested against real hardware (detail tests in "Before merge").

This replicates the current behaviour of the OFM server, by closing connections
when the server is asked to shut down (instead of waiting for them to close).

I've subclassed `uvicorn.Server` rather than monkeypatching it as that felt
cleaner.
As a side-effect it's now easier to catch exceptions raised at server start-up,
though I've not made use of this.

`uvicorn.run` swallows a lot of stuff with its `system.exit(3)`, but that's no longer a problem.
This starts a server in a subprocess and terminates it while holding the stream
open.

I've manually verified that this test does not pass if I don't set the shutdown
function.

Testing that the server hangs if a stream is left open when it's terminated would be
slow and painful. I don't think it's necessary.
@rwb27
rwb27 added this pull request to stack #434 November 26, 2026 16:52
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
100.0%

 passed

████████████████████ 100.0% on changed lines

90 lines changed   0 uncovered   5 files

 📂 5 files changed
  File Coverage Uncovered Lines
🟢 src/labthings_fastapi/message_broker.py 100.0% —

| 🟢 | src/labthings_fastapi/thing_server_interface.py | 100.0% | — |

| 🟢 | src/labthings_fastapi/server/_catch_uvicorn_shutdown.py | 100.0% | — |

| 🟢 | src/labthings_fastapi/outputs/mjpeg_stream.py | 100.0% | — |

| 🟢 | src/labthings_fastapi/server/__init__.py | 100.0% | — |

 📋 Full diff-cover report

Diff Coverage

Diff: origin/main...HEAD, staged and unstaged changes

  • src/labthings_fastapi/message_broker.py (100%)
  • src/labthings_fastapi/outputs/mjpeg_stream.py (100%)
  • src/labthings_fastapi/server/init.py (100%)
  • src/labthings_fastapi/server/_catch_uvicorn_shutdown.py (100%)
  • src/labthings_fastapi/thing_server_interface.py (100%)

Summary

  • Total: 90 lines
  • Missing: 0 lines
  • Coverage: 100%

🛡️ diff-cover-action

This is necessary for a clean shutdown at the command line.
@rwb27
rwb27 marked this pull request as draft November 26, 2026 20:47
We now run the graceful shutdown test again, with `MessageBroker.close_streams` mocked.
This ensures that we know the the graceful shutdown code is working,
and the test is not broken.

This may be an overly paranoid use of an extra second of test suite time, but I think
it's worthwhile to validate the test.

I did do this manually, but I decided I'd rather have it test that every time, just
in case the test gets broken in the future.
@rwb27
rwb27 marked this pull request as ready for review November 26, 2026 20:56
This uses a `finally:` block to make sure the server shuts down
correctly.

I've checked manually that a real server does shut down OK, even
if the shutdown callback raises an exception. The test does not
spin up a server, but it does verify the correct behaviour
when the callback raises an exception.

The stack trace gets dumped to the terminal, and does point
to where the error originated. I think this is better than
logging and swallowing the exception.

The OFM code this replaces used to log and swallow the exception,
because otherwise the server would not shut down. That's because
it ran in the shutdown handler responsible for setting a flag to
stop the event loop.

We are hooking in later in the shutdown process once the flag
is already set. That problem doesn't apply so a finally block
is all we need.
@rwb27
rwb27 force-pushed the mjpeg-graceful-shutdown branch from a872260 to b252fc1 Compare November 26, 2026 22:57

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gracefull shutdown with MJPEG streams connected

1 participant