diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index 254a5ebd2220..b7a1cb44ba4d 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -2,6 +2,7 @@ import asyncio from collections.abc import AsyncGenerator, MutableMapping +from contextlib import suppress from dataclasses import dataclass, field from datetime import datetime import hashlib @@ -14,7 +15,7 @@ from pathlib import Path import re import secrets import struct -from time import monotonic +from time import monotonic, time, time_ns from typing import Any, Final, Protocol from aiohttp import web @@ -1043,6 +1044,7 @@ class SpeechManager: self.cache_dir = cache_dir self.memory_cache_maxage = memory_cache_maxage self.file_cache: dict[str, str] = {} + self._files_pending_removal: set[str] = set() self.mem_cache: dict[str, TTSCache] = {} self.token_to_stream: dict[str, ResultStream] = {} self.converted_override_cache: dict[ @@ -1069,8 +1071,12 @@ class SpeechManager: """Init config folder and load file cache.""" self.file_cache.update(await self.hass.async_add_executor_job(self._init_cache)) - async def async_clear_cache(self) -> None: - """Read file cache and delete files.""" + async def async_clear_cache(self, days: int | None = None) -> None: + """Delete cached files, or only those not used for the given days.""" + if days is not None: + await self._async_clear_unused_cache(days) + return + self.mem_cache.clear() def remove_files(files: list[str]) -> None: @@ -1087,6 +1093,66 @@ class SpeechManager: self.file_cache.clear() await task + async def _async_clear_unused_cache(self, days: int) -> None: + """Delete cached files that were not used for the given days.""" + cutoff = time() - days * 86400 + + def find_unused_files(files: dict[str, str]) -> list[str]: + """Return the keys of files that were not used since the cutoff.""" + unused = [] + for cache_key, filename in files.items(): + try: + if ( + os.stat(os.path.join(self.cache_dir, filename)).st_atime + >= cutoff + ): + continue + except FileNotFoundError: + pass + except OSError as err: + _LOGGER.warning("Can't check cache file '%s': %s", filename, err) + continue + unused.append(cache_key) + return unused + + def remove_files(files: dict[str, str]) -> dict[str, str]: + """Remove files from filesystem and return the ones that failed.""" + failed = {} + for cache_key, filename in files.items(): + try: + os.remove(os.path.join(self.cache_dir, filename)) + except FileNotFoundError: + pass + except OSError as err: + _LOGGER.warning("Can't remove cache file '%s': %s", filename, err) + failed[cache_key] = filename + return failed + + # Messages in the memory cache are in use + unused = await self.hass.async_add_executor_job( + find_unused_files, + { + cache_key: filename + for cache_key, filename in self.file_cache.items() + if cache_key not in self.mem_cache + }, + ) + # Unindex before removing, so a request started meanwhile regenerates + # the audio instead of reading a removed file + files = { + cache_key: filename + for cache_key in unused + if cache_key not in self.mem_cache + and (filename := self.file_cache.pop(cache_key, None)) + } + self._files_pending_removal.update(files.values()) + try: + failed = await self.hass.async_add_executor_job(remove_files, files) + finally: + self._files_pending_removal.difference_update(files.values()) + for cache_key, filename in failed.items(): + self.file_cache.setdefault(cache_key, filename) + @callback def async_get_cache_file_path(self, cache_key: str) -> Path | None: """Return the path to a cached TTS file, if it is in the file cache.""" @@ -1330,6 +1396,10 @@ class SpeechManager: # Is speech already in memory if cache := self.mem_cache.get(cache_key): _LOGGER.debug("Found audio in cache for %s", message[0:32]) + if filename := self.file_cache.get(cache_key): + self.hass.async_add_executor_job( + _mark_file_used, os.path.join(self.cache_dir, filename) + ) return cache store_to_disk = use_file_cache @@ -1449,6 +1519,10 @@ class SpeechManager: f"TTS filename '{filename}' from {engine_instance.name} is invalid!" ) + # Writing now could race the removal of the old file with this name + if filename in self._files_pending_removal: + return + if cache.extension == "mp3": name = ( engine_instance.name if isinstance(engine_instance.name, str) else "-" @@ -1629,12 +1703,14 @@ class SpeechManager: def load_speech() -> bytes: """Load a speech from filesystem.""" with open(voice_file, "rb") as speech: - return speech.read() + data = speech.read() + _mark_file_used(speech.fileno()) + return data try: data = await self.hass.async_add_executor_job(load_speech) except OSError as err: - del self.file_cache[cache_key] + self.file_cache.pop(cache_key, None) raise os_read_error(err, voice_file) from err yield data @@ -1681,6 +1757,12 @@ class SpeechManager: return data_bytes.getvalue() +def _mark_file_used(file: int | str) -> None: + """Set the access time of a cache file, independent of the mount's atime setting.""" + with suppress(OSError): + os.utime(file, ns=(time_ns(), os.stat(file).st_mtime_ns)) + + def _init_tts_cache_dir(hass: HomeAssistant, cache_dir: str) -> str: """Init cache folder.""" if not os.path.isabs(cache_dir): diff --git a/homeassistant/components/tts/const.py b/homeassistant/components/tts/const.py index 32fccc882dd1..01a60b7fdc39 100644 --- a/homeassistant/components/tts/const.py +++ b/homeassistant/components/tts/const.py @@ -60,6 +60,7 @@ class TextToSpeechServiceArgument(StrEnum): """Store keys for text-to-speech service arguments.""" CACHE = "cache" + DAYS = "days" LANGUAGE = "language" MEDIA_PLAYER_ENTITY_ID = "media_player_entity_id" MESSAGE = "message" diff --git a/homeassistant/components/tts/services.py b/homeassistant/components/tts/services.py index 492a5564b940..409ca8c5407a 100644 --- a/homeassistant/components/tts/services.py +++ b/homeassistant/components/tts/services.py @@ -14,12 +14,20 @@ from .const import ( TextToSpeechServiceArgument, ) -SCHEMA_SERVICE_CLEAR_CACHE = probatio.Schema({}) +SCHEMA_SERVICE_CLEAR_CACHE = probatio.Schema( + { + probatio.Optional(TextToSpeechServiceArgument.DAYS): probatio.All( + probatio.Coerce(int), probatio.Range(min=1, max=3650) + ) + } +) async def _async_clear_cache_handle(service: ServiceCall) -> None: """Handle clear cache service call.""" - await service.hass.data[DATA_TTS_MANAGER].async_clear_cache() + await service.hass.data[DATA_TTS_MANAGER].async_clear_cache( + service.data.get(TextToSpeechServiceArgument.DAYS) + ) @callback diff --git a/homeassistant/components/tts/services.yaml b/homeassistant/components/tts/services.yaml index 96913368a4bc..20c018385b52 100644 --- a/homeassistant/components/tts/services.yaml +++ b/homeassistant/components/tts/services.yaml @@ -54,3 +54,12 @@ speak: object: clear_cache: + fields: + days: + example: 30 + selector: + number: + min: 1 + max: 3650 + mode: box + unit_of_measurement: days diff --git a/homeassistant/components/tts/strings.json b/homeassistant/components/tts/strings.json index 887a02471f55..76b9b8413773 100644 --- a/homeassistant/components/tts/strings.json +++ b/homeassistant/components/tts/strings.json @@ -21,7 +21,13 @@ }, "services": { "clear_cache": { - "description": "Removes all cached text-to-speech files and purges the memory.", + "description": "Removes cached text-to-speech files. When all files are removed, also purges the memory.", + "fields": { + "days": { + "description": "Only removes files that have not been used for this many days. Leave empty to remove all files.", + "name": "Days unused" + } + }, "name": "Clear TTS cache" }, "say": { diff --git a/tests/components/tts/test_init.py b/tests/components/tts/test_init.py index 6bf025707e99..e117e341fbeb 100644 --- a/tests/components/tts/test_init.py +++ b/tests/components/tts/test_init.py @@ -5,8 +5,10 @@ from collections.abc import AsyncGenerator, Callable import errno from http import HTTPStatus import io +import os from pathlib import Path import tempfile +import time from typing import Any from unittest.mock import AsyncMock, MagicMock, Mock, patch import wave @@ -35,13 +37,17 @@ from homeassistant.components.media_player import ( MediaType, ) from homeassistant.components.tts import DOMAIN, TextToSpeechCommonOption -from homeassistant.components.tts.const import DEFAULT_TIME_MEMORY +from homeassistant.components.tts.const import ( + DEFAULT_TIME_MEMORY, + TextToSpeechServiceArgument, +) from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util +from homeassistant.util.async_ import run_callback_threadsafe from .common import ( DEFAULT_LANG, @@ -789,6 +795,138 @@ async def test_service_clear_cache( ).is_file() +def _cache_file_name(key: int) -> str: + """Return a file name that matches the TTS cache file pattern.""" + return f"{key:040x}_en-us_-_tts.test.mp3" + + +OLD_CACHE_FILE = _cache_file_name(1) +RECENT_CACHE_FILE = _cache_file_name(2) +DOORBELL_CACHE_FILE = "42f18378fd4393d18c8dd11d03fa9563c1e54491_en-us_-_tts.test.mp3" + + +def _write_cache_file(path: Path, days_unused: int = 0) -> None: + """Write a cache file that was last used days_unused days ago.""" + path.write_bytes(MOCK_DATA) + last_used = time.time() - days_unused * 86400 + os.utime(path, (last_used, last_used)) + + +async def _async_speak_from_cache( + hass: HomeAssistant, calls: list[ServiceCall] +) -> None: + """Speak the doorbell message and wait until its audio is loaded.""" + await hass.services.async_call( + tts.DOMAIN, + "speak", + { + ATTR_ENTITY_ID: "tts.test", + tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something", + tts.ATTR_MESSAGE: "There is someone at the door.", + }, + blocking=True, + ) + await get_media_source_url(hass, calls[-1].data[ATTR_MEDIA_CONTENT_ID]) + await hass.async_block_till_done(wait_background_tasks=True) + + +async def test_service_clear_cache_days( + hass: HomeAssistant, + mock_tts_cache_dir: Path, + mock_tts_entity: MockTTSEntity, +) -> None: + """Test clear cache only removes files not used for the given days.""" + await hass.async_add_executor_job( + _write_cache_file, mock_tts_cache_dir / OLD_CACHE_FILE, 31 + ) + await hass.async_add_executor_job( + _write_cache_file, mock_tts_cache_dir / RECENT_CACHE_FILE, 29 + ) + await mock_config_entry_setup(hass, mock_tts_entity) + + await hass.services.async_call( + tts.DOMAIN, + tts.SERVICE_CLEAR_CACHE, + {TextToSpeechServiceArgument.DAYS: 30}, + blocking=True, + ) + + assert not (mock_tts_cache_dir / OLD_CACHE_FILE).is_file() + assert (mock_tts_cache_dir / RECENT_CACHE_FILE).is_file() + assert list(hass.data[tts.DATA_TTS_MANAGER].file_cache.values()) == [ + RECENT_CACHE_FILE + ] + + +async def test_service_clear_cache_days_missing_file( + hass: HomeAssistant, + mock_tts_cache_dir: Path, + mock_tts_entity: MockTTSEntity, +) -> None: + """Test clear cache drops files that were already removed from disk.""" + await hass.async_add_executor_job( + _write_cache_file, mock_tts_cache_dir / OLD_CACHE_FILE, 31 + ) + await mock_config_entry_setup(hass, mock_tts_entity) + await hass.async_add_executor_job((mock_tts_cache_dir / OLD_CACHE_FILE).unlink) + + await hass.services.async_call( + tts.DOMAIN, + tts.SERVICE_CLEAR_CACHE, + {TextToSpeechServiceArgument.DAYS: 30}, + blocking=True, + ) + + assert hass.data[tts.DATA_TTS_MANAGER].file_cache == {} + + +@pytest.mark.parametrize( + ("failing_call", "expected_log"), + [ + pytest.param("stat", "Can't check", id="stat"), + pytest.param("remove", "Can't remove", id="remove"), + ], +) +async def test_service_clear_cache_days_file_error( + hass: HomeAssistant, + mock_tts_cache_dir: Path, + mock_tts_entity: MockTTSEntity, + caplog: pytest.LogCaptureFixture, + failing_call: str, + expected_log: str, +) -> None: + """Test clear cache keeps files it can't check or remove for a later call.""" + await hass.async_add_executor_job( + _write_cache_file, mock_tts_cache_dir / OLD_CACHE_FILE, 31 + ) + await mock_config_entry_setup(hass, mock_tts_entity) + + with patch( + f"homeassistant.components.tts.os.{failing_call}", + side_effect=OSError("No access"), + ): + await hass.services.async_call( + tts.DOMAIN, + tts.SERVICE_CLEAR_CACHE, + {TextToSpeechServiceArgument.DAYS: 30}, + blocking=True, + ) + + assert list(hass.data[tts.DATA_TTS_MANAGER].file_cache.values()) == [OLD_CACHE_FILE] + assert (mock_tts_cache_dir / OLD_CACHE_FILE).is_file() + assert f"{expected_log} cache file '{OLD_CACHE_FILE}': No access" in caplog.text + + await hass.services.async_call( + tts.DOMAIN, + tts.SERVICE_CLEAR_CACHE, + {TextToSpeechServiceArgument.DAYS: 30}, + blocking=True, + ) + + assert hass.data[tts.DATA_TTS_MANAGER].file_cache == {} + assert not (mock_tts_cache_dir / OLD_CACHE_FILE).is_file() + + @pytest.mark.parametrize( ("setup", "tts_service", "service_data", "expected_url_suffix"), [ @@ -1140,6 +1278,171 @@ async def test_setup_cache_dir( await hass.async_block_till_done() +@pytest.mark.parametrize("mock_tts_entity", [MockEntityBoom(DEFAULT_LANG)]) +async def test_cache_file_use_updates_access_time( + hass: HomeAssistant, + mock_tts_cache_dir: Path, + mock_tts_entity: MockTTSEntity, +) -> None: + """Test playing a message from the file cache marks the file as used.""" + calls = async_mock_service(hass, MP_DOMAIN, SERVICE_PLAY_MEDIA) + cache_file = mock_tts_cache_dir / DOORBELL_CACHE_FILE + await hass.async_add_executor_job(_write_cache_file, cache_file, 31) + mtime = (await hass.async_add_executor_job(cache_file.stat)).st_mtime_ns + await mock_config_entry_setup(hass, mock_tts_entity) + + # Mounts with noatime or relatime don't update atime on every read + with patch("homeassistant.components.tts.os.utime", wraps=os.utime) as mock_utime: + await _async_speak_from_cache(hass, calls) + + mock_utime.assert_called_once() + stat = await hass.async_add_executor_job(cache_file.stat) + assert stat.st_atime > time.time() - 60 + assert stat.st_mtime_ns == mtime + + +@pytest.mark.parametrize("mock_tts_entity", [MockEntityBoom(DEFAULT_LANG)]) +async def test_service_clear_cache_days_keeps_memory_cached( + hass: HomeAssistant, + mock_tts_cache_dir: Path, + mock_tts_entity: MockTTSEntity, +) -> None: + """Test clear cache keeps files of messages still in the memory cache.""" + calls = async_mock_service(hass, MP_DOMAIN, SERVICE_PLAY_MEDIA) + cache_file = mock_tts_cache_dir / DOORBELL_CACHE_FILE + await hass.async_add_executor_job(_write_cache_file, cache_file) + await mock_config_entry_setup(hass, mock_tts_entity) + await _async_speak_from_cache(hass, calls) + # Age the file while its message is still in the memory cache + await hass.async_add_executor_job(_write_cache_file, cache_file, 31) + + await hass.services.async_call( + tts.DOMAIN, + tts.SERVICE_CLEAR_CACHE, + {TextToSpeechServiceArgument.DAYS: 30}, + blocking=True, + ) + + assert cache_file.is_file() + + +@pytest.mark.parametrize("mock_tts_entity", [MockEntityBoom(DEFAULT_LANG)]) +async def test_memory_cache_use_updates_access_time( + hass: HomeAssistant, + mock_tts_cache_dir: Path, + mock_tts_entity: MockTTSEntity, +) -> None: + """Test replaying a message from the memory cache marks its file as used.""" + calls = async_mock_service(hass, MP_DOMAIN, SERVICE_PLAY_MEDIA) + cache_file = mock_tts_cache_dir / DOORBELL_CACHE_FILE + await hass.async_add_executor_job(_write_cache_file, cache_file) + await mock_config_entry_setup(hass, mock_tts_entity) + await _async_speak_from_cache(hass, calls) + await hass.async_add_executor_job(_write_cache_file, cache_file, 31) + mtime = (await hass.async_add_executor_job(cache_file.stat)).st_mtime_ns + + await _async_speak_from_cache(hass, calls) + + stat = await hass.async_add_executor_job(cache_file.stat) + assert stat.st_atime > time.time() - 60 + assert stat.st_mtime_ns == mtime + + +@pytest.mark.parametrize("mock_tts_entity", [MockEntityBoom(DEFAULT_LANG)]) +async def test_service_clear_cache_days_concurrent_load( + hass: HomeAssistant, + mock_tts_cache_dir: Path, + mock_tts_entity: MockTTSEntity, +) -> None: + """Test clear cache keeps a file that a request starts loading meanwhile.""" + cache_file = mock_tts_cache_dir / DOORBELL_CACHE_FILE + await hass.async_add_executor_job(_write_cache_file, cache_file, 31) + await mock_config_entry_setup(hass, mock_tts_entity) + manager = hass.data[tts.DATA_TTS_MANAGER] + caches: list[tts.TTSCache] = [] + add_executor_job = hass.async_add_executor_job + + @callback + def request_message() -> None: + caches.append( + manager.async_cache_message_in_memory( + "tts.test", "There is someone at the door.", True, "en_US", {} + ) + ) + + def find_and_request( + find_unused_files: Callable[[dict[str, str]], list[str]], + files: dict[str, str], + ) -> list[str]: + unused = find_unused_files(files) + run_callback_threadsafe(hass.loop, request_message).result() + return unused + + def add_job(target: Callable[..., Any], *args: Any) -> asyncio.Future[Any]: + if target.__name__ == "find_unused_files": + return add_executor_job(find_and_request, target, *args) + return add_executor_job(target, *args) + + with patch.object(hass, "async_add_executor_job", side_effect=add_job): + await hass.services.async_call( + tts.DOMAIN, + tts.SERVICE_CLEAR_CACHE, + {TextToSpeechServiceArgument.DAYS: 30}, + blocking=True, + ) + + assert b"".join([chunk async for chunk in caches[0].async_stream_data()]) == ( + MOCK_DATA + ) + + assert cache_file.is_file() + + +async def test_service_clear_cache_days_concurrent_regenerate( + hass: HomeAssistant, + mock_tts_cache_dir: Path, + mock_tts_entity: MockTTSEntity, +) -> None: + """Test a message regenerated during clear cache isn't indexed without a file.""" + cache_file = mock_tts_cache_dir / DOORBELL_CACHE_FILE + await hass.async_add_executor_job(_write_cache_file, cache_file, 31) + await mock_config_entry_setup(hass, mock_tts_entity) + manager = hass.data[tts.DATA_TTS_MANAGER] + caches: list[tts.TTSCache] = [] + add_executor_job = hass.async_add_executor_job + + async def regenerate_and_remove( + remove_files: Callable[[dict[str, str]], dict[str, str]], + files: dict[str, str], + ) -> dict[str, str]: + caches.append( + manager.async_cache_message_in_memory( + "tts.test", "There is someone at the door.", True, "en_US", {} + ) + ) + await hass.async_block_till_done(wait_background_tasks=True) + return await add_executor_job(remove_files, files) + + def add_job(target: Callable[..., Any], *args: Any) -> asyncio.Future[Any]: + if getattr(target, "__name__", None) == "remove_files": + return asyncio.ensure_future(regenerate_and_remove(target, *args)) + return add_executor_job(target, *args) + + with patch.object(hass, "async_add_executor_job", side_effect=add_job): + await hass.services.async_call( + tts.DOMAIN, + tts.SERVICE_CLEAR_CACHE, + {TextToSpeechServiceArgument.DAYS: 30}, + blocking=True, + ) + + assert b"".join([chunk async for chunk in caches[0].async_stream_data()]) == ( + MOCK_DATA + ) + assert manager.file_cache == {} + assert not cache_file.is_file() + + class MockProviderEmpty(MockTTSProvider): """Mock provider with empty get_tts_audio."""