Repository navigation
Conversation
Barecheck - Code coverage reportTotal: 97.77%Your code coverage diff: 0.35% ▴ Uncovered files and lines
|
2a7182c to
8d79b7f
Compare
|
Testing this against the OFM simulator, I can see we need to do something in the log: currently it looks like it drops a message when a client disconnects from the stream, and that results in the bytes being dumped to the log/console, which is not desirable. Also I managed to crash the simulator - I'm not sure if that's related to this change or not, but it bears investigating at least a little further. |
|
I have fixed the log issue in two ways:
I have not been able to reproduce the crash: what I can say is that my whole WSL2 environment crashed (including two different VSCode sessions) so it's possible that it got shut down for overloading my computer or something. The noise made by my fans when the simulator spins up suggests that is not unreasonable! |
|
One point to note: currently, stand are being made with a |
|
I have changed the default buffer size to zero, so it should now exactly replicate the old (lossy) behaviour. I have added unit testing of different buffer sizes. I've also made use of I have run the new test with lots of print statements to check I understand what runs when: these are not in the PR but I feel like it's reasonable to state for the record that it's been done. |
768aa1c to
e4959f3
Compare
Starlette's `TestClient` now correctly relays HTTP streams. I have updated this test accordingly. The improved version of this test introduced in #409 will also need updating in due course, but fixing it here untangles the merge ordering.
|
I've tested this against real hardware, but not extensively. I'm happy it's OK to merge, but we definitely want to get this in to OFM soon, so there's plenty time to find the edge cases before it's released. |
|
The audit failure is fixed by #411 |
e4959f3 to
1475921
Compare
|
I've rebased and updated the tests to account for TestClient now working properly for HTTP streams. I think this is ready to go. The breaking changes stop the ofm v3 test from working, but the feature branch should pass. |
1475921 to
f434ec8
Compare
057b0b9 to
1bce41c
Compare
I've added "stream" as a message type, and provided "next message" and "close streams by affordance" methods. This should prepare the way for using MessageBroker for MJPEG streams.
The thing server interface now exposes the message broker.
This strips out the pub/sub logic from MJPEGStream in favour of using MessageBroker, as is already done for property notifications. The resulting class should be much simpler. I've also inherited from BaseDescriptor to save duplication in MJPEGStreamDescriptor.
This uses an event to speed up tests by eliminating `time.sleep` and adds some more checks on the data received.
The stream no longer has the notion of being "active" so we can't check for errors there. This might be a feature we want to revive - I'm not totally sure.
This is tested by a better-isolated test that mocks the server and uses a real MessageBroker.
The async generator actually works quite well with the new stream based structure, so I've resinstated it. I've taken the opportunity to rename it, and return Frame objects, not just bytes. The old name remains for backwards compatibility. This shrinks the code changes slightly, I think, and should also make it neater for client code as there's less need to create/use/type check streams directly. I've added explicit tests for the new functions in message broker.
The old MJPEG stream silently dropped frames. We were logging every dropped frame at WARNING. I've downgraded this to DEBUG for streams. We may choose to turn it off entirely to replicate the old behaviour. I have also altered the `repr` of `Frame` objects, to avoid dumping JPEG data to console/log accidentally.
There are now no buffers used when streaming MJPEG frames, exactly replicating the previous behaviour. This is enabled by a better understanding (by me) of the anyio event loop. Specifically, not all `await` statements yield to the event loop, and so it's necessary to manually yield to the event loop during the test. Now that I've added this, I should be able to write better async tests for a few things.
The latest version of Starlette allows us to test HTTP streams properly. This test now synchronises sending and receiving data with an Event, to avoid dropping frames.
This was picked up a new `ruff` rule introduced in a rebase.
1bce41c to
b9d77f5
Compare
This covers the case where nobody has subscribed to an affordance before it's closed.
| # We don't expect to get any payloads that are not Frame objects. | ||
| yield message.payload | ||
|
|
||
| async def frame_async_generator(self) -> AsyncGenerator[bytes, None]: |
There was a problem hiding this comment.
| async def frame_async_generator(self) -> AsyncGenerator[bytes, None]: | |
| async def frame_bytes_async_generator(self) -> AsyncGenerator[bytes, None]: |
Potentially more clear that the function generates bytes objects?
Or we use the convention from line 225, and rename frames() to frames_with_metadata()
| :param type: the class on which we are defined. | ||
| :param obj: the host `~lt.Thing`. | ||
|
|
||
| :return: an `.MJPEGStream`, or this descriptor. |
There was a problem hiding this comment.
| :return: an `.MJPEGStream`, or this descriptor. | |
| :return: an `.MJPEGStream`. |
| # subscribe to a stream | ||
| send_stream, receive_stream = anyio.create_memory_object_stream[Message]() | ||
| await broker.subscribe("thing_name", "prop", send_stream) | ||
| assert send_stream in broker._subscriptions["thing_name"]["prop"] |
There was a problem hiding this comment.
| assert send_stream in broker._subscriptions["thing_name"]["prop"] | |
| assert send_stream in broker._subscriptions["thing_name"]["prop"] | |
| assert len(broker._subscriptions["thing_name"]["prop"]) == 2 |
Adding in another len() check seems clean
| # then wait for the coroutine to finish | ||
| frame = future.result() | ||
| # this should return a valid JPEG, which we can (sort of) check below | ||
| assert_magic_bytes(frame) |
There was a problem hiding this comment.
Why are we not using check_jpeg_bytes() here?
| async with anyio.create_task_group() as tg: | ||
| handle = tg.start_soon(mjpeg_stream.grab_frame_with_metadata) | ||
| await to_thread.run_sync(mjpeg_stream.add_frame, jpeg_bytes) | ||
| assert handle.return_value.frame is jpeg_bytes |
There was a problem hiding this comment.
Can we also assert that we got the metadata too?
| async with anyio.create_task_group() as tg: | ||
| handle = tg.start_soon(mjpeg_stream.next_frame_size) | ||
| await to_thread.run_sync(mjpeg_stream.add_frame, jpeg_bytes) | ||
| assert handle.return_value == len(jpeg_bytes) |
There was a problem hiding this comment.
Can we also assert that we've gotten the size of the frame?
| await broker.subscribe("thing", "stream", send) | ||
| caplog.set_level(logging.DEBUG) | ||
| caplog.clear() | ||
| # The first message sits in the buffer, the second gets dropped |
There was a problem hiding this comment.
Explain why this happens in a comment (buffer=0 by default)
| await broker.close_streams_for_affordance("thing", "prop") | ||
| # Each time, we should have dropped the last message (because we send two | ||
| # more than the buffer size). | ||
| assert handle.return_value == messages * 2 |
There was a problem hiding this comment.
tg.start_soon only returns a task handle from anyio 4.14.0 onwards (https://anyio.readthedocs.io/en/stable/versionhistory.html). The pyproject.toml currently only pins anyio ~=4.0, so we may need to change this to >=4.14 to make sure this functionality works.
| def test_mjpeg_stream(client): | ||
| """Verify the MJPEG stream contains at least one frame marker. | ||
| We check that `grab_frame` and `next_frame_size` both work when the | ||
| camera emits frames, and also that they raise an error if they're called |
There was a problem hiding this comment.
Error conditions aren't included in this test. Can we add them in?
| if isinstance(message.payload, Frame): | ||
| # We simply ignore messages that don't contain Frame objects. | ||
| # We don't expect to get any payloads that are not Frame objects. | ||
| yield message.payload |
There was a problem hiding this comment.
The path through frames() where message.payload is not a Frame object is untested
This PR strips out the custom pub/sub logic from
MJPEGStreamand replaces it with a couple of calls toMessageBroker. It goes further than #372 by actually using theMessageBrokerobject rather than just pinching a function from it. I think this results in a bigger improvement, from a smaller code change.I hope this makes the code much more readable and much more testable.
The diff has more additions than deletions - but the deletions are (complicated) code while the additions are docstrings, comments, tests, and calls to much clearer code.
The pub/sub logic in MessageBroker is tested much more carefully than the old logic was, even though it was technically covered before.
I have written a fixture that lets me write async tests for the
MJPEGStreamindependent of the server. It usesMessageBrokerbut not the server or FastAPI.This PR passes both the old tests, and the relevant bits of the improved tests in #372, which are included in this PR.
OFM-Feature-Branch: v3-mjpeg-stream-refactor
Skip-OFM-v3-Test
This MR contains the following
Before merge:
Merge checklist:
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).Any decrease in test coverage has been justified.test-against-ofm-v3job passes, ortest-against-ofm-feature-branchpasses.New features have been used in a branch of the OpenFlexure Microscope, which is tested intest-against-ofm-feature-branch.