diff --git a/homeassistant/components/cert_expiry/__init__.py b/homeassistant/components/cert_expiry/__init__.py index ee139d853108..243f14ffd267 100644 --- a/homeassistant/components/cert_expiry/__init__.py +++ b/homeassistant/components/cert_expiry/__init__.py @@ -1,7 +1,7 @@ """The cert_expiry component.""" from homeassistant.const import CONF_HOST, CONF_PORT, Platform -from homeassistant.core import HomeAssistant +from homeassistant.core import CoreState, HomeAssistant from homeassistant.helpers.start import async_at_started from .coordinator import CertExpiryConfigEntry, CertExpiryDataUpdateCoordinator @@ -25,7 +25,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: CertExpiryConfigEntry) - await coordinator.async_refresh() await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) - async_at_started(hass, _async_finish_startup) + # When already started, async_at_started would run the forward in a task + # that setup doesn't await, which isn't allowed + if hass.state is CoreState.running: + await _async_finish_startup(hass) + else: + async_at_started(hass, _async_finish_startup) async def async_unload_entry(hass: HomeAssistant, entry: CertExpiryConfigEntry) -> None: diff --git a/homeassistant/config_entries.py b/homeassistant/config_entries.py index 88f0ed769aeb..af43a7be0b13 100644 --- a/homeassistant/config_entries.py +++ b/homeassistant/config_entries.py @@ -1582,18 +1582,6 @@ class FlowCancelledError(Exception): """Error to indicate that a flow has been cancelled.""" -def _report_non_awaited_platform_forwards(entry: ConfigEntry, what: str) -> None: - """Report non awaited platform forwards.""" - report_usage( - f"calls {what} for integration {entry.domain} with " - f"title: {entry.title} and entry_id: {entry.entry_id}, " - f"during setup without awaiting {what}, which can cause " - "the setup lock to be released before the setup is done", - core_behavior=ReportBehavior.LOG, - breaks_in_ha_version="2025.1", - ) - - class ConfigEntriesFlowManager( data_entry_flow.FlowManager[ConfigFlowContext, ConfigFlowResult] ): @@ -2995,17 +2983,14 @@ class ConfigEntries: in each integration. This is to ensure that all platforms are loaded before the entry is set up. This ensures that the config entry cannot be unloaded before all platforms are loaded. - - This method is more efficient than async_forward_entry_setup as - it can load multiple platforms at once and does not require a separate - import executor job for each platform. """ integration = await loader.async_get_integration(self.hass, entry.domain) if not integration.platforms_are_loaded(platforms): with async_pause_setup(self.hass, SetupPhases.WAIT_IMPORT_PLATFORMS): await integration.async_get_platforms(platforms) - if not entry.setup_lock.locked(): + # A loaded entry's lock is held by another forward, so wait for it + if not entry.setup_lock.locked() or entry.state is ConfigEntryState.LOADED: async with entry.setup_lock: if entry.state is not ConfigEntryState.LOADED: raise OperationNotAllowed( @@ -3017,11 +3002,15 @@ class ConfigEntries: await self._async_forward_entry_setups_locked(entry, platforms) else: await self._async_forward_entry_setups_locked(entry, platforms) - # If the lock was held when we stated, and it was released during - # the platform setup, it means they did not await the setup call. + # If the lock was held when the forward started, and it was released + # during the platform setup, it means they did not await the setup call. if not entry.setup_lock.locked(): - _report_non_awaited_platform_forwards( - entry, "async_forward_entry_setups" + raise HomeAssistantError( + "Detected code that calls async_forward_entry_setups during setup " + f"for integration {entry.domain} with title: {entry.title} and " + f"entry_id: {entry.entry_id}, without awaiting " + "async_forward_entry_setups, which can cause the setup lock to be " + "released before the setup is done" ) async def _async_forward_entry_setups_locked( diff --git a/tests/components/shelly/conftest.py b/tests/components/shelly/conftest.py index a8f51e4d069f..02e2a1b07848 100644 --- a/tests/components/shelly/conftest.py +++ b/tests/components/shelly/conftest.py @@ -1,5 +1,6 @@ """Test configuration for Shelly.""" +import asyncio from collections.abc import Generator from copy import deepcopy from unittest.mock import AsyncMock, Mock, PropertyMock, patch @@ -753,7 +754,12 @@ async def mock_rpc_device(): current_pos, device.status[f"cover:{cover_id}"]["current_pos"] ) + async def _initialize() -> None: + # Yield like the network I/O of a real device + await asyncio.sleep(0) + device = _mock_rpc_device() + device.initialize = AsyncMock(side_effect=_initialize) rpc_device_mock.return_value = device rpc_device_mock.return_value.mock_disconnected = Mock(side_effect=_disconnected) rpc_device_mock.return_value.mock_update = Mock(side_effect=_update) diff --git a/tests/components/shelly/test_config_flow.py b/tests/components/shelly/test_config_flow.py index 8ce57569483d..c6c309b910ff 100644 --- a/tests/components/shelly/test_config_flow.py +++ b/tests/components/shelly/test_config_flow.py @@ -3070,6 +3070,7 @@ async def test_options_flow_ble(hass: HomeAssistant, mock_rpc_device: Mock) -> N assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"][CONF_BLE_SCANNER_MODE] is BLEScannerMode.DISABLED + await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] is FlowResultType.FORM @@ -3085,6 +3086,7 @@ async def test_options_flow_ble(hass: HomeAssistant, mock_rpc_device: Mock) -> N assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"][CONF_BLE_SCANNER_MODE] is BLEScannerMode.ACTIVE + await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] is FlowResultType.FORM @@ -3100,6 +3102,7 @@ async def test_options_flow_ble(hass: HomeAssistant, mock_rpc_device: Mock) -> N assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"][CONF_BLE_SCANNER_MODE] is BLEScannerMode.PASSIVE + await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] is FlowResultType.FORM @@ -3115,6 +3118,7 @@ async def test_options_flow_ble(hass: HomeAssistant, mock_rpc_device: Mock) -> N assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"][CONF_BLE_SCANNER_MODE] is BLEScannerMode.AUTO + await hass.async_block_till_done() # Initial setup plus one reload per options change await hass.async_block_till_done() diff --git a/tests/test_config_entries.py b/tests/test_config_entries.py index 4b43a539d47b..3d09968456aa 100644 --- a/tests/test_config_entries.py +++ b/tests/test_config_entries.py @@ -9878,15 +9878,62 @@ async def test_non_awaited_async_forward_entry_setups( await hass.async_block_till_done() forward_event.set() await hass.async_block_till_done() - await task - assert ( - "Detected code that calls async_forward_entry_setups for integration " - "test with title: Mock Title and entry_id: test2, during setup without " + message = ( + "Detected code that calls async_forward_entry_setups during setup for " + "integration test with title: Mock Title and entry_id: test2, without " "awaiting async_forward_entry_setups, which can cause the setup lock " - "to be released before the setup is done. This will stop working in " - "Home Assistant 2025.1, please report this issue" - ) in caplog.text + "to be released before the setup is done" + ) + with pytest.raises(HomeAssistantError, match=message): + await task + + +async def test_concurrent_async_forward_entry_setups_after_setup( + hass: HomeAssistant, + manager: config_entries.ConfigEntries, +) -> None: + """Test concurrent async_forward_entry_setups calls after setup.""" + forward_event = asyncio.Event() + + async def mock_setup_entry_platform( + hass: HomeAssistant, + entry: config_entries.ConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, + ) -> None: + """Mock setting up platform.""" + await forward_event.wait() + + mock_integration( + hass, MockModule("test", async_setup_entry=AsyncMock(return_value=None)) + ) + mock_platform( + hass, "test.light", MockPlatform(async_setup_entry=mock_setup_entry_platform) + ) + mock_platform( + hass, "test.switch", MockPlatform(async_setup_entry=mock_setup_entry_platform) + ) + mock_platform(hass, "test.config_flow", None) + + entry = MockConfigEntry(domain="test", entry_id="test2") + entry.add_to_manager(manager) + + await manager.async_setup(entry.entry_id) + assert entry.state is config_entries.ConfigEntryState.LOADED + + # The second forward finds the setup lock held by the first one + light_task = create_eager_task( + hass.config_entries.async_forward_entry_setups(entry, ["light"]) + ) + switch_task = create_eager_task( + hass.config_entries.async_forward_entry_setups(entry, ["switch"]) + ) + await hass.async_block_till_done() + forward_event.set() + + await light_task + await switch_task + assert hass.config.components >= {"test.light", "test.switch"} async def test_config_entry_unloaded_during_platform_setup(