Files
ytstream/ytstream/runner.py
T
Tom FluxandClaude Opus 5 155f05773d Build ytstream: catalogue, retention, subscription mirror, proxy
Phases 1-4 of plan.md §13. Forked from youtube-automate as planned rather than
written from scratch: naming, NFO, auth, the admin UI, settings and the DB layer
came across largely unchanged, download.py is gone, and the pieces that only make
sense for a streaming library are new.

  api.py       YouTube Data API v3 client. The whole metadata path.
  strm.py      Materialising: a .strm, an .nfo and a thumbnail. Replaces the
               330-line download.py, because the job is writing a URL to a file.
  subsync.py   The subscription mirror, most of which is refusals.
  reap.py      Retention, rewritten around the 30-day window and min_keep_videos.
  discovery.py RSS polling plus an API-backed, resumable, bounded backfill.
  proxy/       The verified PoC, moved in with a systemd unit.

330 tests, all passing, no network and no yt-dlp in any of them. The suite leans
towards the failure paths, because that is where this design can actually hurt
someone: a 403 that looks like an unsubscribe, a video that ages out and comes
back, a title that never arrives. tests/test_proxy.py replaces the two standalone
scripts under proxy/ and now drives the real make_handler(mgr, ...) rather than the
PoC's make_handler(path, done), so routing and video-id validation are covered too.

Ran it end to end against the live API and it found three real bugs.

The first was mine and the tests caught it: strm.remove pruned empty directories
up to the media root, so a channel directory whose tvshow.nfo happened to be
missing would be deleted along with the season. It only looked safe because
tvshow.nfo normally stops the walk. The prune boundary is now the channel
directory explicitly.

The other two only showed up against real data, and they compounded. The backfill
inserted rows with no title and left the RSS poll to fill them in — but RSS returns
15 entries, which for Pitch Side spans 23 days against a 30-day window, so five of
twenty episodes were named after their video ids. Worse, strm.materialise wrote
that fallback back to the database as the title, which made the row look titled and
permanently disabled the repair path. Both fixed: playlistItems.list now requests
snippet as well as contentDetails, which costs the same single quota unit and
carries the title alongside the exact publish date, and the fallback is used for the
filename without being persisted. A title that does arrive late now also removes the
badly-named files and re-queues, so the episode is rewritten rather than keeping its
video-id name forever. Verified against the live API: all twenty Pitch Side episodes
now carry real titles.

Measured on the real account: 119 subscriptions queued for approval and none added
on the first sync, then a two-channel run backfilled and materialised 26 episodes in
under seven seconds.

Two deliberate departures from plan.md, both recorded there:

min_keep_videos defaults to 5 rather than being left as an open question. Without
it 52 of 117 measured channels are empty Jellyfin series that flicker in and out as
their single video crosses the retention line, and the plan already recommended it.

The Jellyfin refresh is a bare /Library/Refresh with a comment explaining why it
must stay that way. A normal scan makes zero media probes; FullRefresh does probe,
and at 400 episodes that is 400 cold starts.

Not yet done: no systemd units are installed (needs root — deploy/deploy.sh), the
admin UI has no routes for sources or the approval queue yet, and nothing has been
pointed at the real media root.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-12 16:35:23 +01:00

150 lines
5.2 KiB
Python

"""`run` orchestration: sync, then poll, then materialise, then reap — under a lock.
Order matters. The subscription sync runs *first* so that a channel added on
YouTube at 14:00 has its catalogue built in the same pass rather than an hour
later. Retention runs *last* so a video discovered and materialised in this run is
judged against the window once, not twice.
"""
from __future__ import annotations
import contextlib
import fcntl
import logging
import sqlite3
from pathlib import Path
from . import config, discovery, jellyfin, reap, strm, subsync, util, videos
from .settings import Settings
log = logging.getLogger(__name__)
class AlreadyRunning(Exception):
pass
@contextlib.contextmanager
def exclusive_lock(path: Path | None = None):
"""Non-blocking flock. Raises AlreadyRunning if another run holds it.
The cron schedule is hourly and a first-run import of 119 channels can outlast
that, so overlapping runs are expected and must be a silent no-op rather than
two workers fighting over the same queue.
"""
path = path or config.LOCK_PATH
path.parent.mkdir(parents=True, exist_ok=True)
handle = path.open("w")
try:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as exc:
raise AlreadyRunning(f"another run holds {path}") from exc
yield
finally:
with contextlib.suppress(OSError):
fcntl.flock(handle, fcntl.LOCK_UN)
handle.close()
def materialise_all(
conn: sqlite3.Connection, settings: Settings, limit: int | None = None
) -> dict:
"""Write a `.strm` + `.nfo` + thumbnail for everything in `listed`.
There is no retry ladder and no failure state. Writing a 50-byte text file
either works or the filesystem is broken, and in the latter case the run
should stop rather than mark 400 videos as failed.
"""
stats = {"materialised": 0, "shows": 0, "errors": 0}
seen_channels: set[int] = set()
for video in videos.claim_listed(conn, limit):
channel = conn.execute(
"SELECT * FROM channel WHERE id = ?", (video["channel_pk"],)
).fetchone()
if channel is None: # channel deleted mid-run
continue
if channel["id"] not in seen_channels:
# Lazily, so a channel with nothing inside the window never creates an
# empty series in Jellyfin (plan.md §5).
strm.write_show(channel)
seen_channels.add(channel["id"])
stats["shows"] += 1
try:
strm.materialise(conn, settings, channel, video)
stats["materialised"] += 1
except OSError as exc:
log.error("could not materialise %s: %s", video["video_id"], exc)
stats["errors"] += 1
return stats
def run(
conn: sqlite3.Connection, settings: Settings, channel_pk: int | None = None
) -> dict:
"""One full cycle. Assumes the caller holds the lock."""
result: dict = {}
# Sync first: a channel added on YouTube should get its catalogue this run.
# Skipped for a single-channel run, which is a targeted operation.
if channel_pk is None:
result["sync"] = subsync.sync_all(conn, settings)
result["poll"] = discovery.poll_all(conn, settings, channel_pk)
result["materialise"] = materialise_all(conn, settings)
result["reap"] = reap.run(conn, settings)
if result["materialise"]["materialised"] or result["reap"]["aged_out"]:
jellyfin.from_settings(settings).refresh()
settings.set("last_run_at", util.utcnow_iso())
return result
def summarise(result: dict) -> str:
sync = result.get("sync", {})
poll = result.get("poll", {})
made = result.get("materialise", {})
reaped = result.get("reap", {})
parts = [
f"channels={poll.get('channels', 0)}",
f"discovered={poll.get('queued', 0)}",
f"materialised={made.get('materialised', 0)}",
f"aged_out={reaped.get('aged_out', 0)}",
f"shorts={poll.get('shorts', 0)}",
f"live={poll.get('live', 0)}",
f"poll_failures={poll.get('failed', 0)}",
]
if sync:
parts[1:1] = [
f"subs_added={sync.get('added', 0)}",
f"subs_queued={sync.get('queued', 0)}",
f"subs_removed={sync.get('removed', 0)}",
]
if sync.get("refused"):
parts.append(f"SYNC_REFUSED={sync['refused']}")
if made.get("errors"):
parts.append(f"errors={made['errors']}")
return " ".join(parts)
def exit_code(result: dict) -> int:
"""Non-zero when something needs a human.
The cron entry runs under `runitor`, so this is what turns the healthchecks
check red. A silently-broken subscription mirror is the worst outcome
available — nothing looks wrong until someone asks why a channel never
appeared — so a refused sync must be loud.
"""
sync = result.get("sync", {})
if sync.get("refused"):
return 1
if result.get("materialise", {}).get("errors"):
return 1
if result.get("poll", {}).get("failed"):
# Two of 119 measured channels fail permanently (terminated or private),
# so a poll failure is a warning, not a red check.
log.warning("%d channel(s) failed to poll", result["poll"]["failed"])
return 0