-
Notifications
You must be signed in to change notification settings - Fork 4
Add data protocol via control protocol #91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BenediktBurger
wants to merge
10
commits into
main
Choose a base branch
from
manual-data-protocol
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
891d803
Add extended data publisher
BenediktBurger 93b06ee
Add unregister to data publisher.
BenediktBurger 65bfec1
Make extended message handler subscribe via remote protocol
BenediktBurger 14a737f
The actor offers publishing via control protocol (+test)
BenediktBurger ff38d4a
Fix linting and tests.
BenediktBurger c915860
Rename to add_subscription_message
BenediktBurger f106bdb
Use Notifications instead of Requests
BenediktBurger f496721
Fix tests
BenediktBurger 15f0aa8
Fix typing
BenediktBurger e539bd1
Expand data publisher documentation
BenediktBurger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| # | ||
| # This file is part of the PyLECO package. | ||
| # | ||
| # Copyright (c) 2023-2024 PyLECO Developers | ||
| # | ||
| # Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| # of this software and associated documentation files (the "Software"), to deal | ||
| # in the Software without restriction, including without limitation the rights | ||
| # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| # copies of the Software, and to permit persons to whom the Software is | ||
| # furnished to do so, subject to the following conditions: | ||
| # | ||
| # The above copyright notice and this permission notice shall be included in | ||
| # all copies or substantial portions of the Software. | ||
| # | ||
| # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| # THE SOFTWARE. | ||
| # | ||
|
|
||
| from __future__ import annotations | ||
| from json import JSONDecodeError | ||
| from typing import Any, cast, Callable, Generator, Union | ||
|
|
||
| from ..json_utils.errors import JSONRPCError, NODE_UNKNOWN, RECEIVER_UNKNOWN, METHOD_NOT_FOUND | ||
| from ..json_utils.json_objects import Notification | ||
| from ..core.message import Message, MessageTypes | ||
| from ..core.data_message import DataMessage | ||
| from ..json_utils.rpc_generator import RPCGenerator | ||
| from .data_publisher import DataPublisher | ||
|
|
||
| class ExtendedDataPublisher(DataPublisher): | ||
| """A DataPublisher, which sends the data also via the control protocol. | ||
|
|
||
| Handle unsolicited error messages, e.g. unavailable subscribers or not implemented receiving | ||
| method, with :meth:`handle_json_error` to remove these subscribers from the list of subscribers. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, full_name: str, send_message_method: Callable[[Message], None], **kwargs | ||
| ) -> None: | ||
| super().__init__(full_name, **kwargs) | ||
| self.send_control_message = send_message_method | ||
| self.subscribers: set[bytes] = set() | ||
| self.rpc_generator = RPCGenerator() | ||
|
|
||
| def register_subscriber(self, subscriber: Union[bytes, str]) -> None: | ||
| """Register a subscriber, that it may receive data messages via command protocol.""" | ||
| if isinstance(subscriber, str): | ||
| subscriber = subscriber.encode() | ||
| self.subscribers.add(subscriber) | ||
|
|
||
| def unregister_subscriber(self, subscriber: Union[bytes, str]) -> None: | ||
| """Unregister a subscriber, that it may not receive data messages via command protocol.""" | ||
| if isinstance(subscriber, str): | ||
| subscriber = subscriber.encode() | ||
| self.subscribers.discard(subscriber) | ||
|
|
||
| def convert_data_message_to_messages( | ||
| self, data_message: DataMessage, receivers: Union[set[Union[bytes, str]], set[bytes]], | ||
| ) -> Generator[Message, Any, Any]: | ||
| cid = data_message.conversation_id | ||
| raw_message = Message( | ||
| receiver="dummy", | ||
| data=Notification("add_subscription_message"), | ||
| conversation_id=cid, | ||
| additional_payload=data_message.payload, | ||
| message_type=MessageTypes.JSON, | ||
| ) | ||
| for receiver in receivers: | ||
| raw_message.receiver = receiver.encode() if isinstance(receiver, str) else receiver | ||
| yield raw_message | ||
|
|
||
| def send_message(self, message: DataMessage) -> None: | ||
| super().send_message(message) | ||
| for msg in self.convert_data_message_to_messages(message, self.subscribers): | ||
| self.send_control_message(msg) | ||
|
|
||
| def handle_json_error(self, message: Message) -> None: | ||
| """Unregister unavailable subscribers in an error message. | ||
|
|
||
| Call this method from wherever you handle incoming json errors, for example in the | ||
| message handler. | ||
| """ | ||
| try: | ||
| data: dict[str, Any] = message.data # type: ignore | ||
| except JSONDecodeError as exc: | ||
| self.log.exception(f"Could not decode json message {message}", exc_info=exc) | ||
| return | ||
| try: | ||
| self.rpc_generator.get_result_from_response(data) | ||
| except JSONRPCError as exc: | ||
| error_code = exc.rpc_error.code | ||
| try: | ||
| error_data = cast(str, exc.rpc_error.data) # type: ignore | ||
| except AttributeError: | ||
| return | ||
| if error_code in (RECEIVER_UNKNOWN.code, METHOD_NOT_FOUND.code): | ||
| self.unregister_subscriber(error_data) | ||
| if error_code == NODE_UNKNOWN.code: | ||
| if isinstance(error_data, str): | ||
| error_data = error_data.encode() | ||
| for subscriber in self.subscribers: | ||
| if subscriber.startswith(error_data): | ||
| self.unregister_subscriber(subscriber) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| # | ||
| # This file is part of the PyLECO package. | ||
| # | ||
| # Copyright (c) 2023-2024 PyLECO Developers | ||
| # | ||
| # Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| # of this software and associated documentation files (the "Software"), to deal | ||
| # in the Software without restriction, including without limitation the rights | ||
| # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| # copies of the Software, and to permit persons to whom the Software is | ||
| # furnished to do so, subject to the following conditions: | ||
| # | ||
| # The above copyright notice and this permission notice shall be included in | ||
| # all copies or substantial portions of the Software. | ||
| # | ||
| # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| # THE SOFTWARE. | ||
| # | ||
|
|
||
| import pytest | ||
|
|
||
| from pyleco.test import FakeContext | ||
| from pyleco.core.message import Message, MessageTypes | ||
| from pyleco.core.data_message import DataMessage | ||
| from pyleco.json_utils.json_objects import Notification | ||
| from pyleco.utils.extended_data_publisher import ExtendedDataPublisher | ||
|
|
||
|
|
||
| CID = b"conversation_id;" | ||
| messages = [] # for tests | ||
|
|
||
| @pytest.fixture | ||
| def fake_send_message(): | ||
| global messages | ||
| messages = [] | ||
| def _fsm(message: Message): | ||
| global messages | ||
| messages.append(message) | ||
| return _fsm | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def publisher(fake_send_message) -> ExtendedDataPublisher: | ||
| publisher = ExtendedDataPublisher( | ||
| "fn", send_message_method=fake_send_message, | ||
| context=FakeContext(), # type: ignore | ||
| ) | ||
| return publisher | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def data_message() -> DataMessage: | ||
| return DataMessage( | ||
| topic="topic", conversation_id=CID, data=b"0", additional_payload=[b"1", b"2"] | ||
| ) | ||
|
|
||
|
|
||
| def test_register_subscribers(publisher: ExtendedDataPublisher): | ||
| # act | ||
| publisher.register_subscriber("abcdef") | ||
| assert b"abcdef" in publisher.subscribers | ||
|
|
||
| publisher.register_subscriber(b"ghi") | ||
| assert b"ghi" in publisher.subscribers | ||
|
|
||
|
|
||
| def test_unregister_subscribers(publisher: ExtendedDataPublisher): | ||
| # arrange | ||
| publisher.subscribers.add(b"abc") | ||
| publisher.subscribers.add(b"def") | ||
| # act | ||
| # str | ||
| publisher.unregister_subscriber("abc") | ||
| assert b"abc" not in publisher.subscribers | ||
| # bytes | ||
| publisher.unregister_subscriber(b"def") | ||
| assert b"def" not in publisher.subscribers | ||
| # assert that no error is raised at repeated unregistering | ||
| publisher.unregister_subscriber(b"def") | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("receivers", (set(), {b"abc"}, {b"abc", b"def"}, {"string"})) | ||
| def test_convert(publisher: ExtendedDataPublisher, receivers, data_message: DataMessage): | ||
| msgs = list(publisher.convert_data_message_to_messages(data_message, receivers=receivers)) | ||
| assert len(msgs) == len(receivers) | ||
| for rec, msg in zip(receivers, msgs): | ||
| assert msg == Message( | ||
| receiver=rec, | ||
| data=Notification(method="add_subscription_message"), | ||
| conversation_id=CID, | ||
| message_type=MessageTypes.JSON, | ||
| additional_payload=data_message.payload, | ||
| ) | ||
|
|
||
|
|
||
| def test_send_message(publisher: ExtendedDataPublisher, data_message: DataMessage): | ||
| # arrange | ||
| publisher.register_subscriber("abc") | ||
| # act | ||
| publisher.send_message(data_message) | ||
| # assert that the data message is sent | ||
| assert publisher.socket._s == [data_message.to_frames()] | ||
| # assert that the control message is sent | ||
| global messages | ||
| assert messages == [ | ||
| Message( | ||
| "abc", | ||
| data=Notification(method="add_subscription_message"), | ||
| conversation_id=CID, | ||
| message_type=MessageTypes.JSON, | ||
| additional_payload=data_message.payload, | ||
| ) | ||
| ] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.