From a437d861f4b77eb043505a181da7d4c337fe9633 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:23:54 -0500 Subject: [PATCH 01/13] Pass through the voice pack list and packages for the app's Language page GET /voice-pkg/info?model= (and the plugin's own /app//voice-pkg/info path) fetches the official plugin's voice pack info file from the region's cosHost, falling back to its FDS host, and serves the last good copy when both fail. Each voice_pkg_url is rewritten to /voice-pkg/files//.pkg on this server, which downloads the pack once, caches it, and serves it to the robot, so the robot never needs to reach the cloud host itself. Model to bucket follows the plugin's device configs. Upstream requests carry X-RR-Voice-Proxy so a DNS loop back to this server answers 508 instead of recursing. Only allowlisted Roborock and Xiaomi FDS hosts are fetched. Co-Authored-By: Claude Opus 5.5 --- .../https_server/routes/plugin/dispatch.py | 18 +- .../https_server/routes/plugin/voice_pkg.py | 332 ++++++++++++++++++ src/roborock_local_server/server.py | 4 +- tests/test_voice_pkg_routes.py | 225 ++++++++++++ 4 files changed, 577 insertions(+), 2 deletions(-) create mode 100644 src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py create mode 100644 tests/test_voice_pkg_routes.py diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/dispatch.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/dispatch.py index c47b398a..da569a1c 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/dispatch.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/dispatch.py @@ -2,13 +2,16 @@ from __future__ import annotations +from collections.abc import Mapping from pathlib import Path +from typing import Any from fastapi.responses import Response from .category import source_from_category_path from .common import plugin_proxy_response from .proxy import source_from_proxy_request +from .voice_pkg import VoicePkgError, dispatch_voice_pkg_request PLUGIN_PROXY_ROUTE_NAME = "plugin_proxy" @@ -37,10 +40,23 @@ async def dispatch_plugin_zip_request( clean_path: str, query_params: dict[str, list[str]], runtime_dir: Path, + context: Any = None, + headers: Mapping[str, str] | None = None, ) -> PluginZipDispatchResult | None: source_url = resolve_plugin_zip_source(clean_path, query_params) if not source_url: - return None + if context is None: + return None + try: + return await dispatch_voice_pkg_request( + clean_path=clean_path, + query_params=query_params, + headers=headers or {}, + context=context, + runtime_dir=runtime_dir, + ) + except VoicePkgError as exc: + raise PluginZipDispatchError(route_name="voice_pkg_proxy", source_url=exc.source_url, cause=exc) from exc try: response = await plugin_proxy_response(runtime_dir=runtime_dir, source_url=source_url) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py new file mode 100644 index 00000000..9aa018ff --- /dev/null +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -0,0 +1,332 @@ +"""Voice pack list and package passthrough for the app's voice Language page.""" + +from __future__ import annotations + +import hashlib +import json +import re +from collections.abc import Mapping +from pathlib import Path +from typing import Any +from urllib.parse import urlparse + +import aiohttp +from fastapi.responses import JSONResponse, Response +from shared.context import ServerContext + +VOICE_INFO_ROUTE_NAME = "voice_pkg_info" +VOICE_FILE_ROUTE_NAME = "voice_pkg_file" +VOICE_PROXY_HEADER = "x-rr-voice-proxy" +VOICE_PKG_MAX_BYTES = 64 * 1024 * 1024 +VOICE_INFO_MAX_BYTES = 2 * 1024 * 1024 + +# The official plugin's areaServerMap: cosHost first (NewEndpoint robots), then the FDS host. +_REGION_HOSTS: dict[str, tuple[str, ...]] = { + "cn": ("cn-app.roborock.com", "cnbj2.fds.api.xiaomi.com"), + "us": ("us-app.roborock.com", "awsusor0.fds.api.xiaomi.com"), + "eu": ("eu-app.roborock.com", "awsde0.fds.api.xiaomi.com"), + "de": ("eu-app.roborock.com", "awsde0.fds.api.xiaomi.com"), + "ru": ("ksyru0-eco.fds.api.xiaomi.com",), +} +_DEFAULT_HOSTS = ("us-app.roborock.com", "awssgp0.fds.api.xiaomi.com") +_ALLOWED_HOSTS = {"us-app.roborock.com", "eu-app.roborock.com", "cn-app.roborock.com"} + +# Plugin product name (the voice-pkg bucket) to short model ids, from the plugin's device configs. +_BUCKET_MODELS: dict[str, tuple[str, ...]] = { + "pearl": ("a74", "a75"), + "pearls": ("a100", "a101"), + "pearlc": ("a103", "a104"), + "pearlclite": ("a198", "a199", "a205"), + "pearlplus": ("a86", "a87"), + "pearlpluss": ("a116", "a117", "a136"), + "pearlslite": ("a122", "a123"), + "pearle": ("a167", "a168"), + "pearleh": ("a325", "a326"), + "pearlepro": ("a169", "a170"), + "quinn": ("a293", "a294"), + "quinne": ("a358", "a359"), + "vivian": ("a134", "a135", "a155", "a156"), + "vivianc": ("a158", "a159", "a186", "a187", "a209", "a210", "a246"), + "vivianf": ("a182",), + "vivians": ("a184", "a185"), + "vivianspro": ("a225", "a226"), + "viviansproc": ("a297", "a298"), + "vida": ("a295", "a296"), + "viviansc": ("a196", "a197"), + "hera": ("a224", "a249"), + "pandora": ("a243", "a250"), + "beryllite": ("a244", "a245"), + "beryl": ("a120", "a121"), + "beryls": ("a306", "a307"), + "beryle": ("a311", "a312"), + "berylc": ("a327", "a328"), + "pearlfpro": ("a216", "a217"), + "coral": ("a20", "a21"), + "coralpro": ("a143", "a144", "a231", "a236", "a232", "a308"), + "coralpros": ("a219", "a220"), + "coralprosaw": ("a287", "a288"), + "r50": ("a157", "a179"), + "ultron": ("a50", "a51"), + "ultrone": ("a72", "a84"), + "ultronlite": ("a73", "a85"), + "ultronsc": ("a94", "a95"), + "ultronse": ("a124", "a125", "a139", "a140"), + "ultronsplus": ("a68", "a69", "a70"), + "ultronsv": ("a96", "a97"), + "verdelite": ("a146", "a147"), + "verdelites": ("a279", "a278"), + "topazs": ("a29", "a30", "a76"), + "topazsplus": ("a46", "a47", "a66"), + "topazspower": ("a62",), + "topazsc": ("a64", "a65"), + "topazsv": ("a26", "a27"), + "tanoss": ("a14", "a15"), + "tanossplus": ("a23", "a24"), + "tanosslite": ("a37", "a38"), + "talcsc": ("a360", "a361"), + "tanossc": ("a39", "a40"), + "tanosse": ("a33", "a34"), + "tanossmax": ("a52",), + "tanos": ("t6", "s6"), + "tanose": ("t7", "a11"), + "tanosv": ("t7p", "a09", "a10"), + "rubyplus": ("t4", "s4"), + "rubysc": ("p5", "a08"), + "rubyse": ("a19",), + "rubyslite": ("p6", "s5e", "a05"), +} +_MODEL_BUCKETS = { + model: bucket for bucket, models in _BUCKET_MODELS.items() for model in models +} +# These four keep the old "//app/voice-pkg/" layout. +_LEGACY_LAYOUT_BUCKETS = {"tanosv", "rubyplus", "rubyse", "rubysc"} + +_INFO_PATH = re.compile( + r"^(?:/app/[a-z0-9_]{1,40}/voice-pkg/|/[a-z0-9_]{1,40}/app/voice-pkg/)(?:debug/)?info$" +) +_FILE_PATH = re.compile( + r"^/voice-pkg/files/([a-z0-9.-]{1,80})(/[A-Za-z0-9_./-]{1,200}\.pkg)$" +) + + +class VoicePkgError(RuntimeError): + def __init__(self, message: str, *, source_url: str = "") -> None: + super().__init__(message) + self.source_url = source_url + + +def is_allowed_voice_host(host: str) -> bool: + host = host.strip().lower() + return host in _ALLOWED_HOSTS or host.endswith( + (".fds.api.xiaomi.com", ".fds.api.mi-img.com") + ) + + +def voice_info_path_for_model(model: str) -> str: + """The plugin's soundPackageFilePath plus "info" for a model id like roborock.vacuum.a245.""" + full = model.strip().lower() + short = full.rsplit(".", 1)[-1] + bucket = _MODEL_BUCKETS.get(short, "") + if not bucket: + return "" + if "a136" in full: + bucket = "ppscouple" + debug = "debug/" if full.endswith(("v2", "v3", "v4", "v5")) else "" + if bucket in _LEGACY_LAYOUT_BUCKETS: + prefix = f"/{'rubysc1' if bucket == 'rubysc' else bucket}/app/voice-pkg/" + else: + prefix = f"/app/{bucket}/voice-pkg/" + return f"{prefix}{debug}info" + + +def upstream_hosts(region: str) -> tuple[str, ...]: + return _REGION_HOSTS.get(region.strip().lower(), _DEFAULT_HOSTS) + + +async def fetch_voice_bytes(url: str, *, max_bytes: int, timeout_s: float) -> bytes: + timeout = aiohttp.ClientTimeout(total=timeout_s) + headers = {"User-Agent": "roborock-local-server/0.1", VOICE_PROXY_HEADER: "1"} + # No redirects, so the allowed-host check holds; the size cap is enforced while reading. + async with ( + aiohttp.ClientSession(timeout=timeout, headers=headers) as session, + session.get(url, allow_redirects=False) as response, + ): + if int(response.status) != 200: + raise RuntimeError(f"upstream returned HTTP {response.status}") + if response.content_length is not None and response.content_length > max_bytes: + raise RuntimeError(f"voice file too large: {response.content_length} bytes") + data = bytearray() + async for chunk in response.content.iter_chunked(64 * 1024): + data.extend(chunk) + if len(data) > max_bytes: + raise RuntimeError(f"voice file too large: over {max_bytes} bytes") + if not data: + raise RuntimeError("upstream returned empty content") + return bytes(data) + + +def _cache_dir(runtime_dir: Path) -> Path: + path = runtime_dir / "voice_pkg_cache" + path.mkdir(parents=True, exist_ok=True) + return path + + +def _digest(value: str) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest() + + +def _rewrite_info( + info: dict[str, Any], *, info_host: str, api_url: str +) -> dict[str, Any]: + """Points every voice_pkg_url at this server, rehosted on the list's host as the plugin does.""" + out = dict(info) + for key in ("voice_list", "special_voice_list", "factory_test_list"): + items = info.get(key) + if not isinstance(items, list): + continue + rewritten: list[Any] = [] + for item in items: + if isinstance(item, dict) and isinstance(item.get("voice_pkg_url"), str): + item = dict(item) + path = urlparse(item["voice_pkg_url"]).path + if path.endswith(".pkg"): + item["voice_pkg_source_url"] = f"https://{info_host}{path}" + item["voice_pkg_url"] = ( + f"{api_url}/voice-pkg/files/{info_host}{path}" + ) + rewritten.append(item) + out[key] = rewritten + out["voice_pkg_host"] = info_host + return out + + +async def _voice_info_response( + ctx: ServerContext, runtime_dir: Path, upstream_path: str +) -> tuple[str, Response]: + cache_file = _cache_dir(runtime_dir) / f"info-{_digest(upstream_path)[:24]}.json" + errors: list[str] = [] + for host in upstream_hosts(ctx.region): + url = f"https://{host}{upstream_path}" + try: + raw = await fetch_voice_bytes( + url, max_bytes=VOICE_INFO_MAX_BYTES, timeout_s=20 + ) + info = json.loads(raw) + if not isinstance(info, dict) or not isinstance( + info.get("voice_list"), list + ): + raise TypeError("upstream answer has no voice_list") + except Exception as exc: # noqa: BLE001 + errors.append(f"{host}: {exc}") + continue + cache_file.write_text( + json.dumps({"host": host, "info": info}), encoding="utf-8" + ) + body = _rewrite_info(info, info_host=host, api_url=ctx.api_url()) + return url, JSONResponse(body, headers={"X-RR-Voice-Cache": "miss"}) + if cache_file.exists(): + cached = json.loads(cache_file.read_text(encoding="utf-8")) + body = _rewrite_info( + cached["info"], info_host=cached["host"], api_url=ctx.api_url() + ) + return f"https://{cached['host']}{upstream_path}", JSONResponse( + body, headers={"X-RR-Voice-Cache": "stale"} + ) + raise VoicePkgError( + "; ".join(errors) or "no upstream host", source_url=upstream_path + ) + + +async def _voice_file_response( + runtime_dir: Path, host: str, path: str +) -> tuple[str, Response]: + source_url = f"https://{host}{path}" + cache_file = _cache_dir(runtime_dir) / f"{_digest(source_url)}.pkg" + headers = {"Cache-Control": "public, max-age=86400"} + if cache_file.exists(): + return source_url, Response( + cache_file.read_bytes(), + media_type="application/octet-stream", + headers={**headers, "X-RR-Voice-Cache": "hit"}, + ) + try: + payload = await fetch_voice_bytes( + source_url, max_bytes=VOICE_PKG_MAX_BYTES, timeout_s=120 + ) + except Exception as exc: + raise VoicePkgError(str(exc), source_url=source_url) from exc + temp = cache_file.with_suffix(".tmp") + temp.write_bytes(payload) + temp.replace(cache_file) + return source_url, Response( + payload, + media_type="application/octet-stream", + headers={**headers, "X-RR-Voice-Cache": "miss"}, + ) + + +async def dispatch_voice_pkg_request( + *, + clean_path: str, + query_params: dict[str, list[str]], + headers: Mapping[str, str], + context: ServerContext, + runtime_dir: Path, +) -> tuple[str, str, Response] | None: + """Answers the voice pack list and package paths, or None for any other path.""" + path = clean_path.rstrip("/") + upstream_path = "" + if path == "/voice-pkg/info": + model = next((v for v in query_params.get("model") or [] if v.strip()), "") + upstream_path = voice_info_path_for_model(model) + if not upstream_path: + return ( + VOICE_INFO_ROUTE_NAME, + "", + JSONResponse( + { + "success": False, + "code": 404, + "msg": "voice_pkg_unknown_model", + "data": {"model": model}, + }, + status_code=404, + ), + ) + elif _INFO_PATH.match(path): + upstream_path = path + file_match = _FILE_PATH.match(path) + if not upstream_path and not file_match: + return None + route = VOICE_INFO_ROUTE_NAME if upstream_path else VOICE_FILE_ROUTE_NAME + if any(k.lower() == VOICE_PROXY_HEADER for k in headers): + # Our own upstream request came back here (DNS points the cloud host at this server). + return ( + route, + "", + JSONResponse( + {"success": False, "code": 508, "msg": "voice_pkg_loop"}, + status_code=508, + ), + ) + if upstream_path: + source, response = await _voice_info_response( + context, runtime_dir, upstream_path + ) + return route, source, response + host, file_path = file_match.group(1), file_match.group(2) + if ( + not is_allowed_voice_host(host) + or "/voice-pkg/" not in file_path + or ".." in file_path + ): + return ( + route, + "", + JSONResponse( + {"success": False, "code": 403, "msg": "voice_pkg_host_not_allowed"}, + status_code=403, + ), + ) + source, response = await _voice_file_response(runtime_dir, host, file_path) + return route, source, response diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 99371d23..1cb26efc 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -1276,6 +1276,8 @@ async def _handle_roborock_request(self, request: Request) -> Response: clean_path=clean_path, query_params=query_params, runtime_dir=self.paths.runtime_dir, + context=self.context, + headers=request_headers, ) except PluginZipDispatchError as exc: route_name = exc.route_name @@ -1283,7 +1285,7 @@ async def _handle_roborock_request(self, request: Request) -> Response: error_payload = { "success": False, "code": 502, - "msg": "plugin_proxy_failed", + "msg": "voice_pkg_proxy_failed" if route_name == "voice_pkg_proxy" else "plugin_proxy_failed", "data": {"source": plugin_source, "error": str(exc)}, } entry["route"] = route_name diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py new file mode 100644 index 00000000..5f511579 --- /dev/null +++ b/tests/test_voice_pkg_routes.py @@ -0,0 +1,225 @@ +import json +from pathlib import Path + +from conftest import write_release_config +from fastapi.testclient import TestClient + +from roborock_local_server.config import load_config, resolve_paths +from roborock_local_server.server import ReleaseSupervisor + +INFO = { + "voice_pkg_version": 1, + "voice_list": [ + { + "voice_id": 3, + "version": 7, + "applicable": ["us"], + "lang": "en", + "voice_pri": 3, + "voice_title": "English", + "voice_pkg_url": "https://cnbj2.fds.api.xiaomi.com/app/beryllite/voice-pkg/package/en.pkg", + "voice_pkg_md5": "e4681aee0381290597475a598fdfdda6", + } + ], +} + + +def _client(tmp_path: Path) -> TestClient: + config_file = write_release_config(tmp_path) + config = load_config(config_file) + return TestClient( + ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)).app + ) + + +def _fake_fetch(monkeypatch, answers: dict[str, bytes]) -> list[str]: + from https_server.routes.plugin import voice_pkg + + calls: list[str] = [] + + async def fake(url: str, *, max_bytes: int, timeout_s: float) -> bytes: + calls.append(url) + if url not in answers: + raise RuntimeError("upstream returned HTTP 404") + return answers[url] + + monkeypatch.setattr(voice_pkg, "fetch_voice_bytes", fake) + return calls + + +def test_model_maps_to_the_plugin_sound_package_path() -> None: + from https_server.routes.plugin.voice_pkg import voice_info_path_for_model + + assert ( + voice_info_path_for_model("roborock.vacuum.a245") + == "/app/beryllite/voice-pkg/info" + ) + assert ( + voice_info_path_for_model("roborock.vacuum.a136") + == "/app/ppscouple/voice-pkg/info" + ) + assert ( + voice_info_path_for_model("roborock.vacuum.a08") + == "/rubysc1/app/voice-pkg/info" + ) + assert ( + voice_info_path_for_model("roborock.vacuum.a19") == "/rubyse/app/voice-pkg/info" + ) + assert voice_info_path_for_model("roborock.vacuum.zzz") == "" + + +def test_info_is_fetched_from_the_region_host_and_urls_point_at_this_server( + tmp_path: Path, monkeypatch +) -> None: + upstream = "https://us-app.roborock.com/app/beryllite/voice-pkg/info" + calls = _fake_fetch(monkeypatch, {upstream: json.dumps(INFO).encode()}) + client = _client(tmp_path) + + response = client.get("/voice-pkg/info", params={"model": "roborock.vacuum.a245"}) + + assert response.status_code == 200 + assert calls == [upstream] + item = response.json()["voice_list"][0] + assert item["voice_pkg_url"] == ( + "https://api-roborock.example.com/voice-pkg/files/us-app.roborock.com/app/beryllite/voice-pkg/package/en.pkg" + ) + assert ( + item["voice_pkg_source_url"] + == "https://us-app.roborock.com/app/beryllite/voice-pkg/package/en.pkg" + ) + assert item["voice_pkg_md5"] == INFO["voice_list"][0]["voice_pkg_md5"] + assert response.json()["voice_pkg_host"] == "us-app.roborock.com" + + +def test_info_falls_back_to_the_fds_host_then_to_the_cached_copy( + tmp_path: Path, monkeypatch +) -> None: + fds = "https://awsusor0.fds.api.xiaomi.com/app/beryllite/voice-pkg/info" + calls = _fake_fetch(monkeypatch, {fds: json.dumps(INFO).encode()}) + client = _client(tmp_path) + + first = client.get("/app/beryllite/voice-pkg/info?time=1") + assert first.status_code == 200 + assert first.headers["X-RR-Voice-Cache"] == "miss" + assert calls[-1] == fds + + _fake_fetch(monkeypatch, {}) + stale = client.get("/app/beryllite/voice-pkg/info") + assert stale.status_code == 200 + assert stale.headers["X-RR-Voice-Cache"] == "stale" + assert stale.json()["voice_list"][0]["voice_id"] == 3 + + +def test_info_without_any_upstream_is_a_502(tmp_path: Path, monkeypatch) -> None: + _fake_fetch(monkeypatch, {}) + response = _client(tmp_path).get("/voice-pkg/info?model=roborock.vacuum.a245") + assert response.status_code == 502 + + +def test_unknown_model_is_a_404(tmp_path: Path, monkeypatch) -> None: + calls = _fake_fetch(monkeypatch, {}) + response = _client(tmp_path).get("/voice-pkg/info?model=roborock.vacuum.zzz") + assert response.status_code == 404 + assert calls == [] + + +def test_package_is_proxied_once_then_served_from_cache( + tmp_path: Path, monkeypatch +) -> None: + source = "https://us-app.roborock.com/app/beryllite/voice-pkg/package/en.pkg" + calls = _fake_fetch(monkeypatch, {source: b"pkg-bytes"}) + client = _client(tmp_path) + path = "/voice-pkg/files/us-app.roborock.com/app/beryllite/voice-pkg/package/en.pkg" + + first = client.get(path) + second = client.get(path) + + assert first.content == second.content == b"pkg-bytes" + assert first.headers["X-RR-Voice-Cache"] == "miss" + assert second.headers["X-RR-Voice-Cache"] == "hit" + assert calls == [source] + + +def test_package_from_an_unknown_host_is_refused(tmp_path: Path, monkeypatch) -> None: + calls = _fake_fetch(monkeypatch, {}) + response = _client(tmp_path).get( + "/voice-pkg/files/example.com/app/x/voice-pkg/package/en.pkg" + ) + assert response.status_code == 403 + assert calls == [] + + +def test_a_request_from_our_own_proxy_is_not_proxied_again( + tmp_path: Path, monkeypatch +) -> None: + calls = _fake_fetch(monkeypatch, {}) + response = _client(tmp_path).get( + "/app/beryllite/voice-pkg/info", headers={"X-RR-Voice-Proxy": "1"} + ) + assert response.status_code == 508 + assert calls == [] + + +def _serve_and_fetch(app, path: str, max_bytes: int) -> Exception | None: + import asyncio + + from aiohttp import web + + from roborock_local_server.bundled_backend.https_server.routes.plugin import ( + voice_pkg, + ) + + async def run() -> Exception | None: + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + port = site._server.sockets[0].getsockname()[1] # type: ignore[union-attr] + try: + await voice_pkg.fetch_voice_bytes( + f"http://127.0.0.1:{port}{path}", max_bytes=max_bytes, timeout_s=5 + ) + except Exception as exc: # noqa: BLE001 + return exc + finally: + await runner.cleanup() + return None + + return asyncio.run(run()) + + +def test_fetch_does_not_follow_redirects_off_the_allowed_host() -> None: + from aiohttp import web + + async def redirect(_request): + raise web.HTTPFound("http://example.invalid/evil.pkg") + + app = web.Application() + app.router.add_get("/a.pkg", redirect) + error = _serve_and_fetch(app, "/a.pkg", max_bytes=1024) + assert error is not None and "HTTP 302" in str(error) + + +def test_fetch_stops_reading_past_the_size_cap() -> None: + from aiohttp import web + + async def big(_request): + response = web.StreamResponse() + await response.prepare(_request) + for _ in range(64): + await response.write(b"x" * 1024) + return response + + async def declared(_request): + return web.Response(body=b"x" * 4096) + + def app(): + application = web.Application() + application.router.add_get("/big.pkg", big) + application.router.add_get("/declared.pkg", declared) + return application + + streamed = _serve_and_fetch(app(), "/big.pkg", max_bytes=8 * 1024) + assert streamed is not None and "too large" in str(streamed) + by_length = _serve_and_fetch(app(), "/declared.pkg", max_bytes=1024) + assert by_length is not None and "too large: 4096" in str(by_length) From f8bd8731aaf1fa8e5197d659326821d736cf75c8 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:18:02 -0500 Subject: [PATCH 02/13] Use the legacy voice-pkg layout for tanos and tanose too The plugin's soundPackageFilePath uses //app/voice-pkg/ for Tanos, TanosE, TanosV, RubyPlus, RubySE and RubySC (p223 L281411-281523). The set was missing tanos and tanose, so t6, s6, t7 and a11 asked for the wrong path. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 4 ++-- tests/test_voice_pkg_routes.py | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index 9aa018ff..a108f560 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -98,8 +98,8 @@ _MODEL_BUCKETS = { model: bucket for bucket, models in _BUCKET_MODELS.items() for model in models } -# These four keep the old "//app/voice-pkg/" layout. -_LEGACY_LAYOUT_BUCKETS = {"tanosv", "rubyplus", "rubyse", "rubysc"} +# These keep the old "//app/voice-pkg/" layout. +_LEGACY_LAYOUT_BUCKETS = {"tanos", "tanose", "tanosv", "rubyplus", "rubyse", "rubysc"} _INFO_PATH = re.compile( r"^(?:/app/[a-z0-9_]{1,40}/voice-pkg/|/[a-z0-9_]{1,40}/app/voice-pkg/)(?:debug/)?info$" diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index 5f511579..54fc1382 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -68,6 +68,17 @@ def test_model_maps_to_the_plugin_sound_package_path() -> None: assert voice_info_path_for_model("roborock.vacuum.zzz") == "" +def test_tanos_and_tanose_use_the_legacy_layout() -> None: + from https_server.routes.plugin.voice_pkg import voice_info_path_for_model + + cases = (("t6", "tanos"), ("s6", "tanos"), ("t7", "tanose"), ("a11", "tanose")) + for short, bucket in cases: + assert ( + voice_info_path_for_model(f"roborock.vacuum.{short}") + == f"/{bucket}/app/voice-pkg/info" + ) + + def test_info_is_fetched_from_the_region_host_and_urls_point_at_this_server( tmp_path: Path, monkeypatch ) -> None: From 4ed9a7e9359b70209ddb2a1699424a00ba386606 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:18:13 -0500 Subject: [PATCH 03/13] Use the parent's voice-pkg bucket for inherited device configs createDeviceModelConfig takes bucket = product only when forceRealResource is truthy, otherwise the inherited config's bucket (p223 L281131-281183). PearlEH, VivianF, Pandora and PearlFPro pass false and TalcSC passes nothing, so they use pearle, vivian, vivian, viviansc and tanosslite. Every other inheriting entry passes true and keeps its own product name. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 15 +++++---------- tests/test_voice_pkg_routes.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index a108f560..5886a03b 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -31,7 +31,7 @@ _DEFAULT_HOSTS = ("us-app.roborock.com", "awssgp0.fds.api.xiaomi.com") _ALLOWED_HOSTS = {"us-app.roborock.com", "eu-app.roborock.com", "cn-app.roborock.com"} -# Plugin product name (the voice-pkg bucket) to short model ids, from the plugin's device configs. +# Voice-pkg bucket to short model ids; a config that inherits without forceRealResource uses its parent's bucket. _BUCKET_MODELS: dict[str, tuple[str, ...]] = { "pearl": ("a74", "a75"), "pearls": ("a100", "a101"), @@ -40,27 +40,23 @@ "pearlplus": ("a86", "a87"), "pearlpluss": ("a116", "a117", "a136"), "pearlslite": ("a122", "a123"), - "pearle": ("a167", "a168"), - "pearleh": ("a325", "a326"), + "pearle": ("a167", "a168", "a325", "a326"), "pearlepro": ("a169", "a170"), "quinn": ("a293", "a294"), "quinne": ("a358", "a359"), - "vivian": ("a134", "a135", "a155", "a156"), + "vivian": ("a134", "a135", "a155", "a156", "a182", "a243", "a250"), "vivianc": ("a158", "a159", "a186", "a187", "a209", "a210", "a246"), - "vivianf": ("a182",), "vivians": ("a184", "a185"), "vivianspro": ("a225", "a226"), "viviansproc": ("a297", "a298"), "vida": ("a295", "a296"), - "viviansc": ("a196", "a197"), + "viviansc": ("a196", "a197", "a216", "a217"), "hera": ("a224", "a249"), - "pandora": ("a243", "a250"), "beryllite": ("a244", "a245"), "beryl": ("a120", "a121"), "beryls": ("a306", "a307"), "beryle": ("a311", "a312"), "berylc": ("a327", "a328"), - "pearlfpro": ("a216", "a217"), "coral": ("a20", "a21"), "coralpro": ("a143", "a144", "a231", "a236", "a232", "a308"), "coralpros": ("a219", "a220"), @@ -82,8 +78,7 @@ "topazsv": ("a26", "a27"), "tanoss": ("a14", "a15"), "tanossplus": ("a23", "a24"), - "tanosslite": ("a37", "a38"), - "talcsc": ("a360", "a361"), + "tanosslite": ("a37", "a38", "a360", "a361"), "tanossc": ("a39", "a40"), "tanosse": ("a33", "a34"), "tanossmax": ("a52",), diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index 54fc1382..903d0139 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -79,6 +79,24 @@ def test_tanos_and_tanose_use_the_legacy_layout() -> None: ) +def test_inherited_configs_use_their_parents_bucket() -> None: + from https_server.routes.plugin.voice_pkg import voice_info_path_for_model + + expected = { + "a325": "pearle", + "a182": "vivian", + "a243": "vivian", + "a250": "vivian", + "a216": "viviansc", + "a360": "tanosslite", + } + for short, bucket in expected.items(): + assert ( + voice_info_path_for_model(f"roborock.vacuum.{short}") + == f"/app/{bucket}/voice-pkg/info" + ) + + def test_info_is_fetched_from_the_region_host_and_urls_point_at_this_server( tmp_path: Path, monkeypatch ) -> None: From 2e57b88015572d06216fafd4ae5a63d0931dc192 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:18:51 -0500 Subject: [PATCH 04/13] Make concurrent voice pack requests safe and bound the package cache Two requests for the same package wrote the same .tmp file and both downloaded it, and concurrent info misses raced on the cache file. Callers with the same key now share one in-flight fetch, cache writes go through a unique temp file plus replace, and the package cache keeps the newest 64 files (hits refresh the mtime) and drops stale temp files. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 108 +++++++++++++++--- tests/test_voice_pkg_routes.py | 94 +++++++++++++++ 2 files changed, 184 insertions(+), 18 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index 5886a03b..84039387 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -2,12 +2,17 @@ from __future__ import annotations +import asyncio +import contextlib import hashlib import json +import os import re -from collections.abc import Mapping +import time +import uuid +from collections.abc import Awaitable, Callable, Mapping from pathlib import Path -from typing import Any +from typing import Any, TypeVar from urllib.parse import urlparse import aiohttp @@ -19,6 +24,8 @@ VOICE_PROXY_HEADER = "x-rr-voice-proxy" VOICE_PKG_MAX_BYTES = 64 * 1024 * 1024 VOICE_INFO_MAX_BYTES = 2 * 1024 * 1024 +VOICE_PKG_CACHE_MAX_FILES = 64 +_STALE_TMP_SECONDS = 3600 # The official plugin's areaServerMap: cosHost first (NewEndpoint robots), then the FDS host. _REGION_HOSTS: dict[str, tuple[str, ...]] = { @@ -170,6 +177,50 @@ def _digest(value: str) -> str: return hashlib.sha256(value.encode("utf-8")).hexdigest() +_T = TypeVar("_T") +_inflight: dict[str, asyncio.Task[Any]] = {} + + +def _consume_exception(task: asyncio.Task[Any]) -> None: + if not task.cancelled(): + task.exception() + + +async def _single_flight(key: str, factory: Callable[[], Awaitable[_T]]) -> _T: + """Concurrent callers with the same key share one run of factory.""" + task = _inflight.get(key) + if task is None: + task = asyncio.ensure_future(factory()) + _inflight[key] = task + task.add_done_callback(lambda _t: _inflight.pop(key, None)) + task.add_done_callback(_consume_exception) + return await asyncio.shield(task) + + +def _write_atomic(path: Path, data: bytes) -> None: + temp = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp") + temp.write_bytes(data) + temp.replace(path) + + +def _evict_old_packages(cache_dir: Path) -> None: + """Keeps the newest VOICE_PKG_CACHE_MAX_FILES packages and drops stale temp files.""" + now = time.time() + packages: list[tuple[float, Path]] = [] + for entry in cache_dir.iterdir(): + try: + mtime = entry.stat().st_mtime + if entry.suffix == ".tmp" and now - mtime > _STALE_TMP_SECONDS: + entry.unlink() + elif entry.suffix == ".pkg": + packages.append((mtime, entry)) + except OSError: + continue + packages.sort(key=lambda item: item[0], reverse=True) + for _, entry in packages[VOICE_PKG_CACHE_MAX_FILES:]: + entry.unlink(missing_ok=True) + + def _rewrite_info( info: dict[str, Any], *, info_host: str, api_url: str ) -> dict[str, Any]: @@ -195,10 +246,9 @@ def _rewrite_info( return out -async def _voice_info_response( - ctx: ServerContext, runtime_dir: Path, upstream_path: str -) -> tuple[str, Response]: - cache_file = _cache_dir(runtime_dir) / f"info-{_digest(upstream_path)[:24]}.json" +async def _fetch_info( + ctx: ServerContext, cache_file: Path, upstream_path: str +) -> tuple[str, dict[str, Any]]: errors: list[str] = [] for host in upstream_hosts(ctx.region): url = f"https://{host}{upstream_path}" @@ -214,12 +264,27 @@ async def _voice_info_response( except Exception as exc: # noqa: BLE001 errors.append(f"{host}: {exc}") continue - cache_file.write_text( - json.dumps({"host": host, "info": info}), encoding="utf-8" + _write_atomic( + cache_file, json.dumps({"host": host, "info": info}).encode("utf-8") ) - body = _rewrite_info(info, info_host=host, api_url=ctx.api_url()) - return url, JSONResponse(body, headers={"X-RR-Voice-Cache": "miss"}) - if cache_file.exists(): + return host, info + raise VoicePkgError( + "; ".join(errors) or "no upstream host", source_url=upstream_path + ) + + +async def _voice_info_response( + ctx: ServerContext, runtime_dir: Path, upstream_path: str +) -> tuple[str, Response]: + cache_file = _cache_dir(runtime_dir) / f"info-{_digest(upstream_path)[:24]}.json" + try: + host, info = await _single_flight( + f"info:{ctx.region}:{cache_file}", + lambda: _fetch_info(ctx, cache_file, upstream_path), + ) + except VoicePkgError: + if not cache_file.exists(): + raise cached = json.loads(cache_file.read_text(encoding="utf-8")) body = _rewrite_info( cached["info"], info_host=cached["host"], api_url=ctx.api_url() @@ -227,8 +292,9 @@ async def _voice_info_response( return f"https://{cached['host']}{upstream_path}", JSONResponse( body, headers={"X-RR-Voice-Cache": "stale"} ) - raise VoicePkgError( - "; ".join(errors) or "no upstream host", source_url=upstream_path + body = _rewrite_info(info, info_host=host, api_url=ctx.api_url()) + return f"https://{host}{upstream_path}", JSONResponse( + body, headers={"X-RR-Voice-Cache": "miss"} ) @@ -239,20 +305,26 @@ async def _voice_file_response( cache_file = _cache_dir(runtime_dir) / f"{_digest(source_url)}.pkg" headers = {"Cache-Control": "public, max-age=86400"} if cache_file.exists(): + with contextlib.suppress(OSError): + os.utime(cache_file) return source_url, Response( cache_file.read_bytes(), media_type="application/octet-stream", headers={**headers, "X-RR-Voice-Cache": "hit"}, ) - try: - payload = await fetch_voice_bytes( + + async def download() -> bytes: + data = await fetch_voice_bytes( source_url, max_bytes=VOICE_PKG_MAX_BYTES, timeout_s=120 ) + _write_atomic(cache_file, data) + _evict_old_packages(cache_file.parent) + return data + + try: + payload = await _single_flight(f"pkg:{cache_file}", download) except Exception as exc: raise VoicePkgError(str(exc), source_url=source_url) from exc - temp = cache_file.with_suffix(".tmp") - temp.write_bytes(payload) - temp.replace(cache_file) return source_url, Response( payload, media_type="application/octet-stream", diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index 903d0139..0b032ff5 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -252,3 +252,97 @@ def app(): assert streamed is not None and "too large" in str(streamed) by_length = _serve_and_fetch(app(), "/declared.pkg", max_bytes=1024) assert by_length is not None and "too large: 4096" in str(by_length) + + +def test_concurrent_requests_for_one_package_download_it_once( + tmp_path: Path, monkeypatch +) -> None: + import asyncio + + from https_server.routes.plugin import voice_pkg + + calls: list[str] = [] + + async def slow(url: str, *, max_bytes: int, timeout_s: float) -> bytes: + calls.append(url) + await asyncio.sleep(0.05) + return b"pkg-bytes" + + monkeypatch.setattr(voice_pkg, "fetch_voice_bytes", slow) + + async def run() -> list[bytes]: + results = await asyncio.gather( + *( + voice_pkg._voice_file_response( + tmp_path, "us-app.roborock.com", "/a/voice-pkg/package/en.pkg" + ) + for _ in range(4) + ) + ) + return [response.body for _, response in results] + + bodies = asyncio.run(run()) + + assert bodies == [b"pkg-bytes"] * 4 + assert len(calls) == 1 + cache_dir = tmp_path / "voice_pkg_cache" + assert [p.suffix for p in cache_dir.iterdir()] == [".pkg"] + + +def test_concurrent_info_requests_share_one_upstream_fetch( + tmp_path: Path, monkeypatch +) -> None: + import asyncio + from types import SimpleNamespace + + from https_server.routes.plugin import voice_pkg + + calls: list[str] = [] + + async def slow(url: str, *, max_bytes: int, timeout_s: float) -> bytes: + calls.append(url) + await asyncio.sleep(0.05) + return json.dumps(INFO).encode() + + monkeypatch.setattr(voice_pkg, "fetch_voice_bytes", slow) + ctx = SimpleNamespace(region="us", api_url=lambda: "https://api.example") + + async def run() -> list[int]: + results = await asyncio.gather( + *( + voice_pkg._voice_info_response( + ctx, tmp_path, "/app/beryllite/voice-pkg/info" + ) + for _ in range(4) + ) + ) + return [response.status_code for _, response in results] + + assert asyncio.run(run()) == [200] * 4 + assert len(calls) == 1 + + +def test_package_cache_keeps_only_the_newest_files(tmp_path: Path, monkeypatch) -> None: + import os + + from https_server.routes.plugin import voice_pkg + + monkeypatch.setattr(voice_pkg, "VOICE_PKG_CACHE_MAX_FILES", 3) + for index in range(5): + path = tmp_path / f"{index}.pkg" + path.write_bytes(b"x") + os.utime(path, (1000 + index, 1000 + index)) + stale_tmp = tmp_path / "old.pkg.abc.tmp" + stale_tmp.write_bytes(b"x") + os.utime(stale_tmp, (1, 1)) + info = tmp_path / "info-x.json" + info.write_bytes(b"{}") + + voice_pkg._evict_old_packages(tmp_path) + + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "2.pkg", + "3.pkg", + "4.pkg", + "info-x.json", + ] From e0877ca1d7c77969fbb648d21529265fed74b7af Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:19:11 -0500 Subject: [PATCH 05/13] Say plainly that the official app does not use the rewritten voice URLs The plugin builds the robot URL as 'https://' + getResHost() + voice_pkg_url.split('.com')[1] (p223 L1318756-1318805), so our host never reaches the robot. Without a .com in our URL it falls back to the original path on Roborock's res host. With one it cuts at the first .com and sends a garbled path. Redirecting us-app.roborock.com through mitm_redirect.py is not a safe fix: the robot resolves that host itself and whether it accepts our TLS certificate or md5 is unverified. Only clients that pass the URL unchanged, such as LocalRock, install from this server. The module docstring and a test now state this. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 5 ++-- tests/test_voice_pkg_routes.py | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index 84039387..3614a61e 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -1,4 +1,5 @@ -"""Voice pack list and package passthrough for the app's voice Language page.""" +"""Voice pack list and package passthrough for clients that give our URL to the robot unchanged. +The official app rebuilds the robot URL on its own res host and discards ours (see tests).""" from __future__ import annotations @@ -224,7 +225,7 @@ def _evict_old_packages(cache_dir: Path) -> None: def _rewrite_info( info: dict[str, Any], *, info_host: str, api_url: str ) -> dict[str, Any]: - """Points every voice_pkg_url at this server, rehosted on the list's host as the plugin does.""" + """Points every voice_pkg_url at this server and records the upstream URL as voice_pkg_source_url.""" out = dict(info) for key in ("voice_list", "special_voice_list", "factory_test_list"): items = info.get(key) diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index 0b032ff5..dab5ff40 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -97,6 +97,33 @@ def test_inherited_configs_use_their_parents_bucket() -> None: ) +def _plugin_robot_url(res_host: str, voice_pkg_url: str) -> str: + """What the official plugin sends the robot: 'https://' + resHost + url.split('.com')[1].""" + return "https://" + res_host + voice_pkg_url.split(".com")[1] + + +def test_official_plugin_discards_the_rewritten_host() -> None: + from https_server.routes.plugin.voice_pkg import _rewrite_info + + def rewritten(api_url: str) -> str: + info = _rewrite_info(INFO, info_host="us-app.roborock.com", api_url=api_url) + return info["voice_list"][0]["voice_pkg_url"] + + # No ".com" in our URL: the plugin falls back to the original path on Roborock's host. + plain = rewritten("https://home.lan") + assert _plugin_robot_url("us-app.roborock.com", plain) == ( + "https://us-app.roborock.com/app/beryllite/voice-pkg/package/en.pkg" + ) + # ".com" in our URL: the plugin cuts at the first one and the URL is garbled. + dotcom = rewritten("https://api-roborock.example.com") + assert _plugin_robot_url("us-app.roborock.com", dotcom) == ( + "https://us-app.roborock.com/voice-pkg/files/us-app.roborock" + ) + # Either way the robot never receives our host, so only clients that pass the URL + # through unchanged (LocalRock) install from this server. + assert "home.lan" not in _plugin_robot_url("us-app.roborock.com", plain) + + def test_info_is_fetched_from_the_region_host_and_urls_point_at_this_server( tmp_path: Path, monkeypatch ) -> None: From 6af0ca99ca42853132a46f612065d2379ccc3b88 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:10:31 -0500 Subject: [PATCH 06/13] Treat a cache hit that vanishes before the read as a miss Eviction can delete a package between the exists() check and read_bytes(). The hit path now reads once and falls through to a download if the file is gone. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 8 ++++-- tests/test_voice_pkg_routes.py | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index 3614a61e..b9bfe89c 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -305,11 +305,15 @@ async def _voice_file_response( source_url = f"https://{host}{path}" cache_file = _cache_dir(runtime_dir) / f"{_digest(source_url)}.pkg" headers = {"Cache-Control": "public, max-age=86400"} - if cache_file.exists(): + try: + cached = cache_file.read_bytes() + except OSError: + cached = None # missing or evicted while we looked: treat as a miss + if cached is not None: with contextlib.suppress(OSError): os.utime(cache_file) return source_url, Response( - cache_file.read_bytes(), + cached, media_type="application/octet-stream", headers={**headers, "X-RR-Voice-Cache": "hit"}, ) diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index dab5ff40..c9f83822 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -373,3 +373,31 @@ def test_package_cache_keeps_only_the_newest_files(tmp_path: Path, monkeypatch) "4.pkg", "info-x.json", ] + + +def test_cache_hit_that_vanishes_before_the_read_is_a_miss( + tmp_path: Path, monkeypatch +) -> None: + import asyncio + + from https_server.routes.plugin import voice_pkg + + source = "https://us-app.roborock.com/a/voice-pkg/package/en.pkg" + _fake_fetch(monkeypatch, {source: b"fresh"}) + cache_dir = tmp_path / "voice_pkg_cache" + cache_dir.mkdir() + real = Path.read_bytes + + def vanishing(self: Path) -> bytes: + if self.suffix == ".pkg": + raise FileNotFoundError(str(self)) + return real(self) + + monkeypatch.setattr(Path, "read_bytes", vanishing) + _, response = asyncio.run( + voice_pkg._voice_file_response( + tmp_path, "us-app.roborock.com", "/a/voice-pkg/package/en.pkg" + ) + ) + assert response.body == b"fresh" + assert response.headers["X-RR-Voice-Cache"] == "miss" From 7c7f4dac65eb0b17c3847c8261dce59e39e360db Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:10:32 -0500 Subject: [PATCH 07/13] Cap the voice package cache by total bytes as well as file count 64 files of up to 64 MB each could fill 4 GB, and any client can request packages. Eviction now also drops the oldest packages once the cache passes 512 MB. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 16 +++++++++++----- tests/test_voice_pkg_routes.py | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index b9bfe89c..129a6922 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -26,6 +26,7 @@ VOICE_PKG_MAX_BYTES = 64 * 1024 * 1024 VOICE_INFO_MAX_BYTES = 2 * 1024 * 1024 VOICE_PKG_CACHE_MAX_FILES = 64 +VOICE_PKG_CACHE_MAX_BYTES = 512 * 1024 * 1024 _STALE_TMP_SECONDS = 3600 # The official plugin's areaServerMap: cosHost first (NewEndpoint robots), then the FDS host. @@ -205,21 +206,26 @@ def _write_atomic(path: Path, data: bytes) -> None: def _evict_old_packages(cache_dir: Path) -> None: - """Keeps the newest VOICE_PKG_CACHE_MAX_FILES packages and drops stale temp files.""" + """Keeps the newest packages within the file and byte caps and drops stale temp files.""" now = time.time() - packages: list[tuple[float, Path]] = [] + packages: list[tuple[float, int, Path]] = [] for entry in cache_dir.iterdir(): try: mtime = entry.stat().st_mtime if entry.suffix == ".tmp" and now - mtime > _STALE_TMP_SECONDS: entry.unlink() elif entry.suffix == ".pkg": - packages.append((mtime, entry)) + packages.append((mtime, entry.stat().st_size, entry)) except OSError: continue packages.sort(key=lambda item: item[0], reverse=True) - for _, entry in packages[VOICE_PKG_CACHE_MAX_FILES:]: - entry.unlink(missing_ok=True) + kept_bytes = 0 + for index, (_, size, entry) in enumerate(packages): + kept_bytes += size + if index >= VOICE_PKG_CACHE_MAX_FILES or kept_bytes > VOICE_PKG_CACHE_MAX_BYTES: + kept_bytes -= size + with contextlib.suppress(OSError): + entry.unlink(missing_ok=True) def _rewrite_info( diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index c9f83822..df78205d 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -401,3 +401,19 @@ def vanishing(self: Path) -> bytes: ) assert response.body == b"fresh" assert response.headers["X-RR-Voice-Cache"] == "miss" + + +def test_package_cache_is_bounded_by_total_bytes(tmp_path: Path, monkeypatch) -> None: + import os + + from https_server.routes.plugin import voice_pkg + + monkeypatch.setattr(voice_pkg, "VOICE_PKG_CACHE_MAX_BYTES", 25) + for index in range(4): + path = tmp_path / f"{index}.pkg" + path.write_bytes(b"x" * 10) + os.utime(path, (1000 + index, 1000 + index)) + + voice_pkg._evict_old_packages(tmp_path) + + assert sorted(p.name for p in tmp_path.iterdir()) == ["2.pkg", "3.pkg"] From 808e28267995cae06cdc5d6db5250693f5ffaf70 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:10:32 -0500 Subject: [PATCH 08/13] Look up v2 to v5 model strings by their base model id The plugin's model list holds v2 to v5 (p223 L280750-280830, concat of prefix, '.', short, 'vN'), but the bucket lookup used the whole suffix, so those models returned unknown and the debug/ path was unreachable. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 9 ++++++--- tests/test_voice_pkg_routes.py | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index 129a6922..18ecc1f6 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -130,17 +130,20 @@ def voice_info_path_for_model(model: str) -> str: """The plugin's soundPackageFilePath plus "info" for a model id like roborock.vacuum.a245.""" full = model.strip().lower() short = full.rsplit(".", 1)[-1] - bucket = _MODEL_BUCKETS.get(short, "") + debug = full.endswith(("v2", "v3", "v4", "v5")) + # The plugin's model list also holds "v2" to "v5" (p223 L280750-280830). + bucket = _MODEL_BUCKETS.get( + short[:-2] if debug else short, "" + ) or _MODEL_BUCKETS.get(short, "") if not bucket: return "" if "a136" in full: bucket = "ppscouple" - debug = "debug/" if full.endswith(("v2", "v3", "v4", "v5")) else "" if bucket in _LEGACY_LAYOUT_BUCKETS: prefix = f"/{'rubysc1' if bucket == 'rubysc' else bucket}/app/voice-pkg/" else: prefix = f"/app/{bucket}/voice-pkg/" - return f"{prefix}{debug}info" + return f"{prefix}{'debug/' if debug else ''}info" def upstream_hosts(region: str) -> tuple[str, ...]: diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index df78205d..ad580c07 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -375,6 +375,20 @@ def test_package_cache_keeps_only_the_newest_files(tmp_path: Path, monkeypatch) ] +def test_v2_to_v5_model_strings_use_the_debug_path() -> None: + from https_server.routes.plugin.voice_pkg import voice_info_path_for_model + + assert ( + voice_info_path_for_model("roborock.vacuum.a245v4") + == "/app/beryllite/voice-pkg/debug/info" + ) + assert ( + voice_info_path_for_model("roborock.vacuum.t6v2") + == "/tanos/app/voice-pkg/debug/info" + ) + assert voice_info_path_for_model("roborock.vacuum.zzzv2") == "" + + def test_cache_hit_that_vanishes_before_the_read_is_a_miss( tmp_path: Path, monkeypatch ) -> None: From 79bb7b1ec048f3e853901177b70c87f48f9abba6 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:14:52 -0500 Subject: [PATCH 09/13] Key the voice info cache file by region as well as path The in-flight key already included the region, but the cache file name did not, so a stale answer cached for one region could be served for another whose upstream hosts differ. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 8 ++++-- tests/test_voice_pkg_routes.py | 26 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index 18ecc1f6..2f03ea86 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -286,10 +286,14 @@ async def _fetch_info( async def _voice_info_response( ctx: ServerContext, runtime_dir: Path, upstream_path: str ) -> tuple[str, Response]: - cache_file = _cache_dir(runtime_dir) / f"info-{_digest(upstream_path)[:24]}.json" + region = ctx.region.strip().lower() + cache_file = ( + _cache_dir(runtime_dir) + / f"info-{_digest(f'{region}:{upstream_path}')[:24]}.json" + ) try: host, info = await _single_flight( - f"info:{ctx.region}:{cache_file}", + f"info:{region}:{cache_file}", lambda: _fetch_info(ctx, cache_file, upstream_path), ) except VoicePkgError: diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index ad580c07..d6bde248 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -431,3 +431,29 @@ def test_package_cache_is_bounded_by_total_bytes(tmp_path: Path, monkeypatch) -> voice_pkg._evict_old_packages(tmp_path) assert sorted(p.name for p in tmp_path.iterdir()) == ["2.pkg", "3.pkg"] + + +def test_info_cache_is_kept_per_region(tmp_path: Path, monkeypatch) -> None: + from https_server.routes.plugin import voice_pkg + + class Ctx: + def __init__(self, region: str) -> None: + self.region = region + + def api_url(self) -> str: + return "https://api-roborock.example.com" + + import asyncio + + path = "/app/beryllite/voice-pkg/info" + _fake_fetch( + monkeypatch, {"https://us-app.roborock.com" + path: json.dumps(INFO).encode()} + ) + asyncio.run(voice_pkg._voice_info_response(Ctx("us"), tmp_path, path)) + _fake_fetch(monkeypatch, {}) + try: + asyncio.run(voice_pkg._voice_info_response(Ctx("eu"), tmp_path, path)) + except voice_pkg.VoicePkgError: + pass + else: + raise AssertionError("an eu request must not be answered from the us cache") From 10681691b91579777f50d00ee17c4bf73f089fee Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:15:12 -0500 Subject: [PATCH 10/13] Treat an unreadable cached voice info as no cache The stale fallback parsed the cache file without any guard, so a truncated or hand-edited file raised an unhandled error instead of the usual 502. It now reads through a helper that returns nothing for a missing, corrupt or wrongly shaped file, and the original upstream error is raised. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 25 +++++++++++++------ tests/test_voice_pkg_routes.py | 15 +++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index 2f03ea86..ac8cb583 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -283,6 +283,18 @@ async def _fetch_info( ) +def _read_cached_info(cache_file: Path) -> tuple[str, dict[str, Any]] | None: + """The cached info as (host, info), or None when it is missing or unreadable.""" + try: + cached = json.loads(cache_file.read_text(encoding="utf-8")) + host, info = cached["host"], cached["info"] + except (OSError, ValueError, KeyError, TypeError): + return None + if not isinstance(host, str) or not isinstance(info, dict): + return None + return host, info + + async def _voice_info_response( ctx: ServerContext, runtime_dir: Path, upstream_path: str ) -> tuple[str, Response]: @@ -297,14 +309,13 @@ async def _voice_info_response( lambda: _fetch_info(ctx, cache_file, upstream_path), ) except VoicePkgError: - if not cache_file.exists(): + cached = _read_cached_info(cache_file) + if cached is None: raise - cached = json.loads(cache_file.read_text(encoding="utf-8")) - body = _rewrite_info( - cached["info"], info_host=cached["host"], api_url=ctx.api_url() - ) - return f"https://{cached['host']}{upstream_path}", JSONResponse( - body, headers={"X-RR-Voice-Cache": "stale"} + host, info = cached + return f"https://{host}{upstream_path}", JSONResponse( + _rewrite_info(info, info_host=host, api_url=ctx.api_url()), + headers={"X-RR-Voice-Cache": "stale"}, ) body = _rewrite_info(info, info_host=host, api_url=ctx.api_url()) return f"https://{host}{upstream_path}", JSONResponse( diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index d6bde248..4bf088c8 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -457,3 +457,18 @@ def api_url(self) -> str: pass else: raise AssertionError("an eu request must not be answered from the us cache") + + +def test_a_corrupt_cached_info_is_a_502_not_an_error( + tmp_path: Path, monkeypatch +) -> None: + fds = "https://awsusor0.fds.api.xiaomi.com/app/beryllite/voice-pkg/info" + _fake_fetch(monkeypatch, {fds: json.dumps(INFO).encode()}) + client = _client(tmp_path) + assert client.get("/app/beryllite/voice-pkg/info").status_code == 200 + _fake_fetch(monkeypatch, {}) + cache_files = list(tmp_path.rglob("info-*.json")) + assert len(cache_files) == 1 + for content in (b"{not json", b"[]", b'{"host": "x"}', b'{"host": 1, "info": {}}'): + cache_files[0].write_bytes(content) + assert client.get("/app/beryllite/voice-pkg/info").status_code == 502 From 3d18c5fc7d77f62b009166ac9790561c2a63c1ef Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:17:04 -0500 Subject: [PATCH 11/13] Keep voice package and info file IO off the event loop Packages up to 64 MB were read, written and evicted with blocking calls inside the request handler. The writes, the eviction scan and the info cache read and write now run through asyncio.to_thread, and a cache hit is served with FileResponse so the file is streamed rather than loaded into memory. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 39 ++++++++++++------- tests/test_voice_pkg_routes.py | 20 ++++++---- 2 files changed, 37 insertions(+), 22 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index ac8cb583..abbda095 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -17,7 +17,7 @@ from urllib.parse import urlparse import aiohttp -from fastapi.responses import JSONResponse, Response +from fastapi.responses import FileResponse, JSONResponse, Response from shared.context import ServerContext VOICE_INFO_ROUTE_NAME = "voice_pkg_info" @@ -208,6 +208,20 @@ def _write_atomic(path: Path, data: bytes) -> None: temp.replace(path) +def _touch(path: Path) -> bool: + """Marks a cached file as just used; False when it is missing or was evicted.""" + try: + os.utime(path) + except OSError: + return False + return True + + +def _write_and_evict(path: Path, data: bytes) -> None: + _write_atomic(path, data) + _evict_old_packages(path.parent) + + def _evict_old_packages(cache_dir: Path) -> None: """Keeps the newest packages within the file and byte caps and drops stale temp files.""" now = time.time() @@ -274,8 +288,10 @@ async def _fetch_info( except Exception as exc: # noqa: BLE001 errors.append(f"{host}: {exc}") continue - _write_atomic( - cache_file, json.dumps({"host": host, "info": info}).encode("utf-8") + await asyncio.to_thread( + _write_atomic, + cache_file, + json.dumps({"host": host, "info": info}).encode("utf-8"), ) return host, info raise VoicePkgError( @@ -309,7 +325,7 @@ async def _voice_info_response( lambda: _fetch_info(ctx, cache_file, upstream_path), ) except VoicePkgError: - cached = _read_cached_info(cache_file) + cached = await asyncio.to_thread(_read_cached_info, cache_file) if cached is None: raise host, info = cached @@ -329,15 +345,9 @@ async def _voice_file_response( source_url = f"https://{host}{path}" cache_file = _cache_dir(runtime_dir) / f"{_digest(source_url)}.pkg" headers = {"Cache-Control": "public, max-age=86400"} - try: - cached = cache_file.read_bytes() - except OSError: - cached = None # missing or evicted while we looked: treat as a miss - if cached is not None: - with contextlib.suppress(OSError): - os.utime(cache_file) - return source_url, Response( - cached, + if await asyncio.to_thread(_touch, cache_file): + return source_url, FileResponse( + cache_file, media_type="application/octet-stream", headers={**headers, "X-RR-Voice-Cache": "hit"}, ) @@ -346,8 +356,7 @@ async def download() -> bytes: data = await fetch_voice_bytes( source_url, max_bytes=VOICE_PKG_MAX_BYTES, timeout_s=120 ) - _write_atomic(cache_file, data) - _evict_old_packages(cache_file.parent) + await asyncio.to_thread(_write_and_evict, cache_file, data) return data try: diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index 4bf088c8..36685180 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -389,10 +389,11 @@ def test_v2_to_v5_model_strings_use_the_debug_path() -> None: assert voice_info_path_for_model("roborock.vacuum.zzzv2") == "" -def test_cache_hit_that_vanishes_before_the_read_is_a_miss( +def test_cache_hit_that_vanishes_before_it_is_served_is_a_miss( tmp_path: Path, monkeypatch ) -> None: import asyncio + import os from https_server.routes.plugin import voice_pkg @@ -400,14 +401,19 @@ def test_cache_hit_that_vanishes_before_the_read_is_a_miss( _fake_fetch(monkeypatch, {source: b"fresh"}) cache_dir = tmp_path / "voice_pkg_cache" cache_dir.mkdir() - real = Path.read_bytes + path = cache_dir / ( + voice_pkg._digest("https://us-app.roborock.com/a/voice-pkg/package/en.pkg") + + ".pkg" + ) + path.write_bytes(b"old") + real = os.utime - def vanishing(self: Path) -> bytes: - if self.suffix == ".pkg": - raise FileNotFoundError(str(self)) - return real(self) + def vanishing(target, *args, **kwargs): + if str(target).endswith(".pkg"): + raise FileNotFoundError(str(target)) + return real(target, *args, **kwargs) - monkeypatch.setattr(Path, "read_bytes", vanishing) + monkeypatch.setattr(voice_pkg.os, "utime", vanishing) _, response = asyncio.run( voice_pkg._voice_file_response( tmp_path, "us-app.roborock.com", "/a/voice-pkg/package/en.pkg" From 1bbf691cc3127f8bb69b434923ec3ef936696307 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:48:08 -0500 Subject: [PATCH 12/13] Serve cached voice packages from memory so an eviction cannot 500 The hit path touched the file and then returned a FileResponse, which stats and opens the file only when the response is sent. A file evicted in that gap raised instead of falling back to a download. The touch and read now happen together in one thread call and a vanished file is a cache miss. Packages are capped at 64 MB and the miss path already holds them in memory. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 17 +++++----- tests/test_voice_pkg_routes.py | 31 +++++++++++++++++++ 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index abbda095..303dfdef 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -17,7 +17,7 @@ from urllib.parse import urlparse import aiohttp -from fastapi.responses import FileResponse, JSONResponse, Response +from fastapi.responses import JSONResponse, Response from shared.context import ServerContext VOICE_INFO_ROUTE_NAME = "voice_pkg_info" @@ -208,13 +208,13 @@ def _write_atomic(path: Path, data: bytes) -> None: temp.replace(path) -def _touch(path: Path) -> bool: - """Marks a cached file as just used; False when it is missing or was evicted.""" +def _read_cached_package(path: Path) -> bytes | None: + """Marks a cached file as just used and returns it; None when missing or evicted.""" try: os.utime(path) + return path.read_bytes() except OSError: - return False - return True + return None def _write_and_evict(path: Path, data: bytes) -> None: @@ -345,9 +345,10 @@ async def _voice_file_response( source_url = f"https://{host}{path}" cache_file = _cache_dir(runtime_dir) / f"{_digest(source_url)}.pkg" headers = {"Cache-Control": "public, max-age=86400"} - if await asyncio.to_thread(_touch, cache_file): - return source_url, FileResponse( - cache_file, + cached = await asyncio.to_thread(_read_cached_package, cache_file) + if cached is not None: + return source_url, Response( + cached, media_type="application/octet-stream", headers={**headers, "X-RR-Voice-Cache": "hit"}, ) diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index 36685180..ec011668 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -423,6 +423,37 @@ def vanishing(target, *args, **kwargs): assert response.headers["X-RR-Voice-Cache"] == "miss" +def test_cache_hit_removed_after_the_touch_still_answers( + tmp_path: Path, monkeypatch +) -> None: + import asyncio + import os + + from https_server.routes.plugin import voice_pkg + + source = "https://us-app.roborock.com/a/voice-pkg/package/en.pkg" + _fake_fetch(monkeypatch, {source: b"fresh"}) + cache_dir = tmp_path / "voice_pkg_cache" + cache_dir.mkdir() + path = cache_dir / (voice_pkg._digest(source) + ".pkg") + path.write_bytes(b"old") + real = os.utime + + def touch_then_evict(target, *args, **kwargs): + real(target, *args, **kwargs) + if str(target).endswith(".pkg"): + os.remove(target) + + monkeypatch.setattr(voice_pkg.os, "utime", touch_then_evict) + _, response = asyncio.run( + voice_pkg._voice_file_response( + tmp_path, "us-app.roborock.com", "/a/voice-pkg/package/en.pkg" + ) + ) + assert response.body == b"fresh" + assert response.headers["X-RR-Voice-Cache"] == "miss" + + def test_package_cache_is_bounded_by_total_bytes(tmp_path: Path, monkeypatch) -> None: import os From 35f79faa5435d06342909c495036d7de735c76e3 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:48:20 -0500 Subject: [PATCH 13/13] Create the voice package cache directory when writing, not per request _cache_dir ran mkdir on the event loop for every request. Only the atomic writer needs the directory, and it already runs in a worker thread, so the mkdir moves there and lookups just build the path. Co-Authored-By: Claude Sonnet 5.5 --- .../https_server/routes/plugin/voice_pkg.py | 5 ++-- tests/test_voice_pkg_routes.py | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py index 303dfdef..29b1d4d3 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/plugin/voice_pkg.py @@ -173,9 +173,7 @@ async def fetch_voice_bytes(url: str, *, max_bytes: int, timeout_s: float) -> by def _cache_dir(runtime_dir: Path) -> Path: - path = runtime_dir / "voice_pkg_cache" - path.mkdir(parents=True, exist_ok=True) - return path + return runtime_dir / "voice_pkg_cache" def _digest(value: str) -> str: @@ -203,6 +201,7 @@ async def _single_flight(key: str, factory: Callable[[], Awaitable[_T]]) -> _T: def _write_atomic(path: Path, data: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp") temp.write_bytes(data) temp.replace(path) diff --git a/tests/test_voice_pkg_routes.py b/tests/test_voice_pkg_routes.py index ec011668..993db1fe 100644 --- a/tests/test_voice_pkg_routes.py +++ b/tests/test_voice_pkg_routes.py @@ -454,6 +454,31 @@ def touch_then_evict(target, *args, **kwargs): assert response.headers["X-RR-Voice-Cache"] == "miss" +def test_cache_dir_is_created_on_write_not_on_lookup( + tmp_path: Path, monkeypatch +) -> None: + import asyncio + + from https_server.routes.plugin import voice_pkg + + source = "https://us-app.roborock.com/a/voice-pkg/package/en.pkg" + _fake_fetch(monkeypatch, {source: b"fresh"}) + cache_dir = tmp_path / "voice_pkg_cache" + + assert voice_pkg._cache_dir(tmp_path) == cache_dir + assert not cache_dir.exists() + + _, response = asyncio.run( + voice_pkg._voice_file_response( + tmp_path, "us-app.roborock.com", "/a/voice-pkg/package/en.pkg" + ) + ) + assert response.headers["X-RR-Voice-Cache"] == "miss" + assert [p.name for p in cache_dir.glob("*.pkg")] == [ + voice_pkg._digest(source) + ".pkg" + ] + + def test_package_cache_is_bounded_by_total_bytes(tmp_path: Path, monkeypatch) -> None: import os