Tolerate slow catalogue lookups without retrying ARR mutations

This commit is contained in:
Ziad Arafat committed 2026-11-22 13:38:34 -07:00
1 parent 64c37b39ec
commit c8a8e9d947
3 files changed
+149 -14

No files matched your search

+5 -1
View File
@@ -185,7 +185,11 @@ The deployed instance uses English Sonarr on Dragapult8969 and Radarr7878.
Profiles are resolved by name: `Doge - 1080p default` / `Doge - 4K optional`.
New roots are `/arr/library/TV` and `/arr/library/Movies`. A missing selected
profile/root stops the request instead of silently selecting another one.
Raw ARR errors/headers are not sent to Discord. No new service or API endpoint
Raw ARR errors/headers are not sent to Discord. Catalogue lookups have a
60-second read budget and retry one read timeout after a short pause. Writes,
download requests, and deletions are never automatically retried. A timed-out
write tells the user to check its status before retrying; catalogue timeouts
are distinguished from an unreachable ARR service. No new service/API endpoint
is required.
### Shared TV season retention
+90 -1
View File
@@ -9,7 +9,7 @@ from aiohttp.test_utils import TestServer
from redbot.core import Config
from watch_helpers import FakeAuthor, FakeContext
from watch.watch import Watch
from watch.watch import PreloadError, Watch
class RequestBot:
@@ -690,3 +690,92 @@ async def test_ambiguous_watch_selects_correct_media_type(
assert "50%" in ctx.texts[-1]
assert "75%" not in ctx.texts[-1]
assert all(method == "GET" for method, *_ in calls)
@pytest.mark.parametrize("failure", ["first", "always", "slow"])
async def test_catalogue_tolerates_transient_or_slow_reads(
acquisition: tuple[Watch, list[Any], dict[str, Any]],
monkeypatch: pytest.MonkeyPatch,
failure: str,
) -> None:
"""Tolerate slow catalogue reads without calling ARR offline."""
import httpx
cog, _, _ = acquisition
requests: list[httpx.Request] = []
client = httpx.AsyncClient
def respond(request: httpx.Request) -> httpx.Response:
requests.append(request)
slow = (
failure == "slow"
and request.extensions["timeout"]["read"] < 60
)
if (
failure == "always"
or (failure == "first" and len(requests) == 1)
or slow
):
msg = "private-upstream-detail"
raise httpx.ReadTimeout(msg, request=request)
return httpx.Response(
200,
json=[
{
"title": (
"You Don't Mess with the Zohan"
),
"year": 2008,
"tmdbId": 10661,
}
],
)
monkeypatch.setattr(
httpx,
"AsyncClient",
lambda **kwargs: client(
transport=httpx.MockTransport(respond), **kwargs
),
)
if failure == "always":
with pytest.raises(
Exception, match="catalogue.*timed out"
) as error:
await cog.acquisition_search("movie", "Zohan")
assert "private-upstream-detail" not in str(error.value)
assert len(requests) == 2
else:
result = await cog.acquisition_search("movie", "Zohan")
assert result[0]["title"] == "You Don't Mess with the Zohan"
assert len(requests) == (2 if failure == "first" else 1)
assert all(r.method == "GET" for r in requests)
async def test_mutation_timeout_is_never_retried(
acquisition: tuple[Watch, list[Any], dict[str, Any]],
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Never repeat an uncertain download request."""
import httpx
cog, _, _ = acquisition
requests: list[httpx.Request] = []
client = httpx.AsyncClient
def respond(request: httpx.Request) -> httpx.Response:
requests.append(request)
msg = "private-detail"
raise httpx.ReadTimeout(msg, request=request)
monkeypatch.setattr(
httpx,
"AsyncClient",
lambda **kwargs: client(
transport=httpx.MockTransport(respond), **kwargs
),
)
with pytest.raises(PreloadError, match="timed out.*status") as error:
await cog._arr_call("movie", "movie", body={"title": "Zohan"})
assert len(requests) == 1
assert "private-detail" not in str(error.value)
+54 -12
View File
@@ -651,22 +651,30 @@ class Watch(commands.Cog):
if not tokens.get("url") or not tokens.get("api_key"):
msg = f"{service} integration is not configured."
raise PreloadError(msg)
lookup = (
body is None
and method in {None, "GET"}
and path
in {
"movie/lookup",
"series/lookup",
}
)
timeout = httpx.Timeout(30.0, read=60.0 if lookup else 30.0)
async with httpx.AsyncClient(
base_url=tokens["url"].rstrip("/") + "/api/v3/",
headers={"X-Api-Key": tokens["api_key"]},
timeout=30.0,
timeout=timeout,
) as client:
try:
response = await client.request(
method
or ("GET" if body is None else "POST"),
path,
params=params,
json=body,
)
except httpx.HTTPError:
msg = f"{service} could not be reached."
raise PreloadError(msg) from None
response = await self._arr_response(
client,
service,
path,
method or ("GET" if body is None else "POST"),
body,
params,
lookup=lookup,
)
if response.status_code >= 400: # noqa: PLR2004
msg = f"{service} answered HTTP {response.status_code}."
raise PreloadError(msg)
@@ -678,6 +686,40 @@ class Watch(commands.Cog):
msg = f"{service} returned an invalid response."
raise PreloadError(msg) from None
async def _arr_response(
self,
client: httpx.AsyncClient,
service: str,
path: str,
method: str,
body: dict[str, Any] | None,
params: dict[str, str] | None,
*,
lookup: bool,
) -> httpx.Response:
"""Retry only a catalogue read, never an uncertain mutation."""
for attempt in range(2 if lookup else 1):
try:
return await client.request(
method, path, params=params, json=body
)
except httpx.ReadTimeout:
if lookup and attempt == 0:
await asyncio.sleep(1)
continue
if lookup:
msg = f"{service} catalogue lookup "
msg += "timed out. Try again shortly."
else:
msg = f"{service} request timed out. "
msg += "Check status before retrying."
raise PreloadError(msg) from None
except httpx.HTTPError:
msg = f"{service} could not be reached."
raise PreloadError(msg) from None
msg = f"{service} catalogue lookup did not finish."
raise PreloadError(msg)
async def acquisition_search(
self, kind: str, query: str
) -> list[dict[str, Any]]: