Files
privatestudio/privatestudio/studio/tests/test_worker.py
T
Shaun KrugerandClaude Opus 5.5 73b549cb18
Build and publish / cleanup (pull_request) Successful in 17s
Build and publish / test (pull_request) Skipped
Build and publish / build (pull_request) Skipped
Build and publish / pypi (pull_request) Skipped
Add transcode/packaging worker, job slugs, deletes and zip downloads
Worker:
- manage.py run_worker polls the database for pending transcode jobs (ffmpeg)
  and packaging jobs (Bento4 mp4fragment + mp4hls). Jobs are claimed with a
  conditional UPDATE, a heartbeat thread marks progress, stale jobs are failed,
  and SIGTERM returns an interrupted job to the queue.
- SQLite runs in WAL mode with IMMEDIATE transactions and a busy timeout so the
  web server and worker can share the database.
- transcode.py exposes a reusable transcode() and the HW->CPU fallback works.
- Docker image includes ffmpeg and a checksum-verified Bento4 SDK.

Jobs and storage:
- TranscodeJob and PackagingJob have slugs, set explicitly on creation; outputs
  go to transcodes/<slug>/ and packages/<slug>/hls/. Migrations regenerated.
- Uploads into transcodes/ and packages/ are refused; the uploader defaults to
  the videos/raw folder.

UI:
- New packaging job button on transcode jobs.
- Delete views for packaging jobs, transcode jobs, uploaded files and content
  entries, each removing files before records and refusing while referenced.
  TranscodeJob.asset is now SET_NULL so deleting a source keeps its jobs.
- Streamed zip downloads for completed transcode jobs and packages, rooted at
  the job slug; the content page lists packages with download buttons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 16:34:44 -07:00

287 lines
12 KiB
Python

import shutil
import subprocess
from datetime import timedelta
from io import StringIO
from pathlib import Path
from unittest import mock
from django.core.management import call_command
from django.utils import timezone
from privatestudio import transcode as transcoder
from privatestudio.studio import worker as worker_module
from privatestudio.studio.models import (
ContentAsset, JobStatus, PackagingJob, TranscodedAsset, TranscodeJob, UploadedAsset,
)
from privatestudio.studio.storage import get_storage
from privatestudio.studio.tests.base import StudioTestCase
from privatestudio.studio.worker import (
JobLog, Worker, claim_packaging_job, claim_transcode_job, fail_orphaned_packaging_jobs, recover_stale_jobs,
)
PROFILE_YAML = "profiles:\n hd:\n resolution: 1280x720\n bitrate: 2500k\n"
OUTPUTS = ["output_720p.mp4", "output_audio.mp4"]
def fake_transcode(input_asset, profile_config, output_dir, encoder=None, on_line=None, on_start=None, log=None,
return_code=0):
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
for name in OUTPUTS:
(output_dir / name).write_bytes(b"video:" + name.encode())
on_line("ffmpeg version x\n")
on_line("frame=1 size=1\n")
on_line("frame=2 size=2\n")
return transcoder.TranscodeResult(return_code, list(OUTPUTS), ["ffmpeg"], "", "cpu")
def fake_bento4(self, command, log):
tool = Path(str(command[0])).name
log(f"$ {tool}\n")
if tool == "mp4fragment":
Path(command[2]).write_bytes(Path(command[1]).read_bytes())
elif tool == "mp4hls":
out = Path(command[2])
(out / "media-1").mkdir(parents=True)
(out / "master.m3u8").write_text("#EXTM3U\n")
(out / "media-1" / "stream.m3u8").write_text("#EXTM3U\n")
(out / "media-1" / "segment-0.ts").write_bytes(b"ts")
@mock.patch.object(worker_module, "HEARTBEAT_SECONDS", 3600)
class WorkerTestCase(StudioTestCase):
def setUp(self):
super().setUp()
self.storage = get_storage()
self.storage.put_stream("demo", "uploads/source.mov", [b"source"])
self.asset = UploadedAsset.objects.create(
studio=self.studio, filename="source.mov", size=6, s3_path="uploads/source.mov",
)
self.content = ContentAsset.objects.create(studio=self.studio, title="Movie", uploaded_asset=self.asset)
def make_job(self, status=JobStatus.PENDING, content=True, **kwargs):
return TranscodeJob.objects.create(
slug=TranscodeJob.get_random_slug(),
studio=self.studio, asset=self.asset, content_asset=self.content if content else None,
profile_definition=PROFILE_YAML, status=status, **kwargs,
)
def make_packaging(self, job):
return PackagingJob.objects.create(slug=PackagingJob.get_random_slug(), studio=self.studio, transcode_job=job)
class ClaimTests(WorkerTestCase):
def test_claims_oldest_pending_once(self):
self.make_job(status=JobStatus.DRAFT)
first = self.make_job(requested_at=timezone.now() - timedelta(minutes=5))
second = self.make_job()
claimed = claim_transcode_job()
self.assertEqual(claimed.pk, first.pk)
self.assertEqual(claimed.status, JobStatus.IN_PROGRESS)
self.assertIsNotNone(claimed.started_at)
self.assertTrue(claimed.worker)
self.assertEqual(claim_transcode_job().pk, second.pk)
self.assertIsNone(claim_transcode_job())
def test_packaging_waits_for_transcode(self):
job = self.make_job()
packaging = self.make_packaging(job)
self.assertIsNone(claim_packaging_job())
TranscodeJob.objects.filter(pk=job.pk).update(status=JobStatus.COMPLETED)
self.assertEqual(claim_packaging_job().pk, packaging.pk)
def test_packaging_fails_with_transcode(self):
job = self.make_job(status=JobStatus.FAILED)
packaging = self.make_packaging(job)
self.assertEqual(fail_orphaned_packaging_jobs(), 1)
packaging.refresh_from_db()
self.assertEqual(packaging.status, JobStatus.FAILED)
self.assertIn("transcode job failed", packaging.output)
def test_recover_stale(self):
old = timezone.now() - timedelta(hours=1)
stale = self.make_job(status=JobStatus.IN_PROGRESS, heartbeat_at=old, transcode_output="log")
fresh = self.make_job(status=JobStatus.IN_PROGRESS, heartbeat_at=timezone.now())
self.assertEqual(recover_stale_jobs(), 1)
stale.refresh_from_db()
fresh.refresh_from_db()
self.assertEqual(stale.status, JobStatus.FAILED)
self.assertTrue(stale.transcode_output.startswith("log"))
self.assertIn("stopped responding", stale.transcode_output)
self.assertEqual(fresh.status, JobStatus.IN_PROGRESS)
class JobLogTests(StudioTestCase):
def test_keeps_last_progress_line(self):
log = JobLog()
for line in ["start\n", "frame=1\n", "frame=2\n", "end\n", "frame=3\n"]:
log(line)
self.assertEqual(log.text(), "start\nframe=2\nend\nframe=3\n")
class TranscodeJobTests(WorkerTestCase):
def run_job(self, job, **fake_kwargs):
job = claim_transcode_job()
with mock.patch.object(worker_module.transcoder, "transcode",
side_effect=lambda *a, **k: fake_transcode(*a, **k, **fake_kwargs)) as m:
Worker().run_transcode_job(job)
job.refresh_from_db()
return job, m
def test_success(self):
job, m = self.run_job(self.make_job())
self.assertEqual(m.call_args.args[0], self.storage.object_path("demo", "uploads/source.mov"))
self.assertEqual(job.status, JobStatus.COMPLETED)
self.assertIsNotNone(job.completed_at)
self.assertIn("ffmpeg version", job.transcode_output)
self.assertNotIn("frame=1", job.transcode_output)
outputs = {a.filename: a for a in job.transcoded_assets.all()}
self.assertEqual(set(outputs), set(OUTPUTS))
self.assertEqual(outputs["output_audio.mp4"].format, "audio")
self.assertEqual(outputs["output_720p.mp4"].content_asset, self.content)
key = f"transcodes/{job.slug}/output_720p.mp4"
self.assertEqual(outputs["output_720p.mp4"].s3_path, key)
self.assertTrue(self.storage.object_exists("demo", key))
self.assertEqual(list(self.storage.work_path.iterdir()), [])
def test_without_content_asset(self):
job, _ = self.run_job(self.make_job(content=False))
self.assertEqual(job.status, JobStatus.COMPLETED)
self.assertIsNone(job.transcoded_assets.first().content_asset)
def test_ffmpeg_failure(self):
job, _ = self.run_job(self.make_job(), return_code=1)
self.assertEqual(job.status, JobStatus.FAILED)
self.assertIn("ffmpeg exited with code 1", job.transcode_output)
self.assertFalse(TranscodedAsset.objects.exists())
self.assertEqual(list(self.storage.work_path.iterdir()), [])
def test_missing_source(self):
self.storage.delete_object("demo", "uploads/source.mov")
job, m = self.run_job(self.make_job())
self.assertEqual(job.status, JobStatus.FAILED)
self.assertIn("Source file is missing", job.transcode_output)
m.assert_not_called()
def test_shutdown_requeues(self):
job = self.make_job()
claimed = claim_transcode_job()
w = Worker()
w.stop()
with mock.patch.object(worker_module.transcoder, "transcode",
side_effect=lambda *a, **k: fake_transcode(*a, **k, return_code=-15)):
w.run_transcode_job(claimed)
job.refresh_from_db()
self.assertEqual(job.status, JobStatus.PENDING)
self.assertEqual(job.worker, "")
def test_stale_result_discarded(self):
job = self.make_job()
claimed = claim_transcode_job()
TranscodeJob.objects.filter(pk=job.pk).update(status=JobStatus.FAILED)
with mock.patch.object(worker_module.transcoder, "transcode", side_effect=fake_transcode):
Worker().run_transcode_job(claimed)
job.refresh_from_db()
self.assertEqual(job.status, JobStatus.FAILED)
self.assertFalse(TranscodedAsset.objects.exists())
@mock.patch.object(Worker, "_run_tool", fake_bento4)
class PackagingJobTests(WorkerTestCase):
def completed_transcode(self):
job = self.make_job(status=JobStatus.COMPLETED)
for name in OUTPUTS:
key = f"transcodes/{job.slug}/{name}"
self.storage.put_stream("demo", key, [b"data"])
TranscodedAsset.objects.create(studio=self.studio, content_asset=self.content, transcode_job=job,
filename=name, s3_path=key, format="mp4")
return job
def test_success(self):
packaging = self.make_packaging(self.completed_transcode())
Worker().run_packaging_job(claim_packaging_job())
packaging.refresh_from_db()
self.assertEqual(packaging.status, JobStatus.COMPLETED, packaging.output)
prefix = f"packages/{packaging.slug}/hls"
self.assertEqual(packaging.manifest_path, f"{prefix}/master.m3u8")
self.assertTrue(self.storage.object_exists("demo", f"{prefix}/master.m3u8"))
self.assertTrue(self.storage.object_exists("demo", f"{prefix}/media-1/segment-0.ts"))
self.assertIn("mp4hls", packaging.output)
def test_missing_outputs(self):
packaging = self.make_packaging(self.make_job(status=JobStatus.COMPLETED))
Worker().run_packaging_job(claim_packaging_job())
packaging.refresh_from_db()
self.assertEqual(packaging.status, JobStatus.FAILED)
self.assertIn("no output files", packaging.output)
class RunToolTests(StudioTestCase):
def test_failure_and_missing_binary(self):
log = JobLog()
with self.assertRaisesMessage(worker_module.JobError, "exited with code 3"):
Worker()._run_tool(["sh", "-c", "echo hi; exit 3"], log)
self.assertIn("hi\n", log.text())
with self.assertRaisesMessage(worker_module.JobError, "Could not run"):
Worker()._run_tool(["/nonexistent/mp4hls"], log)
@mock.patch.object(Worker, "_run_tool", fake_bento4)
class RunWorkerCommandTests(WorkerTestCase):
def test_once_runs_transcode_then_packaging(self):
job = self.make_job()
packaging = self.make_packaging(job)
out = StringIO()
with mock.patch.object(worker_module.transcoder, "transcode", side_effect=fake_transcode):
call_command("run_worker", "--once", stdout=out)
job.refresh_from_db()
packaging.refresh_from_db()
self.assertEqual(job.status, JobStatus.COMPLETED)
self.assertEqual(packaging.status, JobStatus.COMPLETED, packaging.output)
self.assertIn("Worker stopped.", out.getvalue())
class RealTranscodeTests(WorkerTestCase):
"""Runs ffmpeg for real when it is installed."""
def setUp(self):
if not (shutil.which("ffmpeg") and shutil.which("ffprobe")):
self.skipTest("ffmpeg is not installed")
super().setUp()
def test_transcode(self):
source = self.storage.object_path("demo", "uploads/source.mov")
subprocess.run(
["ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=duration=2:size=640x360:rate=24",
"-f", "lavfi", "-i", "sine=duration=2", "-shortest", "-f", "mp4", str(source)],
check=True,
)
job = self.make_job()
TranscodeJob.objects.filter(pk=job.pk).update(
profile_definition="profiles:\n sd:\n resolution: 320x180\n bitrate: 300k\n",
)
Worker().run_transcode_job(claim_transcode_job())
job.refresh_from_db()
self.assertEqual(job.status, JobStatus.COMPLETED, job.transcode_output)
self.assertEqual(job.transcoded_assets.count(), 2)
class MissingFfmpegTests(WorkerTestCase):
def test_reports_missing_ffmpeg(self):
job = self.make_job()
with mock.patch.object(transcoder.subprocess, "Popen", side_effect=FileNotFoundError("no ffmpeg")):
Worker().run_transcode_job(claim_transcode_job())
job.refresh_from_db()
self.assertEqual(job.status, JobStatus.FAILED)
self.assertIn("Could not run ffmpeg", job.transcode_output)
class DeletedSourceTests(WorkerTestCase):
def test_job_fails_when_source_deleted(self):
job = self.make_job()
self.asset.delete()
Worker().run_transcode_job(claim_transcode_job())
job.refresh_from_db()
self.assertEqual(job.status, JobStatus.FAILED)
self.assertIn("source file was deleted", job.transcode_output)