diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 8860dbb..b133b74 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -3130,7 +3130,7 @@ class MeshCoreDevice(Device): # or a slow response arriving after a timeout) would otherwise misidentify the slot and # misfile a channel's messages. On mismatch we raise rather than return foreign data. async with self._channel_read_lock: - event = self._ok(await self._require().commands.get_channel(index)) + event = await self._channel_event(index) payload = getattr(event, "payload", {}) or {} got = payload.get("channel_idx") if got is not None and int(got) != index: @@ -3139,6 +3139,41 @@ class MeshCoreDevice(Device): return None return payload + async def _channel_event(self, index: int): # noqa: ANN202 - a meshcore Event + """Read one slot, telling the firmware's "no such slot" apart from any other error. + + The slot probe ends on a *rejection* and keeps the list it has as the device's whole + layout, so what counts as one matters. The firmware answers an index past its last + slot with ``ERR_CODE_NOT_FOUND`` and nothing else. But the library does not + serialize commands, and every one that waits for "OK or ERROR" takes the first + ERROR that arrives — so a read racing another command can be handed *that* + command's refusal. At connect the channel prewarm runs beside the clock sync, and a + clock the firmware refuses as malformed ended the probe at whatever slot it had + reached, which cached a list missing every channel after it for the session. + + So only ``NOT_FOUND`` (or a code-less refusal from firmware too old to send one) is + a rejection. Any other refusal is asked again once, since a borrowed error is + someone else's and the next answer is this read's own; a second one, or no answer + at all, is a failed read (:class:`DeviceCommandError`), which the probe reports as + unfinished rather than caching. + """ + commands = self._require().commands + for attempt in (1, 2): + event = await commands.get_channel(index) + if event is None or not getattr(event, "is_error", lambda: False)(): + return event + payload = getattr(event, "payload", {}) or {} + if isinstance(payload, dict) and payload.get("reason") == "no_event_received": + raise DeviceCommandError(f"channel read for slot {index} got no answer") + code = error_code(event) + if code is None or code == _ERR_NOT_FOUND: + return self._ok(event) # the firmware's own "no such slot" + if attempt == 2: + raise DeviceCommandError( + f"channel read for slot {index} was refused: {reject_reason(event)}" + ) + return None # pragma: no cover - the loop always returns or raises + async def set_name(self, name: str) -> None: # noqa: D102 - inherited docstring self._ok(await self._require().commands.set_name(name)) diff --git a/tests/test_connection_channels.py b/tests/test_connection_channels.py index 262cb11..7502c9a 100644 --- a/tests/test_connection_channels.py +++ b/tests/test_connection_channels.py @@ -99,3 +99,77 @@ async def test_get_channel_rejects_response_for_a_different_slot() -> None: with pytest.raises(DeviceCommandError, match="returned slot"): await device.get_channel(0) + + +class _Refusal: + """A meshcore ERROR event: a refusal with a companion error code, or a timeout's.""" + + def __init__(self, payload: dict) -> None: + self.payload = payload + + def is_error(self) -> bool: + return True + + +class _ScriptedCommands: + """Fake ``commands`` answering each slot from a queue of scripted replies. + + ``replies[i]`` is a list of what successive reads of slot ``i`` get: a channel name, or + an error payload. A slot with no script is past the end — the firmware's NOT_FOUND. + """ + + def __init__(self, replies: dict[int, list]) -> None: + self.replies = {i: list(r) for i, r in replies.items()} + self.reads: list[int] = [] + + async def get_channel(self, index: int): # noqa: ANN201 + self.reads.append(index) + queue = self.replies.get(index) + reply = queue.pop(0) if queue else {"error_code": 2} + if isinstance(reply, dict): + return _Refusal(reply) + return _Event({"channel_idx": index, "channel_name": reply, "channel_secret": bytes(16)}) + + +#: What the clock sync's refusal looks like when a concurrent channel read is handed it. +_MALFORMED = {"error_code": 6} + + +async def test_a_borrowed_refusal_does_not_end_the_slot_probe() -> None: + """Another command's error, delivered to a slot read, is asked past — not a list's end. + + The library hands every waiter the first ERROR to arrive, so at connect the channel + prewarm could take the clock sync's "malformed" as slot 2 being past the end, and cache + a list missing every channel after it. + """ + from meshterm.core.channel_probe import probe_channel_slots + + commands = _ScriptedCommands({0: ["Public"], 1: ["ops"], 2: [_MALFORMED, "#montreal"]}) + slots, complete = await probe_channel_slots(_device_with(commands)) + assert [s.name for s in slots] == ["Public", "ops", "#montreal"] + assert complete + assert commands.reads.count(2) == 2 + + +async def test_a_refusal_that_repeats_is_a_failed_read_not_a_layout() -> None: + """Two refusals in a row that aren't NOT_FOUND leave the probe unfinished (not cached).""" + from meshterm.core.channel_probe import probe_channel_slots + + commands = _ScriptedCommands({0: ["Public"], 1: [_MALFORMED, _MALFORMED], 2: ["ops"]}) + slots, complete = await probe_channel_slots(_device_with(commands)) + assert [s.name for s in slots] == ["Public"] + assert not complete + + +async def test_no_answer_is_a_failed_read_and_not_found_is_the_end() -> None: + """A timeout never reads as the end of the slots; the firmware's NOT_FOUND does.""" + from meshterm.core.channel_probe import probe_channel_slots + + timeout = {"reason": "no_event_received"} + slots, complete = await probe_channel_slots( + _device_with(_ScriptedCommands({0: ["Public"], 1: [timeout]})) + ) + assert [s.name for s in slots] == ["Public"] and not complete + + slots, complete = await probe_channel_slots(_device_with(_ScriptedCommands({0: ["Public"]}))) + assert [s.name for s in slots] == ["Public"] and complete