diff --git a/homeassistant/components/music_assistant/__init__.py b/homeassistant/components/music_assistant/__init__.py index a8ffa5dc9ef1..994bbf7d82ef 100644 --- a/homeassistant/components/music_assistant/__init__.py +++ b/homeassistant/components/music_assistant/__init__.py @@ -157,13 +157,29 @@ async def async_setup_entry( # noqa: C901 # store the listen task and mass client in the entry data entry.runtime_data = MusicAssistantEntryData(mass, listen_task) - # If the listen task is already failed, we need to raise ConfigEntryNotReady - if listen_task.done() and (listen_error := listen_task.exception()) is not None: - await hass.config_entries.async_unload_platforms(entry, PLATFORMS) - try: - await mass.disconnect() - finally: - raise ConfigEntryNotReady(listen_error) from listen_error + # check if any playerconfigs have been removed while we were disconnected, + # before forwarding the platforms, as the server can still go away here. + # never clean up dashboard devices: their registration is connection-scoped, + # so the cache may still be empty right after a reconnect. + try: + all_player_configs = await mass.config.get_player_configs() + except (MusicAssistantClientException, MusicAssistantError) as err: + listen_task.cancel() + await mass.disconnect() + raise ConfigEntryNotReady( + f"Lost connection to music assistant server {mass_url}: {err}" + ) from err + player_ids = {player.player_id for player in all_player_configs} + dev_reg = dr.async_get(hass) + dev_entries = dr.async_entries_for_config_entry(dev_reg, entry.entry_id) + for device in dev_entries: + for identifier in device.identifiers: + if ( + identifier[0] == DOMAIN + and not identifier[1].startswith(DASHBOARD_ID_PREFIX) + and identifier[1] not in player_ids + ): + dev_reg.async_remove_device(device.id) # initialize platforms await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) @@ -240,21 +256,14 @@ async def async_setup_entry( # noqa: C901 mass.subscribe(handle_player_config_updated, EventType.PLAYER_CONFIG_UPDATED) ) - # check if any playerconfigs have been removed while we were disconnected. - # never clean up dashboard devices: their registration is connection-scoped, - # so the cache may still be empty right after a reconnect. - all_player_configs = await mass.config.get_player_configs() - player_ids = {player.player_id for player in all_player_configs} - dev_reg = dr.async_get(hass) - dev_entries = dr.async_entries_for_config_entry(dev_reg, entry.entry_id) - for device in dev_entries: - for identifier in device.identifiers: - if ( - identifier[0] == DOMAIN - and not identifier[1].startswith(DASHBOARD_ID_PREFIX) - and identifier[1] not in player_ids - ): - dev_reg.async_remove_device(device.id) + # The listen task skips its reload when it fails with an exception while + # the entry is still being set up, so that case has to be caught here + if listen_task.done() and (listen_error := listen_task.exception()) is not None: + await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + try: + await mass.disconnect() + finally: + raise ConfigEntryNotReady(listen_error) from listen_error return True diff --git a/tests/components/music_assistant/test_init.py b/tests/components/music_assistant/test_init.py index f43036710888..59bb7fe04fcf 100644 --- a/tests/components/music_assistant/test_init.py +++ b/tests/components/music_assistant/test_init.py @@ -1,10 +1,14 @@ """Test the Music Assistant integration init.""" +import asyncio from unittest.mock import AsyncMock, MagicMock +from music_assistant_client.exceptions import ConnectionFailed, InvalidState +from music_assistant_models.config_entries import PlayerConfig from music_assistant_models.dashboard import DashboardDevice from music_assistant_models.enums import DashboardType, EventType from music_assistant_models.errors import ActionUnavailable, AuthenticationRequired +import pytest from homeassistant.components.music_assistant.const import ( ATTR_CONF_EXPOSE_PLAYER_TO_HA, @@ -352,3 +356,65 @@ async def test_authentication_required_addon_no_reauth( issue_id = f"config_entry_reauth_{DOMAIN}_{config_entry.entry_id}" assert issue_registry.async_get_issue("homeassistant", issue_id) is None + + +async def test_server_lost_during_setup_retries( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + music_assistant_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test losing the server during setup leaves no platforms set up.""" + get_player_configs = music_assistant_client.config.get_player_configs + music_assistant_client.config.get_player_configs = AsyncMock( + side_effect=InvalidState("Not connected") + ) + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + music_assistant_client.disconnect.assert_awaited_once() + + music_assistant_client.config.get_player_configs = get_player_configs + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert "has already been setup" not in caplog.text + + +async def test_server_lost_late_in_setup_retries( + hass: HomeAssistant, + music_assistant_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test losing the server after the last server call during setup retries.""" + connection_lost = asyncio.Event() + + async def listen(init_ready: asyncio.Event) -> None: + init_ready.set() + await connection_lost.wait() + raise ConnectionFailed + + get_player_configs = music_assistant_client.config.get_player_configs + + async def get_player_configs_then_lose_server() -> list[PlayerConfig]: + player_configs = await get_player_configs() + connection_lost.set() + # Let the listen task fail before setup continues + await asyncio.sleep(0) + return player_configs + + music_assistant_client.start_listening.side_effect = listen + music_assistant_client.config.get_player_configs = ( + get_player_configs_then_lose_server + ) + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + music_assistant_client.disconnect.assert_awaited_once()