Warm the VPS cache after new Discord media requests import

This commit is contained in:
Ziad Arafat committed 2026-11-28 18:23:34 -07:00
1 parent 6efce31ee8
commit e5386d9b28
4 files changed
+189 -5

No files matched your search

+1 -1
View File
@@ -175,7 +175,7 @@ release/torrent names. ARR subsequently searches its configured indexers under
the chosen quality/custom-format profile. Existing movies show status without
being added or searched again. TV choices update shared season retention as
described below. A successful
request means ARR accepted it, not that a matching release was found or imported.
request means ARR accepted it, not that a matching release was found or imported. After a new request imports and Jellyfin indexes its files, Dogebot automatically queues the movie or requested season into the VPS cache. The completion message reports the cache result. Existing cache size and file limits still apply.
The existing RDTC download/import/NFO/Jellyfin integration handles subsequent work.
Owner configuration uses Red's shared API-token stores `radarr` and `sonarr`:
+45
View File
@@ -574,3 +574,48 @@ async def test_slow_music_import_does_not_delay_another_commands_completion(
finally:
release.set()
await task
async def test_new_movie_waits_for_index_and_tracks_cache_after_restart(
config: Config,
) -> None:
"""Import and cache readiness are separate states."""
from unittest.mock import AsyncMock
from media_preload_client.models import RequestStatus
from watch.jobs import Jobs
queued = SimpleNamespace(id=71, status=RequestStatus.QUEUED)
done = SimpleNamespace(id=71, status=RequestStatus.DONE)
cog = SimpleNamespace(
config=config,
_existing_title=AsyncMock(return_value={"hasFile": True}),
queue_import_warmup=AsyncMock(side_effect=[None, queued]),
fetch=AsyncMock(return_value=done),
)
jobs = Jobs(cast("Any", cog))
persisted = AsyncMock()
jobs.save = persisted
job = {
"kind": "movie",
"foreign_id": 101,
"title": "Dune",
"created": 100,
"stage": "waiting",
"auto_warm": True,
}
await jobs._media("owner:movie:101", job)
assert job["stage"] == "warming"
assert "preload_request_id" not in job
persisted.assert_awaited_once()
await jobs._media("owner:movie:101", job)
assert job["preload_request_id"] == 71
assert (
cog.queue_import_warmup.await_args_list[0].args[1]
== cog.queue_import_warmup.await_args_list[1].args[1]
)
await jobs._media("owner:movie:101", job)
assert job["stage"] == "complete"
assert "VPS cache is ready" in Jobs.message(job)
cog.fetch.assert_awaited_once_with(71)
+57 -4
View File
@@ -8,6 +8,7 @@ import os
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from functools import partial
from hashlib import sha256
from typing import TYPE_CHECKING, Any, cast
import discord
@@ -165,7 +166,7 @@ class Jobs:
if job["kind"] == "playlist":
await self._music(key, job)
else:
await self._media(job)
await self._media(key, job)
except PermissionError:
job["stage"] = "cancelled"
except PreloadError as exc:
@@ -350,7 +351,7 @@ class Jobs:
await self.save(key, job)
return str(match.get("title", "album"))
async def _media(self, job: dict[str, Any]) -> None:
async def _media(self, key: str, job: dict[str, Any]) -> None:
"""Check imported files rather than an empty queue."""
kind = job["kind"]
if kind == "preload":
@@ -359,6 +360,9 @@ class Jobs:
job["stage"] = "complete"
job["result"] = request.status.value
return
if job["stage"] == "warming":
await self._warm_import(key, job)
return
field = "tmdbId" if kind == "movie" else "tvdbId"
title = await self.cog._existing_title(
kind, {field: job["foreign_id"]}
@@ -367,7 +371,7 @@ class Jobs:
return
if kind == "movie":
if title.get("hasFile"):
job["stage"] = "complete"
await self._import_ready(key, job)
return
episodes = await self.cog._arr_call(
"tv", "episode", params={"seriesId": str(title["id"])}
@@ -379,7 +383,46 @@ class Jobs:
and self._aired(e)
]
if selected and all(e.get("hasFile") for e in selected):
if job.get("auto_warm"):
job["imported_episodes"] = sorted(
e["episodeNumber"] for e in selected
)
await self._import_ready(key, job)
async def _import_ready(self, key: str, job: dict[str, Any]) -> None:
if not job.get("auto_warm"):
job["stage"] = "complete"
return
job["stage"] = "warming"
job["imported_at"] = datetime.now(UTC).timestamp()
await self.save(key, job)
await self._warm_import(key, job)
async def _warm_import(self, key: str, job: dict[str, Any]) -> None:
request_id = job.get("preload_request_id")
if request_id is not None:
request = await self.cog.fetch(request_id)
if is_finished(request):
job.update(
stage="complete",
cache_result=request.status.value,
)
return
if datetime.now(UTC).timestamp() - job["imported_at"] > 1800:
job.update(stage="complete", cache_result="unavailable")
return
note = (
"auto-warm:"
+ sha256(f"{key}:{job['created']}".encode()).hexdigest()
)
request = await self.cog.queue_import_warmup(job, note)
if request is not None:
job["preload_request_id"] = request.id
if is_finished(request):
job.update(
stage="complete",
cache_result=request.status.value,
)
@staticmethod
def _aired(episode: dict[str, Any]) -> bool:
@@ -455,7 +498,17 @@ class Jobs:
if job["kind"] == "tv"
else ""
)
return f"**{title}**{season} is downloaded and imported."
reply = f"**{title}**{season} is downloaded and imported."
result = job.get("cache_result")
if result == "done":
return reply + " The VPS cache is ready."
if result:
return (
reply
+ f" Cache warm-up: **{result}**."
+ " Use `d!watch` to retry."
)
return reply
async def finish_preload(
self,
+86
View File
@@ -573,6 +573,91 @@ class Watch(commands.Cog):
)
)
async def queue_import_warmup(
self, job: dict[str, Any], note: str
) -> PreloadRequest | None:
"""Queue the imported title identified by its provider ID."""
client = await self._client()
async with client as c:
recent = _unwrap(
await list_requests.asyncio_detailed(
client=c, limit=100
)
)
existing = next(
(entry for entry in recent if entry.note == note), None
)
if existing is not None:
return existing
async def tokens() -> dict[str, str]:
return await self.bot.get_shared_api_tokens("jellyfin")
jf = Jellyfin(tokens)
movie = job["kind"] == "movie"
provider = "Tmdb" if movie else "Tvdb"
catalogue = await jf.call(
"Items",
params={
"IncludeItemTypes": "Movie"
if movie
else "Series",
"Recursive": "true",
"SearchTerm": job["title"],
"Fields": "Path,ProviderIds",
"Limit": "100",
},
)
items = [
item
for item in catalogue.get("Items", [])
if item.get("Path")
and str(item.get("ProviderIds", {}).get(provider))
== str(job["foreign_id"])
]
if len(items) != 1:
return None
item_id = items[0]["Id"]
body = CreateRequest(
item_id=item_id,
requested_by="discord:" + job["username"],
note=note,
)
if not movie:
season = job["season"]
expected = set(job["imported_episodes"])
index = await jf.call(
f"Shows/{item_id}/Episodes",
params={
"Season": str(season),
"Fields": "Path",
},
)
indexed = {
n
for item in index.get("Items", [])
if item.get("Path")
and isinstance(
start := item.get("IndexNumber"), int
)
for n in range(
start,
(item.get("IndexNumberEnd") or start)
+ 1,
)
}
if not expected.issubset(indexed):
return None
body.season = season
body.episodes = sorted(expected)
client = await self._client()
async with client as c:
return _unwrap(
await create_request.asyncio_detailed(
client=c, body=body
)
)
async def fetch(self, request_id: int) -> PreloadRequest:
"""Return a request with per-file progress."""
client = await self._client()
@@ -1309,6 +1394,7 @@ class Watch(commands.Cog):
"foreign_id": foreign_id,
"title": title["title"],
}
data["auto_warm"] = True
if kind == "tv":
data["season"] = season
await self.background().register(