Skip to content

Commit aa1316e

Browse files
committed
fix: remove_service during zc discovery leaving device stranded
1 parent 34f9d43 commit aa1316e

2 files changed

Lines changed: 104 additions & 6 deletions

File tree

‎src/powersensor_local/zeroconf_devices.py‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,11 @@ async def _on_zc_remove(self, mac: str) -> None:
228228
# Sync to async bridge for callbacks, per asyncio docs
229229
# ------------------------------------------------------------------
230230

231-
def _internal_callback(self, coro: _InternalCallback) -> None:
232-
"""Helper to prevent gc collection of short-lived callback tasks."""
231+
def _internal_callback(self, coro: _InternalCallback) -> Task[None]:
232+
"""Helper to prevent gc collection of short-lived callback tasks.
233+
234+
Returns the task, so callers can cancel it early if needed.
235+
"""
233236
task = asyncio.create_task(coro)
234237

235238
def cleanup(task: Task[None]) -> None:
@@ -244,6 +247,7 @@ def cleanup(task: Task[None]) -> None:
244247

245248
self._internal_callbacks.add(task)
246249
task.add_done_callback(cleanup)
250+
return task
247251

248252

249253
class _Listener(_zc.ServiceListener):
@@ -258,6 +262,13 @@ class _Listener(_zc.ServiceListener):
258262
def __init__(self, owner: PowersensorZeroconfDevices) -> None:
259263
self._owner = owner
260264
self._name_to_mac: dict[str, str] = {}
265+
# Lookups still waiting for a plug to answer, by service name, so a
266+
# removal arriving first can cancel them.
267+
self._lookups: dict[str, Task[None]] = {}
268+
269+
def _forget_lookup(self, name: str, task: Task[Any] | None) -> None:
270+
if self._lookups.get(name) is task:
271+
del self._lookups[name]
261272

262273
def _parse(self, info: AsyncServiceInfo, name: str) -> tuple[str, str, int] | None:
263274
"""Return (mac, ip, port) from a resolved service record, or None."""
@@ -322,8 +333,16 @@ def _resolve(
322333
self._owner._internal_callback(on_resolved(*result))
323334
return
324335

336+
if name in self._lookups:
337+
# A lookup for this plug is already waiting; it will dispatch.
338+
return
339+
325340
async def request() -> None:
326-
if not await info.async_request(zc, _REQUEST_TIMEOUT_MS):
341+
answered = await info.async_request(zc, _REQUEST_TIMEOUT_MS)
342+
# The plug has answered (or not): from here on a removal goes
343+
# through the normal debounced path instead of cancelling this.
344+
self._forget_lookup(name, asyncio.current_task())
345+
if not answered:
327346
self._owner._maybe_log(
328347
_LogLevel.WARNING,
329348
"No response from %s — device will appear on next mDNS announcement",
@@ -334,7 +353,9 @@ async def request() -> None:
334353
await on_resolved(*result)
335354

336355
self._owner._maybe_log(_LogLevel.DEBUG, "No cache entry for %s, requesting it", name)
337-
self._owner._internal_callback(request())
356+
lookup = self._owner._internal_callback(request())
357+
self._lookups[name] = lookup
358+
lookup.add_done_callback(lambda task: self._forget_lookup(name, task))
338359

339360
def add_service(self, zc: Any, type_: str, name: str) -> None:
340361
self._resolve(zc, type_, name, self._owner._on_zc_add)
@@ -343,8 +364,14 @@ def update_service(self, zc: Any, type_: str, name: str) -> None:
343364
self._resolve(zc, type_, name, self._owner._on_zc_update)
344365

345366
def remove_service(self, zc: Any, type_: str, name: str) -> None:
367+
if (lookup := self._lookups.pop(name, None)) is not None:
368+
# Removed before it answered, so it was never dispatched.
369+
lookup.cancel()
370+
self._owner._maybe_log(_LogLevel.DEBUG, "%s removed before it answered; lookup cancelled", name)
346371
mac = self._name_to_mac.pop(name, None)
347372
if mac is None:
373+
if lookup is not None:
374+
return
348375
self._owner._maybe_log(
349376
_LogLevel.WARNING,
350377
"remove_service for %s: MAC not in cache — removal ignored", name,

‎tests/test_zeroconf_devices.py‎

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,16 @@
1515

1616
def fake_service_info(
1717
cached: bool, answers: bool, id_: bytes = b'aabbccddeeff',
18+
gate: asyncio.Event | None = None,
1819
) -> type[Any]:
19-
"""A stand-in for AsyncServiceInfo with a controllable cache and plug response."""
20+
"""A stand-in for AsyncServiceInfo with a controllable cache and plug response.
21+
22+
If gate is given, the plug only answers once the gate is set.
23+
"""
2024

2125
class FakeServiceInfo:
2226
requested = False
27+
requests = 0
2328

2429
def __init__(self, type_: str, name: str) -> None:
2530
self.port = 49476
@@ -30,6 +35,9 @@ def load_from_cache(self, zc: Any) -> bool:
3035

3136
async def async_request(self, zc: Any, timeout: float) -> bool:
3237
FakeServiceInfo.requested = True
38+
FakeServiceInfo.requests += 1
39+
if gate is not None:
40+
await gate.wait()
3341
return answers
3442

3543
def parsed_addresses(self) -> list[str]:
@@ -44,7 +52,13 @@ async def settle(devices: PowersensorZeroconfDevices) -> None:
4452
await asyncio.sleep(0)
4553
if not devices._internal_callbacks:
4654
return
47-
await asyncio.gather(*list(devices._internal_callbacks))
55+
await asyncio.gather(*list(devices._internal_callbacks), return_exceptions=True)
56+
57+
58+
async def let_run() -> None:
59+
"""Let scheduled tasks run up to their next wait, without waiting for them."""
60+
for _ in range(5):
61+
await asyncio.sleep(0)
4862

4963

5064
@pytest.mark.asyncio
@@ -92,6 +106,63 @@ async def test_unanswered_request_is_logged(caplog: pytest.LogCaptureFixture) ->
92106
assert f'No response from {NAME}' in caplog.text
93107

94108

109+
@pytest.mark.asyncio
110+
async def test_removal_before_answer_cancels_lookup(caplog: pytest.LogCaptureFixture) -> None:
111+
devices = PowersensorZeroconfDevices(
112+
zeroconf_instance=MagicMock(), logger=logging.getLogger('test'),
113+
)
114+
gate = asyncio.Event()
115+
info = fake_service_info(cached=False, answers=True, gate=gate)
116+
with caplog.at_level(logging.WARNING), \
117+
patch.object(zd, 'AsyncServiceInfo', info), \
118+
patch.object(devices, '_on_zc_add', AsyncMock()) as on_add, \
119+
patch.object(devices, '_on_zc_remove', AsyncMock()) as on_remove:
120+
listener = zd._Listener(devices)
121+
listener.add_service(MagicMock(), TYPE, NAME)
122+
await let_run()
123+
listener.remove_service(MagicMock(), TYPE, NAME)
124+
gate.set()
125+
await settle(devices)
126+
# The plug was never dispatched, so there is nothing to remove either.
127+
on_add.assert_not_awaited()
128+
on_remove.assert_not_awaited()
129+
assert 'removal ignored' not in caplog.text
130+
131+
132+
@pytest.mark.asyncio
133+
async def test_one_lookup_per_plug_at_a_time() -> None:
134+
devices = PowersensorZeroconfDevices(zeroconf_instance=MagicMock())
135+
gate = asyncio.Event()
136+
info = fake_service_info(cached=False, answers=True, gate=gate)
137+
with patch.object(zd, 'AsyncServiceInfo', info), \
138+
patch.object(devices, '_on_zc_add', AsyncMock()) as on_add, \
139+
patch.object(devices, '_on_zc_update', AsyncMock()) as on_update:
140+
listener = zd._Listener(devices)
141+
listener.add_service(MagicMock(), TYPE, NAME)
142+
await let_run()
143+
listener.update_service(MagicMock(), TYPE, NAME)
144+
gate.set()
145+
await settle(devices)
146+
assert info.requests == 1
147+
on_add.assert_awaited_once_with('aabbccddeeff', '192.0.2.10', 49476)
148+
on_update.assert_not_awaited()
149+
150+
151+
@pytest.mark.asyncio
152+
async def test_removal_after_answer_is_debounced() -> None:
153+
devices = PowersensorZeroconfDevices(zeroconf_instance=MagicMock())
154+
info = fake_service_info(cached=False, answers=True)
155+
with patch.object(zd, 'AsyncServiceInfo', info), \
156+
patch.object(devices, '_on_zc_add', AsyncMock()), \
157+
patch.object(devices, '_on_zc_remove', AsyncMock()) as on_remove:
158+
listener = zd._Listener(devices)
159+
listener.add_service(MagicMock(), TYPE, NAME)
160+
await settle(devices)
161+
listener.remove_service(MagicMock(), TYPE, NAME)
162+
await settle(devices)
163+
on_remove.assert_awaited_once_with('aabbccddeeff')
164+
165+
95166
# Browser callbacks must never raise (see _Listener): zeroconf does not catch
96167
# their exceptions, which would disrupt other listeners on a shared instance.
97168

0 commit comments

Comments
 (0)