Repository navigation
Do not resend reboot or speed test after a dropped connection #555
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
manueltarouca
wants to merge
1
commit into
iMicknl:main
Choose a base branch
from
manueltarouca:fix/no-retry-after-disconnect-for-reboot
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| """Tests for transport retries on actions that must not run twice.""" | ||
|
|
||
| import asyncio | ||
| import json | ||
| import urllib.parse | ||
| from unittest.mock import AsyncMock | ||
|
|
||
| import pytest | ||
| from aiohttp import ClientSession, ClientTimeout | ||
|
|
||
| from sagemcom_api.client import SagemcomClient | ||
| from sagemcom_api.enums import EncryptionMethod | ||
|
|
||
| OK_REPLY = { | ||
| "reply": { | ||
| "uid": 0, | ||
| "id": 0, | ||
| "error": {"code": 16777216, "description": "XMO_REQUEST_NO_ERR"}, | ||
| "actions": [ | ||
| { | ||
| "uid": 1, | ||
| "id": 0, | ||
| "error": {"code": 16777238, "description": "XMO_NO_ERR"}, | ||
| "callbacks": [ | ||
| {"uid": 1, "result": {"code": 16777238, "description": "XMO_NO_ERR"}, "xpath": "Device", "parameters": {"value": "ok"}} | ||
| ], | ||
| } | ||
| ], | ||
| "events": [], | ||
| } | ||
| } | ||
|
|
||
|
|
||
| class FlakyRouter: | ||
| """Raw TCP server that accepts each request, then drops the first `drops` connections without answering.""" | ||
|
|
||
| def __init__(self, drops: int): | ||
| """Drop the first `drops` connections after reading the request.""" | ||
| self.drops = drops | ||
| self.methods: list[str] = [] | ||
| self.server: asyncio.Server | None = None | ||
|
|
||
| async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: | ||
| head = await reader.readuntil(b"\r\n\r\n") | ||
| length = next(int(line.split(b":")[1]) for line in head.split(b"\r\n") if line.lower().startswith(b"content-length")) | ||
| body = await reader.readexactly(length) | ||
| request = json.loads(urllib.parse.parse_qs(body.decode())["req"][0])["request"] | ||
| self.methods.extend(action["method"] for action in request["actions"]) | ||
|
|
||
| if len(self.methods) <= self.drops: | ||
| writer.transport.abort() # The router acted on the request, then went away without replying. | ||
| return | ||
|
|
||
| payload = json.dumps(OK_REPLY).encode() | ||
| writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s" % (len(payload), payload)) | ||
| await writer.drain() | ||
| writer.close() | ||
|
|
||
| async def __aenter__(self) -> str: | ||
| """Start the server and return its host:port.""" | ||
| self.server = await asyncio.start_server(self._handle, "127.0.0.1", 0) | ||
| port = self.server.sockets[0].getsockname()[1] | ||
| return f"127.0.0.1:{port}" | ||
|
|
||
| async def __aexit__(self, *exc) -> None: | ||
| """Stop the server.""" | ||
| assert self.server is not None | ||
| self.server.close() | ||
| await self.server.wait_closed() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize(("call", "method"), [("reboot", "reboot"), ("run_speed_test", "speedTestClient")]) | ||
| async def test_non_idempotent_action_is_not_resent_after_disconnect(call, method): | ||
| """A reboot (or speed test) that reached the router must not be sent again when the connection drops.""" | ||
| router = FlakyRouter(drops=99) | ||
| async with router as host, ClientSession(timeout=ClientTimeout(total=10)) as session: | ||
| client = SagemcomClient(host, "admin", "admin", EncryptionMethod.MD5, session=session) | ||
|
|
||
| with pytest.raises(ConnectionError): | ||
| await getattr(client, call)() | ||
|
|
||
| assert router.methods == [method] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_read_is_still_retried_after_disconnect(monkeypatch): | ||
| """Reads are safe to repeat, so a dropped connection is still retried.""" | ||
| monkeypatch.setattr(asyncio, "sleep", AsyncMock()) # skip the backoff delay | ||
| router = FlakyRouter(drops=1) | ||
| async with router as host, ClientSession(timeout=ClientTimeout(total=10)) as session: | ||
| client = SagemcomClient(host, "admin", "admin", EncryptionMethod.MD5, session=session) | ||
|
|
||
| value = await client.get_value_by_xpath("Device") | ||
|
|
||
| assert value == "ok" | ||
| assert router.methods == ["getValue", "getValue"] |
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.
Should the on exception not be moved to the
__send? It seems like it is now added to the wrong function?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.
It's intentional.
__senddoes the request and has no retry. The two wrappers add different retry rules:__post: retries on any connection error, same as before. Used by everything else (login, get, set, logout).__post_once: retries only onClientConnectorError, i.e. the request never left the client. Used byrebootandrun_speed_test.If the
ClientConnectorErrorretry moved to__send,__postwould retry it a second time (ClientConnectorErroris a subclass ofClientOSError), so a connect failure could take up to 25 attempts.I can add a short comment above
__sendif that helps, or restructure it if you prefer a different split.