Use the uiprotect public resync in UniFi Protect reconnects (#188186)

This commit is contained in:
Raphael Hehl
2026-10-23 16:20:07 +00:00
committed by GitHub
parent 9f767396d5
commit 3f579d65a4
9 changed files with 205 additions and 128 deletions
+13 -34
View File
@@ -316,6 +316,7 @@ class ProtectData:
# The events websocket is public in both modes (see
# ``async_subscribe_public_events``), so track its state in both.
api.subscribe_events_websocket_state(self._async_events_ws_state_changed),
api.subscribe_public_resync(self._async_public_resync_done),
]
if api.is_public_only:
# No private session: the private websocket and the private poll
@@ -523,42 +524,20 @@ class ProtectData:
return
self.last_public_update_success = success
self._async_process_public_updates()
if success:
# The library resyncs its public bootstrap on reconnect, but the
# resync applies silently and races this callback, so the re-read
# above may see the pre-disconnect cache. Refresh again behind a
# guaranteed-fresh snapshot (``update_public`` is serialized) so a
# change from the disconnect gap cannot stay stale.
self._entry.async_create_background_task(
self._hass,
self._async_resignal_after_public_resync(),
"unifiprotect public reconnect refresh",
)
async def _async_resignal_after_public_resync(self) -> None:
"""Re-signal public entities once a fresh public snapshot is applied."""
try:
await self.async_update_public()
except NotAuthorized:
# A revoked API key cannot self-recover.
self._entry.async_start_reauth(self._hass)
return
except (TimeoutError, ClientError, ServerDisconnectedError) as err:
# Retried on the next reconnect, but this now gates discovery of
# devices that appeared during the gap, so make it visible.
_LOGGER.warning("Public refresh after reconnect failed: %s", err)
return
@callback
def _async_public_resync_done(self, success: bool) -> None:
"""Re-signal public entities once the library's reconnect resync has finished.
Added and removed devices arrive as frames, field changes apply silently.
Re-offer cameras and relays because their entity sets derive from fields.
"""
self._async_process_public_updates()
# A device that appeared during the gap gets no add frame, so re-offer
# everything. Platforms and dispatch helpers drop what they already know.
if self.api.has_public_bootstrap:
for public in list(self.api.public_bootstrap.cameras.values()):
async_dispatcher_send(self._hass, self.channels_signal, public)
for device in list(self.api.public_bootstrap.all_devices()):
if isinstance(device, PublicDeviceModel):
self._async_dispatch_new_public_device(device)
for relay in list(self.api.public_bootstrap.relays.values()):
async_dispatcher_send(self._hass, self.relay_signal, relay)
public_bootstrap = self.api.public_bootstrap
for public in list(public_bootstrap.cameras.values()):
async_dispatcher_send(self._hass, self.channels_signal, public)
for relay in list(public_bootstrap.relays.values()):
async_dispatcher_send(self._hass, self.relay_signal, relay)
@callback
def _async_signal_public_doorbell_settings(self) -> None:
+15
View File
@@ -242,6 +242,19 @@ def mock_ufp_client(bootstrap: Bootstrap):
return client
def _subscribe_public_resync(
ufp: MockUFPFixture,
) -> Callable[[Callable[[bool], None]], Mock]:
"""Capture the public resync callback on the fixture."""
def subscribe(resync_callback: Callable[[bool], None]) -> Mock:
ufp.public_resync_subscription = resync_callback
ufp.public_resync_unsub = Mock()
return ufp.public_resync_unsub
return subscribe
@pytest.fixture(name="ufp")
def mock_entry(
hass: HomeAssistant, ufp_config_entry: MockConfigEntry, ufp_client: ProtectApiClient
@@ -304,6 +317,7 @@ def mock_entry(
ufp_client.subscribe_events = subscribe_events
ufp_client.subscribe_devices_websocket_state = subscribe_devices_websocket_state
ufp_client.subscribe_events_websocket_state = subscribe_events_websocket_state
ufp_client.subscribe_public_resync = _subscribe_public_resync(ufp)
async def update_public() -> Any:
# Mirror the library prime: build each camera's public model from the
@@ -672,6 +686,7 @@ def mock_ufp_public_only(
ufp_public_only_client.subscribe_events_websocket_state = (
subscribe_events_websocket_state
)
ufp_public_only_client.subscribe_public_resync = _subscribe_public_resync(ufp)
return ufp
+51 -63
View File
@@ -2,9 +2,8 @@
from collections.abc import Callable, Coroutine
from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock, Mock
from aiohttp.client_exceptions import ServerDisconnectedError
import pytest
from pytest_homeassistant.common import MockConfigEntry, async_capture_events
from uiprotect.api import RTSPSStreams
@@ -50,6 +49,7 @@ from .utils import (
enable_entity,
init_entry,
make_public_camera,
make_streamless_public_camera,
public_device_ws_message,
public_rtsps_for,
remove_entities,
@@ -936,9 +936,8 @@ async def test_public_only_camera_deleted_during_gap(
) -> None:
"""A camera deleted while the websocket was down reads as unavailable.
The library resyncs its public bootstrap on reconnect but applies the
snapshot silently; the integration must re-read behind a fresh snapshot
rather than resurrect the entity from the pre-disconnect cache.
The reconnect itself re-reads the pre-disconnect cache; the library's
resync then removes the camera and the entity must not be resurrected.
"""
for channel in camera.channels:
channel._api = ufp.api
@@ -956,64 +955,23 @@ async def test_public_only_camera_deleted_during_gap(
await init_entry(hass, ufp, [])
entity_id = _channel_entity_id(camera, 0)
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
ufp.api.update_public.reset_mock()
# The websocket drops; the camera is deleted during the gap, so the
# reconnect resync returns a snapshot without it.
async def _prime_empty() -> Any:
pb = ufp.api.public_bootstrap
pb.cameras = {}
return pb
ufp.api.update_public = AsyncMock(side_effect=_prime_empty)
ufp.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
ufp.devices_ws_state_subscription(WebsocketState.CONNECTED)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
# Not resurrected from the stale cache: the fresh snapshot has no camera.
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
@pytest.mark.parametrize(
("error", "expect_reauth"),
[
pytest.param(NotAuthorized("revoked"), True, id="revoked_key"),
pytest.param(ServerDisconnectedError(), False, id="transport_error"),
],
)
async def test_reconnect_refresh_failures(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera: ProtectCamera,
error: Exception,
expect_reauth: bool,
) -> None:
"""A failed reconnect refresh starts reauth on 401 and retries on transport."""
for channel in camera.channels:
channel._api = ufp.api
public = make_public_camera(camera)
public.rtsps_streams = public_rtsps_for(camera)
async def _prime_public_only() -> Any:
pb = ufp.api.public_bootstrap
pb.cameras = {camera.id: public}
return pb
ufp.api.update_public = AsyncMock(side_effect=_prime_public_only)
ufp.api.is_public_only = True
await init_entry(hass, ufp, [])
ufp.api.update_public = AsyncMock(side_effect=error)
ufp.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
# The camera was deleted during the gap; the library resync drops it.
ufp.api.public_bootstrap.cameras = {}
ufp.public_resync(removed=[public])
await hass.async_block_till_done()
with patch.object(ufp.entry, "async_start_reauth") as mock_reauth:
ufp.devices_ws_state_subscription(WebsocketState.CONNECTED)
await hass.async_block_till_done()
assert mock_reauth.called is expect_reauth
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
ufp.api.update_public.assert_not_awaited()
async def test_hybrid_camera_lost_public_mirror_logs(
@@ -1040,9 +998,7 @@ async def test_public_only_camera_added_during_gap(
) -> None:
"""A camera added while the websocket was down enumerates on reconnect.
The resync snapshot is applied silently and no add frame ever arrives for
a camera that appeared during the gap, so the reconnect refresh must
dispatch it for enumeration itself.
The library's reconnect resync announces it with a synthetic add frame.
"""
for channel in camera_all.channels:
channel._api = ufp.api
@@ -1060,7 +1016,7 @@ async def test_public_only_camera_added_during_gap(
await init_entry(hass, ufp, [])
assert_entity_counts(hass, Platform.CAMERA, 3, 1)
# A second camera appears during the gap; the reconnect resync includes it.
# A second camera appears during the gap; the library resync adds it.
second = make_public_camera(camera_all)
second.id = "gap-camera"
second.mac = "FFEEDDCCBB01"
@@ -1068,15 +1024,11 @@ async def test_public_only_camera_added_during_gap(
second.display_name = "Gap Camera"
second.rtsps_streams = first.rtsps_streams
async def _prime_two() -> Any:
pb = ufp.api.public_bootstrap
pb.cameras = {camera_all.id: first, second.id: second}
return pb
ufp.api.update_public = AsyncMock(side_effect=_prime_two)
ufp.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
await hass.async_block_till_done()
ufp.devices_ws_state_subscription(WebsocketState.CONNECTED)
ufp.api.public_bootstrap.cameras[second.id] = second
ufp.public_resync(added=[second])
await hass.async_block_till_done()
# Three tiers each for both cameras; no duplicates for the first one.
@@ -1084,6 +1036,42 @@ async def test_public_only_camera_added_during_gap(
assert hass.states.get("camera.gap_camera_high_resolution_channel") is not None
async def test_public_only_camera_streams_primed_by_resync(
hass: HomeAssistant, ufp: MockUFPFixture, camera_all: ProtectCamera
) -> None:
"""Stream tiers the library primes during its resync get their entities.
The prime of a known camera is silent (no frame), so the resync completion
has to re-offer the cameras.
"""
for channel in camera_all.channels:
channel._api = ufp.api
public = make_streamless_public_camera(camera_all)
async def _prime_streamless() -> Any:
pb = ufp.api.public_bootstrap
pb.cameras = {camera_all.id: public}
return pb
ufp.api.update_public = AsyncMock(side_effect=_prime_streamless)
ufp.api.is_public_only = True
await init_entry(hass, ufp, [])
# Streamless: only the snapshot entity of the first main tier.
assert_entity_counts(hass, Platform.CAMERA, 1, 1)
ufp.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
ufp.devices_ws_state_subscription(WebsocketState.CONNECTED)
await hass.async_block_till_done()
assert_entity_counts(hass, Platform.CAMERA, 1, 1)
public.rtsps_streams = public_rtsps_for(camera_all)
ufp.public_resync()
await hass.async_block_till_done()
assert_entity_counts(hass, Platform.CAMERA, 3, 1)
async def test_unadopted_camera_not_enumerated_from_public_frame(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
+2 -6
View File
@@ -657,15 +657,11 @@ def _readopt_with_add_frame(ufp: MockUFPFixture, fob: Mock, readopted: Mock) ->
def _readopt_during_outage(ufp: MockUFPFixture, fob: Mock, readopted: Mock) -> None:
"""Re-adopt the fob while the devices websocket is down."""
async def resync_public_bootstrap() -> Mock:
ufp.api.public_bootstrap.fobs = {readopted.id: readopted}
return ufp.api.public_bootstrap
ufp.api.update_public.side_effect = resync_public_bootstrap
assert ufp.devices_ws_state_subscription is not None
ufp.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
ufp.devices_ws_state_subscription(WebsocketState.CONNECTED)
ufp.api.public_bootstrap.fobs = {readopted.id: readopted}
ufp.public_resync(added=[readopted], removed=[fob])
@pytest.mark.parametrize(
+19 -3
View File
@@ -185,6 +185,23 @@ async def test_unload(hass: HomeAssistant, ufp: MockUFPFixture, light: Light) ->
await hass.config_entries.async_unload(ufp.entry.entry_id)
assert ufp.entry.state is ConfigEntryState.NOT_LOADED
assert ufp.api.async_disconnect_ws.called
assert ufp.public_resync_unsub is not None
ufp.public_resync_unsub.assert_called_once()
async def test_public_only_unload(
hass: HomeAssistant,
ufp_public_only: MockUFPFixture,
setup_public_only: Callable[[], Coroutine[Any, Any, None]],
) -> None:
"""Unloading an API-key-only entry drops the public resync subscription."""
await setup_public_only()
assert ufp_public_only.entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(ufp_public_only.entry.entry_id)
assert ufp_public_only.entry.state is ConfigEntryState.NOT_LOADED
assert ufp_public_only.public_resync_unsub is not None
ufp_public_only.public_resync_unsub.assert_called_once()
async def test_remove_entry(hass: HomeAssistant, ufp: MockUFPFixture) -> None:
@@ -1006,7 +1023,7 @@ async def test_public_only_setup_retakes_add_baseline(
HA only drops ``runtime_data`` after a successful unload, so an entry that
never loaded keeps its ProtectData across a mode switch. Its baseline was
taken in full-access mode, where the mac set stays empty on purpose, and
reusing it would re-offer every enumerated device on the first reconnect.
reusing it would re-offer an enumerated device on its next add frame.
"""
api = ufp_public_only.api
api.public_bootstrap.lights = {light.id: make_public_light(light)}
@@ -1021,8 +1038,7 @@ async def test_public_only_setup_retakes_add_baseline(
await setup_public_only()
assert len(hass.states.async_entity_ids(Platform.LIGHT.value)) == 1
ufp_public_only.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
ufp_public_only.devices_ws_state_subscription(WebsocketState.CONNECTED)
ufp_public_only.public_resync(added=api.public_bootstrap.lights.values())
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(Platform.LIGHT.value)) == 1
+7 -5
View File
@@ -300,8 +300,7 @@ async def test_light_added_during_gap_public_only(
) -> None:
"""A light added while the websocket was down enumerates on reconnect.
No add frame arrives for a light that appeared during the gap, so the
reconnect resync must dispatch it for enumeration itself.
The library's reconnect resync announces it with a synthetic add frame.
"""
first = make_public_light(light)
@@ -309,24 +308,27 @@ async def test_light_added_during_gap_public_only(
await init_entry(hass, ufp, [])
assert_entity_counts(hass, Platform.LIGHT, 1, 1)
ufp.api.update_public.reset_mock()
# A second light appears during the gap; the reconnect resync includes it.
# A second light appears during the gap; the library resync adds it.
second = make_public_light(light)
second.id = "gap-light"
second.mac = "FFEEDDCCBB02"
second.name = "Gap Light"
second.display_name = "Gap Light"
_use_public_only_bootstrap(ufp, first, second)
ufp.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
await hass.async_block_till_done()
ufp.devices_ws_state_subscription(WebsocketState.CONNECTED)
ufp.api.public_bootstrap.lights[second.id] = second
ufp.public_resync(added=[second])
await hass.async_block_till_done()
assert_entity_counts(hass, Platform.LIGHT, 2, 2)
assert hass.states.get("light.gap_light") is not None
# The resync re-offers the first light too; the dedup must drop it.
assert "already exists" not in caplog.text
# The library owns the resync; the integration does not refresh again.
ufp.api.update_public.assert_not_awaited()
@pytest.mark.parametrize(
+11 -16
View File
@@ -537,16 +537,16 @@ async def test_relay_channel_devices_ws_disconnect_reconnect_resync(
await hass.async_block_till_done()
assert _state(hass, channel.entity_id) == STATE_UNAVAILABLE
async def resync_public_bootstrap() -> Mock:
_set_channel_state(relay, channel, channel.on)
return ufp.api.public_bootstrap
ufp.api.update_public.side_effect = resync_public_bootstrap
ufp.devices_ws_state_subscription(WebsocketState.CONNECTED)
await hass.async_block_till_done()
# Back from the pre-disconnect cache until the library resync lands.
assert _state(hass, channel.entity_id) == STATE_OFF
_set_channel_state(relay, channel, channel.on)
ufp.public_resync()
await hass.async_block_till_done()
assert _state(hass, channel.entity_id) == STATE_ON
ufp.api.update_public.assert_awaited()
@_CHANNELS
@@ -585,14 +585,12 @@ async def test_public_only_relay_channels_resignaled_after_reconnect(
await setup_public_only()
assert hass.states.get(BINARY_SENSOR_ENTITY_ID) is None
async def resync_public_bootstrap() -> Mock:
relay.inputs = [_make_input()]
return public_bootstrap
ufp_public_only.api.update_public.side_effect = resync_public_bootstrap
assert ufp_public_only.devices_ws_state_subscription is not None
ufp_public_only.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
ufp_public_only.devices_ws_state_subscription(WebsocketState.CONNECTED)
# The library resync applies the new input silently.
relay.inputs = [_make_input()]
ufp_public_only.public_resync()
await hass.async_block_till_done()
state = hass.states.get(BINARY_SENSOR_ENTITY_ID)
@@ -676,14 +674,11 @@ async def test_relay_readopted_during_websocket_outage(
readopted.id = "relay-id-2"
_set_channel_state(readopted, _OUTPUT, RelayOutputState.ON)
async def resync_public_bootstrap() -> Mock:
ufp.api.public_bootstrap.relays = {readopted.id: readopted}
return ufp.api.public_bootstrap
ufp.api.update_public.side_effect = resync_public_bootstrap
assert ufp.devices_ws_state_subscription is not None
ufp.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
ufp.devices_ws_state_subscription(WebsocketState.CONNECTED)
ufp.api.public_bootstrap.relays = {readopted.id: readopted}
ufp.public_resync(added=[readopted], removed=[relay])
await hass.async_block_till_done()
assert _state(hass, SWITCH_ENTITY_ID) == STATE_ON
@@ -1667,6 +1667,54 @@ async def test_public_only_select_nvr_arm_profile_follows_public_ws(
assert hass.states.get(entity_id).state == "Home (p1)"
@pytest.mark.parametrize(
"success",
[
pytest.param(True, id="resync_ok"),
# A failed endpoint, e.g. liveviews, keeps what the others applied.
pytest.param(False, id="resync_partial"),
],
)
async def test_public_only_select_nvr_arm_profile_follows_public_resync(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp_public_only: MockUFPFixture,
setup_public_only: Callable[[], Coroutine[Any, Any, None]],
success: bool,
) -> None:
"""Arm profiles the library resync refetched show up without another refresh."""
pb = ufp_public_only.api.public_bootstrap
pb.arm_profiles = {"p1": _make_arm_profile("p1", "Home")}
pb.arm_mode = _make_nvr_arm_mode(profile_id="p1")
await setup_public_only()
ufp_public_only.api.update_public.reset_mock()
entity_id = entity_registry.async_get_entity_id(
Platform.SELECT, DOMAIN, f"{UNIFI_MAC}_nvr_arm_profile"
)
assert entity_id
ufp_public_only.devices_ws_state_subscription(WebsocketState.DISCONNECTED)
ufp_public_only.devices_ws_state_subscription(WebsocketState.CONNECTED)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == "Home (p1)"
# Arm profiles have no websocket frames; the resync applies them silently.
pb.arm_profiles = {
"p1": _make_arm_profile("p1", "Home"),
"p2": _make_arm_profile("p2", "Away"),
}
pb.arm_mode = _make_nvr_arm_mode(profile_id="p2")
ufp_public_only.public_resync(success=success)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state.state == "Away (p2)"
assert set(state.attributes[ATTR_OPTIONS]) == {"Home (p1)", "Away (p2)"}
ufp_public_only.api.update_public.assert_not_awaited()
async def test_select_nvr_arm_profile_decoupled_from_private_websocket(
hass: HomeAssistant, ufp: MockUFPFixture
) -> None:
+39 -1
View File
@@ -1,6 +1,6 @@
"""Test helpers for UniFi Protect."""
from collections.abc import Callable, Iterator, Sequence
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import partial
@@ -31,6 +31,7 @@ from uiprotect.data import (
SmartDetectAudioType,
SmartDetectObjectType,
VideoMode,
WSAction,
WSSubscriptionMessage,
)
from uiprotect.data.bootstrap import ProtectDeviceRef
@@ -82,6 +83,8 @@ class MockUFPFixture:
events_subscription: Callable[[ProtectEvent, EventChange], None] | None = None
devices_ws_state_subscription: Callable[[WebsocketState], None] | None = None
events_ws_state_subscription: Callable[[WebsocketState], None] | None = None
public_resync_subscription: Callable[[bool], None] | None = None
public_resync_unsub: Mock | None = None
def ws_msg(self, msg: WSSubscriptionMessage) -> None:
"""Emit WS message for testing."""
@@ -95,6 +98,41 @@ class MockUFPFixture:
if self.events_subscription is not None:
self.events_subscription(event, change)
def public_resync(
self,
added: Iterable[Any] = (),
removed: Iterable[Any] = (),
success: bool = True,
) -> None:
"""Emit the library's public reconnect resync for testing.
Mirrors uiprotect: one synthetic add/remove devices websocket frame per
device whose membership changed, then the resync completion callback.
"""
assert self.devices_ws_subscription is not None
assert self.public_resync_subscription is not None
for obj in added:
self.devices_ws_subscription(
WSSubscriptionMessage(
action=WSAction.ADD,
new_update_id=obj.id,
changed_data={"modelKey": obj.model.value, "id": obj.id},
new_obj=obj,
old_obj=None,
)
)
for obj in removed:
self.devices_ws_subscription(
WSSubscriptionMessage(
action=WSAction.REMOVE,
new_update_id=obj.id,
changed_data={"modelKey": obj.model.value, "id": obj.id},
new_obj=None,
old_obj=obj,
)
)
self.public_resync_subscription(success)
def reset_objects(bootstrap: Bootstrap):
"""Reset bootstrap objects."""